gpt4 book ai didi

python - 如何将返回的 Python 字典转换为 C++ std::map

转载 作者:太空狗 更新时间:2023-10-29 23:11:32 29 4
gpt4 key购买 nike

我正在从 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 字典的指针。问题是,如何尽可能顺利地将 thh 字典放入 C++ 端的 std::map 中?

我使用的是 C++ Builder 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) ) );
}

关于python - 如何将返回的 Python 字典转换为 C++ std::map<string, string>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49988922/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com