This example illustrates the most primitive form of C++ class wrapping performed by SWIG. In this case, C++ classes are simply transformed into a collection of C-style functions that provide access to class members.
/* File : example.h */
class Shape {
public:
Shape() {
nshapes++;
}
virtual ~Shape() {
nshapes--;
};
double x, y;
void move(double dx, double dy);
virtual double area() = 0;
virtual double perimeter() = 0;
static int nshapes;
};
class Circle : public Shape {
private:
double radius;
public:
Circle(double r) : radius(r) { };
virtual double area();
virtual double perimeter();
};
class Square : public Shape {
private:
double width;
public:
Square(double w) : width(w) { };
virtual double area();
virtual double perimeter();
};
/* File : example.i */
%module example
%{
#include "example.h"
%}
/* Let's just grab the original header file here */
%include "example.h"
Note: when creating a C++ extension, you must run SWIG with the -c++ option like this:
% swig -c++ -python example.i
$c = example::new_Circle(10.0);
Note: when accessing member data, the name of the class in which the data member is defined is used. For example Shape_x_get().example::Shape_x_set($c,15); # Set member data $x = example::Shape_x_get($c); # Get member data
print "The area is ", example::Shape_area($c);
example::Shape_area($c); # Works (c is a Shape) example::Circle_area($c); # Works (c is a Circle) example::Square_area($c); # Fails (c is definitely not a Square)
example::delete_Shape($c); # Deletes a shape
$n = $example::Shape_nshapes; # Get a static data member $example::Shapes_nshapes = 13; # Set a static data member
void foo(int a); %name(foo2) void foo(double a, double b);
%inline %{
Vector *vector_add(Vector *a, Vector *b) {
... whatever ...
}
%}