如何在从 pybind11 传递的 C++ 中编组 py::dict

How to marshal through py::dict in C++ passing from pybind11

我尝试通过 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 编译器。

我通过在 C++ 端使用 py::cast 来解决这个问题:

void cpp_run(const py::dict& results) {
    for (auto it : results) {
        const std::string& name = py::cast<const std::string>(it.first);

        std::unordered_map<int, double>& a_map = py::cast <std::unordered_map<int, double> >(it.second);
        for (auto iter = a_map.begin(); iter != a_map.end(); ++iter) {
            of << "name:" << name << ", id:" << iter->first << ", value:" << iter->second << std::endl;
        }
    }
}