我正在尝试使用 pybind11
将 data_all
暴露给 python,它是 data
的 vector :
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>
我相信 Python 不喜欢 Eigen
返回类型。有人可以帮我解决这个问题吗?我应该如何帮助 Python 理解 getValues
的返回类型,以便我可以使用 numpy
库进一步处理它?</p>
最佳答案
我认为这一行:
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"
位于包装器代码的顶部。
关于python - Pybind11 特征返回类型问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59939278/