【问题标题】:How to convert a returned Python dictionary to a C++ std::map<string, string>如何将返回的 Python 字典转换为 C++ std::map<string, string>
【发布时间】:2018-10-03 23:05:10
【问题描述】:

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

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

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 的代码。

返回的指针 pValue 是一个指向(除其他外)Python 字典的指针。 问题是,如何尽可能顺利地将字典放入 C++ 端的 std::map 中?

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

(由于 python 对象是字典,而不是元组,因此更改了问题)

【问题讨论】:

  • 刚刚找到了一个库,该库可以轻松地将 Python 对象 (Python C API) 转换为标准 C++ 数据类型,正如它所说的 here。看起来它可能会对您有所帮助,因为它还支持std::map
  • 另外,考虑swig
  • Rob,其实我在用 swig。
  • 大卫;那个库看起来不错,但不幸的是我不能在这个编译器中使用它。
  • 我会使用 PyTuple_GetItem 并将值复制到地图中。或者写一个 swig typemap 来为你做这件事。

标签: python c++ c++builder


【解决方案1】:

这很丑,但我想出了这个:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-29
    • 2013-05-24
    • 2014-01-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多