简体   繁体   English

Pybind11 如何从 python -> c++ 传递 n 维 numpy 数组

[英]Pybind11 How to pass an n-dimentional numpy array from python -> c++

I have a numpy array of numpy arrays of floats that I wish to pass to a c++ function that will read and modify the data as if it were a std::vector.我有一个由 numpy 浮点数组成的 numpy 数组,我希望将其传递给 C++ 函数,该函数将读取和修改数据,就好像它是 std::vector 一样。 I am struggling to figure out how to do this.我正在努力弄清楚如何做到这一点。 What would the c++ argument type be for: c++ 参数类型的用途是什么:

np.array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]], dtype=float)

This type declaration: py::array_t<py::array_t<float>>这种类型声明: py::array_t<py::array_t<float>>

produces this error: Attempt to use a non-POD or unimplemented POD type as a numpy dtype产生此错误: Attempt to use a non-POD or unimplemented POD type as a numpy dtype

and I can't see to get this type declaration to work: py:array我看不到让这个类型声明起作用: py:array

I have searched through documentation, github issues and examples I can find online but have not found anything that works or that I can make sense of, if anyone could help me with this, it would be much appreciated :)我已经搜索了文档、github 问题和我可以在网上找到的示例,但没有找到任何有效或我可以理解的内容,如果有人可以帮助我,我将不胜感激:)

Pull in the Eigen library on the C++ side and use that for your matrix operations.在 C++ 端引入 Eigen 库并将其用于矩阵运算。 std::vector is not a good abstraction for 2d matrices... either you have to write your own 2d indexing into a 1d vector, or you need something silly like std::vector<std::vector<>> , which performs very badly and is ugly besides. std::vector对于二维矩阵来说不是一个好的抽象......要么你必须将自己的二维索引写入一维向量,要么你需要像std::vector<std::vector<>>那样愚蠢的东西,它执行非常糟糕,而且还很丑。

pybind11 knows the type conversions to automatically convert np.array to Eigen::MatrixXf , so you should be able to write your C++ function as taking a Eigen::MatrixXf &input , and call it as you've specified. pybind11知道自动将np.array转换为Eigen::MatrixXf的类型转换,因此您应该能够将 C++ 函数编写为采用Eigen::MatrixXf &input ,并按照您指定的方式调用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM