1
私はstd::function<void()> funcs
を含むC++タイプFoo
を持っています。これは正常にPythonにバインドされています。私の目的は、Pythonで関数を定義し、この型に関数を追加してインスタンスを返すことです。 C++では、私はpybindを使用してこのタイプのインスタンスを取得します。しかし、私の関数seg-faultsのうちの1つを呼び出そうとしたとき。pybind11でpython関数をstd :: functionにキャストする方法
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);
}
以降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);
に私のpythonモジュールは、これを持っている:
def newFunc():
print "working!"
def create_foo():
temp = foo.Foo(0, 100)
temp.addFunc(newFunc)
return temp
私はよく分からない機能がCに戻ってキャストされていない理由は、正しく++?