Apparently, SWIG does not understand std::function
and breaks Python bindings. For instance, this works in C++:
// Somewhere in the API
typedef std::function<void(const UnitError & error)> UnitErrorHandler;
// Somewhere else in the API
void Unit::setErrorHandler(const UnitErrorHandler & handler) {}
// In the application code
unit->setErrorHandler([](const UnitError & error){
std::cerr << error << std::endl;
std::exit(1);
});
But this will break code (apart from having a different behaviour for the sake of simplicity, but that's not the point):
unit.setErrorHandler(lambda error: len(error))
The situation is the same with def
(ordinary) unbound functions.
So, does anyone know a workaround for this?
std::function
is relatively new (C++11) so SWIG doesn't have any out-of-the-box solution for it. While not as flexible, you can use function pointers, with a caveat. Quoting 5.4.9 Pointers to functions and callbacks in the docs:
...SWIG provides full support for function pointers provided that the callback functions are defined in C and not in the target language.
So passing a lambda will not work. Read the documentation link for some alternatives.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With