如何从原始(二进制)ctype缓冲区构建python字符串? [英] How do I build a python string from a raw (binary) ctype buffer?

查看:107
本文介绍了如何从原始(二进制)ctype缓冲区构建python字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Python和ctypes,但我不知道如何解决此问题。我调用一个C函数来填充原始二进制数据。我的代码如下所示:

I'm playing with Python and ctypes and I can't figure out how to resolve this problem. I call to a C function which fills a raw binary data. My code looks like this:

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?

The problem is that I'm receiving binary data (with 0x00) and it's truncated when I tried to build my_string. How can I build my_string if self._buf contains null bytes 0x00?

任何想法都值得欢迎。谢谢

Any idea is welcome. Thanks

推荐答案

您可以访问 create_string_buffer()返回的缓冲区使用其 raw 属性创建一个Python字符串:

You can access a buffer returned by create_string_buffer() as a Python string by using its raw attribute:

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

仅访问前 n 个字节,请使用

To only access the first n bytes, use

a.raw[:n]

这篇关于如何从原始(二进制)ctype缓冲区构建python字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