Writing Python ctypes for Function pointer callback function in C -
i trying write python code call dll functions , stuck @ function below, believe related typedef callback function or function pointer thing.
i have tested code below, when callback function called, python crashes (window notification-- python.exe has stop responding) no debug msg.
i confused, appreciated :)
thanks!
c:
#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)
your callback type has wrong signature; forgot result type. it's getting garbage collected when function exits; need make global.
your getstatus
call missing argument parg
. plus when working pointers need define argtypes
, else you'll have problems on 64-bit platforms. ctypes' default argument type 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 callback keep alive _status_fn = statuscb(status_fn) arg = c_int(42) # passed callback? def start(): getstatus(_status_fn, byref(arg))
Comments
Post a Comment