【发布时间】:2011-07-02 06:00:48
【问题描述】:
我正在使用 ctypes,我已经定义了这个结构来传递参数
class my_struct(ctypes.Structure):
_fields_ = [ ("buffer", ctypes.c_char * BUFSIZE),
("size", ctypes.c_int )]
然后我使用以下代码调用 C 函数,但我不知道如何从我创建的结构中创建字符串。
class Client():
def __init__(self):
self.__proto = my_struct()
self.client = ctypes.cdll.LoadLibrary(r"I:\bin\client.dll")
def version(self):
ret = self.client.execute(ctypes.byref(self.__proto))
my_string = self.__proto.buffer[:self.__proto.size]
我想使用缓冲区的前 n 个字节创建一个 python 字符串(缓冲区包含 NULL 字符,但我必须处理这种情况并在必要时使用 /0x00 字符创建字符串)。委托
my_string = self.__proto.buffer[:self.__proto.size]
不工作,因为如果出现 0x00 会截断字符串。欢迎任何想法。提前致谢。
【问题讨论】:
-
在 Python 2.6.3 中,我已经测试过创建一个像缓冲区一样的 ctypes 数组,但我看不到它实际上被截断了。像这样: ar = (ctypes.c_char*10)(); ar.value = "测试";断言 ar[:6] == 'test\x00\x00'。我错过了什么吗?