Created
September 3, 2012 08:08
-
-
Save oliora/3607799 to your computer and use it in GitHub Desktop.
SWIG interface with using of Python callable as callback
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
%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(¶m), 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