Skip to content

[QUESTION] How do I stop pybind11 from automatically deallocating an object created on the python side? #2726

@dograt

Description

@dograt

Copying my question from here.

So, I know that pybind lets you set a return value policy for methods that you wrap up. However, that doesn't seem to be working for me when I try to use this policy on a constructor. I have a class to wrap my C++ type that looks like this:

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)
        ;
}

However, this does NOT stop my Component type from getting deallocated from the Python side if I call Component() and the created object goes out of scope. Any suggestions?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions