【问题标题】:How to marshal through py::dict in C++ passing from pybind11如何在从 pybind11 传递的 C++ 中通过 py::dict 编组
【发布时间】: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


    【解决方案1】:

    我通过在 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;
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-12-28
      • 1970-01-01
      • 2021-03-01
      • 2020-05-20
      • 2019-05-18
      • 2021-12-18
      • 2022-12-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多