I have written a Python Wrapper for a C++14 library using SWIG. Within the C++ API I can register std::functions as callbacks.
I have a SWIG typemap for std::function's to pass a lambda expression which invokes the Python callback:
%typemap(in) std::function {
auto callback = [$input](auto&&... params) {
PyGILState_STATE state = PyGILState_Ensure();
PyObject* result = PyObject_CallFunctionObjArgs($input,makePyObject(std::forward<decltype(params)>(params))..., NULL);
const int retVal = PyObject_IsTrue(result);
Py_DECREF(result);
PyGILState_Release(state);
return retVal == 1;
};
$1 = std::move(callback);
}
When I run a test script, the following Python expression works fine:
callback = lambda a,b: self.doStuff(a,b)
self.cppInterface.registerFunc(callback)
This expression however does not work:
self.cppInterface.registerFunc(lambda a,b: self.doStuff)
When I pass the lambda directly to the register function, I get a the following error when the callback is called from C++:
TypeError: 'managedbuffer' object is not callable
Why is the PyObject $input not a callable? How do I allow both Python expressions?
Example code: