How to create python string from ctype buffer (binary)?

I play with Python and ctypes, and I cannot figure out how to solve this problem. I call the C function, which fills the raw binary data. My code is as follows:

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

The problem is that I am getting binary data (from 0x00) and it was 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

+2
source share
1 answer

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

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

To access only the first bytes n, use

a.raw[:n]
+7
source

All Articles