1
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
3
4
<title>SWIG Basics</title>
6
7
<body bgcolor="#ffffff">
8
<a name="n1"></a><H1>4 SWIG Basics</H1>
11
<li><a href="#n2">Running SWIG</a>
13
<li><a href="#n3">Input format</a>
14
<li><a href="#n4">SWIG Output</a>
15
<li><a href="#n5">Comments</a>
16
<li><a href="#n6">C Preprocessor</a>
17
<li><a href="#n7">SWIG Directives</a>
18
<li><a href="#n8">Parser Limitations</a>
20
<li><a href="#n9">Wrapping Simple C Declarations</a>
22
<li><a href="#n10">Basic Type Handling</a>
23
<li><a href="#n11">Global Variables</a>
24
<li><a href="#n12">Constants</a>
25
<li><a href="#n13">A brief word about <tt>const</tt></a>
26
<li><a href="#n14">A cautionary tale of <tt>char *</tt></a>
28
<li><a href="#n15">Pointers and complex objects</a>
30
<li><a href="#n16">Simple pointers</a>
31
<li><a href="#n17">Run time pointer type checking</a>
32
<li><a href="#n18">Derived types, structs, and classes</a>
33
<li><a href="#n19">Undefined datatypes</a>
34
<li><a href="#n20">Typedef</a>
36
<li><a href="#n21">Other Practicalities</a>
38
<li><a href="#n22">Passing structures by value</a>
39
<li><a href="#n23">Return by value</a>
40
<li><a href="#n24">Linking to structure variables</a>
41
<li><a href="#n25">Linking to <tt>char *</tt></a>
42
<li><a href="#n26">Arrays</a>
43
<li><a href="#n27">Creating read-only variables</a>
44
<li><a href="#n28">Renaming and ignoring declarations</a>
45
<li><a href="#n29">Default/optional arguments</a>
46
<li><a href="#n30">Pointers to functions and callbacks</a>
48
<li><a href="#n31">Structures and unions</a>
50
<li><a href="#n32">Typedef and structures</a>
51
<li><a href="#n33">Character strings and structures</a>
52
<li><a href="#n34">Array members</a>
53
<li><a href="#n35">Structure data members</a>
54
<li><a href="#n36">C constructors and destructors </a>
55
<li><a href="#n37">Adding member functions to C structures</a>
56
<li><a href="#n38">Nested structures</a>
57
<li><a href="#n39">Other things to note about structure wrapping</a>
59
<li><a href="#n40">Code Insertion</a>
61
<li><a href="#n41">The output of SWIG</a>
62
<li><a href="#n42">Code insertion blocks</a>
63
<li><a href="#n43">Inlined code blocks</a>
64
<li><a href="#n44">Initialization blocks</a>
66
<li><a href="#n45">An Interface Building Strategy</a>
68
<li><a href="#n46">Preparing a C program for SWIG</a>
69
<li><a href="#n47">The SWIG interface file</a>
70
<li><a href="#n48">Why use separate interface files?</a>
71
<li><a href="#n49">Getting the right header files</a>
72
<li><a href="#n50">What to do with main()</a>
9
79
This chapter describes the basic operation of SWIG, the structure of its
10
80
input files, and how it handles standard ANSI C declarations. C++ support is
22
93
<blockquote><pre>swig [ <em>options</em> ] filename
24
-tcl Generate Tcl wrappers
25
-perl Generate Perl5 wrappers
26
-python Generate Python wrappers
95
-chicken Generate CHICKEN wrappers
96
-csharp Generate C# wrappers
27
97
-guile Generate Guile wrappers
28
-ruby Generate Ruby wrappers
29
98
-java Generate Java wrappers
30
-mzscheme Generate mzscheme wrappers
99
-mzscheme Generate Mzscheme wrappers
100
-ocaml Generate Ocaml wrappers
101
-perl Generate Perl wrappers
31
102
-php Generate PHP wrappers
103
-pike Generate Pike wrappers
104
-python Generate Python wrappers
105
-ruby Generate Ruby wrappers
106
-sexp Generate Lisp S-Expressions wrappers
107
-tcl Generate Tcl wrappers
108
-xml Generate XML wrappers
32
109
-c++ Enable C++ parsing
110
-D<em>symbol</em> Define a preprocessor symbol
111
-Fstandard Display error/warning messages in commonly used format
112
-Fmicrosoft Display error/warning messages in Microsoft format
113
-help Display all options
33
114
-I<em>dir</em> Add a directory to the file include path
34
115
-l<em>file</em> Include a SWIG library file.
35
-c Generate raw wrapper code (omit supporting code)
116
-module <em>name</em> Set the name of the SWIG module
117
-noruntime Generate raw wrapper code (omit supporting code)
36
118
-o <em>outfile</em> Name of output file
37
-module <em>name</em> Set the name of the SWIG module
38
-D<em>symbol</em> Define a preprocessor symbol
119
-outdir <em>dir</em> Set language specific files output directory
120
-swiglib Show location of SWIG library
39
121
-version Show SWIG version number
40
-swiglib Show location of SWIG library
41
-help Display all options
43
123
</pre></blockquote>
45
Additional options are often defined for each target language. A full list
125
This is a subset of commandline options.
126
Additional options are also defined for each target language. A full list
46
127
can be obtained by typing <tt>swig -help</tt> or <tt>swig
47
128
-<em>lang</em> -help</tt>.
130
<a name="n3"></a><H3>4.1.1 Input format</H3>
51
133
As input, SWIG expects a file containing ANSI C/C++ declarations and
52
134
special SWIG directives. More often than not, this is a special SWIG
79
161
<tt>%module</tt> directive.
82
Everything in the <tt>%{ ... %}</tt> block is simply copied to the
83
resulting output file. The enclosed text is not parsed or interpreted
84
by SWIG. Although the use of a <tt>%{,%}</tt> block is optional, most
85
interface files have one to include header files and other supporting
86
C declarations. The <tt>%{...%}</tt> syntax and
87
semantics in SWIG is analogous to that of the declarations section used
88
in input files to parser generation tools such as yacc or bison.
164
Everything in the <tt>%{ ... %}</tt> block is simply copied verbatim
165
to the resulting wrapper file created by SWIG. This section is almost
166
always used to include header files and other declarations that are
167
required to make the generated wrapper code compile. It is important
168
to emphasize that just because you include a declaration in a SWIG
169
input file, that declaration does <em>not</em> automatically appear in
170
the generated wrapper code---therefore you need to make sure you
171
include the proper header files in the <tt>%{ ... %}</tt> section. It
172
should be noted that the text enclosed in <tt>%{ ... %}</tt> is not
173
parsed or interpreted by SWIG. The <tt>%{...%}</tt> syntax and
174
semantics in SWIG is analogous to that of the declarations section
175
used in input files to parser generation tools such as yacc or bison.
177
<a name="output"></a>
178
<a name="n4"></a><H3>4.1.2 SWIG Output</H3>
92
181
The output of SWIG is a C/C++ file that contains all of the wrapper
93
code needed to build an extension module. By default, an input file
182
code needed to build an extension module. SWIG may generate some
183
additional files depending on the target language. By default, an input file
94
184
with the name <tt>file.i</tt> is transformed into a file
95
185
<tt>file_wrap.c</tt> or <tt>file_wrap.cxx</tt> (depending on whether
96
186
or not the <tt>-c++</tt> option has been used). The name of the
104
194
$ swig -c++ -python -o example_wrap.cpp example.i</pre></blockquote>
107
The output file created by SWIG normally
197
The C/C++ output file created by SWIG often
108
198
contains everything that is needed to construct a extension module
109
for the target scripting language. SWIG is not a stub compiler nor is
199
for the target scripting language. SWIG is not a stub compiler nor is it
110
200
usually necessary to edit the output file (and if you look at the output,
111
201
you probably won't want to). To build the final extension module, the
112
202
SWIG output file is compiled and linked with the rest of your C/C++
113
203
program to create a shared library.
206
Many target languages will also generate proxy class files in the
207
target language. The default output directory for these language
208
specific files is the same directory as the generated C/C++ file. This can
209
can be modified using the <tt>-outdir</tt> option. For example:
212
$ swig -c++ -python -outdir pyfiles -o cppfiles/example_wrap.cpp example.i
215
If the directories <tt>cppfiles</tt> and <tt>pyfiles</tt> exist, the following
218
cppfiles/example_wrap.cpp
222
<a name="n5"></a><H3>4.1.3 Comments</H3>
117
225
C and C++ style comments may appear anywhere in interface files. In
118
226
previous versions of SWIG, comments were used to generate
119
227
documentation files. However, this feature is currently under repair
120
228
and will reappear in a later SWIG release.
122
<h3>C Preprocessor</h3>
230
<a name="n6"></a><H3>4.1.4 C Preprocessor</H3>
124
233
Like C, SWIG preprocesses all input files through an enhanced version
125
234
of the C preprocessor. All standard preprocessor features are
184
294
/* Non-conventional placement of storage specifier (extern) */
185
295
const int extern Number;
186
/* Function declaration with unnecessary grouping */
297
/* Extra declarator grouping */
298
Matrix (foo); // A global variable
300
/* Extra declarator grouping in parameters */
301
void bar(Spam (Grok)(Doh));
192
306
In practice, few (if any) C programmers actually write code like
193
is since this style is never featured in programming books. However,
194
if you're feeling particularly obfuscated, you can certainly break SWIG.
307
this since this style is never featured in programming books. However,
308
if you're feeling particularly obfuscated, you can certainly break SWIG (although why would you want to?).
197
311
<li>Running SWIG on C++ source files (what would appear in a .C or .cxx file)
198
312
is not recommended. Even though SWIG can parse C++ class declarations,
199
it does not like declarations that are decoupled from their
313
it ignores declarations that are decoupled from their
200
314
original class definition (the declarations are parsed, but a lot of warning
201
315
messages may be generated). For example:
632
<h2>Pointers and complex objects</h2>
743
<a name="n14"></a><H3>4.2.5 A cautionary tale of <tt>char *</tt></H3>
746
Before going any further, there is one bit of caution involving
747
<tt>char *</tt> that must now be mentioned. When strings are passed
748
from a scripting language to a C <tt>char *</tt>, the pointer usually
749
points to string data stored inside the interpreter. It is almost
750
always a really bad idea to modify this data. Furthermore, some
751
languages may explicitly disallow it. For instance, in Python,
752
strings are supposed be immutable. If you violate this, you will probably
753
receive a vast amount of wrath when you unleash your module on the world.
756
The primary source of problems are functions that might modify string data in place.
757
A classic example would be a function like this:
761
char *strcat(char *s, const char *t)
765
Although SWIG will certainly generate a wrapper for this, its behavior
766
will be undefined. In fact, it will probably cause your application
767
to crash with a segmentation fault or other memory related problem.
768
This is because <tt>s</tt> refers to some internal data in the target
769
language---data that you shouldn't be touching.
772
The bottom line: don't rely on <tt>char *</tt> for anything other than read-only
773
input values. However, it must be noted that you could change the behavior of SWIG
774
using <a href="Typemaps.html">typemaps</a>.
776
<a name="n15"></a><H2>4.3 Pointers and complex objects</H2>
634
779
Most C programs manipulate arrays, structures, and other types of objects. This section
635
780
discusses the handling of these datatypes.
637
<h3> Simple pointers</h3>
782
<a name="n16"></a><H3>4.3.1 Simple pointers</H3>
639
785
Pointers to primitive C datatypes such as <p>
1673
1862
discussed in a later chapter. In many cases, the warning message is
1676
<h3>C constructors and destructors </h3>
1865
<a name="n35"></a><H3>4.5.4 Structure data members</H3>
1868
Occasionally, a structure will contain data members that are themselves structures. For example:
1872
typedef struct Foo {
1876
typedef struct Bar {
1878
Foo f; /* struct member */
1883
When a structure member is wrapped, it is always handled as a pointer.
1888
Foo *Bar_f_get(Bar *b) {
1891
void Bar_f_set(Bar *b, Foo *value) {
1897
The reasons for this are somewhat subtle but have to do with the
1898
problem of modifying and accessing data inside the data member. For
1899
example, suppose you wanted to modify the value of <tt>f.x</tt>
1900
of a <tt>Bar</tt> object like this:
1909
Translating this assignment to function calls (as would be used inside the scripting
1910
language interface) results in the following code:
1915
Foo_x_set(Bar_f_get(b),37);
1919
In this code, if the <tt>Bar_f_get()</tt> function were to return a <tt>Foo</tt> instead of a
1920
<tt>Foo *</tt>, then the resulting modification would be applied to a <em>copy</em> of <tt>f</tt> and not
1921
the data member <tt>f</tt> itself. Clearly that's not what you want!
1924
It should be noted that this transformation to pointers only occurs if SWIG knows that a data member
1925
is a structure or class. For instance, if you had a structure like this,
1935
and nothing was known about <tt>WORD</tt>, then SWIG will generate more normal accessor functions
1940
WORD Foo_w_get(Foo *f) {
1943
void Foo_w_set(FOO *f, WORD value) {
1949
<b>Compatibility Note: </b> SWIG-1.3.11 and earlier releases transformed all non-primitive member datatypes
1950
to pointers. Starting in SWIG-1.3.12, this transformation <em>only</em> occurs if a datatype is known to be a structure,
1951
class, or union. This is unlikely to break existing code. However, if you need to tell SWIG that an undeclared
1952
datatype is really a struct, simply use a forward struct declaration such as <tt>"struct Foo;"</tt>.
1954
<a name="n36"></a><H3>4.5.5 C constructors and destructors </H3>
1678
1957
When wrapping structures, it is generally useful to have a mechanism
1679
1958
for creating and destroying objects. If you don't do anything, SWIG
1691
1970
<blockquote><pre>swig -no_default example.i
1693
1972
</pre></blockquote>
1696
1975
<blockquote><pre>%module foo
1698
%nodefault // Don't create default constructors/destructors
1977
%nodefault; // Don't create default constructors/destructors
1699
1978
... declarations ...
1700
%makedefault // Reenable default constructors/destructors
1979
%makedefault; // Reenable default constructors/destructors
1702
1980
</pre></blockquote>
1982
If you need more precise control, <tt>%nodefault</tt> can selectively target individual structure
1983
definitions. For example:
1987
%nodefault Foo; // No default constructor/destructors for Foo
1989
struct Foo { // No default generated.
1992
struct Bar { // Default constructor/destructor generated.
1704
1997
<b>Compatibility note:</b> Prior to SWIG-1.3.7, SWIG did not generate default constructors
1705
1998
or destructors unless you explicitly turned them on using <tt>-make_default</tt>.
1706
1999
However, it appears that most users want to have constructor and destructor functions so it
1707
2000
has now been enabled as the default behavior.
1709
<h3> Adding member functions to C structures</h3>
2002
<a name="n37"></a><H3>4.5.6 Adding member functions to C structures</H3>
1711
2005
Most languages provide a mechanism for creating classes and
1712
2006
supporting object oriented programming. From a C standpoint, object
2162
2469
</pre></blockquote>
2164
<h2>SWIG Preprocessor</h2>
2166
SWIG includes its own enhanced version of the C preprocessor. The preprocessor
2167
supports the standard preprocessor directives and macro expansion rules.
2168
However, a number of modifications and enhancements have been made. This
2169
section describes some of these modifications.
2171
<h3>File inclusion</h3>
2173
To include another file into a SWIG interface, use the <tt>%include</tt> directive
2178
%include "pointer.i"
2182
Unlike, <tt>#include</tt>, <tt>%include</tt> includes each file once (and will not
2183
reload the file on subsequent <tt>%include</tt> declarations). Therefore, it
2184
is not necessary to use include-guards in SWIG interfaces.
2187
By default, the <tt>#include</tt> is ignored unless you run SWIG with the
2188
<tt>-includeall</tt> option. The reason for ignoring traditional includes
2189
is that you often don't want SWIG to try and wrap everything included
2190
in standard header system headers and auxilliary files.
2192
<h3>File imports</h3>
2194
SWIG provides another file inclusion directive with the <tt>%import</tt> directive.
2203
The purpose of <tt>%import</tt> is to collect certain information from another
2204
SWIG interface file or a header file without actually generating any wrapper code.
2205
Such information generally includes type declarations (e.g., <tt>typedef</tt>) as well as
2206
C++ classes that might be used as base-classes for class declarations in the interface.
2207
The use of <tt>%import</tt> is also important when SWIG is used to generate
2208
extensions as a collection of related modules. This is advanced topic and is described
2212
The <tt>-importall</tt> directive tells SWIG to follow all <tt>#include</tt> statements
2213
as imports. This might be useful if you want to extract type definitions from system
2214
header files without generating any wrappers.
2216
<h3>Conditional Compilation</h3>
2218
SWIG fully supports the use of <tt>#if</tt>, <tt>#ifdef</tt>,
2219
<tt>#ifndef</tt>, <tt>#else</tt>, <tt>#endif</tt> to conditionally
2220
include parts of an interface. The following symbols are predefined
2221
by SWIG when it is parsing the interface:
2225
SWIG Always defined when SWIG is processing a file
2226
SWIGTCL Defined when using Tcl
2227
SWIGTCL8 Defined when using Tcl8.0
2228
SWIGPERL Defined when using Perl
2229
SWIGPERL5 Defined when using Perl5
2230
SWIGPYTHON Defined when using Python
2231
SWIGGUILE Defined when using Guile
2232
SWIGRUBY Defined when using Ruby
2233
SWIGJAVA Defined when using Java
2234
SWIGMZSCHEME Defined when using Mzscheme
2235
SWIGWIN Defined when running SWIG under Windows
2236
SWIGMAC Defined when running SWIG on the Macintosh
2239
In addition, SWIG defines the following set of standard C/C++ macros:
2243
__LINE__ Current line number
2244
__FILE__ Current file name
2245
__STDC__ Defined to indicate ANSI C
2246
__cplusplus Defined when -c++ option used
2250
Interface files can look at these symbols as necessary to change the
2251
way in which an interface is generated or to mix SWIG directives with
2252
C code. These symbols are also defined within the C code generated by
2253
SWIG (except for the symbol `<tt>SWIG</tt>' which is only defined
2254
within the SWIG compiler).<p>
2256
<h3>Macro Expansion</h3>
2258
Traditional preprocessor macros can be used in SWIG interfaces. Be aware that the <tt>#define</tt> statement
2259
is also used to try and detect constants. Therefore, if you have something like this in your file,
2269
you may get some extra constants such as <tt>_FOO_H</tt> showing up in the scripting interface.
2272
More complex macros can be defined in the standard way. For example:
2276
#define EXTERN extern
2278
#define _ANSI(args) (args)
2280
#define _ANSI(args) ()
2285
The following operators can appear in macro definitions:
2289
Converts macro argument <tt>x</tt> to a string surrounded by double quotes ("x").
2292
<li><tt>x ## y</tt><br>
2293
Concatenates x and y together to form <tt>xy</tt>.
2296
<li><tt>`x`</tt><br>
2297
If <tt>x</tt> is a string surrounded by double quotes, do nothing. Otherwise, turn into a string
2298
like <tt>#x</tt>. This is a non-standard SWIG extension.
2301
<h3>SWIG Macros</h3>
2303
SWIG provides an enhanced macro capability with the <tt>%define</tt> and <tt>%enddef</tt> directives.
2308
%define ARRAYHELPER(type,name)
2310
type *new_ ## name (int nitems) {
2311
return (type *) malloc(sizeof(type)*nitems);
2313
void delete_ ## name(type *t) {
2316
type name ## _get(type *t, int index) {
2319
void name ## _set(type *t, int index, type val) {
2325
ARRAYHELPER(int, IntArray)
2326
ARRAYHELPER(double, DoubleArray)
2330
The primary purpose of <tt>%define</tt> is to define large macros of code. Unlike normal C preprocessor
2331
macros, it is not necessary to terminate each line with a continuation character (\)--the macro definition
2332
extends to the first occurrence of <tt>%enddef</tt>. Furthermore, when such macros are expanded,
2333
they are reparsed through the C preprocessor. Thus, SWIG macros can contain all other preprocessor
2334
directives except for nested <tt>%define</tt> statements.
2337
The SWIG macro capability is a very quick and easy way to generate large amounts of code. In fact,
2338
many of SWIG's advanced features and libraries are built using this mechanism (such as C++ template
2341
<h3>Preprocessing and %{ ... %} blocks</h3>
2343
The SWIG preprocessor does not process any text enclosed in a code block %{ ... %}. Therefore,
2344
if you write code like this,
2358
the contents of the <tt>%{ ... %}</tt> block are copied without
2359
modification to the output (including all preprocessor directives).
2361
<h3>Preprocessing and { ... }</h3>
2363
SWIG always runs the preprocessor on text appearing inside <tt>{ ... }</tt>. However,
2364
sometimes it is desirable to make a preprocessor directive pass through to the output
2372
printf("I'm in bar\n");
2379
By default, SWIG will interpret the <tt>#ifdef DEBUG</tt> statement. However, if you really wanted that code
2380
to actually go into the wrapper file, prefix the preprocessor directives with <tt>%</tt> like this:
2387
printf("I'm in bar\n");
2394
SWIG will strip the extra <tt>%</tt> and leave the preprocessor directive in the code.
2396
<h2>An Interface Building Strategy</h2>
2471
<a name="n45"></a><H2>4.7 An Interface Building Strategy</H2>
2398
2474
This section describes the general approach for building interface
2399
2475
with SWIG. The specifics related to a particular scripting language
2400
2476
are found in later chapters.<p>
2402
<h3> Preparing a C program for SWIG</h3>
2478
<a name="n46"></a><H3>4.7.1 Preparing a C program for SWIG</H3>
2404
2481
SWIG doesn't require modifications to your C code, but if you feed it
2405
2482
a collection of raw C header files or source code, the results might
2562
2643
<tt>main()</tt> program can be completely replaced by a Perl, Python,
2563
2644
or Tcl script.<p>
2565
<h3> How to avoid creating the interface from hell</h3>
2567
SWIG makes it fairly easy to build a big interface really fast. In
2568
fact, if you apply it to a large enough package, you'll find yourself
2569
with a rather large amount of code being produced in the resulting
2570
wrapper file. For instance, wrapping a 1000 line C header file
2571
with a large number of structure declarations may result in a wrapper
2572
file containing 20,000-30,000 lines of code. Here are a few things
2573
you can do to make smaller interface:
2576
<li>It is usually not necessary to wrap every single function in a package.
2577
Try to eliminate the unneeded ones.
2579
<li>SWIG does not require structure definitions to operate. If you are
2580
never going to access the members of a structure, don't wrap the
2581
structure definition.
2583
<li>Eliminate unneeded members of C++ classes.
2585
<li>Think about what you are doing. If you are only using a subset of
2586
some library, there is no need to wrap the whole thing.
2588
<li>Write support or helper functions to simplify common
2589
operations. Some C functions may not be easy to use in a scripting
2590
language environment. You might consider writing an alternative
2591
version and wrapping that instead.
2647
<b>Note:</b> If some cases, you might be inclined to create a
2648
scripting language wrapper for <tt>main()</tt>. If you do this, the
2649
compilation will probably work and your module might even load
2650
correctly. The only trouble is that when you call your
2651
<tt>main()</tt> wrapper, you will find that it actually invokes the
2652
<tt>main()</tt> of the scripting language interpreter itself! This behavior
2653
is a side effect of the symbol binding mechanism used in the dynamic linker.
2654
The bottom line: don't do this.
2596
<address>SWIG 1.3 - Last Modified : December 30, 2001</address>
2658
<address>SWIG 1.3 - Last Modified : August 7, 2003</address>
b'\\ No newline at end of file'