pybind11,将 std::vector 转换为 py::list

标签 pybind11

根据 pybind11 文档 https://pybind11.readthedocs.io/en/stable/advanced/cast/stl.html :

When including the additional header file pybind11/stl.h, conversions between std::vector<>/std::list<>/std::array<>, std::set<>/std::unordered_set<>, and std::map<>/std::unordered_map<> and the Python list, set and dict data structures are automatically enabled.



但是,我一辈子都无法让它发挥作用。我想我误解了一些东西,所以我希望有人能为我澄清一下。

这是我期望的工作:

// Test
std::vector<double> test_vec{1,2,3,4,5};
py::list test_list = test_vec;
py::list test_list2(test_vec);
py::list test_list3 = py::cast<py::list>(test_vec);

以下是错误:

error: conversion from ‘std::vector<double>’ to non-scalar type ‘pybind11::list’ requested
    py::list test_list = test_vec;
error: no matching function for call to ‘pybind11::list::list(std::vector<double>&)’
    py::list test_list2(test_vec);
error: no matching function for call to ‘cast(std::vector<double>&)’
    py::list test_list3 = py::cast<py::list>(test_vec)

文档说要查看 tests/test_stl.cpp有关这应该如何工作的示例,但是恐怕我在破译该文件中发生的事情时遇到了麻烦。

最佳答案

如果包含 pybind11/stl.h,则为您创建绑定(bind)的函数参数和返回值自动进行转换。 .您也可以在 C++ 代码中显式执行此操作,如下所示:

#include <pybind11/stl.h>
// [...]
std::vector<double> test_vec{1, 2, 3, 4, 5};
py::list test_list3 = py::cast(test_vec);

但是请记住,这会创建一个副本。
如需不同的方法,请参阅 making-opaque-typesbinding-stl-containers .

关于pybind11,将 std::vector 转换为 py::list,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53724225/

相关文章:

python - 将元素从一个出队移动到另一个时,C++ 使用两倍的内存

python - pybind11 将 python sys.stdout 从 print() 重定向到 C++

python - pybind11 运行测试用例

python - Pybind11 函数调用阻塞主线程

python - 导入错误 : DLL load failed with pybind11 and PCL

CMake 和 pybind11 使用不一致的 Python 版本

Pybind11 和全局 C 变量

python - 通过 pybind11 返回 numpy 数组

cmake - 通过ExternalProject_Add 使用 pybind11 进行 CMake 项目的智能方法

python - pybind11 中的命名默认参数