How to access data when calling python function from c++ which return numpy array

Viewed 260

I'm calling the python function from c++ by pybind 11. the python function return a numpy array, I want to analyze the data in numpy array in c++

//the code for testing
#include <pybind11/embed.h> // everything needed for embedding
#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>

int main()
{

py::scoped_interpreter guard{};

py::print("test python interpreter");
auto sys = py::module::import("sys");
sys.attr("path").attr("append")(
"<path for python module>");

auto hdf5 = py::module::import("reader_hdf5");

auto rdata = hdf5.attr("load_next_chunk")(0, 1);

// how to access the data from the return value ?

 py::array_t<int16_t> array(331776);
 array = rdata.cast<py::array_t<int16_t>>();
}

There is error for the code here:

terminate called after throwing an instance of 'pybind11::error_already_set'
what():  TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType'
1 Answers

A call to mutable_data() works

    py::array_t<int>rdata= hdf5.attr("load_next_chunk")(0, 1);

    int *carray = rdata.mutable_data();

The contents should then exist in carray. I am not a pybind expert, but this solution was provided by pybind github forum

Related