SWIG Tutorial
So you want to get going in a hurry? To illustrate the use of SWIG, suppose you have some C functions you want added to Tcl, Perl, and Python. Specifically, let's say you have them in a file 'example.c'
/* File : example.c */
#include <time.h>
double My_variable = 3.0;
int fact(int n) {
if (n <= 1) return 1;
else return n*fact(n-1);
}
int my_mod(int x, int y) {
return (x%y);
}
char *get_time()
{
time_t ltime;
time(<ime);
return ctime(<ime);
}
/* example.i */
%module example
%{
/* Put header files here (optional) */
%}
extern double My_variable;
extern int fact(int n);
extern int my_mod(int x, int y);
extern char *get_time();
unix % swig -tcl example.i
Making wrappers for Tcl
unix % gcc -fpic -c example.c example_wrap.c \
-I/usr/local/include
unix % gcc -shared example.o example_wrap.o -o example.so
unix % tclsh
% load ./example.so example
% puts $My_variable
3.0
% fact 5
120
% my_mod 7 3
1
% get_time
Sun Feb 11 23:01:07 1996
%
The swig command produces a file
example_wrap.c that should be compiled and linked with
the rest of the program. In this case, we have built a dynamically
loadable extension that can be loaded into the Tcl interpreter using
the 'load' command.
If your machine does not support dynamic loading, it is also easy to build a new version of the tclsh interpreter as follows :
unix % swig -tcl -ltclsh.i example.i
unix % gcc example.c example_wrap.c -I/usr/local/include \
-L/usr/local/lib -ltcl -lsocket -ldl -lm -o my_tclsh
unix % my_tclsh
% puts $My_variable
3.0
% fact 5
120
%
In this case, the new version of
tclsh is functionally identical to the original, but has new functions
added to it.
unix % swig -python example.i
Making wrappers for Python
unix % gcc -c example.c example_wrap.c \
-I/usr/local/include/python1.4 \
-I/usr/local/lib/python1.4/config
unix % ld -shared example.o example_wrap.o -o examplemodule.so
We can now use the Python module as follows :
>>> import example >>> example.fact(5) 120 >>> example.my_mod(7,3) 1 >>> example.get_time() 'Sun Feb 11 23:01:07 1996' >>>
unix % swig -perl5 example.i
Making wrappers for Perl5
unix % gcc -c example.c example_wrap.c \
-I/usr/lib/perl/solaris/5.003/CORE
unix % ld -G example.o example_wrap.o -o example.so
unix % perl
use example;
print $example::My_variable,"\n";
print example::fact(5),"\n";
print example.get_time(),"\n";
<ctrl-d>
3.0
120
Sun Feb 11 23:01:07 1996
unix %
unix % swig -tcl -module example example.c unix % gcc -c example.c example_wrap.c -I/usr/local/include unix % ld -shared example.o example_wrap.o -o example.so
/* example.i */
%title "Simple Example"
%{
/* Put header files here */
%}
%section "My Commands"
extern double My_variable; // This is an interesting variable
extern int fact(int n); // Computes n factorial
extern int my_mod(int x, int y); // Calculates x % y
extern char *get_time();
/* Returns the current time as a string */