Need help to grok c extension that needs to use callbacks with data
"Martin v. Löwis"
martin at v.loewis.de
Fri Jun 20 04:51:20 EDT 2003
Jim West wrote:
> Python -> C Extension -> MethodWithCallback (void (*userFunc)(unsigned
> char *))
>
> ...and I want the callback function to be a Python function.
You need to write a callback wrapper, and a wrapper object. Roughly,
you need something like that:
struct PyParam{
PyObject *callable;
PyObject *param;
};
void CallbackWrapper(unsigned char* cdata)
{
struct PyParam* data = (struct PyParam*)cdata;
PyObject_CallFunction(data->callable, "O", data->param);
/* look at exceptions. */
}
PyObject* PyMethodWithCallback(PyObject* ignored, PyObject*args)
{
struct PyParam params;
PyArg_ParseTuple(args, "OO", ¶ms.callable, ¶ms.param);
if (!PyCallable_Check(params.callable))
raise TypeError, "first parameter must be callable"
MethodWithCallback(CallbackWrapper, ¶ms);
}
This, of course, assumes that the unsigned char* does not need
to point to a stringz, but can point to arbitrary memory. It also
assumes that the callback will be called before PyMethodWithCallback
returns; otherwise, params must be allocated dynamically.
HTH,
Martin
More information about the Python-list
mailing list