Skip to content
Advertisement

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

I try to pass a dictionary (unordered_map) structure from python to C++ through pybind11. On the python side I am trying to do:

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)

On the C++ side, I have

#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;
        }
    }
}

It prints garbage data. I used reinterpret_cast to satisfy the Visual Studio compiler.

Advertisement

Answer

I sort of solve this by using py::cast on the C++ side:

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;
        }
    }
}
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement