dimanche 29 mars 2015

C++ this pointer equivalent in Python ctypes


I'm calling a C dll from Python using ctypes and having some trouble passing the correct parameters to the IBSU_RegisterCallbacks function, defined below.



int WINAPI IBSU_RegisterCallbacks
(const int handle,
const IBSU_Events event,
void *pCallbackFunction,
void *pContext);


It describes the final parameter as:



/* pContext Pointer to user context that will be passed to callback function.*/


A working C++ example calls the function like this:



RegisterCallbacks(0, 1, OnCallback, this);


So far in Python I have the below code (relevant section shown only), which crashes Python (no traceback) shortly after the event is triggered and callback run! is printed.



from ctypes import *

class IBSU(object):
_dll = WinDLL('ibsu.dll')

_C_CALLBACK = CFUNCTYPE(
None,
c_int, # device handle
c_void_p) # user context

_register_callbacks = _dll.IBSU_RegisterCallbacks
_register_callbacks.restype = c_int
_register_callbacks.argtypes = (c_int, # device handle
c_int, # event type
c_void_p, # callback function
c_void_p) # user context

def _get_c_callback(self):
def callback(handle, # device handle
p_context): # user context
print 'callback run!'
return self._C_CALLBACK(callback)

def register_callbacks(self):
# keep ref to prevent garbage collection
self._c_callback = self._get_c_callback()

self._register_callbacks(0, # device handle
1, # event type
self._c_callback, # callback function
c_void_p()) # user context


What is the equivalent to this in my Python class that I can send instead of just c_void_p()?




Aucun commentaire:

Enregistrer un commentaire