2011-06-01 72 views
8

我在使用ctypes實現時遇到問題。我有2個C函數:回調函數的ctypes無效結果類型

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

其中antichain和counting_function是兩個結構。 antichain可以看作一個集合,包含未知類型的元素(在這個例子中是counting_function)。 decompose_antichain函數作爲參數(除別的以外)用來分解antichain包含的元素( - >原型爲void **(*)(void *))的函數。

現在我想從Python中使用decompose_antichain。我用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)) 

最後一行產生錯誤:回調函數的結果類型無效。

我看不出問題來自哪裏。誰能幫我?謝謝

回答

1

您需要確保argtypes和結果類型匹配。它看起來像交換了decompose_antichain_c的參數類型。您在argtypes中有DECOMPOSE_COUNTING_FUNCTION_FUNC, COMPARE_COUNTING_FUNCTIONS_FUNC,它與您在上面給出的C函數的聲明不匹配。然後嘗試使用COMPARE_COUNTING_FUNCTIONS_FUNC首先調用它,然後再使用DECOMPOSE_COUNTING_FUNCTION_FUNC秒。

DECOMPOSE_COUNTING_FUNCTION_FUNC也看起來不對。它應該可能是CFUNCTYPE(POINTER(c_void_p), c_void_p)只是從其餘的代碼中猜測出來的。

我可以給出更詳細的答案,如果您提供的代碼創建COMPARE_COUNTING_FUNCTIONS_FUNCCountingFunction