开发者

C function passes a pointer and a length, and a Python callback needs to make an array and assign it

I'm wrapping a C library that uses callbacks as external memory allocators. Basically, instead of doing malloc and free itself, it exposes several callbacks for making buffers of specified sizes. Hooking those up with ctypes is fairly easy, and all that seems to be working. However, I can't seem to connect the array to the pointer that's passed in.

The C interface looks something like this:

extern int (*alloc_int_buffer_callback)(some_struct* buffer, uint32_t length);

I've got the struct defined through ctypes, and it seems to match up perfectly.

The ctypes callbacks look something like this:

_int_functype = CFUNCTYPE(c_int, POINTER(some_struct), c_uint)

The problem I'm having i开发者_JAVA技巧s that trying to get the POINTER(some_struct) instance to point at an array of type (c_int * length) doesn't seem to work. Here's the callback I've got right now:

def _alloc_struct_buffer(ptr, length):
    arr_type = SomeStruct * length
    arr = arr_type()

    ptr.contents = cast(addressof(arr), POINTER(SomeStruct))

    return 1

Unfortunately, I'm getting an error along the lines of "Expected SomeStruct instead of LP_SomeStruct". What am I missing?


If you want to return a pointer in a parameter, you need to pass in a pointer to a pointer:

extern int alloc_int_buffer_callback(some_struct **buffer, uint32_t length);

If you simply pass in a pointer, changing the pointer inside the function does nothing, since you passed the pointer by value.

Inside your Python callback, you can use

ptr.contents = cast(arr, POINTER(SomeStruct))

after changing the prototype.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