I try to pass a dictionary (unordered_map) structure from python to C++ through pybind11. On the python side I am trying to do:
JavaScript
x
6
1
v1 = { 1:3.0, 2:4.0}
2
v2 = { 7:13.0, 8:14.0, 15:22.0}
3
4
data={'ab':v1, 'bz':v2}
5
cpp_run(data)
6
On the C++ side, I have
JavaScript
1
21
21
1
#include <iostream>
2
#include <pybind11/pybind11.h>
3
#include <pybind11/numpy.h>
4
#include <pybind11/stl.h>
5
6
namespace py = pybind11;
7
8
void cpp_run(py::dict& results) {
9
10
for (auto it : results) {
11
const std::string& name = reinterpret_cast<const std::string&>(it.first);
12
const py::dict& values = reinterpret_cast<const py::dict&>(it.second);
13
14
for (auto iter : values) {
15
const int& id = reinterpret_cast<const int&>(iter.first);
16
const double& value = reinterpret_cast<const double&>(iter.second);
17
std::cout << "name:" << name << ", id:" << id << ", value:" << value << std::endl;
18
}
19
}
20
}
21
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:
JavaScript
1
11
11
1
void cpp_run(const py::dict& results) {
2
for (auto it : results) {
3
const std::string& name = py::cast<const std::string>(it.first);
4
5
std::unordered_map<int, double>& a_map = py::cast <std::unordered_map<int, double> >(it.second);
6
for (auto iter = a_map.begin(); iter != a_map.end(); ++iter) {
7
of << "name:" << name << ", id:" << iter->first << ", value:" << iter->second << std::endl;
8
}
9
}
10
}
11