Wrapping a C++ class in Python using SWIG

Ajay picture Ajay · Jan 4, 2011 · Viewed 14.9k times · Source

example.h:

#ifndef EXAMPLE_H
#define EXAMPLE_H

class Math {
 public:
    int pi() const;
    void pi(int pi);
 private:
    int _pi;
};

#endif

example.cpp:

#include "example.h"

int Math::pi() const {
    return this->_pi;
}  
void Math::pi(int pi) {
    this->_pi = pi;
}

example.swig:

%module example
%{ 
    #define SWIG_FILE_WITH_INIT
    #include "example.h"
%}
%include "example.h"

I then generate the wrappers, "example.py" and "example_wrap.c" using:

swig  -python example.swig

When I try to compile the wrapper class using:

g++ -fPIC -c example.cpp example_wrap.c -I/usr/local/include/python2.6/

I get the following error:

example_wrap.cpp: In function "PyObject* Swig_var_Math_get()":
example_wrap.cpp:2725: error: expected primary-expression before "void"
example_wrap.cpp:2725: error: expected ")" before "void"

The Error is at the following line :

pyobj = SWIG_NewPointerObj(SWIG_as_voidptr(&Math), SWIGTYPE_p_class,  0 );

#define SWIG_as_voidptr(a) (void *)((const void *)(a))

Is it the right way to generate the wrapper class "example_wrap.c"?

Answer

Chris Card picture Chris Card · Jan 4, 2011

I think the swig command should be "swig -c++ -python example.swig"