July 2002
Intermediate to advanced
608 pages
15h 46m
English
Credit: Swaminathan Narayanan
You must call a C function that takes a function callback as an argument, and you want to pass a Python function as the callback.
For this, we must wrap the Python function in a C function to be passed as the actual C-level callback. For example:
#include "python.h"
/* the C standard library qsort function, just as an example! */
extern void qsort(void *, size_t, size_t, int (*)(const void *, const void *));
/* static data (sigh), as we have no callback data in this (nasty) case */
static PyObject *py_compare_func = NULL;
static int
stub_compare_func(const void *cva, const void *cvb)
{
int retvalue = 0;
const PyObject **a = (const PyObject**)cva;
const PyObject **b = (const PyObject**)cvb;
// Build up the argument list...
PyObject *arglist = Py_BuildValue("(OO)", *a, *b);
// ...for calling the Python compare function
PyObject *result = PyEval_CallObject(py_compare_func, arglist); if (result && PyInt_Check(result)) { retvalue = PyInt_AsLong(result); } Py_XDECREF(result); Py_DECREF(arglist); return retvalue; } static PyObject *pyqsort(PyObject *obj, PyObject *args) { PyObject *pycompobj; PyObject *list; if (!PyArg_ParseTuple(args, "OO", &list, &pycompobj)) return NULL; // Make sure second argument is a function if (!PyCallable_Check(pycompobj)) { PyErr_SetString(PyExc_TypeError, "Need a callable object!"); } else { // Save the compare function. This obviously won't work for multithreaded ...Read now
Unlock full access