I have a c++ type Foo
which contains a std::function<void()> funcs
, which has been successfully bound to python. My aim is to define functions in python and add them to this type, then return an instance. In c++ I use pybind to get an instance of this type which works. However when I attempt to call one of the functions my program seg-faults.
class Foo
{
void addFunc(std::function<void()> _func)
{
funcs.push_back(_func);
}
void call(int _index)
{
funcs[_index]();
}
private:
std::vector<std::function<void()>> funcs;
}
namespace py = pybind11;
PYBIND11_MODULE(foo, m)
{
py::class_<Foo>(m, "foo")
.def(py::init<int, int>())
.def("addFunc", &Foo::addFunc)
.def("call", &Foo::call);
}
And later in c++
py::scoped_interpreter python;
auto module = py::module::import("foo_module");
auto func = module.attr("create_foo");
auto result = func();
//This works!
result.attr("call")(0);
Foo* blah = result.cast<Foo*>();
//This seg-faults!
blah->call(0);
My python module has this:
def newFunc():
print "working!"
def create_foo():
temp = foo.Foo(0, 100)
temp.addFunc(newFunc)
return temp
I'm not sure why the functions aren't being cast back to c++ correctly?
I had to move the py::scoped_interpreter python;
to a higher scope as it wasn't in scope when the function was called
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.