这在ctypes中很棘手,因为ctypes函数指针不实现.value
用于设置其他指针的属性.相反,投你的回调函数和外部函数指针void *
与c_void_p
功能.在设置了void *
如图所示的函数指针之后,C可以调用你的Python函数,你可以将函数作为函数指针检索并用普通的ctypes调用来调用它.
from ctypes import * liblibrary = cdll.LoadLibrary('liblibrary.so') def py_library_hook(strings, n): return 0 # First argument to CFUNCTYPE is the return type: LIBRARY_HOOK_FUNC = CFUNCTYPE(c_int, POINTER(c_char_p), c_int) hook = LIBRARY_HOOK_FUNC(py_library_Hook) ptr = c_void_p.in_dll(liblibrary, 'library_hook') ptr.value = cast(hook, c_void_p).value