1 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
4 <title>SWIG and Perl5</title>
5 <link rel="stylesheet" type="text/css" href="style.css">
8 <body bgcolor="#ffffff">
9 <H1><a name="Perl5"></a>28 SWIG and Perl5</H1>
11 <div class="sectiontoc">
13 <li><a href="#Perl5_nn2">Overview</a>
14 <li><a href="#Perl5_nn3">Preliminaries</a>
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>
24 <li><a href="#Perl5_nn11">Building Perl Extensions under Windows</a>
26 <li><a href="#Perl5_nn12">Running SWIG from Developer Studio</a>
27 <li><a href="#Perl5_nn13">Using other compilers</a>
29 <li><a href="#Perl5_nn14">The low-level interface</a>
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>
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>
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>
51 <li><a href="#Perl5_nn32">Typemap Examples</a>
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>
60 <li><a href="#Perl5_nn39">Proxy classes</a>
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>
70 <li><a href="#Perl5_nn47">Adding additional Perl code</a>
78 <b>Caution: This chapter is under repair!</b>
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.
90 <H2><a name="Perl5_nn2"></a>28.1 Overview</H2>
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.
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.
111 <H2><a name="Perl5_nn3"></a>28.2 Preliminaries</H2>
115 To build a Perl5 module, run Swig using the <tt>-perl</tt> option as
119 <div class="code"><pre>
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.
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.
136 <H3><a name="Perl5_nn4"></a>28.2.1 Getting the right header files</H3>
140 In order to compile, SWIG extensions need the following Perl5 header files :</p>
142 <div class="code"><pre>
149 These are typically located in a directory like this</p>
151 <div class="code"><pre>
152 /usr/lib/perl5/5.00503/i386-linux/CORE
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.
163 % perl -e 'use Config; print $Config{archlib};'
164 /usr/lib/perl5/5.00503/i386-linux
168 <H3><a name="Perl5_nn5"></a>28.2.2 Compiling a dynamic module</H3>
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):
177 <div class="code"><pre>
178 $ swig -perl example.i
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
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.
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.
201 <H3><a name="Perl5_nn6"></a>28.2.3 Building a dynamic module with MakeMaker</H3>
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>
209 <div class="targetlang"><pre>
211 use ExtUtils::MakeMaker;
213 `NAME' => `example', # Name of package
214 `LIBS' => [`-lm'], # Name of custom libraries
215 `OBJECT' => `example.o example_wrap.o' # Object files
221 Now, to build a module, simply follow these steps :</p>
223 <div class="code"><pre>
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>
235 <H3><a name="Perl5_nn7"></a>28.2.4 Building a static version of Perl</H3>
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>
244 <div class="code"><pre>
245 % swig -perl -static example.i
249 By default SWIG includes code for dynamic loading, but the
250 <tt>-static</tt> option takes it out.</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
258 <div class="targetlang"><pre>
262 extern double My_variable;
263 extern int fact(int);
266 // Include code for rebuilding Perl
267 %include <perlmain.i>
271 The same thing can be accomplished by running SWIG as follows :</p>
273 <div class="code"><pre>
274 % swig -perl -static -lperlmain.i example.i
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>
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:
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
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.
304 <H3><a name="Perl5_nn8"></a>28.2.5 Using the module</H3>
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:
312 <div class="targetlang"><pre>
315 print example::fact(4),"\n";
320 A common error received by first-time users is the following:
323 <div class="targetlang">
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.
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.
339 A somewhat related, but slightly different error is this:
342 <div class="targetlang">
345 Can't find 'boot_example' symbol in ./example.so
347 BEGIN failed--compilation aborted at - line 1.
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.
359 Another common error is the following:
362 <div class="targetlang">
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.
369 BEGIN failed--compilation aborted at - line 1.
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
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.
393 Finally, suppose that your extension module is linked with another library like this:
398 $ gcc -shared example.o example_wrap.o -L/home/beazley/projects/lib -lfoo \
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:
408 <div class="targetlang">
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.
415 BEGIN failed--compilation aborted at - line 1.
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:
431 $ gcc -shared example.o example_wrap.o -L/home/beazley/projects/lib -lfoo \
432 <b>-Xlinker -rpath /home/beazley/projects/lib \</b>
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
448 $ env LD_LIBRARY_PATH=/home/beazley/projects/lib perl
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
459 <H3><a name="Perl5_nn9"></a>28.2.6 Compilation problems and compiling with C++</H3>
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
470 On most machines, C++ extension modules should be linked using the C++
471 compiler. For example:
474 <div class="code"><pre>
475 % swig -c++ -perl example.i
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>
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:
487 <div class="code"><pre>
488 % swig -c++ -perl example.i
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>
495 Of course, the names of the extra libraries are completely non-portable---you will
496 probably need to do some experimentation.
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:
505 <div class="code"><pre>
506 % g++ -c example_wrap.cxx -I/usr/lib/perl/5.8.0/CORE -D_GNU_SOURCE
510 -D_GNU_SOURCE is also included in the Perl ccflags, which can be found by running
513 <div class="code"><pre>
514 % perl -e 'use Config; print $Config{ccflags};'
518 So you could also compile the wrapper like
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}'`
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.
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:
546 <b>libstdc++-libc6.1-1.so.2 => /usr/lib/libstdc++-libc6.1-1.so.2 (0x40019000)</b>
547 libm.so.6 => /lib/libm.so.6 (0x4005b000)
548 libc.so.6 => /lib/libc.so.6 (0x40077000)
549 /lib/ld-linux.so.2 => /lib/ld-linux.so.2 (0x40000000)
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.
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>
575 <li>Use <tt>-DHAS_BOOL</tt> when compiling the SWIG wrapper code
576 <li>Or use <tt>-Dbool=char</tt> when compiling.
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:
585 <div class="code"><pre>
586 #define do_open Perl_do_open
590 The problem is, in the <iostream> header from GNU libstdc++v3 there is a private
591 function named do_open. If <iostream> 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>.
602 <H3><a name="Perl5_nn10"></a>28.2.7 Compiling for 64-bit platforms</H3>
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.
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.
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).
629 <H2><a name="Perl5_nn11"></a>28.3 Building Perl Extensions under Windows</H2>
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.
640 <H3><a name="Perl5_nn12"></a>28.3.1 Running SWIG from Developer Studio</H3>
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>
649 <li>Open up a new workspace and use the AppWizard to select a DLL
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.
659 <li>Select the SWIG interface file and go to the settings menu. Under
660 settings, select the "Custom Build" option.
662 <li>Enter "SWIG" in the description field.
664 <li>Enter "<tt>swig -perl5 -o $(ProjDir)\$(InputName)_wrap.cxx
665 $(InputPath)</tt>" in the "Build command(s) field"
667 <li>Enter "<tt>$(ProjDir)\$(InputName)_wrap.c</tt>xx" in the "Output
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".
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.
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).
684 <li>Build your project.
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 :
695 <div class="targetlang"><pre>
698 $a = example::fact(4);
703 <H3><a name="Perl5_nn13"></a>28.3.2 Using other compilers</H3>
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.
711 <H2><a name="Perl5_nn14"></a>28.4 The low-level interface</H2>
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.
721 <H3><a name="Perl5_nn15"></a>28.4.1 Functions</H3>
725 C functions are converted into new Perl built-in commands (or
726 subroutines). For example:
729 <div class="targetlang"><pre>
739 <div class="targetlang"><pre>
741 $a = &example::fact(2);
744 <H3><a name="Perl5_nn16"></a>28.4.2 Global variables</H3>
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>
753 <div class="targetlang"><pre>
761 is accessed as follows :</p>
763 <div class="targetlang"><pre>
765 print $example::Spam,"\n";
766 $example::Spam = $example::Spam + 4
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
778 To make ordinary variables read-only, you can also use the <tt>%immutable</tt> directive. For example:
793 The <tt>%immutable</tt> directive stays in effect until it is explicitly disabled or cleared using
795 See the <a href="SWIG.html#SWIG_readonly_variables">Creating read-only variables</a> section for further details.
799 It is also possible to tag a specific variable as read-only like this:
810 extern char *path; // Declared later in the input
814 <H3><a name="Perl5_nn17"></a>28.4.3 Constants</H3>
818 By default, constants are wrapped as read-only Perl variables. For example:
833 <div class="targetlang">
836 print $example::FOO,"\n"; # OK
837 $example::FOO = 2; # Error
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:
847 <div class="targetlang">
850 print example::FOO,"\n";
854 <H3><a name="Perl5_nn18"></a>28.4.4 Pointers</H3>
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>
863 <div class="code"><pre>
864 Matrix *new_Matrix(int n, int m);
868 The module returns a value generated as follows:
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
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
882 To check to see if a value is the NULL pointer, use the
883 <tt>defined()</tt> command :</p>
885 <div class="targetlang"><pre>
887 print "Not a NULL pointer.";
889 print "Is a NULL pointer.";
895 To create a NULL pointer, you should pass the <tt>undef</tt> value to
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 :
910 <div class="targetlang"><pre>
912 print "a and b point to the same thing in C";
914 print "a and b point to different objects.";
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
934 Bar *FooToBar(Foo *f) {
939 Foo *BarToFoo(Bar *b) {
940 return dynamic_cast<Foo*>(b);
943 Foo *IncrFoo(Foo *f, int i) {
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.
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.
963 <H3><a name="Perl5_nn19"></a>28.4.5 Structures</H3>
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,
971 <div class="code"><pre>
978 gets mapped into the following collection of accessor functions:
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)
994 These functions are then used to access structure data from Perl as follows:
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
1004 Similar access is provided for unions and the data members of C++ classes.
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:
1017 int x; /* Read-only members */
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).
1034 Array members are normally wrapped as read-only. For example,
1046 produces a single accessor function like this:
1051 int *Foo_x_get(Foo *self) {
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).
1065 When structure members are wrapped, they are handled as pointers. For example,
1081 generates accessor functions such as this:
1086 Foo *Bar_f_get(Bar *b) {
1087 return &b->f;
1090 void Bar_f_set(Bar *b, Foo *val) {
1097 <H3><a name="Perl5_nn20"></a>28.4.6 C++ classes</H3>
1101 C++ classes are wrapped by building a set of low level accessor functions.
1102 Consider the following class :
1105 <div class="code"><pre>
1110 int search(char *item);
1111 void insert(char *item);
1112 void remove(char *item);
1115 static void print(List *l);
1120 When wrapped by SWIG, the following functions are created :
1123 <div class="code"><pre>
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);
1137 In Perl, these functions are used in a straightforward manner:
1140 <div class="targetlang"><pre>
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)
1150 print example::List_length_get($l),"\n";
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.
1162 <H3><a name="Perl5_nn21"></a>28.4.7 C++ classes and type-checking</H3>
1166 The SWIG type-checker is fully aware of C++ inheritance. Therefore, if you have
1176 class Bar : public Foo {
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).
1198 <H3><a name="Perl5_nn22"></a>28.4.8 C++ overloaded functions</H3>
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:
1208 /* Forward renaming declarations */
1209 %rename(foo_i) foo(int);
1210 %rename(foo_d) foo(double);
1212 void foo(int); // Becomes 'foo_i'
1213 void foo(char *c); // Stays 'foo' (not renamed)
1217 void foo(int); // Becomes 'foo_i'
1218 void foo(double); // Becomes 'foo_d'
1225 Now, in Perl, the methods are accessed as follows:
1228 <div class="targetlang">
1232 $s = example::new_Spam();
1233 example::Spam_foo_i($s,3);
1234 example::Spam_foo_d($s,3.14);
1239 Please refer to the "SWIG Basics" chapter for more information.
1242 <H3><a name="Perl5_nn23"></a>28.4.9 Operators</H3>
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.
1250 The following C++ operators are currently supported by the Perl module:
1254 <li>operator++ </li>
1255 <li>operator-- </li>
1260 <li>operator== </li>
1261 <li>operator!= </li>
1263 <li>operator> </li>
1264 <li>operator< </li>
1265 <li>operator and </li>
1266 <li>operator or </li>
1269 <H3><a name="Perl5_nn24"></a>28.4.10 Modules and packages</H3>
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 :
1278 <div class="targetlang"><pre>
1280 use example; # load the example module
1281 print example::fact(4),"\n" # Call a function in it
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.
1295 SWIG installs its functions into a package with the same name as
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>
1306 <div class="code"><pre>
1307 %module "Foo::Bar::Baz"
1311 <b>NOTE:</b> the double quotes are necessary.
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
1329 %module(package="XML::Xerces") "XML::Xerces::SAX
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>.
1344 This can be changed by giving SWIG the -package
1348 <div class="code"><pre>
1349 % swig -perl -package Foo example.i
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 :
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
1364 <H2><a name="Perl5_nn25"></a>28.5 Input and output parameters</H2>
1368 A common problem in some C programs is handling parameters passed as simple pointers. For
1374 void add(int x, int y, int *result) {
1386 int sub(int *x, int *y) {
1393 The easiest way to handle these situations is to use the <tt>typemaps.i</tt> file. For example:
1399 %include "typemaps.i"
1401 void add(int, int, int *OUTPUT);
1402 int sub(int *INPUT, int *INPUT);
1407 In Perl, this allows you to pass simple values. For example:
1410 <div class="targetlang">
1412 $a = example::add(3,4);
1415 $b = example::sub(7,4);
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.
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:
1434 %include "typemaps.i"
1436 %apply int *OUTPUT { int *result };
1437 %apply int *INPUT { int *x, int *y};
1439 void add(int x, int y, int *result);
1440 int sub(int *x, int *y);
1445 If a function mutates one of its parameters like this,
1450 void negate(int *x) {
1457 you can use <tt>INOUT</tt> like this:
1462 %include "typemaps.i"
1464 void negate(int *INOUT);
1469 In Perl, a mutated parameter shows up as a return value. For example:
1472 <div class="targetlang">
1474 $a = example::negate(3);
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:
1488 /* send message, return number of bytes sent, along with success code */
1489 int send_message(char *text, int len, int *success);
1494 To wrap such a function, simply use the <tt>OUTPUT</tt> rule above. For example:
1500 %include "typemaps.i"
1501 %apply int *OUTPUT { int *success };
1503 int send_message(char *text, int *success);
1508 When used in Perl, the function will return multiple values.
1511 <div class="targetlang">
1513 ($bytes, $success) = example::send_message("Hello World");
1518 Another common use of multiple return values are in query functions. For example:
1523 void get_dimensions(Matrix *m, int *rows, int *columns);
1528 To wrap this, you might use the following:
1534 %include "typemaps.i"
1535 %apply int *OUTPUT { int *rows, int *columns };
1537 void get_dimensions(Matrix *m, int *rows, *columns);
1545 <div class="targetlang">
1547 ($r,$c) = example::get_dimensions($m);
1552 In certain cases, it is possible to treat Perl references as C pointers. To do this, use the <tt>REFERENCE</tt> typemap. For
1559 %include "typemaps.i"
1561 void add(int x, int y, int *REFERENCE);
1569 <div class="targetlang">
1573 example::add(3,4,\$c);
1580 <b>Note:</b> The <tt>REFERENCE</tt> feature is only currently supported for numeric types (integers and floating point).
1583 <H2><a name="Perl5_nn26"></a>28.6 Exception handling</H2>
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
1594 <div class="code"><pre>
1595 class RangeError {}; // Used for an exception
1602 // Create a new array of fixed size
1603 DoubleArray(int size) {
1604 ptr = new double[size];
1611 // Return the length of the array
1616 // Get an item from the array and perform bounds checking.
1617 double getitem(int i) {
1618 if ((i >= 0) && (i < n))
1624 // Set an item in the array and perform bounds checking.
1625 void setitem(int i, double val) {
1626 if ((i >= 0) && (i < n))
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
1642 <div class="code"><pre>
1647 catch (RangeError) {
1648 croak("Array index out-of-bounds");
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.
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:
1673 %exception getitem {
1677 catch (RangeError) {
1678 croak("Array index out-of-bounds");
1682 %exception setitem {
1686 catch (RangeError) {
1687 croak("Array index out-of-bounds");
1694 In this case, the exception handler is only attached to methods and functions
1695 named <tt>getitem</tt> and <tt>setitem</tt>.
1699 If you had a lot of different methods, you can avoid extra typing by using a macro.
1710 catch (RangeError) {
1711 croak("Array index out-of-bounds");
1716 %exception getitem RANGE_ERROR;
1717 %exception setitem RANGE_ERROR;
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.
1727 <b>Compatibility note:</b> In SWIG1.1, exceptions were defined using the older <tt>%except</tt> directive:
1736 catch (RangeError) {
1737 croak("Array index out-of-bounds");
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.
1748 <H2><a name="Perl5_nn27"></a>28.7 Remapping datatypes with typemaps</H2>
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.
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
1765 <H3><a name="Perl5_nn28"></a>28.7.1 A simple typemap example</H3>
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:
1774 <div class="code"><pre>
1778 $1 = (int) SvIV($input);
1779 printf("Received an integer : %d\n", $1);
1783 extern int fact(int n);
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>).
1799 When this example is used in Perl5, it will operate as follows :
1802 <div class="targetlang"><pre>
1804 $n = example::fact(6);
1809 Received an integer : 6
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:
1821 <div class="targetlang">
1823 %typemap(in) int n {
1824 $1 = (int) SvIV($input);
1825 printf("n = %d\n",$1);
1828 typedef int Integer;
1829 extern int fact(Integer n); // Above typemap is applied
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
1841 Typemaps can also be defined for groups of consecutive arguments. For example:
1844 <div class="targetlang">
1846 %typemap(in) (char *str, unsigned len) {
1847 $1 = SvPV($input,$2);
1850 int count(char c, char *str, unsigned len);
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):
1860 <div class="targetlang">
1862 example::count("e","Hello World");
1869 <H3><a name="Perl5_nn29"></a>28.7.2 Perl5 typemaps</H3>
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
1880 <div class="targetlang">
1883 $result = sv_newmortal();
1884 set_setiv($result, (IV) $1);
1891 The following typemap methods are available:
1895 <tt>%typemap(in)</tt>
1898 <div class="indent">
1899 Converts Perl5 object to input function arguments.
1903 <tt>%typemap(out)</tt>
1906 <div class="indent">
1907 Converts function return value to a Perl5 value.
1911 <tt>%typemap(varin)</tt>
1914 <div class="indent">
1915 Converts a Perl5 object to a global variable.
1919 <tt>%typemap(varout)</tt>
1922 <div class="indent">
1923 Converts a global variable to a Perl5 object.
1927 <tt>%typemap(freearg)</tt>
1930 <div class="indent">
1931 Cleans up a function argument after a function call
1935 <tt>%typemap(argout)</tt>
1938 <div class="indent">
1939 Output argument handling
1943 <tt>%typemap(ret)</tt>
1946 <div class="indent">
1947 Clean up return value from a function.
1951 <tt>%typemap(memberin)</tt>
1954 <div class="indent">
1955 Setting of C++ member data (all languages).
1959 <tt>%typemap(memberout)</tt>
1962 <div class="indent">
1963 Return of C++ member data (all languages).
1967 <tt>%typemap(check)</tt>
1970 <div class="indent">
1971 Check value of input parameter.
1974 <H3><a name="Perl5_nn30"></a>28.7.3 Typemap variables</H3>
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:
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.
1998 <div class="indent">
1999 A Perl object holding the value of an argument of variable value.
2006 <div class="indent">
2007 A Perl object that holds the result to be returned to Perl.
2014 <div class="indent">
2015 The parameter name that was matched.
2022 <div class="indent">
2023 The actual C datatype matched by the typemap.
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
2041 <div class="indent">
2042 The Perl name of the wrapper function being created.
2045 <H3><a name="Perl5_nn31"></a>28.7.4 Useful functions</H3>
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.
2059 <b>Perl Integer Functions</b>
2065 void sv_setiv(SV *sv, IV value);
2066 SV *newSViv(IV value);
2072 <b>Perl Floating Point Functions</b>
2078 void sv_setnv(SV *, double value);
2079 SV *newSVnv(double value);
2085 <b>Perl String Functions</b>
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);
2095 void sv_catpv(SV *, char *);
2096 void sv_catpvn(SV *, char *, STRLEN);
2101 <b>Perl References</b>
2106 void sv_setref_pv(SV *, char *, void *ptr);
2107 int sv_isobject(SV *);
2109 int sv_isa(SV *, char *0;
2114 <H2><a name="Perl5_nn32"></a>28.8 Typemap Examples</H2>
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
2123 <H3><a name="Perl5_nn33"></a>28.8.1 Converting a Perl5 array to a char **</H3>
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.
2133 <div class="code"><pre>
2136 // This tells SWIG to treat char ** as a special case
2137 %typemap(in) char ** {
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 <= len; i++) {
2150 tv = av_fetch(tempav, i, 0);
2151 $1[i] = (char *) SvPV(*tv,PL_na);
2156 // This cleans up the char ** array after the function call
2157 %typemap(freearg) char ** {
2161 // Creates a new Perl array and places a NULL-terminated char ** into it
2162 %typemap(out) char ** {
2166 /* Figure out how many elements we have */
2169 svs = (SV **) malloc(len*sizeof(SV *));
2170 for (i = 0; i < len ; i++) {
2171 svs[i] = sv_newmortal();
2172 sv_setpv((SV*)svs[i],$1[i]);
2174 myav = av_make(len,svs);
2176 $result = newRV_noinc((SV*)myav);
2177 sv_2mortal($result);
2181 // Now a few test functions
2183 int print_args(char **argv) {
2186 printf("argv[%d] = %s\n", i,argv[i]);
2192 // Returns a char ** list
2194 static char *values[] = { "Dave", "Mike", "Susan", "John", "Michelle", 0};
2195 return &values[0];
2202 When this module is compiled, the wrapped C functions can be used in a
2203 Perl script as follows :
2206 <div class="targetlang"><pre>
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
2215 <H3><a name="Perl5_nn34"></a>28.8.2 Return values</H3>
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.
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 :
2233 <div class="code"><pre>
2234 %typemap(argout) int *OUTPUT {
2235 if (argvi >= items) {
2236 EXTEND(sp,1); /* Extend the stack by 1 object */
2238 $result = sv_newmortal();
2239 sv_setiv($target,(IV) *($1));
2244 <H3><a name="Perl5_nn35"></a>28.8.3 Returning values from arguments</H3>
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.
2252 <div class="code"><pre>
2255 // This tells SWIG to treat an double * argument with name 'OutDouble' as
2258 %typemap(argout) double *OUTPUT {
2259 $result = sv_newmortal();
2260 sv_setnv($result, *$input);
2261 argvi++; /* Increment return count -- important! */
2264 // We don't care what the input value is. Ignore, but set to a temporary variable
2266 %typemap(in,numinputs=0) double *OUTPUT(double junk) {
2270 // Now a function to test it
2272 /* Returns the first two input arguments */
2273 int multout(double a, double b, double *out1, double *out2) {
2280 // If we name both parameters OutDouble both will be output
2282 int multout(double a, double b, double *OUTPUT, double *OUTPUT);
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.
2292 <div class="targetlang"><pre>
2294 print "multout(7,13) = @r\n";
2295 ($x,$y) = multout(7,13);
2298 <H3><a name="Perl5_nn36"></a>28.8.4 Accessing array structure members</H3>
2302 Consider the following data structure :
2305 <div class="code"><pre>
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.
2321 <div class="code"><pre>
2322 %typemap(memberin) int [SIZE] {
2324 for (i = 0; i < SIZE; i++) {
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
2338 As in the previous example, the typemap can be generalized for any dimension.
2342 <div class="code"><pre>
2343 %typemap(memberin) int [ANY] {
2345 for (i = 0; i < $1_dim0; i++) {
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.
2361 <H3><a name="Perl5_nn37"></a>28.8.5 Turning Perl references into C pointers</H3>
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 :
2370 <div class="code"><pre>
2371 void add(double a, double b, double *c) {
2377 A common misinterpretation of this function is the following Perl script :
2380 <div class="targetlang"><pre>
2384 $c = 0.0; # Output value
2385 add($a,$b,\$c); # Place result in c (Except that it doesn't work)
2389 To make this work with a reference, you can use a typemap such as this:
2392 <div class="code"><pre>
2393 %typemap(in) double * (double dvalue) {
2395 if (!SvROK($input)) {
2396 croak("expected a reference\n");
2398 tempsv = SvRV($input);
2399 if ((!SvNOK(tempsv)) && (!SvIOK(tempsv))) {
2400 croak("expected a double reference\n");
2402 dvalue = SvNV(tempsv);
2406 %typemap(argout) double * {
2408 tempsv = SvRV($input);
2409 sv_setnv(tempsv, *$1);
2414 Now, if you place this before the add function, you can do this :
2417 <div class="targetlang"><pre>
2421 add($a,$b,\$c); # Now it works!
2426 <H3><a name="Perl5_nn38"></a>28.8.6 Pointer handling</H3>
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
2437 int SWIG_ConvertPtr(SV *obj, void **ptr, swig_type_info *ty, int flags)
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.
2450 void *SWIG_MakePtr(SV *obj, void *ptr, swig_type_info *ty, int flags)</tt>
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
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:
2472 if (SWIG_ConvertPtr($input, (void **) &f, SWIGTYPE_p_Foo, 0) == -1) return NULL;
2474 SV *sv = sv_newmortal();
2475 SWIG_MakePtr(sv, f, SWIGTYPE_p_Foo, 0);
2480 In a typemap, the type descriptor should always be accessed using the special typemap
2481 variable <tt>$1_descriptor</tt>. For example:
2486 %typemap(in) Foo * {
2487 if ((SWIG_ConvertPtr($input,(void **) &$1, $1_descriptor,0)) == -1) return NULL;
2493 If necessary, the descriptor for any type can be obtained using the <tt>$descriptor()</tt> macro in a typemap.
2499 %typemap(in) Foo * {
2500 if ((SWIG_ConvertPtr($input,(void **) &$1, $descriptor(Foo *), 0)) == -1) return NULL;
2505 <H2><a name="Perl5_nn39"></a>28.9 Proxy classes</H2>
2509 <b>Out of date. Needs update.</b>
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.
2521 <H3><a name="Perl5_nn40"></a>28.9.1 Preliminaries</H3>
2525 Proxy classes, are generated by default. If you want to turn them off, use the <tt>-noproxy</tt> command line option.
2531 $ swig -c++ -perl -noproxy example.i
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.
2543 <H3><a name="Perl5_nn41"></a>28.9.2 Structure and class wrappers</H3>
2547 Suppose you have the following SWIG interface file :
2550 <div class="code"><pre>
2553 Vector(double x, double y, double z);
2561 When wrapped, SWIG creates the following set of low-level accessor
2562 functions as described in previous sections.
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);
2578 However, when proxy classes are enabled, these accessor functions are
2579 wrapped inside a Perl class like this:
2582 <div class="targetlang"><pre>
2583 package example::Vector;
2584 @ISA = qw( example );
2586 %BLESSEDMEMBERS = ();
2591 $self = vectorc::new_Vector(@args);
2592 return undef if (!defined($self));
2593 bless $self, "example::Vector";
2596 tie %retval, "example::Vector", $self;
2597 return bless \%retval,"Vector";
2601 return unless $_[0]->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};
2610 my ($self,$field) = @_;
2611 my $member_func = "vectorc::Vector_${field}_get";
2612 my $val = &$member_func($self);
2613 if (exists $BLESSEDMEMBERS{$field}) {
2614 return undef if (!defined($val));
2616 tie %retval,$BLESSEDMEMBERS{$field},$val;
2617 return bless \%retval, $BLESSEDMEMBERS{$field};
2623 my ($self,$field,$newval) = @_;
2624 my $member_func = "vectorc::Vector_${field}_set";
2625 if (exists $BLESSEDMEMBERS{$field}) {
2626 &$member_func($self,tied(%{$newval}));
2628 &$member_func($self,$newval);
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.
2645 To use our new proxy class we can simply do the following:
2648 <div class="targetlang"><pre>
2649 # Perl code using Vector class
2650 $v = new Vector(2,3,4);
2651 $w = Vector->new(-1,-2,-3);
2653 # Assignment of a single member
2656 # Assignment of all members
2669 <H3><a name="Perl5_nn42"></a>28.9.3 Object Ownership</H3>
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 :
2678 <div class="code"><pre>
2679 Vector *Vector_get(Vector *v, int index) {
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
2691 <div class="code"><pre>
2692 Vector *new_Vector(double x, double y, double z) {
2694 v = new Vector(x,y,z); // Call C++ constructor
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
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).
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.
2733 <div class="targetlang"><pre>
2734 # Perl code to change ownership of an object
2735 $v = new Vector(x,y,z);
2740 To acquire ownership of an object, the <tt>ACQUIRE</tt> method can be used.
2743 <div class="targetlang"><pre>
2744 # Given Perl ownership of a file
2745 $u = Vector_get($v);
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.
2756 <H3><a name="Perl5_nn43"></a>28.9.4 Nested Objects</H3>
2760 Suppose that we have a new object that looks like this :
2763 <div class="code"><pre>
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) :
2780 <div class="targetlang"><pre>
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
2799 This implementation allows us to operate on nested structures as follows :
2802 <div class="targetlang"><pre>
2803 # Perl access of nested structure
2804 $p = new Particle();
2805 $p->{f}->{x} = 0.0;
2806 %${$p->{v}} = ( x=>0, y=>0, z=>0);
2809 <H3><a name="Perl5_nn44"></a>28.9.5 Proxy Functions</H3>
2813 When functions take arguments involving a complex object, it is
2814 sometimes necessary to write a proxy function. For example :
2817 <div class="code"><pre>
2818 double dot_product(Vector *v1, Vector *v2);
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
2828 <div class="targetlang"><pre>
2831 $args[0] = tied(%{$args[0]}); # Get the real pointer values
2832 $args[1] = tied(%{$args[1]});
2833 my $result = vectorc::dot_product(@args);
2839 This function replaces the original function, but operates in an
2843 <H3><a name="Perl5_nn45"></a>28.9.6 Inheritance</H3>
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
2852 <div class="code"><pre>
2854 // SWIG interface file for shapes class
2862 virtual double area() = 0;
2863 virtual double perimeter() = 0;
2864 void set_location(double x, double y);
2866 class Circle : public Shape {
2868 Circle(double radius);
2873 class Square : public Shape {
2875 Square(double size);
2884 The resulting, Perl wrapper class will create the following code :
2887 <div class="targetlang"><pre>
2892 @ISA = (shapes Shape);
2895 @ISA = (shapes Shape);
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.
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).
2919 <H3><a name="Perl5_nn46"></a>28.9.7 Modifying the proxy methods</H3>
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:
2928 <div class="targetlang"><pre>
2929 /* Let's make the constructor of the class Square more verbose */
2930 %feature("shadow") Square(double w)
2934 my $self = examplec::new_Square(@_);
2935 print STDERR "Constructed an @{[ref($self)]}\n";
2936 bless $self, $pkg if defined($self);
2947 <H2><a name="Perl5_nn47"></a>28.10 Adding additional Perl code</H2>
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.
2959 void set_transform(Image *im, double x[4][4]);
2962 /* Rewrite the high level interface to set_transform */
2967 my $a = new_mat44();
2968 for (my $i = 0; $i < 4, $i++)
2970 for (my $j = 0; $j < 4, $j++)
2972 mat44_set($a, $i, $j, $x->[i][j])
2975 example.set_transform($im, $a);
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:
2987 <div class="targetlang">
2994 set_transform($im, $a);