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++ -go example.i
The name of the constructor is New followed by the name of the class, capitalized.c := example.NewCircle(10.0)
These are methods on the type returned by the constructor. The getter is named Get followed by the name of the member, capitalized. The setter is similar but uses Set.c.SetX(15) # Set member data x := c.GetX() # Get member data.
fmt.Println("The area is", example.c.Area())
The name of the destructor is Delete followed by the name of the class, capitalized. (Note: destructors are currently not inherited. This might change later).example.DeleteShape(c) # Deletes a shape
The name is Get or Set, followed by the name of the class, capitalized, followed by the name of the member, capitalized.n := GetShapeNshapes() # Get a static data member SetShapeNshapes(13) # Set a static data member