I have the following C++ code:
const std::string Get(const std::map<std::string, std::string> map) {
PyObject* module = PyImport_ImportModule("dummy");
boost::python::dict dict;
for (auto const& pair : map) {
dict[pair.first] = pair.second;
}
// This is the line
PyObject* args = PyTuple_Pack(1, &dict);
/// ^^^^^^^^^^^
PyObject* function = PyObject_GetAttrString(module,"get_something");
PyObject* pyResult = PyObject_CallObject(function, args);
std::string result = PyUnicode_AsUTF8(pyResult);
return result;
}
Calling this python script:
def get_something(map):
return map['a']
I can pass std::string to python by calling PyUnicode_FromString.
The problem is I was not able to find a similar function that takes std::map and returns PyObject*.
- I tried passing a ref to
boost::python::dictbut this segfaults on runtime. - I tried passing the
mapitself directly. Segfault again. - I know I can encode the
mapas JSON, pass a string and unpack in python but that's a terrible kludge. - I might be able to wrap the
mapin a class and pass that. I was able to do that elsewhere.
But I really want this code to be as simple as possible. Surely this is possible.
PyObject*, so usedict.ptr().dictinherited fromobject....ptr()conversion for you.