Passing a callback from Python to C by structure
I am trying to pass a callback function from Python to C contained in a struct. So far I've had no luck on how to pass a Python function to C.
Definition of structure C:
typedef int (* TOUCH_CALLBACK_FUNC)(int x, int y);
typedef int (* HARDKEY_CALLBACK_FUNC)(int key);
typedef struct _rect
{
u32 left;
u32 top;
u32 width;
u32 height;
} RECT;
typedef struct _touch_data
{
u8 sign[16];
u8 *file;
RECT rect;
u32 destWidth;
u32 destHeight;
u32 uiTimeOut;
TOUCH_CALLBACK_FUNC cb;
HARDKEY_CALLBACK_FUNC keyCb;
void *extArg;
void *extArg2;
} TOUCH_DATA;
Python definition is as follows
from ctypes import Structure, CFUNCTYPE, c_int32, POINTER
TOUCH_CALLBACK_FUNC = CFUNCTYPE(c_int32, POINTER(c_int32), POINTER(c_int32))
HARDKEY_CALLBACK_FUNC = CFUNCTYPE(c_int32, POINTER(c_int32))
class Rect(Structure):
_pack_ = 1
_fields_ = [('left', c_int32),
('top', c_int32),
('width', c_int32),
('height', c_int32)]
class TouchDataStruct(Structure):
_pack_ = 1
_fields_ = [('sign', c_char * 16),
('file', c_char_p),
('rect', Rect),
('destWidth', c_uint32),
('destHeight', c_uint32),
('touchCallback', TOUCH_CALLBACK_FUNC),
('keyCallback', HARDKEY_CALLBACK_FUNC),
('uiTimeOut', c_uint32),
('extArg', c_void_p),
('extArg2', c_void_p)]
I am executing the following code from Python:
def touch_cb(x, y):
return 0
def key_cb(key):
return 0
data = TouchDataStruct(
file='...'.encode('ascii'),
rect=Rect(left=0,top=0,width=50,height=25),
cb=TOUCH_CALLBACK_FUNC(touch_cb),
keyCb=TOUCH_CALLBACK_FUNC(key_cb),
destWidth=75,
destHeight=30,
uiTimeOut=60000
)
cwrapper.process(data)
The actual error is that size_t
for the structure that C accepts is 48 and the size_t
actual structure for C is 64.
To get the structure in C, I use the following snippet:
PyObject *Wrapper_Process(PyObject *self, PyObject *args) {
TOUCH_DATA *touch_data;
size_t size;
PyArg_ParseTuple(args, "y#", &touch_data, &size);
if (size != sizeof(TOUCH_DATA)) {
// Raise error here!
}
}
Thank you in advance:)
Edit 1: Added more information about both structures and detailed the error
Edit 2: Forgot to convert the string to bytes
Edit 3: The example code had double underscores for the fields and package (which was correct for the actual code, just fixing it here)
source to share
No one has answered this question yet
Check out similar questions: