3

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

在这个示例库liblibrary.so中,如何使用 ctypes 将 library_hook 设置为 Python 函数?

图书馆.h:

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

1 回答 1

9

这在 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
于 2009-01-29T17:39:14.423 回答