我有下面的示例代码,它获得一个py::list
作为计算某些python代码的输出。
我想把它转换成一个std::vector<std::string>
,但是我得到了一个错误:
从‘pybind11 11::list’到非标量类型'std::vector的转换请求
根据文档
当包含附加的头文件
pybind11/stl.h
时,将自动启用pybind11/stl.h
std::set<>
/std::unordered_set<>
、std::map<>
/std::unordered_map<>
和Pythonlist
、set
和dict
数据结构之间的转换。
正如您可以从下面的代码示例中看到的那样,我已经包含了stl.h
,但是自动转换不起作用。
#include <iostream>
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <pybind11/eval.h>
namespace py = pybind11;
py::list func()
{
py::object scope = py::module_::import("__main__").attr("__dict__");
return py::eval("[ 'foo', 'bar', 'baz' ]", scope);
}
int main()
{
Py_Initialize();
// call the function and iterate over the returned list of strings
py::list list = func();
for (auto it : list)
std::cout << py::str(it) << '\n';
// error
// conversion from 'pybind11::list' to non-scalar type 'std::vector<std::__cxx11::basic_string<char> >' requested
std::vector<std::string> vec = list;
for (auto str : vec)
std::cout << str << '\n';
return 0;
}
我可以手动遍历py::list
并使用每个元素调用vector::push_back
// populating the vector manually myself works
std::vector<std::string> vec;
vec.reserve(list.size());
for (auto it : list)
vec.push_back(py::str(it));
因此,我想上面的链接文档只引用了c++ -> python转换,而不是其他方式?
从py::list
转换到std::vector
的推荐方法是什么?
发布于 2022-10-11 09:43:01
你需要打电话给.cast<>
auto vec = list.cast<std::vector<std::string>>();
<pybind11/stl.h>
只是对允许这种转换的转换模板进行了专门化,并且在将函数绑定到向量参数或返回向量(或其他标准容器)时也允许隐式转换。
https://stackoverflow.com/questions/74025986
复制相似问题