如何使用pybind传递numpy数组列表
Howto pass a list of numpy array with pybind
我有一个用python编写的预处理器。此预处理器计算未知数量的 numpy 数组。它们存储在列表中。为了进一步计算,我需要阅读 cpp 中的这些 numpy 数组列表。我不知道如何将列表中的元素转换为数组类型。
main.py
import numpy as np
import myCPPAlgo
my_list = [ np.zeroes(shape=(10, 10), dtype=np.uint32) for _ in range(10)]
myCPPAlgo.call(my_list)
主.cpp
#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)
相关文章:
- C++如何生成std::数组列表
- GTEST : 如何将数组列表作为参数传递到 ValuesIn of INSTANTIATE_TEST_CASE_P?
- 如何通过 cython 将 numpy 数组列表传递给 C++
- 如何删除数组列表中的元素
- 如何将移动平均线写入数组列表类?
- 如何使用pybind传递numpy数组列表
- 继承向量/数组/列表并更改其大小
- 内存泄漏 C++ 数组列表
- 如何使用一维数组列表初始化二维数组
- 从数组列表中的字符串迭代器获取 int dat<struct>
- 数组列表、行搜索和气泡排序.作业C++
- 是否可以使用三元运算符"?"在 C/C++ 中填充数组列表?
- 从我的c++应用程序调用c#dll(解析XML文件),将数组/列表返回给c++
- (C++)用于检查对象是否在向量/数组/列表/.中的模板
- C#中数组/列表的子集迭代器,没有屈服
- 链接数组列表实现
- 如何将多个位图包含在全局数组列表中
- C++:如何将数组的元素推送到数组列表中
- 视觉 我正在使用C++用于一些基本图形。我想知道如何读取顶点、索引和面以及如何在数组列表中使用面?
- C++ 将文件读入数组/列表/向量