I was planning on using a C function exported by a DLL in my Python application. This particular function takes multiple callbacks as parameters, so I was fiddling around with defining such callbacks with ctypes in python. However, I quickly got stuck on this simple test:
from ctypes import *
someFunction = CFUNCTYPE(POINTER(c_long), c_long)
def someFunctionPy(someLong):
return pointer(c_long(someLong))
print POINTER(c_long)
print someFunctionPy(1)
someFunctionImpl = someFunction(someFunctionPy)
Where someFunctionImpl could then be passed on to a C function as a parameter. This gives me the following error:
<class '__main__.LP_c_long'>
<__main__.LP_c_long object at 0x022928F0>
Traceback (most recent call last):
File "test.py", line 12, in <module>
someFunctionImpl = someFunction(someFunctionPy)
TypeError: invalid result type for callback function
The print outputs tell me that the function returns an object of the correct type, so what am I missing here?
Edit: It does seem to work when I use someFunction = CFUNCTYPE(c_void_p, c_long), even though c_void_p and POINTER(c_long) have differing types. Huh?
This doesn't really help though, since eventually I'll have to use a predefined CFUNCTYPE that has POINTER(c_int) as return type.
CFUNCTYPEthat someone else has defined and that I cannot edit. ThatCFUNCTYPEhasPOINTER(c_long)as return type. - Maassetfuncto set the return value in the FFI result buffer. Only simple type's have asetfunc, including the simple pointer typesc_char_p,c_wchar_p, andc_void_p. Non-simple pointer types, array types, and struct types do not have asetfunc, so they cannot be directly returned by a callback. - Eryk Sunsetfuncwon't leak memory for non-pointer types, but it does leak a refcount forc_char_pand the encodedwchar_t *buffer forc_wchar_p. If you set the result type toc_void_p, then you can return just the address of a ctypes object. This puts the onus on you to keep the object alive while the C library has access, e.g. in this case you'd need to keep a reference to thec_longinstance. - Eryk SunMediaOpenCb = ctypes.CFUNCTYPE(ctypes.POINTER(ctypes.c_int), ctypes.c_void_p, ListPOINTER(ctypes.c_void_p), ctypes.POINTER(ctypes.c_uint64)), which comes directly from the libvlc API? (which I assume has been tested) - Maas