1

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)
2
  • Check out xtensor-python. You'd need to write an interface function that takes an xt::pyarray<double> reference and pass to your C-style function by taking the address of the first element similar to a vector/STL array. Commented Mar 15, 2018 at 14:11
  • Did you have a look at the documentation about custom contructors? pybind11.readthedocs.io/en/stable/advanced/…. This would allow you to write a wrapper that converts e.g. list to raw array. Commented Mar 15, 2018 at 14:22

1 Answer 1

1

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 &>());
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.