簡體   English   中英

如何使用ctypes將庫的extern函數指針設置為Python回調函數?

[英]How do I use ctypes to set a library's extern function pointer to a Python callback function?

一些C庫導出函數指針,使得庫的用戶將該函數指針設置為它們自己的函數的地址以實現鈎子或回調。

在這個示例庫liblibrary.so ,如何使用ctypes將library_hook設置為Python函數?

library.h:

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

這在ctypes中很棘手,因為ctypes函數指針不實現用於設置其他指針的.value屬性。 相反,使用c_void_p函數將回調函數和extern函數指針c_void_pvoid * 在將函數指針設置為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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM