我可以使用 pybind11 将 numpy 数组传递给接受 Eigen::Tensor 的函数吗?

fab*_*ian 5 c++ python eigen pybind11

我可以pybind1用来将三维 numpy 数组传递给接受Eigen::Tensoras 参数的 c++ 函数吗?例如,考虑以下 c++ 函数:

Eigen::Tensor<double, 3> addition_tensor(Eigen::Tensor<double, 3> a,
                                         Eigen::Tensor<double, 3> b) {
    return a + b;
}
Run Code Online (Sandbox Code Playgroud)

编译函数后,将其导入 python 并将 numpy 数组传递np.ones((1, 2, 2))给它,我收到以下错误消息:

TypeError: addition_tensor(): incompatible function arguments. The following argument types are supported:
    1. (arg0: Eigen::Tensor<double, 3, 0, long>, arg1: Eigen::Tensor<double, 3, 0, long>) -> Eigen::Tensor<double, 3, 0, long>
Run Code Online (Sandbox Code Playgroud)

我特别惊讶的是不能传递一个三维 numpy 数组,因为我可以将一个二维传递numpy array给一个接受 an 的函数Eigen::MatrixXd,如:

TypeError: addition_tensor(): incompatible function arguments. The following argument types are supported:
    1. (arg0: Eigen::Tensor<double, 3, 0, long>, arg1: Eigen::Tensor<double, 3, 0, long>) -> Eigen::Tensor<double, 3, 0, long>
Run Code Online (Sandbox Code Playgroud)

我在这个例子中使用的整个代码是:

Eigen::MatrixXd addition(Eigen::MatrixXd a, Eigen::MatrixXd b) { return a + b; }
Run Code Online (Sandbox Code Playgroud)

我用g++ -shared -fPIC `python3 -m pybind11 --includes` example.cpp -o example`python3-config --extension-suffix`. 有人知道如何将三维numpy数组转换为接受三维的函数Eigen::Tensor吗?

Joh*_*nck 5

它不直接支持,这里有一些讨论(如果您想将其添加到项目中,包括一些用于进行映射的代码):https ://github.com/pybind/pybind11/issues/1377