Eigen Return 类型的 Pybind11 问题

Pybind11 Issue for Eigen Return Type

我正在尝试使用 pybind11:

data_all 公开为 data 到 python 的向量
struct data {
    std::vector<Eigen::ArrayXf> values;
    std::vector<int> indices;
    float x;
    float y;
    float z;
};

class dataBuffer {
public:
    std::vector<data> data_all;
    Eigen::ArrayXf getValues(ssize_t i, ssize_t j) { return data_all.at(i).values.at(j); };
};

我将我的 pybind11 包装器定义如下:

PYBIND11_MODULE(example, m) {
    py::class_<data>(m, "data")
        .def(py::init<>())
        .def_readonly("values", &data::values)
        .def_readonly("indices", &data::indices)
        .def_readonly("x", &data::x)
        .def_readonly("y", &data::y)
        .def_readonly("z", &data::z);

    py::class_<dataBuffer>(m, "dataBuffer")
        .def(py::init<>())
        .def("getValues", &dataBuffer::getValues);
}

我的 C++ 示例代码是

namespace py = pybind11;
int main()
{
    data d;
    d.x = 1.1;
    d.y = 2.1;
    d.z = 3.1;
    d.indices.push_back(4);
    d.values.push_back(Eigen::ArrayXf::LinSpaced(50, 0.0, 50 - 1.0));
    d.indices.push_back(5);
    d.values.push_back(Eigen::ArrayXf::LinSpaced(60, 0.0, 60 - 1.0));
    d.indices.push_back(11);
    d.values.push_back(Eigen::ArrayXf::LinSpaced(70, 0.0, 70 - 1.0));

    dataBuffer D;
    D.data_all.push_back(d);
    D.data_all.push_back(d);
    std::cout << D.getValues(0,0) << "\n";

    py::scoped_interpreter guard{};
    py::object result = py::module::import("pybind11_test").attr("testData")(0,0);

}

文件内容pybind11_test.py

import numpy as np
import example as m
def testData(buffer):
    help(buffer)
    a = buffer.getValues(0,0) # trying to retrieve the data buffer created in C++
    print(a)

help(buffer) 打印以下签名:

Help on method getValues in module example:

getValues(...) method of example.dataBuffer instance
    getValues(self: example.dataBuffer, arg0: int, arg1: int) -> Eigen::Array<float,-1,1,0,-1,1>

然而,当 python 到达执行 buffer.getValues(0,0) 时它失败了:

(in Visual Studio)
pybind11::error already set at memory location

(in Python)
Traceback (most recent call last):    
  File "<stdin>", line 1, in <module>
TypeError: getValues(): incompatible function arguments. The following argument types are supported:
    1. (self: example.dataBuffer, arg0: int, arg1: int) -> Eigen::Array<float,-1,1,0,-1,1>

我相信 Eigen return 类型不被 Python 欣赏。有人可以帮我解决问题吗?我应该如何帮助 Python 理解 getValues 的 return 类型,以便我可以使用 numpy 库进一步处理它?

我假设这一行:

py::object result = py::module::import("pybind11_test").attr("testData")(0,0);

本来是:

py::object result = py::module::import("pybind11_test").attr("testData")(D);

除此之外,你还缺的是:

#include "pybind11/eigen.h"

在包装代码的顶部。