[C++-sig] Wrapping std::vector<AbstractClass*>

Paul Melis paul at pecm.nl
Fri Jul 1 20:00:07 CEST 2005

I have an abstract class and a std::vector<> of pointers to this class. 
A routine in my c++ code fills a vector with objects of classes derived 
from the abstract class.
I'd like to iterate over the vector in python and use each of the items 
in the vector depending on the type of derived class.

I have the following:

#include <vector>
#include <boost/python.hpp>
#include <boost/python/suite/indexing/vector_indexing_suite.hpp>

using namespace boost::python;

class Abstract
    virtual void    f() =0;

class Concrete1 : public Abstract
    virtual void    f()    { }

typedef std::vector<Abstract*>   ListOfObjects;

class DoesSomething
    DoesSomething()    {}
    ListOfObjects   returnList()    { ListOfObjects lst; 
lst.push_back(new Concrete1()); return lst; }

class_<Abstract, boost::noncopyable>("Abstract", no_init)

   .def( vector_indexing_suite<ListOfObjects>() )  

    .def("returnList", &DoesSomething::returnList)

Now, when I put this stuff in a python module and try to use it I get:

Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
 >>> import test
 >>> dir(test)
['Abstract', 'DoesSomething', 'ListOfObjects', '__doc__', '__file__', 
 >>> d = test.DoesSomething()
 >>> d.returnList()
<test.ListOfObjects object at 0x009C5588>
 >>> lst = d.returnList()
 >>> lst[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: No to_python (by-value) converter found for C++ type: class 

I suspect that boost.python will wrap the return value of returnList() 
as a pointer to Abstract, without the possibility at runtime to look at 
the actual object type. Is this something I would have to code by hand? 
For example, by making a routine that takes a pointer to Abstract and 
uses dynamic_cast<> to test which of the concrete classes the object 
actually is from?


More information about the Cplusplus-sig mailing list