簡體   English   中英

如何使用 pybind11 將堆分配指針的“std::vector”傳遞給 python?

[英]How to pass a `std::vector` of heap allocated pointers to python using pybind11?

Say I am now having a bunch of pointers foo* and I would like to pass them to python using std::vector in a c++ function get_foos , but I want to manage the life time of those heap allocated pointers in the vector within c++,即,當 c++ 向量foos超出 Z23EEEB4347BDD26BDDFC6B7 中的 scope 時,python 應該只釋放向量而不是那些指針。

return_value_policy::reference似乎還不夠,因為它也不會破壞向量,如果我錯了,請糾正我。

struct foo {};

py::class_<foo>(m, "Foo");

auto get_foos() -> std::vector<foo*> {
  auto foos = std::vector<foo*> {};

  for(...) {
    auto p = get_foo_ptr(...);
    foos.emplace_back(p);
  }
  return foos;
}

有一個助手 header 你必須包括<pybind11/stl.h>

這是一個例子:


struct Foo {
    Foo(const char *name) : m_name(name) {}
    ~Foo() {}

    const char *get_name() const { return m_name.c_str(); }

private:
    string m_name;
};

vector<unique_ptr<Foo>> make_foos() {
    vector<unique_ptr<Foo>> foos;
    foos.push_back(make_unique<Foo>("Hello"));
    foos.push_back(make_unique<Foo>("World"));
    return foos;
}

vector<Foo *> get_foos() {
    static vector<unique_ptr<Foo>> all_foos = make_foos();

    vector<Foo *> foos;
    for (unique_ptr<Foo> &foo : all_foos) {
        foos.push_back(foo.get());
    }
    return foos;
}


PYBIND11_MODULE(example, m) {
    py::class_<Foo>(m, "Foo")
            .def("get_name", &Foo::get_name);

    m.def("get_foos", get_foos, py::return_value_policy::reference);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM