Skip to content Skip to sidebar Skip to footer

C++ Smart Pointer To External Managed (e.g: Python) Resources?

Is there a smart pointer in C++ to a resource managed by others? I am using pybind11 to wrap C++ code as followed. class B {}; class A { public: // original

Solution 1:

Pybind11 is using a unique pointer behind the scenes to manage the C++ object as it thinks it owns the object, and should deallocate the object whenever the Python wrapper object is deallocated. However, you are sharing this pointer with other parts of the C++ code base. As such, you need to make the Python wrapper of the B class to manage the instance of B using a shared pointer. You can do this in the with class_ template. eg.

PYBIND11_MODULE(test, m)
{
   py::class_<B, std::shared_ptr<B> >(m, "B")
   .def(py::init<>());

   py::class_<A>(m, "A")
   .def(py::init<std::shared_ptr<B> >());
}

https://pybind11.readthedocs.io/en/stable/advanced/smart_ptrs.html#std-shared-ptr


Post a Comment for "C++ Smart Pointer To External Managed (e.g: Python) Resources?"