指向外部托管(例如:Python)资源的C++智能指针?

2024-09-17 19:54:45 发布

您现在位置:Python中文网/ 问答频道 /正文

< C++中有智能指针到其他人管理的资源吗?我使用PybDun11来包装C++代码,如下所示。

    class B {};
    class A {
      public:
        // original C++ class interface
        A(std::shared_ptr<B> pb) : mb(pb){}
        // have to add this for pybind11, since pybind11 doesn't take shared_ptr as argument.
        A(B * pb):A(std::shared_ptr<B>(pb)){}
      private:
        std::shared_ptr<B> mb;
    }
    namespace py = pybind11;
    PYBIND11_MODULE(test, m)
    {
       py::class_<B>(m, "B")
       .def(py::init<>());

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

然后在python中,我将按如下方式使用它们:

^{pr2}$

这是很好的,只要我不删除.a,当我在Python中删除A时,在C++的“A”中创建的SyrdYPPTMB将尝试销毁由Python和Burn管理的B对象。所以,我的问题是,C++中是否有一些智能指针不能获取原始指针的所有权?弱的\u ptr不起作用,因为我仍然需要创建一个共享的\u ptr。


Tags: 代码pyinit智能defmb资源class
1条回答
网友
1楼 · 发布于 2024-09-17 19:54:45
class_模板中执行此操作。例如

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

相关问题 更多 >