Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ctypes invalid result type for a callback function

Tags:

python

ctypes

I face a problem while implementing with ctypes. I have 2 C functions:

antichain** decompose_antichain(antichain*, int, char (*)(void*, void*), void** (*)(void*));
counting_function** decompose_counting_function(counting_function*);

where antichain and counting_function are two structures. An antichain can be seen like a set, containing elements of unknown type (in this exemple, counting_function). The decompose_antichain function takes as argument (amongst other things) the function to use to decompose the elements the antichain contains (-> a function of which the prototype is void** (*) (void*)).

Now i would like to use decompose_antichain from Python. I used ctypes:

lib = cdll.LoadLibrary("./mylib.dylib")
#CountingFunction, Antichain and other definitions skipped
DECOMPOSE_COUNTING_FUNCTION_FUNC = CFUNCTYPE(POINTER(c_void_p), POINTER(CountingFunction))
decompose_counting_function_c = lib.decompose_counting_function
decompose_counting_function_c.argtypes = [POINTER(CountingFunction)]
decompose_counting_function_c.restype = POINTER(c_void_p)
decompose_antichain_c = lib.decompose_antichain
decompose_antichain_c.argtypes = [POINTER(Antichain), c_int, DECOMPOSE_COUNTING_FUNCTION_FUNC, COMPARE_COUNTING_FUNCTIONS_FUNC]
decompose_antichain_c.restype = POINTER(POINTER(Antichain))

(...)

antichains_list = decompose_antichain_c(antichain, nb_components, COMPARE_COUNTING_FUNCTIONS_FUNC(compare_counting_functions_c), DECOMPOSE_COUNTING_FUNCTION_FUNC(decompose_counting_function_c))

The last line produces the error: invalid result type for a callback function.

I can't see where the problem come from. Can anyone help me? Thanks

like image 380
Naked Avatar asked Jun 01 '11 11:06

Naked


1 Answers

You need to make sure the argtypes and result types match. It looks like you swapped the argument types of decompose_antichain_c. You have DECOMPOSE_COUNTING_FUNCTION_FUNC, COMPARE_COUNTING_FUNCTIONS_FUNC in the argtypes, which doesn't match the declaration of the C function you gave above. You then try to call it with COMPARE_COUNTING_FUNCTIONS_FUNC first, and DECOMPOSE_COUNTING_FUNCTION_FUNC second.

DECOMPOSE_COUNTING_FUNCTION_FUNC also looks wrong. It should probably be CFUNCTYPE(POINTER(c_void_p), c_void_p) just guessing from the rest of the code.

I can give a more detailed answer if you provide the code that creates COMPARE_COUNTING_FUNCTIONS_FUNC and CountingFunction

like image 163
ricochet1k Avatar answered Nov 07 '22 09:11

ricochet1k