Alex Rivera | Logout

casting into a Python string from a char[] returned by a DLL

Asked 2012-01-16T02:26:06.947
14

I am attempting to cast a C style const char[] string pointer (returned from a DLL) into a Python compatible string type. but when Python27 executes:

import ctypes

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

we get: charPtr = c_char_p('HiThere')

perhaps something is not to be evaluating properly. My questions are:

  1. how should one cast this charPtr back into a Python compatible, print-able string?
  2. is the cast operation just mentioned doing what it should be doing?
Edit
Report

1 Answer

10

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

Here's an example calling the C-runtime time and ctime functions:

>>> 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'
answered 2012-01-16T07:50:35.823

Your Answer