ctypes回调函数的返回类型无效

8

我在使用ctypes时遇到了问题。我有两个C函数:

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个回答

1

您需要确保argtypes和result types匹配。看起来您交换了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的代码,我可以提供更详细的答案。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接