在C++程序中如何使用python函数所返回的字典

BlueBuleSky 2010-01-21 09:43:06
我在python中定义了一个函数,函数返回一个字典,看起来大体是这个样子的:

def get_a_dic():
dic = {}
#在这里对字典进行操作
……
return dic

然后再C++中调用这个函数
得到一个PyObject* pDic
我该怎么使用这个pDic?
我想获得里面的所有Key和对应的value,把这个字典中的所有item导入到一个map中,应该怎么做?

我是用的是python3.0,eclipse3.5 挂接mingw编译环境,没有使用boost库。

请高手指教!
...全文
433 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
BlueBuleSky 2010-01-23
  • 打赏
  • 举报
回复
昨天加班没时间上CSDN
十分感谢各位的回答!

特别鸣谢 notax!
angel_su 2010-01-22
  • 打赏
  • 举报
回复
thy38 2010-01-22
  • 打赏
  • 举报
回复
同学一下
notax 2010-01-22
  • 打赏
  • 举报
回复
写了个,试试, 用cpython 2.5

1. my_utils.py
def get_a_dict():
d = {'A':1, 'B':2, 'C':3}
return d


if __name__ == '__main__' :
print get_a_dict()


----------output--------
$ ./a.out
{'A': 1, 'C': 3, 'B': 2}
pos, key value = 1 A 1
pos, key value = 3 C 3
pos, key value = 4 B 2
key value = A 1
key value = B 2
key value = C 3

*/

#include <iostream>
#include <string>
#include <map>
#include <Python.h>

using namespace std;

int main() {
typedef map<string, long> mapType;
mapType data;

Py_Initialize();
PyObject * pFunc = NULL;
PyObject * pArg = NULL;

PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append('./')");

PyObject* mod= PyImport_ImportModule("my_utils");

if(mod == 0) {
puts("didn't load" );
}

pFunc = PyObject_GetAttrString(mod, "get_a_dict");
PyObject *dict1 = PyEval_CallObject(pFunc, pArg); //pArg = NULL => no argument

printf( "%s\n", PyString_AsString( PyObject_Repr(dict1) ) );

PyObject *key, *value;
Py_ssize_t pos = 0;
while (PyDict_Next(dict1, &pos, &key, &value)) {
printf("pos, key value = %ld %s %ld\n", pos, PyString_AsString(key), PyLong_AsLong(value));
data[PyString_AsString(key)] = PyLong_AsLong(value);
}

Py_DECREF( dict1 );

Py_Finalize();

for(mapType::const_iterator it = data.begin(); it != data.end(); ++it) {
printf("key value = %s %ld\n", (it->first).c_str(), it->second);
}
return 0;
}
notax 2010-01-22
  • 打赏
  • 举报
回复
学习学习

37,743

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • WuKongSecurity@BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