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

Ben*_*mer 7 pybind11

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

当包含额外的头文件 pybind11/stl.h 时,std::vector<>/std::list<>/std::array<>、std::set<>/std::unordered_set<> 和 std::set<>/std::unordered_set<> 之间的转换自动启用 std::map<>/std::unordered_map<> 和 Python 列表、集合和字典数据结构。

但是,我终其一生都无法让它发挥作用。我想我误解了一些东西,所以我希望有人可以为我澄清。

这是我期望的工作:

// 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);
Run Code Online (Sandbox Code Playgroud)

以下是错误:

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)
Run Code Online (Sandbox Code Playgroud)

文档说要查看tests/test_stl.cpp这应该如何工作的示例,但是我担心我无法破译该文件中发生的事情。

aha*_*ans 8

如果包含pybind11/stl.h. 您也可以在 C++ 代码中显式执行此操作,如下所示:

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

不过请记住,这会创建一个副本。
对于不同的方法,请参阅Making- opaque-typesbinding-stl-containers