[C++-sig] question about vectors of pointers (boost python)

David Philp david.philp at anu.edu.au
Tue Jul 15 05:11:37 CEST 2008


Hi

This is very much a newbie question... but I can't find the answer  
anywhere in the boost python documentation or elsewhere.  Please feel  
free to give a URL instead of an answer.

I have a vector of pointers in C++, and am trying to expose them to  
python.  In particular I want to be able to iterate through them using  
e.g.

for item in my_vec:
   print item.i

This always fails with the following:
TypeError: No to_python (by-value) converter found for C++ type:  
my_struct*
(In every other way it works as expected.)

The error seems reasonable:  I have told Python about my_struct, but  
not what to do with my_struct*.  I want Python to treat my_struct* as  
though it were a my_struct, but I can't figure out what I need to do.   
Do I need to use pointer_wrapper?  Is there an example?

Some context that may be important: it's not apparent from this  
example, but I intend for the vector to be owned by a C++ class that  
will be in existence for the lifetime of the Python program.  So I am  
not overly concerned about details of memory management (unless they  
are more important than I thought.)

Many thanks in advance!

David

-----------------Relevant C++ code-----------------

struct my_struct
{
   int i_;
   bool operator==(my_struct const& m) const {return i_ == m.i_;}
};

BOOST_PYTHON_MODULE(pye)
{
   class_<my_struct>("my_struct")
     .def_readwrite("i", &my_struct::i_)
   ;

   class_<std::vector<my_struct *> >("my_struct_vector")
     .def(vector_indexing_suite<std::vector<my_struct *> >())
   ;
};


-----------------Relevant Python code-----------------

from pye import *
q = my_struct()
q.i = 3

my_vec = my_struct_vector()
my_vec.append(q)

len(my_vec)
print my_vec[0].i

for item in my_vec :
    print item.i








More information about the Cplusplus-sig mailing list