PageRenderTime 33ms CodeModel.GetById 23ms app.highlight 5ms RepoModel.GetById 1ms app.codeStats 0ms

/trunk/Doc/Manual/Introduction.html

#
HTML | 463 lines | 382 code | 79 blank | 2 comment | 0 complexity | 50c1a175435e34e12ae7a6291c0efcf6 MD5 | raw file
  1<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
  2<html>
  3<head>
  4<title>Introduction</title>
  5<link rel="stylesheet" type="text/css" href="style.css">
  6</head>
  7
  8<body bgcolor="#ffffff">
  9<H1><a name="Introduction"></a>2 Introduction</H1>
 10<!-- INDEX -->
 11<div class="sectiontoc">
 12<ul>
 13<li><a href="#Introduction_nn2">What is SWIG?</a>
 14<li><a href="#Introduction_nn3">Why use SWIG?</a>
 15<li><a href="#Introduction_nn4">A SWIG example</a>
 16<ul>
 17<li><a href="#Introduction_nn5">SWIG interface file</a>
 18<li><a href="#Introduction_nn6">The swig command</a>
 19<li><a href="#Introduction_nn7">Building a Perl5 module</a>
 20<li><a href="#Introduction_nn8">Building a Python module</a>
 21<li><a href="#Introduction_nn9">Shortcuts</a>
 22</ul>
 23<li><a href="#Introduction_nn10">Supported C/C++ language features</a>
 24<li><a href="#Introduction_nn11">Non-intrusive interface building</a>
 25<li><a href="#Introduction_build_system">Incorporating SWIG into a build system</a>
 26<li><a href="#Introduction_nn12">Hands off code generation</a>
 27<li><a href="#Introduction_nn13">SWIG and freedom</a>
 28</ul>
 29</div>
 30<!-- INDEX -->
 31
 32
 33
 34<H2><a name="Introduction_nn2"></a>2.1 What is SWIG?</H2>
 35
 36
 37<p>
 38SWIG is a software development tool that simplifies the task of
 39interfacing different languages to C and C++ programs.  In a
 40nutshell, SWIG is a compiler that takes C/C++ declarations and creates
 41the wrappers needed to access those declarations from other languages including
 42including Perl, Python, Tcl, Ruby, Guile, and Java.  SWIG normally
 43requires no modifications to existing code and can often be used to
 44build a usable interface in only a few minutes.  Possible applications
 45of SWIG include:
 46</p>
 47
 48<ul>
 49<li>Building interpreted interfaces to existing C programs.
 50<li>Rapid prototyping and application development.
 51<li>Interactive debugging.
 52<li>Reengineering or refactoring of legacy software into a scripting language components.
 53<li>Making a graphical user interface (using Tk for example).
 54<li>Testing of C libraries and programs (using scripts).
 55<li>Building high performance C modules for scripting languages.
 56<li>Making C programming more enjoyable (or tolerable depending on your point of view).
 57<li>Impressing your friends.
 58<li>Obtaining vast sums of research funding (although obviously not applicable to the author).
 59</ul>
 60
 61<p>
 62SWIG was originally designed to make it extremely easy for scientists
 63and engineers to build extensible scientific software without having to get a
 64degree in software engineering.  Because of this, the use of
 65SWIG tends to be somewhat informal and ad-hoc (e.g., SWIG does not
 66require users to provide formal interface specifications as you would find in
 67a dedicated IDL compiler).  Although
 68this style of development isn't appropriate for every
 69project, it is particularly well suited to software development in the
 70small; especially the research and development work that is commonly found
 71in scientific and engineering projects. However, nowadays SWIG is known to be used in many
 72large open source and commercial projects.
 73
 74<H2><a name="Introduction_nn3"></a>2.2 Why use SWIG?</H2>
 75
 76
 77<p>
 78As stated in the previous section, the primary purpose of SWIG is to simplify
 79the task of integrating C/C++ with other programming languages.  However, why would
 80anyone want to do that?   To answer that question, it is useful to list a few strengths
 81of C/C++ programming:
 82</p>
 83
 84<ul>
 85<li>Excellent support for writing programming libraries.
 86<li>High performance (number crunching, data processing, graphics, etc.).
 87<li>Systems programming and systems integration.
 88<li>Large user community and software base.
 89</ul>
 90
 91<p>
 92Next, let's list a few problems with C/C++ programming
 93</p>
 94
 95<ul>
 96<li>Writing a user interface is rather painful (i.e., consider programming with MFC, X11, GTK, or any number
 97of other libraries).
 98<li>Testing is time consuming (the compile/debug cycle).
 99<li>Not easy to reconfigure or customize without recompilation.
