Skip to content

Instantly share code, notes, and snippets.

@oliora
Created September 3, 2012 08:08
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save oliora/3607799 to your computer and use it in GitHub Desktop.
Save oliora/3607799 to your computer and use it in GitHub Desktop.
SWIG interface with using of Python callable as callback
%module(threads="1") something
%{
// Register a callback (called from Python code)
// callbackFunc is a Python callable accepting one argument
void registerHandler(PyObject *callbackFunc)
{
SWIG_PYTHON_THREAD_BEGIN_ALLOW;
const bool hasCallback =
callbackFunc != 0 && callbackFunc != Py_None;
// do registration of 'callbackFunc' ...
SWIG_PYTHON_THREAD_END_ALLOW;
Py_XINCREF(callbackFunc); // to keep callback alive, don't forget to DECREF on unregiser
}
// Calls the callback (called from C code), Param is some SWIG-wrapped type
void processCallback(PyObject *callbackFunc, Param& param)
{
SWIG_PYTHON_THREAD_BEGIN_BLOCK;
PyObject *arglist = PyTuple_New(1);
PyTuple_SET_ITEM(arglist, 0,
SWIG_NewPointerObj(SWIG_as_voidptr(&param), SWIGTYPE_p_Param_Type, 0));
PyObject *result = PyEval_CallObject(callbackFunc, arglist);
Py_DECREF(arglist);
Py_XDECREF(result);
SWIG_PYTHON_THREAD_END_BLOCK;
}
%}
%typemap(in) PyObject * {
$1 = $input;
}
%typemap(out) PyObject * {
$result = $1;
}
%nothread registerHandler;
void registerHandler(PyObject *callbackFunc);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment