~ubuntu-branches/ubuntu/hoary/swig1.3/hoary

« back to all changes in this revision

Viewing changes to Doc/Manual/SWIG.html

  • Committer: Bazaar Package Importer
  • Author(s): Thom May
  • Date: 2004-08-02 15:57:10 UTC
  • mfrom: (1.1.1 upstream)
  • Revision ID: james.westby@ubuntu.com-20040802155710-bm292q1d6x6tw7gc
Tags: 1.3.21-5ubuntu1
Fix linking for ruby, python, perl and tcl bindings

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
1
2
<html>
2
3
<head>
3
4
<title>SWIG Basics</title>
4
5
</head>
5
6
 
6
7
<body bgcolor="#ffffff">
7
 
<h1>3 SWIG Basics</h1>
 
8
<a name="n1"></a><H1>4 SWIG Basics</H1>
 
9
<!-- INDEX -->
 
10
<ul>
 
11
<li><a href="#n2">Running SWIG</a>
 
12
<ul>
 
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>
 
19
</ul>
 
20
<li><a href="#n9">Wrapping Simple C Declarations</a>
 
21
<ul>
 
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>
 
27
</ul>
 
28
<li><a href="#n15">Pointers and complex objects</a>
 
29
<ul>
 
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>
 
35
</ul>
 
36
<li><a href="#n21">Other Practicalities</a>
 
37
<ul>
 
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>
 
47
</ul>
 
48
<li><a href="#n31">Structures and unions</a>
 
49
<ul>
 
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>
 
58
</ul>
 
59
<li><a href="#n40">Code Insertion</a>
 
60
<ul>
 
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>
 
65
</ul>
 
66
<li><a href="#n45">An Interface Building Strategy</a>
 
67
<ul>
 
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>
 
73
</ul>
 
74
</ul>
 
75
<!-- INDEX -->
 
76
 
 
77
 
8
78
 
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
13
83
Specific details about each target language are described in later
14
84
chapters. 
15
85
 
16
 
<h2>Running SWIG</h2>
 
86
<a name="n2"></a><H2>4.1 Running SWIG</H2>
 
87
 
17
88
 
18
89
To run SWIG, use the <tt>swig</tt> command with one or more of the
19
90
following options and a filename like this:
21
92
<p>
22
93
<blockquote><pre>swig [ <em>options</em> ] filename
23
94
 
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
42
122
 
43
123
</pre></blockquote>
44
124
 
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>.
48
129
 
49
 
<h3>Input format</h3>
 
130
<a name="n3"></a><H3>4.1.1 Input format</H3>
 
131
 
50
132
 
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.
80
162
 
81
163
<p>
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.
89
 
 
90
 
<h3>SWIG Output</h3>
 
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.
 
176
 
 
177
<a name="output"></a>
 
178
<a name="n4"></a><H3>4.1.2 SWIG Output</H3>
 
179
 
91
180
 
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>
105
195
 
106
196
<p>
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. 
114
204
 
115
 
<h3>Comments</h3>
 
205
<p>
 
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:
 
210
 
 
211
<blockquote><pre>
 
212
$ swig -c++ -python -outdir pyfiles -o cppfiles/example_wrap.cpp example.i
 
213
</pre></blockquote>
 
214
 
 
215
If the directories <tt>cppfiles</tt> and <tt>pyfiles</tt> exist, the following
 
216
will be generated:
 
217
<blockquote><pre>
 
218
cppfiles/example_wrap.cpp
 
219
pyfiles/example.py
 
220
</pre></blockquote>
 
221
 
 
222
<a name="n5"></a><H3>4.1.3 Comments</H3>
 
223
 
116
224
 
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.
121
229
 
122
 
<h3>C Preprocessor</h3>
 
230
<a name="n6"></a><H3>4.1.4 C Preprocessor</H3>
 
231
 
123
232
 
124
233
Like C, SWIG preprocesses all input files through an enhanced version
125
234
of the C preprocessor.  All standard preprocessor features are
137
246
enclosed inside a <tt>%{...%}</tt> block.  In addition, the
138
247
preprocessor includes a number of macro handling enhancements that
139
248
make it more powerful than the normal C preprocessor.  These
140
 
extensions are described in the "Preprocessor" section near the end of
141
 
this chapter.
142
 
 
143
 
<h3>SWIG Directives</h3>
 
249
extensions are described in the "<a href="Preprocessor.html">Preprocessor</a>" chapter.
 
250
 
 
251
<a name="n7"></a><H3>4.1.5 SWIG Directives</H3>
 
252
 
144
253
 
145
254
Most of SWIG's operation is controlled by special directives that are
146
255
always preceded by a "<tt>%</tt>" to distinguish them from normal C
165
274
<tt>SWIG</tt> is a special preprocessing symbol defined by SWIG when
166
275
it is parsing an input file.
167
276
 
168
 
<h3>Parser Limitations</h3>
169
 
 
170
 
Although SWIG can parse most common C/C++ declarations, it does not
 
277
<a name="n8"></a><H3>4.1.6 Parser Limitations</H3>
 
278
 
 
279
 
 
280
Although SWIG can parse most C/C++ declarations, it does not
171
281
provide a complete C/C++ parser implementation.  Most of these
172
282
limitations pertain to very complicated type declarations and certain
173
283
advanced C++ features.  Specifically, the following features are not
183
293
<pre>
184
294
/* Non-conventional placement of storage specifier (extern) */
185
295
const int extern Number;
186
 
