[C++-sig] Python-overridable method taking const ref?

Roman Yakovenko roman.yakovenko at gmail.com
Wed Feb 4 20:15:03 CET 2009


On Wed, Feb 4, 2009 at 8:49 PM, Paul Melis
<pyplusplus at assumetheposition.nl> wrote:
> Hello,
>
> Classes with protected destructors (as found when custom reference
> counting is used) seem to cause some trouble when using bp::wrapper<>
> containing  a method that takes a const reference to a refcounted class.
>
> Say I have:
>
> #include <cstdio>
> #include <boost/python.hpp>
>
> namespace bp = boost::python;
>
> class Thing
> {
> protected:
>    virtual ~Thing() {}
> };
>
> class Callback
> {
> public:
>    Callback() { }
>    virtual void execute(const Thing& t) { }
> protected:
>    virtual ~Callback() {}
> };
>
> And I want to add a wrapper class so that Callback can be derived from
> in Python and its execute() method overridden.

Try the following code:

#include "boost/python.hpp"

namespace bp = boost::python;

struct Callback_wrapper : Callback, bp::wrapper< Callback > {

    Callback_wrapper( )
    : Callback( )
      , bp::wrapper< Callback >(){
        // null constructor

    }

    virtual void execute( ::Thing const & t ) {
        if( bp::override func_execute = this->get_override( "execute" ) )
            func_execute( boost::ref(t) );
        else
            this->Callback::execute( boost::ref(t) );
    }


    void default_execute( ::Thing const & t ) {
        Callback::execute( boost::ref(t) );
    }

};

BOOST_PYTHON_MODULE(pyplusplus){
    bp::class_< Callback_wrapper, boost::noncopyable >( "Callback",
bp::no_init )
        .def( bp::init< >() )
        .def(
            "execute"
            , (void ( ::Callback::* )( ::Thing const & ) )(&::Callback::execute)
            , (void ( Callback_wrapper::* )( ::Thing const & )
)(&Callback_wrapper::default_execute)
            , ( bp::arg("t") ) );

    bp::class_< Thing, boost::noncopyable >( "Thing", bp::no_init );
}

It was generated by Py++ and I believe it exposes your use case correctly.


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


More information about the Cplusplus-sig mailing list