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

unable to return shared_ptr from static function in pybind11

本文关键字:返回 shared ptr 静态函数 pybind11      更新时间:2023-10-16

我试图绑定一个静态函数,该函数返回指向另一个类的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);
}

这是蟒蛇的一面

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>将得到妥善处理。