如何将返回的 Python 字典转换为 C++ std::map<string,string>
How to convert a returned Python dictionary to a C++ std::map<string, string>
我正在从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) ) );
}
相关文章:
- cppcheck在const std::string[]上引发警告
- 将std::string传递给WriteConsole API
- 为std::string的某个索引赋值
- std中有类似find_last_of的函数,而string中没有
- EASTL矢量<向量<int>>连续的
- 使用 std::string () const 函数启动线程或未来
- 使用char类型将decimal转换为string,将string转换为decimal
- 迭代和比较映射<字符串、矢量<string>> c++ 中的值
- 当我们进行一些操作时,应该使用什么'std::string'或'std::stringstream'?
- 将向量解析<string>为字符串
- 'string.assign(string.data(), 5)' 是明确定义的还是 UB?
- 如何更改大小(std::string)
- "string.h"在构建适用于iOS的qt应用程序中找不到消息
- C++:如何将 unix 时间的字符串转换为 *tm?(使用时间错误:"cannot convert 'String' to 'tm*' ")
- std::string 的对象真的可以移动吗?
- 与'operator='不匹配(操作数类型'String'且"void")
- SegFault 同时使用 std::string::operator+= 和函数作为参数
- 无法从 std::string 中提取C++ Unicode 符号
- std::string 构造函数如何处理固定大小的 char[]?
- <string> 使用 for 循环写入向量