首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >pybind11:将py::list转换为std::vector<std::string>

pybind11:将py::list转换为std::vector<std::string>
EN

Stack Overflow用户
提问于 2022-10-11 09:36:47
回答 1查看 81关注 0票数 0

我有下面的示例代码,它获得一个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<>和Pythonlistsetdict数据结构之间的转换。

正如您可以从下面的代码示例中看到的那样,我已经包含了stl.h,但是自动转换不起作用。

代码语言:javascript
运行
复制
#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

代码语言:javascript
运行
复制
// 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的推荐方法是什么?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-10-11 09:43:01

你需要打电话给.cast<>

代码语言:javascript
运行
复制
auto vec = list.cast<std::vector<std::string>>();

<pybind11/stl.h>只是对允许这种转换的转换模板进行了专门化,并且在将函数绑定到向量参数或返回向量(或其他标准容器)时也允许隐式转换。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74025986

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档