1

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 Answer 1

2

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)

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your answer - you really pointed my along the right lines: - I found out that ctypes has a memmove function which wraps memcpy - so I didn't need to import libc. The only other thing I needed to do was to declare my function type as CFUNCTYPE(None, POINTER(c_char), c_int) rather than CFUNCTYPE(None, c_char_p, c_int) .

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.