【问题标题】:How do I use ctypes to set a library's extern function pointer to a Python callback function?如何使用 ctypes 将库的外部函数指针设置为 Python 回调函数?
【发布时间】:2009-01-29 16:31:41
【问题描述】:

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

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

图书馆.h:

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

【问题讨论】:

    标签: python ctypes


    【解决方案1】:

    这在 ctypes 中很棘手,因为 ctypes 函数指针没有实现用于设置其他指针的 .value 属性。相反,使用c_void_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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-01
      • 2013-04-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-02
      相关资源
      最近更新 更多