[C++-sig] Re: Inheriting a Python class from a C++ class

David Abrahams dave at boost-consulting.com
Wed Aug 6 13:47:37 CEST 2003


Benny Kramek <benny at kramekweb.com> writes:

> Hi, this is my first message here.
>
> This is what I would like to do:
>
> an abstract class in c++
> a python class inherits from this class
> python code calls a c++ function that takes as an argument an instance
> of the c++ abstract base class
>
> Here is a simple code example of what I tried
>
> //--- animal.cpp ---
>
> #include <boost/python.hpp>
>
> using namespace boost::python;
>
> class Animal
> {
> 	public:
> 		virtual void sleep(int hours) = 0;
> };
>
> class AnimalWrap : public Animal
> {
> 	public:
> 		AnimalWrap(PyObject* self_) : self(self_) {}
> 		void sleep(int hours) { return call_method<void>(self, "sleep"); }
> 		PyObject* self;
> };
>
> void checkAnimal(Animal* animal)
> {
> 	// ...
> }
>
> BOOST_PYTHON_MODULE(animal)
> {
> 	class_<Animal, AnimalWrap, boost::noncopyable>("Animal", no_init)
                                                             ^^^^^^^
You have to eliminate this.
> 		;
>
> 	def("checkAnimal", checkAnimal);
> }
>
> //--- animal.cpp ---
>
> # --- baboon.py ---
>
> import animal
>
> class Baboon(animal.Animal):
> 	def __init__(self):
> 		pass
and ^^^^^^^^^^^^^^^^^^^ this.

Your Baboon class must contain an Animal class somewhere, or it will
never be able to be passed where an Animal* is expected.

You can also

   def __init__(self):
       animal.Animal.__init__(self)

of course.

> 	def sleep(self, hours):
> 		print 'sleeping'
>
> george = Baboon()
>
> animal.checkAnimal(george)
>
> # --- baboon.py ---
>
> when I execute baboon.py I get the following error:
>
> Traceback (most recent call last):
>   File "baboon.py", line 11, in ?
>     animal.checkAnimal(george)
> TypeError: bad argument type for built-in operation
>
> I also tried changing the checkAnimal c++ function to take a
> reference as an argument instead of a pointer, but i get the same
> error.
>
> Thank you,
> Benny Kramek

-- 
Dave Abrahams
Boost Consulting
www.boost-consulting.com





More information about the Cplusplus-sig mailing list