import source from 1.3.40
[external/swig.git] / Doc / Manual / SWIG.html
1 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
2 <html>
3 <head>
4 <title>SWIG Basics</title>
5 <link rel="stylesheet" type="text/css" href="style.css">
6 </head>
7
8 <body bgcolor="#ffffff">
9 <H1><a name="SWIG"></a>5 SWIG Basics</H1>
10 <!-- INDEX -->
11 <div class="sectiontoc">
12 <ul>
13 <li><a href="#SWIG_nn2">Running SWIG</a>
14 <ul>
15 <li><a href="#SWIG_nn3">Input format</a>
16 <li><a href="#output">SWIG Output</a>
17 <li><a href="#SWIG_nn5">Comments</a>
18 <li><a href="#SWIG_nn6">C Preprocessor</a>
19 <li><a href="#SWIG_nn7">SWIG Directives</a>
20 <li><a href="#SWIG_nn8">Parser Limitations</a>
21 </ul>
22 <li><a href="#SWIG_nn9">Wrapping Simple C Declarations</a>
23 <ul>
24 <li><a href="#SWIG_nn10">Basic Type Handling</a>
25 <li><a href="#SWIG_nn11">Global Variables</a>
26 <li><a href="#SWIG_nn12">Constants</a>
27 <li><a href="#SWIG_nn13">A brief word about <tt>const</tt></a>
28 <li><a href="#SWIG_nn14">A cautionary tale of <tt>char *</tt></a>
29 </ul>
30 <li><a href="#SWIG_nn15">Pointers and complex objects</a>
31 <ul>
32 <li><a href="#SWIG_nn16">Simple pointers</a>
33 <li><a href="#SWIG_nn17">Run time pointer type checking</a>
34 <li><a href="#SWIG_nn18">Derived types, structs, and classes</a>
35 <li><a href="#SWIG_nn19">Undefined datatypes</a>
36 <li><a href="#SWIG_nn20">Typedef</a>
37 </ul>
38 <li><a href="#SWIG_nn21">Other Practicalities</a>
39 <ul>
40 <li><a href="#SWIG_nn22">Passing structures by value</a>
41 <li><a href="#SWIG_nn23">Return by value</a>
42 <li><a href="#SWIG_nn24">Linking to structure variables</a>
43 <li><a href="#SWIG_nn25">Linking to <tt>char *</tt></a>
44 <li><a href="#SWIG_nn26">Arrays</a>
45 <li><a href="#SWIG_readonly_variables">Creating read-only variables</a>
46 <li><a href="#SWIG_rename_ignore">Renaming and ignoring declarations</a>
47 <li><a href="#SWIG_default_args">Default/optional arguments</a>
48 <li><a href="#SWIG_nn30">Pointers to functions and callbacks</a>
49 </ul>
50 <li><a href="#SWIG_nn31">Structures and unions</a>
51 <ul>
52 <li><a href="#SWIG_nn32">Typedef and structures</a>
53 <li><a href="#SWIG_nn33">Character strings and structures</a>
54 <li><a href="#SWIG_nn34">Array members</a>
55 <li><a href="#SWIG_structure_data_members">Structure data members</a>
56 <li><a href="#SWIG_nn36">C constructors and destructors</a>
57 <li><a href="#SWIG_adding_member_functions">Adding member functions to C structures</a>
58 <li><a href="#SWIG_nested_structs">Nested structures</a>
59 <li><a href="#SWIG_nn39">Other things to note about structure wrapping</a>
60 </ul>
61 <li><a href="#SWIG_nn40">Code Insertion</a>
62 <ul>
63 <li><a href="#SWIG_nn41">The output of SWIG</a>
64 <li><a href="#SWIG_nn42">Code insertion blocks</a>
65 <li><a href="#SWIG_nn43">Inlined code blocks</a>
66 <li><a href="#SWIG_nn44">Initialization blocks</a>
67 </ul>
68 <li><a href="#SWIG_nn45">An Interface Building Strategy</a>
69 <ul>
70 <li><a href="#SWIG_nn46">Preparing a C program for SWIG</a>
71 <li><a href="#SWIG_nn47">The SWIG interface file</a>
72 <li><a href="#SWIG_nn48">Why use separate interface files?</a>
73 <li><a href="#SWIG_nn49">Getting the right header files</a>
74 <li><a href="#SWIG_nn50">What to do with main()</a>
75 </ul>
76 </ul>
77 </div>
78 <!-- INDEX -->
79
80
81
82 <p>
83 This chapter describes the basic operation of SWIG, the structure of its
84 input files, and how it handles standard ANSI C declarations.  C++ support is
85 described in the next chapter.  However, C++ programmers should still read this
86 chapter to understand the basics.
87 Specific details about each target language are described in later
88 chapters. 
89 </p>
90
91 <H2><a name="SWIG_nn2"></a>5.1 Running SWIG</H2>
92
93
94 <p>
95 To run SWIG, use the <tt>swig</tt> command with options options and a filename like this:
96 </p>
97
98 <div class="shell"><pre>
99 swig [ <em>options</em> ] filename
100 </pre></div>
101
102 <p>
103 where <tt>filename</tt> is a SWIG interface file or a C/C++ header file.
104 Below is a subset of <em>options</em> that can be used.
105 Additional options are also defined for each target language.  A full list
106 can be obtained by typing <tt>swig -help</tt> or <tt>swig
107 -<em>lang</em> -help</tt>.
108 </p>
109
110 <div class="shell"><pre>
111 -allegrocl            Generate ALLEGROCL wrappers
112 -chicken              Generate CHICKEN wrappers
113 -clisp                Generate CLISP wrappers
114 -cffi                 Generate CFFI wrappers
115 -csharp               Generate C# wrappers
116 -guile                Generate Guile wrappers
117 -java                 Generate Java wrappers
118 -lua                  Generate Lua wrappers
119 -modula3              Generate Modula 3 wrappers
120 -mzscheme             Generate Mzscheme wrappers
121 -ocaml                Generate Ocaml wrappers
122 -perl                 Generate Perl wrappers
123 -php                  Generate PHP wrappers
124 -pike                 Generate Pike wrappers
125 -python               Generate Python wrappers
126 -r                    Generate R (aka GNU S) wrappers
127 -ruby                 Generate Ruby wrappers
128 -sexp                 Generate Lisp S-Expressions wrappers
129 -tcl                  Generate Tcl wrappers
130 -uffi                 Generate Common Lisp / UFFI wrappers
131 -xml                  Generate XML wrappers
132
133 -c++                  Enable C++ parsing
134 -D<em>symbol</em>              Define a preprocessor symbol
135 -Fstandard            Display error/warning messages in commonly used format
136 -Fmicrosoft           Display error/warning messages in Microsoft format
137 -help                 Display all options
138 -I<em>dir</em>                 Add a directory to the file include path
139 -l<em>file</em>                Include a SWIG library file.
140 -module <em>name</em>          Set the name of the SWIG module
141 -o <em>outfile</em>            Name of output file
142 -outcurrentdir        Set default output dir to current dir instead of input file's path
143 -outdir <em>dir</em>           Set language specific files output directory
144 -swiglib              Show location of SWIG library
145 -version              Show SWIG version number
146
147 </pre></div>
148
149 <H3><a name="SWIG_nn3"></a>5.1.1 Input format</H3>
150
151
152 <p>
153 As input, SWIG expects a file containing ANSI C/C++ declarations and
154 special SWIG directives.  More often than not, this is a special SWIG
155 interface file which is usually denoted with a special <tt>.i</tt> or
156 <tt>.swg</tt> suffix.  In certain cases, SWIG can be used directly on
157 raw header files or source files.  However, this is not the most
158 typical case and there are several reasons why you might not want to
159 do this (described later).
160 </p>
161
162 <p>
163 The most common format of a SWIG interface is as follows:
164 </p>
165
166 <div class="code"><pre>
167 %module mymodule 
168 %{
169 #include "myheader.h"
170 %}
171 // Now list ANSI C/C++ declarations
172 int foo;
173 int bar(int x);
174 ...
175 </pre></div>
176 <p>
177 The module name is supplied using the special <tt>%module</tt>
178 directive. Modules are described further in the <a href="Modules.html#Modules_introduction">Modules Introduction</a> section.
179 </p>
180
181 <p>
182 Everything in the <tt>%{ ... %}</tt> block is simply copied verbatim
183 to the resulting wrapper file created by SWIG.  This section is almost
184 always used to include header files and other declarations that are
185 required to make the generated wrapper code compile.  It is important
186 to emphasize that just because you include a declaration in a SWIG
187 input file, that declaration does <em>not</em> automatically appear in
188 the generated wrapper code---therefore you need to make sure you
189 include the proper header files in the <tt>%{ ... %}</tt> section.  It
190 should be noted that the text enclosed in <tt>%{ ... %}</tt> is not
191 parsed or interpreted by SWIG.  The <tt>%{...%}</tt> syntax and
192 semantics in SWIG is analogous to that of the declarations section
193 used in input files to parser generation tools such as yacc or bison.
194 </p>
195
196 <H3><a name="output"></a>5.1.2 SWIG Output</H3>
197
198
199 <p>
200 The output of SWIG is a C/C++ file that contains all of the wrapper
201 code needed to build an extension module.  SWIG may generate some
202 additional files depending on the target language. By default, an input file
203 with the name <tt>file.i</tt> is transformed into a file
204 <tt>file_wrap.c</tt> or <tt>file_wrap.cxx</tt> (depending on whether
205 or not the <tt>-c++</tt> option has been used).  The name of the
206 output file can be changed using the <tt>-o</tt> option.  In certain
207 cases, file suffixes are used by the compiler to determine the source
208 language (C, C++, etc.). Therefore, you have to use the
209 <tt>-o</tt> option to change the suffix of the SWIG-generated wrapper
210 file if you want something different than the default. For example:
211 </p>
212
213 <div class="shell"><pre>
214 $ swig -c++ -python -o example_wrap.cpp example.i
215 </pre></div>
216
217 <p>
218 The C/C++ output file created by SWIG often
219 contains everything that is needed to construct a extension module
220 for the target scripting language. SWIG is not a stub compiler nor is it
221 usually necessary to edit the output file (and if you look at the output,
222 you probably won't want to). To build the final extension module, the
223 SWIG output file is compiled and linked with the rest of your C/C++
224 program to create a shared library. 
225 </p>
226
227 <p>
228 Many target languages will also generate proxy class files in the
229 target language. The default output directory for these language 
230 specific files is the same directory as the generated C/C++ file. This
231 can be modified using the <tt>-outdir</tt> option. For example:
232 </p>
233
234 <div class="shell"><pre>
235 $ swig -c++ -python -outdir pyfiles -o cppfiles/example_wrap.cpp example.i
236 </pre></div>
237 <p>
238 If the directories <tt>cppfiles</tt> and <tt>pyfiles</tt> exist, the following
239 will be generated:</p>
240 <div class="shell"><pre>
241 cppfiles/example_wrap.cpp
242 pyfiles/example.py
243 </pre></div>
244
245 <p>
246 If the <tt>-outcurrentdir</tt> option is used (without <tt>-o</tt>)
247 then SWIG behaves like a typical C/C++
248 compiler and the default output directory is then the current directory. Without
249 this option the default output directory is the path to the input file. 
250 If <tt>-o</tt> and
251 <tt>-outcurrentdir</tt> are used together, <tt>-outcurrentdir</tt> is effectively ignored
252 as the output directory for the language files is the same directory as the
253 generated C/C++ file if not overidden with <tt>-outdir</tt>.
254 </p>
255
256 <H3><a name="SWIG_nn5"></a>5.1.3 Comments</H3>
257
258
259 <p>
260 C and C++ style comments may appear anywhere in interface files.  In
261 previous versions of SWIG, comments were used to generate
262 documentation files. However, this feature is currently under repair
263 and will reappear in a later SWIG release.
264 </p>
265
266 <H3><a name="SWIG_nn6"></a>5.1.4 C Preprocessor</H3>
267
268
269 <p>
270 Like C, SWIG preprocesses all input files through an enhanced version
271 of the C preprocessor.  All standard preprocessor features are
272 supported including file inclusion, conditional compilation and
273 macros. However, <tt>#include</tt> statements are ignored unless the
274 <tt>-includeall</tt> command line option has been supplied.  The
275 reason for disabling includes is that SWIG is sometimes used to
276 process raw C header files.  In this case, you usually only want the
277 extension module to include functions in the supplied header file
278 rather than everything that might be included by that header file
279 (i.e., system headers, C library functions, etc.).
280 </p>
281
282 <p>
283 It should also be noted that the SWIG preprocessor skips all text
284 enclosed inside a <tt>%{...%}</tt> block.  In addition, the
285 preprocessor includes a number of macro handling enhancements that
286 make it more powerful than the normal C preprocessor.  These
287 extensions are described in the "<a href="Preprocessor.html#Preprocessor">Preprocessor</a>" chapter.
288 </p>
289
290 <H3><a name="SWIG_nn7"></a>5.1.5 SWIG Directives</H3>
291
292
293 <p>
294 Most of SWIG's operation is controlled by special directives that are
295 always preceded by a "<tt>%</tt>" to distinguish them from normal C
296 declarations. These directives are used to give SWIG hints or to alter
297 SWIG's parsing behavior in some manner.   
298 </p>
299
300 <p>
301 Since SWIG directives are not legal C syntax, it is generally not
302 possible to include them in header files.  However, SWIG directives can be
303 included in C header files using conditional compilation like this:
304 </p>
305
306 <div class="code"><pre>
307 /* header.h  --- Some header file */
308
309 /* SWIG directives -- only seen if SWIG is running */ 
310 #ifdef SWIG
311 %module foo
312 #endif
313 </pre>
314 </div>
315
316 <p>
317 <tt>SWIG</tt> is a special preprocessing symbol defined by SWIG when
318 it is parsing an input file.
319 </p>
320
321 <H3><a name="SWIG_nn8"></a>5.1.6 Parser Limitations</H3>
322
323
324 <p>
325 Although SWIG can parse most C/C++ declarations, it does not
326 provide a complete C/C++ parser implementation.  Most of these
327 limitations pertain to very complicated type declarations and certain
328 advanced C++ features.  Specifically, the following features are not
329 currently supported:
330 </p>
331
332 <ul>
333 <li>Non-conventional type declarations.
334 For example, SWIG does not support declarations such as the following
335 (even though this is legal C):
336
337 <div class="code">
338 <pre>
339 /* Non-conventional placement of storage specifier (extern) */
340 const int extern Number;
341
342 /* Extra declarator grouping */
343 Matrix (foo);    // A global variable
344
345 /* Extra declarator grouping in parameters */
346 void bar(Spam (Grok)(Doh));
347
348 </pre>
349 </div>
350
351 <p>
352 In practice, few (if any) C programmers actually write code like
353 this since this style is never featured in programming books.  However,
354 if you're feeling particularly obfuscated, you can certainly break SWIG (although why would you want to?).
355 </p>
356 </li>
357
358 <li>Running SWIG on C++ source files (what would appear in a .C or .cxx file) 
359 is not recommended.  Even though SWIG can parse C++ class declarations,
360 it ignores declarations that are decoupled from their
361 original class definition (the declarations are parsed, but a lot of warning
362 messages may be generated).  For example:
363
364 <div class="code">
365 <pre>
366 /* Not supported by SWIG */
367 int foo::bar(int) {
368     ... whatever ...
369 }
370 </pre>
371 </div>
372 </li>
373
374 <li>Certain advanced features of C++ such as nested classes 
375 are not yet supported. Please see the section on using SWIG
376 with C++ for more information.
377 </ul>
378
379 <p>
380 In the event of a parsing error, conditional compilation can be used to skip
381 offending code.  For example:
382 </p>
383
384 <div class="code">
385 <pre>
386 #ifndef SWIG
387 ... some bad declarations ...
388 #endif
389 </pre>
390 </div>
391 <p>
392 Alternatively, you can just delete the offending code from the interface file.
393 </p>
394
395 <p>
396 One of the reasons why SWIG does not provide a full C++ parser
397 implementation is that it has been designed to work with incomplete
398 specifications and to be very permissive in its handling of C/C++
399 datatypes (e.g., SWIG can generate interfaces even when there are
400 missing class declarations or opaque datatypes).  Unfortunately, this
401 approach makes it extremely difficult to implement certain parts of a
402 C/C++ parser as most compilers use type information to assist in the
403 parsing of more complex declarations (for the truly curious, the
404 primary complication in the implementation is that the SWIG parser
405 does not utilize a separate <em>typedef-name</em> terminal symbol as
406 described on p. 234 of K&amp;R).
407 </p>
408
409 <H2><a name="SWIG_nn9"></a>5.2 Wrapping Simple C Declarations</H2>
410
411
412 <p>
413 SWIG wraps simple C declarations by creating an interface that closely matches
414 the way in which the declarations would be used in a C program.
415 For example, consider the following interface file:
416 </p>
417
418 <div class="code"><pre>
419 %module example
420
421 %inline %{
422 extern double sin(double x);
423 extern int strcmp(const char *, const char *);
424 extern int Foo;
425 %}
426 #define STATUS 50
427 #define VERSION "1.1"
428 </pre></div>
429 <p>
430 In this file, there are two functions <tt>sin()</tt> and <tt>strcmp()</tt>,
431 a global variable <tt>Foo</tt>, and two constants <tt>STATUS</tt> and
432 <tt>VERSION</tt>.  When SWIG creates an extension module, these
433 declarations are accessible as scripting language functions, variables, and
434 constants respectively.  For example, in Tcl:
435 </p>
436
437 <div class="targetlang"><pre>
438 % sin 3
439 5.2335956
440 % strcmp Dave Mike
441 -1
442 % puts $Foo
443 42
444 % puts $STATUS
445 50
446 % puts $VERSION
447 1.1
448 </pre></div>
449 <p>
450 Or in Python:
451 </p>
452
453 <div class="targetlang"><pre>
454 &gt;&gt;&gt; example.sin(3)
455 5.2335956
456 &gt;&gt;&gt; example.strcmp('Dave','Mike')
457 -1
458 &gt;&gt;&gt; print example.cvar.Foo
459 42
460 &gt;&gt;&gt; print example.STATUS
461 50
462 &gt;&gt;&gt; print example.VERSION
463 1.1
464 </pre></div>
465 <p>
466 Whenever possible, SWIG creates an interface that closely matches the underlying C/C++
467 code. However, due to subtle differences between languages, run-time
468 environments, and semantics, it is not always possible to do so.   The
469 next few sections describes various aspects of this mapping.
470 </p>
471
472 <H3><a name="SWIG_nn10"></a>5.2.1 Basic Type Handling</H3>
473
474
475 <p>
476 In order to build an interface, SWIG has to convert C/C++ datatypes to
477 equivalent types in the target language.  Generally,
478 scripting languages provide a more limited set of primitive types than C.
479 Therefore, this conversion process involves a certain amount of type
480 coercion.
481 </p>
482
483 <p>
484 Most scripting languages provide a single integer type that is implemented using
485 the <tt>int</tt> or <tt>long</tt> datatype in C.   The following list shows
486 all of the C datatypes that SWIG will convert to and from integers in the target language:
487 </p>
488
489 <div class="code"><pre>
490 int
491 short
492 long
493 unsigned
494 signed
495 unsigned short
496 unsigned long
497 unsigned char
498 signed char
499 bool
500 </pre></div>
501
502 <p>
503 When an integral value is converted from C, a cast is used to convert it to
504 the representation in the target language.
505 Thus, a 16 bit short in C may be promoted to a 32 bit integer.  When integers are 
506 converted in the other direction, the value is cast back into the original C type.  
507 If the value is too large to fit, it is silently truncated.
508 <!-- Dave: Maybe we should fix this -->
509 </p>
510
511 <p>
512 <tt>unsigned char</tt> and <tt>signed char</tt> are special cases that
513 are handled as small 8-bit integers. Normally, the <tt>char</tt>
514 datatype is mapped as a one-character ASCII string. </p>
515
516 <p>
517 The <tt>bool</tt> datatype is cast to and from an integer value of 0
518 and 1 unless the target language provides a special boolean type.</p>
519
520 <p>
521 Some care is required when working with large integer values. Most
522 scripting languages use 32-bit integers so mapping a 64-bit long
523 integer may lead to truncation errors. Similar problems may arise with
524 32 bit unsigned integers (which may appear as large negative
525 numbers). As a rule of thumb, the <tt>int</tt> datatype and all
526 variations of <tt>char</tt> and <tt>short</tt> datatypes are safe to
527 use. For <tt>unsigned int</tt> and <tt>long</tt> datatypes, you will
528 need to carefully check the correct operation of your program after
529 it has been wrapped with SWIG.
530 </p>
531
532 <p>
533 Although the SWIG parser supports the <tt>long long</tt> datatype, not
534 all language modules support it.  This is because <tt>long long</tt>
535 usually exceeds the integer precision available in the target
536 language.  In certain modules such as Tcl and Perl5, <tt>long
537 long</tt> integers are encoded as strings. This allows the full range
538 of these numbers to be represented.  However, it does not allow
539 <tt>long long</tt> values to be used in arithmetic expressions.  It
540 should also be noted that although <tt>long long</tt> is part
541 of the ISO C99 standard, it is not universally supported by all C
542 compilers.  Make sure you are using a compiler that supports <tt>long
543 long</tt> before trying to use this type with SWIG.
544 </p>
545
546 <p>
547 SWIG recognizes the following floating point types :</p>
548
549 <div class="code"><pre>
550 float
551 double
552 </pre></div>
553
554 <p>
555 Floating point numbers are mapped to and from the natural
556 representation of floats in the target language. This is almost always
557 a C <tt>double</tt>. The rarely used datatype of <tt>long double</tt>
558 is not supported by SWIG.</p>
559
560 <p>
561 The <tt>char</tt> datatype is mapped into a NULL terminated ASCII
562 string with a single character. When used in a scripting language it
563 shows up as a tiny string containing the character value. When
564 converting the value back into C, SWIG takes a character string
565 from the scripting language and strips off the first character as the
566 char value. Thus if the value "foo" is assigned to a
567 <tt>char</tt> datatype, it gets the value `f'.</p>
568
569 <p>
570 The <tt>char *</tt> datatype is handled as a NULL-terminated ASCII
571 string. SWIG maps this into a 8-bit character string in the target
572 scripting language. SWIG converts character strings in the target
573 language to NULL terminated strings before passing them into
574 C/C++. The default handling of these strings does not allow them to
575 have embedded NULL bytes.  Therefore, the <tt>char *</tt> datatype is
576 not generally suitable for passing binary data.  However, it is
577 possible to change this behavior by defining a SWIG typemap.  See the chapter
578 on <a href="Typemaps.html#Typemaps">Typemaps</a> for details about this.
579 </p>
580
581 <p>
582 At this time, SWIG provides limited support for Unicode and
583 wide-character strings (the C <tt>wchar_t</tt> type).  
584 Some languages provide typemaps for wchar_t, but bear in mind these
585 might not be portable across different operating systems.  This is a
586 delicate topic that is poorly understood by many programmers and not
587 implemented in a consistent manner across languages.  For those
588 scripting languages that provide Unicode support, Unicode strings are
589 often available in an 8-bit representation such as UTF-8 that can be
590 mapped to the <tt>char *</tt> type (in which case the SWIG interface
591 will probably work).  If the program you are wrapping uses Unicode,
592 there is no guarantee that Unicode characters in the target language
593 will use the same internal representation (e.g., UCS-2 vs. UCS-4).
594 You may need to write some special conversion functions.
595 </p>
596
597 <H3><a name="SWIG_nn11"></a>5.2.2 Global Variables</H3>
598
599
600 <p>
601 Whenever possible, SWIG maps C/C++ global variables into scripting language
602 variables.  For example,
603 </p>
604
605 <div class="code"><pre>
606 %module example
607 double foo;
608
609 </pre></div>
610 <p>
611 results in a scripting language variable like this:
612 </p>
613
614 <div class="code"><pre>
615 # Tcl
616 set foo [3.5]                   ;# Set foo to 3.5
617 puts $foo                       ;# Print the value of foo
618
619 # Python
620 cvar.foo = 3.5                  # Set foo to 3.5
621 print cvar.foo                  # Print value of foo
622
623 # Perl
624 $foo = 3.5;                     # Set foo to 3.5
625 print $foo,"\n";                # Print value of foo
626
627 # Ruby
628 Module.foo = 3.5               # Set foo to 3.5
629 print Module.foo, "\n"         # Print value of foo
630 </pre></div>
631 <p>
632 Whenever the scripting language variable is used, the underlying C
633 global variable is accessed.  Although SWIG makes every
634 attempt to make global variables work like scripting language
635 variables, it is not always possible to do so.  For instance, in
636 Python, all global variables must be accessed through a special
637 variable object known as <tt>cvar</tt> (shown above).  In Ruby, variables are
638 accessed as attributes of the module. Other languages may
639 convert variables to a pair of accessor functions.  For example, the
640 Java module generates a pair of functions <tt>double get_foo()</tt>
641 and <tt>set_foo(double val)</tt> that are used to manipulate the
642 value.
643 </p>
644
645 <p>
646 Finally, if a global variable has been declared as <tt>const</tt>, it
647 only supports read-only access.  Note: this behavior is new to SWIG-1.3.
648 Earlier versions of SWIG incorrectly handled <tt>const</tt> and created
649 constants instead.
650 </p>
651
652 <H3><a name="SWIG_nn12"></a>5.2.3 Constants</H3>
653
654
655 <p>
656 Constants can be created using <tt>#define</tt>, enumerations,
657 or a special <tt>%constant</tt> directive.  The following
658 interface file shows a few valid constant declarations :</p>
659
660 <div class="code"><pre>
661 #define I_CONST       5               // An integer constant
662 #define PI            3.14159         // A Floating point constant
663 #define S_CONST       "hello world"   // A string constant
664 #define NEWLINE       '\n'            // Character constant
665
666 enum boolean {NO=0, YES=1};
667 enum months {JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG,
668              SEP, OCT, NOV, DEC};
669 %constant double BLAH = 42.37;
670 #define PI_4 PI/4
671 #define FLAGS 0x04 | 0x08 | 0x40
672
673 </pre></div>
674 <p>
675 In <tt>#define</tt> declarations, the type of a constant is inferred
676 by syntax. For example, a number with a decimal point is assumed to be
677 floating point.  In addition, SWIG must be able to fully resolve all
678 of the symbols used in a <tt>#define</tt> in order for a constant to
679 actually be created.  This restriction is necessary because
680 <tt>#define</tt> is also used to define preprocessor macros that are
681 definitely not meant to be part of the scripting language interface.
682 For example:
683 </p>
684
685 <div class="code">
686 <pre>
687 #define EXTERN extern
688
689 EXTERN void foo();
690 </pre>
691 </div>
692 <p>
693 In this case, you probably don't want to create a constant called 
694 <tt>EXTERN</tt> (what would the value be?).  In general,
695 SWIG will not create constants for macros unless the value can
696 be completely determined by the preprocessor.  For instance, in the above example,
697 the declaration
698 </p>
699
700 <div class="code">
701 <pre>
702 #define PI_4  PI/4
703 </pre>
704 </div>
705 <p>
706 defines a constant because <tt>PI</tt> was already defined as a
707 constant and the value is known.
708 However, for the same conservative reasons even a constant with a simple cast will be ignored, such as
709 </p>
710
711 <div class="code">
712 <pre>
713 #define F_CONST (double) 5            // A floating pointer constant with cast
714 </pre>
715 </div>
716
717 <p>
718 The use of constant expressions is allowed, but SWIG does not evaluate
719 them. Rather, it passes them through to the output file and lets the C
720 compiler perform the final evaluation (SWIG does perform a limited
721 form of type-checking however).</p>
722
723 <p>
724 For enumerations, it is critical that the original enum definition be
725 included somewhere in the interface file (either in a header file or
726 in the <tt>%{,%}</tt> block). SWIG only translates the enumeration
727 into code needed to add the constants to a scripting language. It
728 needs the original enumeration declaration in order to get the correct
729 enum values as assigned by the C compiler.
730 </p>
731
732 <p>
733 The <tt>%constant</tt> directive is used to more precisely create
734 constants corresponding to different C datatypes.  Although it is not
735 usually not needed for simple values, it is more useful when working
736 with pointers and other more complex datatypes.  Typically, <tt>%constant</tt>
737 is only used when you want to add constants to the scripting language
738 interface that are not defined in the original header file. 
739 </p>
740
741 <H3><a name="SWIG_nn13"></a>5.2.4 A brief word about <tt>const</tt></H3>
742
743
744 <p>
745 A common confusion with C programming is the semantic meaning of the
746 <tt>const</tt> qualifier in declarations--especially when it is mixed
747 with pointers and other type modifiers. In fact, previous versions of SWIG
748 handled <tt>const</tt> incorrectly--a situation that SWIG-1.3.7 and newer
749 releases have fixed.
750 </p>
751
752 <p>
753 Starting with SWIG-1.3, all variable declarations, regardless of any
754 use of <tt>const</tt>, are wrapped as global variables.  If a
755 declaration happens to be declared as <tt>const</tt>, it is wrapped as
756 a read-only variable. To tell if a variable is <tt>const</tt> or not,
757 you need to look at the right-most occurrence of the <tt>const</tt>
758 qualifier (that appears before the variable name).  If the right-most
759 <tt>const</tt> occurs after all other type modifiers (such as
760 pointers), then the variable is <tt>const</tt>.  Otherwise, it is not.
761 </p>
762
763 <p>
764 Here are some examples of <tt>const</tt> declarations.
765 </p>
766
767 <div class="code">
768 <pre>
769 const char a;           // A constant character
770 char const b;           // A constant character (the same)
771 char *const c;          // A constant pointer to a character
772 const char *const d;    // A constant pointer to a constant character
773 </pre>
774 </div>
775 <p>
776 Here is an example of a declaration that is not <tt>const</tt>:
777 </p>
778
779 <div class="code">
780 <pre>
781 const char *e;          // A pointer to a constant character.  The pointer
782                         // may be modified.
783 </pre>
784 </div>
785 <p>
786 In this case, the pointer <tt>e</tt> can change---it's only the value
787 being pointed to that is read-only.
788 </p>
789
790 <p>
791 <b>Compatibility Note:</b> One reason for changing SWIG to handle
792 <tt>const</tt> declarations as read-only variables is that there are
793 many situations where the value of a <tt>const</tt> variable might
794 change.  For example, a library might export a symbol as
795 <tt>const</tt> in its public API to discourage modification, but still
796 allow the value to change through some other kind of internal
797 mechanism.  Furthermore, programmers often overlook the fact that with
798 a constant declaration like <tt>char *const</tt>, the underlying data
799 being pointed to can be modified--it's only the pointer itself that is
800 constant.  In an embedded system, a <tt>const</tt> declaration might
801 refer to a read-only memory address such as the location of a
802 memory-mapped I/O device port (where the value changes, but writing to
803 the port is not supported by the hardware).  Rather than trying to
804 build a bunch of special cases into the <tt>const</tt> qualifier, the
805 new interpretation of <tt>const</tt> as "read-only" is simple and
806 exactly matches the actual semantics of <tt>const</tt> in C/C++.  If
807 you really want to create a constant as in older versions of SWIG, use
808 the <tt>%constant</tt> directive instead.  For example:
809 </p>
810
811 <div class="code">
812 <pre>
813 %constant double PI = 3.14159;
814 </pre>
815 </div>
816
817 <p>
818 or
819 </p>
820
821 <div class="code">
822 <pre>
823 #ifdef SWIG
824 #define const %constant
825 #endif
826 const double foo = 3.4;
827 const double bar = 23.4;
828 const int    spam = 42;
829 #ifdef SWIG
830 #undef const
831 #endif
832 ...
833
834 </pre>
835 </div>
836
837 <H3><a name="SWIG_nn14"></a>5.2.5 A cautionary tale of <tt>char *</tt></H3>
838
839
840 <p>
841 Before going any further, there is one bit of caution involving
842 <tt>char *</tt> that must now be mentioned.  When strings are passed
843 from a scripting language to a C <tt>char *</tt>, the pointer usually
844 points to string data stored inside the interpreter.  It is almost
845 always a really bad idea to modify this data.  Furthermore, some
846 languages may explicitly disallow it.  For instance, in Python,
847 strings are supposed be immutable.   If you violate this, you will probably
848 receive a vast amount of wrath when you unleash your module on the world.
849 </p>
850
851 <p>
852 The primary source of problems are functions that might modify string data in place.
853 A classic example would be a function like this:
854 </p>
855
856 <div class="code">
857 <pre>
858 char *strcat(char *s, const char *t)
859 </pre>
860 </div>
861
862 <p>
863 Although SWIG will certainly generate a wrapper for this, its behavior
864 will be undefined.  In fact, it will probably cause your application
865 to crash with a segmentation fault or other memory related problem.
866 This is because <tt>s</tt> refers to some internal data in the target
867 language---data that you shouldn't be touching.
868 </p>
869
870 <p>
871 The bottom line: don't rely on <tt>char *</tt> for anything other than read-only 
872 input values.   However, it must be noted that you could change the behavior of SWIG
873 using <a href="Typemaps.html#Typemaps">typemaps</a>.  
874 </p>
875
876 <H2><a name="SWIG_nn15"></a>5.3 Pointers and complex objects</H2>
877
878
879 <p>
880 Most C programs manipulate arrays, structures, and other types of objects.  This section
881 discusses the handling of these datatypes.
882 </p>
883
884 <H3><a name="SWIG_nn16"></a>5.3.1 Simple pointers</H3>
885
886
887 <p>
888 Pointers to primitive C datatypes such as </p>
889
890 <div class="code"><pre>
891 int *
892 double ***
893 char **
894 </pre></div>
895 <p>
896 are fully supported by SWIG.  Rather than trying to convert the data being pointed to into a scripting
897 representation, SWIG simply encodes the pointer itself into a
898 representation that contains the actual value of the pointer and a type-tag.
899 Thus, the SWIG representation of the above
900 pointers (in Tcl), might look like this:</p>
901
902 <div class="targetlang"><pre>
903 _10081012_p_int
904 _1008e124_ppp_double
905 _f8ac_pp_char
906 </pre></div>
907
908 <p>
909 A NULL pointer is represented by the string "NULL" or the value 0
910 encoded with type information.</p>
911
912 <p>
913 All pointers are treated as opaque objects by SWIG. Thus, a pointer
914 may be returned by a function and passed around to other C functions
915 as needed.  For all practical purposes, the scripting language
916 interface works in exactly the same way as you would use the
917 pointer in a C program.  The only difference is that there is no mechanism for
918 dereferencing the pointer since this would require the target language
919 to understand the memory layout of the underlying object.
920 </p>
921
922 <p>
923 The scripting language representation of a pointer value should never be
924 manipulated directly.   Even though the values shown look like hexadecimal
925 addresses, the numbers used may differ from the actual machine address (e.g.,
926 on little-endian machines, the digits may appear in reverse order).
927 Furthermore, SWIG does not
928 normally map pointers into high-level objects such as associative
929 arrays or lists (for example, converting an
930 <tt>int *</tt> into an list of integers). There are several reasons
931 why SWIG does not do this:</p>
932
933 <ul>
934 <li>There is not enough information in a C declaration to properly map
935 pointers into higher level constructs. For example, an <tt>int *</tt>
936 may indeed be an array of integers, but if it contains ten million
937 elements, converting it into a list object is probably a bad idea.
938 </li>
939
940 <li>The underlying semantics associated with a pointer is not known
941 by SWIG.   For instance, an <tt>int *</tt> might not be an array at all--perhaps it
942 is an output value!
943 </li>
944
945 <li>By handling all pointers in a consistent manner, the implementation of SWIG is greatly
946 simplified and less prone to error.
947 </li>
948 </ul>
949
950 <H3><a name="SWIG_nn17"></a>5.3.2 Run time pointer type checking</H3>
951
952
953 <p>
954 By allowing pointers to be manipulated from a scripting language, extension modules
955 effectively bypass compile-time type checking in the C/C++
956 compiler.  To prevent errors, a type signature is encoded into all
957 pointer values and is used to perform run-time type checking.  This
958 type-checking process is an integral part of SWIG and can not be
959 disabled or modified without using typemaps (described in later
960 chapters).
961 </p>
962
963 <p>
964 Like C, <tt>void *</tt> matches any kind of pointer.  Furthermore,
965 <tt>NULL</tt> pointers can be passed to any function that expects to
966 receive a pointer.  Although this has the potential to cause a crash,
967 <tt>NULL</tt> pointers are also sometimes used
968 as sentinel values or to denote a missing/empty value.  Therefore,
969 SWIG leaves NULL pointer checking up to the application.
970 </p>
971
972 <H3><a name="SWIG_nn18"></a>5.3.3 Derived types, structs, and classes</H3>
973
974
975 <p>
976 For everything else (structs, classes, arrays, etc...) SWIG applies a
977 very simple rule :</p>
978
979 <center>
980 <b>Everything else is a pointer</b>
981 </center>
982
983 <p>
984 In other words, SWIG manipulates everything else by reference. This
985 model makes sense because most C/C++ programs make heavy use of
986 pointers and SWIG can use the type-checked pointer mechanism already
987 present for handling pointers to basic datatypes.</p>
988
989 <p>
990 Although this probably sounds complicated, it's really quite
991 simple. Suppose you have an interface file like this :</p>
992
993 <div class="code"><pre>
994 %module fileio
995 FILE *fopen(char *, char *);
996 int fclose(FILE *);
997 unsigned fread(void *ptr, unsigned size, unsigned nobj, FILE *);
998 unsigned fwrite(void *ptr, unsigned size, unsigned nobj, FILE *);
999 void *malloc(int nbytes);
1000 void free(void *);
1001
1002 </pre></div>
1003
1004 <p>
1005 In this file, SWIG doesn't know what a <tt>FILE</tt> is, but since it's used
1006 as a pointer, so it doesn't really matter what it is. If you wrapped
1007 this module into Python, you can use the functions just like you
1008 expect :</p>
1009
1010 <div class="targetlang"><pre>
1011 # Copy a file 
1012 def filecopy(source,target):
1013         f1 = fopen(source,"r")
1014         f2 = fopen(target,"w")
1015         buffer = malloc(8192)
1016         nbytes = fread(buffer,8192,1,f1)
1017         while (nbytes &gt; 0):
1018                 fwrite(buffer,8192,1,f2)
1019                 nbytes = fread(buffer,8192,1,f1)
1020         free(buffer)
1021
1022 </pre></div>
1023
1024 <p>
1025 In this case <tt>f1</tt>,<tt> f2</tt>, and <tt>buffer</tt> are all
1026 opaque objects containing C pointers. It doesn't matter what value
1027 they contain--our program works just fine without this knowledge.</p>
1028
1029 <H3><a name="SWIG_nn19"></a>5.3.4 Undefined datatypes</H3>
1030
1031
1032 <p>
1033 When SWIG encounters an undeclared datatype, it automatically assumes
1034 that it is a structure or class. For example, suppose the following
1035 function appeared in a SWIG input file:</p>
1036
1037 <div class="code"><pre>
1038 void matrix_multiply(Matrix *a, Matrix *b, Matrix *c);
1039 </pre></div>
1040
1041 <p>
1042 SWIG has no idea what a "<tt>Matrix</tt>" is.  However, it is obviously
1043 a pointer to something so SWIG generates a wrapper using its generic pointer
1044 handling code. 
1045 </p>
1046
1047 <p>
1048 Unlike C or C++, SWIG does not actually care whether <tt>Matrix</tt>
1049 has been previously defined in the interface file or not.  This
1050 allows SWIG to generate interfaces from
1051 only partial or limited information. In some cases, you may not care
1052 what a <tt>Matrix</tt> really is as long as you can pass an opaque reference to
1053 one around in the scripting language interface.
1054 </p>
1055
1056 <p>
1057 An important detail to mention is that SWIG will gladly generate
1058 wrappers for an interface when there are unspecified type names.
1059 However, <b>all unspecified types are internally handled as pointers
1060 to structures or classes!</b> For example, consider the following declaration:
1061 </p>
1062
1063 <div class="code">
1064 <pre>
1065 void foo(size_t num);
1066 </pre>
1067 </div>
1068
1069 <p>
1070 If <tt>size_t</tt> is undeclared, SWIG generates wrappers
1071 that expect to receive a type of <tt>size_t *</tt> (this mapping is described shortly).
1072 As a result, the scripting interface might behave strangely.  For example:
1073 </p>
1074
1075 <div class="code">
1076 <pre>
1077 foo(40);
1078 TypeError: expected a _p_size_t.
1079 </pre>
1080 </div>
1081
1082 <p>
1083 The only way to fix this problem is to make sure you properly declare type names using
1084 <tt>typedef</tt>.
1085 </p>
1086
1087 <!-- We might want to add an error reporting flag to swig -->
1088
1089 <H3><a name="SWIG_nn20"></a>5.3.5 Typedef</H3>
1090
1091
1092 <p>
1093 Like C, <tt>typedef</tt> can be used to define new type names in SWIG. For example:
1094 </p>
1095
1096 <div class="code"><pre>
1097 typedef unsigned int size_t;
1098 </pre></div>
1099
1100 <p>
1101 <tt>typedef</tt> definitions appearing in a SWIG interface
1102 are not propagated to the generated wrapper code.  Therefore, they
1103 either need to be defined in an included header file or placed in the
1104 declarations section like this:
1105 </p>
1106
1107 <div class="code">
1108 <pre>
1109 %{
1110 /* Include in the generated wrapper file */
1111 typedef unsigned int size_t;
1112 %}
1113 /* Tell SWIG about it */
1114 typedef unsigned int size_t;
1115 </pre>
1116 </div>
1117
1118 <p>
1119 or
1120 </p>
1121
1122 <div class="code">
1123 <pre>
1124 %inline %{
1125 typedef unsigned int size_t;
1126 %}
1127 </pre>
1128 </div>
1129
1130 <p>
1131 In certain cases, you might be able to include other header files to collect type information.
1132 For example:
1133 </p>
1134
1135 <div class="code">
1136 <pre>
1137 %module example
1138 %import "sys/types.h"
1139 </pre>
1140 </div>
1141
1142 <p>
1143 In this case, you might run SWIG as follows:
1144 </p>
1145
1146 <div class="shell">
1147 <pre>
1148 $ swig -I/usr/include -includeall example.i
1149 </pre>
1150 </div>
1151
1152 <p>
1153 It should be noted that your mileage will vary greatly here.
1154 System headers are notoriously complicated and may rely upon a variety
1155 of non-standard C coding extensions (e.g., such as special directives
1156 to GCC).  Unless you exactly specify the right include directories and
1157 preprocessor symbols, this may not work correctly (you will have to
1158 experiment).
1159 </p>
1160
1161 <p>
1162 SWIG tracks <tt>typedef</tt> declarations and uses this information
1163 for run-time type checking. For instance, if you use the above <tt>typedef</tt> and
1164 had the following function declaration:
1165 </p>
1166
1167 <div class="code">
1168 <pre>
1169 void foo(unsigned int *ptr);
1170 </pre>
1171 </div>
1172
1173 <p>
1174 The corresponding wrapper function will accept arguments of
1175 type <tt>unsigned int *</tt> or <tt>size_t *</tt>.
1176 </p>
1177
1178 <H2><a name="SWIG_nn21"></a>5.4 Other Practicalities</H2>
1179
1180
1181 <p>
1182 So far, this chapter has presented almost everything you need to know to use SWIG
1183 for simple interfaces. However, some C programs use idioms that are somewhat
1184 more difficult to map to a scripting language interface.  This section describes
1185 some of these issues.
1186 </p>
1187
1188 <H3><a name="SWIG_nn22"></a>5.4.1 Passing structures by value</H3>
1189
1190
1191 <p>
1192 Sometimes a C function takes structure parameters that are passed
1193 by value.  For example, consider the following function:
1194 </p>
1195
1196 <div class="code"><pre>
1197 double dot_product(Vector a, Vector b);
1198 </pre></div>
1199
1200 <p>
1201 To deal with this, SWIG transforms the function to use pointers by
1202 creating a wrapper equivalent to the following:
1203 </p>
1204
1205 <div class="code"><pre>
1206 double wrap_dot_product(Vector *a, Vector *b) {
1207     Vector x = *a;
1208     Vector y = *b;
1209     return dot_product(x,y);
1210 }
1211 </pre></div>
1212
1213 <p>
1214 In the target language, the <tt>dot_product()</tt> function now accepts pointers
1215 to Vectors instead of Vectors.  For the most part, this transformation
1216 is transparent so you might not notice.
1217 </p>
1218
1219 <H3><a name="SWIG_nn23"></a>5.4.2 Return by value</H3>
1220
1221
1222 <p>
1223 C functions that return structures or classes datatypes by value are more difficult
1224 to handle. Consider the following function:</p>
1225
1226 <div class="code"><pre>
1227 Vector cross_product(Vector v1, Vector v2);
1228 </pre></div>
1229
1230 <p>
1231 This function wants to return <tt>Vector</tt>, but SWIG only really supports
1232 pointers.  As a result, SWIG creates a wrapper like this:
1233 </p>
1234
1235 <div class="code"><pre>
1236 Vector *wrap_cross_product(Vector *v1, Vector *v2) {
1237         Vector x = *v1;
1238         Vector y = *v2;
1239         Vector *result;
1240         result = (Vector *) malloc(sizeof(Vector));
1241         *(result) = cross(x,y);
1242         return result;
1243 }
1244 </pre></div>
1245
1246 <p>
1247 or if SWIG was run with the <tt>-c++</tt> option:</p>
1248
1249 <div class="code"><pre>
1250 Vector *wrap_cross(Vector *v1, Vector *v2) {
1251         Vector x = *v1;
1252         Vector y = *v2;
1253         Vector *result = new Vector(cross(x,y)); // Uses default copy constructor
1254         return result;
1255 }
1256 </pre></div>
1257
1258 <p>
1259 In both cases, SWIG allocates a new object and returns a reference to it. It
1260 is up to the user to delete the returned object when it is no longer
1261 in use. Clearly, this will leak memory if you are unaware of the implicit
1262 memory allocation and don't take steps to free the result.  That said, it should be
1263 noted that some language modules can now automatically track newly created objects and
1264 reclaim memory for you.  Consult the documentation for each language module for more details.
1265 </p>
1266
1267 <p>
1268 It should also be noted that the handling of pass/return by value in
1269 C++ has some special cases.  For example, the above code fragments
1270 don't work correctly if <tt>Vector</tt> doesn't define a default
1271 constructor.  The section on SWIG and C++ has more information about this case.
1272 </p>
1273
1274 <H3><a name="SWIG_nn24"></a>5.4.3 Linking to structure variables</H3>
1275
1276
1277 <p>
1278 When global variables or class members involving structures are
1279 encountered, SWIG handles them as pointers. For example, a global
1280 variable like this</p>
1281
1282 <div class="code"><pre>
1283 Vector unit_i;
1284 </pre></div>
1285
1286 <p>
1287 gets mapped to an underlying pair of set/get functions like this :</p>
1288
1289 <div class="code"><pre>
1290 Vector *unit_i_get() {
1291         return &amp;unit_i;
1292 }
1293 void unit_i_set(Vector *value) {
1294         unit_i = *value;
1295 }
1296 </pre></div>
1297
1298 <p>
1299 Again some caution is in order. A global variable created in this
1300 manner will show up as a pointer in the target scripting language. It
1301 would be an extremely bad idea to free or destroy such a pointer.    Also,
1302 C++ classes must supply a properly defined copy constructor in order for
1303 assignment to work correctly.
1304 </p>
1305
1306 <H3><a name="SWIG_nn25"></a>5.4.4 Linking to <tt>char *</tt></H3>
1307
1308
1309 <p>
1310 When a global variable of type <tt>char *</tt> appears, SWIG uses <tt>malloc()</tt> or
1311 <tt>new</tt> to allocate memory for the new value.   Specifically, if you have a variable
1312 like this
1313 </p>
1314
1315 <div class="code">
1316 <pre>
1317 char *foo;
1318 </pre>
1319 </div>
1320
1321 <p>
1322 SWIG generates the following code:
1323 </p>
1324
1325 <div class="code">
1326 <pre>
1327 /* C mode */
1328 void foo_set(char *value) {
1329    if (foo) free(foo);
1330    foo = (char *) malloc(strlen(value)+1);
1331    strcpy(foo,value);
1332 }
1333
1334 /* C++ mode.  When -c++ option is used */
1335 void foo_set(char *value) {
1336    if (foo) delete [] foo;
1337    foo = new char[strlen(value)+1];
1338    strcpy(foo,value);
1339 }
1340 </pre>
1341 </div>
1342
1343 <p>
1344 If this is not the behavior that you want, consider making the variable read-only using the
1345 <tt>%immutable</tt> directive.  Alternatively, you might write a short assist-function to set the value
1346 exactly like you want.  For example:
1347 </p>
1348
1349 <div class="code">
1350 <pre>
1351 %inline %{
1352   void set_foo(char *value) {
1353        strncpy(foo,value, 50);
1354    }
1355 %}
1356 </pre>
1357 </div>
1358
1359 <p>
1360 Note: If you write an assist function like this, you will have to call
1361 it as a function from the target scripting language (it does not work
1362 like a variable).  For example, in Python you will have to write:
1363 </p>
1364
1365 <div class="targetlang">
1366 <pre>
1367 &gt;&gt;&gt; set_foo("Hello World")
1368 </pre>
1369 </div>
1370
1371 <p>
1372 A common mistake with <tt>char *</tt> variables is to link to a variable declared like this:
1373 </p>
1374
1375 <div class="code">
1376 <pre>
1377 char *VERSION = "1.0";
1378 </pre>
1379 </div>
1380
1381 <p>
1382 In this case, the variable will be readable, but any attempt to change
1383 the value results in a segmentation or general protection fault.  This
1384 is due to the fact that SWIG is trying to release the old value using
1385 <tt>free</tt> or <tt>delete</tt> when the string literal value currently assigned to the variable wasn't
1386 allocated using <tt>malloc()</tt> or <tt>new</tt>.
1387 To fix this behavior, you can
1388 either mark the variable as read-only, write a typemap (as described in Chapter 6), 
1389 or write a special set function as shown.  Another alternative is to declare the
1390 variable as an array:
1391 </p>
1392
1393 <div class="code">
1394 <pre>
1395 char VERSION[64] = "1.0";
1396 </pre>
1397 </div>
1398
1399 <p>
1400 When variables of type <tt>const char *</tt> are declared, SWIG still generates functions for setting and
1401 getting the value.  However, the default behavior does <em>not</em> release the previous contents (resulting in
1402 a possible memory leak).  In fact, you may get a warning message such as this when wrapping such a variable:
1403 </p>
1404
1405 <div class="shell">
1406 <pre>
1407 example.i:20. Typemap warning. Setting const char * variable may leak memory
1408 </pre>
1409 </div>
1410
1411 <p>
1412 The reason for this behavior is that <tt>const char *</tt> variables are often used to point to string literals.
1413 For example:
1414 </p>
1415
1416 <div class="code">
1417 <pre>
1418 const char *foo = "Hello World\n";
1419 </pre>
1420 </div>
1421
1422 <p>
1423 Therefore, it's a really bad idea to call <tt>free()</tt> on such a
1424 pointer.  On the other hand, it <em>is</em> legal to change the
1425 pointer to point to some other value.  When setting a variable of this
1426 type, SWIG allocates a new string (using malloc or new) and changes
1427 the pointer to point to the new value.  However, repeated
1428 modifications of the value will result in a memory leak since the old
1429 value is not released. 
1430 </p>
1431
1432
1433
1434
1435 <H3><a name="SWIG_nn26"></a>5.4.5 Arrays</H3>
1436
1437
1438 <p>
1439 Arrays are fully supported by SWIG, but they are always handled as pointers instead
1440 of mapping them to a special array object or list in the target language.  Thus, the
1441 following declarations :</p>
1442
1443 <div class="code"><pre>
1444 int foobar(int a[40]);
1445 void grok(char *argv[]);
1446 void transpose(double a[20][20]);
1447 </pre></div>
1448
1449 <p>
1450 are processed as if they were really declared like this:
1451 </p>
1452
1453 <div class="code"><pre>
1454 int foobar(int *a);
1455 void grok(char **argv);
1456 void transpose(double (*a)[20]);
1457 </pre></div>
1458
1459 <p>
1460 Like C, SWIG does not perform array bounds checking.  
1461 It is up to the
1462 user to make sure the pointer points a suitably allocated region of memory. 
1463 </p>
1464
1465 <p>
1466 Multi-dimensional arrays are transformed into a pointer to an array of one less
1467 dimension.  For example:
1468 </p>
1469
1470 <div class="code">
1471 <pre>
1472 int [10];         // Maps to int *
1473 int [10][20];     // Maps to int (*)[20]
1474 int [10][20][30]; // Maps to int (*)[20][30]
1475 </pre>
1476 </div>
1477
1478 <p>
1479 It is important to note that in the C type system, a multidimensional
1480 array <tt>a[][]</tt> is <b>NOT</b> equivalent to a single pointer
1481 <tt>*a</tt> or a double pointer such as <tt>**a</tt>.  Instead, a
1482 pointer to an array is used (as shown above) where the actual value of
1483 the pointer is the starting memory location of the array.  The
1484 reader is strongly advised to dust off their C book and re-read the
1485 section on arrays before using them with SWIG.
1486 </p>
1487
1488 <p>
1489 Array variables are supported, but are read-only by default.  For example:
1490 </p>
1491
1492 <div class="code">
1493 <pre>
1494 int   a[100][200];
1495 </pre>
1496 </div>
1497
1498 <p>
1499 In this case, reading the variable 'a' returns a pointer of type <tt>int (*)[200]</tt>
1500 that points to the first element of the array <tt>&amp;a[0][0]</tt>.  Trying to modify 'a' results
1501 in an error.  This is because SWIG does not know how to copy data from the target
1502 language into the array.   To work around this limitation, you may want to write
1503 a few simple assist functions like this:
1504 </p>
1505
1506 <div class="code">
1507 <pre>
1508 %inline %{
1509 void a_set(int i, int j, int val) {
1510    a[i][j] = val;
1511 }
1512 int a_get(int i, int j) {
1513    return a[i][j];
1514 }
1515 %}
1516 </pre>
1517 </div>
1518
1519 <p>
1520 To dynamically create arrays of various sizes and shapes, it may be useful to write
1521 some helper functions in your interface.  For example:
1522 </p>
1523
1524 <div class="code">
1525 <pre>
1526 // Some array helpers
1527 %inline %{
1528   /* Create any sort of [size] array */
1529   int *int_array(int size) {
1530      return (int *) malloc(size*sizeof(int));
1531   }
1532   /* Create a two-dimension array [size][10] */
1533   int (*int_array_10(int size))[10] {
1534      return (int (*)[10]) malloc(size*10*sizeof(int));
1535   }
1536 %}
1537 </pre>
1538 </div>
1539
1540 <p>
1541 Arrays of <tt>char</tt> are handled as a special case by SWIG.  In this case, strings in the
1542 target language can be stored in the array.  For example, if you have a declaration like this,
1543 </p>
1544
1545 <div class="code">
1546 <pre>
1547 char pathname[256];
1548 </pre>
1549 </div>
1550
1551 <p>
1552 SWIG generates functions for both getting and setting the value that are equivalent to the following
1553 code:
1554 </p>
1555
1556 <div class="code">
1557 <pre>
1558 char *pathname_get() {
1559    return pathname;
1560 }
1561 void pathname_set(char *value) {
1562    strncpy(pathname,value,256);
1563 }
1564 </pre>
1565 </div>
1566
1567 <p>
1568 In the target language, the value can be set like a normal variable.
1569 </p>
1570
1571 <H3><a name="SWIG_readonly_variables"></a>5.4.6 Creating read-only variables</H3>
1572
1573
1574 <p>
1575 A read-only variable can be created by using the <tt>%immutable</tt>
1576 directive as shown :</p>
1577
1578 <div class="code"><pre>
1579 // File : interface.i
1580
1581 int     a;                      // Can read/write
1582 %immutable;
1583 int     b,c,d                   // Read only variables
1584 %mutable;
1585 double  x,y                     // read/write
1586 </pre></div>
1587
1588 <p>
1589 The <tt>%immutable</tt> directive enables read-only mode until it is
1590 explicitly disabled using the <tt>%mutable</tt> directive.  As an alternative to turning
1591 read-only mode off and on like this, individual declarations can also be tagged as
1592 immutable.  For example:
1593 </p>
1594
1595 <div class="code"><pre>
1596 %immutable x;                   // Make x read-only
1597 ...
1598 double x;                       // Read-only (from earlier %immutable directive)
1599 double y;                       // Read-write
1600 ...
1601 </pre></div>
1602
1603 <p>
1604 The <tt>%mutable</tt> and <tt>%immutable</tt> directives are actually 
1605 <a href="Customization.html#features">%feature directives</a> defined like this:
1606 </p>
1607
1608 <div class="code"><pre>
1609 #define %immutable   %feature("immutable")
1610 #define %mutable     %feature("immutable","")
1611 </pre></div>
1612
1613 <p>
1614 If you wanted to make all wrapped variables read-only, barring one or two, it might be easier to take this approach:
1615 </p>
1616
1617 <div class="code"><pre>
1618 %immutable;                     // Make all variables read-only
1619 %feature("immutable","0") x;    // except, make x read/write
1620 ...
1621 double x;
1622 double y;
1623 double z;
1624 ...
1625 </pre></div>
1626
1627 <p>
1628 Read-only variables are also created when declarations are declared as <tt>const</tt>.
1629 For example:
1630 </p>
1631
1632 <div class="code">
1633 <pre>
1634 const int foo;               /* Read only variable */
1635 char * const version="1.0";  /* Read only variable */
1636 </pre></div>
1637
1638 <p>
1639 <b>Compatibility note:</b> Read-only access used to be controlled by a pair of directives
1640 <tt>%readonly</tt> and <tt>%readwrite</tt>.   Although these directives still work, they
1641 generate a warning message.   Simply change the directives to <tt>%immutable;</tt> and
1642 <tt>%mutable;</tt> to silence the warning.  Don't forget the extra semicolon!
1643 </p>
1644
1645 <H3><a name="SWIG_rename_ignore"></a>5.4.7 Renaming and ignoring declarations</H3>
1646
1647
1648 <p>
1649 Normally, the name of a C declaration is used when that declaration is
1650 wrapped into the target language. However, this may generate a
1651 conflict with a keyword or already existing function in the scripting
1652 language. To resolve a name conflict, you can use the <tt>%rename</tt>
1653 directive as shown :</p>
1654
1655 <div class="code"><pre>
1656 // interface.i
1657
1658 %rename(my_print) print;
1659 extern void print(char *);
1660
1661 %rename(foo) a_really_long_and_annoying_name;
1662 extern int a_really_long_and_annoying_name;
1663
1664 </pre></div>
1665
1666 <p>
1667 SWIG still calls the correct C function, but in this case the
1668 function <tt>print()</tt> will really be called "<tt>my_print()</tt>"
1669 in the target language. </p>
1670
1671 <p>
1672 The placement of the <tt>%rename</tt> directive is arbitrary as long as it appears
1673 before the declarations to be renamed.  A common technique is to write code for
1674 wrapping a header file like this:
1675 </p>
1676
1677 <div class="code"><pre>
1678 // interface.i
1679
1680 %rename(my_print) print;
1681 %rename(foo) a_really_long_and_annoying_name;
1682
1683 %include "header.h"
1684 </pre></div>
1685
1686 <p>
1687 <tt>%rename </tt>applies a renaming operation to all future
1688 occurrences of a name. The renaming applies to functions, variables,
1689 class and structure names, member functions, and member data. For
1690 example, if you had two-dozen C++ classes, all with a member function
1691 named `print' (which is a keyword in Python), you could rename them
1692 all to `output' by specifying :</p>
1693
1694 <div class="code"><pre>
1695 %rename(output) print; // Rename all `print' functions to `output'
1696 </pre></div>
1697
1698 <p>
1699 SWIG does not normally perform any checks to see if the functions it wraps are
1700 already defined in the target scripting language. However, if you are
1701 careful about namespaces and your use of modules, you can usually
1702 avoid these problems.</p>
1703
1704 <p>
1705 Closely related to <tt>%rename</tt> is the <tt>%ignore</tt> directive.  <tt>%ignore</tt> instructs SWIG
1706 to ignore declarations that match a given identifier.  For example:
1707 </p>
1708
1709 <div class="code">
1710 <pre>
1711 %ignore print;         // Ignore all declarations named print
1712 %ignore _HAVE_FOO_H;   // Ignore an include guard constant
1713 ...
1714 %include "foo.h"       // Grab a header file
1715 ...
1716 </pre>
1717 </div>
1718
1719 <p>
1720 Any function, variable etc which matches <tt>%ignore</tt> will not be wrapped and therefore will not be available from the target language.
1721 A common usage of <tt>%ignore</tt> is to selectively remove certain declarations from a header file without having
1722 to add conditional compilation to the header.   However, it should be stressed that this only works for simple
1723 declarations.  If you need to remove a whole section of problematic code, the SWIG preprocessor should be used instead.
1724 </p>
1725
1726 <p>
1727 More powerful variants of <tt>%rename</tt> and <tt>%ignore</tt> directives can be used to help 
1728 wrap C++ overloaded functions and methods or C++ methods which use default arguments. This is described in the 
1729 <a href="SWIGPlus.html#ambiguity_resolution_renaming">Ambiguity resolution and renaming</a> section in the C++ chapter.
1730 </p>
1731
1732 <p>
1733 <b>Compatibility note: </b> Older versions of SWIG provided a special <tt>%name</tt> directive for renaming declarations.
1734 For example:
1735 </p>
1736
1737 <div class="code">
1738 <pre>
1739 %name(output) extern void print(char *);
1740 </pre>
1741 </div>
1742
1743 <p>
1744 This directive is still supported, but it is deprecated and should probably be avoided.  The <tt>%rename</tt>
1745 directive is more powerful and better supports wrapping of raw header file information.
1746 </p>
1747
1748 <H3><a name="SWIG_default_args"></a>5.4.8 Default/optional arguments</H3>
1749
1750
1751 <p>
1752 SWIG supports default arguments in both C and C++ code.  For example:
1753 </p>
1754
1755 <div class="code"><pre>
1756 int plot(double x, double y, int color=WHITE);
1757 </pre></div>
1758
1759 <p>
1760 In this case, SWIG generates wrapper code where the
1761 default arguments are optional in the target language. For example, this function could be
1762 used in Tcl as follows :</p>
1763
1764 <div class="targetlang"><pre>
1765 % plot -3.4 7.5                                 # Use default value
1766 % plot -3.4 7.5 10                              # set color to 10 instead
1767
1768 </pre></div>
1769
1770 <p>
1771 Although the ANSI C standard does not allow default arguments, default
1772 arguments specified in a SWIG interface work with both C and C++.
1773 </p>
1774
1775 <p>
1776 <b>Note:</b> There is a subtle semantic issue concerning the use 
1777 of default arguments and the SWIG generated wrapper code.  When default
1778 arguments are used in C code, the default values are emitted into the wrappers and the
1779 function is invoked with a full set of arguments. This is different to when wrapping C++
1780 where an overloaded wrapper method is generated for each defaulted argument.
1781 Please refer to the section on <a href="SWIGPlus.html#SWIGPlus_default_args">default arguments</a>
1782 in the C++ chapter for further details.
1783 </p>
1784
1785 <H3><a name="SWIG_nn30"></a>5.4.9 Pointers to functions and callbacks</H3>
1786
1787
1788 <p>
1789 Occasionally, a C library may include functions that expect to receive
1790 pointers to functions--possibly to serve as callbacks. SWIG
1791 provides full support for function pointers provided that the callback
1792 functions are defined in C and not in the target language.  For example,
1793 consider a function like this:
1794 </p>
1795
1796 <div class="code"><pre>
1797 int binary_op(int a, int b, int (*op)(int,int));
1798 </pre></div>
1799
1800 <p>
1801 When you first wrap something like this into an extension module, you
1802 may find the function to be impossible to use.  For instance, in Python:
1803 </p>
1804
1805 <div class="targetlang"><pre>
1806 &gt;&gt;&gt; def add(x,y):
1807 ...     return x+y
1808 ...
1809 &gt;&gt;&gt; binary_op(3,4,add)
1810 Traceback (most recent call last):
1811   File "&lt;stdin&gt;", line 1, in ?
1812 TypeError: Type error. Expected _p_f_int_int__int
1813 &gt;&gt;&gt;
1814 </pre>
1815 </div>
1816
1817 <p>
1818 The reason for this error is that SWIG doesn't know how to map a scripting
1819 language function into a C callback.  However, existing C functions can
1820 be used as arguments provided you install them as constants.
1821 One way to do this is to use the <tt>%constant</tt> directive like this:
1822 </p>
1823
1824 <div class="code"><pre>
1825 /* Function with a callback */
1826 int binary_op(int a, int b, int (*op)(int,int));
1827
1828 /* Some callback functions */
1829 %constant int add(int,int);
1830 %constant int sub(int,int);
1831 %constant int mul(int,int);
1832 </pre></div>
1833
1834 <p>
1835 In this case, <tt>add</tt>, <tt>sub</tt>, and <tt>mul</tt> become function pointer
1836 constants in the target scripting language.  This allows you to use them as follows:
1837 </p>
1838
1839 <div class="targetlang">
1840 <pre>
1841 &gt;&gt;&gt; binary_op(3,4,add)
1842 7
1843 &gt;&gt;&gt; binary_op(3,4,mul)
1844 12
1845 &gt;&gt;&gt;
1846 </pre>
1847 </div>
1848
1849 <p>
1850 Unfortunately, by declaring the callback functions as constants, they are no longer accessible
1851 as functions. For example:
1852 </p>
1853
1854 <div class="targetlang">
1855 <pre>
1856 &gt;&gt;&gt; add(3,4)
1857 Traceback (most recent call last):
1858   File "&lt;stdin&gt;", line 1, in ?
1859 TypeError: object is not callable: '_ff020efc_p_f_int_int__int'
1860 &gt;&gt;&gt;
1861 </pre>
1862 </div>
1863
1864 <p>
1865 If you want to make a function available as both a callback function and a function, you
1866 can use the <tt>%callback</tt> and <tt>%nocallback</tt> directives like this:
1867 </p>
1868
1869 <div class="code">
1870 <pre>
1871 /* Function with a callback */
1872 int binary_op(int a, int b, int (*op)(int,int));
1873
1874 /* Some callback functions */
1875 %callback("%s_cb");
1876 int add(int,int);
1877 int sub(int,int);
1878 int mul(int,int);
1879 %nocallback;
1880 </pre></div>
1881
1882 <p>
1883 The argument to <tt>%callback</tt> is a printf-style format string that
1884 specifies the naming convention for the callback constants (<tt>%s</tt> gets replaced
1885 by the function name).  The callback mode remains in effect until it is explicitly
1886 disabled using <tt>%nocallback</tt>.  When you do this, the interface now works as follows:
1887 </p>
1888
1889 <div class="targetlang">
1890 <pre>
1891 &gt;&gt;&gt; binary_op(3,4,add_cb)
1892 7
1893 &gt;&gt;&gt; binary_op(3,4,mul_cb)
1894 12
1895 &gt;&gt;&gt; add(3,4)
1896 7
1897 &gt;&gt;&gt; mul(3,4)
1898 12
1899 </pre>
1900 </div>
1901
1902 <p>
1903 Notice that when the function is used as a callback, special names
1904 such as <tt>add_cb</tt> is used instead.  To call the function
1905 normally, just use the original function name such as <tt>add()</tt>.
1906 </p>
1907
1908 <p>
1909 SWIG provides a number of extensions to standard C printf formatting
1910 that may be useful in this context.  For instance, the following
1911 variation installs the callbacks as all upper-case constants such as
1912 <tt>ADD</tt>, <tt>SUB</tt>, and <tt>MUL</tt>:
1913 </p>
1914
1915 <div class="code"><pre>
1916 /* Some callback functions */
1917 %callback("%(upper)s");
1918 int add(int,int);
1919 int sub(int,int);
1920 int mul(int,int);
1921 %nocallback;
1922 </pre></div>
1923
1924 <p>
1925 A format string of <tt>"%(lower)s"</tt> converts all characters to lower-case.
1926 A string of <tt>"%(title)s"</tt> capitalizes the first character and converts the
1927 rest to lower case.
1928 </p>
1929
1930 <p>
1931 And now, a final note about function pointer support.  Although SWIG
1932 does not normally allow callback functions to be written in the target language, this
1933 can be accomplished with the use of typemaps and other advanced SWIG features.
1934 This is described in a later chapter.
1935 </p>
1936
1937 <H2><a name="SWIG_nn31"></a>5.5 Structures and unions</H2>
1938
1939
1940 <p>
1941 This section describes the behavior of SWIG when processing ANSI C structures and union declarations.  Extensions to
1942 handle C++ are described in the next section.
1943 </p>
1944
1945 <p>
1946 If SWIG encounters the definition of a structure or union, it
1947 creates a set of accessor functions. Although SWIG does not need
1948 structure definitions to build an interface, providing definitions
1949 make it possible to access structure members. The accessor functions
1950 generated by SWIG simply take a pointer to an object and allow access
1951 to an individual member. For example, the declaration :</p>
1952
1953 <div class="code"><pre>
1954 struct Vector {
1955         double x,y,z;
1956 }
1957
1958 </pre></div>
1959
1960 <p>
1961 gets transformed into the following set of accessor functions :</p>
1962
1963 <div class="code"><pre>
1964 double Vector_x_get(struct Vector *obj) {
1965         return obj-&gt;x;
1966 }
1967 double Vector_y_get(struct Vector *obj) { 
1968         return obj-&gt;y;
1969 }
1970 double Vector_z_get(struct Vector *obj) { 
1971         return obj-&gt;z;
1972 }
1973 void Vector_x_set(struct Vector *obj, double value) {
1974         obj-&gt;x = value;
1975 }
1976 void Vector_y_set(struct Vector *obj, double value) {
1977         obj-&gt;y = value;
1978 }
1979 void Vector_z_set(struct Vector *obj, double value) {
1980         obj-&gt;z = value;
1981 }
1982 </pre></div>
1983
1984 <p>
1985 In addition, SWIG creates default constructor and destructor functions if none are
1986 defined in the interface.  For example:
1987 </p>
1988
1989 <div class="code"><pre>
1990 struct Vector *new_Vector() {
1991     return (Vector *) calloc(1,sizeof(struct Vector));
1992 }
1993 void delete_Vector(struct Vector *obj) {
1994     free(obj);
1995 }
1996 </pre>
1997 </div>
1998
1999 <p>
2000 Using these low-level accessor functions, an object can be minimally manipulated from the target
2001 language using code like this:
2002 </p>
2003
2004 <div class="code">
2005 <pre>
2006 v = new_Vector()
2007 Vector_x_set(v,2)
2008 Vector_y_set(v,10)
2009 Vector_z_set(v,-5)
2010 ...
2011 delete_Vector(v)
2012 </pre>
2013 </div>
2014
2015 <p>
2016 However, most of SWIG's language modules also provide a high-level interface that is more convenient. Keep reading.
2017 </p>
2018
2019 <H3><a name="SWIG_nn32"></a>5.5.1 Typedef and structures</H3>
2020
2021
2022 <p>
2023 SWIG supports the following construct which is quite common in C
2024 programs :</p>
2025
2026 <div class="code"><pre>
2027 typedef struct {
2028         double x,y,z;
2029 } Vector;
2030
2031 </pre></div>
2032
2033 <p>
2034 When encountered, SWIG assumes that the name of the object is `Vector'
2035 and creates accessor functions like before.  The only difference is
2036 that the use of <tt>typedef</tt> allows SWIG to drop the
2037 <tt>struct</tt> keyword on its generated code. For example:
2038 </p>
2039
2040 <div class="code">
2041 <pre>
2042 double Vector_x_get(Vector *obj) {
2043         return obj-&gt;x;
2044 }
2045 </pre>
2046 </div>
2047
2048 <p>
2049 If two different names are used like this :</p>
2050
2051 <div class="code"><pre>
2052 typedef struct vector_struct {
2053         double x,y,z;
2054 } Vector;
2055
2056 </pre></div>
2057
2058 <p>
2059 the name <tt>Vector</tt> is used instead of <tt>vector_struct</tt> since
2060 this is more typical C programming style. If declarations defined later in the interface use the type <tt>struct
2061 vector_struct</tt>, SWIG knows that this is the same as
2062 <tt>Vector</tt> and it generates the appropriate type-checking code.
2063 </p>
2064
2065 <H3><a name="SWIG_nn33"></a>5.5.2 Character strings and structures</H3>
2066
2067
2068 <p>
2069 Structures involving character strings require some care. SWIG assumes
2070 that all members of type <tt>char *</tt> have been dynamically
2071 allocated using <tt>malloc()</tt> and that they are NULL-terminated
2072 ASCII strings. When such a member is modified, the previously contents
2073 will be released, and the new contents allocated. For example :</p>
2074
2075 <div class="code"><pre>
2076 %module mymodule
2077 ...
2078 struct Foo {
2079         char *name;
2080         ...
2081 }
2082
2083 </pre></div>
2084
2085 <p>
2086 This results in the following accessor functions :</p>
2087
2088 <div class="code"><pre>
2089 char *Foo_name_get(Foo *obj) {
2090         return Foo-&gt;name;
2091 }
2092
2093 char *Foo_name_set(Foo *obj, char *c) {
2094         if (obj-&gt;name) free(obj-&gt;name);
2095         obj-&gt;name = (char *) malloc(strlen(c)+1);
2096         strcpy(obj-&gt;name,c);
2097         return obj-&gt;name;
2098 }
2099 </pre></div>
2100
2101 <p>
2102 If this behavior differs from what you need in your applications,
2103 the SWIG "memberin" typemap can be used to change it.  See the
2104 typemaps chapter for further details.
2105 </p>
2106
2107 <p>
2108 Note: If the <tt>-c++</tt> option is used, <tt>new</tt> and <tt>delete</tt> are used to
2109 perform memory allocation.
2110 </p>
2111
2112 <H3><a name="SWIG_nn34"></a>5.5.3 Array members</H3>
2113
2114
2115 <p>
2116 Arrays may appear as the members of structures, but they will be
2117 read-only. SWIG will write an accessor function that returns the
2118 pointer to the first element of the array, but will not write a
2119 function to change the contents of the array itself. 
2120 When this
2121 situation is detected, SWIG may generate a warning message such as the
2122 following :</p>
2123
2124 <div class="shell"><pre>
2125 interface.i:116. Warning. Array member will be read-only
2126 </pre></div>
2127
2128 <p>
2129 To eliminate the warning message, typemaps can be used, but this is
2130 discussed in a later chapter.  In many cases, the warning message is
2131 harmless.
2132 </p>
2133
2134 <H3><a name="SWIG_structure_data_members"></a>5.5.4 Structure data members</H3>
2135
2136
2137 <p>
2138 Occasionally, a structure will contain data members that are themselves structures.  For example:
2139 </p>
2140
2141 <div class="code">
2142 <pre>
2143 typedef struct Foo {
2144    int x;
2145 } Foo;
2146
2147 typedef struct Bar {
2148    int y;
2149    Foo f;           /* struct member */
2150 } Bar;
2151 </pre>
2152 </div>
2153
2154 <p>
2155 When a structure member is wrapped, it is handled as a pointer, unless the <tt>%naturalvar</tt> directive
2156 is used where it is handled more like a C++ reference (see <a href="SWIGPlus.html#SWIGPlus_member_data">C++ Member data</a>).
2157 The accessors to the member variable as a pointer is effectively wrapped as follows:
2158 </p>
2159
2160 <div class="code">
2161 <pre>
2162 Foo *Bar_f_get(Bar *b) {
2163    return &amp;b-&gt;f;
2164 }
2165 void Bar_f_set(Bar *b, Foo *value) {
2166    b-&gt;f = *value;
2167 }
2168 </pre>
2169 </div>
2170
2171 <p>
2172 The reasons for this are somewhat subtle but have to do with the
2173 problem of modifying and accessing data inside the data member.  For
2174 example, suppose you wanted to modify the value of <tt>f.x</tt> 
2175 of a <tt>Bar</tt> object like this:
2176 </p>
2177
2178 <div class="code">
2179 <pre>
2180 Bar *b;
2181 b-&gt;f.x = 37;
2182 </pre>
2183 </div>
2184
2185 <p>
2186 Translating this assignment to function calls (as would be used inside the scripting
2187 language interface) results in the following code:
2188 </p>
2189
2190 <div class="code">
2191 <pre>
2192 Bar *b;
2193 Foo_x_set(Bar_f_get(b),37);
2194 </pre>
2195 </div>
2196
2197 <p>
2198 In this code, if the <tt>Bar_f_get()</tt> function were to return a <tt>Foo</tt> instead of a
2199 <tt>Foo *</tt>, then the resulting modification would be applied to a <em>copy</em> of <tt>f</tt> and not
2200 the data member <tt>f</tt> itself.  Clearly that's not what you want!
2201 </p>
2202
2203 <p>
2204 It should be noted that this transformation to pointers only occurs if SWIG knows that a data member
2205 is a structure or class.   For instance, if you had a structure like this,
2206 </p>
2207
2208 <div class="code">
2209 <pre>
2210 struct Foo {
2211    WORD   w;
2212 };
2213 </pre>
2214 </div>
2215
2216 <p>
2217 and nothing was known about <tt>WORD</tt>, then SWIG will generate more normal accessor functions
2218 like this:
2219 </p>
2220
2221 <div class="code">
2222 <pre>
2223 WORD Foo_w_get(Foo *f) {
2224     return f-&gt;w;
2225 }
2226 void Foo_w_set(FOO *f, WORD value) {
2227     f-&gt;w = value;
2228 }
2229 </pre>
2230 </div>
2231
2232
2233 <p>
2234 <b>Compatibility Note:</b>  SWIG-1.3.11 and earlier releases transformed all non-primitive member datatypes
2235 to pointers.  Starting in SWIG-1.3.12, this transformation <em>only</em> occurs if a datatype is known to be a structure,
2236 class, or union.  This is unlikely to break existing code.  However, if you need to tell SWIG that an undeclared
2237 datatype is really a struct, simply use a forward struct declaration such as <tt>"struct Foo;"</tt>.
2238 </p>
2239
2240 <H3><a name="SWIG_nn36"></a>5.5.5 C constructors and destructors</H3>
2241
2242
2243 <p>
2244 When wrapping structures, it is generally useful to have a mechanism
2245 for creating and destroying objects.  If you don't do anything, SWIG
2246 will automatically generate functions for creating and destroying
2247 objects using <tt>malloc()</tt> and <tt>free()</tt>.  Note: the use of
2248 <tt>malloc()</tt> only applies when SWIG is used on C code (i.e., when the
2249 <tt>-c++</tt> option  is <em>not</em> supplied on the command line).  C++ is handled
2250 differently.
2251 </p>
2252
2253 <p>
2254 If you don't want SWIG to generate default constructors for your
2255 interfaces, you can use the <tt>%nodefaultctor</tt> directive or the
2256 <tt>-nodefaultctor</tt> command line option.  For example:
2257 </p>
2258
2259 <div class="shell"><pre>
2260 swig -nodefaultctor example.i 
2261 </pre></div>
2262
2263 <p>
2264 or
2265 </p>
2266
2267 <div class="code"><pre>
2268 %module foo
2269 ...
2270 %nodefaultctor;        // Don't create default constructors
2271 ... declarations ...
2272 %clearnodefaultctor;   // Re-enable default constructors
2273 </pre></div>
2274
2275 <p>
2276 If you need more precise control, <tt>%nodefaultctor</tt> can selectively target individual structure 
2277 definitions.  For example:
2278 </p>
2279
2280 <div class="code">
2281 <pre>
2282 %nodefaultctor Foo;      // No default constructor for Foo
2283 ...
2284 struct Foo {             // No default constructor generated.
2285 };
2286
2287 struct Bar {             // Default constructor generated.
2288 };
2289 </pre>
2290 </div>
2291
2292
2293 <p>
2294 Since ignoring the implicit or default destructors most of the times
2295 produce memory leaks, SWIG will always try to generate them. If
2296 needed, however, you can selectively disable the generation of the
2297 default/implicit destructor by using <tt>%nodefaultdtor</tt>
2298 </p>
2299
2300 <div class="code">
2301 <pre>
2302 %nodefaultdtor Foo; // No default/implicit destructor for Foo
2303 ...
2304 struct Foo {              // No default destructor is generated.
2305 };
2306
2307 struct Bar {              // Default destructor generated.
2308 };
2309 </pre>
2310 </div>
2311
2312
2313
2314 <p>
2315 <b>Compatibility note:</b> Prior to SWIG-1.3.7, SWIG did not generate default constructors
2316 or destructors unless you explicitly turned them on using <tt>-make_default</tt>. 
2317 However, it appears that most users want to have constructor and destructor functions so it
2318 has now been enabled as the default behavior.
2319 </p>
2320
2321 <p>
2322 <b>Note:</b> There are also the <tt>-nodefault</tt> option and
2323 <tt>%nodefault</tt> directive, which disable both the default or
2324 implicit destructor generation. This could lead to memory leaks across 
2325 the target languages, and is highly recommended you don't use them.
2326 </p>
2327
2328
2329 <H3><a name="SWIG_adding_member_functions"></a>5.5.6 Adding member functions to C structures</H3>
2330
2331
2332 <p>
2333 Most languages provide a mechanism for creating classes and
2334 supporting object oriented programming. From a C standpoint, object
2335 oriented programming really just boils down to the process of
2336 attaching functions to structures. These functions normally operate
2337 on an instance of the structure (or object).  Although there is a
2338 natural mapping of C++ to such a scheme, there is no direct mechanism
2339 for utilizing it with C code. However, SWIG provides a special
2340 <tt>%extend</tt> directive that makes it possible to attach
2341 methods to C structures for purposes of building an object oriented
2342 interface. Suppose you have a C header file with
2343 the following declaration :</p>
2344
2345 <div class="code"><pre>
2346 /* file : vector.h */
2347 ...
2348 typedef struct {
2349         double x,y,z;
2350 } Vector;
2351
2352 </pre></div>
2353
2354 <p>
2355 You can make a <tt>Vector</tt> look a lot like a class by writing a SWIG interface like this:
2356 </p>
2357
2358 <div class="code"><pre>
2359 // file : vector.i
2360 %module mymodule
2361 %{
2362 #include "vector.h"
2363 %}
2364
2365 %include "vector.h"          // Just grab original C header file
2366 %extend Vector {             // Attach these functions to struct Vector
2367         Vector(double x, double y, double z) {
2368                 Vector *v;
2369                 v = (Vector *) malloc(sizeof(Vector));
2370                 v-&gt;x = x;
2371                 v-&gt;y = y;
2372                 v-&gt;z = z;
2373                 return v;
2374         }
2375         ~Vector() {
2376                 free($self);
2377         }
2378         double magnitude() {
2379                 return sqrt($self-&gt;x*$self-&gt;x+$self-&gt;y*$self-&gt;y+$self-&gt;z*$self-&gt;z);
2380         }
2381         void print() {
2382                 printf("Vector [%g, %g, %g]\n", $self-&gt;x,$self-&gt;y,$self-&gt;z);
2383         }
2384 };
2385
2386 </pre></div>
2387
2388 <p>
2389 Note the usage of the <tt>$self</tt> special variable.
2390 Its usage is identical to a C++ 'this' pointer and should be used whenever access to the struct instance is required.
2391 Also note that C++ constructor and destructor syntax has been used to simulate a constructor and destructor, even for C code.
2392 There is one subtle difference to a normal C++ constructor implementation though and that is although the constructor declaration 
2393 is as per a normal C++ constructor, the newly constructed object must be returned <b>as if</b> the constructor declaration 
2394 had a return value, a <tt>Vector *</tt> in this case.
2395 </p>
2396
2397 <p>
2398 Now, when used with proxy classes in Python, you can do things like
2399 this :</p>
2400
2401 <div class="targetlang"><pre>
2402 &gt;&gt;&gt; v = Vector(3,4,0)                 # Create a new vector
2403 &gt;&gt;&gt; print v.magnitude()                # Print magnitude
2404 5.0
2405 &gt;&gt;&gt; v.print()                  # Print it out
2406 [ 3, 4, 0 ]
2407 &gt;&gt;&gt; del v                      # Destroy it
2408 </pre></div>
2409
2410 <p>
2411 The <tt>%extend</tt> directive can also be used inside the definition
2412 of the Vector structure. For example:</p>
2413
2414 <div class="code"><pre>
2415 // file : vector.i
2416 %module mymodule
2417 %{
2418 #include "vector.h"
2419 %}
2420
2421 typedef struct {
2422         double x,y,z;
2423         %extend {
2424                 Vector(double x, double y, double z) { ... }
2425                 ~Vector() { ... }
2426                 ...
2427         }
2428 } Vector;
2429 </pre></div>
2430
2431 <p>
2432 Finally, <tt>%extend</tt> can be used to access externally written
2433 functions provided they follow the naming convention used in this
2434 example :</p>
2435
2436 <div class="code"><pre>
2437 /* File : vector.c */
2438 /* Vector methods */
2439 #include "vector.h"
2440 Vector *new_Vector(double x, double y, double z) {
2441         Vector *v;
2442         v = (Vector *) malloc(sizeof(Vector));
2443         v-&gt;x = x;
2444         v-&gt;y = y;
2445         v-&gt;z = z;
2446         return v;
2447 }
2448 void delete_Vector(Vector *v) {
2449         free(v);
2450 }
2451
2452 double Vector_magnitude(Vector *v) {
2453         return sqrt(v-&gt;x*v-&gt;x+v-&gt;y*v-&gt;y+v-&gt;z*v-&gt;z);
2454 }
2455
2456 // File : vector.i
2457 // Interface file
2458 %module mymodule
2459 %{
2460 #include "vector.h"
2461 %}
2462
2463 typedef struct {
2464         double x,y,z;
2465         %extend {
2466                 Vector(int,int,int); // This calls new_Vector()
2467                ~Vector();            // This calls delete_Vector()
2468                 double magnitude();  // This will call Vector_magnitude()
2469                 ...
2470         }
2471 } Vector;
2472 </pre>
2473 </div>
2474
2475 <p>
2476 A little known feature of the <tt>%extend</tt> directive is that
2477 it can also be used to add synthesized attributes or to modify the
2478 behavior of existing data attributes.  For example, suppose you wanted
2479 to make <tt>magnitude</tt> a read-only attribute of <tt>Vector</tt>
2480 instead of a method.  To do this, you might write some code like this:
2481 </p>
2482
2483 <div class="code">
2484 <pre>
2485 // Add a new attribute to Vector
2486 %extend Vector {
2487     const double magnitude;
2488 }
2489 // Now supply the implementation of the Vector_magnitude_get function
2490 %{
2491 const double Vector_magnitude_get(Vector *v) {
2492   return (const double) return sqrt(v-&gt;x*v-&gt;x+v-&gt;y*v-&gt;y+v-&gt;z*v-&gt;z);
2493 }
2494 %}
2495
2496 </pre>
2497 </div>
2498
2499 <p>
2500 Now, for all practical purposes, <tt>magnitude</tt> will appear like an attribute
2501 of the object.
2502 </p>
2503
2504 <p>
2505 A similar technique can also be used to work with problematic data members.
2506 For example, consider this interface:
2507 </p>
2508
2509 <div class="code">
2510 <pre>
2511 struct Person {
2512    char name[50];
2513    ...
2514 }
2515 </pre>
2516 </div>
2517
2518 <p>
2519 By default, the <tt>name</tt> attribute is read-only because SWIG does not
2520 normally know how to modify arrays.  However, you can rewrite the interface
2521 as follows to change this:
2522 </p>
2523
2524 <div class="code">
2525 <pre>
2526 struct Person {
2527     %extend {
2528        char *name;
2529     }
2530 ...
2531 }
2532
2533 // Specific implementation of set/get functions
2534 %{
2535 char *Person_name_get(Person *p) {
2536    return p-&gt;name;
2537 }
2538 void Person_name_set(Person *p, char *val) {
2539    strncpy(p-&gt;name,val,50);
2540 }
2541 %}
2542 </pre>
2543 </div>
2544
2545 <p>
2546 Finally, it should be stressed that even though <tt>%extend</tt>
2547 can be used to add new data members, these new members can not require
2548 the allocation of additional storage in the object (e.g., their values must
2549 be entirely synthesized from existing attributes of the structure).
2550 </p>
2551
2552 <p>
2553 <b>Compatibility note:</b>  The <tt>%extend</tt> directive is a new
2554 name for the <tt>%addmethods</tt> directive.  Since <tt>%addmethods</tt> could
2555 be used to extend a structure with more than just methods, a more suitable
2556 directive name has been chosen.
2557 </p>
2558
2559 <H3><a name="SWIG_nested_structs"></a>5.5.7 Nested structures</H3>
2560
2561
2562 <p>
2563 Occasionally, a C program will involve structures like this :</p>
2564
2565 <div class="code"><pre>
2566 typedef struct Object {
2567         int objtype;
2568         union {
2569                 int     ivalue;
2570                 double  dvalue;
2571                 char    *strvalue;
2572                 void    *ptrvalue;
2573         } intRep;
2574 } Object;
2575
2576 </pre></div>
2577
2578 <p>
2579 When SWIG encounters this, it performs a structure splitting operation
2580 that transforms the declaration into the equivalent of the
2581 following:</p>
2582
2583 <div class="code"><pre>
2584 typedef union {
2585         int             ivalue;
2586         double          dvalue;
2587         char            *strvalue;
2588         void            *ptrvalue;
2589 } Object_intRep;
2590
2591 typedef struct Object {
2592         int objType;
2593         Object_intRep intRep;
2594 } Object;
2595
2596 </pre></div>
2597
2598 <p>
2599 SWIG will then create an <tt>Object_intRep</tt> structure for use inside
2600 the interface file. Accessor functions will be created for both
2601 structures. In this case, functions like this would be created :</p>
2602
2603 <div class="code"><pre>
2604 Object_intRep *Object_intRep_get(Object *o) {
2605         return (Object_intRep *) &amp;o-&gt;intRep;
2606 }
2607 int Object_intRep_ivalue_get(Object_intRep *o) {
2608         return o-&gt;ivalue;
2609 }
2610 int Object_intRep_ivalue_set(Object_intRep *o, int value) {
2611         return (o-&gt;ivalue = value);
2612 }
2613 double Object_intRep_dvalue_get(Object_intRep *o) {
2614         return o-&gt;dvalue;
2615 }
2616 ... etc ...
2617
2618 </pre></div>
2619
2620 <p>
2621 Although this process is a little hairy, it works like you would expect in the
2622 target scripting language--especially when proxy classes are used.  For instance, in Perl:
2623 </p>
2624
2625 <div class="targetlang"><pre>
2626 # Perl5 script for accessing nested member
2627 $o = CreateObject();                    # Create an object somehow
2628 $o-&gt;{intRep}-&gt;{ivalue} = 7              # Change value of o.intRep.ivalue
2629 </pre></div>
2630
2631 <p>
2632 If you have a lot nested structure declarations, it is
2633 advisable to double-check them after running SWIG. Although,
2634 there is a good chance that they will work, you may have to
2635 modify the interface file in certain cases.
2636
2637 <H3><a name="SWIG_nn39"></a>5.5.8 Other things to note about structure wrapping</H3>
2638
2639
2640 <p>
2641 SWIG doesn't care if the declaration of a structure in a <tt>.i</tt> file exactly matches
2642 that used in the underlying C code (except in the case of nested
2643 structures). For this reason, there are no problems omitting
2644 problematic members or simply omitting the structure definition
2645 altogether. If you are happy passing pointers around, this can
2646 be done without ever giving SWIG a structure definition.</p>
2647
2648 <p>
2649 Starting with SWIG1.3, a number of improvements have been made to SWIG's
2650 code generator. Specifically, even though structure access has been described
2651 in terms of high-level accessor functions such as this,
2652 </p>
2653
2654 <div class="code">
2655 <pre>
2656 double Vector_x_get(Vector *v) {
2657    return v-&gt;x;
2658 }
2659 </pre>
2660 </div>
2661
2662 <p>
2663 most of the generated code is actually inlined directly into wrapper
2664 functions.  Therefore, no function <tt>Vector_x_get()</tt> actually
2665 exists in the generated wrapper file.  For example, when creating a Tcl module,
2666 the following function is generated instead:
2667 </p>
2668
2669 <div class="code">
2670 <pre>
2671 static int
2672 _wrap_Vector_x_get(ClientData clientData, Tcl_Interp *interp, 
2673                    int objc, Tcl_Obj *CONST objv[]) {
2674     struct Vector *arg1 ;
2675     double result ;
2676     
2677     if (SWIG_GetArgs(interp, objc, objv,"p:Vector_x_get self ",&amp;arg0,
2678                      SWIGTYPE_p_Vector) == TCL_ERROR)
2679          return TCL_ERROR;
2680     result = (double ) (arg1-&gt;x);
2681     Tcl_SetObjResult(interp,Tcl_NewDoubleObj((double) result));
2682     return TCL_OK;
2683 }
2684 </pre>
2685 </div>
2686
2687 <p>
2688 The only exception to this rule are methods defined with <tt>%extend</tt>.  In this
2689 case, the added code is contained in a separate function.
2690 </p>
2691
2692 <p>
2693 Finally, it is important to note that most language modules may choose to
2694 build a more advanced interface. Although you may never use the low-level
2695 interface described here, most of SWIG's language modules use it in
2696 some way or another.
2697 </p>
2698
2699 <H2><a name="SWIG_nn40"></a>5.6 Code Insertion</H2>
2700
2701
2702 <p>
2703 Sometimes it is necessary to insert special code into the resulting
2704 wrapper file generated by SWIG.  For example, you may want to include
2705 additional C code to perform initialization or other operations.
2706 There are four common ways to insert code, but it's useful to know how the
2707 output of SWIG is structured first.</p>
2708
2709 <H3><a name="SWIG_nn41"></a>5.6.1 The output of SWIG</H3>
2710
2711
2712 <p>
2713 When SWIG creates its output file, it is broken up into four sections
2714 corresponding to runtime code, headers, wrapper functions, and module
2715 initialization code (in that order).   
2716 </p>
2717
2718 <ul>
2719 <li><b>Begin section</b>.  <br>
2720 A placeholder to put code at the beginning of the C/C++ wrapper file.
2721 </li>
2722
2723 <li><b>Runtime code</b>.  <br>
2724 This code is internal to SWIG and is used to include
2725 type-checking and other support functions that are used by the rest of the module.
2726 </li>
2727
2728 <li><b>Header section</b>.  <br>
2729 This is user-defined support code that has been included by 
2730 the <tt>%{ ... %}</tt> directive.  Usually this consists of header files and 
2731 other helper functions.
2732 </li>
2733
2734 <li><b>Wrapper code</b>.  <br>
2735 These are the wrappers generated automatically by SWIG.
2736 </li>
2737
2738 <li><b>Module initialization</b>.  <br>
2739 The function generated by SWIG to initialize
2740 the module upon loading.
2741 </li>
2742 </ul>
2743
2744 <H3><a name="SWIG_nn42"></a>5.6.2 Code insertion blocks</H3>
2745
2746
2747 <p>
2748 Code is inserted into the appropriate code section by using one
2749 of the code insertion directives listed below. The order of the sections in
2750 the wrapper file is as shown:
2751 </p>
2752
2753 <div class="code">
2754 <pre>
2755 %begin %{
2756    ... code in begin section ...
2757 %}
2758
2759 %runtime %{
2760    ... code in runtime section ...
2761 %}
2762
2763 %header %{
2764    ... code in header section ...
2765 %}
2766
2767 %wrapper %{
2768    ... code in wrapper section ...
2769 %}
2770
2771 %init %{
2772    ... code in init section ...
2773 %}
2774 </pre>
2775 </div>
2776
2777 <p>
2778 The bare <tt>%{ ... %}</tt> directive is a shortcut that is the same as
2779 <tt>%header %{ ... %}</tt>. 
2780 </p>
2781
2782 <p>
2783 The <tt>%begin</tt> section is effectively empty as it just contains the SWIG banner by default. 
2784 This section is provided as a way for users to insert code at the top of the wrapper file before any other code is generated.
2785 Everything in a code insertion block is copied verbatim into the output file and is 
2786 not parsed by SWIG.   Most SWIG input files have at least one such block to include header
2787 files and support C code.  Additional code blocks may be placed anywhere in a
2788 SWIG file as needed. </p>
2789
2790 <div class="code"><pre>
2791 %module mymodule
2792 %{
2793 #include "my_header.h"
2794 %}
2795 ... Declare functions here
2796 %{
2797
2798 void some_extra_function() {
2799   ...
2800 }
2801 %}
2802 </pre></div>
2803
2804 <p>
2805 A common use for code blocks is to write "helper" functions. These
2806 are functions that are used specifically for the purpose of building
2807 an interface, but which are generally not visible to the normal C
2808 program. For example :</p>
2809
2810 <div class="code"><pre>
2811 %{
2812 /* Create a new vector */
2813 static Vector *new_Vector() {
2814         return (Vector *) malloc(sizeof(Vector));
2815 }
2816
2817 %}
2818 // Now wrap it 
2819 Vector *new_Vector();
2820 </pre></div>
2821
2822 <H3><a name="SWIG_nn43"></a>5.6.3 Inlined code blocks</H3>
2823
2824
2825 <p>
2826 Since the process of writing helper functions is fairly common,
2827 there is a special inlined form of code block that is used as follows
2828 :</p>
2829
2830 <div class="code"><pre>
2831 %inline %{
2832 /* Create a new vector */
2833 Vector *new_Vector() {
2834         return (Vector *) malloc(sizeof(Vector));
2835 }
2836 %}
2837
2838 </pre></div>
2839
2840 <p>
2841 The <tt>%inline</tt> directive inserts all of the code that follows
2842 verbatim into the header portion of an interface file. The code is
2843 then parsed by both the SWIG preprocessor and parser.
2844 Thus, the above example creates a new command <tt>new_Vector</tt> using only one
2845 declaration. Since the code inside an <tt>%inline %{ ... %}</tt> block
2846 is given to both the C compiler and SWIG, it is illegal to include any
2847 SWIG directives inside a <tt>%{ ... %}</tt> block.</p>
2848
2849 <H3><a name="SWIG_nn44"></a>5.6.4 Initialization blocks</H3>
2850
2851
2852 <p>
2853 When code is included in the <tt>%init</tt> section, it is copied directly into the 
2854 module initialization function.  For example, if you needed to perform some extra
2855 initialization on module loading, you could write this:
2856 </p>
2857
2858 <div class="code"><pre>
2859 %init %{
2860         init_variables();
2861 %}
2862 </pre></div>
2863
2864 <H2><a name="SWIG_nn45"></a>5.7 An Interface Building Strategy</H2>
2865
2866
2867 <p>
2868 This section describes the general approach for building interface
2869 with SWIG. The specifics related to a particular scripting language
2870 are found in later chapters.</p>
2871
2872 <H3><a name="SWIG_nn46"></a>5.7.1 Preparing a C program for SWIG</H3>
2873
2874
2875 <p>
2876 SWIG doesn't require modifications to your C code, but if you feed it
2877 a collection of raw C header files or source code, the results might
2878 not be what you expect---in fact, they might be awful. Here's a series
2879 of steps you can follow to make an interface for a C program :</p>
2880
2881 <ul>
2882 <li>Identify the functions that you want to wrap. It's probably not
2883 necessary to access every single function in a C program--thus, a
2884 little forethought can dramatically simplify the resulting scripting
2885 language interface. C header files are particularly good source for
2886 finding things to wrap.
2887
2888 <li>Create a new interface file to describe the scripting language
2889 interface to your program.
2890
2891 <li>Copy the appropriate declarations into the interface file or use
2892 SWIG's <tt>%include</tt> directive to process an entire C
2893 source/header file. 
2894
2895 <li>Make sure everything in the interface file uses ANSI C/C++ syntax.
2896
2897 <li>Make sure all necessary `<tt>typedef</tt>' declarations and
2898 type-information is available in the interface file. 
2899 In particular, ensure that the type information is specified in the correct order as required by a C/C++ compiler.
2900 Most importantly, define a type before it is used! A C compiler will tell you
2901 if the full type information is not available if it is needed, whereas
2902 SWIG will usually not warn or error out as it is designed to work without
2903 full type information. However, if type information is not specified
2904 correctly, the wrappers can be sub-optimal and even result in uncompileable C/C++ code.
2905
2906 <li>If your program has a main() function, you may need to rename it
2907 (read on).
2908
2909 <li>Run SWIG and compile.
2910 </ul>
2911
2912 <p>
2913 Although this may sound complicated, the process turns out to be
2914 fairly easy once you get the hang of it. 
2915 </p>
2916
2917 <p>
2918 In the process of building an interface, SWIG may encounter syntax errors or
2919 other problems.  The best way to deal with this is to simply copy the offending
2920 code into a separate interface file and edit it.   However, the SWIG developers
2921 have worked very hard to improve the SWIG parser--you should report parsing errors
2922 to the <a href="http://www.swig.org/mail.html">swig-devel mailing list</a> or to the 
2923 <a href="http://www.swig.org/bugs.html">SWIG bug tracker</a>.
2924 </p>
2925
2926 <H3><a name="SWIG_nn47"></a>5.7.2 The SWIG interface file</H3>
2927
2928
2929 <p>
2930 The preferred method of using SWIG is to generate separate interface
2931 file. Suppose you have the following C header file :</p>
2932
2933 <div class="code"><pre>
2934 /* File : header.h */
2935
2936 #include &lt;stdio.h&gt;
2937 #include &lt;math.h&gt;
2938
2939 extern int foo(double);
2940 extern double bar(int, int);
2941 extern void dump(FILE *f);
2942
2943 </pre></div>
2944
2945 <p>
2946 A typical SWIG interface file for this header file would look like the
2947 following :</p>
2948
2949 <div class="code"><pre>
2950 /* File : interface.i */
2951 %module mymodule
2952 %{
2953 #include "header.h"
2954 %}
2955 extern int foo(double);
2956 extern double bar(int, int);
2957 extern void dump(FILE *f);
2958
2959 </pre></div>
2960
2961 <p>
2962 Of course, in this case, our header file is pretty simple so we could
2963 use a simpler approach and use an interface file like this:</p>
2964
2965 <div class="code"><pre>
2966 /* File : interface.i */
2967 %module mymodule
2968 %{
2969 #include "header.h"
2970 %}
2971 %include "header.h"
2972 </pre></div>
2973
2974 <p>
2975 The main advantage of this approach is minimal maintenance of an interface file for when the header file changes in the future.
2976 In more complex projects, an interface file containing numerous <tt>%include</tt> and <tt>#include</tt> statements like this is one of the most common approaches to interface file design due to lower maintenance overhead.
2977 </p>
2978
2979 <H3><a name="SWIG_nn48"></a>5.7.3 Why use separate interface files?</H3>
2980
2981
2982 <p>
2983 Although SWIG can parse many header files, it is more common to write a
2984 special <tt>.i</tt> file defining the interface to a package. There
2985 are several reasons why you might want to do this:
2986 </p>
2987
2988 <ul>
2989 <li>It is rarely necessary to access every single function in a large
2990 package. Many C functions might have little or no use in a scripted
2991 environment. Therefore, why wrap them?
2992
2993 <li>Separate interface files provide an opportunity to provide more
2994 precise rules about how an interface is to be constructed.
2995
2996 <li>Interface files can provide more structure and organization.
2997
2998 <li>SWIG can't parse certain definitions that appear in header
2999 files. Having a separate file allows you to eliminate or work around
3000 these problems.
3001
3002 <li>Interface files provide a more precise definition of what the interface
3003 is. Users wanting to extend the system can go to the interface file
3004 and immediately see what is available without having to dig it out of
3005 header files.
3006 </ul>
3007
3008 <H3><a name="SWIG_nn49"></a>5.7.4 Getting the right header files</H3>
3009
3010
3011 <p>
3012 Sometimes, it is necessary to use certain header files in order for
3013 the code generated by SWIG to compile properly. Make sure you
3014 include certain header files by using a <tt>%{,%}</tt> block like this:
3015 </p>
3016
3017 <div class="code"><pre>
3018 %module graphics
3019 %{
3020 #include &lt;GL/gl.h&gt;
3021 #include &lt;GL/glu.h&gt;
3022 %}
3023
3024 // Put rest of declarations here
3025 ...
3026 </pre></div>
3027
3028 <H3><a name="SWIG_nn50"></a>5.7.5 What to do with main()</H3>
3029
3030
3031 <p>
3032 If your program defines a <tt>main()</tt> function, you may need to
3033 get rid of it or rename it in order to use a scripting language. Most
3034 scripting languages define their own <tt>main()</tt> procedure that
3035 is called instead. <tt>main()</tt> also makes no sense when
3036 working with dynamic loading. There are a few approaches to solving
3037 the <tt>main()</tt> conflict :</p>
3038
3039 <ul>
3040 <li>Get rid of <tt>main()</tt> entirely. 
3041
3042 <li>Rename <tt>main()</tt> to something else. You can do this by
3043 compiling your C program with an option like <tt>-Dmain=oldmain</tt>.
3044
3045 <li>Use conditional compilation to only include <tt>main()</tt> when
3046 not using a scripting language.
3047 </ul>
3048
3049 <p>
3050 Getting rid of <tt>main()</tt> may cause potential initialization
3051 problems of a program. To handle this problem, you may consider
3052 writing a special function called <tt>program_init()</tt> that
3053 initializes your program upon startup. This function could then be
3054 called either from the scripting language as the first operation, or
3055 when the SWIG generated module is loaded.</p>
3056
3057 <p>
3058 As a general note, many C programs only use the <tt>main()</tt>
3059 function to parse command line options and to set parameters. However,
3060 by using a scripting language, you are probably trying to create a
3061 program that is more interactive. In many cases, the old
3062 <tt>main()</tt> program can be completely replaced by a Perl, Python,
3063 or Tcl script.</p>
3064
3065 <p>
3066 <b>Note:</b> If some cases, you might be inclined to create a
3067 scripting language wrapper for <tt>main()</tt>.  If you do this, the
3068 compilation will probably work and your module might even load
3069 correctly.  The only trouble is that when you call your
3070 <tt>main()</tt> wrapper, you will find that it actually invokes the
3071 <tt>main()</tt> of the scripting language interpreter itself!    This behavior
3072 is a side effect of the symbol binding mechanism used in the dynamic linker.
3073 The bottom line: don't do this.
3074 </p>
3075
3076 </body>
3077 </html>