Python objects as userdata in ctypes callback functions

前端 未结 1 1034
Happy的楠姐
Happy的楠姐 2020-12-16 18:34

The C function myfunc operates on a larger chunk of data. The results are returned in chunks to a callback function:

int myfunc(const char *data         


        
相关标签:
1条回答
  • 2020-12-16 18:41

    I guess you could use the Python C API to do that... maybe you could use a PyObject pointer.

    edit: As the op pointed out in the comments, there's already a py_object type readily available in ctypes, so the solution is to create first a ctypes.py_object object from the python list and then casting it to c_void_p to pass it as an argument to the C function (I think this step might be unnecessary as a parameter typed as void* should accept any pointer, and it would be faster to pass just a byref). In the callback, the reverse steps are done (casting from the void pointer to a pointer to py_object and then getting the value of the contents).

    A workaround could be to use a closure for your callback function so it already knows in which list it has to append the items...

    myfunc = mylib.myfunc
    myfunc.restype = c_int
    myfuncFUNCTYPE = CFUNCTYPE(STRING)
    myfunc.argtypes = [POINTER(c_char), callbackFUNCTYPE]
    
    
    def mycb(result, userdata):
        userdata.append(result)
    
    input="A large chunk of data."
    userdata = []
    myfunc(input, myfuncFUNCTYPE(lambda x: mycb(x, userdata)))
    
    0 讨论(0)
提交回复
热议问题