[C++-sig] Re: vector<foo*> -> list, preserving identity

Raoul Gough RaoulGough at yahoo.co.uk
Wed Dec 3 11:00:02 CET 2003


Jacek Generowicz <jacek.generowicz at cern.ch> writes:

> Raoul Gough <RaoulGough at yahoo.co.uk> writes:
[snip]
>> I've never actually used reference_existing_object, but if you think
>> about it, a reference to an existing vector object won't really help
>> you access the void * pointers that it contains.
>
> What I was wondering was whether I could prevent the new foo objects
> being created in the process of stuffing them into the
> boost::python::list, by using whatever trick it is that copy_const_reference
> uses.

OK. I'm probably not the best person to answer this, but it seems to
me that the following should work:

#include <boost/python/to_python_indirect.hpp>

...
  
  pylist.append (
     boost::python::detail::make_reference_holder::execute (foo_ptr));

Of course, things in namespace detail are undocumented and could
easily change from one release to another.

>> What you could probably do is something along these lines
>> (untested):
>> 
>>   typedef std::vector<foo const *> foo_ptr_vector;
>>   typedef foo const * (foo_ptr_vector::*memfn_type)(size_t) const;
>>   class_<> ("foo_ptr_vector")
>>     .def ("__getitem__"
>>         , static_cast<memfn_type>(&foo_ptr_vector::at)
>>         , return_value_policy<reference_existing_object>());
>> 
>> Providing __getitem__ will allow you to use a foo_ptr_vector from
>> Python via things like vec[n] or "for x in vec".
>
> Actually, the solution I found is similar: create an iterator for the
> vectors, and give the iterator the appropriate policy (which applies
> to the iterator's "next" method).
>
>   class_<std::vector<const foo*> >("foovec")
>     .def("__iter__", iterator<std::vector<const foo*>,
>                      return_value_policy<reference_existing_object> >());
>
> And now, on the Python side I wrap makefoos in something that returns 
>
>   [i for i in makefoos(n)]

The good thing about __getitem__ is that it gives you iteration as
well as indexing (Python can generate an iterator automatically given
an indexable object).

-- 
Raoul Gough.
export LESS='-X'





More information about the Cplusplus-sig mailing list