/* Function declaration with unnecessary grouping */
187
 
int (foo)(int,int); 
188
 
...
 
296
 
 
297
/* Extra declarator grouping */
 
298
Matrix (foo);    // A global variable
 
299
 
 
300
/* Extra declarator grouping in parameters */
 
301
void bar(Spam (Grok)(Doh));
 
302
 
189
303
</pre>
190
304
</blockquote>
191
305
 
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?).
195
309
 
196
310
<p>
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:
202
316
 
209
323
</pre>
210
324
</blockquote>
211
325
 
212
 
<li>Certain advanced features of C++ such as namespaces and nested classes
 
326
<li>Certain advanced features of C++ such as nested classes 
213
327
are not yet supported. Please see the section on using SWIG
214
328
with C++ for more information.
215
329
</ul> <p>
240
354
does not utilize a separate <em>typedef-name</em> terminal symbol as
241
355
described on p. 234 of K&amp;R).
242
356
 
243
 
<p>
244
 
It should also be noted that the SWIG parser was never really
245
 
developed with the intent that it would be blindly used on raw C/C++
246
 
source code.  Although parsing has become a lot more powerful in
247
 
recent versions, the underlying assumption was that one would usually
248
 
start with a header and enhance it by adding additional support code, cutting
249
 
certain features out, supplying special SWIG directives, and so forth.
 
357
<a name="n9"></a><H2>4.2 Wrapping Simple C Declarations</H2>
250
358
 
251
 
<h2>Wrapping Simple C Declarations</h2>
252
359
 
253
360
SWIG wraps simple C declarations by creating an interface that closely matches
254
361
the way in which the declarations would be used in a C program.
304
411
environments, and semantics, it is not always possible to do so.   The
305
412
next few sections describes various aspects of this mapping.
306
413
 
307
 
<h3>Basic Type Handling</h3>
 
414
<a name="n10"></a><H3>4.2.1 Basic Type Handling</H3>
 
415
 
308
416
 
309
417
In order to build an interface, SWIG has to convert C/C++ datatypes to
310
418
equivalent types in the target language.  Generally,
366
474
long</tt> integers are encoded as strings. This allows the full range
367
475
of these numbers to be represented.  However, it does not allow
368
476
<tt>long long</tt> values to be used in arithmetic expressions.  It
369
 
should also be noted that since <tt>long long</tt> support is not part
370
 
of the ANSI C standard, it is not universally supported by all C
 
477
should also be noted that although <tt>long long</tt> is part
 
478
of the ISO C99 standard, it is not universally supported by all C
371
479
compilers.  Make sure you are using a compiler that supports <tt>long
372
 
long</tt> before trying to this type with SWIG.
 
480
long</tt> before trying to use this type with SWIG.
373
481
 
374
482
<p>
375
483
SWIG recognizes the following floating point types :<p>
418
526
will use the same internal representation (e.g., UCS-2 vs. UCS-4).
419
527
You may need to write some special conversion functions.
420
528
 
421
 
<h3>Global Variables</h3>
 
529
<a name="n11"></a><H3>4.2.2 Global Variables</H3>
 
530
 
422
531
 
423
532
Whenever possible, SWIG maps C/C++ global variables into scripting language
424
533
variables.  For example,
467
576
Earlier versions of SWIG incorrectly handled <tt>const</tt> and created
468
577
constants instead.
469
578
 
470
 
<h3> Constants</h3>
 
579
<a name="n12"></a><H3>4.2.3 Constants</H3>
 
580
 
471
581
 
472
582
Constants can be created using <tt>#define</tt>, enumerations,
473
583
or a special <tt>%constant</tt> directive.  The following
543
653
is only used when you want to add constants to the scripting language
544
654
interface that are not defined in the original header file. 
545
655
 
546
 
<h3>A brief word about <tt>const</tt></h3>
 
656
<a name="n13"></a><H3>4.2.4 A brief word about <tt>const</tt></H3>
 
657
 
547
658
 
548
659
A common confusion with C programming is the semantic meaning of the
549
660
<tt>const</tt> qualifier in declarations--especially when it is mixed
629
740
</pre>
630
741
</blockquote>
631
742
 
632
 
<h2>Pointers and complex objects</h2>
 
743
<a name="n14"></a><H3>4.2.5 A cautionary tale of <tt>char *</tt></H3>
 
744
 
 
745
 
 
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.
 
754
 
 
755
<p>
 
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:
 
758
 
 
759
<blockquote>
 
760
<pre>
 
761
char *strcat(char *s, const char *t)
 
762
</pre>
 
763
</blockquote>
 
764
 
 
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.
 
770
 
 
771
<p>
 
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>.  
 
775
 
 
776
<a name="n15"></a><H2>4.3 Pointers and complex objects</H2>
 
777
 
633
778
 
634
779
Most C programs manipulate arrays, structures, and other types of objects.  This section
635
780
discusses the handling of these datatypes.
636
781
 
637
 
<h3> Simple pointers</h3>
 
782
<a name="n16"></a><H3>4.3.1 Simple pointers</H3>
 
783
 
638
784
 
639
785
Pointers to primitive C datatypes such as <p>
640
786
<p>
643
789
char **
644
790
</pre></blockquote>
645
791
<p>
646
 
are fully supported by SWIG.  SWIG encodes pointers into a
 
792
are fully supported by SWIG.  Rather than trying to convert the data being pointed to into a scripting
 
793
representation, SWIG simply encodes the pointer itself into a
647
794
representation that contains the actual value of the pointer and a type-tag.
648
795
Thus, the SWIG representation of the above
649
796
pointers (in Tcl), might look like this:<p>
662
809
All pointers are treated as opaque objects by SWIG. Thus, a pointer
663
810
may be returned by a function and passed around to other C functions
664
811
as needed.  For all practical purposes, the scripting language
665
 
interface works in exactly the same way as you would manipulate the
 
812
interface works in exactly the same way as you would use the
666
813
pointer in a C program.  The only difference is that there is no mechanism for
667
814
dereferencing the pointer since this would require the target language
668
815
to understand the memory layout of the underlying object.
669
816
 
670
817
<p>
671
818
The scripting language representation of a pointer value should never be
672
 
manipulated directly.   Even though the values shown above look like hexadecimal
 
819
manipulated directly.   Even though the values shown look like hexadecimal
673
820
addresses, the numbers used may differ from the actual machine address (e.g.,
674
821
on little-endian machines, the digits may appear in reverse order).
675
822
Furthermore, SWIG does not
683
830
<li>There is not enough information in a C declaration to properly map
684
831
pointers into higher level constructs. For example, an <tt>int *</tt>
685
832
may indeed be an array of integers, but if it contains ten million
686
 
elements, converting it into a list would
687
 
probably be best avoided.
 
833
elements, converting it into a list object is probably a bad idea.
688
834
 
689
835
<p>
690
836
<li>The underlying semantics associated with a pointer is not known
697
843
</ul>
698
844
<p>
699
845
 
700
 
<h3> Run time pointer type checking</h3>
 
846
<a name="n17"></a><H3>4.3.2 Run time pointer type checking</H3>
 
847
 
701
848
 
702
849
By allowing pointers to be manipulated from a scripting language, extension modules
703
850
effectively bypass compile-time type checking in the C/C++
715
862
as sentinel values or to denote a missing/empty value.  Therefore,
716
863
SWIG leaves NULL pointer checking up to the application.
717
864
 
718
 
<h3> Derived types, structs, and classes</h3>
 
865
<a name="n18"></a><H3>4.3.3 Derived types, structs, and classes</H3>
 
866
 
719
867
 
720
868
For everything else (structs, classes, arrays, etc...) SWIG applies a
721
869
very simple rule :<p>
769
917
opaque objects containing C pointers. It doesn't matter what value
770
918
they contain--our program works just fine without this knowledge.<p>
771
919
 
772
 
<h3>Undefined datatypes</h3>
 
920
<a name="n19"></a><H3>4.3.4 Undefined datatypes</H3>
 
921
 
773
922
 
774
923
When SWIG encounters an undeclared datatype, it automatically assumes
775
924
that it is a structure or class. For example, suppose the following
820
969
 
821
970
<!-- We might want to add an error reporting flag to swig -->
822
971
 
823
 
<h3>Typedef</h3>
 
972
<a name="n20"></a><H3>4.3.5 Typedef</H3>
 
973
 
824
974
 
825
975
Like C, <tt>typedef</tt> can be used to define new type names in SWIG. For example:
826
976
<p>
894
1044
The corresponding wrapper function will accept arguments of
895
1045
type <tt>unsigned int *</tt> or <tt>size_t *</tt>.
896
1046
 
897
 
<h2>Other Practicalities</h2>
 
1047
<a name="n21"></a><H2>4.4 Other Practicalities</H2>
 
1048
 
898
1049
 
899
1050
So far, this chapter has presented almost everything you need to know to use SWIG
900
1051
for simple interfaces. However, some C programs use idioms that are somewhat
901
1052
more difficult to map to a scripting language interface.  This section describes
902
1053
some of these issues.
903
1054
 
904
 
<h3> Passing structures by value</h3>
 
1055
<a name="n22"></a><H3>4.4.1 Passing structures by value</H3>
 
1056
 
905
1057
 
906
1058
Sometimes a C function takes structure parameters that are passed
907
1059
by value.  For example, consider the following function:
927
1079
to Vectors instead of Vectors.  For the most part, this transformation
928
1080
is transparent so you might not notice.
929
1081
 
930
 
<h3>Return by value</h3>
 
1082
<a name="n23"></a><H3>4.4.2 Return by value</H3>
 
1083
 
931
1084
 
932
1085
C functions that return structures or classes datatypes by value are more difficult
933
1086
to handle. Consider the following function:<p>
977
1130
don't work correctly if <tt>Vector</tt> doesn't define a default
978
1131
constructor.  The section on SWIG and C++ has more information about this case.
979
1132
 
980
 
<h3>Linking to structure variables</h3>
 
1133
<a name="n24"></a><H3>4.4.3 Linking to structure variables</H3>
 
1134
 
981
1135
 
982
1136
When global variables or class members involving structures are
983
1137
encountered, SWIG handles them as pointers. For example, a global
1004
1158
C++ classes must supply a properly defined copy constructor in order for
1005
1159
assignment to work correctly.
1006
1160
 
1007
 
<h3> Linking to <tt>char *</tt></h3>
 
1161
<a name="n25"></a><H3>4.4.4 Linking to <tt>char *</tt></H3>
 
1162
 
1008
1163
 
