SWIG Features

Having completed a tour of the extension process, let's zoom in for a closer look at SWIG's compendium of features. We mentioned earlier that SWIG handles a useful subset of ANSI C/C++, which means support for data structures as well as functions. Specifically, it supports the following:

The following interface file shows an example of using classes, accessing methods, and creating shadow classes:

%module Graphics class Shape {
 public: int x, y; // origin int w, h; // width, ht (defines bounding area) draw();
};
 class Polygon : public Shape {
 public: Polygon(int x, int y, int w, int h); draw();
};

We invoke SWIG with the -c++ option, since it is not enabled by default, and the -shadow option for creating shadow classes:

% swig -c++ -shadow Graphics.i

SWIG sets up an identical inheritance hierarchy in script space, and using this class in Perl feels completely natural:

use Graphics; $poly = new Polygon(10, 10, 30, 40);
printf "Origin: %d %d \n", $poly->{x}, poly->{y};
 $poly->draw();

You'll be happy to know that SWIG properly handles the relationship between base classes and derived classes. For example, a function involving a base class will recognize pointers that have been blessed into a derived class. In the case of multiple inheritance, SWIG performs proper C++ type-casting to make sure the pointer values are correct. XS has no such feature.

While the shadow class feature is convenient, you should be aware that for every instance generated using new, an additional object is created internally. The reason is that to support the member access notation ($poly->{x}), new returns a tied hash, whose FETCH subroutine calls the appropriate accessor function. You know by now that the tie facility interposes an intermediate object.