How to convert a returned Python dictionary to a C++ std::map<string, string>

岁酱吖の 提交于 2020-01-03 19:04:17

问题


I'm calling Python from C++, and trying to perform some data conversions.

For example, if I call the following Python function

def getAMap():
   data = {}
   data["AnItem 1"] = "Item value 1"
   data["AnItem 2"] = "Item value 2"
   return data

from C++ as:

PyObject *pValue= PyObject_CallObject(pFunc, NULL);

where pFunc is a PyObject* that points to the getAMap python function. Code for setting up pFunc omitted for clarity.

The returned pointer, pValue is a pointer to a (among other things) Python dictionary. Question is, how to get thh dictionary into a std::map on the C++ side as smoothly as possible?

I'm using C++ Builder bcc32 compiler that can't handle any fancy template code, like boost python, or C++11 syntax.

(Changed question as the python object is a dictionary, not a tuple)


回答1:


It's pretty ugly, but I came up with this:

std::map<std::string, std::string> my_map;

// Python Dictionary object
PyObject *pDict = PyObject_CallObject(pFunc, NULL);

// Both are Python List objects
PyObject *pKeys = PyDict_Keys(pDict);
PyObject *pValues = PyDict_Values(pDict);

for (Py_ssize_t i = 0; i < PyDict_Size(pDict); ++i) {
    // PyString_AsString returns a char*
    my_map.insert( std::pair<std::string, std::string>(
            *PyString_AsString( PyList_GetItem(pKeys,   i) ),
            *PyString_AsString( PyList_GetItem(pValues, i) ) );
}


来源:https://stackoverflow.com/questions/49988922/how-to-convert-a-returned-python-dictionary-to-a-c-stdmapstring-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!