From: William S F. <ws...@fu...> - 2007-04-29 21:25:27
|
Eric Mahurin wrote: > I'm trying to setup a generic python module that wraps the bulk of C++ > STL for use in python with normal python objects. So far, I've been > able to wrap containers/iterators quite well. Here's what I'm using: > > %module stl > > %include <std_container.i> > > %include <std_vector.i> > %include <std_deque.i> > %include <std_list.i> > %include <std_set.i> > %include <std_map.i> > %include <std_multiset.i> > %include <std_multimap.i> > > %template(_vector ) std::vector <swig::PyObject_ptr>; > %template(_deque ) std::deque <swig::PyObject_ptr>; > %template(_list ) std::list <swig::PyObject_ptr>; > %template(_set ) std::set <swig::PyObject_ptr>; > %template(_map ) std::map <swig::PyObject_ptr,swig::PyObject_ptr>; > %template(_multiset) std::multiset<swig::PyObject_ptr>; > %template(_multimap) std::multimap<swig::PyObject_ptr,swig::PyObject_ptr>; > > %pythoncode %{ > vector = _vector > deque = _deque > list = _list > set = _set > map = _map > multiset = _multiset > multimap = _multimap > %} > > After creating this module, I can use the classes vector, deque, etc > from this module with both python (i.e. __iter__ and append) and C++ > (i.e. begin/end and push_back) method names. These containers also hold > generic python objects. Very nice. > > There are a few other data structures I would also like too see: slist, > priority_queue, hash_set, hash_map. But, the major ones I wanted are > listed above - set and map. Those give me ordered sequences with > O(log(n)) performance - usually implemented with red-black trees. There > is no performance equivalent of this in standard python. > > The major category missing from this STL module above is the > "algorithms". I specifically would like stuff from the sorting > category: nth_element and *_heap since priority_queue isn't ready for > swig yet. > > Can anbody get me started by showing me how to port the STL algorithm > nth_element over to python using iterators to STL containers containing > python objects (from above)? > You should tackle this like any other templated code you want to use from SWIG. So giving the following to SWIG would be a start... namespace std { template <class RandomAccessIterator> void nth_element(RandomAccessIterator first, RandomAccessIterator nth, RandomAccessIterator last); } then you need a %template for RandomAccessIterator. I don't know the Python STL iterator mappings at all, so this might be covered already. If not you need to get the RandomAccessIterator from the C++ world into Python, by either using one of the Python STL wrappers (eg vector::begin()) or write a method that will return it for you. If I had more knowledge on the Python STL wrappers or loads of time, I'd write some code, but I'm afraid you're going to have to experiment yourself. William |