【问题标题】:unable to return shared_ptr from static function in pybind11无法从 pybind11 中的静态函数返回 shared_ptr
【发布时间】:2019-05-07 07:57:52
【问题描述】:

我尝试绑定一个静态函数,该函数返回指向另一个类的 shared_ptr。

这里是示例代码

class Example {
  public:
    Example() {}
    ~Example() {}
};

class ABC {
  public:
    static std::shared_ptr<Example> get_example() {std::make_shared<Example();}
 };

void init_abc(py::module & m) {
  py::class_<Example>(m, "Example")
    .def(py::init<>());

  py::class_<ABC>(m, "ABC")
    .def_static("get_example", &ABC::get_example);
}

这里是python的一面

example = my_module.ABC.get_example()

但是,python 端抛出了分段错误。

有什么想法吗?

【问题讨论】:

  • 我不知道pybind11是否支持shared_ptr,如果不支持,您可以随时尝试使用.get()返回实际指针。在 Python 端返回 shared_ptr 或实际的 pointer 并不一定重要,因为 shared_ptr 无论如何都是由 C++ 管理的。如果可以解决问题,我认为使用 .get() 应该是安全的。

标签: python c++ pybind11


【解决方案1】:

您的代码中缺少一些位,例如 &gt;。这是工作示例:

class Example {
public:
    Example() {}
    ~Example() {}
};

class ABC {
public:
    static std::shared_ptr<Example> get_example() { return std::make_shared<Example>();}
};

接下来,在包装 Example 类的地方提供额外的模板参数 shared_ptr&lt;Example&gt;

py::class_<Example, std::shared_ptr<Example>>(m, "Example")
    .def(py::init<>());

py::class_<ABC>(m, "ABC")
    .def_static("get_example", &ABC::get_example);

这样shared_ptr&lt;Example&gt;就会得到妥善处理。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-31
    • 2023-02-13
    • 1970-01-01
    • 2013-02-08
    • 2016-05-06
    • 1970-01-01
    • 2020-07-20
    相关资源
    最近更新 更多