Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling std::function with SWIG

Tags:

c++

c++11

swig

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?

like image 697
Stefano Sanfilippo Avatar asked Nov 03 '22 19:11

Stefano Sanfilippo


1 Answers

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.

like image 113
Mark Tolonen Avatar answered Nov 14 '22 00:11

Mark Tolonen