100<li>Modularization can be tricky.
101<li>Security concerns (buffer overflow for instance).
102</ul>
103<p>
104To address these limitations, many programmers have arrived at the
105conclusion that it is much easier to use different programming
106languages for different tasks.  For instance, writing a graphical user
107interface may be significantly easier in a scripting language like
108Python or Tcl (consider the reasons why millions of programmers have used languages like
109Visual Basic if you need more proof). An interactive interpreter might also serve as a
110useful debugging and testing tool.  Other languages like Java might
111greatly simplify the task of writing distributed computing software.
112The key point is that different programming languages offer different
113strengths and weaknesses.  Moreover, it is extremely unlikely that any
114programming is ever going to be perfect.  Therefore, by combining
115languages together, you can utilize the best features of each language
116and greatly simplify certain aspects of software development.
117</p>
118
119<p>
120From the standpoint of C/C++, a lot of people use SWIG because they want to break
121out of the traditional monolithic C programming model which usually results
122in programs that resemble this:
123
124<ul>
125<li>A collection of functions and variables that do something useful.
126<li>A <tt>main()</tt> program that starts everything.
127<li>A horrible collection of hacks that form some kind of user interface (but 
128which no-one really wants to touch).
129</ul>
130<p>
131Instead of going down that route, incorporating C/C++ into a higher level language
132often results in a more modular design, less code, better flexibility, and increased
133programmer productivity.   
134</p>
135
136<p>
137SWIG tries to make the problem of C/C++ integration as painless as possible.
138This allows you to focus on the underlying C
139program and using the high-level language interface, but not
140the tedious and complex chore of making the two languages talk to each
141other.  At the same time, SWIG recognizes that all applications are different.  Therefore,
142it provides a wide variety of customization features that let you change almost
143every aspect of the language bindings.  This is the main reason why SWIG has such a large
144user manual ;-).
145
146<H2><a name="Introduction_nn4"></a>2.3 A SWIG example</H2>
147
148
149<p>
150The best way to illustrate SWIG is with a simple example. Consider the
151following C code:
152</p>
153
154<div class="code"><pre>
155/* File : example.c */
156
157double  My_variable  = 3.0;
158
159/* Compute factorial of n */
160int  fact(int n) {
161	if (n &lt;= 1) return 1;
162	else return n*fact(n-1);
163}
164
165/* Compute n mod m */
166int my_mod(int n, int m) {
167	return(n % m);
168}
169</pre></div>
170
171<p>
172Suppose that you wanted to access these functions and the global
173variable <tt>My_variable</tt> from Tcl.  You start by making a SWIG
174interface file as shown below (by convention, these files carry a .i
175suffix) :
176
177<H3><a name="Introduction_nn5"></a>2.3.1 SWIG interface file</H3>
178
179
180<div class="code"><pre>
181/* File : example.i */
182%module example
183%{
184/* Put headers and other declarations here */
185extern double My_variable;
186extern int    fact(int);
187extern int    my_mod(int n, int m);
188%}
189
190extern double My_variable;
191extern int    fact(int);
192extern int    my_mod(int n, int m);
193</pre></div>
194
195<p>
196The interface file contains ANSI C function prototypes and variable
197declarations.  The <tt>%module</tt> directive defines the name of the
198module that will be created by SWIG.  The <tt>%{ %}</tt> block
199provides a location for inserting additional code, such as C header
200files or additional C declarations, into the generated C wrapper code.
201
202<H3><a name="Introduction_nn6"></a>2.3.2 The swig command</H3>
203
204
205<p>
206SWIG is invoked using the <tt>swig</tt> command. We can use this to
207build a Tcl module (under Linux) as follows :
208</p>
209
210<div class="shell"><pre>
211unix &gt; <b>swig -tcl example.i</b>
212unix &gt; <b>gcc -c -fpic example.c example_wrap.c -I/usr/local/include</b>
213unix &gt; <b>gcc -shared example.o example_wrap.o -o example.so</b>
214unix &gt; <b>tclsh</b>
215% <b>load ./example.so</b>
216% <b>fact 4</b>
21724
218% <b>my_mod 23 7</b>
2192
220% <b>expr $My_variable + 4.5</b>
2217.5
222%
223</pre></div>
224	<p>
225
226The <tt>swig</tt> command produced a new file called
227<tt>example_wrap.c</tt> that should be compiled along with the
228<tt>example.c</tt> file.  Most operating systems and scripting
229languages now support dynamic loading of modules.  In our example, our
230Tcl module has been compiled into a shared library that can be loaded
231into Tcl.  When loaded, Tcl can now access the functions
232and variables declared in the SWIG interface.  A look at the file
233<tt>example_wrap.c</tt> reveals a hideous mess.  However, you 
234almost never need to worry about it.
235
236<H3><a name="Introduction_nn7"></a>2.3.3 Building a Perl5 module</H3>
237
238
239<p>
240Now, let's turn these functions into a Perl5 module. Without making
241any changes type the following (shown for Solaris):
242</p>
243
244<div class="shell"><pre>
245unix &gt; <b>swig -perl5 example.i</b>
246unix &gt; <b>gcc -c example.c example_wrap.c \
247	-I/usr/local/lib/perl5/sun4-solaris/5.003/CORE</b>
248unix &gt; <b>ld -G example.o example_wrap.o -o example.so</b>		# This is for Solaris
249unix &gt; <b>perl5.003
250use example;
251print example::fact(4), "\n";
252print example::my_mod(23,7), "\n";
253print $example::My_variable + 4.5, "\n";
254&lt;ctrl-d&gt;</b>
25524
2562
2577.5
258unix &gt;
259</pre></div>
260
261
262<H3><a name="Introduction_nn8"></a>2.3.4 Building a Python module</H3>
263
264
265<p>
266Finally, let's build a module for Python (shown for Irix).
267</p>
268
269<div class="shell"><pre>
270unix &gt; <b>swig -python example.i</b>
271unix &gt; <b>gcc -c -fpic example.c example_wrap.c -I/usr/local/include/python2.0</b>
272unix &gt; <b>gcc -shared example.o example_wrap.o -o _example.so</b>
273unix &gt; <b>python</b>
274Python 2.0 (#6, Feb 21 2001, 13:29:45)
275[GCC egcs-2.91.66 19990314/Linux (egcs-1.1.2 release)] on linux2
276Type "copyright", "credits" or "license" for more information.     
277&gt;&gt;&gt; <b>import example</b>
278&gt;&gt;&gt; <b>example.fact(4)</b>
27924
280&gt;&gt;&gt; <b>example.my_mod(23,7)</b>
2812
282&gt;&gt;&gt; <b>example.cvar.My_variable + 4.5</b>
2837.5
284</pre></div>
285
286<H3><a name="Introduction_nn9"></a>2.3.5 Shortcuts</H3>
287
288
289<p>
290To the truly lazy programmer, one may wonder why we needed the extra
291interface file at all. As it turns out, you can often do without
292it. For example, you could also build a Perl5 module by just running
293SWIG on the C header file and specifying a module name as follows
294</p>
295
296<div class="shell"><pre>
297unix &gt; <b>swig -perl5 -module example example.h</b>
298unix &gt; <b>gcc -c example.c example_wrap.c \
299	-I/usr/local/lib/perl5/sun4-solaris/5.003/CORE</b>
300unix &gt; <b>ld -G example.o example_wrap.o -o example.so</b>
301unix &gt; <b>perl5.003
302use example;
303print example::fact(4), "\n";
304print example::my_mod(23,7), "\n";
305print $example::My_variable + 4.5, "\n";
306&lt;ctrl-d&gt;</b>
30724
3082
3097.5
310</pre></div>
311
312<H2><a name="Introduction_nn10"></a>2.4 Supported C/C++ language features</H2>
313
314
315<p>
316A primary goal of the SWIG project is to make the language binding
317process extremely easy.  Although a few simple examples have been shown,
318SWIG is quite capable in supporting most of C++.  Some of the
319major features include:
320</p>
321
322<ul>
323<li>Full C99 preprocessing.
324<li>All ANSI C and C++ datatypes.
325<li>Functions, variables, and constants.
326<li>Classes.
327<li>Single and multiple inheritance.
328<li>Overloaded functions and methods.
329<li>Overloaded operators.
330<li>C++ templates (including member templates, specialization, and partial specialization).
331<li>Namespaces.
332<li>Variable length arguments.
333<li>C++ smart pointers.
334</ul>
335
336<p>
337Currently, the only major C++ feature not supported is nested classes--a limitation
338that should be removed in a future release, but has some workarounds for the moment.
339</p>
340
341<p>
342It is important to stress that SWIG is not a simplistic C++ lexing
343tool like several apparently similar wrapper generation tools.  SWIG
344not only parses C++, it implements the full C++ type system and it is
345able to understand C++ semantics.  SWIG generates its wrappers with
346full knowledge of this information.  As a result, you will find SWIG
347to be just as capable of dealing with nasty corner cases as it is in
348wrapping simple C++ code.  In fact, SWIG is able handle C++ code that
349stresses the very limits of many C++ compilers.
350
351
352<H2><a name="Introduction_nn11"></a>2.5 Non-intrusive interface building</H2>
353
354
355<p>
356When used as intended, SWIG requires minimal (if any) modification to
357existing C or C++ code. This makes SWIG extremely easy to use with existing
358packages and promotes software reuse and modularity. By making
359the C/C++ code independent of the high level interface, you can change the
360interface and reuse the code in other applications.   It is also
361possible to support different types of interfaces depending on the application.
362</p>
363
364<H2><a name="Introduction_build_system"></a>2.6 Incorporating SWIG into a build system</H2>
365
366
367<p>
368SWIG is a command line tool and as such can be incorporated into any build system that supports invoking external tools/compilers.
369SWIG is most commonly invoked from within a Makefile, but is also known to be invoked from popular IDEs such as 
370Microsoft Visual Studio.
371</p>
372
373<p>
374If you are using the GNU Autotools 
375(<a href="http://www.gnu.org/software/autoconf/">Autoconf</a>/
376<a href="http://www.gnu.org/software/automake/">Automake</a>/
377<a href="http://www.gnu.org/software/libtool/">Libtool</a>)
378to configure SWIG use in your project, the SWIG Autoconf macros can be used.
379The primary macro is <tt>ax_pkg_swig</tt>, see
380<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>.
381The <tt>ax_python_devel</tt> macro is also helpful for generating Python extensions. See the 
382<a href="http://www.gnu.org/software/autoconf-archive/">Autoconf Archive</a>
383for further information on this and other Autoconf macros.
384</p>
385
386<p>
387There is growing support for SWIG in some build tools, for example <a href="http://www.cmake.org">CMake</a>
388is a cross-platform, open-source build manager with built in support for SWIG. CMake can detect the SWIG executable
389and many of the target language libraries for linking against.
390CMake knows how to build shared libraries and loadable modules on many different operating systems.
391This allows easy cross platform SWIG development.  It also can generate the custom commands necessary for
392driving SWIG from IDE's and makefiles.  All of this can be done from a single cross platform input file.
393The following example is a CMake input file for creating a python wrapper for the SWIG interface file, example.i:
394</p>
395
396<div class="code"><pre>
397
398# This is a CMake example for Python
399
400FIND_PACKAGE(SWIG REQUIRED)
401INCLUDE(${SWIG_USE_FILE})
402
403FIND_PACKAGE(PythonLibs)
404INCLUDE_DIRECTORIES(${PYTHON_INCLUDE_PATH})
405
406INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR})
407
408SET(CMAKE_SWIG_FLAGS "")
409
410SET_SOURCE_FILES_PROPERTIES(example.i PROPERTIES CPLUSPLUS ON)
411SET_SOURCE_FILES_PROPERTIES(example.i PROPERTIES SWIG_FLAGS "-includeall")
412SWIG_ADD_MODULE(example python example.i example.cxx)
413SWIG_LINK_LIBRARIES(example ${PYTHON_LIBRARIES})
414
415</pre></div>
416<p>
417The above example will generate native build files such as makefiles, nmake files and Visual Studio projects
418which will invoke SWIG and compile the generated C++ files into _example.so (UNIX) or _example.pyd (Windows).
419For other target languages on Windows a dll, instead of a .pyd file, is usually generated.
420</p>
421
422<H2><a name="Introduction_nn12"></a>2.7 Hands off code generation</H2>
423
424
425<p>
426SWIG is designed to produce working code that needs no
427hand-modification (in fact, if you look at the output, you probably
428won't want to modify it). You should think of your target language interface being
429defined entirely by the input to SWIG, not the resulting output
430file. While this approach may limit flexibility for hard-core hackers,
431it allows others to forget about the low-level implementation
432details.
433</p>
434
435<H2><a name="Introduction_nn13"></a>2.8 SWIG and freedom</H2>
436
437
438<p>
439No, this isn't a special section on the sorry state of world politics.
440However, it may be useful to know that SWIG was written with a
441certain "philosophy" about programming---namely that programmers are
442smart and that tools should just stay out of their way.  Because of
443that, you will find that SWIG is extremely permissive in what it lets
444you get away with. In fact, you can use SWIG to go well beyond
445"shooting yourself in the foot" if dangerous programming is your goal.
446On the other hand, this kind of freedom may be exactly what is needed
447to work with complicated and unusual C/C++ applications.
448</p>
449
450<p>
451Ironically, the freedom that SWIG provides is countered by an
452extremely conservative approach to code generation. At it's core, SWIG
453tries to distill even the most advanced C++ code down to a small
454well-defined set of interface building techniques based on ANSI C
455programming.  Because of this, you will find that SWIG interfaces can
456be easily compiled by virtually every C/C++ compiler and that they can
457be used on any platform.  Again, this is an important part of staying out 
458of the programmer's way----the last thing any developer wants to do is
459to spend their time debugging the output of a tool that relies on 
460non-portable or unreliable programming features.
461
462</body>
463</html>