[C++-sig] Python iterable to std map

Charles Solar charlessolar at gmail.com
Wed Nov 3 15:22:46 CET 2010


I have a class interface I expose to python that has methods such as begin,
end, rbegin, rend.  Its meant to be a class that C++ can iterate over.  I
now want to make the object defined in python, so python can pass the C++
library an object of python's class and C++ can use it like it would any
real C++ object derived from the same interface.
Since python does not really have a concept of begin, end, rbegin, rend, I
thought a good idea would be to have the python class define a __iter__
method and use that method with stl_input_iterator to pull in the complete
list from python to use with begin, end, etc.

What I have currently is a python converter for tuples of size 2 to std
pairs, then the wrapper class for the interface calls
> struct IFooHolder_wrapper : IFooHolder, bp::wrapper< IFooHolder >
> {
> mutable std::map< std::string, boost::shared_ptr< IFoo > > _map;
> const_iterator begin() const
> {
>    std::copy( bp::stl_input_iterator< std::pair< std::string,
boost::shared_ptr< IFoo > > >( bp::object( bp::handle<>( bp::borrowed(
bp::detail::wrapper_base_::get_owner(*this) ) ) ) ),
bp::stl_input_iterator<      std::pair< std::string, boost::shared_ptr< IFoo
> > >(), std::inserter( _map, _map.begin() ) );
>    return _map.begin();
> }

to copy all the iterations into a map the wrapper holds.  Then the begin,
end, rbegin, rend methods return iterations from that map.

My main concern is firstly if there is a better way.  More elegant solutions
like the map indexing suite do not really work on this problem, and google
can only help so much.  I fear there is not much documentation from others
trying to do the same thing.
I especially do not like "bp::object( bp::handle<>( bp::borrowed(
bp::detail::wrapper_base_::get_owner(*this) ) ) )"
>From my understanding of stl_input_iterator, it needs a bp::object that has
an "__iter__" attribute.  I want to use this->get_override( "__iter__" ) but
that does not work.

So if someone knows a better way to build a bp::object from a bp::wrapper
class that would be a good start.  I should mention my solution compiles but
does not work.  Python crashes when it tries to do the std::copy

Thanks for any input
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/cplusplus-sig/attachments/20101103/408e19c5/attachment.html>


More information about the Cplusplus-sig mailing list