Writing Python types for a function pointer callback function in C

I am trying to write python code to call dll functions and am stuck in the function below, which I assume is related to the typedef callback function or function pointer function.

I tested the code below when the callback function is called, python crashes (Window notification - python.exe stops responding) without msg debugging.

I am deeply confused, any help would be appreciated :)

Thanks!

WITH

#ifdef O_Win32 /** @cond */ #ifdef P_EXPORTS #define API __declspec(dllexport) #else #define API __declspec(dllimport) #endif // #ifdef P_EXPORTS /** @endcond */ #endif // #ifdef O_Win32 // Type definition typedef void (__stdcall *StatusCB)(int nErrorCode, int nSID, void *pArg); //Function void GetStatus(StatusCB StatusFn, void *pArg); 

Python:

 from ctypes import * def StatusCB(nErrorCode, nSID, pArg): print 'Hello world' def start(): lib = cdll.LoadLibrary('API.dll') CMPFUNC = WINFUNCTYPE(c_int, c_int, c_void_p) cmp_func = CMPFUNC(StatusCB) status_func = lib.GetStatus status_func(cmp_func) 
+6
source share
1 answer

Your callback type has an incorrect signature; You forgot the type of result. It also receives garbage collection when a function exits; you need to make it global.

The GetStatus call GetStatus missing the pArg argument. Plus, when working with pointers, you need to define argtypes , otherwise you will have problems on 64-bit platforms. The default argument type ctypes is C int .

 from ctypes import * api = CDLL('API.dll') StatusCB = WINFUNCTYPE(None, c_int, c_int, c_void_p) GetStatus = api.GetStatus GetStatus.argtypes = [StatusCB, c_void_p] GetStatus.restype = None def status_fn(nErrorCode, nSID, pArg): print 'Hello world' print pArg[0] # 42? # reference the callback to keep it alive _status_fn = StatusCB(status_fn) arg = c_int(42) # passed to callback? def start(): GetStatus(_status_fn, byref(arg)) 
+9
source

Source: https://habr.com/ru/post/950757/


All Articles