4
votes

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.

1
What's wrong with using a void pointer? - cdonts
As I mentioned, eventually I'll have to use a CFUNCTYPE that someone else has defined and that I cannot edit. That CFUNCTYPE has POINTER(c_long) as return type. - Maas
Callbacks use the return type's setfunc to set the return value in the FFI result buffer. Only simple type's have a setfunc, including the simple pointer types c_char_p, c_wchar_p, and c_void_p. Non-simple pointer types, array types, and struct types do not have a setfunc, so they cannot be directly returned by a callback. - Eryk Sun
Using the setfunc won't leak memory for non-pointer types, but it does leak a refcount for c_char_p and the encoded wchar_t * buffer for c_wchar_p. If you set the result type to c_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 the c_long instance. - Eryk Sun
Then why is it used in the following function definition: MediaOpenCb = 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

1 Answers

4
votes

This is currently not possible. See this CPython bug report.