如何将返回的 Python 字典转换为 C++ std::map<string,string>

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

本文关键字:string gt map lt std C++ 返回 Python 转换 字典      更新时间:2023-10-16

我正在从C 调用Python,并尝试执行一些数据转换。

例如,如果我调用以下python函数

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

来自C AS:

PyObject *pValue= PyObject_CallObject(pFunc, NULL);

其中pfunc是一个指向getAmap Python函数的PyObject*。为了清晰而省略了用于设置PFUNC的代码。

返回的指针,Pvalue是(除其他外(python词典的指针。问题是,如何将thh字典尽可能顺利地进入C 侧的std ::映射?

我正在使用无法处理任何精美模板代码的C 构建器BCC32编译器,例如Boost Python或C 11语法。

(更改为Python对象是字典,而不是元组(

这很丑陋,但我想到了:

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