PageRenderTime 86ms CodeModel.GetById 16ms app.highlight 55ms RepoModel.GetById 1ms app.codeStats 0ms

/trunk/Doc/Manual/Perl5.html

#
HTML | 2537 lines | 2288 code | 247 blank | 2 comment | 0 complexity | 3824fc5a2d2915f5fbebfbbf64c1e40c MD5 | raw file
   1<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
   2<html>
   3<head>
   4<title>SWIG and Perl5</title>
   5<link rel="stylesheet" type="text/css" href="style.css">
   6</head>
   7
   8<body bgcolor="#ffffff">
   9<H1><a name="Perl5"></a>31 SWIG and Perl5</H1>
  10<!-- INDEX -->
  11<div class="sectiontoc">
  12<ul>
  13<li><a href="#Perl5_nn2">Overview</a>
  14<li><a href="#Perl5_nn3">Preliminaries</a>
  15<ul>
  16<li><a href="#Perl5_nn4">Getting the right header files</a>
  17<li><a href="#Perl5_nn5">Compiling a dynamic module</a>
  18<li><a href="#Perl5_nn6">Building a dynamic module with MakeMaker</a>
  19<li><a href="#Perl5_nn7">Building a static version of Perl</a>
  20<li><a href="#Perl5_nn8">Using the module</a>
  21<li><a href="#Perl5_nn9">Compilation problems and compiling with C++</a>
  22<li><a href="#Perl5_nn10">Compiling for 64-bit platforms</a>
  23</ul>
  24<li><a href="#Perl5_nn11">Building Perl Extensions under Windows</a>
  25<ul>
  26<li><a href="#Perl5_nn12">Running SWIG from Developer Studio</a>
  27<li><a href="#Perl5_nn13">Using other compilers</a>
  28</ul>
  29<li><a href="#Perl5_nn14">The low-level interface</a>
  30<ul>
  31<li><a href="#Perl5_nn15">Functions</a>
  32<li><a href="#Perl5_nn16">Global variables</a>
  33<li><a href="#Perl5_nn17">Constants</a>
  34<li><a href="#Perl5_nn18">Pointers</a>
  35<li><a href="#Perl5_nn19">Structures</a>
  36<li><a href="#Perl5_nn20">C++ classes</a>
  37<li><a href="#Perl5_nn21">C++ classes and type-checking</a>
  38<li><a href="#Perl5_nn22">C++ overloaded functions</a>
  39<li><a href="#Perl5_nn23">Operators</a>
  40<li><a href="#Perl5_nn24">Modules and packages</a>
  41</ul>
  42<li><a href="#Perl5_nn25">Input and output parameters</a>
  43<li><a href="#Perl5_nn26">Exception handling</a>
  44<li><a href="#Perl5_nn27">Remapping datatypes with typemaps</a>
  45<ul>
  46<li><a href="#Perl5_nn28">A simple typemap example</a>
  47<li><a href="#Perl5_nn29">Perl5 typemaps</a>
  48<li><a href="#Perl5_nn30">Typemap variables</a>
  49<li><a href="#Perl5_nn31">Useful functions</a>
  50</ul>
  51<li><a href="#Perl5_nn32">Typemap Examples</a>
  52<ul>
  53<li><a href="#Perl5_nn33">Converting a Perl5 array to a char **</a>
  54<li><a href="#Perl5_nn34">Return values</a>
  55<li><a href="#Perl5_nn35">Returning values from arguments</a>
  56<li><a href="#Perl5_nn36">Accessing array structure members</a>
  57<li><a href="#Perl5_nn37">Turning Perl references into C pointers</a>
  58<li><a href="#Perl5_nn38">Pointer handling</a>
  59</ul>
  60<li><a href="#Perl5_nn39">Proxy classes</a>
  61<ul>
  62<li><a href="#Perl5_nn40">Preliminaries</a>
  63<li><a href="#Perl5_nn41">Structure and class wrappers</a>
  64<li><a href="#Perl5_nn42">Object Ownership</a>
  65<li><a href="#Perl5_nn43">Nested Objects</a>
  66<li><a href="#Perl5_nn44">Proxy Functions</a>
  67<li><a href="#Perl5_nn45">Inheritance</a>
  68<li><a href="#Perl5_nn46">Modifying the proxy methods</a>
  69</ul>
  70<li><a href="#Perl5_nn47">Adding additional Perl code</a>
  71</ul>
  72</div>
  73<!-- INDEX -->
  74
  75
  76
  77<p>
  78<b>Caution: This chapter is under repair!</b>
  79</p>
  80
  81<p>
  82This chapter describes SWIG's support of Perl5. Although the Perl5
  83module is one of the earliest SWIG modules, it has continued to evolve
  84and has been improved greatly with the help of SWIG users. For the
  85best results, it is recommended that SWIG be used with Perl 5.8 or
  86later. We're no longer testing regularly with older versions, but
  87Perl 5.6 seems to mostly work, while older versions don't.
  88</p>
  89
  90<H2><a name="Perl5_nn2"></a>31.1 Overview</H2>
  91
  92
  93<p>
  94To build Perl extension modules, SWIG uses a layered approach.  At
  95the lowest level, simple procedural wrappers are generated for
  96functions, classes, methods, and other declarations in the input file.
  97Then, for structures and classes, an optional collection of Perl
  98proxy classes can be generated in order to provide a more natural object oriented Perl
  99interface. These proxy classes simply build upon the low-level interface.
 100</p>
 101
 102<p>
 103In describing the Perl interface, this chapter begins by covering the
 104essentials. First, the problem of configuration, compiling,
 105and installing Perl modules is discussed.  Next, the low-level
 106procedural interface is presented.  Finally, proxy classes are
 107described.  Advanced customization features, typemaps, and other
 108options are found near the end of the chapter.
 109</p>
 110
 111<H2><a name="Perl5_nn3"></a>31.2 Preliminaries</H2>
 112
 113
 114<p>
 115To build a Perl5 module, run SWIG using the <tt>-perl</tt> option as
 116follows:
 117</p>
 118
 119<div class="code"><pre>
 120swig -perl example.i
 121
 122</pre></div>
 123
 124<p>
 125This produces two files. The first file, <tt>example_wrap.c</tt>
 126contains all of the C code needed to build a Perl5 module. The second
 127file, <tt>example.pm</tt> contains supporting Perl code needed to
 128properly load the module.
 129</p>
 130
 131<p>
 132To build the module, you will need to compile the file
 133<tt>example_wrap.c</tt> and link it with the rest of your program.
 134</p>
 135
 136<H3><a name="Perl5_nn4"></a>31.2.1 Getting the right header files</H3>
 137
 138
 139<p>
 140In order to compile, SWIG extensions need the following Perl5 header files:</p>
 141
 142<div class="code"><pre>
 143#include "Extern.h"
 144#include "perl.h"
 145#include "XSUB.h"
 146</pre></div>
 147
 148<p>
 149These are typically located in a directory like this</p>
 150
 151<div class="code"><pre>
 152/usr/lib/perl/5.14/CORE
 153</pre></div>
 154
 155<p>
 156The SWIG configuration script automatically tries to locate this directory so
 157that it can compile examples.  However, if you need to find out where the directory is
 158located, an easy way to find out is to ask Perl itself:
 159</p>
 160
 161<div class="code">
 162<pre>
 163$ perl -e 'use Config; print "$Config{archlib}\n";'
 164/usr/lib/perl/5.14
 165</pre>
 166</div>
 167
 168<H3><a name="Perl5_nn5"></a>31.2.2 Compiling a dynamic module</H3>
 169
 170
 171<p>
 172The preferred approach to building an extension module is to compile it into
 173a shared object file or DLL.   To do this, you will need to compile your program
 174using commands like this (shown for Linux):
 175</p>
 176
 177<div class="code"><pre>
 178$ swig -perl example.i
 179$ gcc -fPIC example.c
 180$ gcc -fPIC -c example_wrap.c -I/usr/lib/perl/5.14/CORE -Dbool=char
 181$ gcc -shared example.o example_wrap.o -o example.so
 182</pre></div>
 183
 184<p>
 185The exact compiler options vary from platform to platform. 
 186SWIG tries to guess the right options when it is installed.  Therefore, 
 187you may want to start with one of the examples in the <tt>SWIG/Examples/perl5</tt> 
 188directory.   If that doesn't work, you will need to read the man-pages for
 189your compiler and linker to get the right set of options.  You might also
 190check the <a href="http://www.dabeaz.com/cgi-bin/wiki.pl">SWIG Wiki</a> for
 191additional information.
 192</p>
 193
 194<p>
 195When linking the module, the name of the shared object file must match the module name used in
 196the SWIG interface file. If you used `<tt>%module example</tt>', then
 197the target should be named `<tt>example.so</tt>',
 198`<tt>example.sl</tt>', or the appropriate dynamic module name on your system.
 199</p>
 200
 201<H3><a name="Perl5_nn6"></a>31.2.3 Building a dynamic module with MakeMaker</H3>
 202
 203
 204<p>
 205It is also possible to use Perl to build dynamically loadable modules
 206for you using the MakeMaker utility.  To do this, write a Perl
 207script such as the following:</p>
 208
 209<div class="targetlang"><pre>
 210# File : Makefile.PL
 211use ExtUtils::MakeMaker;
 212WriteMakefile(
 213	`NAME'    =&gt; `example',                  # Name of package
 214	`LIBS'    =&gt; [`-lm'],                    # Name of custom libraries
 215	`OBJECT'  =&gt; `example.o example_wrap.o'  # Object files
 216);
 217
 218</pre></div>
 219
 220<p>
 221Now, to build a module, simply follow these steps:</p>
 222
 223<div class="code"><pre>
 224$ perl Makefile.PL
 225$ make
 226$ make install
 227</pre></div>
 228
 229<p>
 230If you are planning to distribute a SWIG-generated module, this is
 231the preferred approach to compilation.  More information about MakeMaker can be
 232found in "Programming Perl, 2nd ed." by Larry Wall, Tom Christiansen,
 233and Randal Schwartz.</p>
 234
 235<H3><a name="Perl5_nn7"></a>31.2.4 Building a static version of Perl</H3>
 236
 237
 238<p>
 239If you machine does not support dynamic loading or if you've tried to
 240use it without success, you can build a new version of the Perl
 241interpreter with your SWIG extensions added to it. To build a static
 242extension, you first need to invoke SWIG as follows:</p>
 243
 244<div class="code"><pre>
 245$ swig -perl -static example.i
 246</pre></div>
 247
 248<p>
 249By default SWIG includes code for dynamic loading, but the
 250<tt>-static</tt> option takes it out.</p>
 251
 252<p>
 253Next, you will need to supply a <tt>main()</tt> function that
 254initializes your extension and starts the Perl interpreter. While,
 255this may sound daunting, SWIG can do this for you automatically as
 256follows:</p>
 257
 258<div class="targetlang"><pre>
 259%module example
 260
 261%inline %{
 262extern double My_variable;
 263extern int fact(int);
 264%}
 265
 266// Include code for rebuilding Perl
 267%include &lt;perlmain.i&gt;
 268</pre></div>
 269
 270<p>
 271The same thing can be accomplished by running SWIG as follows:</p>
 272
 273<div class="code"><pre>
 274$ swig -perl -static -lperlmain.i example.i
 275</pre></div>
 276
 277<p>
 278The <tt>perlmain.i</tt> file inserts Perl's <tt>main()</tt> function
 279into the wrapper code and automatically initializes the SWIG generated
 280module. If you just want to make a quick a dirty module, this may be
 281the easiest way. By default, the <tt>perlmain.i</tt> code does not
 282initialize any other Perl extensions. If you need to use other
 283packages, you will need to modify it appropriately. You can do this by
 284just copying <tt>perlmain.i</tt> out of the SWIG library, placing it
 285in your own directory, and modifying it to suit your purposes.</p>
 286
 287<p>
 288To build your new Perl executable, follow the exact same procedure as
 289for a dynamic module, but change the link line to something like this:
 290</p>
 291
 292<div class="code"><pre>
 293$ gcc example.o example_wrap.o -L/usr/lib/perl/5.14/CORE \
 294	-lperl -lsocket -lnsl -lm -o myperl
 295</pre></div>
 296
 297<p>
 298This will produce a new version of Perl called <tt>myperl</tt>. It
 299should be functionality identical to Perl with your C/C++ extension
 300added to it.  Depending on your machine, you may need to link with
 301additional libraries such as <tt>-lsocket, -lnsl, -ldl</tt>, etc.
 302</p>
 303
 304<H3><a name="Perl5_nn8"></a>31.2.5 Using the module</H3>
 305
 306
 307<p>
 308To use the module, simply use the Perl <tt>use</tt> statement.  If
 309all goes well, you will be able to do this:
 310</p>
 311
 312<div class="targetlang"><pre>
 313$ perl
 314use example;
 315print example::fact(4),"\n";
 31624
 317</pre></div>
 318
 319<p>
 320A common error received by first-time users is the following:
 321</p>
 322
 323<div class="targetlang">
 324<pre>
 325use example;
 326Can't locate example.pm in @INC (@INC contains: /etc/perl /usr/local/lib/perl/5.14.2 /usr/local/share/perl/5.14.2 /usr/lib/perl5 /usr/share/perl5 /usr/lib/perl/5.14 /usr/share/perl/5.14 /usr/local/lib/site_perl .) at - line 1.
 327BEGIN failed--compilation aborted at - line 1.
 328</pre>
 329</div>
 330
 331<p>
 332This error is almost caused when the name of the shared object file you created doesn't match the module name
 333you specified with the <tt>%module</tt> directive.  
 334</p>
 335
 336<p>
 337A somewhat related, but slightly different error is this:
 338</p>
 339
 340<div class="targetlang">
 341<pre>
 342use example;
 343Can't find 'boot_example' symbol in ./example.so
 344 at - line 1
 345BEGIN failed--compilation aborted at - line 1.
 346</pre>
 347</div>
 348
 349<p>
 350This error is generated because Perl can't locate the module bootstrap function in the
 351SWIG extension module.  This could be caused by a mismatch between the module name and the shared library name.
 352However, another possible cause is forgetting to link the SWIG-generated wrapper code with the rest
 353of your application when you linked the extension module.
 354</p>
 355
 356<p>
 357Another common error is the following:
 358</p>
 359
 360<div class="targetlang">
 361<pre>
 362use example;
 363Can't load './example.so' for module example: ./example.so: 
 364undefined symbol: Foo at /usr/lib/perl/5.14/i386-linux/DynaLoader.pm line 169.
 365
 366 at - line 1
 367BEGIN failed--compilation aborted at - line 1.
 368</pre>
 369</div>
 370
 371<p>
 372This error usually indicates that you forgot to include some object
 373files or libraries in the linking of the shared library file.  Make
 374sure you compile both the SWIG wrapper file and your original program
 375into a shared library file.  Make sure you pass all of the required libraries
 376to the linker.  
 377</p>
 378
 379<p>
 380Sometimes unresolved symbols occur because a wrapper has been created
 381for a function that doesn't actually exist in a library.  This usually
 382occurs when a header file includes a declaration for a function that
 383was never actually implemented or it was removed from a library
 384without updating the header file.  To fix this, you can either edit
 385the SWIG input file to remove the offending declaration or you can use
 386the <tt>%ignore</tt> directive to ignore the declaration.  Better yet,
 387update the header file so that it doesn't have an undefined declaration.
 388</p>
 389
 390<p>
 391Finally, suppose that your extension module is linked with another library like this:
 392</p>
 393
 394<div class="code">
 395<pre>
 396$ gcc -shared example.o example_wrap.o -L/home/beazley/projects/lib -lfoo \
 397      -o example.so
 398</pre>
 399</div>
 400
 401<p>
 402If the <tt>foo</tt> library is compiled as a shared library, you might get the following
 403error when you try to use your module:
 404</p>
 405
 406<div class="targetlang">
 407<pre>
 408use example;
 409Can't load './example.so' for module example: libfoo.so: cannot open shared object file: 
 410No such file or directory at /usr/lib/perl/5.14/i386-linux/DynaLoader.pm line 169.
 411
 412 at - line 1
 413BEGIN failed--compilation aborted at - line 1.
 414&gt;&gt;&gt;                 
 415</pre>
 416</div>
 417
 418<p>
 419This error is generated because the dynamic linker can't locate the
 420<tt>libfoo.so</tt> library.  When shared libraries are loaded, the
 421system normally only checks a few standard locations such as
 422<tt>/usr/lib</tt> and <tt>/usr/local/lib</tt>.   To get the loader to look in other
 423locations, there are several things you can do.  First, you can recompile your extension
 424module with extra path information. For example, on Linux you can do this:
 425</p>
 426
 427<div class="code">
 428<pre>
 429$ gcc -shared example.o example_wrap.o -L/home/beazley/projects/lib -lfoo \
 430      <b>-Xlinker -rpath /home/beazley/projects/lib \</b>
 431      -o example.so
 432</pre>
 433</div>
 434
 435<p>
 436Alternatively, you can set the <tt>LD_LIBRARY_PATH</tt> environment
 437variable to include the directory with your shared libraries.  If
 438setting <tt>LD_LIBRARY_PATH</tt>, be aware that setting this variable
 439can introduce a noticeable performance impact on all other
 440applications that you run.  To set it only for Perl, you might want
 441to do this instead:
 442</p>
 443
 444<div class="code">
 445<pre>
 446$ env LD_LIBRARY_PATH=/home/beazley/projects/lib perl
 447</pre>
 448</div>
 449
 450<p>
 451Finally, you can use a command such as <tt>ldconfig</tt> (Linux) or
 452<tt>crle</tt> (Solaris) to add additional search paths to the default
 453system configuration (this requires root access and you will need to
 454read the man pages).
 455</p>
 456
 457<H3><a name="Perl5_nn9"></a>31.2.6 Compilation problems and compiling with C++</H3>
 458
 459
 460<p>
 461Compilation of C++ extensions has traditionally been a tricky problem.
 462Since the Perl interpreter is written in C, you need to take steps to
 463make sure C++ is properly initialized and that modules are compiled
 464correctly.
 465</p>
 466
 467<p>
 468On most machines, C++ extension modules should be linked using the C++
 469compiler.  For example:
 470</p>
 471
 472<div class="code"><pre>
 473$ swig -c++ -perl example.i
 474$ g++ -fPIC -c example.cxx
 475$ g++ -fPIC -c example_wrap.cxx -I/usr/lib/perl/5.14/i386-linux/CORE
 476$ <b>g++ -shared example.o example_wrap.o -o example.so</b>
 477</pre></div>
 478
 479<p>
 480In addition to this, you may need to include additional library
 481files to make it work.  For example, if you are using the Sun C++ compiler on
 482Solaris, you often need to add an extra library <tt>-lCrun</tt> like this:
 483</p>
 484
 485<div class="code"><pre>
 486$ swig -c++ -perl example.i
 487$ CC -c example.cxx
 488$ CC -c example_wrap.cxx -I/usr/lib/perl/5.14/i386-linux/CORE
 489$ CC -shared example.o example_wrap.o -o example.so <b>-lCrun</b>
 490</pre></div>
 491
 492<p>
 493Of course, the names of the extra libraries are completely non-portable---you will 
 494probably need to do some experimentation.
 495</p>
 496
 497<p>
 498Another possible compile problem comes from recent versions of Perl (5.8.0) and the GNU tools.
 499If you see errors having to do with _crypt_struct, that means _GNU_SOURCE is not defined and
 500it needs to be.  So you should compile the wrapper like:
 501</p>
 502
 503<div class="code"><pre>
 504$ g++ -fPIC -c example_wrap.cxx -I/usr/lib/perl/5.8.0/CORE -D_GNU_SOURCE
 505</pre></div>
 506
 507<p>
 508-D_GNU_SOURCE is also included in the Perl ccflags, which can be found by running
 509</p>
 510
 511<div class="code"><pre>
 512$ perl -e 'use Config; print "$Config{ccflags}\n";'
 513</pre></div>
 514
 515<p>
 516So you could also compile the wrapper like
 517</p>
 518
 519<div class="code"><pre>
 520$ g++ -fPIC -c example_wrap.cxx -I/usr/lib/perl/5.8.0/CORE \
 521`perl -MConfig -e 'print $Config{ccflags}'`
 522</pre></div>
 523
 524<p>
 525Sometimes people have suggested that it is necessary to relink the
 526Perl interpreter using the C++ compiler to make C++ extension modules work.
 527In the experience of this author, this has never actually appeared to be
 528necessary on most platforms.   Relinking the interpreter with C++ really only includes the 
 529special run-time libraries described above---as long as you link your extension 
 530modules with these libraries, it should not be necessary to rebuild Perl.
 531</p>
 532
 533<p>
 534If you aren't entirely sure about the linking of a C++ extension, you
 535might look at an existing C++ program.  On many Unix machines, the
 536<tt>ldd</tt> command will list library dependencies.  This should give
 537you some clues about what you might have to include when you link your
 538extension module. For example, notice the first line of output here:
 539</p>
 540
 541<div class="code">
 542<pre>
 543$ ldd swig
 544        <b>libstdc++-libc6.1-1.so.2 =&gt; /usr/lib/libstdc++-libc6.1-1.so.2 (0x40019000)</b>
 545        libm.so.6 =&gt; /lib/libm.so.6 (0x4005b000)
 546        libc.so.6 =&gt; /lib/libc.so.6 (0x40077000)
 547        /lib/ld-linux.so.2 =&gt; /lib/ld-linux.so.2 (0x40000000)
 548$
 549</pre>
 550</div>
 551
 552<p>
 553If linking wasn't enough of a problem, another major complication of C++ is that it does not
 554define any sort of standard for binary linking of libraries.  This
 555means that C++ code compiled by different compilers will not link
 556together properly as libraries nor is the memory layout of classes and
 557data structures implemented in any kind of portable manner.  In a
 558monolithic C++ program, this problem may be unnoticed.  However, in Perl, it
 559is possible for different extension modules to be compiled with
 560different C++ compilers.  As long as these modules are self-contained,
 561this probably won't matter.  However, if these modules start sharing data,
 562you will need to take steps to avoid segmentation faults and other
 563erratic program behavior.   Also, be aware that certain C++ features, especially RTTI,
 564can behave strangely when working with multiple modules.
 565</p>
 566
 567<p>
 568It should be noted that you may get a lot of error messages
 569about the '<tt>bool</tt>' datatype when compiling a C++ Perl module. If
 570you experience this problem, you can try the following:</p>
 571
 572<ul>
 573<li>Use <tt>-DHAS_BOOL</tt> when compiling the SWIG wrapper code
 574<li>Or use <tt>-Dbool=char</tt> when compiling.
 575</ul>
 576
 577<p>
 578Finally, recent versions of Perl (5.8.0) have namespace conflict problems.  Perl defines a bunch
 579of short macros to make the Perl API function names shorter.  For example, in 
 580/usr/lib/perl/5.8.0/CORE/embed.h there is a line:
 581</p>
 582
 583<div class="code"><pre>
 584#define do_open Perl_do_open
 585</pre></div>
 586
 587<p>
 588The problem is, in the &lt;iostream&gt; header from GNU libstdc++v3 there is a private 
 589function named do_open.  If &lt;iostream&gt; is included after the perl headers, then
 590the Perl macro causes the iostream do_open to be renamed, which causes compile errors.
 591Hopefully in the future Perl will support a PERL_NO_SHORT_NAMES flag, but for now the 
 592only solution is to undef the macros that conflict.  Lib/perl5/noembed.h in the SWIG 
 593source has a list of macros that are known to conflict with either standard headers or
 594other headers.  But if you get macro type conflicts from other macros not included
 595in Lib/perl5/noembed.h while compiling the wrapper, you will
 596have to find the macro that conflicts and add an #undef into the .i file.  Please report
 597any conflicting macros you find to <a href="http://www.swig.org/mail.html">swig-user mailing list</a>.
 598</p>
 599
 600<H3><a name="Perl5_nn10"></a>31.2.7 Compiling for 64-bit platforms</H3>
 601
 602
 603<p>
 604On platforms that support 64-bit applications (Solaris, Irix, etc.),
 605special care is required when building extension modules.  On these
 606machines, 64-bit applications are compiled and linked using a different
 607set of compiler/linker options.  In addition, it is not generally possible to mix 
 60832-bit and 64-bit code together in the same application.
 609</p>
 610
 611<p>
 612To utilize 64-bits, the Perl executable will need to be recompiled
 613as a 64-bit application.  In addition, all libraries, wrapper code,
 614and every other part of your application will need to be compiled for
 61564-bits.  If you plan to use other third-party extension modules, they
 616will also have to be recompiled as 64-bit extensions.
 617</p>
 618
 619<p>
 620If you are wrapping commercial software for which you have no source
 621code, you will be forced to use the same linking standard as used by
 622that software.  This may prevent the use of 64-bit extensions.  It may
 623also introduce problems on platforms that support more than one
 624linking standard (e.g., -o32 and -n32 on Irix).
 625</p>
 626
 627<H2><a name="Perl5_nn11"></a>31.3 Building Perl Extensions under Windows</H2>
 628
 629
 630<p>
 631Building a SWIG extension to Perl under Windows is roughly
 632similar to the process used with Unix.  Normally, you will want to
 633produce a DLL that can be loaded into the Perl interpreter.  This
 634section assumes you are using SWIG with Microsoft Visual C++
 635although the procedure may be similar with other compilers.  
 636</p>
 637
 638<H3><a name="Perl5_nn12"></a>31.3.1 Running SWIG from Developer Studio</H3>
 639
 640
 641<p>
 642If you are developing your application within Microsoft developer
 643studio, SWIG can be invoked as a custom build option.  The process
 644roughly requires these steps:</p>
 645
 646<ul>
 647<li>Open up a new workspace and use the AppWizard to select a DLL
 648project.
 649
 650<li>Add both the SWIG interface file (the .i file), any supporting C
 651files, and the name of the wrapper file that will be created by SWIG
 652(ie. <tt>example_wrap.c</tt>).  Note: If using C++, choose a
 653different suffix for the wrapper file such as
 654<tt>example_wrap.cxx</tt>. Don't worry if the wrapper file doesn't
 655exist yet--Developer studio will keep a reference to it around.
 656
 657<li>Select the SWIG interface file and go to the settings menu.  Under
 658settings, select the "Custom Build" option.
 659
 660<li>Enter "SWIG" in the description field.
 661
 662<li>Enter "<tt>swig -perl5 -o $(ProjDir)\$(InputName)_wrap.cxx
 663$(InputPath)</tt>" in the "Build command(s) field"
 664
 665<li>Enter "<tt>$(ProjDir)\$(InputName)_wrap.c</tt>xx" in the "Output
 666files(s) field".
 667
 668<li>Next, select the settings for the entire project and go to
 669"C++:Preprocessor". Add the include directories for your Perl 5
 670installation under "Additional include directories".
 671
 672<li>Define the symbols WIN32 and MSWIN32 under preprocessor options.
 673If using the ActiveWare port, also define the symbol PERL_OBJECT.
 674Note that all extensions to the ActiveWare port must be compiled with
 675the C++ compiler since Perl has been encapsulated in a C++ class.
 676
 677<li>Finally, select the settings for the entire project and go to
 678"Link Options".  Add the Perl library file to your link libraries.
 679For example "perl.lib".  Also, set the name of the output file to
 680match the name of your Perl module (ie. example.dll).
 681
 682<li>Build your project.
 683</ul>
 684
 685<p>
 686Now, assuming you made it this far, SWIG will be automatically invoked when
 687you build your project.  Any changes made to the interface file will
 688result in SWIG being automatically invoked to produce a new version of
 689the wrapper file.  To run your new Perl extension, simply run Perl and
 690use the use command as normal. For example:
 691</p>
 692
 693<div class="targetlang"><pre>
 694DOS &gt; perl
 695use example;
 696$a = example::fact(4);
 697print "$a\n";
 698
 699</pre></div>
 700
 701<H3><a name="Perl5_nn13"></a>31.3.2 Using other compilers</H3>
 702
 703
 704<p>
 705SWIG is known to work with Cygwin and may work with other compilers on Windows.
 706For general hints and suggestions refer to the <a href="Windows.html#Windows">Windows</a> chapter.
 707</p>
 708
 709<H2><a name="Perl5_nn14"></a>31.4 The low-level interface</H2>
 710
 711
 712<p>
 713At its core, the Perl module uses a simple low-level interface
 714to C function, variables, constants, and classes.  This low-level interface
 715can be used to control your application.  However, it is also used to
 716construct more user-friendly proxy classes as described in the next section.
 717</p>
 718
 719<H3><a name="Perl5_nn15"></a>31.4.1 Functions</H3>
 720
 721
 722<p>
 723C functions are converted into new Perl built-in commands (or
 724subroutines). For example:
 725</p>
 726
 727<div class="targetlang"><pre>
 728%module example
 729int fact(int a);
 730...
 731</pre></div>
 732
 733<p>
 734Now, in Perl:
 735</p>
 736
 737<div class="targetlang"><pre>
 738use example;
 739$a = &amp;example::fact(2);
 740</pre></div>
 741
 742<H3><a name="Perl5_nn16"></a>31.4.2 Global variables</H3>
 743
 744
 745<p>
 746Global variables are handled using Perl's magic
 747variable mechanism.   SWIG generates a pair of functions
 748that intercept read/write operations and attaches them to a Perl variable with
 749the same name as the C global variable. Thus, an interface like this </p>
 750
 751<div class="targetlang"><pre>
 752%module example;
 753...
 754double Spam;
 755...
 756</pre></div>
 757
 758<p>
 759is accessed as follows:</p>
 760
 761<div class="targetlang"><pre>
 762use example;
 763print $example::Spam,"\n";
 764$example::Spam = $example::Spam + 4
 765# ... etc ...
 766
 767</pre></div>
 768
 769<p>
 770If a variable is declared as <tt>const</tt>, it is wrapped as a
 771read-only variable.  Attempts to modify its value will result in an
 772error.
 773</p>
 774
 775<p>
 776To make ordinary variables read-only, you can also use the <tt>%immutable</tt> directive. For example:
 777</p>
 778
 779<div class="code">
 780<pre>
 781%{
 782extern char *path;
 783%}
 784%immutable;
 785extern char *path;
 786%mutable;
 787</pre>
 788</div>
 789
 790<p>
 791The <tt>%immutable</tt> directive stays in effect until it is explicitly disabled or cleared using
 792<tt>%mutable</tt>.
 793See the <a href="SWIG.html#SWIG_readonly_variables">Creating read-only variables</a> section for further details.
 794</p>
 795
 796<p>
 797It is also possible to tag a specific variable as read-only like this:
 798</p>
 799
 800<div class="code">
 801<pre>
 802%{
 803extern char *path;
 804%}
 805%immutable path; 
 806...
 807...
 808extern char *path;       // Declared later in the input
 809</pre>
 810</div>
 811
 812<H3><a name="Perl5_nn17"></a>31.4.3 Constants</H3>
 813
 814
 815<p>
 816By default, constants are wrapped as read-only Perl variables.  For example:
 817</p>
 818
 819<div class="code">
 820<pre>
 821%module example
 822
 823#define FOO 42
 824</pre>
 825</div>
 826
 827<p>
 828In Perl:
 829</p>
 830
 831<div class="targetlang">
 832<pre>
 833use example;
 834print $example::FOO,"\n";    # OK
 835$example::FOO = 2;           # Error
 836</pre>
 837</div>
 838
 839<p>
 840Alternatively, if you use swig's <tt>-const</tt> option, constants are wrapped
 841such that the leading $ isn't required (by using a constant subroutine), which
 842usually gives a more natural Perl interface, for example:
 843</p>
 844
 845<div class="targetlang">
 846<pre>
 847use example;
 848print example::FOO,"\n";
 849</pre>
 850</div>
 851
 852<H3><a name="Perl5_nn18"></a>31.4.4 Pointers</H3>
 853
 854
 855<p>
 856SWIG represents pointers as blessed references.  A blessed reference
 857is the same as a Perl reference except that it has additional
 858information attached to it indicating what kind of reference it
 859is. That is, if you have a C declaration like this:</p>
 860
 861<div class="code"><pre>
 862Matrix *new_Matrix(int n, int m);
 863</pre></div>
 864
 865<p>
 866The module returns a value generated as follows:
 867</p>
 868
 869<div class="targetlang"><pre>
 870$ptr = new_Matrix(int n, int m);     # Save pointer return result
 871bless $ptr, "p_Matrix";              # Bless it as a pointer to Matrix
 872</pre></div>
 873
 874<p>
 875SWIG uses the "blessing" to check the datatype of various pointers.
 876In the event of a mismatch, an error or warning message is
 877generated.</p>
 878
 879<p>
 880To check to see if a value is the NULL pointer, use the
 881<tt>defined()</tt> command:</p>
 882
 883<div class="targetlang"><pre>
 884if (defined($ptr)) {
 885	print "Not a NULL pointer.";
 886} else {
 887	print "Is a NULL pointer.";
 888}
 889
 890</pre></div>
 891
 892<p>
 893To create a NULL pointer, you should pass the <tt>undef</tt> value to
 894a function.
 895</p>
 896
 897<p>
 898The "value" of a Perl reference is not the same as the underlying C
 899pointer that SWIG wrapper functions return.  Suppose that <tt>$a</tt>
 900and <tt>$b</tt> are two references that point to the same C object.
 901In general, <tt>$a</tt> and <tt>$b</tt> will be different--since they
 902are different references.  Thus, it is a mistake to check the equality
 903of <tt>$a</tt> and <tt>$b</tt> to check the equality of two C
 904pointers.  The correct method to check equality of C pointers is to
 905dereference them as follows:
 906</p>
 907
 908<div class="targetlang"><pre>
 909if ($$a == $$b) {
 910	print "a and b point to the same thing in C";
 911} else {
 912	print "a and b point to different objects.";
 913}
 914
 915</pre></div>
 916
 917<p>
 918As much as you might be inclined to modify a pointer value directly
 919from Perl, don't.  Manipulating pointer values is architecture dependent and
 920could cause your program to crash.  Similarly, don't try to manually cast
 921a pointer to a new type by reblessing a pointer.  This 
 922may not work like you expect and it is particularly dangerous when
 923casting C++ objects. If you need to cast a pointer or
 924change its value, consider writing some helper functions instead.  For
 925example:
 926</p>
 927
 928<div class="code">
 929<pre>
 930%inline %{
 931/* C-style cast */
 932Bar *FooToBar(Foo *f) {
 933   return (Bar *) f;
 934}
 935
 936/* C++-style cast */
 937Foo *BarToFoo(Bar *b) {
 938   return dynamic_cast&lt;Foo*&gt;(b);
 939}
 940
 941Foo *IncrFoo(Foo *f, int i) {
 942    return f+i;
 943}
 944%}
 945</pre>
 946</div>
 947
 948<p>
 949Also, if working with C++, you should always try
 950to use the new C++ style casts.  For example, in the above code, the
 951C-style cast may return a bogus result whereas as the C++-style cast will return
 952<tt>NULL</tt> if the conversion can't be performed.
 953</p>
 954
 955<p>
 956<b>Compatibility Note:</b> In earlier versions, SWIG tried to preserve the same pointer naming conventions
 957as XS and <tt>xsubpp</tt>.  Given the advancement of the SWIG typesystem and the growing differences between 
 958SWIG and XS, this is no longer supported.
 959</p>
 960
 961<H3><a name="Perl5_nn19"></a>31.4.5 Structures</H3>
 962
 963
 964<p>
 965Access to the contents of a structure are provided through a set of low-level
 966accessor functions as described in the "SWIG Basics" chapter.  For example,
 967</p>
 968
 969<div class="code"><pre>
 970struct Vector {
 971	double x,y,z;
 972};
 973</pre></div>
 974
 975<p>
 976gets mapped into the following collection of accessor functions:
 977</p>
 978
 979<div class="code"><pre>
 980struct Vector *new_Vector();
 981void           delete_Vector(Vector *v);
 982double         Vector_x_get(Vector *obj)
 983void           Vector_x_set(Vector *obj, double x)
 984double         Vector_y_get(Vector *obj)
 985void           Vector_y_set(Vector *obj, double y)
 986double         Vector_z_get(Vector *obj)
 987void           Vector_z_set(Vector *obj, double z)
 988
 989</pre></div>
 990
 991<p>
 992These functions are then used to access structure data from Perl as follows:
 993</p>
 994
 995<div class="targetlang"><pre>
 996$v = example::new_Vector();
 997print example::Vector_x_get($v),"\n";    # Get x component
 998example::Vector_x_set($v,7.8);          # Change x component
 999</pre></div>
