0
votes

I have a C function in a DLL which is calling back to a Python function via ctypes.

The C function calls the function with the following prototype:

void GetData(u8 Buffer[], u16 Length);

Note that the buffer points to a static data array which is held in the DLL.

I've generated a Python function type for this as the following:

CFUNCTYPE(None, c_char_p, c_int)

And my Python callback function is being called without any obvious problems.

My problem is, I can't work out how to get ctypes to add raw data to a buffer which is external to Python. Is there a way to define a ctypes string buffer and give it the address of the DLL's buffer?

1

1 Answers

2
votes

You could use memcpy from libc. If your c_char_p is buffer and c_int is bufferlen:

libc = ctypes.cdll.LoadLibrary('libc.so.6')
content = 'My new content'
bufcontent = ctypes.create_string_buffer(content)
libc.memcpy(buffer. newcontent, min(len(content) + 1, bufferlen))

Same as you would do in C. (note that i've used memcpy for possible binary content, but if you don't care about it, use strncpy instead)