4
4
<title>SWIG and Perl5</title>
5
<link rel="stylesheet" type="text/css" href="style.css">
7
8
<body bgcolor="#ffffff">
8
9
<H1><a name="Perl5"></a>23 SWIG and Perl5</H1>
11
<div class="sectiontoc">
11
13
<li><a href="#Perl5_nn2">Overview</a>
12
14
<li><a href="#Perl5_nn3">Preliminaries</a>
84
89
<H2><a name="Perl5_nn2"></a>23.1 Overview</H2>
87
93
To build Perl extension modules, SWIG uses a layered approach. At
88
94
the lowest level, simple procedural wrappers are generated for
89
95
functions, classes, methods, and other declarations in the input file.
90
96
Then, for structures and classes, an optional collection of Perl
91
97
proxy classes can be generated in order to provide a more natural object oriented Perl
92
98
interface. These proxy classes simply build upon the low-level interface.
95
102
In describing the Perl interface, this chapter begins by covering the
118
<div class="code"><pre>
112
119
swig -perl example.i
116
124
This produces two files. The first file, <tt>example_wrap.c</tt>
117
125
contains all of the C code needed to build a Perl5 module. The second
118
126
file, <tt>example.pm</tt> contains supporting Perl code needed to
119
127
properly load the module.
122
131
To build the module, you will need to compile the file
130
139
In order to compile, SWIG extensions need the following Perl5 header files :</p>
141
<div class="code"><pre>
133
142
#include "Extern.h"
134
143
#include "perl.h"
135
144
#include "XSUB.h"
139
148
These are typically located in a directory like this</p>
150
<div class="code"><pre>
142
151
/usr/lib/perl5/5.00503/i386-linux/CORE
146
155
The SWIG configuration script automatically tries to locate this directory so
148
157
loaded, an easy way to find out is to run Perl itself.
153
162
% perl -e 'use Config; print $Config{archlib};'
154
163
/usr/lib/perl5/5.00503/i386-linux
158
167
<H3><a name="Perl5_nn5"></a>23.2.2 Compiling a dynamic module</H3>
161
171
The preferred approach to building an extension module is to compile it into
162
172
a shared object file or DLL. To do this, you will need to compile your program
163
173
using comands like this (shown for Linux):
176
<div class="code"><pre>
166
177
$ swig -perl example.i
168
179
% gcc -c example_wrap.c -I/usr/lib/perl5/5.00503/i386-linux/CORE -Dbool=char
169
180
% gcc -shared example.o example_wrap.o -o example.so
172
184
The exact compiler options vary from platform to platform.
173
185
SWIG tries to guess the right options when it is installed. Therefore,
174
186
you may want to start with one of the examples in the <tt>SWIG/Examples/perl5</tt>
201
214
`OBJECT' => `example.o example_wrap.o' # Object files
207
220
Now, to build a module, simply follow these steps :</p>
222
<div class="code"><pre>
210
223
% perl Makefile.PL
216
229
If you are planning to distribute a SWIG-generated module, this is
227
240
interpreter with your SWIG extensions added to it. To build a static
228
241
extension, you first need to invoke SWIG as follows :</p>
243
<div class="code"><pre>
231
244
% swig -perl -static example.i
235
248
By default SWIG includes code for dynamic loading, but the
241
254
this may sound daunting, SWIG can do this for you automatically as
257
<div class="code"><pre>
247
261
extern double My_variable;
248
262
extern int fact(int);
250
265
// Include code for rebuilding Perl
251
266
%include perlmain.i
255
270
The same thing can be accomplished by running SWIG as follows :</p>
272
<div class="code"><pre>
258
273
% swig -perl -static -lperlmain.i example.i
262
277
The <tt>permain.i</tt> file inserts Perl's <tt>main()</tt> function
273
288
for a dynamic module, but change the link line to something like this:
291
<div class="code"><pre>
277
292
% gcc example.o example_wrap.o -L/usr/lib/perl5/5.00503/i386-linux/CORE \
278
293
-lperl -lsocket -lnsl -lm -o myperl
282
297
This will produce a new version of Perl called <tt>myperl</tt>. It
293
308
all goes well, you will be able to do this:
311
<div class="code"><pre>
299
314
print example::fact(4),"\n";
303
319
A common error received by first-time users is the following:
308
325
Can't locate example.pm in @INC (@INC contains: /usr/lib/perl5/5.00503/i386-lin
310
327
rl5/site_perl/5.005 .) at - line 1.
311
328
BEGIN failed--compilation aborted at - line 1.
315
333
This error is almost caused when the name of the shared object file you created doesn't match the module name
316
334
you specified with the <tt>%module</tt> directive.
319
338
A somewhat related, but slightly different error is this:
325
344
Can't find 'boot_example' symbol in ./example.so
327
346
BEGIN failed--compilation aborted at - line 1.
331
351
This error is generated because Perl can't locate the module bootstrap function in the
332
352
SWIG extension module. This could be caused by a mismatch between the module name and the shared library name.
333
353
However, another possible cause is forgetting to link the SWIG-generated wrapper code with the rest
334
354
of your application when you linked the extension module.
337
358
Another common error is the following:
343
364
Can't load './example.so' for module example: ./example.so:
347
368
BEGIN failed--compilation aborted at - line 1.
351
373
This error usually indicates that you forgot to include some object
352
374
files or libraries in the linking of the shared library file. Make
353
375
sure you compile both the SWIG wrapper file and your original program
354
376
into a shared library file. Make sure you pass all of the required libraries
358
381
Sometimes unresolved symbols occur because a wrapper has been created
369
392
Finally, suppose that your extension module is linked with another library like this:
374
397
$ gcc -shared example.o example_wrap.o -L/home/beazley/projects/lib -lfoo \
379
403
If the <tt>foo</tt> library is compiled as a shared library, you might get the following
380
404
error when you try to use your module:
385
410
Can't load './example.so' for module example: libfoo.so: cannot open shared object file:
389
414
BEGIN failed--compilation aborted at - line 1.
394
420
This error is generated because the dynamic linker can't locate the
395
421
<tt>libfoo.so</tt> library. When shared libraries are loaded, the
396
422
system normally only checks a few standard locations such as
397
423
<tt>/usr/lib</tt> and <tt>/usr/local/lib</tt>. To get the loader to look in other
398
424
locations, there are several things you can do. First, you can recompile your extension
399
425
module with extra path information. For example, on Linux you can do this:
403
430
$ gcc -shared example.o example_wrap.o -L/home/beazley/projects/lib -lfoo \
404
431
<b>-Xlinker -rpath /home/beazley/projects/lib \</b>
409
437
Alternatively, you can set the <tt>LD_LIBRARY_PATH</tt> environment
410
438
variable to include the directory with your shared libraries. If
411
439
setting <tt>LD_LIBRARY_PATH</tt>, be aware that setting this variable
412
440
can introduce a noticeable performance impact on all other
413
441
applications that you run. To set it only for Perl, you might want
414
442
to do this instead:
418
447
$ env LD_LIBRARY_PATH=/home/beazley/projects/lib perl
422
452
Finally, you can use a command such as <tt>ldconfig</tt> (Linux) or
423
453
<tt>crle</tt> (Solaris) to add additional search paths to the default
424
454
system configuration (this requires root access and you will need to
425
455
read the man pages).
427
458
<H3><a name="Perl5_nn9"></a>23.2.6 Compilation problems and compiling with C++</H3>
430
462
Compilation of C++ extensions has traditionally been a tricky problem.
431
463
Since the Perl interpreter is written in C, you need to take steps to
432
464
make sure C++ is properly initialized and that modules are compiled
436
469
On most machines, C++ extension modules should be linked using the C++
437
470
compiler. For example:
473
<div class="code"><pre>
441
474
% swig -c++ -perl example.i
442
475
% g++ -c example.cxx
443
476
% g++ -c example_wrap.cxx -I/usr/lib/perl5/5.00503/i386-linux/CORE
444
477
% <b>g++ -shared example.o example_wrap.o -o example.so</b>
448
481
In addition to this, you may need to include additional library
450
483
Solaris, you often need to add an extra library <tt>-lCrun</tt> like this:
486
<div class="code"><pre>
454
487
% swig -c++ -perl example.i
455
488
% g++ -c example.cxx
456
489
% g++ -c example_wrap.cxx -I/usr/lib/perl5/5.00503/i386-linux/CORE
457
490
% g++ -shared example.o example_wrap.o -o example.so <b>-lCrun</b>
460
494
Of course, the names of the extra libraries are completely non-portable---you will
461
495
probably need to do some experimentation.
464
499
Another possible compile problem comes from recent versions of Perl (5.8.0) and the GNU tools.
466
501
it needs to be. So you should compile the wrapper like:
504
<div class="code"><pre>
470
505
% g++ -c example_wrap.cxx -I/usr/lib/perl/5.8.0/CORE -D_GNU_SOURCE
473
509
-D_GNU_SOURCE is also included in the Perl ccflags, which can be found by running
512
<div class="code"><pre>
475
513
% perl -e 'use Config; print $Config{ccflags};'
477
517
So you could also compile the wrapper like
520
<div class="code"><pre>
479
521
% g++ -c example_wrap.cxx -I/usr/lib/perl/5.8.0/CORE \
480
522
`perl -e 'use Config; print $Config{ccflags}'`
484
526
Sometimes people have suggested that it is necessary to relink the
539
581
/usr/lib/perl/5.8.0/CORE/embed.h there is a line:
584
<div class="code"><pre>
543
585
#define do_open Perl_do_open
546
589
The problem is, in the <iostream> header from GNU libstdc++v3 there is a private
547
590
function named do_open. If <iostream> is included after the perl headers, then
548
591
the Perl macro causes the iostream do_open to be renamed, which causes compile errors.
553
596
in Lib/perl5/noembed.h while compiling the wrapper, you will
554
597
have to find the macro that conflicts and add an #undef into the .i file. Please report
555
598
any conflicting macros you find to <a href="http://www.swig.org/mail.html">swig mailing list</a>.
557
601
<H3><a name="Perl5_nn10"></a>23.2.7 Compiling for 64-bit platforms</H3>
560
605
On platforms that support 64-bit applications (Solaris, Irix, etc.),
561
606
special care is required when building extension modules. On these
562
607
machines, 64-bit applications are compiled and linked using a different
563
608
set of compiler/linker options. In addition, it is not generally possible to mix
564
609
32-bit and 64-bit code together in the same application.
567
613
To utilize 64-bits, the Perl executable will need to be recompiled
582
628
<H2><a name="Perl5_nn11"></a>23.3 Building Perl Extensions under Windows</H2>
585
632
Building a SWIG extension to Perl under Windows is roughly
586
633
similar to the process used with Unix. Normally, you will want to
587
634
produce a DLL that can be loaded into the Perl interpreter. This
588
635
section assumes you are using SWIG with Microsoft Visual C++
589
636
although the procedure may be similar with other compilers.
591
639
<H3><a name="Perl5_nn12"></a>23.3.1 Running SWIG from Developer Studio</H3>
643
691
use the use command as normal. For example :
694
<div class="code"><pre>
649
697
$a = example::fact(4);
654
702
<H3><a name="Perl5_nn13"></a>23.3.2 Using other compilers</H3>
657
706
SWIG is known to work with Cygwin and may work with other compilers on Windows.
658
707
For general hints and suggestions refer to the <a href="Windows.html#Windows">Windows</a> chapter.
660
710
<H2><a name="Perl5_nn14"></a>23.4 The low-level interface</H2>
663
714
At its core, the Perl module uses a simple low-level interface
664
715
to C function, variables, constants, and classes. This low-level interface
665
716
can be used to control your application. However, it is also used to
666
717
construct more user-friendly proxy classes as described in the next section.
668
720
<H3><a name="Perl5_nn15"></a>23.4.1 Functions</H3>
697
749
that intercept read/write operations and attaches them to a Perl variable with
698
750
the same name as the C global variable. Thus, an interface like this </p>
752
<div class="code"><pre>
708
760
is accessed as follows :</p>
762
<div class="code"><pre>
712
764
print $example::Spam,"\n";
713
765
$example::Spam = $example::Spam + 4
719
771
If a variable is declared as <tt>const</tt>, it is wrapped as a
725
777
To make ordinary variables read-only, you can also use the <tt>%immutable</tt> directive. For example:
731
786
extern char *path;
736
The <tt>%immutable</tt> directive stays in effect until it is explicitly disabled using
737
<tt>%mutable</tt>. It is also possible to tag a specific variable as read-only like this:
792
The <tt>%immutable</tt> directive stays in effect until it is explicitly disabled or cleared using
794
See the <a href="SWIG.html#SWIG_readonly_variables">Creatng read-only variables</a> section for further details.
798
It is also possible to tag a specific variable as read-only like this:
744
809
extern char *path; // Declared later in the input
748
813
<H3><a name="Perl5_nn17"></a>23.4.3 Constants</H3>
751
817
Constants are wrapped as read-only Perl variables. For example:
766
835
print $example::FOO,"\n"; # OK
767
836
$example::FOO = 2; # Error
771
840
<H3><a name="Perl5_nn18"></a>23.4.4 Pointers</H3>
777
846
information attached to it indicating what kind of reference it
778
847
is. That is, if you have a C declaration like this :</p>
849
<div class="code"><pre>
781
850
Matrix *new_Matrix(int n, int m);
785
854
The module returns a value generated as follows:
857
<div class="code"><pre>
789
858
$ptr = new_Matrix(int n, int m); # Save pointer return result
790
859
bless $ptr, "p_Matrix"; # Bless it as a pointer to Matrix
794
863
SWIG uses the "blessing" to check the datatype of various pointers.
799
868
To check to see if a value is the NULL pointer, use the
800
869
<tt>defined()</tt> command :</p>
871
<div class="code"><pre>
803
872
if (defined($ptr)) {
804
873
print "Not a NULL pointer.";
806
875
print "Is a NULL pointer.";
812
881
To create a NULL pointer, you should pass the <tt>undef </tt>value to
824
893
dereference them as follows :
896
<div class="code"><pre>
828
897
if ($$a == $$b) {
829
898
print "a and b point to the same thing in C";
831
900
print "a and b point to different objects.";
836
906
As much as you might be inclined to modify a pointer value directly
837
907
from Perl, don't. Manipulating pointer values is architecture dependent and
838
908
could cause your program to crash. Similarly, don't try to manually cast
865
937
Also, if working with C++, you should always try
866
938
to use the new C++ style casts. For example, in the above code, the
867
939
C-style cast may return a bogus result whereas as the C++-style cast will return
868
940
<tt>NULL</tt> if the conversion can't be performed.
871
944
<b>Compatibility Note:</b> In earlier versions, SWIG tried to preserve the same pointer naming conventions
881
954
accessor functions as described in the "SWIG Basics" chapter. For example,
957
<div class="code"><pre>
891
964
gets mapped into the following collection of accessor functions:
967
<div class="code"><pre>
895
968
struct Vector *new_Vector();
896
969
void delete_Vector(Vector *v);
897
970
double Vector_x_get(Vector *obj)
901
974
double Vector_z_get(Vector *obj)
902
975
void Vector_z_set(Vector *obj, double z)
907
980
These functions are then used to access structure data from Perl as follows:
983
<div class="code"><pre>
911
984
$v = example::new_Vector();
912
985
print example::Vector_x_get($v),"\n"; # Get x component
913
986
example::Vector_x_set($v,7.8); # Change x component
917
990
Similar access is provided for unions and the data members of C++ classes.
947
1020
Array members are normally wrapped as read-only. For example,
958
1032
produces a single accessor function like this:
962
1037
int *Foo_x_get(Foo *self) {
963
1038
return self->x;
968
1044
If you want to set an array member, you will need to supply a "memberin" typemap
969
1045
described later in this chapter. As a special case, SWIG does generate
970
1046
code to set array members of type <tt>char</tt> (allowing you to store a Python
971
1047
string in the structure).
974
1051
When structure members are wrapped, they are handled as pointers. For example,
1022
1101
static void print(List *l);
1027
1106
When wrapped by SWIG, the following functions are created :
1109
<div class="code"><pre>
1031
1110
List *new_List();
1032
1111
void delete_List(List *l);
1033
1112
int List_search(List *l, char *item);
1038
1117
void List_length_set(List *l, int n);
1039
1118
void List_print(List *l);
1043
1123
In Perl, these functions are used in a straightforward manner:
1126
<div class="code"><pre>
1047
1128
$l = example::new_List();
1048
1129
example::List_insert($l,"Ale");
1055
1136
print example::List_length_get($l),"\n";
1059
1141
At this low level, C++ objects are really just typed pointers. Member
1060
1142
functions are accessed by calling a C-like wrapper with an instance pointer
1061
1143
as the first argument. Although this interface is fairly primitive, it
1062
1144
provides direct access to C++ objects. A higher level interface using Perl proxy classes
1063
1145
can be built using these low-level accessors. This is described shortly.
1065
1148
<H3><a name="Perl5_nn21"></a>23.4.7 C++ classes and type-checking</H3>
1068
1152
The SWIG type-checker is fully aware of C++ inheritance. Therefore, if you have
1069
1153
classes like this
1087
1174
void spam(Foo *f);
1091
1179
then the function <tt>spam()</tt> accepts <tt>Foo *</tt> or a pointer to any class derived from <tt>Foo</tt>.
1092
1180
If necesssary, the type-checker also adjusts the value of the pointer (as is necessary when
1093
1181
multiple inheritance is used).
1095
1184
<H3><a name="Perl5_nn22"></a>23.4.8 C++ overloaded functions</H3>
1098
1188
If you have a C++ program with overloaded functions or methods, you will need to disambiguate
1099
1189
those methods using <tt>%rename</tt>. For example:
1103
1194
/* Forward renaming declarations */
1104
1195
%rename(foo_i) foo(int);
1126
1219
example::Spam_foo_i($s,3);
1127
1220
example::Spam_foo_d($s,3.14);
1131
1225
Please refer to the "SWIG Basics" chapter for more information.
1133
1228
<H3><a name="Perl5_nn23"></a>23.4.9 Operators</H3>
1136
1232
C++ operators can also be wrapped using the <tt>%rename</tt> directive. All you need to do is
1137
1233
give the operator the name of a valid Perl identifier. For example:
1141
1238
%rename(add_complex) operator+(Complex &, Complex &);
1143
1240
Complex operator+(Complex &, Complex &);
1147
1245
Now, in Perl, you can do this:
1152
1251
$a = example::new_Complex(2,3);
1153
1252
$b = example::new_Complex(4,-1);
1154
1253
$c = example::add_complex($a,$b);
1158
1258
Some preliminary work on mapping C++ operators into Perl operators has been completed. This is covered later.
1160
1261
<H3><a name="Perl5_nn24"></a>23.4.10 Modules and packages</H3>
1166
1267
<tt>%module</tt> directive. To use the module, do the following :
1270
<div class="code"><pre>
1171
1272
use example; # load the example module
1172
1273
print example::fact(4),"\n" # Call a function in it
1177
1278
Usually, a module consists of a collection of code that is contained
1218
1319
`<tt>Foo</tt>.' For example :
1322
<div class="code"><pre>
1222
1323
use example; # Load the module like before
1223
1324
print Foo::fact(4),"\n"; # Call a function in package FooBar
1227
1328
<H2><a name="Perl5_nn25"></a>23.5 Input and output parameters</H2>
1230
1332
A common problem in some C programs is handling parameters passed as simple pointers. For
1235
1338
void add(int x, int y, int *result) {
1236
1339
*result = x + y;
1245
1350
int sub(int *x, int *y) {
1251
1357
The easiest way to handle these situations is to use the <tt>typemaps.i</tt> file. For example:
1255
1362
%module example
1256
1363
%include "typemaps.i"
1258
1365
void add(int, int, int *OUTPUT);
1259
1366
int sub(int *INPUT, int *INPUT);
1263
1371
In Perl, this allows you to pass simple values. For example:
1267
1376
$a = example::add(3,4);
1294
1403
void add(int x, int y, int *result);
1295
1404
int sub(int *x, int *y);
1300
1409
If a function mutates one of its parameters like this,
1305
1414
void negate(int *x) {
1311
1421
you can use <tt>INOUT</tt> like this:
1315
1426
%include "typemaps.i"
1317
1428
void negate(int *INOUT);
1321
1433
In Perl, a mutated parameter shows up as a return value. For example:
1325
1438
$a = example::negate(3);
1332
1445
The most common use of these special typemap rules is to handle functions that
1334
1447
as well as a special error code:
1339
1452
/* send message, return number of bytes sent, along with success code */
1340
1453
int send_message(char *text, int len, int *success);
1344
1458
To wrap such a function, simply use the <tt>OUTPUT</tt> rule above. For example:
1348
1463
%module example
1349
1464
%include "typemaps.i"
1352
1467
int send_message(char *text, int *success);
1356
1472
When used in Perl, the function will return multiple values.
1360
1477
($bytes, $success) = example::send_message("Hello World");
1364
1482
Another common use of multiple return values are in query functions. For example:
1368
1487
void get_dimensions(Matrix *m, int *rows, int *columns);
1372
1492
To wrap this, you might use the following:
1376
1497
%module example
1377
1498
%include "typemaps.i"
1380
1501
void get_dimensions(Matrix *m, int *rows, *columns);
1388
1511
($r,$c) = example::get_dimensions($m);
1392
1516
In certain cases, it is possible to treat Perl references as C pointers. To do this, use the <tt>REFERENCE</tt> typemap. For
1397
1522
%module example
1398
1523
%include typemaps.i
1400
1525
void add(int x, int y, int *REFERENCE);
1528
1658
In this case, the exception handler is only attached to methods and functions
1529
1659
named <tt>getitem</tt> and <tt>setitem</tt>.
1532
1663
If you had a lot of different methods, you can avoid extra typing by using a macro.
1538
1669
%define RANGE_ERROR
1549
1680
%exception getitem RANGE_ERROR;
1550
1681
%exception setitem RANGE_ERROR;
1554
1686
Since SWIG's exception handling is user-definable, you are not limited to C++ exception handling.
1555
1687
See the chapter on "<a href="Customization.html#Customization">Customization features</a>" for more examples.
1558
1691
<b>Compatibility note:</b> In SWIG1.1, exceptions were defined using the older <tt>%except</tt> directive:
1563
1696
%except(python) {
1574
1708
This is still supported, but it is deprecated. The newer <tt>%exception</tt> directive provides the same
1575
1709
functionality, but it has additional capabilities that make it more powerful.
1577
1712
<H2><a name="Perl5_nn27"></a>23.7 Remapping datatypes with typemaps</H2>
1645
1782
the typemap system follows <tt>typedef</tt> declarations. For example:
1650
1787
%typemap(in) int n {
1651
1788
$1 = (int) SvIV($input);
1652
1789
printf("n = %d\n",$1);
1654
1792
typedef int Integer;
1655
1793
extern int fact(Integer n); // Above typemap is applied
1659
1799
It should be noted that the matching of <tt>typedef</tt> only occurs in one direction. If you
1660
1800
defined a typemap for <tt>Integer</tt>, it is not applied to arguments of
1661
1801
type <tt>int</tt>.
1664
1805
Typemaps can also be defined for groups of consecutive arguments. For example:
1669
1810
%typemap(in) (char *str, unsigned len) {
1670
1811
$1 = SvPV($input,$2);
1673
1814
int count(char c, char *str, unsigned len);
1677
1819
When a multi-argument typemap is defined, the arguments are always handled as a single
1678
1820
Perl object. This allows the function to be used like this (notice how the length
1679
1821
parameter is ommitted):
1683
1826
example::count("e","Hello World");
1690
1833
<H3><a name="Perl5_nn29"></a>23.7.2 Perl5 typemaps</H3>
1693
1837
The previous section illustrated an "in" typemap for converting Perl objects to C.
1694
1838
A variety of different typemap methods are defined by the Perl module. For example,
1695
1839
to convert a C integer back into a Perl object, you might define an "out" typemap
1701
1846
%typemap(out) int {
1702
1847
$result = sv_newmortal();
1714
1859
<tt>%typemap(in)</tt>
1862
<div class="indent">
1718
1863
Converts Perl5 object to input function arguments.
1722
1867
<tt>%typemap(out)</tt>
1870
<div class="indent">
1726
1871
Converts function return value to a Perl5 value.
1730
1875
<tt>%typemap(varin)</tt>
1878
<div class="indent">
1734
1879
Converts a Perl5 object to a global variable.
1738
1883
<tt>%typemap(varout)</tt>
1886
<div class="indent">
1742
1887
Converts a global variable to a Perl5 object.
1746
1891
<tt>%typemap(freearg)</tt>
1894
<div class="indent">
1750
1895
Cleans up a function argument after a function call
1754
1899
<tt>%typemap(argout)</tt>
1902
<div class="indent">
1758
1903
Output argument handling
1762
1907
<tt>%typemap(ret)</tt>
1910
<div class="indent">
1766
1911
Clean up return value from a function.
1770
1915
<tt>%typemap(memberin)</tt>
1918
<div class="indent">
1774
1919
Setting of C++ member data (all languages).
1778
1923
<tt>%typemap(memberout)</tt>
1926
<div class="indent">
1782
1927
Return of C++ member data (all languages).
1786
1931
<tt>%typemap(check)</tt>
1934
<div class="indent">
1790
1935
Check value of input parameter.
1793
1938
<H3><a name="Perl5_nn30"></a>23.7.3 Typemap variables</H3>
1796
1942
Within typemap code, a number of special variables prefaced with a <tt>$</tt> may appear.
1797
1943
A full list of variables can be found in the "<a href="Typemaps.html#Typemaps">Typemaps</a>" chapter.
1798
1944
This is a list of the most common variables:
1951
<div class="indent">
1805
1952
A C local variable corresponding to the actual type specified in the
1806
1953
<tt>%typemap</tt> directive. For input values, this is a C local variable
1807
1954
that's supposed to hold an argument value. For output values, this is
1808
1955
the raw result that's supposed to be returned to Perl.
1812
1959
<tt>$input</tt>
1962
<div class="indent">
1816
1963
A Perl object holding the value of an argument of variable value.
1820
1967
<tt>$result</tt>
1970
<div class="indent">
1824
1971
A Perl object that holds the result to be returned to Perl.
1828
1975
<tt>$1_name</tt>
1978
<div class="indent">
1832
1979
The parameter name that was matched.
1836
1983
<tt>$1_type</tt>
1986
<div class="indent">
1840
1987
The actual C datatype matched by the typemap.
1844
1991
<tt>$1_ltype</tt>
1994
<div class="indent">
1848
1995
An assignable version of the datatype matched by the typemap (a type that can appear on the left-hand-side of
1849
1996
a C assignment operation). This type is stripped of qualifiers and may be an altered version of <tt>$1_type</tt>.
1850
1997
All arguments and local variables in wrapper functions are declared using this type so that their values can be
1851
1998
properly assigned.
1854
2002
<tt>$symname</tt>
2005
<div class="indent">
1856
2006
The Perl name of the wrapper function being created.
1859
2009
<H3><a name="Perl5_nn31"></a>23.7.4 Useful functions</H3>
1873
2023
<b>Perl Integer Functions</b>
1878
2028
int SvIV(SV *);
1879
2029
void sv_setiv(SV *sv, IV value);
1880
2030
SV *newSViv(IV value);
1881
2031
int SvIOK(SV *);
1885
2036
<b>Perl Floating Point Functions</b>
1889
2041
double SvNV(SV *);
1890
2042
void sv_setnv(SV *, double value);
1891
2043
SV *newSVnv(double value);
1892
2044
int SvNOK(SV *);
1896
2049
<b>Perl String Functions</b>
1900
2054
char *SvPV(SV *, STRLEN len);
1901
2055
void sv_setpv(SV *, char *val);
1905
2059
void sv_catpv(SV *, char *);
1906
2060
void sv_catpvn(SV *, char *, STRLEN);
1910
2065
<b>Perl References</b>
1914
2070
void sv_setref_pv(SV *, char *, void *ptr);
1915
2071
int sv_isobject(SV *);
1916
2072
SV *SvRV(SV *);
1917
2073
int sv_isa(SV *, char *0;
1922
2078
<H2><a name="Perl5_nn32"></a>23.8 Typemap Examples</H2>
1925
2082
This section includes a few examples of typemaps. For more examples, you
1926
2083
might look at the files "<tt>perl5.swg</tt>" and "<tt>typemaps.i</tt>" in
1927
2084
the SWIG library.
1929
2087
<H3><a name="Perl5_nn33"></a>23.8.1 Converting a Perl5 array to a char ** </H3>
2008
2166
When this module is compiled, the wrapped C functions can be used in a
2009
2167
Perl script as follows :
2170
<div class="code"><pre>
2014
2172
@a = ("Dave", "Mike", "John", "Mary"); # Create an array of strings
2015
2173
argv::print_args(\@a); # Pass it to our C function
2016
2174
$b = argv::get_args(); # Get array of strings from C
2017
2175
print @$b,"\n"; # Print it out
2021
2179
<H3><a name="Perl5_nn34"></a>23.8.2 Return values </H3>
2306
<div class="code"><pre>
2149
2307
%typemap(memberin) int [ANY] {
2151
2309
for (i = 0; i < $1_dim0; i++) {
2152
2310
$1[i] = $input[i];
2157
2316
When setting structure members, the input object is always assumed to
2158
2317
be a C array of values that have already been converted from the
2159
2318
target language. Because of this, the <tt>memberin</tt> typemap is
2161
2320
the "in" typemap in the previous section would be used to convert an
2162
2321
<tt>int[]</tt> array to C whereas the "memberin" typemap would be used
2163
2322
to copy the converted array into a C data structure.
2165
2325
<H3><a name="Perl5_nn37"></a>23.8.5 Turning Perl references into C pointers</H3>
2171
2331
have a C function that modifies its arguments like this :
2334
<div class="code"><pre>
2175
2335
void add(double a, double b, double *c) {
2181
2341
A common misinterpretation of this function is the following Perl script :
2344
<div class="code"><pre>
2188
2348
$c = 0.0; # Output value
2189
2349
add($a,$b,\$c); # Place result in c (Except that it doesn't work)
2193
2353
To make this work with a reference, you can use a typemap such as this:
2356
<div class="code"><pre>
2197
2357
%typemap(in) double * (double dvalue) {
2199
2359
if (!SvROK($input)) {
2210
2370
%typemap(argout) double * {
2212
2372
tempsv = SvRV($input);
2213
sv_setnv(tempsv, *$input);
2373
sv_setnv(tempsv, *$1);
2218
2378
Now, if you place this before the add function, you can do this :
2381
<div class="code"><pre>
2225
2385
add($a,$b,\$c); # Now it works!
2230
2390
<H3><a name="Perl5_nn38"></a>23.8.6 Pointer handling</H3>
2405
<div class="indent">
2246
2406
Converts a Perl object <tt>obj</tt> to a C pointer. The result of the conversion is placed
2247
2407
into the pointer located at <tt>ptr</tt>. <tt>ty</tt> is a SWIG type descriptor structure.
2248
2408
<tt>flags</tt> is used to handle error checking and other aspects of conversion. <tt>flags</tt> is
2249
2409
currently undefined and reserved for future expansion. Returns 0 on success and -1 on error.
2254
2414
void *SWIG_MakePtr(SV *obj, void *ptr, swig_type_info *ty, int flags)</tt>
2417
<div class="indent">
2258
2418
Creates a new Perl pointer object. <tt>obj</tt> is a Perl SV that has been initialized to hold the result,
2259
2419
<tt>ptr</tt> is the pointer to convert, <tt>ty</tt> is the SWIG type descriptor structure that
2260
2420
describes the type, and <tt>flags</tt> is a flag that controls properties of the conversion. <tt>flags</tt> is currently undefined
2265
2425
Both of these functions require the use of a special SWIG
2278
2438
SV *sv = sv_newmortal();
2279
2439
SWIG_MakePtr(sv, f, SWIGTYPE_p_Foo, 0);
2283
2444
In a typemap, the type descriptor should always be accessed using the special typemap
2284
2445
variable <tt>$1_descriptor</tt>. For example:
2288
2450
%typemap(in) Foo * {
2289
2451
if ((SWIG_ConvertPtr($input,(void **) &$1, $1_descriptor,0)) == -1) return NULL;
2294
2457
If necessary, the descriptor for any type can be obtained using the <tt>$descriptor()</tt> macro in a typemap.
2299
2463
%typemap(in) Foo * {
2300
2464
if ((SWIG_ConvertPtr($input,(void **) &$1, $descriptor(Foo *), 0)) == -1) return NULL;
2305
2469
<H2><a name="Perl5_nn39"></a>23.9 Proxy classes</H2>
2321
2485
<H3><a name="Perl5_nn40"></a>23.9.1 Preliminaries</H3>
2324
2489
Proxy classes, are generated by default. If you want to turn them off, use the <tt>-noproxy</tt> command line option.
2329
2495
$ swig -c++ -perl -noproxy example.i
2333
2500
When proxy classes are used, SWIG moves all of the low-level procedural wrappers to
2334
2501
another package name. By default, this package is named 'modulec' where 'module' is the name of the module
2335
2502
you provided with the <tt>%module</tt> directive. Then, in place of the original module,
2336
2503
SWIG creates a collection of high-level Perl wrappers. In your scripts, you will use these
2337
2504
high level wrappers. The wrappers, in turn, interact with the low-level procedural module.
2339
2507
<H3><a name="Perl5_nn41"></a>23.9.2 Structure and class wrappers</H3>
2357
2525
When wrapped, SWIG creates the following set of low-level accessor
2358
2526
functions as described in previous sections.
2529
<div class="code"><pre>
2362
2530
Vector *new_Vector(double x, double y, double z);
2363
2531
void delete_Vector(Vector *v);
2364
2532
double Vector_x_get(Vector *v);
2368
2536
double Vector_z_get(Vector *v);
2369
2537
double Vector_z_set(Vector *v, double value);
2374
2542
However, when proxy classes are enabled, these accessor functions are
2375
2543
wrapped inside a Perl class like this:
2546
<div class="code"><pre>
2379
2547
package example::Vector;
2380
2548
@ISA = qw( example );
2484
2652
Vector object :
2655
<div class="code"><pre>
2488
2656
Vector *new_Vector(double x, double y, double z) {
2490
2658
v = new Vector(x,y,z); // Call C++ constructor
2496
2664
Both functions return a Vector, but the constructor is returning a
2526
2694
done using the <tt>DISOWN </tt>method.
2697
<div class="code"><pre>
2530
2698
# Perl code to change ownership of an object
2531
2699
$v = new Vector(x,y,z);
2532
2700
$v->DISOWN();
2536
2704
To acquire ownership of an object, the <tt>ACQUIRE</tt> method can be used.
2707
<div class="code"><pre>
2540
2708
# Given Perl ownership of a file
2541
2709
$u = Vector_get($v);
2542
2710
$u->ACQUIRE();
2547
2715
As always, a little care is in order. SWIG does not provide reference
2595
2763
This implementation allows us to operate on nested structures as follows :
2766
<div class="code"><pre>
2599
2767
# Perl access of nested structure
2600
2768
$p = new Particle();
2601
2769
$p->{f}->{x} = 0.0;
2602
2770
%${$p->{v}} = ( x=>0, y=>0, z=>0);
2605
2773
<H3><a name="Perl5_nn44"></a>23.9.5 Proxy Functions</H3>
2715
2883
<H3><a name="Perl5_nn46"></a>23.9.7 Modifying the proxy methods</H3>
2718
2887
It is possible to override the SWIG generated proxy/shadow methods, using <tt>%feature("shadow")</tt>.
2719
2888
It works like all the other <a href="Customization.html#features">%feature directives</a>.
2720
2889
Here is a simple example showing how to add some Perl debug code to the constructor:
2892
<div class="code"><pre>
2723
2893
/* Let's make the constructor of the class Square more verbose */
2724
2894
%feature("shadow") Square(double w)