This example illustrates C++ class wrapping performed by SWIG. C++ classes are simply transformed into Ruby classes that provide methods to access 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(); };
Note: when creating a C++ extension, you must run SWIG with the -c++ option like this:/* File : example.i */ %module example %{ #include "example.h" %} /* Let's just grab the original header file here */ %include "example.h"
% swig -c++ -ruby example.i
c = Example::Circle.new(10)
c.x = 15 # Set member data x = c.x # Get member data
print "The area is ", c.area, "\n"
n = Shape.nshapes # Get a static data member 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 ... } %}