[英]How with pybind11 to bind a function that takes as argument a numpy.array() with, for instance, a shape (10, 10, 3)?
I would like to write a function that can take a multidimensional numpy array, not just 2D. 我想编写一个可以采用多维numpy数组,而不仅仅是2D的函数。
void compute(Eigen::Ref<Eigen::MatrixXd> array3d) {
// change the array in-place
// ...
}
or 要么
Eigen::MatrixXd &compute() {
// create array
// ...
// and return it
}
I am using Eigen here just to depict the goal, I believe Eigen does not support 3D, or more dimensions, arrays. 我在这里使用Eigen只是为了描述目标,我相信Eigen不支持3D或更多维的数组。
I appreciate your feedback and patience since I am not familiar with Pybind11 nor Eigen. 感谢您的反馈和耐心,因为我不熟悉Pybind11或Eigen。
From the pybind information, you can extract the dimension information. 从pybind信息中,您可以提取尺寸信息。
For instance, this is what I do inside Audio ToolKit with m
the current Python module you want to build: 例如,这是我做的内部音频工具包与
m
要构建当前Python模块:
py::class_<MyClass>(m,"name")
.def("set_pointer", [](MyClass& instance, const py::array_t<DataType>& array)
{
gsl::index channels = 1;
gsl::index size = array.shape(0);
if(array.ndim() == 2)
{
channels = array.shape(0);
size = array.shape(1);
}
// Call using array.data() and possibly add more dimension information, this is specific to my use case
instance.set_pointer(array.data(), channels, size);
});
From this, you can create the Eigen::Map
call instead to create an Eigen-like matrix that you can use in your templated code. 由此,您可以创建
Eigen::Map
调用,而不是创建可在模板代码中使用的类似Eigen的矩阵。
Basically, pybind11 allows you to create a lambda where you can create your wrapper for your use case. 基本上,pybind11允许您创建一个lambda,您可以在其中创建用例的包装。 The same works for return, you can get the Eigen class, create a pybind array that you populate with the Eigen data.
同样的返回方法,您可以获取Eigen类,创建一个用Eigen数据填充的pybind数组。
Eigen has the Tensor class that you can use as well. Eigen具有您也可以使用的Tensor类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.