Hi,<br><br>I'm trying to wrap std::map using boost::python so my embedded python code can access maps. I have the following wrapper class:<br><br>//Map - takes e.g std::map<std::string,thing*> as MapType<br>template<class MapType>
<br>struct MapItem<br>{<br> //Typedefine the key and value types for ease<br> typedef typename MapType::key_type KeyType;<br> typedef typename MapType::mapped_type ValueType;<br> <br> static ValueType& Get(MapType & x,KeyType const& i)
<br> {<br> if( x.find(i) != x.end() ) <br> return x[i];<br> //Some kind of error!<br> }<br> static void Set(MapType & x,KeyType const& i,ValueType const& v)<br> {<br> x[i]=v; // use map autocreation feature
<br> }<br> static void Del(MapType & x,KeyType const& i)<br> {<br> if( x.find(i) != x.end() ) <br> x.erase(i);<br><br> }<br>}<br><br>And the following Boost::Python class definition to wrap a particular map:
<br><br>[source lang="cpp"]<br>boost::python::class_<std::map<std::string,SubGrid> >("SubGridMap")<br> .def("__len__",&std::map<std::string,SubGrid>::size)<br> .def("clear",&std::map<std::string,SubGrid>::clear)
<br> .def("__getitem__",&MapItem<std::map<std::string,SubGrid> >::Get,boost::python::return_value_policy<boost::python::copy_non_const_reference>())<br> .def("__setitem__",&MapItem<std::map<std::string,SubGrid> >::Set,boost::python::with_custodian_and_ward<1,2>()) // to let container keep value
<br> .def("__delitem__",&MapItem<std::map<std::string,SubGrid> >::Del)<br>;<br><br>I really need iterator support and following the Python Wiki entry on STL containers, have written a function like this to convert the std::map to a std::list of tuples as boost::python::iterator doesn't seem to be compatible with std::map (which seems a bit icky but makes sense):
<br><br>static std::list<boost::tuple<KeyType,ValueType> > Items(MapType const& x)<br>{<br> std::list<boost::tuple<KeyType,ValueType> > t;<br> typename MapType::const_iterator it;<br>
<br> for(it=x.begin(); it!=x.end(); ++it)<br> t.push_back(boost::make_tuple(it->first,it->second));<br> <br> return t;<br>}<br><br><br>But the wiki entry irritatingly stops short of telling you how the hell you wrap it into an __iter__ and the attachement to the wiki entry seems to be empty...Has anyone done this or have any ideas?
<br><br>Cheers<br><br>Jamie