问题描述
某些C库导出函数指针,以便该库的用户将函数指针设置为指向其自己函数的地址,以实现钩子或回调。
Some C libraries export function pointers such that the user of the library sets that function pointer to the address of their own function to implement a hook or callback.
In此示例库 liblibrary.so
,如何使用ctypes将library_hook设置为Python函数?
In this example library liblibrary.so
, how do I set library_hook to a Python function using ctypes?
library.h :
library.h:
typedef int exported_function_t(char**, int);
extern exported_function_t *library_hook;
推荐答案
在ctypes中这很棘手,因为ctypes函数指针不实现用于设置其他指针的 .value
属性。而是使用 c_void_p
函数将回调函数和extern函数指针转换为 void *
。如图所示将函数指针设置为 void *
之后,C可以调用您的Python函数,并且您可以将函数作为函数指针进行检索,并使用普通的ctypes调用进行调用。 / p>
This is tricky in ctypes because ctypes function pointers do not implement the .value
property used to set other pointers. Instead, cast your callback function and the extern function pointer to void *
with the c_void_p
function. After setting the function pointer as void *
as shown, C can call your Python function, and you can retrieve the function as a function pointer and call it with normal ctypes calls.
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
这篇关于如何使用ctypes将库的extern函数指针设置为Python回调函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!