1009
1164
When a global variable of type <tt>char *</tt> appears, SWIG uses <tt>malloc()</tt> or
1010
1165
<tt>new</tt> to allocate memory for the new value.   Specifically, if you have a variable
1037
1192
</blockquote>
1038
1193
 
1039
1194
If this is not the behavior that you want, consider making the variable read-only using the
1040
 
<tt>%readonly</tt> directive.  Alternatively, you might write a short assist-function to set the value
 
1195
<tt>%immutable</tt> directive.  Alternatively, you might write a short assist-function to set the value
1041
1196
exactly like you want.  For example:
1042
1197
 
1043
1198
<blockquote>
1114
1269
 
1115
1270
 
1116
1271
 
1117
 
<h3> Arrays</h3>
 
1272
<a name="n26"></a><H3>4.4.5 Arrays</H3>
 
1273
 
1118
1274
 
1119
1275
Arrays are fully supported by SWIG, but they are always handled as pointers instead
1120
1276
of mapping them to a special array object or list in the target language.  Thus, the
1231
1387
 
1232
1388
In the target language, the value can be set like a normal variable.
1233
1389
 
1234
 
<h3>Creating read-only variables</h3>
1235
 
 
1236
 
A read-only variable can be created by using the <tt>%readonly</tt>
 
1390
<a name="n27"></a><H3>4.4.6 Creating read-only variables</H3>
 
1391
 
 
1392
 
 
1393
A read-only variable can be created by using the <tt>%immutable</tt>
1237
1394
directive as shown :<p>
1238
1395
 
1239
1396
<blockquote><pre>
1240
1397
// File : interface.i
1241
1398
 
1242
1399
int     a;                      // Can read/write
1243
 
%readonly
 
1400
%immutable;
1244
1401
int     b,c,d                   // Read only variables
1245
 
%readwrite
 
1402
%mutable;
1246
1403
double  x,y                     // read/write
1247
1404
</pre></blockquote>
1248
1405
 
1249
1406
<p>
1250
 
The <tt>%readonly</tt> directive enables read-only mode until it is
1251
 
explicitly disabled using the <tt>%readwrite</tt> directive.<p>
 
1407
The <tt>%immutable</tt> directive enables read-only mode until it is
 
1408
explicitly disabled using the <tt>%mutable</tt> directive.  As an alternative to turning
 
1409
read-only mode off and on like this, individual declarations can also be tagged as
 
1410
immutable.  For example:
 
1411
 
 
1412
<blockquote><pre>
 
1413
%immutable x;               // Make x read-only
 
1414
...
 
1415
double x;                   // Read-only (from earlier %immutable directive)
 
1416
double y;                   // Read-write
 
1417
...
 
1418
</pre>
 
1419
</blockquote>
1252
1420
 
1253
1421
Read-only variables are also created when declarations are declared as <tt>const</tt>.
1254
1422
For example:
1260
1428
</pre>
1261
1429
</blockquote>
1262
1430
 
1263
 
<h3>Renaming and ignoring declarations</h3>
 
1431
<p>
 
1432
<b>Compatibility note:</b> Read-only access used to be controlled by a pair of directives
 
1433
<tt>%readonly</tt> and <tt>%readwrite</tt>.   Although these directives still work, they
 
1434
generate a warning message.   Simply change the directives to <tt>%immutable;</tt> and
 
1435
<tt>%mutable;</tt> to silence the warning.  Don't forget the extra semicolon!
 
1436
 
 
1437
<a name="n28"></a><H3>4.4.7 Renaming and ignoring declarations</H3>
 
1438
 
1264
1439
 
1265
1440
Normally, the name of a C declaration is used when that declaration is
1266
1441
wrapped into the target language. However, this may generate a
1349
1524
This directive is still supported, but it is deprecated and should probably be avoided.  The <tt>%rename</tt>
1350
1525
directive is more powerful and better supports wrapping of raw header file information.
1351
1526
 
1352
 
<h3>Default/optional arguments</h3>
 
1527
<a name="n29"></a><H3>4.4.8 Default/optional arguments</H3>
 
1528
 
1353
1529
 
1354
1530
SWIG supports default arguments in both C and C++ code.  For example:
1355
1531
<p>
1369
1545
Although the ANSI C standard does not allow default arguments, default
1370
1546
arguments specified in a SWIG interface work with both C and C++.
1371
1547
 
1372
 
<h3>Pointers to functions and callbacks</h3>
 
1548
<p>
 
1549
<b>Note:</b> There is a subtle semantic issue concerning the use 
 
1550
of default arguments and the SWIG generated wrapper code.  When default
 
1551
arguments are used, the default values are emitted into the wrappers and the
 
1552
function is invoked with a full set of arguments.  This behavior is not
 
1553
100% compatible with all uses of default arguments in C++.  Please refer to
 
1554
the C++ chapter for further details.
 
1555
 
 
1556
<a name="n30"></a><H3>4.4.9 Pointers to functions and callbacks</H3>
 
1557
 
1373
1558
 
1374
1559
Occasionally, a C library may include functions that expect to receive
1375
1560
pointers to functions--possibly to serve as callbacks. SWIG
1501
1686
can be accomplished with the use of typemaps and other advanced SWIG features.
1502
1687
This is described in a later chapter.
1503
1688
 
1504
 
<h2>Structures and unions</h2>
 
1689
<a name="n31"></a><H2>4.5 Structures and unions</H2>
 
1690
 
1505
1691
 
