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;
}
#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);
}
#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
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
本文转自elbertchen 51CTO博客,原文链接:http://blog.51cto.com/linkyou/751828,如需转载请自行联系原作者