从DLL返回的char[]转换为Python字符串
我试图将C风格的const char[]字符串指针(从DLL返回)转换为与Python兼容的字符串类型。但是当Python27执行时:从DLL返回的char[]转换为Python字符串,python,c,string,ctypes,Python,C,String,Ctypes,我试图将C风格的const char[]字符串指针(从DLL返回)转换为与Python兼容的字符串类型。但是当Python27执行时: import ctypes charPtr = ctypes.cast( "HiThere", ctypes.c_char_p ) print( "charPtr = ", charPtr ) 我们得到:charPtr=c\u char\u p('heree') 也许有些事情没有得到正确的评估。 我的问题是: 如何将这个charPtr转换回与Python兼容
import ctypes
charPtr = ctypes.cast( "HiThere", ctypes.c_char_p )
print( "charPtr = ", charPtr )
我们得到:charPtr=c\u char\u p('heree')
也许有些事情没有得到正确的评估。
我的问题是:
>>> s = "Hello, World"
>>> c_s = c_char_p(s)
>>> print c_s
c_char_p('Hello, World')
>>> print c_s.value
Hello, World
更多信息如果设置函数的或属性,它们将返回正确的Python对象,而不需要强制转换
下面是一个调用C-runtimetime
和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'
@海伦王:不,不是。在本例中,
ctime
返回指向静态内存的指针,因此无需管理。您知道一般情况吗c库返回了在堆上分配的内存。@HelinWang即使在一般情况下,如果c分配了它,c也必须释放它。在这种情况下,您也不想使用c\u char\p
,因为ctypes
是“有用的”并将其转换为Python字符串。您无法获取返回的指针,因此无法将其传递给ctypes包装的free
函数。使用另一种类型,例如POINTER(char)
或c\u void\u p
,提取字符串,然后将指针传递到free
或类似位置。