我正在使用 Python 和 ctypes,但我不知道如何解决这个问题。我调用了一个填充原始二进制数据的 C 函数。我的代码如下所示:
class Client():
def __init__(self):
self.__BUFSIZE = 1024*1024
self.__buf = ctypes.create_string_buffer(self.__BUFSIZE)
self.client = ctypes.cdll.LoadLibrary(r"I:\bin\client.dll")
def do_something(self):
len_written = self.client.fill_raw_buffer(self.__buf, self.__BUFSIZE)
my_string = repr(self.__buf.value)
print my_string
问题是我正在接收二进制数据(带有 0x00),当我尝试构建 my_string 时它被截断了。如果 self._buf 包含空字节 0x00,我如何构建 my_string?
欢迎任何想法。谢谢
最佳答案
您可以使用 raw
属性访问由 create_string_buffer()
返回的缓冲区作为 Python 字符串:
a = ctypes.create_string_buffer(10)
a.raw
# '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
要仅访问前 n
个字节,请使用
a.raw[:n]
关于python - 如何从原始(二进制)ctype 缓冲区构建 python 字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5047536/