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


Some of the export function pointers libraries such that the library is set to apply to work with their pointer over your function address users in a hook or callback

this example Library liblibrary.so , how do I set library_hook to a python function using ctypes I

library .h.?:

typedef int exported_function_t (char **, int); Exxton Exports _ Function _ T * Library_Hook;

It is difficult Ctypes, because Ctypes function pointers do not apply . Price it used the property to set other points, c_void_p to your callback function and extern function pointer with function void * Put . As the function indicator is installed after zero * is shown, C can call your python function, and you can retrieve the function as a function indicator and call it with normal ctypes Can say.

 ctypes from  import * liblibrary = cdll.LoadLibrary ( 'liblibrary.so') def py_library_hook (string, n) return 0 # CFUNCTYPE the first case back 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  
< / Html>

Comments