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

标签 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?

欢迎任何想法。谢谢

最佳答案

您可以使用 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/

相关文章:

javascript - 在javascript中使用按位或转换为整数

c++ - 比较两个字符串迭代器总是得出正确的 C++

python - 在 py.test 中,当我明确跳过标记为 xfail 的测试时,如何将其报告为 'skipped' 而不是 'xfailed' ?

python - django_settings_module 在 GAE 服务器上未定义

javascript - 在渲染时转义 html 中的 angularJS 术语

python - 在执行 pool.map 时,是否可以在 python 中每 x 秒执行一次函数?

string - 将 R 向量转换为 1 个元素的字符串向量

python - 在 Python 中使用 ctypes 返回结构

Python Ctypes 奇怪的行为

python - 在 python ctypes 中将结构传递给 Windows API