如何从原始(二进制)ctype缓冲区构建python字符串?

时间:2011-02-18 23:09:25

标签: python string ctypes

我正在玩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?

欢迎任何想法。感谢

1 个答案:

答案 0 :(得分:7)

您可以使用create_string_buffer()属性访问raw返回的缓冲区作为Python字符串:

a = ctypes.create_string_buffer(10)
a.raw 
# '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'

要仅访问第一个n字节,请使用

a.raw[:n]
相关问题