Quasar
Quasar

Reputation: 295

Pybind11: Passing a Python list to C-style array

I would like to pass a Python list to a constructor which takes C-style arrays. How should that work. The problem is that the C-style array is essentially a pointer. Furthermore, the array has dimension n x n, i.e. it is a multi-dimensional array.

     PYBIND11_MODULE(matrix_class_bind, m){
         py::class_<matrix_class<double>>(m, "matrix_class")
         .def(py::init([](double x[3][3]){
          matrix_class<double> new_class(x);
          return new_class;}));
    }

On the python side it should be something like:

import matrix_class_bind as mcb    
a = [[1,2,3], [3,4,5], [1,1,1]]
mcb.matrix_class(a)

Upvotes: 1

Views: 4075

Answers (1)

jackw11111
jackw11111

Reputation: 1547

Instead of passing the matrix as a pointer, you could pass it using py::list, if your aim is to access the matrix as a C array.

class matrix_class {
    public:
        static const int n = 3;
        int carray[n][n];
        py::list list;
        matrix_class(const py::list &list) : list(list) {
            for (int i = 0; i < n; i++) {
                py::list l = list[i].cast<py::list>();
                for (int j = 0; j < n; j++){
                    int p = l[j].cast<int>();
                    carray[i][j] = p;
                }
            }
    }
}

PYBIND11_MODULE(matrix_class_bind, m) {
    py::class_<matrix_class>(m, "matrix_class")
        .def(py::init<const py::list &>());
}

Upvotes: 1

Related Questions