Pybind11: How to set std::vector<std::vector<int>> in pybind.

Created on 8 Sep 2017  路  1Comment  路  Source: pybind/pybind11

If a class has a data member in type of std::vector<std::vector<int>> and the set function in this class. For example:

class A {
  void set(std::vector<std::vecotr<int>> x) {
    x_ = x;
  }
 private:
   std::vector<std::vecotr<int>> x_;
}

How to expose this set function in pybind?

Most helpful comment

You can ask short questions on Gitter and probably will get quicker responses.

You'll want to use #include <pybind11/stl.h>:

#include <pybind11/pybind11.h>
#include <vector>
#include <pybind11/stl.h>

namespace py = pybind11;

// Shorter for readability
using vvi = std::vector<std::vector<int>>;

class A {
    vvi x_;
public:
    void set(vvi x) {x_ = x;}
    vvi get() const {return x_;}
};

PYBIND11_MODULE(example, m) {
    py::class_<A>(m, "A")
        .def(py::init<>())
        .def("set", &A::set)
        .def("get", &A::get)
        // Alternative for property access in Python
        .def_property("x", &A::get, &A::set);
        // Also def_property_readonly
        // Also can use def_readonly and def_readwrite on public properties
}

Compile it (added a symbolic link to my pybind directory):

cmake_minimum_required(VERSION 3.9)
project(vecvecint LANGUAGES CXX)
add_subdirectory(pybind11)
pybind11_add_module(example example.cpp)

Then use it:

>>> import example
>>> a = example.A()
>>> a.set([[1,2],[3,4]])
>>> a.get()
[[1, 2], [3, 4]]
>>> a.x
[[1, 2], [3, 4]]

>All comments

You can ask short questions on Gitter and probably will get quicker responses.

You'll want to use #include <pybind11/stl.h>:

#include <pybind11/pybind11.h>
#include <vector>
#include <pybind11/stl.h>

namespace py = pybind11;

// Shorter for readability
using vvi = std::vector<std::vector<int>>;

class A {
    vvi x_;
public:
    void set(vvi x) {x_ = x;}
    vvi get() const {return x_;}
};

PYBIND11_MODULE(example, m) {
    py::class_<A>(m, "A")
        .def(py::init<>())
        .def("set", &A::set)
        .def("get", &A::get)
        // Alternative for property access in Python
        .def_property("x", &A::get, &A::set);
        // Also def_property_readonly
        // Also can use def_readonly and def_readwrite on public properties
}

Compile it (added a symbolic link to my pybind directory):

cmake_minimum_required(VERSION 3.9)
project(vecvecint LANGUAGES CXX)
add_subdirectory(pybind11)
pybind11_add_module(example example.cpp)

Then use it:

>>> import example
>>> a = example.A()
>>> a.set([[1,2],[3,4]])
>>> a.get()
[[1, 2], [3, 4]]
>>> a.x
[[1, 2], [3, 4]]
Was this page helpful?
0 / 5 - 0 ratings