[C++-sig] Re: SWIG: overriding virtual functions in Python.
Jacek Generowicz
jacek.generowicz at cern.ch
Mon Apr 28 14:27:28 CEST 2003
Jacek Generowicz <jacek.generowicz at cern.ch> writes:
> given a C++ class
>
> struct foo {
> virtual void one() {
> cout << "This is foo::one() calling two()" << endl;
> two();
> }
> virtual void two() {
> cout << "This is foo::two()" << endl;
> }
> };
>
> I would like to subclass it in Python and override "two()" thus:
>
> class bar(foo):
> def two(self):
> print "This is bar.two()"
>
> in such a way that calling bar.one() ...
>
> bar().one()
>
> gives the result
>
> This is foo::one() calling two()
> This is bar.two()
>
> rather than
>
> This is foo::one() calling two()
> This is foo.two()
>
> In Boost this is achieved by doing providing a wrapper class around
> the original C++ implementation, and giving it a default
> implementation of the virtual function, which calls back into Python.
>
> Is there a way of doing it in SWIG?
Replying to myself for the benefit of anyone searching archives for
a solution to this problem.
The keyword is "directors":
http://www.swig.org/Doc1.3/Python.html#n32
In brief, for the above example
a) Change
%module the_module_name
to
%module(directors="1") the_module_name
b) Add
%feature("director") foo;
anywhere before foo is declared.
More information about the Cplusplus-sig
mailing list