如何使用ctypes设置库';指向Python回调函数的外部函数指针?

如何使用ctypes设置库';指向Python回调函数的外部函数指针?,python,ctypes,Python,Ctypes,一些C库导出函数指针,以便库的用户将该函数指针设置为自己函数的地址,以实现钩子或回调 在这个示例库libliblibrary.so中,如何使用ctypes将library\u hook设置为Python函数 图书馆h: typedef int exported_function_t(char**, int); extern exported_function_t *library_hook; 这在ctypes中很棘手,因为ctypes函数指针没有实现用于设置其他指针的.value属性。相反,使

一些C库导出函数指针,以便库的用户将该函数指针设置为自己函数的地址,以实现钩子或回调

在这个示例库
libliblibrary.so
中,如何使用ctypes将library\u hook设置为Python函数

图书馆h:

typedef int exported_function_t(char**, int);
extern exported_function_t *library_hook;

这在ctypes中很棘手,因为ctypes函数指针没有实现用于设置其他指针的
.value
属性。相反,使用
c\u void\u p
函数将回调函数和外部函数指针强制转换为
void*
。如图所示,将函数指针设置为
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