1506
1692
This section describes the behavior of SWIG when processing ANSI C structures and union declarations.  Extensions to
1507
1693
handle C++ are described in the next section.
1573
1759
 
1574
1760
However, most of SWIG's language modules also provide a high-level interface that is more convenient. Keep reading.
1575
1761
 
1576
 
<h3> Typedef and structures</h3>
 
1762
<a name="n32"></a><H3>4.5.1 Typedef and structures</H3>
 
1763
 
1577
1764
 
1578
1765
SWIG supports the following construct which is quite common in C
1579
1766
programs :<p>
1612
1799
vector_struct</tt>, SWIG knows that this is the same as
1613
1800
<tt>Vector</tt> and it generates the appropriate type-checking code.
1614
1801
 
1615
 
<h3> Character strings and structures</h3>
 
1802
<a name="n33"></a><H3>4.5.2 Character strings and structures</H3>
 
1803
 
1616
1804
 
1617
1805
Structures involving character strings require some care. SWIG assumes
1618
1806
that all members of type <tt>char *</tt> have been dynamically
1654
1842
Note: If the <tt>-c++</tt> option is used, <tt>new</tt> and <tt>delete</tt> are used to
1655
1843
perform memory allocation.
1656
1844
 
1657
 
<h3>Array members</h3>
 
1845
<a name="n34"></a><H3>4.5.3 Array members</H3>
 
1846
 
1658
1847
 
1659
1848
Arrays may appear as the members of structures, but they will be
1660
1849
read-only. SWIG will write an accessor function that returns the
1673
1862
discussed in a later chapter.  In many cases, the warning message is
1674
1863
harmless.
1675
1864
 
1676
 
<h3>C constructors and destructors </h3>
 
1865
<a name="n35"></a><H3>4.5.4 Structure data members</H3>
 
1866
 
 
1867
 
 
1868
Occasionally, a structure will contain data members that are themselves structures.  For example:
 
1869
 
 
1870
<blockquote>
 
1871
<pre>
 
1872
typedef struct Foo {
 
1873
   int x;
 
1874
} Foo;
 
1875
 
 
1876
typedef struct Bar {
 
1877
   int y;
 
1878
   Foo f;           /* struct member */
 
1879
} Bar;
 
1880
</pre>
 
1881
</blockquote>
 
1882
 
 
1883
When a structure member is wrapped, it is always handled as a pointer.
 
1884
For example:
 
1885
 
 
1886
<blockquote>
 
1887
<pre>
 
1888
Foo *Bar_f_get(Bar *b) {
 
1889
   return &b->f;
 
1890
}
 
1891
void Bar_f_set(Bar *b, Foo *value) {
 
1892
   b->f = *value;
 
1893
}
 
1894
</pre>
 
1895
</blockquote>
 
1896
 
 
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:
 
1901
 
 
1902
<blockquote>
 
1903
<pre>
 
1904
Bar *b;
 
1905
b->f.x = 37;
 
1906
</pre>
 
1907
</blockquote>
 
1908
 
 
1909
Translating this assignment to function calls (as would be used inside the scripting
 
1910
language interface) results in the following code:
 
1911
 
 
1912
<blockquote>
 
1913
<pre>
 
1914
Bar *b;
 
1915
Foo_x_set(Bar_f_get(b),37);
 
1916
</pre>
 
1917
</blockquote>
 
1918
 
 
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!
 
1922
 
 
1923
<p>
 
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,
 
1926
 
 
1927
<blockquote>
 
1928
<pre>
 
1929
struct Foo {
 
1930
   WORD   w;
 
1931
};
 
1932
</pre>
 
1933
</blockquote>
 
1934
 
 
1935
and nothing was known about <tt>WORD</tt>, then SWIG will generate more normal accessor functions
 
1936
like this:
 
1937
 
 
1938
<blockquote>
 
1939
<pre>
 
1940
WORD Foo_w_get(Foo *f) {
 
1941
    return f->w;
 
1942
}
 
1943
void Foo_w_set(FOO *f, WORD value) {
 
1944
    f->w = value;
 
1945
}
 
1946
</pre>
 
1947
</blockquote>
 
1948
 
 
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>.
 
1953
 
 
1954
<a name="n36"></a><H3>4.5.5 C constructors and destructors </H3>
 
1955
 
1677
1956
 
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 
1692
1971
 
1693
1972
</pre></blockquote>
1694
 
or<p>
 
1973
or
1695
1974
<p>
1696
1975
<blockquote><pre>%module foo
1697
1976
...
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
1701
 
 
 
1979
%makedefault;      // Reenable default constructors/destructors
1702
1980
</pre></blockquote>
1703
1981
 
 
1982
If you need more precise control, <tt>%nodefault</tt> can selectively target individual structure 
 
1983
definitions.  For example:
 
1984
 
 
1985
<blockquote>
 
1986
<pre>
 
1987
%nodefault Foo;          // No default constructor/destructors for Foo
 
1988
...
 
1989
struct Foo {             // No default generated.
 
1990
};
 
1991
 
 
1992
struct Bar {             // Default constructor/destructor generated.
 
1993
};
 
1994
</pre>
 
1995
</blockquote>
 
1996
 
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.
1708
2001
 
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>
 
2003
 
1710
2004
 
1711
2005
Most languages provide a mechanism for creating classes and
1712
2006
supporting object oriented programming. From a C standpoint, object
1715
2009
on an instance of the structure (or object).  Although there is a
1716
2010
natural mapping of C++ to such a scheme, there is no direct mechanism
1717
2011
for utilizing it with C code. However, SWIG provides a special
1718
 
