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