PageRenderTime 35ms CodeModel.GetById 13ms app.highlight 14ms RepoModel.GetById 1ms app.codeStats 0ms

/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

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

   1<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
   2<html>
   3<head>
   4<title>SWIG 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>
1937W…

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