How to write partial of a buffer which was returned from a C function to a file?

jfong at jfong at
Thu Apr 12 05:14:57 EDT 2018

Chris Angelico於 2018年4月12日星期四 UTC+8下午4時05分29秒寫道:
> On Thu, Apr 12, 2018 at 4:20 PM,  <jfong at> wrote:
> > Chris Angelico於 2018年4月12日星期四 UTC+8下午1時31分35秒寫道:
> >> On Thu, Apr 12, 2018 at 2:16 PM,  <jfong at> wrote:
> >> > This C function returns a buffer which I declared it as a ctypes.c_char_p. The buffer has size 0x10000 bytes long and the valid data may vary from a few bytes to the whole size.
> >> >
> >> > In every call I know how much the valid data size is, but I suppose I can't use slice to get it because there may be zero byte in it. What to do?
> >> >
> >>
> >> You suppose? Or have you tested it?
> >>
> >> ChrisA
> >
> > Yes, I had test it once before. Now, I re-do it again to make sure. After a call which returns 3 bytes of data, I use len(buf) to check the length and get the number 24. I can see the first 24 bytes of data by using buf[:30] but buf[24] will cause an "index out of range" error. I don't know how to see what the buf[24] exactly is but I suppose it might be a zero byte.
> >
> If you have 24 bytes, they're numbered 0 through 23. So there is no byte at 24.
> ChrisA

Using a technique you mentioned in subject "how to memory dump an object?" at 16/5/21, I confirm the length of buf was decided by a \x00 byte:

>>> len(buf)
>>> id(buf)
>>> ptr = ctypes.cast(id(buf), ctypes.POINTER(ctypes.c_ubyte))
>>> buf[:24]
>>> bytes([ptr[i] for i in range(50)])

but it won't help on solving my problem. Still need someone's help:-)


More information about the Python-list mailing list