Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a derived class to a function taking a base class in SWIG Python

Tags:

python

swig

I am passing a derived class into a function taking a base class using Python 3.3 and SWIG 2.0.10.

The same SWIG .i file is being used for C# and it works well. However, in Python, SWIG reports that there is no C++ method accepting the derived type - only a method accepting the base type. That statement is true, but I need to pass the derived type and have SWIG direct the call as if it was the base type.

The derived type does not exist in C++. It only exists in Python (and C#). However, we have directors enabled and, as stated, it is working fine in C#.

Same result in Python 2.6 and 2.7.

C++

class Base {};
// Note: there is NO "class Derived" in C++.
void f(Base* a) { ... }

Python

class Derived(Base): pass

x = Derived()
f(x) # SWIG runtime error - In C++ there is no f(Derived*) - there is only f(Base*)
like image 994
bluedog Avatar asked May 12 '26 21:05

bluedog


1 Answers

The problem was that in class Derived I did not properly call Base.__init__().

Once I fixed that, the polymorphism in Swig just worked.

class Derived(Base):
    def __init__(self):
        super(Derived, self).__init__()
like image 158
bluedog Avatar answered May 14 '26 11:05

bluedog



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!