PageRenderTime 41ms CodeModel.GetById 14ms app.highlight 15ms RepoModel.GetById 1ms app.codeStats 0ms

/trunk/Doc/Manual/SWIG.html

#
HTML | 2032 lines | 1733 code | 295 blank | 4 comment | 0 complexity | 4ab2478ddd8445934616c2165844b179 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

   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="#SWIG_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<ul>
  48<li><a href="#SWIG_nn29">Simple renaming of specific identifiers</a>
  49<li><a href="#SWIG_advanced_renaming">Advanced renaming support</a>
  50<li><a href="#SWIG_limiting_renaming">Limiting global renaming rules</a>
  51<li><a href="#SWIG_chosen_unignore">Ignoring everything then wrapping a few selected symbols</a>
  52</ul>
  53<li><a href="#SWIG_default_args">Default/optional arguments</a>
  54<li><a href="#SWIG_nn30">Pointers to functions and callbacks</a>
  55</ul>
  56<li><a href="#SWIG_nn31">Structures and unions</a>
  57<ul>
  58<li><a href="#SWIG_nn32">Typedef and structures</a>
  59<li><a href="#SWIG_nn33">Character strings and structures</a>
  60<li><a href="#SWIG_nn34">Array members</a>
  61<li><a href="#SWIG_structure_data_members">Structure data members</a>
  62<li><a href="#SWIG_nn36">C constructors and destructors</a>
  63<li><a href="#SWIG_adding_member_functions">Adding member functions to C structures</a>
  64<li><a href="#SWIG_nested_structs">Nested structures</a>
  65<li><a href="#SWIG_nn39">Other things to note about structure wrapping</a>
  66</ul>
  67<li><a href="#SWIG_nn40">Code Insertion</a>
  68<ul>
  69<li><a href="#SWIG_nn41">The output of SWIG</a>
  70<li><a href="#SWIG_nn42">Code insertion blocks</a>
  71<li><a href="#SWIG_nn43">Inlined code blocks</a>
  72<li><a href="#SWIG_nn44">Initialization blocks</a>
  73</ul>
  74<li><a href="#SWIG_nn45">An Interface Building Strategy</a>
  75<ul>
  76<li><a href="#SWIG_nn46">Preparing a C program for SWIG</a>
  77<li><a href="#SWIG_nn47">The SWIG interface file</a>
  78<li><a href="#SWIG_nn48">Why use separate interface files?</a>
  79<li><a href="#SWIG_nn49">Getting the right header files</a>
  80<li><a href="#SWIG_nn50">What to do with main()</a>
  81</ul>
  82</ul>
  83</div>
  84<!-- INDEX -->
  85
  86
  87
  88<p>
  89This chapter describes the basic operation of SWIG, the structure of its
  90input files, and how it handles standard ANSI C declarations.  C++ support is
  91described in the next chapter.  However, C++ programmers should still read this
  92chapter to understand the basics.
  93Specific details about each target language are described in later
  94chapters. 
  95</p>
  96
  97<H2><a name="SWIG_nn2"></a>5.1 Running SWIG</H2>
  98
  99
 100<p>
 101To run SWIG, use the <tt>swig</tt> command with options and a filename like this:
 102</p>
 103
 104<div class="shell"><pre>
 105swig [ <em>options</em> ] filename
 106</pre></div>
 107
 108<p>
 109where <tt>filename</tt> is a SWIG interface file or a C/C++ header file.
 110Below is a subset of <em>options</em> that can be used.
 111Additional options are also defined for each target language.  A full list
 112can be obtained by typing <tt>swig -help</tt> or <tt>swig
 113-<em>lang</em> -help</tt>.
 114</p>
 115
 116<div class="shell"><pre>
 117-allegrocl            Generate ALLEGROCL wrappers
 118-chicken              Generate CHICKEN wrappers
 119-clisp                Generate CLISP wrappers
 120-cffi                 Generate CFFI wrappers
 121-csharp               Generate C# wrappers
 122-go                   Generate Go wrappers
 123-guile                Generate Guile wrappers
 124-java                 Generate Java wrappers
 125-lua                  Generate Lua wrappers
 126-modula3              Generate Modula 3 wrappers
 127-mzscheme             Generate Mzscheme wrappers
 128-ocaml                Generate Ocaml wrappers
 129-perl                 Generate Perl wrappers
 130-php                  Generate PHP wrappers
 131-pike                 Generate Pike wrappers
 132-python               Generate Python wrappers
 133-r                    Generate R (aka GNU S) wrappers
 134-ruby                 Generate Ruby wrappers
 135-sexp                 Generate Lisp S-Expressions wrappers
 136-tcl                  Generate Tcl wrappers
 137-uffi                 Generate Common Lisp / UFFI wrappers
 138-xml                  Generate XML wrappers
 139
 140-c++                  Enable C++ parsing
 141-D<em>symbol</em>              Define a preprocessor symbol
 142-Fstandard            Display error/warning messages in commonly used format
 143-Fmicrosoft           Display error/warning messages in Microsoft format
 144-help                 Display all options
 145-I<em>dir</em>                 Add a directory to the file include path
 146-l<em>file</em>                Include a SWIG library file.
 147-module <em>name</em>          Set the name of the SWIG module
 148-o <em>outfile</em>            Name of output file
 149-outcurrentdir	      Set default output dir to current dir instead of input file's path
 150-outdir <em>dir</em>           Set language specific files output directory
 151-pcreversion          Display PCRE version information
 152-swiglib              Show location of SWIG library
 153-version              Show SWIG version number
 154
 155</pre></div>
 156
 157<H3><a name="SWIG_nn3"></a>5.1.1 Input format</H3>
 158
 159
 160<p>
 161As input, SWIG expects a file containing ANSI C/C++ declarations and
 162special SWIG directives.  More often than not, this is a special SWIG
 163interface file which is usually denoted with a special <tt>.i</tt> or
 164<tt>.swg</tt> suffix.  In certain cases, SWIG can be used directly on
 165raw header files or source files.  However, this is not the most
 166typical case and there are several reasons why you might not want to
 167do this (described later).
 168</p>
 169
 170<p>
 171The most common format of a SWIG interface is as follows:
 172</p>
 173
 174<div class="code"><pre>
 175%module mymodule 
 176%{
 177#include "myheader.h"
 178%}
 179// Now list ANSI C/C++ declarations
 180int foo;
 181int bar(int x);
 182...
 183</pre></div>
 184<p>
 185The module name is supplied using the special <tt>%module</tt>
 186directive. Modules are described further in the <a href="Modules.html#Modules_introduction">Modules Introduction</a> section.
 187</p>
 188
 189<p>
 190Everything in the <tt>%{ ... %}</tt> block is simply copied verbatim
 191to the resulting wrapper file created by SWIG.  This section is almost
 192always used to include header files and other declarations that are
 193required to make the generated wrapper code compile.  It is important
 194to emphasize that just because you include a declaration in a SWIG
 195input file, that declaration does <em>not</em> automatically appear in
 196the generated wrapper code---therefore you need to make sure you
 197include the proper header files in the <tt>%{ ... %}</tt> section.  It
 198should be noted that the text enclosed in <tt>%{ ... %}</tt> is not
 199parsed or interpreted by SWIG.  The <tt>%{...%}</tt> syntax and
 200semantics in SWIG is analogous to that of the declarations section
 201used in input files to parser generation tools such as yacc or bison.
 202</p>
 203
 204<H3><a name="SWIG_output"></a>5.1.2 SWIG Output</H3>
 205
 206
 207<p>
 208The output of SWIG is a C/C++ file that contains all of the wrapper
 209code needed to build an extension module.  SWIG may generate some
 210additional files depending on the target language. By default, an input file
 211with the name <tt>file.i</tt> is transformed into a file
 212<tt>file_wrap.c</tt> or <tt>file_wrap.cxx</tt> (depending on whether
 213or not the <tt>-c++</tt> option has been used).  The name of the
 214output file can be changed using the <tt>-o</tt> option.  In certain
 215cases, file suffixes are used by the compiler to determine the source
 216language (C, C++, etc.). Therefore, you have to use the
 217<tt>-o</tt> option to change the suffix of the SWIG-generated wrapper
 218file if you want something different than the default. For example:
 219</p>
 220
 221<div class="shell"><pre>
 222$ swig -c++ -python -o example_wrap.cpp example.i
 223</pre></div>
 224
 225<p>
 226The C/C++ output file created by SWIG often
 227contains everything that is needed to construct a extension module
 228for the target scripting language. SWIG is not a stub compiler nor is it
 229usually necessary to edit the output file (and if you look at the output,
 230you probably won't want to). To build the final extension module, the
 231SWIG output file is compiled and linked with the rest of your C/C++
 232program to create a shared library. 
 233</p>
 234
 235<p>
 236Many target languages will also generate proxy class files in the
 237target language. The default output directory for these language 
 238specific files is the same directory as the generated C/C++ file. This
 239can be modified using the <tt>-outdir</tt> option. For example:
 240</p>
 241
 242<div class="shell"><pre>
 243$ swig -c++ -python -outdir pyfiles -o cppfiles/example_wrap.cpp example.i
 244</pre></div>
 245<p>
 246If the directories <tt>cppfiles</tt> and <tt>pyfiles</tt> exist, the following
 247will be generated:</p>
 248<div class="shell"><pre>
 249cppfiles/example_wrap.cpp
 250pyfiles/example.py
 251</pre></div>
 252
 253<p>
 254If the <tt>-outcurrentdir</tt> option is used (without <tt>-o</tt>)
 255then SWIG behaves like a typical C/C++
 256compiler and the default output directory is then the current directory. Without
 257this option the default output directory is the path to the input file. 
 258If <tt>-o</tt> and
 259<tt>-outcurrentdir</tt> are used together, <tt>-outcurrentdir</tt> is effectively ignored
 260as the output directory for the language files is the same directory as the
 261generated C/C++ file if not overidden with <tt>-outdir</tt>.
 262</p>
 263
 264<H3><a name="SWIG_nn5"></a>5.1.3 Comments</H3>
 265
 266
 267<p>
 268C and C++ style comments may appear anywhere in interface files.  In
 269previous versions of SWIG, comments were used to generate
 270documentation files. However, this feature is currently under repair
 271and will reappear in a later SWIG release.
 272</p>
 273
 274<H3><a name="SWIG_nn6"></a>5.1.4 C Preprocessor</H3>
 275
 276
 277<p>
 278Like C, SWIG preprocesses all input files through an enhanced version
 279of the C preprocessor.  All standard preprocessor features are
 280supported including file inclusion, conditional compilation and
 281macros. However, <tt>#include</tt> statements are ignored unless the
 282<tt>-includeall</tt> command line option has been supplied.  The
 283reason for disabling includes is that SWIG is sometimes used to
 284process raw C header files.  In this case, you usually only want the
 285extension module to include functions in the supplied header file
 286rather than everything that might be included by that header file
 287(i.e., system headers, C library functions, etc.).
 288</p>
 289
 290<p>
 291It should also be noted that the SWIG preprocessor skips all text
 292enclosed inside a <tt>%{...%}</tt> block.  In addition, the
 293preprocessor includes a number of macro handling enhancements that
 294make it more powerful than the normal C preprocessor.  These
 295extensions are described in the "<a href="Preprocessor.html#Preprocessor">Preprocessor</a>" chapter.
 296</p>
 297
 298<H3><a name="SWIG_nn7"></a>5.1.5 SWIG Directives</H3>
 299
 300
 301<p>
 302Most of SWIG's operation is controlled by special directives that are
 303always preceded by a "<tt>%</tt>" to distinguish them from normal C
 304declarations. These directives are used to give SWIG hints or to alter
 305SWIG's parsing behavior in some manner.   
 306</p>
 307
 308<p>
 309Since SWIG directives are not legal C syntax, it is generally not
 310possible to include them in header files.  However, SWIG directives can be
 311included in C header files using conditional compilation like this:
 312</p>
 313
 314<div class="code"><pre>
 315/* header.h  --- Some header file */
 316
 317/* SWIG directives -- only seen if SWIG is running */ 
 318#ifdef SWIG
 319%module foo
 320#endif
 321</pre>
 322</div>
 323
 324<p>
 325<tt>SWIG</tt> is a special preprocessing symbol defined by SWIG when
 326it is parsing an input file.
 327</p>
 328
 329<H3><a name="SWIG_nn8"></a>5.1.6 Parser Limitations</H3>
 330
 331
 332<p>
 333Although SWIG can parse most C/C++ declarations, it does not
 334provide a complete C/C++ parser implementation.  Most of these
 335limitations pertain to very complicated type declarations and certain
 336advanced C++ features.  Specifically, the following features are not
 337currently supported:
 338</p>
 339
 340<ul>
 341  <li>
 342<p>
 343Non-conventional type declarations.
 344For example, SWIG does not support declarations such as the following
 345(even though this is legal C):
 346
 347</p>
 348<div class="code">
 349<pre>
 350/* Non-conventional placement of storage specifier (extern) */
 351const int extern Number;
 352
 353/* Extra declarator grouping */
 354Matrix (foo);    // A global variable
 355
 356/* Extra declarator grouping in parameters */
 357void bar(Spam (Grok)(Doh));
 358
 359</pre>
 360</div>
 361
 362<p>
 363In practice, few (if any) C programmers actually write code like
 364this since this style is never featured in programming books.  However,
 365if you're feeling particularly obfuscated, you can certainly break SWIG (although why would you want to?).
 366</p>
 367</li>
 368
 369<li>
 370<p>
 371Running SWIG on C++ source files (the code in a .C, .cpp or .cxx file) is not recommended.
 372The usual approach is to feed SWIG header files for parsing C++ definitions and declarations.
 373The main reason is if SWIG parses a scoped definition or declaration (as is normal for C++ source files),
 374it is ignored, unless a declaration for the symbol was parsed earlier.
 375For example
 376</p>
 377
 378<div class="code">
 379<pre>
 380/* bar not wrapped unless foo has been defined and 
 381   the declaration of bar within foo has already been parsed */
 382int foo::bar(int) {
 383    ... whatever ...
 384}
 385</pre>
 386</div>
 387</li>
 388
 389<li>
 390<p>
 391Certain advanced features of C++ such as nested classes 
 392are not yet fully supported. Please see the C++ <a href="SWIGPlus.html#SWIGPlus_nested_classes">Nested classes</a> section
 393for more information.
 394</p>
 395</ul>
 396
 397<p>
 398In the event of a parsing error, conditional compilation can be used to skip
 399offending code.  For example:
 400</p>
 401
 402<div class="code">
 403<pre>
 404#ifndef SWIG
 405... some bad declarations ...
 406#endif
 407</pre>
 408</div>
 409<p>
 410Alternatively, you can just delete the offending code from the interface file.
 411</p>
 412
 413<p>
 414One of the reasons why SWIG does not provide a full C++ parser
 415implementation is that it has been designed to work with incomplete
 416specifications and to be very permissive in its handling of C/C++
 417datatypes (e.g., SWIG can generate interfaces even when there are
 418missing class declarations or opaque datatypes).  Unfortunately, this
 419approach makes it extremely difficult to implement certain parts of a
 420C/C++ parser as most compilers use type information to assist in the
 421parsing of more complex declarations (for the truly curious, the
 422primary complication in the implementation is that the SWIG parser
 423does not utilize a separate <em>typedef-name</em> terminal symbol as
 424described on p. 234 of K&amp;R).
 425</p>
 426
 427<H2><a name="SWIG_nn9"></a>5.2 Wrapping Simple C Declarations</H2>
 428
 429
 430<p>
 431SWIG wraps simple C declarations by creating an interface that closely matches
 432the way in which the declarations would be used in a C program.
 433For example, consider the following interface file:
 434</p>
 435
 436<div class="code"><pre>
 437%module example
 438
 439%inline %{
 440extern double sin(double x);
 441extern int strcmp(const char *, const char *);
 442extern int Foo;
 443%}
 444#define STATUS 50
 445#define VERSION "1.1"
 446</pre></div>
 447<p>
 448In this file, there are two functions <tt>sin()</tt> and <tt>strcmp()</tt>,
 449a global variable <tt>Foo</tt>, and two constants <tt>STATUS</tt> and
 450<tt>VERSION</tt>.  When SWIG creates an extension module, these
 451declarations are accessible as scripting language functions, variables, and
 452constants respectively.  For example, in Tcl:
 453</p>
 454
 455<div class="targetlang"><pre>
 456% sin 3
 4575.2335956
 458% strcmp Dave Mike
 459-1
 460% puts $Foo
 46142
 462% puts $STATUS
 46350
 464% puts $VERSION
 4651.1
 466</pre></div>
 467<p>
 468Or in Python:
 469</p>
 470
 471<div class="targetlang"><pre>
 472&gt;&gt;&gt; example.sin(3)
 4735.2335956
 474&gt;&gt;&gt; example.strcmp('Dave','Mike')
 475-1
 476&gt;&gt;&gt; print example.cvar.Foo
 47742
 478&gt;&gt;&gt; print example.STATUS
 47950
 480&gt;&gt;&gt; print example.VERSION
 4811.1
 482</pre></div>
 483<p>
 484Whenever possible, SWIG creates an interface that closely matches the underlying C/C++
 485code. However, due to subtle differences between languages, run-time
 486environments, and semantics, it is not always possible to do so.   The
 487next few sections describes various aspects of this mapping.
 488</p>
 489
 490<H3><a name="SWIG_nn10"></a>5.2.1 Basic Type Handling</H3>
 491
 492
 493<p>
 494In order to build an interface, SWIG has to convert C/C++ datatypes to
 495equivalent types in the target language.  Generally,
 496scripting languages provide a more limited set of primitive types than C.
 497Therefore, this conversion process involves a certain amount of type
 498coercion.
 499</p>
 500
 501<p>
 502Most scripting languages provide a single integer type that is implemented using
 503the <tt>int</tt> or <tt>long</tt> datatype in C.   The following list shows
 504all of the C datatypes that SWIG will convert to and from integers in the target language:
 505</p>
 506
 507<div class="code"><pre>
 508int
 509short
 510long
 511unsigned
 512signed
 513unsigned short
 514unsigned long
 515unsigned char
 516signed char
 517bool
 518</pre></div>
 519
 520<p>
 521When an integral value is converted from C, a cast is used to convert it to
 522the representation in the target language.
 523Thus, a 16 bit short in C may be promoted to a 32 bit integer.  When integers are 
 524converted in the other direction, the value is cast back into the original C type.  
 525If the value is too large to fit, it is silently truncated.
 526<!-- Dave: Maybe we should fix this -->
 527</p>
 528
 529<p>
 530<tt>unsigned char</tt> and <tt>signed char</tt> are special cases that
 531are handled as small 8-bit integers. Normally, the <tt>char</tt>
 532datatype is mapped as a one-character ASCII string. </p>
 533
 534<p>
 535The <tt>bool</tt> datatype is cast to and from an integer value of 0
 536and 1 unless the target language provides a special boolean type.</p>
 537
 538<p>
 539Some care is required when working with large integer values. Most
 540scripting languages use 32-bit integers so mapping a 64-bit long
 541integer may lead to truncation errors. Similar problems may arise with
 54232 bit unsigned integers (which may appear as large negative
 543numbers). As a rule of thumb, the <tt>int</tt> datatype and all
 544variations of <tt>char</tt> and <tt>short</tt> datatypes are safe to
 545use. For <tt>unsigned int</tt> and <tt>long</tt> datatypes, you will
 546need to carefully check the correct operation of your program after
 547it has been wrapped with SWIG.
 548</p>
 549
 550<p>
 551Although the SWIG parser supports the <tt>long long</tt> datatype, not
 552all language modules support it.  This is because <tt>long long</tt>
 553usually exceeds the integer precision available in the target
 554language.  In certain modules such as Tcl and Perl5, <tt>long
 555long</tt> integers are encoded as strings. This allows the full range
 556of these numbers to be represented.  However, it does not allow
 557<tt>long long</tt> values to be used in arithmetic expressions.  It
 558should also be noted that although <tt>long long</tt> is part
 559of the ISO C99 standard, it is not universally supported by all C
 560compilers.  Make sure you are using a compiler that supports <tt>long
 561long</tt> before trying to use this type with SWIG.
 562</p>
 563
 564<p>
 565SWIG recognizes the following floating point types :</p>
 566
 567<div class="code"><pre>
 568float
 569double
 570</pre></div>
 571
 572<p>
 573Floating point numbers are mapped to and from the natural
 574representation of floats in the target language. This is almost always
 575a C <tt>double</tt>. The rarely used datatype of <tt>long double</tt>
 576is not supported by SWIG.</p>
 577
 578<p>
 579The <tt>char</tt> datatype is mapped into a NULL terminated ASCII
 580string with a single character. When used in a scripting language it
 581shows up as a tiny string containing the character value. When
 582converting the value back into C, SWIG takes a character string
 583from the scripting language and strips off the first character as the
 584char value. Thus if the value "foo" is assigned to a
 585<tt>char</tt> datatype, it gets the value `f'.</p>
 586
 587<p>
 588The <tt>char *</tt> datatype is handled as a NULL-terminated ASCII
 589string. SWIG maps this into a 8-bit character string in the target
 590scripting language. SWIG converts character strings in the target
 591language to NULL terminated strings before passing them into
 592C/C++. The default handling of these strings does not allow them to
 593have embedded NULL bytes.  Therefore, the <tt>char *</tt> datatype is
 594not generally suitable for passing binary data.  However, it is
 595possible to change this behavior by defining a SWIG typemap.  See the chapter
 596on <a href="Typemaps.html#Typemaps">Typemaps</a> for details about this.
 597</p>
 598
 599<p>
 600At this time, SWIG provides limited support for Unicode and
 601wide-character strings (the C <tt>wchar_t</tt> type).  
 602Some languages provide typemaps for wchar_t, but bear in mind these
 603might not be portable across different operating systems.  This is a
 604delicate topic that is poorly understood by many programmers and not
 605implemented in a consistent manner across languages.  For those
 606scripting languages that provide Unicode support, Unicode strings are
 607often available in an 8-bit representation such as UTF-8 that can be
 608mapped to the <tt>char *</tt> type (in which case the SWIG interface
 609will probably work).  If the program you are wrapping uses Unicode,
 610there is no guarantee that Unicode characters in the target language
 611will use the same internal representation (e.g., UCS-2 vs. UCS-4).
 612You may need to write some special conversion functions.
 613</p>
 614
 615<H3><a name="SWIG_nn11"></a>5.2.2 Global Variables</H3>
 616
 617
 618<p>
 619Whenever possible, SWIG maps C/C++ global variables into scripting language
 620variables.  For example,
 621</p>
 622
 623<div class="code"><pre>
 624%module example
 625double foo;
 626
 627</pre></div>
 628<p>
 629results in a scripting language variable like this:
 630</p>
 631
 632<div class="code"><pre>
 633# Tcl
 634set foo [3.5]                   ;# Set foo to 3.5
 635puts $foo                       ;# Print the value of foo
 636
 637# Python
 638cvar.foo = 3.5                  # Set foo to 3.5
 639print cvar.foo                  # Print value of foo
 640
 641# Perl
 642$foo = 3.5;                     # Set foo to 3.5
 643print $foo,"\n";                # Print value of foo
 644
 645# Ruby
 646Module.foo = 3.5               # Set foo to 3.5
 647print Module.foo, "\n"         # Print value of foo
 648</pre></div>
 649<p>
 650Whenever the scripting language variable is used, the underlying C
 651global variable is accessed.  Although SWIG makes every
 652attempt to make global variables work like scripting language
 653variables, it is not always possible to do so.  For instance, in
 654Python, all global variables must be accessed through a special
 655variable object known as <tt>cvar</tt> (shown above).  In Ruby, variables are
 656accessed as attributes of the module. Other languages may
 657convert variables to a pair of accessor functions.  For example, the
 658Java module generates a pair of functions <tt>double get_foo()</tt>
 659and <tt>set_foo(double val)</tt> that are used to manipulate the
 660value.
 661</p>
 662
 663<p>
 664Finally, if a global variable has been declared as <tt>const</tt>, it
 665only supports read-only access.  Note: this behavior is new to SWIG-1.3.
 666Earlier versions of SWIG incorrectly handled <tt>const</tt> and created
 667constants instead.
 668</p>
 669
 670<H3><a name="SWIG_nn12"></a>5.2.3 Constants</H3>
 671
 672
 673<p>
 674Constants can be created using <tt>#define</tt>, enumerations,
 675or a special <tt>%constant</tt> directive.  The following
 676interface file shows a few valid constant declarations :</p>
 677
 678<div class="code"><pre>
 679#define I_CONST       5               // An integer constant
 680#define PI            3.14159         // A Floating point constant
 681#define S_CONST       "hello world"   // A string constant
 682#define NEWLINE       '\n'            // Character constant
 683
 684enum boolean {NO=0, YES=1};
 685enum months {JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG,
 686             SEP, OCT, NOV, DEC};
 687%constant double BLAH = 42.37;
 688#define PI_4 PI/4
 689#define FLAGS 0x04 | 0x08 | 0x40
 690
 691</pre></div>
 692<p>
 693In <tt>#define</tt> declarations, the type of a constant is inferred
 694by syntax. For example, a number with a decimal point is assumed to be
 695floating point.  In addition, SWIG must be able to fully resolve all
 696of the symbols used in a <tt>#define</tt> in order for a constant to
 697actually be created.  This restriction is necessary because
 698<tt>#define</tt> is also used to define preprocessor macros that are
 699definitely not meant to be part of the scripting language interface.
 700For example:
 701</p>
 702
 703<div class="code">
 704<pre>
 705#define EXTERN extern
 706
 707EXTERN void foo();
 708</pre>
 709</div>
 710<p>
 711In this case, you probably don't want to create a constant called 
 712<tt>EXTERN</tt> (what would the value be?).  In general,
 713SWIG will not create constants for macros unless the value can
 714be completely determined by the preprocessor.  For instance, in the above example,
 715the declaration
 716</p>
 717
 718<div class="code">
 719<pre>
 720#define PI_4  PI/4
 721</pre>
 722</div>
 723<p>
 724defines a constant because <tt>PI</tt> was already defined as a
 725constant and the value is known.
 726However, for the same conservative reasons even a constant with a simple cast will be ignored, such as
 727</p>
 728
 729<div class="code">
 730<pre>
 731#define F_CONST (double) 5            // A floating pointer constant with cast
 732</pre>
 733</div>
 734
 735<p>
 736The use of constant expressions is allowed, but SWIG does not evaluate
 737them. Rather, it passes them through to the output file and lets the C
 738compiler perform the final evaluation (SWIG does perform a limited
 739form of type-checking however).</p>
 740
 741<p>
 742For enumerations, it is critical that the original enum definition be
 743included somewhere in the interface file (either in a header file or
 744in the <tt>%{,%}</tt> block). SWIG only translates the enumeration
 745into code needed to add the constants to a scripting language. It
 746needs the original enumeration declaration in order to get the correct
 747enum values as assigned by the C compiler.
 748</p>
 749
 750<p>
 751The <tt>%constant</tt> directive is used to more precisely create
 752constants corresponding to different C datatypes.  Although it is not
 753usually not needed for simple values, it is more useful when working
 754with pointers and other more complex datatypes.  Typically, <tt>%constant</tt>
 755is only used when you want to add constants to the scripting language
 756interface that are not defined in the original header file. 
 757</p>
 758
 759<H3><a name="SWIG_nn13"></a>5.2.4 A brief word about <tt>const</tt></H3>
 760
 761
 762<p>
 763A common confusion with C programming is the semantic meaning of the
 764<tt>const</tt> qualifier in declarations--especially when it is mixed
 765with pointers and other type modifiers. In fact, previous versions of SWIG
 766handled <tt>const</tt> incorrectly--a situation that SWIG-1.3.7 and newer
 767releases have fixed.
 768</p>
 769
 770<p>
 771Starting with SWIG-1.3, all variable declarations, regardless of any
 772use of <tt>const</tt>, are wrapped as global variables.  If a
 773declaration happens to be declared as <tt>const</tt>, it is wrapped as
 774a read-only variable. To tell if a variable is <tt>const</tt> or not,
 775you need to look at the right-most occurrence of the <tt>const</tt>
 776qualifier (that appears before the variable name).  If the right-most
 777<tt>const</tt> occurs after all other type modifiers (such as
 778pointers), then the variable is <tt>const</tt>.  Otherwise, it is not.
 779</p>
 780
 781<p>
 782Here are some examples of <tt>const</tt> declarations.
 783</p>
 784
 785<div class="code">
 786<pre>
 787const char a;           // A constant character
 788char const b;           // A constant character (the same)
 789char *const c;          // A constant pointer to a character
 790const char *const d;    // A constant pointer to a constant character
 791</pre>
 792</div>
 793<p>
 794Here is an example of a declaration that is not <tt>const</tt>:
 795</p>
 796
 797<div class="code">
 798<pre>
 799const char *e;          // A pointer to a constant character.  The pointer
 800                        // may be modified.
 801</pre>
 802</div>
 803<p>
 804In this case, the pointer <tt>e</tt> can change---it's only the value
 805being pointed to that is read-only.
 806</p>
 807
 808<p>
 809Please note that for const parameters or return types used in a function, SWIG pretty much ignores
 810the fact that these are const, see the section on <a href="SWIGPlus.html#SWIGPlus_const">const-correctness</a>
 811for more information.
 812</p>
 813
 814<p>
 815<b>Compatibility Note:</b> One reason for changing SWIG to handle
 816<tt>const</tt> declarations as read-only variables is that there are
 817many situations where the value of a <tt>const</tt> variable might
 818change.  For example, a library might export a symbol as
 819<tt>const</tt> in its public API to discourage modification, but still
 820allow the value to change through some other kind of internal
 821mechanism.  Furthermore, programmers often overlook the fact that with
 822a constant declaration like <tt>char *const</tt>, the underlying data
 823being pointed to can be modified--it's only the pointer itself that is
 824constant.  In an embedded system, a <tt>const</tt> declaration might
 825refer to a read-only memory address such as the location of a
 826memory-mapped I/O device port (where the value changes, but writing to
 827the port is not supported by the hardware).  Rather than trying to
 828build a bunch of special cases into the <tt>const</tt> qualifier, the
 829new interpretation of <tt>const</tt> as "read-only" is simple and
 830exactly matches the actual semantics of <tt>const</tt> in C/C++.  If
 831you really want to create a constant as in older versions of SWIG, use
 832the <tt>%constant</tt> directive instead.  For example:
 833</p>
 834
 835<div class="code">
 836<pre>
 837%constant double PI = 3.14159;
 838</pre>
 839</div>
 840
 841<p>
 842or
 843</p>
 844
 845<div class="code">
 846<pre>
 847#ifdef SWIG
 848#define const %constant
 849#endif
 850const double foo = 3.4;
 851const double bar = 23.4;
 852const int    spam = 42;
 853#ifdef SWIG
 854#undef const
 855#endif
 856...
 857
 858</pre>
 859</div>
 860
 861<H3><a name="SWIG_nn14"></a>5.2.5 A cautionary tale of <tt>char *</tt></H3>
 862
 863
 864<p>
 865Before going any further, there is one bit of caution involving
 866<tt>char *</tt> that must now be mentioned.  When strings are passed
 867from a scripting language to a C <tt>char *</tt>, the pointer usually
 868points to string data stored inside the interpreter.  It is almost
 869always a really bad idea to modify this data.  Furthermore, some
 870languages may explicitly disallow it.  For instance, in Python,
 871strings are supposed be immutable.   If you violate this, you will probably
 872receive a vast amount of wrath when you unleash your module on the world.
 873</p>
 874
 875<p>
 876The primary source of problems are functions that might modify string data in place.
 877A classic example would be a function like this:
 878</p>
 879
 880<div class="code">
 881<pre>
 882char *strcat(char *s, const char *t)
 883</pre>
 884</div>
 885
 886<p>
 887Although SWIG will certainly generate a wrapper for this, its behavior
 888will be undefined.  In fact, it will probably cause your application
 889to crash with a segmentation fault or other memory related problem.
 890This is because <tt>s</tt> refers to some internal data in the target
 891language---data that you shouldn't be touching.
 892</p>
 893
 894<p>
 895The bottom line: don't rely on <tt>char *</tt> for anything other than read-only 
 896input values.   However, it must be noted that you could change the behavior of SWIG
 897using <a href="Typemaps.html#Typemaps">typemaps</a>.  
 898</p>
 899
 900<H2><a name="SWIG_nn15"></a>5.3 Pointers and complex objects</H2>
 901
 902
 903<p>
 904Most C programs manipulate arrays, structures, and other types of objects.  This section
 905discusses the handling of these datatypes.
 906</p>
 907
 908<H3><a name="SWIG_nn16"></a>5.3.1 Simple pointers</H3>
 909
 910
 911<p>
 912Pointers to primitive C datatypes such as </p>
 913
 914<div class="code"><pre>
 915int *
 916double ***
 917char **
 918</pre></div>
 919<p>
 920are fully supported by SWIG.  Rather than trying to convert the data being pointed to into a scripting
 921representation, SWIG simply encodes the pointer itself into a
 922representation that contains the actual value of the pointer and a type-tag.
 923Thus, the SWIG representation of the above
 924pointers (in Tcl), might look like this:</p>
 925
 926<div class="targetlang"><pre>
 927_10081012_p_int
 928_1008e124_ppp_double
 929_f8ac_pp_char
 930</pre></div>
 931
 932<p>
 933A NULL pointer is represented by the string "NULL" or the value 0
 934encoded with type information.</p>
 935
 936<p>
 937All pointers are treated as opaque objects by SWIG. Thus, a pointer
 938may be returned by a function and passed around to other C functions
 939as needed.  For all practical purposes, the scripting language
 940interface works in exactly the same way as you would use the
 941pointer in a C program.  The only difference is that there is no mechanism for
 942dereferencing the pointer since this would require the target language
 943to understand the memory layout of the underlying object.
 944</p>
 945
 946<p>
 947The scripting language representation of a pointer value should never be
 948manipulated directly.   Even though the values shown look like hexadecimal
 949addresses, the numbers used may differ from the actual machine address (e.g.,
 950on little-endian machines, the digits may appear in reverse order).
 951Furthermore, SWIG does not
 952normally map pointers into high-level objects such as associative
 953arrays or lists (for example, converting an
 954<tt>int *</tt> into an list of integers). There are several reasons
 955why SWIG does not do this:</p>
 956
 957<ul>
 958<li>There is not enough information in a C declaration to properly map
 959pointers into higher level constructs. For example, an <tt>int *</tt>
 960may indeed be an array of integers, but if it contains ten million
 961elements, converting it into a list object is probably a bad idea.
 962</li>
 963
 964<li>The underlying semantics associated with a pointer is not known
 965by SWIG.   For instance, an <tt>int *</tt> might not be an array at all--perhaps it
 966is an output value!
 967</li>
 968
 969<li>By handling all pointers in a consistent manner, the implementation of SWIG is greatly
 970simplified and less prone to error.
 971</li>
 972</ul>
 973
 974<H3><a name="SWIG_nn17"></a>5.3.2 Run time pointer type checking</H3>
 975
 976
 977<p>
 978By allowing pointers to be manipulated from a scripting language, extension modules
 979effectively bypass compile-time type checking in the C/C++
 980compiler.  To prevent errors, a type signature is encoded into all
 981pointer values and is used to perform run-time type checking.  This
 982type-checking process is an integral part of SWIG and can not be
 983disabled or modified without using typemaps (described in later
 984chapters).
 985</p>
 986
 987<p>
 988Like C, <tt>void *</tt> matches any kind of pointer.  Furthermore,
 989<tt>NULL</tt> pointers can be passed to any function that expects to
 990receive a pointer.  Although this has the potential to cause a crash,
 991<tt>NULL</tt> pointers are also sometimes used
 992as sentinel values or to denote a missing/empty value.  Therefore,
 993SWIG leaves NULL pointer checking up to the application.
 994</p>
 995
 996<H3><a name="SWIG_nn18"></a>5.3.3 Derived types, structs, and classes</H3>
 997
 998
 999<p>
1000For everything else (structs, classes, arrays, etc...) SWIG applies a
1001very simple rule :</p>
1002
1003<center>
1004<b>Everything else is a pointer</b>
1005</center>
1006
1007<p>
1008In other words, SWIG manipulates everything else by reference. This
1009model makes sense because most C/C++ programs make heavy use of
1010pointers and SWIG can use the type-checked pointer mechanism already
1011present for handling pointers to basic datatypes.</p>
1012
1013<p>
1014Although this probably sounds complicated, it's really quite
1015simple. Suppose you have an interface file like this :</p>
1016
1017<div class="code"><pre>
1018%module fileio
1019FILE *fopen(char *, char *);
1020int fclose(FILE *);
1021unsigned fread(void *ptr, unsigned size, unsigned nobj, FILE *);
1022unsigned fwrite(void *ptr, unsigned size, unsigned nobj, FILE *);
1023void *malloc(int nbytes);
1024void free(void *);
1025
1026</pre></div>
1027
1028<p>
1029In this file, SWIG doesn't know what a <tt>FILE</tt> is, but since it's used
1030as a pointer, so it doesn't really matter what it is. If you wrapped
1031this module into Python, you can use the functions just like you
1032expect :</p>
1033
1034<div class="targetlang"><pre>
1035# Copy a file 
1036def filecopy(source,target):
1037	f1 = fopen(source,"r")
1038	f2 = fopen(target,"w")
1039	buffer = malloc(8192)
1040	nbytes = fread(buffer,8192,1,f1)
1041	while (nbytes &gt; 0):
1042		fwrite(buffer,8192,1,f2)
1043		nbytes = fread(buffer,8192,1,f1)
1044	free(buffer)
1045
1046</pre></div>
1047
1048<p>
1049In this case <tt>f1</tt>,<tt> f2</tt>, and <tt>buffer</tt> are all
1050opaque objects containing C pointers. It doesn't matter what value
1051they contain--our program works just fine without this knowledge.</p>
1052
1053<H3><a name="SWIG_nn19"></a>5.3.4 Undefined datatypes</H3>
1054
1055
1056<p>
1057When SWIG encounters an undeclared datatype, it automatically assumes
1058that it is a structure or class. For example, suppose the following
1059function appeared in a SWIG input file:</p>
1060
1061<div class="code"><pre>
1062void matrix_multiply(Matrix *a, Matrix *b, Matrix *c);
1063</pre></div>
1064
1065<p>
1066SWIG has no idea what a "<tt>Matrix</tt>" is.  However, it is obviously
1067a pointer to something so SWIG generates a wrapper using its generic pointer
1068handling code. 
1069</p>
1070
1071<p>
1072Unlike C or C++, SWIG does not actually care whether <tt>Matrix</tt>
1073has been previously defined in the interface file or not.  This
1074allows SWIG to generate interfaces from
1075only partial or limited information. In some cases, you may not care
1076what a <tt>Matrix</tt> really is as long as you can pass an opaque reference to
1077one around in the scripting language interface.
1078</p>
1079
1080<p>
1081An important detail to mention is that SWIG will gladly generate
1082wrappers for an interface when there are unspecified type names.
1083However, <b>all unspecified types are internally handled as pointers
1084to structures or classes!</b> For example, consider the following declaration:
1085</p>
1086
1087<div class="code">
1088<pre>
1089void foo(size_t num);
1090</pre>
1091</div>
1092
1093<p>
1094If <tt>size_t</tt> is undeclared, SWIG generates wrappers
1095that expect to receive a type of <tt>size_t *</tt> (this mapping is described shortly).
1096As a result, the scripting interface might behave strangely.  For example:
1097</p>
1098
1099<div class="code">
1100<pre>
1101foo(40);
1102TypeError: expected a _p_size_t.
1103</pre>
1104</div>
1105
1106<p>
1107The only way to fix this problem is to make sure you properly declare type names using
1108<tt>typedef</tt>.
1109</p>
1110
1111<!-- We might want to add an error reporting flag to swig -->
1112
1113<H3><a name="SWIG_nn20"></a>5.3.5 Typedef</H3>
1114
1115
1116<p>
1117Like C, <tt>typedef</tt> can be used to define new type names in SWIG. For example:
1118</p>
1119
1120<div class="code"><pre>
1121typedef unsigned int size_t;
1122</pre></div>
1123
1124<p>
1125<tt>typedef</tt> definitions appearing in a SWIG interface
1126are not propagated to the generated wrapper code.  Therefore, they
1127either need to be defined in an included header file or placed in the
1128declarations section like this:
1129</p>
1130
1131<div class="code">
1132<pre>
1133%{
1134/* Include in the generated wrapper file */
1135typedef unsigned int size_t;
1136%}
1137/* Tell SWIG about it */
1138typedef unsigned int size_t;
1139</pre>
1140</div>
1141
1142<p>
1143or
1144</p>
1145
1146<div class="code">
1147<pre>
1148%inline %{
1149typedef unsigned int size_t;
1150%}
1151</pre>
1152</div>
1153
1154<p>
1155In certain cases, you might be able to include other header files to collect type information.
1156For example:
1157</p>
1158
1159<div class="code">
1160<pre>
1161%module example
1162%import "sys/types.h"
1163</pre>
1164</div>
1165
1166<p>
1167In this case, you might run SWIG as follows:
1168</p>
1169
1170<div class="shell">
1171<pre>
1172$ swig -I/usr/include -includeall example.i
1173</pre>
1174</div>
1175
1176<p>
1177It should be noted that your mileage will vary greatly here.
1178System headers are notoriously complicated and may rely upon a variety
1179of non-standard C coding extensions (e.g., such as special directives
1180to GCC).  Unless you exactly specify the right include directories and
1181preprocessor symbols, this may not work correctly (you will have to
1182experiment).
1183</p>
1184
1185<p>
1186SWIG tracks <tt>typedef</tt> declarations and uses this information
1187for run-time type checking. For instance, if you use the above <tt>typedef</tt> and
1188had the following function declaration:
1189</p>
1190
1191<div class="code">
1192<pre>
1193void foo(unsigned int *ptr);
1194</pre>
1195</div>
1196
1197<p>
1198The corresponding wrapper function will accept arguments of
1199type <tt>unsigned int *</tt> or <tt>size_t *</tt>.
1200</p>
1201
1202<H2><a name="SWIG_nn21"></a>5.4 Other Practicalities</H2>
1203
1204
1205<p>
1206So far, this chapter has presented almost everything you need to know to use SWIG
1207for simple interfaces. However, some C programs use idioms that are somewhat
1208more difficult to map to a scripting language interface.  This section describes
1209some of these issues.
1210</p>
1211
1212<H3><a name="SWIG_nn22"></a>5.4.1 Passing structures by value</H3>
1213
1214
1215<p>
1216Sometimes a C function takes structure parameters that are passed
1217by value.  For example, consider the following function:
1218</p>
1219
1220<div class="code"><pre>
1221double dot_product(Vector a, Vector b);
1222</pre></div>
1223
1224<p>
1225To deal with this, SWIG transforms the function to use pointers by
1226creating a wrapper equivalent to the following:
1227</p>
1228
1229<div class="code"><pre>
1230double wrap_dot_product(Vector *a, Vector *b) {
1231    Vector x = *a;
1232    Vector y = *b;
1233    return dot_product(x,y);
1234}
1235</pre></div>
1236
1237<p>
1238In the target language, the <tt>dot_product()</tt> function now accepts pointers
1239to Vectors instead of Vectors.  For the most part, this transformation
1240is transparent so you might not notice.
1241</p>
1242
1243<H3><a name="SWIG_nn23"></a>5.4.2 Return by value</H3>
1244
1245
1246<p>
1247C functions that return structures or classes datatypes by value are more difficult
1248to handle. Consider the following function:</p>
1249
1250<div class="code"><pre>
1251Vector cross_product(Vector v1, Vector v2);
1252</pre></div>
1253
1254<p>
1255This function wants to return <tt>Vector</tt>, but SWIG only really supports
1256pointers.  As a result, SWIG creates a wrapper like this:
1257</p>
1258
1259<div class="code"><pre>
1260Vector *wrap_cross_product(Vector *v1, Vector *v2) {
1261        Vector x = *v1;
1262        Vector y = *v2;
1263        Vector *result;
1264        result = (Vector *) malloc(sizeof(Vector));
1265        *(result) = cross(x,y);
1266        return result;
1267}
1268</pre></div>
1269
1270<p>
1271or if SWIG was run with the <tt>-c++</tt> option:</p>
1272
1273<div class="code"><pre>
1274Vector *wrap_cross(Vector *v1, Vector *v2) {
1275        Vector x = *v1;
1276        Vector y = *v2;
1277        Vector *result = new Vector(cross(x,y)); // Uses default copy constructor
1278        return result;
1279}
1280</pre></div>
1281
1282<p>
1283In both cases, SWIG allocates a new object and returns a reference to it. It
1284is up to the user to delete the returned object when it is no longer
1285in use. Clearly, this will leak memory if you are unaware of the implicit
1286memory allocation and don't take steps to free the result.  That said, it should be
1287noted that some language modules can now automatically track newly created objects and
1288reclaim memory for you.  Consult the documentation for each language module for more details.
1289</p>
1290
1291<p>
1292It should also be noted that the handling of pass/return by value in
1293C++ has some special cases.  For example, the above code fragments
1294don't work correctly if <tt>Vector</tt> doesn't define a default
1295constructor.  The section on SWIG and C++ has more information about this case.
1296</p>
1297
1298<H3><a name="SWIG_nn24"></a>5.4.3 Linking to structure variables</H3>
1299
1300
1301<p>
1302When global variables or class members involving structures are
1303encountered, SWIG handles them as pointers. For example, a global
1304variable like this</p>
1305
1306<div class="code"><pre>
1307Vector unit_i;
1308</pre></div>
1309
1310<p>
1311gets mapped to an underlying pair of set/get functions like this :</p>
1312
1313<div class="code"><pre>
1314Vector *unit_i_get() {
1315	return &amp;unit_i;
1316}
1317void unit_i_set(Vector *value) {
1318	unit_i = *value;
1319}
1320</pre></div>
1321
1322<p>
1323Again some caution is in order. A global variable created in this
1324manner will show up as a pointer in the target scripting language. It
1325would be an extremely bad idea to free or destroy such a pointer.    Also,
1326C++ classes must supply a properly defined copy constructor in order for
1327assignment to work correctly.
1328</p>
1329
1330<H3><a name="SWIG_nn25"></a>5.4.4 Linking to <tt>char *</tt></H3>
1331
1332
1333<p>
1334When a global variable of type <tt>char *</tt> appears, SWIG uses <tt>malloc()</tt> or
1335<tt>new</tt> to allocate memory for the new value.   Specifically, if you have a variable
1336like this
1337</p>
1338
1339<div class="code">
1340<pre>
1341char *foo;
1342</pre>
1343</div>
1344
1345<p>
1346SWIG generates the following code:
1347</p>
1348
1349<div class="code">
1350<pre>
1351/* C mode */
1352void foo_set(char *value) {
1353   if (foo) free(foo);
1354   foo = (char *) malloc(strlen(value)+1);
1355   strcpy(foo,value);
1356}
1357
1358/* C++ mode.  When -c++ option is used */
1359void foo_set(char *value) {
1360   if (foo) delete [] foo;
1361   foo = new char[strlen(value)+1];
1362   strcpy(foo,value);
1363}
1364</pre>
1365</div>
1366
1367<p>
1368If this is not the behavior that you want, consider making the variable read-only using the
1369<tt>%immutable</tt> directive.  Alternatively, you might write a short assist-function to set the value
1370exactly like you want.  For example:
1371</p>
1372
1373<div class="code">
1374<pre>
1375%inline %{
1376  void set_foo(char *value) {
1377       strncpy(foo,value, 50);
1378   }
1379%}
1380</pre>
1381</div>
1382
1383<p>
1384Note: If you write an assist function like this, you will have to call
1385it as a function from the target scripting language (it does not work
1386like a variable).  For example, in Python you will have to write:
1387</p>
1388
1389<div class="targetlang">
1390<pre>
1391&gt;&gt;&gt; set_foo("Hello World")
1392</pre>
1393</div>
1394
1395<p>
1396A common mistake with <tt>char *</tt> variables is to link to a variable declared like this:
1397</p>
1398
1399<div class="code">
1400<pre>
1401char *VERSION = "1.0";
1402</pre>
1403</div>
1404
1405<p>
1406In this case, the variable will be readable, but any attempt to change
1407the value results in a segmentation or general protection fault.  This
1408is due to the fact that SWIG is trying to release the old value using
1409<tt>free</tt> or <tt>delete</tt> when the string literal value currently assigned to the variable wasn't
1410allocated using <tt>malloc()</tt> or <tt>new</tt>.
1411To fix this behavior, you can
1412either mark the variable as read-only, write a typemap (as described in Chapter 6), 
1413or write a special set function as shown.  Another alternative is to declare the
1414variable as an array:
1415</p>
1416
1417<div class="code">
1418<pre>
1419char VERSION[64] = "1.0";
1420</pre>
1421</div>
1422
1423<p>
1424When variables of type <tt>const char *</tt> are declared, SWIG still generates functions for setting and
1425getting the value.  However, the default behavior does <em>not</em> release the previous contents (resulting in
1426a possible memory leak).  In fact, you may get a warning message such as this when wrapping such a variable:
1427</p>
1428
1429<div class="shell">
1430<pre>
1431example.i:20. Typemap warning. Setting const char * variable may leak memory
1432</pre>
1433</div>
1434
1435<p>
1436The reason for this behavior is that <tt>const char *</tt> variables are often used to point to string literals.
1437For example:
1438</p>
1439
1440<div class="code">
1441<pre>
1442const char *foo = "Hello World\n";
1443</pre>
1444</div>
1445
1446<p>
1447Therefore, it's a really bad idea to call <tt>free()</tt> on such a
1448pointer.  On the other hand, it <em>is</em> legal to change the
1449pointer to point to some other value.  When setting a variable of this
1450type, SWIG allocates a new string (using malloc or new) and changes
1451the pointer to point to the new value.  However, repeated
1452modifications of the value will result in a memory leak since the old
1453value is not released. 
1454</p>
1455
1456
1457
1458
1459<H3><a name="SWIG_nn26"></a>5.4.5 Arrays</H3>
1460
1461
1462<p>
1463Arrays are fully supported by SWIG, but they are always handled as pointers instead
1464of mapping them to a special array object or list in the target language.  Thus, the
1465following declarations :</p>
1466
1467<div class="code"><pre>
1468int foobar(int a[40]);
1469void grok(char *argv[]);
1470void transpose(double a[20][20]);
1471</pre></div>
1472
1473<p>
1474are processed as if they were really declared like this:
1475</p>
1476
1477<div class="code"><pre>
1478int foobar(int *a);
1479void grok(char **argv);
1480void transpose(double (*a)[20]);
1481</pre></div>
1482
1483<p>
1484Like C, SWIG does not perform array bounds checking.  
1485It is up to the
1486user to make sure the pointer points a suitably allocated region of memory. 
1487</p>
1488
1489<p>
1490Multi-dimensional arrays are transformed into a pointer to an array of one less
1491dimension.  For example:
1492</p>
1493
1494<div class="code">
1495<pre>
1496int [10];         // Maps to int *
1497int [10][20];     // Maps to int (*)[20]
1498int [10][20][30]; // Maps to int (*)[20][30]
1499</pre>
1500</div>
1501
1502<p>
1503It is important to note that in the C type system, a multidimensional
1504array <tt>a[][]</tt> is <b>NOT</b> equivalent to a single pointer
1505<tt>*a</tt> or a double pointer such as <tt>**a</tt>.  Instead, a
1506pointer to an array is used (as shown above) where the actual value of
1507the pointer is the starting memory location of the array.  The
1508reader is strongly advised to dust off their C book and re-read the
1509section on arrays before using them with SWIG.
1510</p>
1511
1512<p>
1513Array variables are supported, but are read-only by default.  For example:
1514</p>
1515
1516<div class="code">
1517<pre>
1518int   a[100][200];
1519</pre>
1520</div>
1521
1522<p>
1523In this case, reading the variable 'a' returns a pointer of type <tt>int (*)[200]</tt>
1524that points to the first element of the array <tt>&amp;a[0][0]</tt>.  Trying to modify 'a' results
1525in an error.  This is because SWIG does not know how to copy data from the target
1526language into the array.   To work around this limitation, you may want to write
1527a few simple assist functions like this:
1528</p>
1529
1530<div class="code">
1531<pre>
1532%inline %{
1533void a_set(int i, int j, int val) {
1534   a[i][j] = val;
1535}
1536int a_get(int i, int j) {
1537   return a[i][j];
1538}
1539%}
1540</pre>
1541</div>
1542
1543<p>
1544To dynamically create arrays of various sizes and shapes, it may be useful to write
1545some helper functions in your interface.  For example:
1546</p>
1547
1548<div class="code">
1549<pre>
1550// Some array helpers
1551%inline %{
1552  /* Create any sort of [size] array */
1553  int *int_array(int size) {
1554     return (int *) malloc(size*sizeof(int));
1555  }
1556  /* Create a two-dimension array [size][10] */
1557  int (*int_array_10(int size))[10] {
1558     return (int (*)[10]) malloc(size*10*sizeof(int));
1559  }
1560%}
1561</pre>
1562</div>
1563
1564<p>
1565Arrays of <tt>char</tt> are handled as a special case by SWIG.  In this case, strings in the
1566target language can be stored in the array.  For example, if you have a declaration like this,
1567</p>
1568
1569<div class="code">
1570<pre>
1571char pathname[256];
1572</pre>
1573</div>
1574
1575<p>
1576SWIG geneā€¦

Large files files are truncated, but you can click here to view the full file