首页 > 解决方案 > PyBind11:返回 c++ 数组作为 numpy 数组更改值

问题描述

我正在使用 pybind11 从 python 调用 c++ 函数,它必须将多维数组作为 numpy 数组返回。数组是整数数组[100][100][3]。

我在 py::array_t 构造函数中使用指向数组的指针,并且能够在 python 中成功返回一个 numpy 数组。但是由于某种原因,python 中的值正在更改。

return py::array_t<int>( {100, 100, 3}, // shape
                         {100*3*4, 3*4, 4}, // C-style contiguous strides
                         pointer // the data pointer
                        );

另外,我尝试创建一个单维数组 [100 x 100 x 3] 并使用:

return py::array_t<int>( {100*100*3}, // shape
                         {4}, // C-style contiguous strides
                         pointer // the data pointer
                        );

在 python 中将数组作为 numpy 数组后,我尝试使用 array.reshape((100,100,3)) 以及此处提到的 .view() 方法将形状更改为我的需要: https ://numpy.org/ doc/stable/reference/generated/numpy.reshape.html。但没有运气。

有人可以告诉我如何解决这个问题吗?如果可能的话,我会尽量避免任何复制。

标签: pythonc++arraysnumpypybind11

解决方案


推荐阅读