How can I return a Numpy array using PyBind11 without requiring Python cast?

Viewed 34

I have a C++ class which is interchangeable with Numpy arrays through the buffer protocol, and already I can return objects from C++ to Python which are convertible to Numpy via the numpy.asarray() call.

I would like to make my class even easier to use, so I would like to return Numpy arrays which wrap my class directly from C++.

Is it possible to construct a numpy array from the C++ side using PyBind11 and return it?

1 Answers

I found out how to do this, you can just call the numpy "asarray" function directly on my buffer type.

py::buffer pybuf_to_numpy(py::buffer& b)
{
    py::object np = py::module::import("numpy");
    py::object asarray = np.attr("asarray");
    return asarray(b);
}
Related