[C++-sig] [boost.python] Exposing abstract derived classes

Roman Yakovenko roman.yakovenko at gmail.com
Mon Jul 14 21:29:50 CEST 2008


On Mon, Jul 14, 2008 at 10:04 PM, Maximilian Matthe <Maxi.Matthe at web.de> wrote:
> Hi!
>
> I have a problem with exposing derived classes to python:
>
> class Base
> {
> public:
>        virtual void f() = 0;
> }
>
> class Derived : public Base
> {
> public:
>        virtual void g() = 0;
> }
>
> // here's how to wrap and expose Base:
> class BaseWrap : public Base, public wrapper<Base>
> {
> public:
>        void f()
>        {
>                this->get_override("f")();
>        }
> }
> BOOST_PYTHON_MODULE(a)
> {
>        class_<BaseWrap, boost::noncopyable>("Base")
>                .def(f, pure_virtual(&BaseWrap::f)) ;
> }
>
> // How should I wrap and expose Derived?
> // It is also pure virtual, but if I create a wrapper that
> // derives from Derived and wrapper<Derived> and create the method
> // g(), f() is still not implmented, thus it does not compile.
>
>
> I do not feel comfortable by deriving DerivedWrapper from BaseWrapper,
> Derived and wrapper<Derived>, which could even not work because of
> same base classes and so on.
> So what is the right implementation for my problem?

To use Py++ :-)

Next piece of code was generated by Py++:

#include "boost/python.hpp"

#include "1.h"

namespace bp = boost::python;

struct Base_wrapper : Base, bp::wrapper< Base > {

    Base_wrapper()
    : Base()
      , bp::wrapper< Base >(){
        // null constructor

    }

    virtual void f(  ){
        bp::override func_f = this->get_override( "f" );
        func_f(  );
    }

};

struct Derived_wrapper : Derived, bp::wrapper< Derived > {

    Derived_wrapper()
    : Derived()
      , bp::wrapper< Derived >(){
        // null constructor

    }

    virtual void g(  ){
        bp::override func_g = this->get_override( "g" );
        func_g(  );
    }

    virtual void f(  ){
        bp::override func_f = this->get_override( "f" );
        func_f(  );
    }

};

BOOST_PYTHON_MODULE(pyplusplus){
    bp::class_< Base_wrapper, boost::noncopyable >( "Base" )
        .def(
            "f"
            , bp::pure_virtual( (void ( ::Base::* )(  ) )(&::Base::f) ) );

    bp::class_< Derived_wrapper, bp::bases< Base >, boost::noncopyable
>( "Derived" )
        .def(
            "g"
            , bp::pure_virtual( (void ( ::Derived::* )(  )
)(&::Derived::g) ) )
        .def(
            "f"
            , bp::pure_virtual( (void ( ::Base::* )(  ) )(&::Base::f) ) );
}


-- 
Roman Yakovenko
C++ Python language binding
http://www.language-binding.net/



More information about the Cplusplus-sig mailing list