gpt4 book ai didi

python - C++ 2D vector 到 2D pybind11 数组

转载 作者:行者123 更新时间:2023-12-03 07:23:27 26 4
gpt4 key购买 nike

我对 C++ 相当陌生,并且在 pybind 中挣扎。我只是不知道如何说服 pybind 将 2D vector 从 C++ 转换为 python 可读格式。

这就是我想到的代码:

py::array_t<float> to_matrix(std::vector<std::vector<float>> &vals)
{
int N = vals.size();
int M = 6;
py::array_t<float>({N, M}) arr;
for (int i = 0; (i < N); i++)
{
for (int j = 0; (j < M); j++)
{
arr[i][j] = vals[i][j];
};
};
return arr;
};

C++ 的输入是一个有 N 行 6 列的 vector ,只是一个很长的数据点列表。理想情况下,我希望将输出作为 numpy 数组,但任何 python 数据结构都可以(例如,列表列表)。

文档使它听起来很简单,但我无法弄清楚。我究竟做错了什么?

提前感谢您的任何帮助。

最佳答案

这里发生了一些事情,但让我们从一个最小的例子开始。以下函数将从硬编码 std::vector<std::vector<float>> 创建一个二维数组

py::array_t<float> to_matrix()
{
std::vector<std::vector<float>> vals = {
{1, 2, 3, 4, 5},
{6, 7, 8, 9, 10},
{11, 12, 13, 14, 15}
};

size_t N = vals.size();
size_t M = vals[0].size();

py::array_t<float, py::array::c_style> arr({N, M});

auto ra = arr.mutable_unchecked();

for (size_t i = 0; i < N; i++)
{
for (size_t j = 0; j < M; j++)
{
ra(i, j) = vals[i][j];
};
};

return arr;
};

PYBIND11_MODULE(foo, m)
{
m.def("to_matrix", &to_matrix);
}

有两点需要注意,首先数组形状是数组的构造函数参数。二是使用 mutable_unchecked获取可用于进行分配的代理对象。

在您的情况下, vector 的 vector 将来自您的 C++ 代码中的其他地方。

但请注意,pybind11 还提供了用于包装容器的样板,例如 std::vector .这些在标题 pybind11/stl_bind.h 中可用,并允许您执行此操作

std::vector<std::vector<float>> make_vector()
{
std::vector<std::vector<float>> vals = {
{1, 2, 3, 4, 5},
{6, 7, 8, 9, 10},
{11, 12, 13, 14, 15}
};

return vals;

}

PYBIND11_MODULE(foo, m)
{
py::bind_vector<std::vector<std::vector<float>>>(m, "FloatVector2D");
m.def("make_vector", &make_vector);
}

虽然这样的对象不会完全等同于 numpy 数组(没有 shape 属性等)

关于python - C++ 2D vector 到 2D pybind11 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61920449/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com