Calling Python functions from SWIG/C++

To make it more easy to integrate my Sparse Grid framework into existing applications (like those almighty financial applications where one function evaluation takes a whole day to calculate) and of course for easier development/testing, I searched for a way to call python callables from my swig-wrapped c++ code.

Lets first have a look in the swig documentation:

SWIG provides full support for function pointers provided that the callback functions are defined in C and not in the target language.

That’s unfortunate. Further research revealed that there is indeed a (rather hackish) way to manage that.

First we define a function for setting the a callback:

void setCallback(PyObject* obj) ;

Now SWIG expects a wrapped PyObject-object, which we don’t have. That behavior can be overwritten be defining a custom typemap. The easiest possible solution would be:

%typemap(in) PyObject* {
$1 = $input;
}

All you have to do now is to check the object in your previously defined function and grab a reference to it. Read the Python documentation on how to do that.

Overall rating: Working, but not very portable.

Leave a Reply