blob: 0140bfa5750c1b395d741e0cf63ae50f709a7859 [file] [log] [blame]
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Introduction</title>
<link rel="stylesheet" type="text/css" href="style.css">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body bgcolor="#ffffff">
<H1><a name="Introduction">2 Introduction</a></H1>
<!-- INDEX -->
<div class="sectiontoc">
<ul>
<li><a href="#Introduction_nn2">What is SWIG?</a>
<li><a href="#Introduction_nn3">Why use SWIG?</a>
<li><a href="#Introduction_nn4">A SWIG example</a>
<ul>
<li><a href="#Introduction_nn5">SWIG interface file</a>
<li><a href="#Introduction_nn6">The swig command</a>
<li><a href="#Introduction_nn7">Building a Perl5 module</a>
<li><a href="#Introduction_nn8">Building a Python module</a>
<li><a href="#Introduction_nn9">Shortcuts</a>
</ul>
<li><a href="#Introduction_nn10">Supported C/C++ language features</a>
<li><a href="#Introduction_nn11">Non-intrusive interface building</a>
<li><a href="#Introduction_build_system">Incorporating SWIG into a build system</a>
<li><a href="#Introduction_nn12">Hands off code generation</a>
<li><a href="#Introduction_nn13">SWIG and freedom</a>
</ul>
</div>
<!-- INDEX -->
<H2><a name="Introduction_nn2">2.1 What is SWIG?</a></H2>
<p>
SWIG is a software development tool that simplifies the task of
interfacing different languages to C and C++ programs. In a
nutshell, SWIG is a compiler that takes C/C++ declarations and creates
the wrappers needed to access those declarations from other languages
including Perl, Python, Tcl, Ruby, Guile, and Java. SWIG normally
requires no modifications to existing code and can often be used to
build a usable interface in only a few minutes. Possible applications
of SWIG include:
</p>
<ul>
<li>Building interpreted interfaces to existing C programs.
<li>Rapid prototyping and application development.
<li>Interactive debugging.
<li>Reengineering or refactoring of legacy software into scripting language components.
<li>Making a graphical user interface (using Tk for example).
<li>Testing of C libraries and programs (using scripts).
<li>Building high performance C modules for scripting languages.
<li>Making C programming more enjoyable (or tolerable depending on your point of view).
<li>Impressing your friends.
<li>Obtaining vast sums of research funding (although obviously not applicable to the author).
</ul>
<p>
SWIG was originally designed to make it extremely easy for scientists
and engineers to build extensible scientific software without having to get a
degree in software engineering. Because of this, the use of
SWIG tends to be somewhat informal and ad-hoc (e.g., SWIG does not
require users to provide formal interface specifications as you would find in
a dedicated IDL compiler). Although
this style of development isn't appropriate for every
project, it is particularly well suited to software development in the
small; especially the research and development work that is commonly found
in scientific and engineering projects. However, nowadays SWIG is known to be used in many
large open source and commercial projects.
<H2><a name="Introduction_nn3">2.2 Why use SWIG?</a></H2>
<p>
As stated in the previous section, the primary purpose of SWIG is to simplify
the task of integrating C/C++ with other programming languages. However, why would
anyone want to do that? To answer that question, it is useful to list a few strengths
of C/C++ programming:
</p>
<ul>
<li>Excellent support for writing programming libraries.
<li>High performance (number crunching, data processing, graphics, etc.).
<li>Systems programming and systems integration.
<li>Large user community and software base.
</ul>
<p>
Next, let's list a few problems with C/C++ programming
</p>
<ul>
<li>Writing a user interface is rather painful (i.e., consider programming with MFC, X11, GTK, or any number
of other libraries).
<li>Testing is time consuming (the compile/debug cycle).
<li>Not easy to reconfigure or customize without recompilation.
<li>Modularization can be tricky.
<li>Security concerns (buffer overflows for instance).
</ul>
<p>
To address these limitations, many programmers have arrived at the
conclusion that it is much easier to use different programming
languages for different tasks. For instance, writing a graphical user
interface may be significantly easier in a scripting language like
Python or Tcl (consider the reasons why millions of programmers have used languages like
Visual Basic if you need more proof). An interactive interpreter might also serve as a
useful debugging and testing tool. Other languages like Java might
greatly simplify the task of writing distributed computing software.
The key point is that different programming languages offer different
strengths and weaknesses. Moreover, it is extremely unlikely that any
programming is ever going to be perfect. Therefore, by combining
languages together, you can utilize the best features of each language
and greatly simplify certain aspects of software development.
</p>
<p>
From the standpoint of C/C++, a lot of people use SWIG because they want to break
out of the traditional monolithic C programming model which usually results
in programs that resemble this:
<ul>
<li>A collection of functions and variables that do something useful.
<li>A <tt>main()</tt> program that starts everything.
<li>A horrible collection of hacks that form some kind of user interface (but
which no-one really wants to touch).
</ul>
<p>
Instead of going down that route, incorporating C/C++ into a higher level language
often results in a more modular design, less code, better flexibility, and increased
programmer productivity.
</p>
<p>
SWIG tries to make the problem of C/C++ integration as painless as possible.
This allows you to focus on the underlying C
program and using the high-level language interface, but not
the tedious and complex chore of making the two languages talk to each
other. At the same time, SWIG recognizes that all applications are different. Therefore,
it provides a wide variety of customization features that let you change almost
every aspect of the language bindings. This is the main reason why SWIG has such a large
user manual ;-).
<H2><a name="Introduction_nn4">2.3 A SWIG example</a></H2>
<p>
The best way to illustrate SWIG is with a simple example. Consider the
following C code:
</p>
<div class="code"><pre>
/* File : example.c */
double My_variable = 3.0;
/* Compute factorial of n */
int fact(int n) {
if (n &lt;= 1)
return 1;
else
return n*fact(n-1);
}
/* Compute n mod m */
int my_mod(int n, int m) {
return(n % m);
}
</pre></div>
<p>
Suppose that you wanted to access these functions and the global
variable <tt>My_variable</tt> from Tcl. You start by making a SWIG
interface file as shown below (by convention, these files carry a .i
suffix) :
<H3><a name="Introduction_nn5">2.3.1 SWIG interface file</a></H3>
<div class="code"><pre>
/* File : example.i */
%module example
%{
/* Put headers and other declarations here */
extern double My_variable;
extern int fact(int);
extern int my_mod(int n, int m);
%}
extern double My_variable;
extern int fact(int);
extern int my_mod(int n, int m);
</pre></div>
<p>
The interface file contains ANSI C function prototypes and variable
declarations. The <tt>%module</tt> directive defines the name of the
module that will be created by SWIG. The <tt>%{ %}</tt> block
provides a location for inserting additional code, such as C header
files or additional C declarations, into the generated C wrapper code.
<H3><a name="Introduction_nn6">2.3.2 The swig command</a></H3>
<p>
SWIG is invoked using the <tt>swig</tt> command. We can use this to
build a Tcl module (under Linux) as follows :
</p>
<div class="shell"><pre>
unix &gt; <b>swig -tcl example.i</b>
unix &gt; <b>gcc -c -fpic example.c example_wrap.c -I/usr/local/include</b>
unix &gt; <b>gcc -shared example.o example_wrap.o -o example.so</b>
unix &gt; <b>tclsh</b>
% <b>load ./example.so</b>
% <b>fact 4</b>
24
% <b>my_mod 23 7</b>
2
% <b>expr $My_variable + 4.5</b>
7.5
%
</pre></div>
<p>
The <tt>swig</tt> command produced a new file called
<tt>example_wrap.c</tt> that should be compiled along with the
<tt>example.c</tt> file. Most operating systems and scripting
languages now support dynamic loading of modules. In our example, our
Tcl module has been compiled into a shared library that can be loaded
into Tcl. When loaded, Tcl can now access the functions
and variables declared in the SWIG interface. A look at the file
<tt>example_wrap.c</tt> reveals a hideous mess. However, you
almost never need to worry about it.
<H3><a name="Introduction_nn7">2.3.3 Building a Perl5 module</a></H3>
<p>
Now, let's turn these functions into a Perl5 module. Without making
any changes type the following (shown for Solaris):
</p>
<div class="shell"><pre>
unix &gt; <b>swig -perl5 example.i</b>
unix &gt; <b>gcc -c example.c example_wrap.c \
-I/usr/local/lib/perl5/sun4-solaris/5.003/CORE</b>
unix &gt; <b>ld -G example.o example_wrap.o -o example.so</b> # This is for Solaris
unix &gt; <b>perl5.003
use example;
print example::fact(4), "\n";
print example::my_mod(23, 7), "\n";
print $example::My_variable + 4.5, "\n";
&lt;ctrl-d&gt;</b>
24
2
7.5
unix &gt;
</pre></div>
<H3><a name="Introduction_nn8">2.3.4 Building a Python module</a></H3>
<p>
Finally, let's build a module for Python (shown for Irix).
</p>
<div class="shell"><pre>
unix &gt; <b>swig -python example.i</b>
unix &gt; <b>gcc -c -fpic example.c example_wrap.c -I/usr/local/include/python2.0</b>
unix &gt; <b>gcc -shared example.o example_wrap.o -o _example.so</b>
unix &gt; <b>python</b>
Python 2.0 (#6, Feb 21 2001, 13:29:45)
[GCC egcs-2.91.66 19990314/Linux (egcs-1.1.2 release)] on linux2
Type "copyright", "credits" or "license" for more information.
&gt;&gt;&gt; <b>import example</b>
&gt;&gt;&gt; <b>example.fact(4)</b>
24
&gt;&gt;&gt; <b>example.my_mod(23, 7)</b>
2
&gt;&gt;&gt; <b>example.cvar.My_variable + 4.5</b>
7.5
</pre></div>
<H3><a name="Introduction_nn9">2.3.5 Shortcuts</a></H3>
<p>
To the truly lazy programmer, one may wonder why we needed the extra
interface file at all. As it turns out, you can often do without
it. For example, you could also build a Perl5 module by just running
SWIG on the C header file and specifying a module name as follows
</p>
<div class="shell"><pre>
unix &gt; <b>swig -perl5 -module example example.h</b>
unix &gt; <b>gcc -c example.c example_wrap.c \
-I/usr/local/lib/perl5/sun4-solaris/5.003/CORE</b>
unix &gt; <b>ld -G example.o example_wrap.o -o example.so</b>
unix &gt; <b>perl5.003
use example;
print example::fact(4), "\n";
print example::my_mod(23, 7), "\n";
print $example::My_variable + 4.5, "\n";
&lt;ctrl-d&gt;</b>
24
2
7.5
</pre></div>
<H2><a name="Introduction_nn10">2.4 Supported C/C++ language features</a></H2>
<p>
A primary goal of the SWIG project is to make the language binding
process extremely easy. Although a few simple examples have been shown,
SWIG is quite capable in supporting most of C++. Some of the
major features include:
</p>
<ul>
<li>Full C99 preprocessing.
<li>All ANSI C and C++ datatypes.
<li>Functions, variables, and constants.
<li>Classes.
<li>Single and multiple inheritance.
<li>Overloaded functions and methods.
<li>Overloaded operators.
<li>C++ templates (including member templates, specialization, and partial specialization).
<li>Namespaces.
<li>Variable length arguments.
<li>C++ smart pointers.
</ul>
<p>
Most of C++11 is also supported. Details are in the <a href="CPlusPlus11.html#CPlusPlus11">C++11</a> section.
</p>
<p>
It is important to stress that SWIG is not a simplistic C++ lexing
tool like several apparently similar wrapper generation tools. SWIG
not only parses C++, it implements the full C++ type system and it is
able to understand C++ semantics. SWIG generates its wrappers with
full knowledge of this information. As a result, you will find SWIG
to be just as capable of dealing with nasty corner cases as it is in
wrapping simple C++ code. In fact, SWIG is able to handle C++ code that
stresses the very limits of many C++ compilers.
<H2><a name="Introduction_nn11">2.5 Non-intrusive interface building</a></H2>
<p>
When used as intended, SWIG requires minimal (if any) modification to
existing C or C++ code. This makes SWIG extremely easy to use with existing
packages and promotes software reuse and modularity. By making
the C/C++ code independent of the high level interface, you can change the
interface and reuse the code in other applications. It is also
possible to support different types of interfaces depending on the application.
</p>
<H2><a name="Introduction_build_system">2.6 Incorporating SWIG into a build system</a></H2>
<p>
SWIG is a command line tool and as such can be incorporated into any build system that supports invoking external tools/compilers.
SWIG is most commonly invoked from within a Makefile, but is also known to be invoked from popular IDEs such as
Microsoft Visual Studio.
</p>
<p>
If you are using the GNU Autotools
(<a href="http://www.gnu.org/software/autoconf/">Autoconf</a>/
<a href="http://www.gnu.org/software/automake/">Automake</a>/
<a href="http://www.gnu.org/software/libtool/">Libtool</a>)
to configure SWIG use in your project, the SWIG Autoconf macros can be used.
The primary macro is <tt>ax_pkg_swig</tt>, see
<a href="http://www.gnu.org/software/autoconf-archive/ax_pkg_swig.html#ax_pkg_swig">http://www.gnu.org/software/autoconf-archive/ax_pkg_swig.html#ax_pkg_swig</a>.
The <tt>ax_python_devel</tt> macro is also helpful for generating Python extensions. See the
<a href="http://www.gnu.org/software/autoconf-archive/">Autoconf Archive</a>
for further information on this and other Autoconf macros.
</p>
<p>
There is growing support for SWIG in some build tools, for example <a href="http://cmake.org">CMake</a>
is a cross-platform, open-source build manager with built in support for SWIG. CMake can detect the SWIG executable
and many of the target language libraries for linking against.
CMake knows how to build shared libraries and loadable modules on many different operating systems.
This allows easy cross platform SWIG development. It can also generate the custom commands necessary for
driving SWIG from IDEs and makefiles. All of this can be done from a single cross platform input file.
The following example is a CMake input file for creating a python wrapper for the SWIG interface file, example.i:
</p>
<div class="code"><pre>
# This is a CMake example for Python
FIND_PACKAGE(SWIG REQUIRED)
INCLUDE(${SWIG_USE_FILE})
FIND_PACKAGE(PythonLibs)
INCLUDE_DIRECTORIES(${PYTHON_INCLUDE_PATH})
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR})
SET(CMAKE_SWIG_FLAGS "")
SET_SOURCE_FILES_PROPERTIES(example.i PROPERTIES CPLUSPLUS ON)
SET_SOURCE_FILES_PROPERTIES(example.i PROPERTIES SWIG_FLAGS "-includeall")
SWIG_ADD_MODULE(example python example.i example.cxx)
SWIG_LINK_LIBRARIES(example ${PYTHON_LIBRARIES})
</pre></div>
<p>
The above example will generate native build files such as makefiles, nmake files and Visual Studio projects
which will invoke SWIG and compile the generated C++ files into _example.so (UNIX) or _example.pyd (Windows).
For other target languages on Windows a dll, instead of a .pyd file, is usually generated.
</p>
<H2><a name="Introduction_nn12">2.7 Hands off code generation</a></H2>
<p>
SWIG is designed to produce working code that needs no
hand-modification (in fact, if you look at the output, you probably
won't want to modify it). You should think of your target language interface being
defined entirely by the input to SWIG, not the resulting output
file. While this approach may limit flexibility for hard-core hackers,
it allows others to forget about the low-level implementation
details.
</p>
<H2><a name="Introduction_nn13">2.8 SWIG and freedom</a></H2>
<p>
No, this isn't a special section on the sorry state of world politics.
However, it may be useful to know that SWIG was written with a
certain "philosophy" about programming---namely that programmers are
smart and that tools should just stay out of their way. Because of
that, you will find that SWIG is extremely permissive in what it lets
you get away with. In fact, you can use SWIG to go well beyond
"shooting yourself in the foot" if dangerous programming is your goal.
On the other hand, this kind of freedom may be exactly what is needed
to work with complicated and unusual C/C++ applications.
</p>
<p>
Ironically, the freedom that SWIG provides is countered by an
extremely conservative approach to code generation. At its core, SWIG
tries to distill even the most advanced C++ code down to a small
well-defined set of interface building techniques based on ANSI C
programming. Because of this, you will find that SWIG interfaces can
be easily compiled by virtually every C/C++ compiler and that they can
be used on any platform. Again, this is an important part of staying out
of the programmer's way----the last thing any developer wants to do is
to spend their time debugging the output of a tool that relies on
non-portable or unreliable programming features.
Dependencies are often a source of incompatibilities and problems and so
additional third party libraries are not used in the generated code.
SWIG will also generally avoid generating code that introduces a dependency
on the C++ Standard Template Library (STL).
SWIG will generate code that depends on the C libraries though.
</p>
</body>
</html>