Casting to Python string from char [] returned by DLL

I am trying to cast a string pointer of a C style char [] style string (returned from a DLL) to a Python compatible string type. but when Python27 does:

import ctypes charPtr = ctypes.cast( "HiThere", ctypes.c_char_p ) print( "charPtr = ", charPtr ) 

we get: charPtr = c_char_p('HiThere')

perhaps something should not be judged correctly. My questions:

  • how should this charPtr be returned to a printable compatible Python string?
  • - is the casting operation just mentioned doing what it should do?
+6
source share
2 answers

ctypes.cast () is used to convert one ctype instance to another ctype data type. You do not need this to convert it to a python string. Just use ".value" to get it in the python string.

 >>> s = "Hello, World" >>> c_s = c_char_p(s) >>> print c_s c_char_p('Hello, World') >>> print c_s.value Hello, World 

More here

+9
source

If you set the argtypes or restype attributes to ctypes , they will return the right Python object without the need for a cast.

Here is an example of the C-runtime time and ctime :

 >>> from ctypes import * >>> m=CDLL('msvcrt') >>> t=c_long(0) >>> m.time(byref(t)) 1326700130 >>> m.ctime(byref(t)) # restype not set 6952984 >>> m.ctime.restype=c_char_p # set restype correctly >>> m.ctime(byref(t)) 'Sun Jan 15 23:48:50 2012\n' 
+5
source

Source: https://habr.com/ru/post/906067/


All Articles