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