python - 如何使用 pybind 传递 numpy 数组列表
问题描述
我有一个用 python 编写的预处理器。该预处理器计算未知数量的 numpy 数组。它们存储在列表中。为了进一步计算,我需要在 cpp 中阅读这些 numpy 数组列表。我不知道如何将列表的元素转换为数组类型。
主文件
import numpy as np
import myCPPAlgo
my_list = [ np.zeroes(shape=(10, 10), dtype=np.uint32) for _ in range(10)]
myCPPAlgo.call(my_list)
主文件
#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>
#include <pybind11/stl.h>
#include <iostream>
namespace py = pybind11;
int call(py::list listOfNumpyArrays)
{
for( py::handle array: listOfNumpyArrays)
{
// howto transform?
py::array_t<uint32_t> casted_array = ???
auto requestCastedArray = casted_array.request();
uint32_t nRows = requestCastedArray.shape[1];
uint32_t nCols = requestCastedArray.shape[0];
uint32_t* pBlockedArray = (uint32_t*) requestCastedArray.ptr;
}
return 0;
}
PYBIND11_MODULE(myCPPAlgo, m) {
m.doc() = ""
m.def("call", &call, "");
}
如何将 pybind::handle 转换为 py::array_t?
解决方案
只需转换为数组:py::array_t<uint32_t> casted_array = py::cast<py::array>(array);
. 下面的完整工作示例(模错误检查:))。
#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>
#include <pybind11/stl.h>
#include <iostream>
namespace py = pybind11;
int call(py::list listOfNumpyArrays)
{
for( py::handle array: listOfNumpyArrays)
{
// howto transform?
py::array_t<uint32_t> casted_array = py::cast<py::array>(array);
auto requestCastedArray = casted_array.request();
uint32_t nRows = requestCastedArray.shape[1];
uint32_t nCols = requestCastedArray.shape[0];
uint32_t* pBlockedArray = (uint32_t*) requestCastedArray.ptr;
std::cerr << " rows x columns = " << nRows << " x " << nCols << std::endl;
for (int i = 0; i < nCols; ++i) {
for (int j = 0; j < nRows; ++j) {
std::cerr << pBlockedArray[i*nRows + j] << " ";
}
std::cerr << '\n';
}
}
return 0;
}
PYBIND11_MODULE(myCPPAlgo, m) {
m.doc() = "";
m.def("call", &call, "");
}
和测试代码:
import numpy as np
import myCPPAlgo
my_list = [ np.ones(shape=(3, 10), dtype=np.uint32) for _ in range(10)]
my_list[9][1, 0] = 42
myCPPAlgo.call(my_list)
推荐阅读
- php - 如何让我的 Yii2 404 页面显示在实时服务器上
- python-3.x - 如何在保存神经网络的同时解决路径问题
- c# - 从 Office Web 加载项访问 C# 库
- python - 给定各种条件,如何在熊猫数据框中更改日期的年份?
- c - 为什么 C 宏调用会占用大括号?
- python - Django 2.0 查询集显示“对象(1)”不显示值
- oracle-apex - 是否有可能使用我们从 Oracle Apex 中的程序 Refcursor 获得的数据
- performance - 如何以非线性方式在 C++ 中保存矩阵
- html - 它如何设置网格模板列:[outer-start] 1fr [center-start] 1fr [center-end] 1fr [outer-end]?
- sql - SQL Server 中字符串的单引号