Executive Summary
SWIG is an interface compiler that connects programs written in C,
C++, and Objective-C with scripting languages including Perl,
Python, and
Tcl/Tk. It works by taking the declarations commonly found in C/C++ header
files and using them to generate the glue code (wrappers) that scripting
languages need to access the underlying C/C++ code.
John Ousterhout has written a
paper
that describes the
benefits of scripting languages. SWIG makes it fairly easy to connect scripting
languages with C/C++ code.
You might use SWIG in a number of ways:
- Building more interesting C/C++ programs. Using SWIG, you can replace the main()
function of a C program with a scripting interpreter from which you can control your
application. This adds quite a lot of flexibility and makes it easier to build
extensible programs. When combined with Tk, you can also build graphical user interfaces.
- Rapid prototyping and debugging. SWIG allows C/C++ programs to be placed in
a scripting environment that can be used for testing and debugging.
For example, you might test a library with a collection of scripts or use the scripting
interpreter as an interactive debugger. Since SWIG requires no modifications to the
underlying C code, it can be used even if the final product does not rely upon scripting.
- Systems integration. Scripting languages work fairly well for controlling and gluing
software components together. With SWIG, different C/C++ programs can be turned into
scripting language extension modules. These modules can then be combined together
to create new and interesting applications.
SWIG is sometimes compared to interface definition language (IDL)
compilers such as those you would find with systems such as CORBA and
COM. Although there are a few similarities, the whole point of SWIG
is to make it so you don't have to screw around with that stuff. If
anything, it's much more of a rapid application development and
prototyping tool. Specifically:
- ANSI C/C++ syntax. SWIG parses a form of ANSI C
syntax that has been extended with a number of special directives.
As a result, interfaces are usually built by grabbing a header file
and tweaking it a little bit.
- SWIG is not a stub generator. SWIG produces code that you
simply compile and run. You don't have to fill in any stubs or write
special code as you do with RPC-like systems.
- Designed to work with existing C/C++ code. SWIG requires little, if any, modifications
to existing code. For the most part, it encourages you to keep a clean separation between
C/C++ and its scripting interface.
- Extensibility. SWIG provides a variety of customization options that
allow you to blow your whole leg off. SWIG does not enforce any rules related to programming
morality.
A number of papers and tutorials describing SWIG are available.
You can also view a simple tutorial to see an
example of SWIG in action.