【发布时间】:2022-01-19 17:16:53
【问题描述】:
我尝试通过 pybind11 将字典 (unordered_map) 结构从 python 传递到 C++。在 python 方面,我正在尝试做:
v1 = { 1:3.0, 2:4.0}
v2 = { 7:13.0, 8:14.0, 15:22.0}
data={'ab':v1, 'bz':v2}
cpp_run(data)
在 C++ 方面,我有
#include <iostream>
#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>
#include <pybind11/stl.h>
namespace py = pybind11;
void cpp_run(py::dict& results) {
for (auto it : results) {
const std::string& name = reinterpret_cast<const std::string&>(it.first);
const py::dict& values = reinterpret_cast<const py::dict&>(it.second);
for (auto iter : values) {
const int& id = reinterpret_cast<const int&>(iter.first);
const double& value = reinterpret_cast<const double&>(iter.second);
std::cout << "name:" << name << ", id:" << id << ", value:" << value << std::endl;
}
}
}
它打印垃圾数据。我使用 reinterpret_cast 来满足 Visual Studio 编译器的要求。
【问题讨论】:
标签: python c++ dictionary stl pybind11