Search code examples
pythonc++arraysnumpypybind11

How to pass 2d numpy array to C++ pybind11?


In C++ pybind11 wrapper:

.def("calcSomething", 
[](py::array_t<double> const & arr1,
   py::array_t<double> const & arr2)
{
  // do calculation
}
)

In python:

example.calcSomething(
   arr1=np.full((10, 2), 20, dtype='float64'),
   arr2=np.full((10, 2), 100, dtype='float64')
)

And I got this error message:

ValueError: array has incorrect number of dimensions: 2; expected 1

So how should I pass 2d or nd array to pybind11?


Solution

  • In pybind11 array_t is an n-dimensional array, just like a numpy array.

    So there are no restrictions on dimensionality.

    The error message is probably coming from somewhere else. Not from pybind11.

    At least the code you show should not cause this behavior.