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