[C++-sig] Re: pure virtual methods with pyste

Nicodemus nicodemus at globalite.com.br
Mon Jul 28 16:29:10 CEST 2003


wiedeman at gmx.net wrote:

>Hello Dave,
>
>sorry for the error in the posted code. This wasn't due to misunderstanding
>of the tutorial, but due to copy & paste. In fact, i got the code working
>with 'normal' boost.python, but wondered, why pyste doesn't provide a wrapper
>for the pure virtual function a(). Here is the code:
>
>struct Abstract {
>  virtual void a() = 0;
>};
>
>#include <boost/python.hpp>
>using namespace boost::python;
>
>BOOST_PYTHON_MODULE(wrap_Test) {
>  class_<Abstract, boost::noncopyable>("Abstract", no_init)
>    .def("a", &Abstract::a)
>    ;
>}
>  
>

But this code won't work if the user wants to override a() in Python, 
right? We have two use cases regarding abstract classes, AFAIK:

- The user doesn't want to override the abstract class in Python: it 
will use factory functions that create instances of derived classes.
- The user wants to be able to override the methods of the abstract 
class in Python.

Here is an attempt to support both:

#include <boost/python.hpp>
using namespace boost::python;

struct Abstract {
  virtual void a() = 0;
};

struct AbstractWrap: Abstract
{
    AbstractWrap(PyObject* self_): self(self_) {}
    void a(){
        call_method<void>(self, "a");
    }
    PyObject* self;
};

void call(Abstract* a)
{
    a->a();  
}

BOOST_PYTHON_MODULE(test)
{
    class_<Abstract, AbstractWrap, boost::noncopyable>("Abstract")
        .def("a", &Abstract::a)
    ;
    def("call", call);
}


It works, i.e., we can use instances of derived classes in C++ and we 
can override a() in Python, but it is not safe, because you can 
instantiate Abstract, and calling its a method will make Python crash. 
Adding no_init prevents the class from being instantiated, even in a 
derived class, so that does not work. There's a way to support both 
usages at the same time?

Regards,
Nicodemus.
 





More information about the Cplusplus-sig mailing list