根据 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-types和 binding-stl-containers .
关于pybind11,将 std::vector 转换为 py::list,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53724225/