我有以下示例代碼,它獲得 apy::list作為評估某些 python 代碼的輸出。
我想將其轉換為 a std::vector<std::string>,但出現錯誤:
conversion from 'pybind11::list' to non-scalar type 'std::vector<std::__cxx11::basic_string<char> >' requested
根據檔案:
當包含附加頭檔案
pybind11/stl.h時,std::vector<>/std::deque<>/std::list<>/std::array<>/std::valarray<>、std::set<>/std::unordered_set<>和std::map<>/與std::unordered_map<>Pythonlist和資料結構之間的轉換將自動啟用。setdict
從下面的代碼示例中可以看到,我已經包含了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從to轉換的推薦方法是std::vector什么?
uj5u.com熱心網友回復:
您需要致電.cast<>:
auto vec = list.cast<std::vector<std::string>>();
<pybind11/stl.h>簡單地帶來允許這種轉換的轉換模板的特殊化,并且當您將函式與向量引數或回傳向量(或其他標準容器)系結時也允許隱式轉換。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/513864.html
上一篇:std::ostringstream::str()輸出帶有'\0'的字串
下一篇:不同型別名的模板引數推導
