SWIG/Examples/ruby/class/

Wrapping a simple C++ class

$Header: /cvsroot/swig/SWIG/Examples/ruby/class/index.html,v 1.3 2002/11/30 22:10:05 beazley Exp $

This example illustrates C++ class wrapping performed by SWIG. C++ classes are simply transformed into Ruby classes that provide methods to access class members.

The C++ Code

Suppose you have some C++ classes described by the following (and admittedly lame) header file:
/* 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();
};

The SWIG interface

A simple SWIG interface for this can be built by simply grabbing the header file like this:
/* 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++ -ruby example.i

A sample Ruby script

Click here to see a script that calls the C++ functions from Ruby.

Key points

General Comments