如何将返回的Python字典转换为C ++ std :: map< string,string> [英] How to convert a returned Python dictionary to a C++ std::map<string, string>

查看:94
本文介绍了如何将返回的Python字典转换为C ++ std :: map< string,string>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

从C ++开始:

PyObject *pValue= PyObject_CallObject(pFunc, NULL);

其中pFunc是指向getAMap python函数的PyObject *。
为清晰起见,省略了设置pFunc的代码。

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

返回的指针pValue是指向Python字典的指​​针。
问题是,如何使字典尽可能顺利地进入C ++侧的std :: map中?

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?

我使用的C ++ Builder bcc32编译器无法处理任何精美的模板代码,如boost python或C ++ 11语法。

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

(已更改问题,因为python对象是字典,而不是元组)

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

推荐答案

相当丑陋,但我想出了这个:

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

这篇关于如何将返回的Python字典转换为C ++ std :: map&lt; string,string&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