我试图绑定(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/