[英]casting into a Python string from a char[] returned by a DLL
我试图将C样式const char []字符串指针(从DLL返回)转换为Python兼容的字符串类型。 但是当Python27执行时:
import ctypes
charPtr = ctypes.cast( "HiThere", ctypes.c_char_p )
print( "charPtr = ", charPtr )
我们得到: charPtr = c_char_p('HiThere')
也许某些事情无法正确评估。 我的问题是:
ctypes.cast()用于将一个ctype实例转换为另一个ctype数据类型。 你不需要它将它转换为python字符串。 只需使用“.value”即可在python字符串中获取它。
>>> s = "Hello, World"
>>> c_s = c_char_p(s)
>>> print c_s
c_char_p('Hello, World')
>>> print c_s.value
Hello, World
更多信息在这里
如果设置ctypes
函数的argtypes
或restype
属性,它们将返回正确的Python对象而无需强制转换。
这是一个调用C运行time
和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'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.