2

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

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

1 Answer 1

8

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'

To only access the first n bytes, use

a.raw[:n]
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, but I have a big working buffer that is partially filled by function I'm calling for. I also know how many bytes were written (5 bytes for example). The question is how can I build a python string using the first 5 bytes considering some of those bytes can be null.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.