python - 无法从 pybind11 中的静态函数返回 shared_ptr

标签 python c++ pybind11

我试图绑定(bind)一个返回指向另一个类的 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 端抛出了一个段错误。

有什么想法吗?

最佳答案

您的代码中缺少一些位,例如 > .这是工作示例:

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

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

接下来,提供额外的模板参数 shared_ptr<Example>在你包裹的地方 Example类:

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<Example>会妥善处理。

关于python - 无法从 pybind11 中的静态函数返回 shared_ptr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56017998/

相关文章:

php - 坚持使用 PHP 还是学习 Go-lang?

c++ - 将 QPair 的 QList 写入 QSettings 对象

python - 将 std::vector 作为 numpy 数组返回给 python

c++ - 可以将连续放置在内存中的变量视为数组的一部分吗?

python - Pytest mocker.patch 返回 NonCallableMagicMock

python - 找不到lpython2.7

c++ - 问号运算符的多个语句

c++ - 我只是在查看模板并在我的书中找到了这段代码,这显示了段错误?

python - C++ 嵌入式解释器和对象

python - 在 Python 中从字符串中提取数字