首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >PyBind11:返回对std::std::unique_ptr向量的const引用

PyBind11:返回对std::std::unique_ptr向量的const引用
EN

Stack Overflow用户
提问于 2020-05-19 16:39:12
回答 1查看 1.3K关注 0票数 0

我正在尝试将C++库中唯一ptrs向量的const引用返回到python接口。我正在尝试类似于下面的代码,但是当我试图调用py::bind_vector<std::vector<std::unique_ptr<A>>>时,我会得到编译错误

代码语言:javascript
复制
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <pybind11/stl_bind.h>

class A
{
  public:
    A( int x ){ i = x; }
    A(const A&) = delete;
    A& operator=(const A&) = delete;
    int getI() { return i; }

  private:
    int i;
};

class Test
{
  public:
    Test(){
      for(int i = 0; i < 10; ++i) {
        avec_.emplace_back( std::make_unique<A>(i));
      }
    }
    Test( const Test& ) = delete;
    Test& operator=(const Test& ) = delete;

    const std::vector<std::unique_ptr<A>>& getVec() const { return avec_; }

  private:
    std::vector<std::unique_ptr<A>> avec_;
};

PYBIND11_MODULE(UniqContainer, m) {

  py::bind_vector<std::vector<std::unique_ptr<A>>>(m, "VecA", py::module_local() );

  py::class_<A>(m, "A")
    .def( py::init<int>() )
    .def( "getI", &A::getI );

  py::class_<Test>(m, "Test" )
    .def( py::init<>() )
    .def( "getVec", &Test::getVec, py::return_value_policy::reference_internal );
}

我的问题是--在python绑定中返回对std::vector<std::unique_ptr<A>>的const引用是可能的吗?

编辑:添加:

delete

  • py::return_value_policy::reference_internal

  • 复制器和赋值运算符
EN

回答 1

Stack Overflow用户

发布于 2020-06-01 21:40:04

所以这是我能想到的最好的了。如果将句柄保存到python中的A实例,然后在c++中删除它们,则可能存在生命周期问题。您不能在我正在使用的上下文中使用reference_internal,因为它不知道所引用的生命周期。您可能还可以显式地将py::keep_alive添加到函数def中,以便将内容保持在范围内。我不知道你的终身需求是什么,我对API的那个部分还有点模糊。

代码语言:javascript
复制
  py::class_<Test>(m, "Test" )
    .def( py::init<>() )
    .def( "getVec",
          [](const Test& obj) {
            auto pylist = py::list();
            for (auto& ptr : obj.getVec()) {
              auto pyobj = py::cast(*ptr, py::return_value_policy::reference);
              pylist.append(pyobj);
            }
            return pylist;
          });
}

基本上,必须手动创建py::list,然后通过引用将其中的智能指针转换为py::object来填充列表。

(注意,我还删除了py::bind_vector,以使所有内容都能编译)

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61896281

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档