Need help to grok c extension that needs to use callbacks with data

"Martin v. Löwis" martin at
Fri Jun 20 10:51:20 CEST 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", &params.callable, &params.param);
   if (!PyCallable_Check(params.callable))
      raise TypeError, "first parameter must be callable"
   MethodWithCallback(CallbackWrapper, &params);

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.


More information about the Python-list mailing list