How to write partial of a buffer which was returned from a C function to a file?
eryksun at gmail.com
Fri Apr 13 00:16:06 EDT 2018
On Fri, Apr 13, 2018 at 12:38 AM, Jach Fong <jfong at ms4.hinet.net> wrote:
> Gregory Ewing at 2018/4/13 上午 07:25 wrote:
>> To get around this, you may need to declare the return type
>> as POINTER(c_char) instead:
>>> For a general character pointer that may also point to binary data,
>> > POINTER(c_char) must be used.
> I had missed this statement:-(
> To make a quick try, I set the function's restype to
> ctypes.POINTER(ctypes.c_ubyte), instead of ctypes.c_char_p. It's amazing,
> the \x00 trap can be avoided in this way. Now I can use "mydata =
> bytes(buf[:n])" to extract n bytes of data and write it to file.
Slicing a ctypes.POINTER(ctypes.c_char) pointer returns bytes without
having to make a third copy via the bytes constructor. (Note that
c_char is the fundamental C char integer type, not to be confused with
c_char_p, which is a char * pointer.) However, if you're working with
multi-megabyte data buffers,it's more efficient and safer to use an
array view (ctypes or NumPy) on the returned buffer.
In most cases, you should free the returned pointer after you're
finished processing the data buffer, else you'll have a memory leak.
The library should export a function for this.
More information about the Python-list