首页 > 解决方案 > 如何阻止 pybind11 释放由 Python 构造的对象?

问题描述

所以,我知道 pybind 可以让你为你封装的方法设置一个返回值策略。但是,当我尝试在构造函数上使用此策略时,这似乎对我不起作用。我有一个类来包装我的 C++ 类型,如下所示:

class PyComponent{
public:


    static Component* Create(ComponentType type) {
        Component* c = new Component(type);
        // Irrelevant stuff removed here
        return c;
    }

    /// @brief Wrap a behavior for Python
    static void PyInitialize(py::module_& m);

};
void PyComponent::PyInitialize(py::module_ & m)
{
    py::class_<Component>(m, "Component")
        .def(py::init<>(&PyComponent::Create), py::return_value_policy::reference)
        ;
}

Component()但是,如果我调用并且创建的对象超出范围,这不会阻止我的 Component 类型从 Python 端释放。有什么建议么?

标签: pythonc++pybind11

解决方案


我确实想出了解决方案。这是传递py::nodelete给我的班级的包装器

void PyComponent::PyInitialize(py::module_ & m)
{
    py::class_<Component, std::unique_ptr<Component, py::nodelete>>(m, "Component")
        .def(py::init<>(&PyComponent::Create), py::return_value_policy::reference)
        ;
}

推荐阅读