3

I am currently using SWIG to make the implementation of small modules easier in my main C++ programm. The class architecture is as follow :

foo.hpp :

class Foo
{
public:
  virtual int pureFunc() = 0;
  int func() { return (42); }
};

file.i :

%module(directors="1") foo
%feature("director") Foo;
%{
  #include "foo.hpp"
%}
%include "foo.hpp"

file.py :

import sys
sys.path.append('.')
import foo

class Bar(foo.Foo):
    def __init__(self):
        pass
    def pureFunc(self):
        return 21

lol = Bar()
print lol.pureFunc()
print lol.func()

I then generate the swig wrappers using the following command :

swig -python -c++ file.i

and compile the .so like this :

g++ -fPIC -shared -o _foo.so file_wrap.cxx -I/usr/include/python2.7 -lpython2.7

And when I try to run the python script I get the following error :

# python file.py 
21
Traceback (most recent call last):
  File "file.py", line 13, in <module>
    print lol.func()
  File "/home/volent/dev/CPP/cython/foo.py", line 84, in func
    def func(self): return _foo.Foo_func(self)
TypeError: in method 'Foo_func', argument 1 of type 'Foo *'
# _

That shows that the use of the pure method is working but I can't use the one already defined in the .hpp file.

I have tried to read the SWIG documentation and the only things I see about abstract class and inheritance are 34.4.7 C++ Classes and 34.4.8 C++ Inheritance. And I can't see anything mentionning a case like that.

3
  • It might be because you are are not calling the __init__ method of the parent class. In your file.py try replacing pass with super(Bar,self).__init__() (or in python 3.0, super().__init__()). Commented May 30, 2013 at 18:29
  • Also, is there more to that traceback? Commented May 30, 2013 at 18:30
  • Thanks a lot, the super(Bar, self).__init__() fixed it ! Commented May 31, 2013 at 9:39

1 Answer 1

1

You have forgotten to call the __init__ method of the parent class of Bar. Replace your __init__ method with this:

class Bar(foo.Foo):
    def __init__(self):
        super(Bar,self).__init__()

This should let your Bar class know about the Foo method.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.