Hi,

> currently i am facing a problem regarding inheritance with boost::python
>
> Here is a simple code snippet:
>
>
> class Base
> {
> public:
>      virtual void print() { std::cout << "hello" << std::endl; }
>
> };
>
> [...]
>
> And in python i want to have the following reslut:
>
>  >>import my_module
>  >> derived = my_module.Derived()
>  >> derived.printIt()
>
> Actually this should print "hello" but instead throws an error saying:
>
> derived.printIt()
> Boost.Python.ArgumentError: Python argument types in
> Base.printIt(Derived)
> did not match C++ signature:
>      printIt(_Base {lvalue})

Maybe I'm oversimplifying but if all you need is exposing some derived
class then
I don't see why you'd need all the BaseWrapper, self-pointer etc. stuff.

S.th. as simple as that should work:

// file cppcode.hpp

#include <iostream>

class Base
{
public:
     virtual void print() { std::cout << "hello Base" << std::endl; }

};


class Derived : public Base
{
public:
     virtual void print() { std::cout << "hello Derived" << std::endl; }


};

// only to show callback-into-python-overrides necessities
void callback(Base& base) {
    base.print();
}

// file wrap.cpp

#include <boost/python.hpp>
#include "cppcode.hpp"

namespace bp = boost::python;



BOOST_PYTHON_MODULE(cppcode)
{
    bp::class_<Base>("Base")
        .def("printIt", &Base::print)
     ;
    bp::class_<Derived, bp::bases<Base> >("Derived");
    bp::def("callback", &callback);
};



When run:

# file test.py
import cppcode

derived = cppcode.Derived()
derived.printIt()
cppcode.callback(derived)

class PythonDerived(cppcode.Base):
    def printIt(self):
        print "hello PythonDerived"

pyderived = PythonDerived()
pyderived.printIt()
cppcode.callback(pyderived)

$ python2.7 -i ./test.py
hello Derived
hello Derived
hello PythonDerived
hello Base
>>>

Note that you'd need a Base wrapper class to actually make callbacks to
Python method-overrides work,
just as documented in
http://www.boost.org/doc/libs/1_47_0/libs/python/doc/tutorial/doc/html/python/exposing.html#python.class_virtual_functions

Holger


Landesbank Baden-Wuerttemberg
Anstalt des oeffentlichen Rechts
Hauptsitze: Stuttgart, Karlsruhe, Mannheim, Mainz
HRA 12704
Amtsgericht Stuttgart

_______________________________________________
Cplusplus-sig mailing list
[email protected]
http://mail.python.org/mailman/listinfo/cplusplus-sig

Reply via email to