PageRenderTime 7ms CodeModel.GetById 18ms app.highlight 20ms RepoModel.GetById 0ms app.codeStats 1ms

/tags/rel-1-3-29/SWIG/Doc/Manual/Perl5.html

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