[C++-sig] Trouble wrapping abstract and inherited classes

Benny Kramek benny at kramekweb.com
Tue Dec 2 13:23:33 CET 2003


Hi,
I'm having trouble wrapping some C++ classes. This is the simplest 
example I could come up with that shows my problem:

// --------------------------------------------------------
// bpt.cpp
// --------------------------------------------------------

#include <boost/python.hpp>

using namespace boost::python;

// ----- Classes ------------------------------------------

class Animal
{
     public:
         virtual void eat(void) = 0;
};

class Baboon : public Animal
{
     public:
         void eat(void);
};

class Feeder
{
     public:
         virtual void feedAnimal(Animal* animal) = 0;
};

class Zoo
{
     public:
         Zoo(void);
         ~Zoo();
         void setFeeder(Feeder* f);
         void feedAnimals(void);
     private:
         Baboon* theBaboon;
         Feeder* feeder;
};

// ----- Function Definitions -----------------------------

void Baboon::eat(void)
{
     printf("baboon eating\n");
}

Zoo::Zoo(void)
{
     theBaboon = new Baboon();
     feeder = NULL;
}

Zoo::~Zoo()
{
     delete theBaboon;
}

void Zoo::setFeeder(Feeder* f)
{
     feeder = f;
}

void Zoo::feedAnimals(void)
{
     if(feeder)
         feeder->feedAnimal(theBaboon);
}

// ----- bpt module ---------------------------------------

class FeederWrap : public Feeder
{
     public:
         FeederWrap(PyObject* self_) : self(self_) {}
         void feedAnimal(Animal* animal) { call_method<void>(self, 
"feedAnimal", animal); }
         PyObject* self;
};

BOOST_PYTHON_MODULE(bpt)
{
     class_<Animal, boost::noncopyable>("Animal", no_init)
         ;

     class_<Baboon, bases<Animal>, boost::noncopyable>("Baboon", no_init)
         .def("eat", &Baboon::eat)
         ;

     class_<Feeder, FeederWrap, boost::noncopyable>("Feeder")
         ;

     class_<Zoo, boost::noncopyable>("Zoo")
         .def("setFeeder", &Zoo::setFeeder, with_custodian_and_ward<1, 2>())
         .def("feedAnimals", &Zoo::feedAnimals)
         ;
}

# ----- Testing with python, bpt.py:
import bpt

class SpecialFeeder(bpt.Feeder):
     def __init__(self):
         bpt.Feeder.__init__(self)
     def feedAnimal(self, animal):
         animal.eat()

zoo = bpt.Zoo()
feeder = SpecialFeeder()
zoo.setFeeder(feeder)
zoo.feedAnimals() # <- line 14

# ---------------------------------------

It compiles ok, but when I run the python script, I get this error:

Traceback (most recent call last):
   File "./bpt.py", line 14, in ?
     zoo.feedAnimals()
TypeError: No to_python (by-value) converter found for C++ type: 6Animal

I've tried playing around a lot, but I couldn't figure it out.
Thank you for any help

-- 
Benny Kramek
   http://benny.kramekweb.com
   benny at kramekweb.com






More information about the Cplusplus-sig mailing list