如何使用ctypes的到库的外部函数指针设置为一个Python回调函数?
题
某些C库导出函数指针从而使得文库的用户设置一个函数指针自己函数的地址来实现的钩或回调。
在这个例子中库liblibrary.so
,如何设置library_hook到Python函数使用ctypes的?
library.h:
typedef int exported_function_t(char**, int);
extern exported_function_t *library_hook;
解决方案
这是在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
不隶属于 StackOverflow