1 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
4 <title>SWIG Basics</title>
5 <link rel="stylesheet" type="text/css" href="style.css">
8 <body bgcolor="#ffffff">
9 <H1><a name="SWIG"></a>5 SWIG Basics</H1>
11 <div class="sectiontoc">
13 <li><a href="#SWIG_nn2">Running SWIG</a>
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>
22 <li><a href="#SWIG_nn9">Wrapping Simple C Declarations</a>
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>
30 <li><a href="#SWIG_nn15">Pointers and complex objects</a>
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>
38 <li><a href="#SWIG_nn21">Other Practicalities</a>
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>
50 <li><a href="#SWIG_nn31">Structures and unions</a>
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>
61 <li><a href="#SWIG_nn40">Code Insertion</a>
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>
68 <li><a href="#SWIG_nn45">An Interface Building Strategy</a>
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>
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
91 <H2><a name="SWIG_nn2"></a>5.1 Running SWIG</H2>
95 To run SWIG, use the <tt>swig</tt> command with options options and a filename like this:
98 <div class="shell"><pre>
99 swig [ <em>options</em> ] filename
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>.
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
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
149 <H3><a name="SWIG_nn3"></a>5.1.1 Input format</H3>
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).
163 The most common format of a SWIG interface is as follows:
166 <div class="code"><pre>
169 #include "myheader.h"
171 // Now list ANSI C/C++ declarations
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.
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.
196 <H3><a name="output"></a>5.1.2 SWIG Output</H3>
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:
213 <div class="shell"><pre>
214 $ swig -c++ -python -o example_wrap.cpp example.i
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.
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:
234 <div class="shell"><pre>
235 $ swig -c++ -python -outdir pyfiles -o cppfiles/example_wrap.cpp example.i
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
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.
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>.
256 <H3><a name="SWIG_nn5"></a>5.1.3 Comments</H3>
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.
266 <H3><a name="SWIG_nn6"></a>5.1.4 C Preprocessor</H3>
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.).
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.
290 <H3><a name="SWIG_nn7"></a>5.1.5 SWIG Directives</H3>
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.
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:
306 <div class="code"><pre>
307 /* header.h --- Some header file */
309 /* SWIG directives -- only seen if SWIG is running */
317 <tt>SWIG</tt> is a special preprocessing symbol defined by SWIG when
318 it is parsing an input file.
321 <H3><a name="SWIG_nn8"></a>5.1.6 Parser Limitations</H3>
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
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):
339 /* Non-conventional placement of storage specifier (extern) */
340 const int extern Number;
342 /* Extra declarator grouping */
343 Matrix (foo); // A global variable
345 /* Extra declarator grouping in parameters */
346 void bar(Spam (Grok)(Doh));
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?).
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:
366 /* Not supported by SWIG */
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.
380 In the event of a parsing error, conditional compilation can be used to skip
381 offending code. For example:
387 ... some bad declarations ...
392 Alternatively, you can just delete the offending code from the interface file.
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&R).
409 <H2><a name="SWIG_nn9"></a>5.2 Wrapping Simple C Declarations</H2>
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:
418 <div class="code"><pre>
422 extern double sin(double x);
423 extern int strcmp(const char *, const char *);
427 #define VERSION "1.1"
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:
437 <div class="targetlang"><pre>
453 <div class="targetlang"><pre>
454 >>> example.sin(3)
456 >>> example.strcmp('Dave','Mike')
458 >>> print example.cvar.Foo
460 >>> print example.STATUS
462 >>> print example.VERSION
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.
472 <H3><a name="SWIG_nn10"></a>5.2.1 Basic Type Handling</H3>
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
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:
489 <div class="code"><pre>
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 -->
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>
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>
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.
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.
547 SWIG recognizes the following floating point types :</p>
549 <div class="code"><pre>
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>
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>
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.
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.
597 <H3><a name="SWIG_nn11"></a>5.2.2 Global Variables</H3>
601 Whenever possible, SWIG maps C/C++ global variables into scripting language
602 variables. For example,
605 <div class="code"><pre>
611 results in a scripting language variable like this:
614 <div class="code"><pre>
616 set foo [3.5] ;# Set foo to 3.5
617 puts $foo ;# Print the value of foo
620 cvar.foo = 3.5 # Set foo to 3.5
621 print cvar.foo # Print value of foo
624 $foo = 3.5; # Set foo to 3.5
625 print $foo,"\n"; # Print value of foo
628 Module.foo = 3.5 # Set foo to 3.5
629 print Module.foo, "\n" # Print value of foo
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
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
652 <H3><a name="SWIG_nn12"></a>5.2.3 Constants</H3>
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>
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
666 enum boolean {NO=0, YES=1};
667 enum months {JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG,
669 %constant double BLAH = 42.37;
671 #define FLAGS 0x04 | 0x08 | 0x40
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.
687 #define EXTERN extern
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,
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
713 #define F_CONST (double) 5 // A floating pointer constant with cast
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>
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.
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.
741 <H3><a name="SWIG_nn13"></a>5.2.4 A brief word about <tt>const</tt></H3>
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
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.
764 Here are some examples of <tt>const</tt> declarations.
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
776 Here is an example of a declaration that is not <tt>const</tt>:
781 const char *e; // A pointer to a constant character. The pointer
786 In this case, the pointer <tt>e</tt> can change---it's only the value
787 being pointed to that is read-only.
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:
813 %constant double PI = 3.14159;
824 #define const %constant
826 const double foo = 3.4;
827 const double bar = 23.4;
837 <H3><a name="SWIG_nn14"></a>5.2.5 A cautionary tale of <tt>char *</tt></H3>
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.
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:
858 char *strcat(char *s, const char *t)
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.
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>.
876 <H2><a name="SWIG_nn15"></a>5.3 Pointers and complex objects</H2>
880 Most C programs manipulate arrays, structures, and other types of objects. This section
881 discusses the handling of these datatypes.
884 <H3><a name="SWIG_nn16"></a>5.3.1 Simple pointers</H3>
888 Pointers to primitive C datatypes such as </p>
890 <div class="code"><pre>
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>
902 <div class="targetlang"><pre>
909 A NULL pointer is represented by the string "NULL" or the value 0
910 encoded with type information.</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.
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>
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.
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
945 <li>By handling all pointers in a consistent manner, the implementation of SWIG is greatly
946 simplified and less prone to error.
950 <H3><a name="SWIG_nn17"></a>5.3.2 Run time pointer type checking</H3>
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
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.
972 <H3><a name="SWIG_nn18"></a>5.3.3 Derived types, structs, and classes</H3>
976 For everything else (structs, classes, arrays, etc...) SWIG applies a
977 very simple rule :</p>
980 <b>Everything else is a pointer</b>
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>
990 Although this probably sounds complicated, it's really quite
991 simple. Suppose you have an interface file like this :</p>
993 <div class="code"><pre>
995 FILE *fopen(char *, char *);
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);
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
1010 <div class="targetlang"><pre>
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 > 0):
1018 fwrite(buffer,8192,1,f2)
1019 nbytes = fread(buffer,8192,1,f1)
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>
1029 <H3><a name="SWIG_nn19"></a>5.3.4 Undefined datatypes</H3>
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>
1037 <div class="code"><pre>
1038 void matrix_multiply(Matrix *a, Matrix *b, Matrix *c);
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
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.
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:
1065 void foo(size_t num);
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:
1078 TypeError: expected a _p_size_t.
1083 The only way to fix this problem is to make sure you properly declare type names using
1087 <!-- We might want to add an error reporting flag to swig -->
1089 <H3><a name="SWIG_nn20"></a>5.3.5 Typedef</H3>
1093 Like C, <tt>typedef</tt> can be used to define new type names in SWIG. For example:
1096 <div class="code"><pre>
1097 typedef unsigned int size_t;
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:
1110 /* Include in the generated wrapper file */
1111 typedef unsigned int size_t;
1113 /* Tell SWIG about it */
1114 typedef unsigned int size_t;
1125 typedef unsigned int size_t;
1131 In certain cases, you might be able to include other header files to collect type information.
1138 %import "sys/types.h"
1143 In this case, you might run SWIG as follows:
1148 $ swig -I/usr/include -includeall example.i
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
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:
1169 void foo(unsigned int *ptr);
1174 The corresponding wrapper function will accept arguments of
1175 type <tt>unsigned int *</tt> or <tt>size_t *</tt>.
1178 <H2><a name="SWIG_nn21"></a>5.4 Other Practicalities</H2>
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.
1188 <H3><a name="SWIG_nn22"></a>5.4.1 Passing structures by value</H3>
1192 Sometimes a C function takes structure parameters that are passed
1193 by value. For example, consider the following function:
1196 <div class="code"><pre>
1197 double dot_product(Vector a, Vector b);
1201 To deal with this, SWIG transforms the function to use pointers by
1202 creating a wrapper equivalent to the following:
1205 <div class="code"><pre>
1206 double wrap_dot_product(Vector *a, Vector *b) {
1209 return dot_product(x,y);
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.
1219 <H3><a name="SWIG_nn23"></a>5.4.2 Return by value</H3>
1223 C functions that return structures or classes datatypes by value are more difficult
1224 to handle. Consider the following function:</p>
1226 <div class="code"><pre>
1227 Vector cross_product(Vector v1, Vector v2);
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:
1235 <div class="code"><pre>
1236 Vector *wrap_cross_product(Vector *v1, Vector *v2) {
1240 result = (Vector *) malloc(sizeof(Vector));
1241 *(result) = cross(x,y);
1247 or if SWIG was run with the <tt>-c++</tt> option:</p>
1249 <div class="code"><pre>
1250 Vector *wrap_cross(Vector *v1, Vector *v2) {
1253 Vector *result = new Vector(cross(x,y)); // Uses default copy constructor
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.
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.
1274 <H3><a name="SWIG_nn24"></a>5.4.3 Linking to structure variables</H3>
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>
1282 <div class="code"><pre>
1287 gets mapped to an underlying pair of set/get functions like this :</p>
1289 <div class="code"><pre>
1290 Vector *unit_i_get() {
1293 void unit_i_set(Vector *value) {
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.
1306 <H3><a name="SWIG_nn25"></a>5.4.4 Linking to <tt>char *</tt></H3>
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
1322 SWIG generates the following code:
1328 void foo_set(char *value) {
1330 foo = (char *) malloc(strlen(value)+1);
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];
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:
1352 void set_foo(char *value) {
1353 strncpy(foo,value, 50);
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:
1365 <div class="targetlang">
1367 >>> set_foo("Hello World")
1372 A common mistake with <tt>char *</tt> variables is to link to a variable declared like this:
1377 char *VERSION = "1.0";
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:
1395 char VERSION[64] = "1.0";
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:
1407 example.i:20. Typemap warning. Setting const char * variable may leak memory
1412 The reason for this behavior is that <tt>const char *</tt> variables are often used to point to string literals.
1418 const char *foo = "Hello World\n";
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.
1435 <H3><a name="SWIG_nn26"></a>5.4.5 Arrays</H3>
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>
1443 <div class="code"><pre>
1444 int foobar(int a[40]);
1445 void grok(char *argv[]);
1446 void transpose(double a[20][20]);
1450 are processed as if they were really declared like this:
1453 <div class="code"><pre>
1455 void grok(char **argv);
1456 void transpose(double (*a)[20]);
1460 Like C, SWIG does not perform array bounds checking.
1462 user to make sure the pointer points a suitably allocated region of memory.
1466 Multi-dimensional arrays are transformed into a pointer to an array of one less
1467 dimension. For example:
1472 int [10]; // Maps to int *
1473 int [10][20]; // Maps to int (*)[20]
1474 int [10][20][30]; // Maps to int (*)[20][30]
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.
1489 Array variables are supported, but are read-only by default. For example:
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>&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:
1509 void a_set(int i, int j, int val) {
1512 int a_get(int i, int j) {
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:
1526 // Some array helpers
1528 /* Create any sort of [size] array */
1529 int *int_array(int size) {
1530 return (int *) malloc(size*sizeof(int));
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));
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,
1552 SWIG generates functions for both getting and setting the value that are equivalent to the following
1558 char *pathname_get() {
1561 void pathname_set(char *value) {
1562 strncpy(pathname,value,256);
1568 In the target language, the value can be set like a normal variable.
1571 <H3><a name="SWIG_readonly_variables"></a>5.4.6 Creating read-only variables</H3>
1575 A read-only variable can be created by using the <tt>%immutable</tt>
1576 directive as shown :</p>
1578 <div class="code"><pre>
1579 // File : interface.i
1581 int a; // Can read/write
1583 int b,c,d // Read only variables
1585 double x,y // read/write
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:
1595 <div class="code"><pre>
1596 %immutable x; // Make x read-only
1598 double x; // Read-only (from earlier %immutable directive)
1599 double y; // Read-write
1604 The <tt>%mutable</tt> and <tt>%immutable</tt> directives are actually
1605 <a href="Customization.html#features">%feature directives</a> defined like this:
1608 <div class="code"><pre>
1609 #define %immutable %feature("immutable")
1610 #define %mutable %feature("immutable","")
1614 If you wanted to make all wrapped variables read-only, barring one or two, it might be easier to take this approach:
1617 <div class="code"><pre>
1618 %immutable; // Make all variables read-only
1619 %feature("immutable","0") x; // except, make x read/write
1628 Read-only variables are also created when declarations are declared as <tt>const</tt>.
1634 const int foo; /* Read only variable */
1635 char * const version="1.0"; /* Read only variable */
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!
1645 <H3><a name="SWIG_rename_ignore"></a>5.4.7 Renaming and ignoring declarations</H3>
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>
1655 <div class="code"><pre>
1658 %rename(my_print) print;
1659 extern void print(char *);
1661 %rename(foo) a_really_long_and_annoying_name;
1662 extern int a_really_long_and_annoying_name;
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>
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:
1677 <div class="code"><pre>
1680 %rename(my_print) print;
1681 %rename(foo) a_really_long_and_annoying_name;
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>
1694 <div class="code"><pre>
1695 %rename(output) print; // Rename all `print' functions to `output'
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>
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:
1711 %ignore print; // Ignore all declarations named print
1712 %ignore _HAVE_FOO_H; // Ignore an include guard constant
1714 %include "foo.h" // Grab a header file
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.
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.
1733 <b>Compatibility note: </b> Older versions of SWIG provided a special <tt>%name</tt> directive for renaming declarations.
1739 %name(output) extern void print(char *);
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.
1748 <H3><a name="SWIG_default_args"></a>5.4.8 Default/optional arguments</H3>
1752 SWIG supports default arguments in both C and C++ code. For example:
1755 <div class="code"><pre>
1756 int plot(double x, double y, int color=WHITE);
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>
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
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++.
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.
1785 <H3><a name="SWIG_nn30"></a>5.4.9 Pointers to functions and callbacks</H3>
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:
1796 <div class="code"><pre>
1797 int binary_op(int a, int b, int (*op)(int,int));
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:
1805 <div class="targetlang"><pre>
1806 >>> def add(x,y):
1809 >>> binary_op(3,4,add)
1810 Traceback (most recent call last):
1811 File "<stdin>", line 1, in ?
1812 TypeError: Type error. Expected _p_f_int_int__int
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:
1824 <div class="code"><pre>
1825 /* Function with a callback */
1826 int binary_op(int a, int b, int (*op)(int,int));
1828 /* Some callback functions */
1829 %constant int add(int,int);
1830 %constant int sub(int,int);
1831 %constant int mul(int,int);
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:
1839 <div class="targetlang">
1841 >>> binary_op(3,4,add)
1843 >>> binary_op(3,4,mul)
1850 Unfortunately, by declaring the callback functions as constants, they are no longer accessible
1851 as functions. For example:
1854 <div class="targetlang">
1856 >>> add(3,4)
1857 Traceback (most recent call last):
1858 File "<stdin>", line 1, in ?
1859 TypeError: object is not callable: '_ff020efc_p_f_int_int__int'
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:
1871 /* Function with a callback */
1872 int binary_op(int a, int b, int (*op)(int,int));
1874 /* Some callback functions */
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:
1889 <div class="targetlang">
1891 >>> binary_op(3,4,add_cb)
1893 >>> binary_op(3,4,mul_cb)
1895 >>> add(3,4)
1897 >>> mul(3,4)
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>.
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>:
1915 <div class="code"><pre>
1916 /* Some callback functions */
1917 %callback("%(upper)s");
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
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.
1937 <H2><a name="SWIG_nn31"></a>5.5 Structures and unions</H2>
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.
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>
1953 <div class="code"><pre>
1961 gets transformed into the following set of accessor functions :</p>
1963 <div class="code"><pre>
1964 double Vector_x_get(struct Vector *obj) {
1967 double Vector_y_get(struct Vector *obj) {
1970 double Vector_z_get(struct Vector *obj) {
1973 void Vector_x_set(struct Vector *obj, double value) {
1976 void Vector_y_set(struct Vector *obj, double value) {
1979 void Vector_z_set(struct Vector *obj, double value) {
1985 In addition, SWIG creates default constructor and destructor functions if none are
1986 defined in the interface. For example:
1989 <div class="code"><pre>
1990 struct Vector *new_Vector() {
1991 return (Vector *) calloc(1,sizeof(struct Vector));
1993 void delete_Vector(struct Vector *obj) {
2000 Using these low-level accessor functions, an object can be minimally manipulated from the target
2001 language using code like this:
2016 However, most of SWIG's language modules also provide a high-level interface that is more convenient. Keep reading.
2019 <H3><a name="SWIG_nn32"></a>5.5.1 Typedef and structures</H3>
2023 SWIG supports the following construct which is quite common in C
2026 <div class="code"><pre>
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:
2042 double Vector_x_get(Vector *obj) {
2049 If two different names are used like this :</p>
2051 <div class="code"><pre>
2052 typedef struct vector_struct {
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.
2065 <H3><a name="SWIG_nn33"></a>5.5.2 Character strings and structures</H3>
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>
2075 <div class="code"><pre>
2086 This results in the following accessor functions :</p>
2088 <div class="code"><pre>
2089 char *Foo_name_get(Foo *obj) {
2090 return Foo->name;
2093 char *Foo_name_set(Foo *obj, char *c) {
2094 if (obj->name) free(obj->name);
2095 obj->name = (char *) malloc(strlen(c)+1);
2096 strcpy(obj->name,c);
2097 return obj->name;
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.
2108 Note: If the <tt>-c++</tt> option is used, <tt>new</tt> and <tt>delete</tt> are used to
2109 perform memory allocation.
2112 <H3><a name="SWIG_nn34"></a>5.5.3 Array members</H3>
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.
2121 situation is detected, SWIG may generate a warning message such as the
2124 <div class="shell"><pre>
2125 interface.i:116. Warning. Array member will be read-only
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
2134 <H3><a name="SWIG_structure_data_members"></a>5.5.4 Structure data members</H3>
2138 Occasionally, a structure will contain data members that are themselves structures. For example:
2143 typedef struct Foo {
2147 typedef struct Bar {
2149 Foo f; /* struct member */
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:
2162 Foo *Bar_f_get(Bar *b) {
2163 return &b->f;
2165 void Bar_f_set(Bar *b, Foo *value) {
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:
2186 Translating this assignment to function calls (as would be used inside the scripting
2187 language interface) results in the following code:
2193 Foo_x_set(Bar_f_get(b),37);
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!
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,
2217 and nothing was known about <tt>WORD</tt>, then SWIG will generate more normal accessor functions
2223 WORD Foo_w_get(Foo *f) {
2226 void Foo_w_set(FOO *f, WORD value) {
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>.
2240 <H3><a name="SWIG_nn36"></a>5.5.5 C constructors and destructors</H3>
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
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:
2259 <div class="shell"><pre>
2260 swig -nodefaultctor example.i
2267 <div class="code"><pre>
2270 %nodefaultctor; // Don't create default constructors
2271 ... declarations ...
2272 %clearnodefaultctor; // Re-enable default constructors
2276 If you need more precise control, <tt>%nodefaultctor</tt> can selectively target individual structure
2277 definitions. For example:
2282 %nodefaultctor Foo; // No default constructor for Foo
2284 struct Foo { // No default constructor generated.
2287 struct Bar { // Default constructor generated.
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>
2302 %nodefaultdtor Foo; // No default/implicit destructor for Foo
2304 struct Foo { // No default destructor is generated.
2307 struct Bar { // Default destructor generated.
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.
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.
2329 <H3><a name="SWIG_adding_member_functions"></a>5.5.6 Adding member functions to C structures</H3>
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>
2345 <div class="code"><pre>
2346 /* file : vector.h */
2355 You can make a <tt>Vector</tt> look a lot like a class by writing a SWIG interface like this:
2358 <div class="code"><pre>
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) {
2369 v = (Vector *) malloc(sizeof(Vector));
2378 double magnitude() {
2379 return sqrt($self->x*$self->x+$self->y*$self->y+$self->z*$self->z);
2382 printf("Vector [%g, %g, %g]\n", $self->x,$self->y,$self->z);
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.
2398 Now, when used with proxy classes in Python, you can do things like
2401 <div class="targetlang"><pre>
2402 >>> v = Vector(3,4,0) # Create a new vector
2403 >>> print v.magnitude() # Print magnitude
2405 >>> v.print() # Print it out
2407 >>> del v # Destroy it
2411 The <tt>%extend</tt> directive can also be used inside the definition
2412 of the Vector structure. For example:</p>
2414 <div class="code"><pre>
2424 Vector(double x, double y, double z) { ... }
2432 Finally, <tt>%extend</tt> can be used to access externally written
2433 functions provided they follow the naming convention used in this
2436 <div class="code"><pre>
2437 /* File : vector.c */
2438 /* Vector methods */
2440 Vector *new_Vector(double x, double y, double z) {
2442 v = (Vector *) malloc(sizeof(Vector));
2448 void delete_Vector(Vector *v) {
2452 double Vector_magnitude(Vector *v) {
2453 return sqrt(v->x*v->x+v->y*v->y+v->z*v->z);
2466 Vector(int,int,int); // This calls new_Vector()
2467 ~Vector(); // This calls delete_Vector()
2468 double magnitude(); // This will call Vector_magnitude()
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:
2485 // Add a new attribute to Vector
2487 const double magnitude;
2489 // Now supply the implementation of the Vector_magnitude_get function
2491 const double Vector_magnitude_get(Vector *v) {
2492 return (const double) return sqrt(v->x*v->x+v->y*v->y+v->z*v->z);
2500 Now, for all practical purposes, <tt>magnitude</tt> will appear like an attribute
2505 A similar technique can also be used to work with problematic data members.
2506 For example, consider this interface:
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:
2533 // Specific implementation of set/get functions
2535 char *Person_name_get(Person *p) {
2538 void Person_name_set(Person *p, char *val) {
2539 strncpy(p->name,val,50);
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).
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.
2559 <H3><a name="SWIG_nested_structs"></a>5.5.7 Nested structures</H3>
2563 Occasionally, a C program will involve structures like this :</p>
2565 <div class="code"><pre>
2566 typedef struct Object {
2579 When SWIG encounters this, it performs a structure splitting operation
2580 that transforms the declaration into the equivalent of the
2583 <div class="code"><pre>
2591 typedef struct Object {
2593 Object_intRep intRep;
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>
2603 <div class="code"><pre>
2604 Object_intRep *Object_intRep_get(Object *o) {
2605 return (Object_intRep *) &o->intRep;
2607 int Object_intRep_ivalue_get(Object_intRep *o) {
2608 return o->ivalue;
2610 int Object_intRep_ivalue_set(Object_intRep *o, int value) {
2611 return (o->ivalue = value);
2613 double Object_intRep_dvalue_get(Object_intRep *o) {
2614 return o->dvalue;
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:
2625 <div class="targetlang"><pre>
2626 # Perl5 script for accessing nested member
2627 $o = CreateObject(); # Create an object somehow
2628 $o->{intRep}->{ivalue} = 7 # Change value of o.intRep.ivalue
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.
2637 <H3><a name="SWIG_nn39"></a>5.5.8 Other things to note about structure wrapping</H3>
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>
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,
2656 double Vector_x_get(Vector *v) {
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:
2672 _wrap_Vector_x_get(ClientData clientData, Tcl_Interp *interp,
2673 int objc, Tcl_Obj *CONST objv[]) {
2674 struct Vector *arg1 ;
2677 if (SWIG_GetArgs(interp, objc, objv,"p:Vector_x_get self ",&arg0,
2678 SWIGTYPE_p_Vector) == TCL_ERROR)
2680 result = (double ) (arg1->x);
2681 Tcl_SetObjResult(interp,Tcl_NewDoubleObj((double) result));
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.
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.
2699 <H2><a name="SWIG_nn40"></a>5.6 Code Insertion</H2>
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>
2709 <H3><a name="SWIG_nn41"></a>5.6.1 The output of SWIG</H3>
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).
2719 <li><b>Begin section</b>. <br>
2720 A placeholder to put code at the beginning of the C/C++ wrapper file.
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.
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.
2734 <li><b>Wrapper code</b>. <br>
2735 These are the wrappers generated automatically by SWIG.
2738 <li><b>Module initialization</b>. <br>
2739 The function generated by SWIG to initialize
2740 the module upon loading.
2744 <H3><a name="SWIG_nn42"></a>5.6.2 Code insertion blocks</H3>
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:
2756 ... code in begin section ...
2760 ... code in runtime section ...
2764 ... code in header section ...
2768 ... code in wrapper section ...
2772 ... code in init section ...
2778 The bare <tt>%{ ... %}</tt> directive is a shortcut that is the same as
2779 <tt>%header %{ ... %}</tt>.
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>
2790 <div class="code"><pre>
2793 #include "my_header.h"
2795 ... Declare functions here
2798 void some_extra_function() {
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>
2810 <div class="code"><pre>
2812 /* Create a new vector */
2813 static Vector *new_Vector() {
2814 return (Vector *) malloc(sizeof(Vector));
2819 Vector *new_Vector();
2822 <H3><a name="SWIG_nn43"></a>5.6.3 Inlined code blocks</H3>
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
2830 <div class="code"><pre>
2832 /* Create a new vector */
2833 Vector *new_Vector() {
2834 return (Vector *) malloc(sizeof(Vector));
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>
2849 <H3><a name="SWIG_nn44"></a>5.6.4 Initialization blocks</H3>
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:
2858 <div class="code"><pre>
2864 <H2><a name="SWIG_nn45"></a>5.7 An Interface Building Strategy</H2>
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>
2872 <H3><a name="SWIG_nn46"></a>5.7.1 Preparing a C program for SWIG</H3>
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>
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.
2888 <li>Create a new interface file to describe the scripting language
2889 interface to your program.
2891 <li>Copy the appropriate declarations into the interface file or use
2892 SWIG's <tt>%include</tt> directive to process an entire C
2895 <li>Make sure everything in the interface file uses ANSI C/C++ syntax.
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.
2906 <li>If your program has a main() function, you may need to rename it
2909 <li>Run SWIG and compile.
2913 Although this may sound complicated, the process turns out to be
2914 fairly easy once you get the hang of it.
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>.
2926 <H3><a name="SWIG_nn47"></a>5.7.2 The SWIG interface file</H3>
2930 The preferred method of using SWIG is to generate separate interface
2931 file. Suppose you have the following C header file :</p>
2933 <div class="code"><pre>
2934 /* File : header.h */
2936 #include <stdio.h>
2937 #include <math.h>
2939 extern int foo(double);
2940 extern double bar(int, int);
2941 extern void dump(FILE *f);
2946 A typical SWIG interface file for this header file would look like the
2949 <div class="code"><pre>
2950 /* File : interface.i */
2955 extern int foo(double);
2956 extern double bar(int, int);
2957 extern void dump(FILE *f);
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>
2965 <div class="code"><pre>
2966 /* File : interface.i */
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.
2979 <H3><a name="SWIG_nn48"></a>5.7.3 Why use separate interface files?</H3>
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:
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?
2993 <li>Separate interface files provide an opportunity to provide more
2994 precise rules about how an interface is to be constructed.
2996 <li>Interface files can provide more structure and organization.
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
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
3008 <H3><a name="SWIG_nn49"></a>5.7.4 Getting the right header files</H3>
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:
3017 <div class="code"><pre>
3020 #include <GL/gl.h>
3021 #include <GL/glu.h>
3024 // Put rest of declarations here
3028 <H3><a name="SWIG_nn50"></a>5.7.5 What to do with main()</H3>
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>
3040 <li>Get rid of <tt>main()</tt> entirely.
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>.
3045 <li>Use conditional compilation to only include <tt>main()</tt> when
3046 not using a scripting language.
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>
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,
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.