c++ python交互之boost.python 简集之Map处理

C++中经常使用map来存储键值对,本章介绍python如何传递或返回c++ map键值对
c++源码:src.cpp
#include <iostream>
#include <string>
#include <map>
using namespace std;

typedef map<string,int> simap;

simap A()
{
simap m;
m["aaa"] = 1;
m["bbb"] = 2;
m["ccc"] = 3;
m["ddd"] = 4;
m["eee"] = 5;
m["fff"] = 6;

return m;
}

为python做转换代码,src4py.cpp
#include <boost/python.hpp>
#include <boost/python/suite/indexing/map_indexing_suite.hpp>
#include "src.cpp"
using namespace boost::python;
BOOST_PYTHON_MODULE(test)
{

class_<simap>("pySImap")
.def( map_indexing_suite<simap>() )
;

def("a",A);
}

python调用端代码: test.py
import test
mapcontainer = test.pySImap()
mapcontainer = test.a()

for i in mapcontainer:
print i

dict = {}
for i in mapcontainer:
key = i.key()
dict[key] = i.data()
print dict

你可能感兴趣的:(C++,python,休闲,boost.python简集,Map处理)