我正在通过pybind 11从c ++调用python函数。python函数返回一个numpy数组,我想分析c ++中numpy数组中的数据
//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>>();
}
此处的代码有误:
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'
答案 0 :(得分:1)
对 mutable_data() 的调用有效
py::array_t<int>rdata= hdf5.attr("load_next_chunk")(0, 1);
int *carray = rdata.mutable_data();
内容应该存在于carray中。我不是 pybind 专家,但此解决方案由 pybind github forum
提供