Recently I started to use SWIG to develop a solution that passes (possibly) several callback functions that should be called in the C++ layer. Besides, I spent some time reading the introduction callback chapter and the director feature.
I've managed to achieve my goal by coding different classes that inherit from the base class in the C++ layer from the documentation example, but I'm trying to learn in how to pass std::function
instances instead of pointer to classes.
I believe that the (incorrect) example below summarizes my objective:
File example.h:
#include <functional>
#include <map>
#include <vector>
class Controller {
private:
std::vector<std::function<void()>> functions;
public:
virtual void AddFunction(const std::function<void(void)>& func) {
functions.push_back(func);
}
virtual void Execute() {
for (int m = 0; m < functions.size(); ++m) functions[m]();
}
Controller() {}
virtual ~Controller() {}
};
File example.i:
%module example
%{
#include "example.h"
%}
%include "example.h"
File example.py:
import example
def foo():
print("yey")
def bar():
print("dog")
def cat():
print("miaw")
e = example.Controller()
e.AddFunction(foo)
e.AddFunction(bar)
e.AddFunction(cat)
# Prints yey, dog and miaw sequentially
e.Execute()
So, my question is:
- Am I in the right direction here? In other words, is this really possible to do with SWIG?
- Can I achieve my goal with the director feature only?