<tt>%addmethods</tt> directive that makes it possible to attach
 
2012
<tt>%extend</tt> directive that makes it possible to attach
1719
2013
methods to C structures for purposes of building an object oriented
1720
2014
interface. Suppose you have a C header file with
1721
2015
the following declaration :<p>
1738
2032
%}
1739
2033
 
1740
2034
%include vector.h            // Just grab original C header file
1741
 
%addmethods Vector {         // Attach these functions to struct Vector
 
2035
%extend Vector {             // Attach these functions to struct Vector
1742
2036
        Vector(double x, double y, double z) {
1743
2037
                Vector *v;
1744
2038
                v = (Vector *v) malloc(sizeof(Vector));
1773
2067
</pre></blockquote>
1774
2068
<p>
1775
2069
 
1776
 
The <tt>%addmethods</tt> directive can also be used inside the definition
 
2070
The <tt>%extend</tt> directive can also be used inside the definition
1777
2071
of the Vector structure. For example:<p>
1778
2072
 
1779
2073
<blockquote><pre>// file : vector.i
1784
2078
 
1785
2079
typedef struct {
1786
2080
        double x,y,z;
1787
 
        %addmethods {
 
2081
        %extend {
1788
2082
                Vector(double x, double y, double z) { ... }
1789
2083
                ~Vector() { ... }
1790
2084
                ...
1793
2087
</pre></blockquote>
1794
2088
 
1795
2089
<p>
1796
 
Finally, <tt>%addmethods</tt> can be used to access externally written
 
2090
Finally, <tt>%extend</tt> can be used to access externally written
1797
2091
functions provided they follow the naming convention used in this
1798
2092
example :<p>
1799
2093
 
1826
2120
 
1827
2121
typedef struct {
1828
2122
        double x,y,z;
1829
 
        %addmethods {
 
2123
        %extend {
1830
2124
                Vector(int,int,int); // This calls new_Vector()
1831
2125
               ~Vector();            // This calls delete_Vector()
1832
2126
                double magnitude();  // This will call Vector_magnitude()
1836
2130
</pre>
1837
2131
</blockquote>
1838
2132
 
1839
 
A little known feature of the <tt>%addmethods</tt> directive is that
 
2133
A little known feature of the <tt>%extend</tt> directive is that
1840
2134
it can also be used to add synthesized attributes or to modify the
1841
2135
behavior of existing data attributes.  For example, suppose you wanted
1842
2136
to make <tt>magnitude</tt> a read-only attribute of <tt>Vector</tt>
1845
2139
<blockquote>
1846
2140
<pre>
1847
2141
// Add a new attribute to Vector
1848
 
%addmethods Vector {
 
2142
%extend Vector {
1849
2143
    const double magnitude;
1850
2144
}
1851
2145
// Now supply the implementation of the Vector_magnitude_get function
1881
2175
<blockquote>
1882
2176
<pre>
1883
2177
struct Person {
1884
 
    %addmethods {
 
2178
    %extend {
1885
2179
       char *name;
1886
2180
    }
1887
2181
...
1899
2193
</pre>
1900
2194
</blockquote>
1901
2195
 
1902
 
Finally, it should be stressed that even though <tt>%addmethods</tt>
 
2196
Finally, it should be stressed that even though <tt>%extend</tt>
1903
2197
can be used to add new data members, these new members can not require
1904
2198
the allocation of additional storage in the object (e.g., their values must
1905
2199
be entirely synthesized from existing attributes of the structure).
1906
2200
 
1907
 
<h3> Nested structures</h3>
 
2201
<p>
 
2202
<b>Compatibility note:</b>  The <tt>%extend</tt> directive is a new
 
2203
name for the <tt>%addmethods</tt> directive.  Since <tt>%addmethods</tt> could
 
2204
be used to extend a structure with more than just methods, a more suitable
 
2205
directive name has been chosen.
 
2206
 
 
2207
<a name="n38"></a><H3>4.5.7 Nested structures</H3>
 
2208
 
1908
2209
 
1909
2210
Occasionally, a C program will involve structures like this :<p>
1910
2211
<p>
1973
2274
there is a good chance that they will work, you may have to
1974
2275
modify the interface file in certain cases.
1975
2276
 
1976
 
<h3>Other things to note about structure wrapping</h3>
 
2277
<a name="n39"></a><H3>4.5.8 Other things to note about structure wrapping</H3>
 
2278
 
1977
2279
 
1978
2280
SWIG doesn't care if the declaration of a structure in a <tt>.i</tt> file exactly matches
1979
2281
that used in the underlying C code (except in the case of nested
2018
2320
</pre>
2019
2321
</blockquote>
2020
2322
 
2021
 
The only exception to this rule are methods defined with <tt>%addmethods</tt>.  In this
 
2323
The only exception to this rule are methods defined with <tt>%extend</tt>.  In this
2022
2324
case, the added code is contained in a separate function.
2023
2325
 
2024
2326
<p>
2027
2329
interface described here, most of SWIG's language modules use it in
2028
2330
some way or another.
2029
2331
 
2030
 
<h2> Code Insertion</h2>
 
2332
<a name="n40"></a><H2>4.6 Code Insertion</H2>
 
2333
 
2031
2334
 
2032
2335
Sometimes it is necessary to insert special code into the resulting
2033
2336
wrapper file generated by SWIG.  For example, you may want to include
2035
2338
There are four common ways to insert code, but it's useful to know how the
2036
2339
output of SWIG is structured first.<p>
2037
2340
 
2038
 
<h3> The output of SWIG</h3>
 
2341
<a name="n41"></a><H3>4.6.1 The output of SWIG</H3>
 
2342
 
2039
2343
 
2040
2344
When SWIG creates its output file, it is broken up into four sections
2041
2345
corresponding to runtime libraries, headers, wrapper functions, and module
2062
2366
the module upon loading.
2063
2367
</ul>
2064
2368
 
2065
 
<h3> Code insertion blocks</h3>
 
2369
<a name="n42"></a><H3>4.6.2 Code insertion blocks</H3>
 
2370
 
2066
2371
 
2067
2372
Code is inserted into the appropriate code section by using one
2068
2373
of the following code insertion directives:
2127
2432
Vector *new_Vector();
2128
2433
</pre></blockquote>
2129
2434
 
2130
 
<h3>Inlined code blocks</h3>
 
2435
<a name="n43"></a><H3>4.6.3 Inlined code blocks</H3>
 
2436
 
2131
2437
 
2132
2438
Since the process of writing helper functions is fairly common,
2133
2439
there is a special inlined form of code block that is used as follows
2150
2456
is given to both the C compiler and SWIG, it is illegal to include any
2151
2457
SWIG directives inside a <tt>%{ ... %}</tt> block.<p>
2152
2458
 
2153
 
<h3>Initialization blocks</h3>
 
2459
<a name="n44"></a><H3>4.6.4 Initialization blocks</H3>
 
2460
 
2154
2461
 
2155
2462
When code is included in the <tt>%init</tt> section, it is copied directly into the 
2156
2463
module initialization function.  For example, if you needed to perform some extra
2161
2468
%}
2162
2469
</pre></blockquote>
2163
2470
 
2164
 
<h2>SWIG Preprocessor</h2>
2165
 
 
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.
2170
 
 
2171
 
<h3>File inclusion</h3>
2172
 
 
2173
 
To include another file into a SWIG interface, use the <tt>%include</tt> directive
2174
 
like this:
2175
 
 
2176
 
<blockquote>
2177
 
<pre>
2178
 
%include "pointer.i"
2179
 
</pre>
2180
 
</blockquote>
2181
 
 
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.
2185
 
 
2186
 
<p>
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.
2191
 
 
2192
 
<h3>File imports</h3>
2193
 
 
2194
 
SWIG provides another file inclusion directive with the <tt>%import</tt> directive.
2195
 
For example:
2196
 
 
2197
 
<blockquote>
2198
 
<pre>
2199
 
%import "foo.i"
2200
 
</pre>
2201
 
</blockquote>
2202
 
 
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
2209
 
in a later chapter.
2210
 
 
2211
 
<P>
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.
2215
 
 
2216
 
<h3>Conditional Compilation</h3>
2217
 
 
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:
2222
 
 
2223
 
<p>
2224
 
<blockquote><pre>
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
2237
 
</pre></blockquote>
2238
 
 
2239
 
In addition, SWIG defines the following set of standard C/C++ macros:
2240
 
 
2241
 
<blockquote>
2242
 
<pre>
2243
 
__LINE__                        Current line number
2244
 
__FILE__                        Current file name
2245
 
__STDC__                        Defined to indicate ANSI C
2246
 
__cplusplus                     Defined when -c++ option used
2247
 
</pre>
2248
 
</blockquote>
2249
 
 
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>
2255
 
 
2256
 
<h3>Macro Expansion</h3>
2257
 
 
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,
2260
 
 
2261
 
<blockquote>
2262
 
<pre>
2263
 
#ifndef _FOO_H 1
2264
 
#define _FOO_H 1
2265
 
...
2266
 
#endif
2267
 
</pre>
2268
 
</blockquote>
2269
 
you may get some extra constants such as <tt>_FOO_H</tt> showing up in the scripting interface.
2270
 
 
2271
 
<p>
2272
 
More complex macros can be defined in the standard way. For example:
2273
 
 
2274
 
<blockquote>
2275
 
<pre>
2276
 
#define EXTERN extern
2277
 
#ifdef __STDC__
2278
 
#define _ANSI(args)   (args)
2279
 
#else
2280
 
#define _ANSI(args) ()
2281
 
#endif
2282
 
</pre>
2283
 
</blockquote>
2284
 
 
2285
 
The following operators can appear in macro definitions:
2286
 
 
2287
 
<ul>
2288
 
<li><tt>#x</tt><br>
2289
 
Converts macro argument <tt>x</tt> to a string surrounded by double quotes ("x").
2290
 
 
2291
 
<p>
2292
 
<li><tt>x ## y</tt><br>
2293
 
Concatenates x and y together to form <tt>xy</tt>.
2294
 
 
2295
 
<p>
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.
2299
 
</ul>
2300
 
 
2301
 
<h3>SWIG Macros</h3>
2302
 
 
2303
 
SWIG provides an enhanced macro capability with the <tt>%define</tt> and <tt>%enddef</tt> directives. 
2304
 
For example:
2305
 
 
2306
 
<blockquote>
2307
 
<pre>
2308
 
%define ARRAYHELPER(type,name)
2309
 
%inline %{
2310
 
type *new_ ## name (int nitems) {
2311
 
   return (type *) malloc(sizeof(type)*nitems);
2312
 
}
2313
 
void delete_ ## name(type *t) {
2314
 
   free(t);
2315
 
}
2316
 
type name ## _get(type *t, int index) {
2317
 
   return t[index];
2318
 
}
2319
 
void name ## _set(type *t, int index, type val) {
2320
 
   t[index] = val;
2321
 
}
2322
 
%}
2323
 
%enddef
2324
 
 
2325
 
ARRAYHELPER(int, IntArray)
2326
 
ARRAYHELPER(double, DoubleArray)
2327
 
</pre>
2328
 
</blockquote>
2329
 
 
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.
2335
 
 
2336
 
<p>
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
2339
 
support).
2340
 
 
2341
 
<h3>Preprocessing and %{ ... %} blocks</h3>
2342
 
 
2343
 
The SWIG preprocessor does not process any text enclosed in a code block %{ ... %}.  Therefore,
2344
 
if you write code like this,
2345
 
 
2346
 
<blockquote>
2347
 
<pre>
2348
 
%{
2349
 
#ifdef NEED_BLAH
2350
 
int blah() {
2351
 
   ...
2352
 
}
2353
 
#endif
2354
 
%}
2355
 
</pre>
2356
 
</blockquote>
2357
 
 
2358
 
the contents of the <tt>%{ ... %}</tt> block are copied without
2359
 
modification to the output (including all preprocessor directives).
2360
 
 
2361
 
<h3>Preprocessing and { ... }</h3>
2362
 
 
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
2365
 
file.  For example:
2366
 
 
2367
 
<blockquote>
2368
 
<pre>
2369
 
%addmethods Foo {
2370
 
   void bar() {
2371
 
      #ifdef DEBUG
2372
 
       printf("I'm in bar\n");
2373
 
      #endif
2374
 
   }
2375
 
}
2376
 
</pre>
2377
 
</blockquote>
2378
 
 
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:
2381
 
 
2382
 
<blockquote>
2383
 
<pre>
2384
 
%addmethods Foo {
2385
 
   void bar() {
2386
 
      %#ifdef DEBUG
2387
 
       printf("I'm in bar\n");
2388
 
      %#endif
2389
 
   }
2390
 
}
2391
 
</pre>
2392
 
</blockquote>
2393
 
 
2394
 
SWIG will strip the extra <tt>%</tt> and leave the preprocessor directive in the code.
2395
 
 
2396
 
<h2>An Interface Building Strategy</h2>
 
2471
<a name="n45"></a><H2>4.7 An Interface Building Strategy</H2>
 
2472
 
2397
2473
 
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>
2401
2477
 
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>
 
2479
 
2403
2480
 
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
2442
2519
have worked very hard to improve the SWIG parser--you should report parsing errors
2443
2520
to <tt>swig-dev@cs.uchicago.edu</tt> or to the SWIG bug tracker on <tt>www.swig.org</tt>.
2444
2521
 
2445
 
<h3> The SWIG interface file</h3>
 
2522
<a name="n47"></a><H3>4.7.2 The SWIG interface file</H3>
 
2523
 
2446
2524
 
2447
2525
The preferred method of using SWIG is to generate separate interface
2448
2526
file. Suppose you have the following C header file :<p>
2484
2562
<p>
2485
2563
Naturally, your mileage may vary.<p>
2486
2564
 
2487
 
<h3>Why use separate interface files?</h3>
 
2565
<a name="n48"></a><H3>4.7.3 Why use separate interface files?</H3>
 
2566
 
2488
2567
 
2489
2568
Although SWIG can parse many header files, it is more common to write a
2490
2569
special <tt>.i</tt> file defining the interface to a package. There
2510
2589
header files.
2511
2590
</ul>
2512
2591
 
2513
 
<h3>Getting the right header files</h3>
 
2592
<a name="n49"></a><H3>4.7.4 Getting the right header files</H3>
 
2593
 
2514
2594
 
2515
2595
Sometimes, it is necessary to use certain header files in order for
2516
2596
the code generated by SWIG to compile properly. Make sure you
2527
2607
...
2528
2608
</pre></blockquote>
2529
2609
 
2530
 
<h3> What to do with main()</h3>
 
2610
<a name="n50"></a><H3>4.7.5 What to do with main()</H3>
 
2611
 
2531
2612
 
2532
2613
If your program defines a <tt>main()</tt> function, you may need to
2533
2614
get rid of it or rename it in order to use a scripting language. Most
2562
2643
<tt>main()</tt> program can be completely replaced by a Perl, Python,
2563
2644
or Tcl script.<p>
2564
2645
 
2565
 
<h3> How to avoid creating the interface from hell</h3>
2566
 
 
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:
2574
2646
<p>
2575
 
<ul>
2576
 
<li>It is usually not necessary to wrap every single function in a package.
2577
 
Try to eliminate the unneeded ones.
2578
 
 
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.
2582
 
 
2583
 
<li>Eliminate unneeded members of C++ classes.
2584
 
 
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.
2587
 
 
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.
2592
 
</ul>
 
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.
2593
2655
 
2594
2656
<p><hr>
2595
2657
 
2596
 
<address>SWIG 1.3 - Last Modified : December 30, 2001</address>
 
2658
<address>SWIG 1.3 - Last Modified : August 7, 2003</address>
2597
2659
</body>
2598
 
</html>
 
2660
</html>
 
 
b'\\ No newline at end of file'