Language Wrappers
using SWIG as example

by
Jim Kytola

        Language wrappers such as SWIG and XS (See Advanced Perl Programming) can be used to gain access to a higher level programming language function call, class or object through a scripting language. Imagine we had some function that we know our scripting language cannot execute as efficiently as our higher level language - or that we already have many functions written in C/C++ that we would like to be able to use from a Perl script. This is were SWIG helps out. By taking our existing code, creating an interface file and some command line execution we can so just this. Say for instance we have some factorial function:

// example.c
int factorial(int n)
{
        if (n <= 1) return 1;
        else return n*factorial(n-1);
}

And we would like to use this in a Perl script. We need to create an interface file as define in te SWIG documentation.

//examlpe.i
%module example
%{
%}

extern int factorial(int n);

Now all we need to do (on a CS machine at Carleton) is:

swig -perl5 example.i
g++ -c example.c example_wrap.c -I/usr/lib/perl5/5.00503/i386-linux/CORE
ld -G example.o example_wrap.o -o example.so

And we have created our library which we can "use" in our Perl script like so:

#!/usr/bin/perl
use example;
print example::factorial(5),"\n";

And we get 120 as our result.
We have now used a C function in our Perl script. SWIG also allows similar functionality for Perl Python and Tcl/Tk. It has also been interfaced to make use of Java, Guile and other programming languages (high level and scripting)

Just imagine the possibility! The power of our high level language (such as C/C++) combined with the swiftness of our scripting languages...

For more information please see:
http://www.swig.org