1000
1001<p>
1002Similar access is provided for unions and the data members of C++ classes.
1003</p>
1004
1005<p>
1006<tt>const</tt> members of a structure are read-only. Data members
1007can also be forced to be read-only using the <tt>%immutable</tt> directive. For example:
1008</p>
1009
1010<div class="code">
1011<pre>
1012struct Foo {
1013   ...
1014   %immutable;
1015   int x;        /* Read-only members */
1016   char *name;
1017   %mutable;
1018   ...
1019};
1020</pre>
1021</div>
1022
1023<p>
1024When <tt>char *</tt> members of a structure are wrapped, the contents are assumed to be
1025dynamically allocated using <tt>malloc</tt> or <tt>new</tt> (depending on whether or not
1026SWIG is run with the -c++ option).   When the structure member is set, the old contents will be 
1027released and a new value created.   If this is not the behavior you want, you will have to use
1028a typemap (described later).
1029</p>
1030
1031<p>
1032Array members are normally wrapped as read-only.   For example,
1033</p>
1034
1035<div class="code">
1036<pre>
1037struct Foo {
1038   int  x[50];
1039};
1040</pre>
1041</div>
1042
1043<p>
1044produces a single accessor function like this:
1045</p>
1046
1047<div class="code">
1048<pre>
1049int *Foo_x_get(Foo *self) {
1050    return self-&gt;x;
1051};
1052</pre>
1053</div>
1054
1055<p>
1056If you want to set an array member, you will need to supply a "memberin" typemap
1057described later in this chapter.  As a special case, SWIG does generate
1058code to set array members of type <tt>char</tt> (allowing you to store a Python
1059string in the structure).
1060</p>
1061
1062<p>
1063When structure members are wrapped, they are handled as pointers.   For example,
1064</p>
1065
1066<div class="code">
1067<pre>
1068struct Foo {
1069   ...
1070};
1071
1072struct Bar {
1073   Foo f;
1074};
1075</pre>
1076</div>
1077
1078<p>
1079generates accessor functions such as this:
1080</p>
1081
1082<div class="code">
1083<pre>
1084Foo *Bar_f_get(Bar *b) {
1085    return &amp;b-&gt;f;
1086}
1087
1088void Bar_f_set(Bar *b, Foo *val) {
1089    b-&gt;f = *val;
1090}
1091</pre>
1092</div>
1093
1094
1095<H3><a name="Perl5_nn20"></a>31.4.6 C++ classes</H3>
1096
1097
1098<p>
1099C++ classes are wrapped by building a set of low level accessor functions. 
1100Consider the following class:
1101</p>
1102
1103<div class="code"><pre>
1104class List {
1105public:
1106  List();
1107  ~List();
1108  int  search(char *item);
1109  void insert(char *item);
1110  void remove(char *item);
1111  char *get(int n);
1112  int  length;
1113static void print(List *l);
1114};
1115</pre></div>
1116
1117<p>
1118When wrapped by SWIG, the following functions are created:
1119</p>
1120
1121<div class="code"><pre>
1122List    *new_List();
1123void     delete_List(List *l);
1124int      List_search(List *l, char *item);
1125void     List_insert(List *l, char *item);
1126void     List_remove(List *l, char *item);
1127char    *List_get(List *l, int n);
1128int      List_length_get(List *l);
1129void     List_length_set(List *l, int n);
1130void     List_print(List *l);
1131
1132</pre></div>
1133
1134<p>
1135In Perl, these functions are used in a straightforward manner:
1136</p>
1137
1138<div class="targetlang"><pre>
1139use example;
1140$l = example::new_List();
1141example::List_insert($l,"Ale");
1142example::List_insert($l,"Stout");
1143example::List_insert($l,"Lager")
1144example::List_print($l)
1145Lager
1146Stout
1147Ale
1148print example::List_length_get($l),"\n";
11493
1150</pre></div>
1151
1152<p>
1153At this low level, C++ objects are really just typed pointers.  Member
1154functions are accessed by calling a C-like wrapper with an instance pointer
1155as the first argument.   Although this interface is fairly primitive, it
1156provides direct access to C++ objects.  A higher level interface using Perl proxy classes
1157can be built using these low-level accessors.  This is described shortly.
1158</p>
1159
1160<H3><a name="Perl5_nn21"></a>31.4.7 C++ classes and type-checking</H3>
1161
1162
1163<p>
1164The SWIG type-checker is fully aware of C++ inheritance.  Therefore, if you have
1165classes like this
1166</p>
1167
1168<div class="code">
1169<pre>
1170class Foo {
1171...
1172};
1173
1174class Bar : public Foo {
1175...
1176};
1177</pre>
1178</div>
1179
1180<p>
1181and a function
1182</p>
1183
1184<div class="code">
1185<pre>
1186void spam(Foo *f);
1187</pre>
1188</div>
1189
1190<p>
1191then the function <tt>spam()</tt> accepts <tt>Foo *</tt> or a pointer to any class derived from <tt>Foo</tt>.
1192If necessary, the type-checker also adjusts the value of the pointer (as is necessary when
1193multiple inheritance is used).
1194</p>
1195
1196<H3><a name="Perl5_nn22"></a>31.4.8 C++ overloaded functions</H3>
1197
1198
1199<p>
1200If you have a C++ program with overloaded functions or methods, you will need to disambiguate
1201those methods using <tt>%rename</tt>.   For example:
1202</p>
1203
1204<div class="code">
1205<pre>
1206/* Forward renaming declarations */
1207%rename(foo_i) foo(int); 
1208%rename(foo_d) foo(double);
1209...
1210void foo(int);           // Becomes 'foo_i'
1211void foo(char *c);       // Stays 'foo' (not renamed)
1212
1213class Spam {
1214public:
1215   void foo(int);      // Becomes 'foo_i'
1216   void foo(double);   // Becomes 'foo_d'
1217   ...
1218};
1219</pre>
1220</div>
1221
1222<p>
1223Now, in Perl, the methods are accessed as follows:
1224</p>
1225
1226<div class="targetlang">
1227<pre>
1228use example;
1229example::foo_i(3);
1230$s = example::new_Spam();
1231example::Spam_foo_i($s,3);
1232example::Spam_foo_d($s,3.14);
1233</pre>
1234</div>
1235
1236<p>
1237Please refer to the "SWIG Basics" chapter for more information. 
1238</p>
1239
1240<H3><a name="Perl5_nn23"></a>31.4.9 Operators</H3>
1241
1242
1243    <p>
1244As of version 1.3.27 SWIG automatically renames the most common C++ operators, and maps them into the perl module with the proper 'use overload ...' so you don't need to do any work.
1245    </p>
1246
1247    <p>
1248The following C++ operators are currently supported by the Perl module:
1249    </p>
1250
1251    <ul>
1252<li>operator++	 </li>
1253<li>operator--	 </li>
1254<li>operator+	 </li>
1255<li>operator-	 </li>
1256<li>operator*	 </li>
1257<li>operator/	 </li>
1258<li>operator==	 </li>
1259<li>operator!=	 </li>
1260<li>operator%	 </li>
1261<li>operator&gt;	 </li>
1262<li>operator&lt;	 </li>
1263<li>operator and </li>
1264<li>operator or  </li>
1265    </ul>
1266
1267<H3><a name="Perl5_nn24"></a>31.4.10 Modules and packages</H3>
1268
1269
1270<p>
1271When you create a SWIG extension, everything gets placed into
1272a single Perl module. The name of the module is determined by the
1273<tt>%module</tt> directive. To use the module, do the following:
1274</p>
1275
1276<div class="targetlang"><pre>
1277$ perl5
1278use example;                      # load the example module
1279print example::fact(4),"\n"       # Call a function in it
128024
1281</pre></div>
1282
1283<p>
1284Usually, a module consists of a collection of code that is contained
1285within a single file. A package, on the other hand, is the Perl
1286equivalent of a namespace. A package is a lot like a module, except
1287that it is independent of files. Any number of files may be part of
1288the same package--or a package may be broken up into a collection of
1289modules if you prefer to think about it in this way.
1290</p>
1291
1292<p>
1293SWIG installs its functions into a package with the same name as
1294the module. </p>
1295
1296<p>
1297<b>Incompatible Change:</b> previous versions of SWIG enabled you to
1298change the name of the package by using the -package option, this
1299feature has been removed in order to properly support modules that
1300used nested namespaces, e.g. Foo::Bar::Baz. To give your module a
1301nested namespace simply provide the fully qualified name in your
1302%module directive: </p>
1303
1304<div class="code"><pre>
1305%module "Foo::Bar::Baz"
1306</pre></div>
1307
1308<p>
1309<b>NOTE:</b> the double quotes are necessary.
1310</p>
1311
1312<p>
1313      Using the <tt>package</tt> option of the <tt>%module</tt> directive allows
1314      you to specify what Perl namespace that the module will be living in when
1315      installed.  This is useful in the situation where a module maintainer
1316      wants to split a large module into smaller pieces to make maintenance
1317      easier, but doesn't want to have that affect the module name used by
1318      applications. So for example, if I wanted to split <tt>XML::Xerces</tt>
1319      into <tt>XML::Xerces::SAX</tt>, etc. , but I wanted all the applications
1320      to be able to access the classes using the <tt>XML::Xerces</tt> namespace
1321      I could use:
1322
1323</p>
1324
1325<div class="code">
1326<pre>
1327%module(package="XML::Xerces") "XML::Xerces::SAX
1328</pre>
1329</div>
1330
1331<p>
1332      And now all the applications could use the class
1333      <tt>XML::Xerces::SAXParser</tt>. Without the <tt>package</tt> directive
1334      splitting the module would force applications to use the class
1335      <tt>XML::Xerces::SAX::SAXParser</tt>. This could break compatibility for
1336      existing applications that are already using the class under the name
1337      <tt>XML::Xerces::SAXParser</tt>.
1338    </p>
1339
1340<!--
1341<p>
1342This can be changed by giving SWIG the -package
1343option:
1344</p>
1345
1346<div class="code"><pre>
1347$ swig -perl -package Foo example.i
1348</pre></div>
1349
1350<p>
1351In this case, you still create a module called `<tt>example</tt>' exactly as before, but
1352all of the functions in that module will be installed into the package
1353`<tt>Foo</tt>.' For example:
1354</p>
1355
1356<div class="targetlang"><pre>
1357use example;   # Load the module like before
1358print Foo::fact(4),"\n";        # Call a function in package FooBar
1359</pre></div>
1360-->
1361
1362<H2><a name="Perl5_nn25"></a>31.5 Input and output parameters</H2>
1363
1364
1365<p>
1366A common problem in some C programs is handling parameters passed as simple pointers.  For
1367example:
1368</p>
1369
1370<div class="code">
1371<pre>
1372void add(int x, int y, int *result) {
1373   *result = x + y;
1374}
1375</pre>
1376</div>
1377
1378<p>
1379or perhaps
1380</p>
1381
1382<div class="code">
1383<pre>
1384int sub(int *x, int *y) {
1385   return *x+*y;
1386}
1387</pre>
1388</div>
1389
1390<p>
1391The easiest way to handle these situations is to use the <tt>typemaps.i</tt> file.  For example:
1392</p>
1393
1394<div class="code">
1395<pre>
1396%module example
1397%include "typemaps.i"
1398
1399void add(int, int, int *OUTPUT);
1400int  sub(int *INPUT, int *INPUT);
1401</pre>
1402</div>
1403
1404<p>
1405In Perl, this allows you to pass simple values.  For example:
1406</p>
1407
1408<div class="targetlang">
1409<pre>
1410$a = example::add(3,4);
1411print "$a\n";
14127
1413$b = example::sub(7,4);
1414print "$b\n";
14153
1416</pre>
1417</div>
1418
1419<p>
1420Notice how the <tt>INPUT</tt> parameters allow integer values to be passed instead of pointers
1421and how the <tt>OUTPUT</tt> parameter creates a return result.
1422</p>
1423
1424<p>
1425If you don't want to use the names <tt>INPUT</tt> or <tt>OUTPUT</tt>, use the <tt>%apply</tt>
1426directive.  For example:
1427</p>
1428
1429<div class="code">
1430<pre>
1431%module example
1432%include "typemaps.i"
1433
1434%apply int *OUTPUT { int *result };
1435%apply int *INPUT  { int *x, int *y};
1436
1437void add(int x, int y, int *result);
1438int  sub(int *x, int *y);
1439</pre>
1440</div>
1441
1442<p>
1443If a function mutates one of its parameters like this,
1444</p>
1445
1446<div class="code">
1447<pre>
1448void negate(int *x) {
1449   *x = -(*x);
1450}
1451</pre>
1452</div>
1453
1454<p>
1455you can use <tt>INOUT</tt> like this:
1456</p>
1457
1458<div class="code">
1459<pre>
1460%include "typemaps.i"
1461...
1462void negate(int *INOUT);
1463</pre>
1464</div>
1465
1466<p>
1467In Perl, a mutated parameter shows up as a return value.  For example:
1468</p>
1469
1470<div class="targetlang">
1471<pre>
1472$a = example::negate(3);
1473print "$a\n";
1474-3
1475</pre>
1476</div>
1477
1478<p>
1479The most common use of these special typemap rules is to handle functions that
1480return more than one value.   For example, sometimes a function returns a result
1481as well as a special error code:
1482</p>
1483
1484<div class="code">
1485<pre>
1486/* send message, return number of bytes sent, along with success code */
1487int send_message(char *text, int len, int *success);
1488</pre>
1489</div>
1490
1491<p>
1492To wrap such a function, simply use the <tt>OUTPUT</tt> rule above. For example:
1493</p>
1494
1495<div class="code">
1496<pre>
1497%module example
1498%include "typemaps.i"
1499%apply int *OUTPUT { int *success };
1500...
1501int send_message(char *text, int *success);
1502</pre>
1503</div>
1504
1505<p>
1506When used in Perl, the function will return multiple values.  
1507</p>
1508
1509<div class="targetlang">
1510<pre>
1511($bytes, $success) = example::send_message("Hello World");
1512</pre>
1513</div>
1514
1515<p>
1516Another common use of multiple return values are in query functions.  For example:
1517</p>
1518
1519<div class="code">
1520<pre>
1521void get_dimensions(Matrix *m, int *rows, int *columns);
1522</pre>
1523</div>
1524
1525<p>
1526To wrap this, you might use the following:
1527</p>
1528
1529<div class="code">
1530<pre>
1531%module example
1532%include "typemaps.i"
1533%apply int *OUTPUT { int *rows, int *columns };
1534...
1535void get_dimensions(Matrix *m, int *rows, *columns);
1536</pre>
1537</div>
1538
1539<p>
1540Now, in Perl:
1541</p>
1542
1543<div class="targetlang">
1544<pre>
1545($r,$c) = example::get_dimensions($m);
1546</pre>
1547</div>
1548
1549<p>
1550In certain cases, it is possible to treat Perl references as C pointers.  To do this, use the <tt>REFERENCE</tt> typemap.  For
1551example:
1552</p>
1553
1554<div class="code">
1555<pre>
1556%module example
1557%include "typemaps.i"
1558
1559void add(int x, int y, int *REFERENCE);
1560</pre>
1561</div>
1562
1563<p>
1564In Perl:
1565</p>
1566
1567<div class="targetlang">
1568<pre>
1569use example;
1570$c = 0.0;
1571example::add(3,4,\$c);
1572print "$c\n";
15737
1574</pre>
1575</div>
1576
1577<p>
1578<b>Note:</b> The <tt>REFERENCE</tt> feature is only currently supported for numeric types (integers and floating point).
1579</p>
1580
1581<H2><a name="Perl5_nn26"></a>31.6 Exception handling</H2>
1582
1583
1584<p>
1585The SWIG <tt>%exception</tt> directive can be used to create a
1586user-definable exception handler for converting exceptions in your
1587C/C++ program into Perl exceptions.  The chapter on customization features
1588contains more details, but suppose you have a C++ class like the
1589following:
1590</p>
1591
1592<div class="code"><pre>
1593class RangeError {};   // Used for an exception
1594
1595class DoubleArray {
1596  private:
1597    int n;
1598    double *ptr;
1599  public:
1600    // Create a new array of fixed size
1601    DoubleArray(int size) {
1602      ptr = new double[size];
1603      n = size;
1604    }
1605    // Destroy an array
1606    ~DoubleArray() {
1607       delete ptr;
1608    }
1609    // Return the length of the array
1610    int   length() {
1611      return n;
1612    }
1613
1614    // Get an item from the array and perform bounds checking.
1615    double getitem(int i) {
1616      if ((i &gt;= 0) &amp;&amp; (i &lt; n))
1617        return ptr[i];
1618      else
1619        throw RangeError();
1620    }
1621
1622    // Set an item in the array and perform bounds checking.
1623    void setitem(int i, double val) {
1624      if ((i &gt;= 0) &amp;&amp; (i &lt; n))
1625        ptr[i] = val;
1626      else {
1627        throw RangeError();
1628      }
1629    }
1630  };
1631</pre></div>
1632
1633<p>
1634Since several methods in this class can throw an exception
1635for an out-of-bounds access, you might want to catch
1636this in the Perl extension by writing the following in an
1637interface file:
1638</p>
1639
1640<div class="code"><pre>
1641%exception {
1642  try {
1643    $action
1644  }
1645  catch (RangeError) {
1646    croak("Array index out-of-bounds");
1647  }
1648}
1649
1650class DoubleArray {
1651...
1652};
1653</pre></div>
1654
1655<p>
1656The exception handling code is inserted directly into generated wrapper
1657functions.  The <tt>$action</tt> variable is replaced with the C/C++
1658code being executed by the wrapper.  When an exception handler
1659is defined, errors can be caught and used to gracefully generate a Perl error
1660instead of forcing the entire program to terminate with an uncaught error.
1661</p>
1662
1663<p>
1664As shown, the exception handling code will be added to every wrapper function.
1665Since this is somewhat inefficient.  You might consider refining the 
1666exception handler to only apply to specific methods like this:
1667</p>
1668
1669<div class="code">
1670<pre>
1671%exception getitem {
1672  try {
1673    $action
1674  }
1675  catch (RangeError) {
1676    croak("Array index out-of-bounds");
1677  }
1678}
1679
1680%exception setitem {
1681  try {
1682    $action
1683  }
1684  catch (RangeError) {
1685    croak("Array index out-of-bounds");
1686  }
1687}
1688</pre>
1689</div>
1690
1691<p>
1692In this case, the exception handler is only attached to methods and functions
1693named <tt>getitem</tt> and <tt>setitem</tt>.
1694</p>
1695
1696<p>
1697If you had a lot of different methods, you can avoid extra typing by using a macro.
1698For example:
1699</p>
1700
1701<div class="code">
1702<pre>
1703%define RANGE_ERROR
1704{
1705  try {
1706    $action
1707  }
1708  catch (RangeError) {
1709    croak("Array index out-of-bounds");
1710  }
1711}
1712%enddef
1713
1714%exception getitem RANGE_ERROR;
1715%exception setitem RANGE_ERROR;
1716</pre>
1717</div>
1718
1719<p>
1720Since SWIG's exception handling is user-definable, you are not limited to C++ exception handling.
1721See the chapter on "<a href="Customization.html#Customization">Customization features</a>" for more examples.
1722</p>
1723
1724<p>
1725<b>Compatibility note:</b> In SWIG1.1, exceptions were defined using the older <tt>%except</tt> directive:
1726</p>
1727
1728<div class="code">
1729<pre>
1730%except(python) {
1731  try {
1732    $function
1733  }
1734  catch (RangeError) {
1735    croak("Array index out-of-bounds");
1736  }
1737}
1738</pre>
1739</div>
1740
1741<p>
1742This is still supported, but it is deprecated.  The newer <tt>%exception</tt> directive provides the same
1743functionality, but it has additional capabilities that make it more powerful.
1744</p>
1745
1746<H2><a name="Perl5_nn27"></a>31.7 Remapping datatypes with typemaps</H2>
1747
1748
1749<p>
1750This section describes how you can modify SWIG's default wrapping behavior
1751for various C/C++ datatypes using the <tt>%typemap</tt> directive.   This
1752is an advanced topic that assumes familiarity with the Perl C API as well
1753as the material in the "<a href="Typemaps.html#Typemaps">Typemaps</a>" chapter.
1754</p>
1755
1756<p>
1757Before proceeding, it should be stressed that typemaps are <em>not</em> a required 
1758part of using SWIG---the default wrapping behavior is enough in most cases.
1759Typemaps are only used if you want to change some aspect of the primitive
1760C-Perl interface.
1761</p>
1762
1763<H3><a name="Perl5_nn28"></a>31.7.1 A simple typemap example</H3>
1764
1765
1766<p>
1767A typemap is nothing more than a code generation rule that is attached to 
1768a specific C datatype.   For example, to convert integers from Perl to C,
1769you might define a typemap like this:
1770</p>
1771
1772<div class="code"><pre>
1773%module example
1774
1775%typemap(in) int {
1776	$1 = (int) SvIV($input);
1777	printf("Received an integer : %d\n", $1);
1778}
1779...
1780%inline %{
1781extern int fact(int n);
1782%}
1783
1784</pre></div>
1785
1786<p>
1787Typemaps are always associated with some specific aspect of code generation.
1788In this case, the "in" method refers to the conversion of input arguments
1789to C/C++.  The datatype <tt>int</tt> is the datatype to which the typemap
1790will be applied.  The supplied C code is used to convert values.  In this
1791code a number of special variable prefaced by a <tt>$</tt> are used.  The
1792<tt>$1</tt> variable is placeholder for a local variable of type <tt>int</tt>.
1793The <tt>$input</tt> variable is the input object (usually a <tt>SV *</tt>).
1794</p>
1795
1796<p>
1797When this example is used in Perl5, it will operate as follows:
1798</p>
1799
1800<div class="targetlang"><pre>
1801use example;
1802$n = example::fact(6);
1803print "$n\n";
1804...
1805
1806Output:
1807Received an integer : 6
1808720
1809</pre></div>
1810
1811<p>
1812The application of a typemap to specific datatypes and argument names involves
1813more than simple text-matching--typemaps are fully integrated into the
1814SWIG type-system.   When you define a typemap for <tt>int</tt>, that typemap
1815applies to <tt>int</tt> and qualified variations such as <tt>const int</tt>.  In addition,
1816the typemap system follows <tt>typedef</tt> declarations.  For example:
1817</p>
1818
1819<div class="targetlang">
1820<pre>
1821%typemap(in) int n {
1822	$1 = (int) SvIV($input);
1823	printf("n = %d\n",$1);
1824}
1825%inline %{
1826typedef int Integer;
1827extern int fact(Integer n);    // Above typemap is applied
1828%}
1829</pre>
1830</div>
1831
1832<p>
1833It should be noted that the matching of <tt>typedef</tt> only occurs in one direction.  If you
1834defined a typemap for <tt>Integer</tt>, it is not applied to arguments of
1835type <tt>int</tt>.
1836</p>
1837
1838<p>
1839Typemaps can also be defined for groups of consecutive arguments.  For example:
1840</p>
1841
1842<div class="targetlang">
1843<pre>
1844%typemap(in) (char *str, unsigned len) {
1845    $1 = SvPV($input,$2);
1846};
1847
1848int count(char c, char *str, unsigned len);
1849</pre>
1850</div>
1851
1852<p>
1853When a multi-argument typemap is defined, the arguments are always handled as a single
1854Perl object.  This allows the function to be used like this (notice how the length
1855parameter is omitted):
1856</p>
1857
1858<div class="targetlang">
1859<pre>
1860example::count("e","Hello World");
18611
1862&gt;&gt;&gt;
1863</pre>
1864</div>
1865
1866
1867<H3><a name="Perl5_nn29"></a>31.7.2 Perl5 typemaps</H3>
1868
1869
1870<p>
1871The previous section illustrated an "in" typemap for converting Perl objects to C.
1872A variety of different typemap methods are defined by the Perl module.  For example,
1873to convert a C integer back into a Perl object, you might define an "out" typemap
1874like this:
1875</p>
1876
1877
1878<div class="targetlang">
1879<pre>
1880%typemap(out) int {
1881    $result = sv_newmortal();
1882    set_setiv($result, (IV) $1);
1883    argvi++;
1884}
1885</pre>
1886</div>
1887
1888<p>
1889The following typemap methods are available:
1890</p>
1891
1892<p>
1893<tt>%typemap(in)</tt>
1894</p>
1895
1896<div class="indent">
1897Converts Perl5 object to input function arguments.
1898</div>
1899
1900<p>
1901<tt>%typemap(out)</tt>
1902</p>
1903
1904<div class="indent">
1905Converts function return value to a Perl5 value.
1906</div>
1907
1908<p>
1909<tt>%typemap(varin)</tt>
1910</p>
1911
1912<div class="indent">
1913Converts a Perl5 object to a global variable.
1914</div>
1915
1916<p>
1917<tt>%typemap(varout)</tt>
1918</p>
1919
1920<div class="indent">
1921Converts a global variable to a Perl5 object.
1922</div>
1923
1924<p>
1925<tt>%typemap(freearg)</tt>
1926</p>
1927
1928<div class="indent">
1929Cleans up a function argument after a function call
1930</div>
1931
1932<p>
1933<tt>%typemap(argout)</tt>
1934</p>
1935
1936<div class="indent">
1937Output argument handling
1938</div>
1939
1940<p>
1941<tt>%typemap(ret)</tt>
1942</p>
1943
1944<div class="indent">
1945Clean up return value from a function.
1946</div>
1947
1948<p>
1949<tt>%typemap(memberin)</tt>
1950</p>
1951
1952<div class="indent">
1953Setting of C++ member data (all languages).
1954</div>
1955
1956<p>
1957<tt>%typemap(memberout)</tt>
1958</p>
1959
1960<div class="indent">
1961Return of C++ member data (all languages).
1962</div>
1963
1964<p>
1965<tt>%typemap(check)</tt>
1966</p>
1967
1968<div class="indent">
1969Check value of input parameter.
1970</div>
1971
1972<H3><a name="Perl5_nn30"></a>31.7.3 Typemap variables</H3>
1973
1974
1975<p>
1976Within typemap code, a number of special variables prefaced with a <tt>$</tt> may appear.
1977A full list of variables can be found in the "<a href="Typemaps.html#Typemaps">Typemaps</a>" chapter.
1978This is a list of the most common variables:
1979</p>
1980
1981<p>
1982<tt>$1</tt>
1983</p>
1984
1985<div class="indent">
1986A C local variable corresponding to the actual type specified in the
1987<tt>%typemap</tt> directive.  For input values, this is a C local variable
1988that's supposed to hold an argument value.  For output values, this is
1989the raw result that's supposed to be returned to Perl.
1990</div>
1991
1992<p>
1993<tt>$input</tt>
1994</p>
1995
1996<div class="indent">
1997A Perl object holding the value of an argument of variable value.
1998</div>
1999
2000<p>
2001<tt>$result</tt>
2002</p>
2003
2004<div class="indent">
2005A Perl object that holds the result to be returned to Perl.
2006</div>
2007
2008<p>
2009<tt>$1_name</tt>
2010</p>
2011
2012<div class="indent">
2013The parameter name that was matched. 
2014</div>
2015
2016<p>
2017<tt>$1_type</tt>
2018</p>
2019
2020<div class="indent">
2021The actual C datatype matched by the typemap.
2022</div>
2023
2024<p>
2025<tt>$1_ltype</tt>
2026</p>
2027
2028<div class="indent">
2029An assignable version of the datatype matched by the typemap (a type that can appear on the left-hand-side of
2030a C assignment operation).  This type is stripped of qualifiers and may be an altered version of <tt>$1_type</tt>.
2031All arguments and local variables in wrapper functions are declared using this type so that their values can be
2032properly assigned.
2033</div>
2034
2035<p>
2036<tt>$symname</tt>
2037</p>
2038
2039<div class="indent">
2040The Perl name of the wrapper function being created.
2041</div>
2042
2043<H3><a name="Perl5_nn31"></a>31.7.4 Useful functions</H3>
2044
2045
2046<p>
2047When writing typemaps, it is necessary to work directly with Perl5
2048objects.  This, unfortunately, can be a daunting task.  Consult the
2049"perlguts" man-page for all of the really ugly details.  A short
2050summary of commonly used functions is provided here for reference.  It
2051should be stressed that SWIG can be used quite effectively without
2052knowing any of these details--especially now that there are typemap
2053libraries that can already been written.
2054</p>
2055
2056<p>
2057<b>Perl Integer Functions</b>
2058</p>
2059
2060<div class="code">
2061<pre>
2062int   SvIV(SV *);
2063void  sv_setiv(SV *sv, IV value);
2064SV   *newSViv(IV value);
2065int   SvIOK(SV *);
2066</pre>
2067</div>
2068
2069<p>
2070<b>Perl Floating Point Functions</b>
2071</p>
2072
2073<div class="code">
2074<pre>
2075double SvNV(SV *);
2076void   sv_setnv(SV *, double value);
2077SV    *newSVnv(double value);
2078int    SvNOK(SV *);
2079</pre>
2080</div>
2081
2082<p>
2083<b>Perl String Functions</b>
2084</p>
2085
2086<div class="code">
2087<pre>
2088char     *SvPV(SV *, STRLEN len);
2089void      sv_setpv(SV *, char *val);
2090void      sv_setpvn(SV *, char *val, STRLEN len);
2091SV       *newSVpv(char *value, STRLEN len);
2092int       SvPOK(SV *);
2093void      sv_catpv(SV *, char *);
2094void      sv_catpvn(SV *, char *, STRLEN);
2095</pre>
2096</div>
2097
2098<p>
2099<b>Perl References</b>
2100</p>
2101
2102<div class="code">
2103<pre>
2104void      sv_setref_pv(SV *, char *, void *ptr);
2105int       sv_isobject(SV *);
2106SV       *SvRV(SV *);
2107int       sv_isa(SV *, char *0;
2108</pre>
2109</div>
2110
2111
2112<H2><a name="Perl5_nn32"></a>31.8 Typemap Examples</H2>
2113
2114
2115<p>
2116This section includes a few examples of typemaps.  For more examples, you
2117might look at the files "<tt>perl5.swg</tt>" and "<tt>typemaps.i</tt>" in
2118the SWIG library.
2119</p>
2120
2121<H3><a name="Perl5_nn33"></a>31.8.1 Converting a Perl5 array to a char **</H3>
2122
2123
2124<p>
2125A common problem in many C programs is the processing of command line
2126arguments, which are usually passed in an array of NULL terminated
2127strings.  The following SWIG interface file allows a Perl5 array
2128reference to be used as a char ** datatype.
2129</p>
2130
2131<div class="code"><pre>
2132%module argv
2133
2134// This tells SWIG to treat char ** as a special case
2135%typemap(in) char ** {
2136	AV *tempav;
2137	I32 len;
2138	int i;
2139	SV  **tv;
2140	if (!SvROK($input))
2141	    croak("Argument $argnum is not a reference.");
2142        if (SvTYPE(SvRV($input)) != SVt_PVAV)
2143	    croak("Argument $argnum is not an array.");
2144        tempav = (AV*)SvRV($input);
2145	len = av_len(tempav);
2146	$1 = (char **) malloc((len+2)*sizeof(char *));
2147	for (i = 0; i &lt;= len; i++) {
2148	    tv = av_fetch(tempav, i, 0);	
2149	    $1[i] = (char *) SvPV(*tv,PL_na);
2150        }
2151	$1[i] = NULL;
2152};
2153
2154// This cleans up the char ** array after the function call
2155%typemap(freearg) char ** {
2156	free($1);
2157}
2158
2159// Creates a new Perl array and places a NULL-terminated char ** into it
2160%typemap(out) char ** {
2161	AV *myav;
2162	SV **svs;
2163	int i = 0,len = 0;
2164	/* Figure out how many elements we have */
2165	while ($1[len])
2166	   len++;
2167	svs = (SV **) malloc(len*sizeof(SV *));
2168	for (i = 0; i &lt; len ; i++) {
2169	    svs[i] = sv_newmortal();
2170	    sv_setpv((SV*)svs[i],$1[i]);
2171	};
2172	myav =	av_make(len,svs);
2173	free(svs);
2174        $result = newRV_noinc((SV*)myav);
2175        sv_2mortal($result);
2176        argvi++;
2177}
2178
2179// Now a few test functions
2180%inline %{
2181int print_args(char **argv) {
2182    int i = 0;
2183    while (argv[i]) {
2184         printf("argv[%d] = %s\n", i,argv[i]);
2185         i++;
2186    }
2187    return i;
2188}
2189
2190// Returns a char ** list 
2191char **get_args() {
2192    static char *values[] = { "Dave", "Mike", "Susan", "John", "Michelle", 0};
2193    return &amp;values[0];
2194}
2195%}
2196
2197</pre></div>
2198
2199<p>
2200When this module is compiled, the wrapped C functions can be used in a
2201Perl script as follows:
2202</p>
2203
2204<div class="targetlang"><pre>
2205use argv;
2206@a = ("Dave", "Mike", "John", "Mary");           # Create an array of strings
2207argv::print_args(\@a);                           # Pass it to our C function
2208$b = argv::get_args();                           # Get array of strings from C
2209print @$b,"\n";                                  # Print it out
2210</pre></div>
2211
2212
2213<H3><a name="Perl5_nn34"></a>31.8.2 Return values</H3>
2214
2215
2216<p>
2217Return values are placed on the argument stack of each wrapper
2218function.  The current value of the argument stack pointer is
2219contained in a variable <tt>argvi</tt>.  Whenever a new output value
2220is added, it is critical that this value be incremented.  For multiple
2221output values, the final value of <tt>argvi</tt> should be the total
2222number of output values.
2223</p>
2224
2225<p>
2226The total number of return values should not exceed the number of
2227input values unless you explicitly extend the argument stack.  This
2228can be done using the <tt>EXTEND()</tt> macro as in:
2229</p>
2230
2231<div class="code"><pre>
2232%typemap(argout) int *OUTPUT {
2233	if (argvi &gt;= items) {            
2234		EXTEND(sp,1);              /* Extend the stack by 1 object */
2235	}
2236	$result = sv_newmortal();
2237	sv_setiv($target,(IV) *($1));
2238	argvi++;
2239}
2240</pre></div>
2241
2242<H3><a name="Perl5_nn35"></a>31.8.3 Returning values from arguments</H3>
2243
2244
2245<p>
2246Sometimes it is desirable for a function to return a value in one of
2247its arguments.  This example describes the implementation of the <tt>OUTPUT</tt> typemap.
2248</p>
2249
2250<div class="code"><pre>
2251%module return
2252
2253// This tells SWIG to treat an double * argument with name 'OutDouble' as
2254// an output value.  
2255
2256%typemap(argout) double *OUTPUT {
2257	$result = sv_newmortal();
2258	sv_setnv($result, *$input);
2259	argvi++;                     /* Increment return count -- important! */
2260}
2261
2262// We don't care what the input value is. Ignore, but set to a temporary variable
2263
2264%typemap(in,numinputs=0) double *OUTPUT(double junk) {
2265	$1 = &amp;junk;
2266}
2267
2268// Now a function to test it
2269%{
2270/* Returns the first two input arguments */
2271int multout(double a, double b, double *out1, double *out2) {
2272	*out1 = a;
2273	*out2 = b;
2274	return 0;
2275};
2276%}
2277
2278// If we name both parameters OutDouble both will be output
2279
2280int multout(double a, double b, double *OUTPUT, double *OUTPUT);
2281...
2282</pre></div>
2283
2284<p>
2285When this function is called, the output arguments are appended to the stack used
2286to return results.  This shows up an array in Perl.
2287For example:
2288</p>
2289
2290<div class="targetlang"><pre>
2291@r = multout(7,13);
2292print "multout(7,13) = @r\n";
2293($x,$y) = multout(7,13);
2294</pre></div>
2295
2296<H3><a name="Perl5_nn36"></a>31.8.4 Accessing array structure members</H3>
2297
2298
2299<p>
2300Consider the following data structure:
2301</p>
2302
2303<div class="code"><pre>
2304#define SIZE  8
2305typedef struct {
2306    int   values[SIZE];
2307    ...
2308} Foo;
2309
2310</pre></div>
2311
2312<p>
2313By default, SWIG doesn't know how to the handle the values structure
2314member it's an array, not a pointer.  In this case, SWIG makes the array member
2315read-only.   Reading will simply return a pointer to the first item in the array.
2316To make the member writable, a "memberin" typemap can be used.
2317</p>
2318
2319<div class="code"><pre>
2320%typemap(memberin) int [SIZE] {
2321    int i;
2322    for (i = 0; i &lt; SIZE; i++) {
2323        $1[i] = $input[i];
2324    }
2325}
2326
2327</pre></div>
2328
2329<p>
2330Whenever a <tt>int [SIZE]</tt> member is encountered in a structure
2331or class, this typemap provides a safe mechanism for setting its
2332value.  
2333</p>
2334
2335<p>
2336As in the previous example, the typemap can be generalized for any dimension.
2337For example:
2338</p>
2339
2340<div class="code"><pre>
2341%typemap(memberin) int [ANY] {
2342   int i;
2343   for (i = 0; i &lt; $1_dim0; i++) {
2344      $1[i] = $input[i];
2345   }
2346}
2347</pre></div>
2348
2349<p>
2350When setting structure members, the input object is always assumed to
2351be a C array of values that have already been converted from the
2352target language.  Because of this, the <tt>memberin</tt> typemap is
2353almost always combined with the use of an "in" typemap.  For example,
2354the "in" typemap in the previous section would be used to convert an
2355<tt>int[]</tt> array to C whereas the "memberin" typemap would be used
2356to copy the converted array into a C data structure.
2357</p>
2358
2359<H3><a name="Perl5_nn37"></a>31.8.5 Turning Perl references into C pointers</H3>
2360
2361
2362<p>
2363A frequent confusion on the SWIG mailing list is errors caused by the
2364mixing of Perl references and C pointers.  For example, suppose you
2365have a C function that modifies its arguments like this:
2366</p>
2367
2368<div class="code"><pre>
2369void add(double a, double b, double *c) {
2370	*c = a + b;
2371}
2372</pre></div>
2373
2374<p>
2375A common misinterpretation of this function is the following Perl script:
2376</p>
2377
2378<div class="targetlang"><pre>
2379# Perl script
2380$a = 3.5;
2381$b = 7.5;
2382$c = 0.0;          # Output value
2383add($a,$b,\$c);    # Place result in c (Except that it doesn't work)
2384</pre></div>
2385
2386<p>
2387To make this work with a reference, you can use a typemap such as this:
2388</p>
2389
2390<div class="code"><pre>
2391%typemap(in) double * (double dvalue) {
2392  SV* tempsv;
2393  if (!SvROK($input)) {
2394    croak("expected a reference\n");
2395  }
2396  tempsv = SvRV($input);
2397  if ((!SvNOK(tempsv)) &amp;&amp; (!SvIOK(tempsv))) {
2398    croak("expected a double reference\n");
2399  }
2400  dvalue = SvNV(tempsv);
2401  $1 = &amp;dvalue;
2402}
2403
2404%typemap(argout) double * {
2405  SV *tempsv;
2406  tempsv = SvRV($input);
2407  sv_setnv(tempsv, *$1);
2408}
2409</pre></div>
2410
2411<p>
2412Now, if you place this before the add function, you can do this:
2413</p>
2414
2415<div class="targetlang"><pre>
2416$a = 3.5;
2417$b = 7.5;
2418$c = 0.0;
2419add($a,$b,\$c);            # Now it works!
2420print "$c\n";
2421
2422</pre></div>
2423
2424<H3><a name="Perl5_nn38"></a>31.8.6 Pointer handling</H3>
2425
2426
2427<p>
2428Occasionally, it might be necessary to convert pointer values that have
2429been stored using the SWIG typed-pointer representation.  To convert a pointer from Perl to C, the following
2430function is used:
2431</p>
2432
2433<p>
2434<tt>
2435int SWIG_ConvertPtr(SV *obj, void **ptr, swig_type_info *ty, int flags)
2436</tt>
2437</p>
2438
2439<div class="indent">
2440Converts a Perl object <tt>obj</tt> to a C pointer.  The result of the conversion is placed
2441into the pointer located at <tt>ptr</tt>.  <tt>ty</tt> is a SWIG type descriptor structure.
2442<tt>flags</tt> is used to handle error checking and other aspects of conversion. <tt>flags</tt> is
2443currently undefined and reserved for future expansion.  Returns 0 on success and -1 on error.
2444</div>
2445
2446<p>
2447<tt>
2448void *SWIG_MakePtr(SV *obj, void *ptr, swig_type_info *ty, int flags)</tt>
2449</p>
2450
2451<div class="indent">
2452Creates a new Perl pointer object.  <tt>obj</tt> is a Perl SV that has been initialized to hold the result,
2453<tt>ptr</tt> is the pointer to convert, <tt>ty</tt> is the SWIG type descriptor structure that
2454describes the type, and <tt>flags</tt> is a flag that controls properties of the conversion.  <tt>flags</tt> is currently undefined
2455and reserved.
2456</div>
2457
2458<p>
2459Both of these functions require the use of a special SWIG
2460type-descriptor structure.  This structure contains information about
2461the mangled name of the datatype, type-equivalence information, as
2462well as information about converting pointer values under C++
2463inheritance.   For a type of <tt>Foo *</tt>, the type descriptor structure
2464is usually accessed as follows:
2465</p>
2466
2467<div class="code">
2468<pre>
2469Foo *f;
2470if (SWIG_ConvertPtr($input, (void **) &amp;f, SWIGTYPE_p_Foo, 0) == -1) return NULL;
2471
2472SV *sv = sv_newmortal();
2473SWIG_MakePtr(sv, f, SWIGTYPE_p_Foo, 0);
2474</pre>
2475</div>
2476
2477<p>
2478In a typemap, the type descriptor should always be accessed using the special typemap
2479variable <tt>$1_descriptor</tt>.  For example:
2480</p>
2481
2482<div class="code">
2483<pre>
2484%typemap(in) Foo * {
2485   if ((SWIG_ConvertPtr($input,(void **) &amp;$1, $1_descriptor,0)) == -1) return NULL;
2486}
2487</pre>
2488</div>
2489
2490<p>
2491If necessary, the descriptor for any type can be obtained using the <tt>$descriptor()</tt> macro in a typemap.
2492For example:
2493</p>
2494
2495<div class="code">
2496<pre>
2497%typemap(in) Foo * {
2498   if ((SWIG_ConvertPtr($input,(void **) &amp;$1, $descriptor(Foo *), 0)) == -1) return NULL;
2499}
2500</pre>
2501</div>
2502
2503<H2><a name="Perl5_nn39"></a>31.9 Proxy classes</H2>
2504
2505
2506<p>
2507<b>Out of date. Needs update.</b>
2508</p>
2509
2510<p>
2511Using the low-level procedural interface, SWIG can also construct a
2512high-level object oriented interface to C structures and C++ classes.
2513This is done by constructing a Perl proxy class (also known as a shadow class)
2514that provides an OO wrapper
2515to the underlying code.  This section describes the implementation
2516details of the proxy interface.
2517</p>
2518
2519<H3><a name="Perl5_nn40"></a>31.9.1 Preliminaries</H3>
2520
2521
2522<p>
2523Proxy classes, are generated by default. If you want to turn them off, use the <tt>-noproxy</tt> command line option.
2524For example:
2525</p>
2526
2527<div class="code">
2528<pre>
2529$ swig -c++ -perl -noproxy example.i
2530</pre>
2531</div>
2532
2533<p>
2534When proxy classes are used, SWIG moves all of the low-level procedural wrappers to
2535another package name.  By default, this package is named 'modulec' where 'module' is the name of the module
2536you provided with the <tt>%module</tt> directive.  Then, in place of the original module, 
2537SWIG creates a collection of high-leve