如何通过pybind传递numpy数组的列表

zujrkrfu  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(93)

我有一个用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)

main.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?

nafvub8i

nafvub8i1#

简单地转换为数组: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)

相关问题