简体   繁体   English

如何使用pybind11将python函数转换为std :: function

[英]How to cast a python function to std::function with pybind11

I have a c++ type Foo which contains a std::function<void()> funcs , which has been successfully bound to python. 我有一个C ++类型的Foo ,其中包含一个std::function<void()> funcs ,它已成功绑定到python。 My aim is to define functions in python and add them to this type, then return an instance. 我的目标是在python中定义函数并将其添加到此类型,然后返回一个实例。 In c++ I use pybind to get an instance of this type which works. 在c ++中,我使用pybind来获取这种类型的实例,该实例可以工作。 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++ 后来在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: 我的python模块有这个:

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? 我不确定为什么函数没有正确地转换回c ++?

I had to move the py::scoped_interpreter python; 我不得不移动py::scoped_interpreter python; to a higher scope as it wasn't in scope when the function was called 到更高的范围,因为调用该函数时不在范围内

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM