简体   繁体   中英

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++, ie, python should only free vector but not those pointers when the c++ vector foos goes out of scope in python.

return_value_policy::reference seems not sufficient as it will also not destruct the vector, please correct me if I am wrong.

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

There is a helper header that you have to include <pybind11/stl.h> .

And here is an example:


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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM