PageRenderTime 60ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/trunk/Doc/Manual/Perl5.html

#
HTML | 2537 lines | 2288 code | 247 blank | 2 comment | 0 complexity | 3824fc5a2d2915f5fbebfbbf64c1e40c MD5 | raw file
Possible License(s): LGPL-2.1, Cube, GPL-3.0, 0BSD, GPL-2.0
  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. <body bgcolor="#ffffff">
  8. <H1><a name="Perl5"></a>31 SWIG and Perl5</H1>
  9. <!-- INDEX -->
  10. <div class="sectiontoc">
  11. <ul>
  12. <li><a href="#Perl5_nn2">Overview</a>
  13. <li><a href="#Perl5_nn3">Preliminaries</a>
  14. <ul>
  15. <li><a href="#Perl5_nn4">Getting the right header files</a>
  16. <li><a href="#Perl5_nn5">Compiling a dynamic module</a>
  17. <li><a href="#Perl5_nn6">Building a dynamic module with MakeMaker</a>
  18. <li><a href="#Perl5_nn7">Building a static version of Perl</a>
  19. <li><a href="#Perl5_nn8">Using the module</a>
  20. <li><a href="#Perl5_nn9">Compilation problems and compiling with C++</a>
  21. <li><a href="#Perl5_nn10">Compiling for 64-bit platforms</a>
  22. </ul>
  23. <li><a href="#Perl5_nn11">Building Perl Extensions under Windows</a>
  24. <ul>
  25. <li><a href="#Perl5_nn12">Running SWIG from Developer Studio</a>
  26. <li><a href="#Perl5_nn13">Using other compilers</a>
  27. </ul>
  28. <li><a href="#Perl5_nn14">The low-level interface</a>
  29. <ul>
  30. <li><a href="#Perl5_nn15">Functions</a>
  31. <li><a href="#Perl5_nn16">Global variables</a>
  32. <li><a href="#Perl5_nn17">Constants</a>
  33. <li><a href="#Perl5_nn18">Pointers</a>
  34. <li><a href="#Perl5_nn19">Structures</a>
  35. <li><a href="#Perl5_nn20">C++ classes</a>
  36. <li><a href="#Perl5_nn21">C++ classes and type-checking</a>
  37. <li><a href="#Perl5_nn22">C++ overloaded functions</a>
  38. <li><a href="#Perl5_nn23">Operators</a>
  39. <li><a href="#Perl5_nn24">Modules and packages</a>
  40. </ul>
  41. <li><a href="#Perl5_nn25">Input and output parameters</a>
  42. <li><a href="#Perl5_nn26">Exception handling</a>
  43. <li><a href="#Perl5_nn27">Remapping datatypes with typemaps</a>
  44. <ul>
  45. <li><a href="#Perl5_nn28">A simple typemap example</a>
  46. <li><a href="#Perl5_nn29">Perl5 typemaps</a>
  47. <li><a href="#Perl5_nn30">Typemap variables</a>
  48. <li><a href="#Perl5_nn31">Useful functions</a>
  49. </ul>
  50. <li><a href="#Perl5_nn32">Typemap Examples</a>
  51. <ul>
  52. <li><a href="#Perl5_nn33">Converting a Perl5 array to a char **</a>
  53. <li><a href="#Perl5_nn34">Return values</a>
  54. <li><a href="#Perl5_nn35">Returning values from arguments</a>
  55. <li><a href="#Perl5_nn36">Accessing array structure members</a>
  56. <li><a href="#Perl5_nn37">Turning Perl references into C pointers</a>
  57. <li><a href="#Perl5_nn38">Pointer handling</a>
  58. </ul>
  59. <li><a href="#Perl5_nn39">Proxy classes</a>
  60. <ul>
  61. <li><a href="#Perl5_nn40">Preliminaries</a>
  62. <li><a href="#Perl5_nn41">Structure and class wrappers</a>
  63. <li><a href="#Perl5_nn42">Object Ownership</a>
  64. <li><a href="#Perl5_nn43">Nested Objects</a>
  65. <li><a href="#Perl5_nn44">Proxy Functions</a>
  66. <li><a href="#Perl5_nn45">Inheritance</a>
  67. <li><a href="#Perl5_nn46">Modifying the proxy methods</a>
  68. </ul>
  69. <li><a href="#Perl5_nn47">Adding additional Perl code</a>
  70. </ul>
  71. </div>
  72. <!-- INDEX -->
  73. <p>
  74. <b>Caution: This chapter is under repair!</b>
  75. </p>
  76. <p>
  77. This chapter describes SWIG's support of Perl5. Although the Perl5
  78. module is one of the earliest SWIG modules, it has continued to evolve
  79. and has been improved greatly with the help of SWIG users. For the
  80. best results, it is recommended that SWIG be used with Perl 5.8 or
  81. later. We're no longer testing regularly with older versions, but
  82. Perl 5.6 seems to mostly work, while older versions don't.
  83. </p>
  84. <H2><a name="Perl5_nn2"></a>31.1 Overview</H2>
  85. <p>
  86. To build Perl extension modules, SWIG uses a layered approach. At
  87. the lowest level, simple procedural wrappers are generated for
  88. functions, classes, methods, and other declarations in the input file.
  89. Then, for structures and classes, an optional collection of Perl
  90. proxy classes can be generated in order to provide a more natural object oriented Perl
  91. interface. These proxy classes simply build upon the low-level interface.
  92. </p>
  93. <p>
  94. In describing the Perl interface, this chapter begins by covering the
  95. essentials. First, the problem of configuration, compiling,
  96. and installing Perl modules is discussed. Next, the low-level
  97. procedural interface is presented. Finally, proxy classes are
  98. described. Advanced customization features, typemaps, and other
  99. options are found near the end of the chapter.
  100. </p>
  101. <H2><a name="Perl5_nn3"></a>31.2 Preliminaries</H2>
  102. <p>
  103. To build a Perl5 module, run SWIG using the <tt>-perl</tt> option as
  104. follows:
  105. </p>
  106. <div class="code"><pre>
  107. swig -perl example.i
  108. </pre></div>
  109. <p>
  110. This produces two files. The first file, <tt>example_wrap.c</tt>
  111. contains all of the C code needed to build a Perl5 module. The second
  112. file, <tt>example.pm</tt> contains supporting Perl code needed to
  113. properly load the module.
  114. </p>
  115. <p>
  116. To build the module, you will need to compile the file
  117. <tt>example_wrap.c</tt> and link it with the rest of your program.
  118. </p>
  119. <H3><a name="Perl5_nn4"></a>31.2.1 Getting the right header files</H3>
  120. <p>
  121. In order to compile, SWIG extensions need the following Perl5 header files:</p>
  122. <div class="code"><pre>
  123. #include "Extern.h"
  124. #include "perl.h"
  125. #include "XSUB.h"
  126. </pre></div>
  127. <p>
  128. These are typically located in a directory like this</p>
  129. <div class="code"><pre>
  130. /usr/lib/perl/5.14/CORE
  131. </pre></div>
  132. <p>
  133. The SWIG configuration script automatically tries to locate this directory so
  134. that it can compile examples. However, if you need to find out where the directory is
  135. located, an easy way to find out is to ask Perl itself:
  136. </p>
  137. <div class="code">
  138. <pre>
  139. $ perl -e 'use Config; print "$Config{archlib}\n";'
  140. /usr/lib/perl/5.14
  141. </pre>
  142. </div>
  143. <H3><a name="Perl5_nn5"></a>31.2.2 Compiling a dynamic module</H3>
  144. <p>
  145. The preferred approach to building an extension module is to compile it into
  146. a shared object file or DLL. To do this, you will need to compile your program
  147. using commands like this (shown for Linux):
  148. </p>
  149. <div class="code"><pre>
  150. $ swig -perl example.i
  151. $ gcc -fPIC example.c
  152. $ gcc -fPIC -c example_wrap.c -I/usr/lib/perl/5.14/CORE -Dbool=char
  153. $ gcc -shared example.o example_wrap.o -o example.so
  154. </pre></div>
  155. <p>
  156. The exact compiler options vary from platform to platform.
  157. SWIG tries to guess the right options when it is installed. Therefore,
  158. you may want to start with one of the examples in the <tt>SWIG/Examples/perl5</tt>
  159. directory. If that doesn't work, you will need to read the man-pages for
  160. your compiler and linker to get the right set of options. You might also
  161. check the <a href="http://www.dabeaz.com/cgi-bin/wiki.pl">SWIG Wiki</a> for
  162. additional information.
  163. </p>
  164. <p>
  165. When linking the module, the name of the shared object file must match the module name used in
  166. the SWIG interface file. If you used `<tt>%module example</tt>', then
  167. the target should be named `<tt>example.so</tt>',
  168. `<tt>example.sl</tt>', or the appropriate dynamic module name on your system.
  169. </p>
  170. <H3><a name="Perl5_nn6"></a>31.2.3 Building a dynamic module with MakeMaker</H3>
  171. <p>
  172. It is also possible to use Perl to build dynamically loadable modules
  173. for you using the MakeMaker utility. To do this, write a Perl
  174. script such as the following:</p>
  175. <div class="targetlang"><pre>
  176. # File : Makefile.PL
  177. use ExtUtils::MakeMaker;
  178. WriteMakefile(
  179. `NAME' =&gt; `example', # Name of package
  180. `LIBS' =&gt; [`-lm'], # Name of custom libraries
  181. `OBJECT' =&gt; `example.o example_wrap.o' # Object files
  182. );
  183. </pre></div>
  184. <p>
  185. Now, to build a module, simply follow these steps:</p>
  186. <div class="code"><pre>
  187. $ perl Makefile.PL
  188. $ make
  189. $ make install
  190. </pre></div>
  191. <p>
  192. If you are planning to distribute a SWIG-generated module, this is
  193. the preferred approach to compilation. More information about MakeMaker can be
  194. found in "Programming Perl, 2nd ed." by Larry Wall, Tom Christiansen,
  195. and Randal Schwartz.</p>
  196. <H3><a name="Perl5_nn7"></a>31.2.4 Building a static version of Perl</H3>
  197. <p>
  198. If you machine does not support dynamic loading or if you've tried to
  199. use it without success, you can build a new version of the Perl
  200. interpreter with your SWIG extensions added to it. To build a static
  201. extension, you first need to invoke SWIG as follows:</p>
  202. <div class="code"><pre>
  203. $ swig -perl -static example.i
  204. </pre></div>
  205. <p>
  206. By default SWIG includes code for dynamic loading, but the
  207. <tt>-static</tt> option takes it out.</p>
  208. <p>
  209. Next, you will need to supply a <tt>main()</tt> function that
  210. initializes your extension and starts the Perl interpreter. While,
  211. this may sound daunting, SWIG can do this for you automatically as
  212. follows:</p>
  213. <div class="targetlang"><pre>
  214. %module example
  215. %inline %{
  216. extern double My_variable;
  217. extern int fact(int);
  218. %}
  219. // Include code for rebuilding Perl
  220. %include &lt;perlmain.i&gt;
  221. </pre></div>
  222. <p>
  223. The same thing can be accomplished by running SWIG as follows:</p>
  224. <div class="code"><pre>
  225. $ swig -perl -static -lperlmain.i example.i
  226. </pre></div>
  227. <p>
  228. The <tt>perlmain.i</tt> file inserts Perl's <tt>main()</tt> function
  229. into the wrapper code and automatically initializes the SWIG generated
  230. module. If you just want to make a quick a dirty module, this may be
  231. the easiest way. By default, the <tt>perlmain.i</tt> code does not
  232. initialize any other Perl extensions. If you need to use other
  233. packages, you will need to modify it appropriately. You can do this by
  234. just copying <tt>perlmain.i</tt> out of the SWIG library, placing it
  235. in your own directory, and modifying it to suit your purposes.</p>
  236. <p>
  237. To build your new Perl executable, follow the exact same procedure as
  238. for a dynamic module, but change the link line to something like this:
  239. </p>
  240. <div class="code"><pre>
  241. $ gcc example.o example_wrap.o -L/usr/lib/perl/5.14/CORE \
  242. -lperl -lsocket -lnsl -lm -o myperl
  243. </pre></div>
  244. <p>
  245. This will produce a new version of Perl called <tt>myperl</tt>. It
  246. should be functionality identical to Perl with your C/C++ extension
  247. added to it. Depending on your machine, you may need to link with
  248. additional libraries such as <tt>-lsocket, -lnsl, -ldl</tt>, etc.
  249. </p>
  250. <H3><a name="Perl5_nn8"></a>31.2.5 Using the module</H3>
  251. <p>
  252. To use the module, simply use the Perl <tt>use</tt> statement. If
  253. all goes well, you will be able to do this:
  254. </p>
  255. <div class="targetlang"><pre>
  256. $ perl
  257. use example;
  258. print example::fact(4),"\n";
  259. 24
  260. </pre></div>
  261. <p>
  262. A common error received by first-time users is the following:
  263. </p>
  264. <div class="targetlang">
  265. <pre>
  266. use example;
  267. Can't locate example.pm in @INC (@INC contains: /etc/perl /usr/local/lib/perl/5.14.2 /usr/local/share/perl/5.14.2 /usr/lib/perl5 /usr/share/perl5 /usr/lib/perl/5.14 /usr/share/perl/5.14 /usr/local/lib/site_perl .) at - line 1.
  268. BEGIN failed--compilation aborted at - line 1.
  269. </pre>
  270. </div>
  271. <p>
  272. This error is almost caused when the name of the shared object file you created doesn't match the module name
  273. you specified with the <tt>%module</tt> directive.
  274. </p>
  275. <p>
  276. A somewhat related, but slightly different error is this:
  277. </p>
  278. <div class="targetlang">
  279. <pre>
  280. use example;
  281. Can't find 'boot_example' symbol in ./example.so
  282. at - line 1
  283. BEGIN failed--compilation aborted at - line 1.
  284. </pre>
  285. </div>
  286. <p>
  287. This error is generated because Perl can't locate the module bootstrap function in the
  288. SWIG extension module. This could be caused by a mismatch between the module name and the shared library name.
  289. However, another possible cause is forgetting to link the SWIG-generated wrapper code with the rest
  290. of your application when you linked the extension module.
  291. </p>
  292. <p>
  293. Another common error is the following:
  294. </p>
  295. <div class="targetlang">
  296. <pre>
  297. use example;
  298. Can't load './example.so' for module example: ./example.so:
  299. undefined symbol: Foo at /usr/lib/perl/5.14/i386-linux/DynaLoader.pm line 169.
  300. at - line 1
  301. BEGIN failed--compilation aborted at - line 1.
  302. </pre>
  303. </div>
  304. <p>
  305. This error usually indicates that you forgot to include some object
  306. files or libraries in the linking of the shared library file. Make
  307. sure you compile both the SWIG wrapper file and your original program
  308. into a shared library file. Make sure you pass all of the required libraries
  309. to the linker.
  310. </p>
  311. <p>
  312. Sometimes unresolved symbols occur because a wrapper has been created
  313. for a function that doesn't actually exist in a library. This usually
  314. occurs when a header file includes a declaration for a function that
  315. was never actually implemented or it was removed from a library
  316. without updating the header file. To fix this, you can either edit
  317. the SWIG input file to remove the offending declaration or you can use
  318. the <tt>%ignore</tt> directive to ignore the declaration. Better yet,
  319. update the header file so that it doesn't have an undefined declaration.
  320. </p>
  321. <p>
  322. Finally, suppose that your extension module is linked with another library like this:
  323. </p>
  324. <div class="code">
  325. <pre>
  326. $ gcc -shared example.o example_wrap.o -L/home/beazley/projects/lib -lfoo \
  327. -o example.so
  328. </pre>
  329. </div>
  330. <p>
  331. If the <tt>foo</tt> library is compiled as a shared library, you might get the following
  332. error when you try to use your module:
  333. </p>
  334. <div class="targetlang">
  335. <pre>
  336. use example;
  337. Can't load './example.so' for module example: libfoo.so: cannot open shared object file:
  338. No such file or directory at /usr/lib/perl/5.14/i386-linux/DynaLoader.pm line 169.
  339. at - line 1
  340. BEGIN failed--compilation aborted at - line 1.
  341. &gt;&gt;&gt;
  342. </pre>
  343. </div>
  344. <p>
  345. This error is generated because the dynamic linker can't locate the
  346. <tt>libfoo.so</tt> library. When shared libraries are loaded, the
  347. system normally only checks a few standard locations such as
  348. <tt>/usr/lib</tt> and <tt>/usr/local/lib</tt>. To get the loader to look in other
  349. locations, there are several things you can do. First, you can recompile your extension
  350. module with extra path information. For example, on Linux you can do this:
  351. </p>
  352. <div class="code">
  353. <pre>
  354. $ gcc -shared example.o example_wrap.o -L/home/beazley/projects/lib -lfoo \
  355. <b>-Xlinker -rpath /home/beazley/projects/lib \</b>
  356. -o example.so
  357. </pre>
  358. </div>
  359. <p>
  360. Alternatively, you can set the <tt>LD_LIBRARY_PATH</tt> environment
  361. variable to include the directory with your shared libraries. If
  362. setting <tt>LD_LIBRARY_PATH</tt>, be aware that setting this variable
  363. can introduce a noticeable performance impact on all other
  364. applications that you run. To set it only for Perl, you might want
  365. to do this instead:
  366. </p>
  367. <div class="code">
  368. <pre>
  369. $ env LD_LIBRARY_PATH=/home/beazley/projects/lib perl
  370. </pre>
  371. </div>
  372. <p>
  373. Finally, you can use a command such as <tt>ldconfig</tt> (Linux) or
  374. <tt>crle</tt> (Solaris) to add additional search paths to the default
  375. system configuration (this requires root access and you will need to
  376. read the man pages).
  377. </p>
  378. <H3><a name="Perl5_nn9"></a>31.2.6 Compilation problems and compiling with C++</H3>
  379. <p>
  380. Compilation of C++ extensions has traditionally been a tricky problem.
  381. Since the Perl interpreter is written in C, you need to take steps to
  382. make sure C++ is properly initialized and that modules are compiled
  383. correctly.
  384. </p>
  385. <p>
  386. On most machines, C++ extension modules should be linked using the C++
  387. compiler. For example:
  388. </p>
  389. <div class="code"><pre>
  390. $ swig -c++ -perl example.i
  391. $ g++ -fPIC -c example.cxx
  392. $ g++ -fPIC -c example_wrap.cxx -I/usr/lib/perl/5.14/i386-linux/CORE
  393. $ <b>g++ -shared example.o example_wrap.o -o example.so</b>
  394. </pre></div>
  395. <p>
  396. In addition to this, you may need to include additional library
  397. files to make it work. For example, if you are using the Sun C++ compiler on
  398. Solaris, you often need to add an extra library <tt>-lCrun</tt> like this:
  399. </p>
  400. <div class="code"><pre>
  401. $ swig -c++ -perl example.i
  402. $ CC -c example.cxx
  403. $ CC -c example_wrap.cxx -I/usr/lib/perl/5.14/i386-linux/CORE
  404. $ CC -shared example.o example_wrap.o -o example.so <b>-lCrun</b>
  405. </pre></div>
  406. <p>
  407. Of course, the names of the extra libraries are completely non-portable---you will
  408. probably need to do some experimentation.
  409. </p>
  410. <p>
  411. Another possible compile problem comes from recent versions of Perl (5.8.0) and the GNU tools.
  412. If you see errors having to do with _crypt_struct, that means _GNU_SOURCE is not defined and
  413. it needs to be. So you should compile the wrapper like:
  414. </p>
  415. <div class="code"><pre>
  416. $ g++ -fPIC -c example_wrap.cxx -I/usr/lib/perl/5.8.0/CORE -D_GNU_SOURCE
  417. </pre></div>
  418. <p>
  419. -D_GNU_SOURCE is also included in the Perl ccflags, which can be found by running
  420. </p>
  421. <div class="code"><pre>
  422. $ perl -e 'use Config; print "$Config{ccflags}\n";'
  423. </pre></div>
  424. <p>
  425. So you could also compile the wrapper like
  426. </p>
  427. <div class="code"><pre>
  428. $ g++ -fPIC -c example_wrap.cxx -I/usr/lib/perl/5.8.0/CORE \
  429. `perl -MConfig -e 'print $Config{ccflags}'`
  430. </pre></div>
  431. <p>
  432. Sometimes people have suggested that it is necessary to relink the
  433. Perl interpreter using the C++ compiler to make C++ extension modules work.
  434. In the experience of this author, this has never actually appeared to be
  435. necessary on most platforms. Relinking the interpreter with C++ really only includes the
  436. special run-time libraries described above---as long as you link your extension
  437. modules with these libraries, it should not be necessary to rebuild Perl.
  438. </p>
  439. <p>
  440. If you aren't entirely sure about the linking of a C++ extension, you
  441. might look at an existing C++ program. On many Unix machines, the
  442. <tt>ldd</tt> command will list library dependencies. This should give
  443. you some clues about what you might have to include when you link your
  444. extension module. For example, notice the first line of output here:
  445. </p>
  446. <div class="code">
  447. <pre>
  448. $ ldd swig
  449. <b>libstdc++-libc6.1-1.so.2 =&gt; /usr/lib/libstdc++-libc6.1-1.so.2 (0x40019000)</b>
  450. libm.so.6 =&gt; /lib/libm.so.6 (0x4005b000)
  451. libc.so.6 =&gt; /lib/libc.so.6 (0x40077000)
  452. /lib/ld-linux.so.2 =&gt; /lib/ld-linux.so.2 (0x40000000)
  453. $
  454. </pre>
  455. </div>
  456. <p>
  457. If linking wasn't enough of a problem, another major complication of C++ is that it does not
  458. define any sort of standard for binary linking of libraries. This
  459. means that C++ code compiled by different compilers will not link
  460. together properly as libraries nor is the memory layout of classes and
  461. data structures implemented in any kind of portable manner. In a
  462. monolithic C++ program, this problem may be unnoticed. However, in Perl, it
  463. is possible for different extension modules to be compiled with
  464. different C++ compilers. As long as these modules are self-contained,
  465. this probably won't matter. However, if these modules start sharing data,
  466. you will need to take steps to avoid segmentation faults and other
  467. erratic program behavior. Also, be aware that certain C++ features, especially RTTI,
  468. can behave strangely when working with multiple modules.
  469. </p>
  470. <p>
  471. It should be noted that you may get a lot of error messages
  472. about the '<tt>bool</tt>' datatype when compiling a C++ Perl module. If
  473. you experience this problem, you can try the following:</p>
  474. <ul>
  475. <li>Use <tt>-DHAS_BOOL</tt> when compiling the SWIG wrapper code
  476. <li>Or use <tt>-Dbool=char</tt> when compiling.
  477. </ul>
  478. <p>
  479. Finally, recent versions of Perl (5.8.0) have namespace conflict problems. Perl defines a bunch
  480. of short macros to make the Perl API function names shorter. For example, in
  481. /usr/lib/perl/5.8.0/CORE/embed.h there is a line:
  482. </p>
  483. <div class="code"><pre>
  484. #define do_open Perl_do_open
  485. </pre></div>
  486. <p>
  487. The problem is, in the &lt;iostream&gt; header from GNU libstdc++v3 there is a private
  488. function named do_open. If &lt;iostream&gt; is included after the perl headers, then
  489. the Perl macro causes the iostream do_open to be renamed, which causes compile errors.
  490. Hopefully in the future Perl will support a PERL_NO_SHORT_NAMES flag, but for now the
  491. only solution is to undef the macros that conflict. Lib/perl5/noembed.h in the SWIG
  492. source has a list of macros that are known to conflict with either standard headers or
  493. other headers. But if you get macro type conflicts from other macros not included
  494. in Lib/perl5/noembed.h while compiling the wrapper, you will
  495. have to find the macro that conflicts and add an #undef into the .i file. Please report
  496. any conflicting macros you find to <a href="http://www.swig.org/mail.html">swig-user mailing list</a>.
  497. </p>
  498. <H3><a name="Perl5_nn10"></a>31.2.7 Compiling for 64-bit platforms</H3>
  499. <p>
  500. On platforms that support 64-bit applications (Solaris, Irix, etc.),
  501. special care is required when building extension modules. On these
  502. machines, 64-bit applications are compiled and linked using a different
  503. set of compiler/linker options. In addition, it is not generally possible to mix
  504. 32-bit and 64-bit code together in the same application.
  505. </p>
  506. <p>
  507. To utilize 64-bits, the Perl executable will need to be recompiled
  508. as a 64-bit application. In addition, all libraries, wrapper code,
  509. and every other part of your application will need to be compiled for
  510. 64-bits. If you plan to use other third-party extension modules, they
  511. will also have to be recompiled as 64-bit extensions.
  512. </p>
  513. <p>
  514. If you are wrapping commercial software for which you have no source
  515. code, you will be forced to use the same linking standard as used by
  516. that software. This may prevent the use of 64-bit extensions. It may
  517. also introduce problems on platforms that support more than one
  518. linking standard (e.g., -o32 and -n32 on Irix).
  519. </p>
  520. <H2><a name="Perl5_nn11"></a>31.3 Building Perl Extensions under Windows</H2>
  521. <p>
  522. Building a SWIG extension to Perl under Windows is roughly
  523. similar to the process used with Unix. Normally, you will want to
  524. produce a DLL that can be loaded into the Perl interpreter. This
  525. section assumes you are using SWIG with Microsoft Visual C++
  526. although the procedure may be similar with other compilers.
  527. </p>
  528. <H3><a name="Perl5_nn12"></a>31.3.1 Running SWIG from Developer Studio</H3>
  529. <p>
  530. If you are developing your application within Microsoft developer
  531. studio, SWIG can be invoked as a custom build option. The process
  532. roughly requires these steps:</p>
  533. <ul>
  534. <li>Open up a new workspace and use the AppWizard to select a DLL
  535. project.
  536. <li>Add both the SWIG interface file (the .i file), any supporting C
  537. files, and the name of the wrapper file that will be created by SWIG
  538. (ie. <tt>example_wrap.c</tt>). Note: If using C++, choose a
  539. different suffix for the wrapper file such as
  540. <tt>example_wrap.cxx</tt>. Don't worry if the wrapper file doesn't
  541. exist yet--Developer studio will keep a reference to it around.
  542. <li>Select the SWIG interface file and go to the settings menu. Under
  543. settings, select the "Custom Build" option.
  544. <li>Enter "SWIG" in the description field.
  545. <li>Enter "<tt>swig -perl5 -o $(ProjDir)\$(InputName)_wrap.cxx
  546. $(InputPath)</tt>" in the "Build command(s) field"
  547. <li>Enter "<tt>$(ProjDir)\$(InputName)_wrap.c</tt>xx" in the "Output
  548. files(s) field".
  549. <li>Next, select the settings for the entire project and go to
  550. "C++:Preprocessor". Add the include directories for your Perl 5
  551. installation under "Additional include directories".
  552. <li>Define the symbols WIN32 and MSWIN32 under preprocessor options.
  553. If using the ActiveWare port, also define the symbol PERL_OBJECT.
  554. Note that all extensions to the ActiveWare port must be compiled with
  555. the C++ compiler since Perl has been encapsulated in a C++ class.
  556. <li>Finally, select the settings for the entire project and go to
  557. "Link Options". Add the Perl library file to your link libraries.
  558. For example "perl.lib". Also, set the name of the output file to
  559. match the name of your Perl module (ie. example.dll).
  560. <li>Build your project.
  561. </ul>
  562. <p>
  563. Now, assuming you made it this far, SWIG will be automatically invoked when
  564. you build your project. Any changes made to the interface file will
  565. result in SWIG being automatically invoked to produce a new version of
  566. the wrapper file. To run your new Perl extension, simply run Perl and
  567. use the use command as normal. For example:
  568. </p>
  569. <div class="targetlang"><pre>
  570. DOS &gt; perl
  571. use example;
  572. $a = example::fact(4);
  573. print "$a\n";
  574. </pre></div>
  575. <H3><a name="Perl5_nn13"></a>31.3.2 Using other compilers</H3>
  576. <p>
  577. SWIG is known to work with Cygwin and may work with other compilers on Windows.
  578. For general hints and suggestions refer to the <a href="Windows.html#Windows">Windows</a> chapter.
  579. </p>
  580. <H2><a name="Perl5_nn14"></a>31.4 The low-level interface</H2>
  581. <p>
  582. At its core, the Perl module uses a simple low-level interface
  583. to C function, variables, constants, and classes. This low-level interface
  584. can be used to control your application. However, it is also used to
  585. construct more user-friendly proxy classes as described in the next section.
  586. </p>
  587. <H3><a name="Perl5_nn15"></a>31.4.1 Functions</H3>
  588. <p>
  589. C functions are converted into new Perl built-in commands (or
  590. subroutines). For example:
  591. </p>
  592. <div class="targetlang"><pre>
  593. %module example
  594. int fact(int a);
  595. ...
  596. </pre></div>
  597. <p>
  598. Now, in Perl:
  599. </p>
  600. <div class="targetlang"><pre>
  601. use example;
  602. $a = &amp;example::fact(2);
  603. </pre></div>
  604. <H3><a name="Perl5_nn16"></a>31.4.2 Global variables</H3>
  605. <p>
  606. Global variables are handled using Perl's magic
  607. variable mechanism. SWIG generates a pair of functions
  608. that intercept read/write operations and attaches them to a Perl variable with
  609. the same name as the C global variable. Thus, an interface like this </p>
  610. <div class="targetlang"><pre>
  611. %module example;
  612. ...
  613. double Spam;
  614. ...
  615. </pre></div>
  616. <p>
  617. is accessed as follows:</p>
  618. <div class="targetlang"><pre>
  619. use example;
  620. print $example::Spam,"\n";
  621. $example::Spam = $example::Spam + 4
  622. # ... etc ...
  623. </pre></div>
  624. <p>
  625. If a variable is declared as <tt>const</tt>, it is wrapped as a
  626. read-only variable. Attempts to modify its value will result in an
  627. error.
  628. </p>
  629. <p>
  630. To make ordinary variables read-only, you can also use the <tt>%immutable</tt> directive. For example:
  631. </p>
  632. <div class="code">
  633. <pre>
  634. %{
  635. extern char *path;
  636. %}
  637. %immutable;
  638. extern char *path;
  639. %mutable;
  640. </pre>
  641. </div>
  642. <p>
  643. The <tt>%immutable</tt> directive stays in effect until it is explicitly disabled or cleared using
  644. <tt>%mutable</tt>.
  645. See the <a href="SWIG.html#SWIG_readonly_variables">Creating read-only variables</a> section for further details.
  646. </p>
  647. <p>
  648. It is also possible to tag a specific variable as read-only like this:
  649. </p>
  650. <div class="code">
  651. <pre>
  652. %{
  653. extern char *path;
  654. %}
  655. %immutable path;
  656. ...
  657. ...
  658. extern char *path; // Declared later in the input
  659. </pre>
  660. </div>
  661. <H3><a name="Perl5_nn17"></a>31.4.3 Constants</H3>
  662. <p>
  663. By default, constants are wrapped as read-only Perl variables. For example:
  664. </p>
  665. <div class="code">
  666. <pre>
  667. %module example
  668. #define FOO 42
  669. </pre>
  670. </div>
  671. <p>
  672. In Perl:
  673. </p>
  674. <div class="targetlang">
  675. <pre>
  676. use example;
  677. print $example::FOO,"\n"; # OK
  678. $example::FOO = 2; # Error
  679. </pre>
  680. </div>
  681. <p>
  682. Alternatively, if you use swig's <tt>-const</tt> option, constants are wrapped
  683. such that the leading $ isn't required (by using a constant subroutine), which
  684. usually gives a more natural Perl interface, for example:
  685. </p>
  686. <div class="targetlang">
  687. <pre>
  688. use example;
  689. print example::FOO,"\n";
  690. </pre>
  691. </div>
  692. <H3><a name="Perl5_nn18"></a>31.4.4 Pointers</H3>
  693. <p>
  694. SWIG represents pointers as blessed references. A blessed reference
  695. is the same as a Perl reference except that it has additional
  696. information attached to it indicating what kind of reference it
  697. is. That is, if you have a C declaration like this:</p>
  698. <div class="code"><pre>
  699. Matrix *new_Matrix(int n, int m);
  700. </pre></div>
  701. <p>
  702. The module returns a value generated as follows:
  703. </p>
  704. <div class="targetlang"><pre>
  705. $ptr = new_Matrix(int n, int m); # Save pointer return result
  706. bless $ptr, "p_Matrix"; # Bless it as a pointer to Matrix
  707. </pre></div>
  708. <p>
  709. SWIG uses the "blessing" to check the datatype of various pointers.
  710. In the event of a mismatch, an error or warning message is
  711. generated.</p>
  712. <p>
  713. To check to see if a value is the NULL pointer, use the
  714. <tt>defined()</tt> command:</p>
  715. <div class="targetlang"><pre>
  716. if (defined($ptr)) {
  717. print "Not a NULL pointer.";
  718. } else {
  719. print "Is a NULL pointer.";
  720. }
  721. </pre></div>
  722. <p>
  723. To create a NULL pointer, you should pass the <tt>undef</tt> value to
  724. a function.
  725. </p>
  726. <p>
  727. The "value" of a Perl reference is not the same as the underlying C
  728. pointer that SWIG wrapper functions return. Suppose that <tt>$a</tt>
  729. and <tt>$b</tt> are two references that point to the same C object.
  730. In general, <tt>$a</tt> and <tt>$b</tt> will be different--since they
  731. are different references. Thus, it is a mistake to check the equality
  732. of <tt>$a</tt> and <tt>$b</tt> to check the equality of two C
  733. pointers. The correct method to check equality of C pointers is to
  734. dereference them as follows:
  735. </p>
  736. <div class="targetlang"><pre>
  737. if ($$a == $$b) {
  738. print "a and b point to the same thing in C";
  739. } else {
  740. print "a and b point to different objects.";
  741. }
  742. </pre></div>
  743. <p>
  744. As much as you might be inclined to modify a pointer value directly
  745. from Perl, don't. Manipulating pointer values is architecture dependent and
  746. could cause your program to crash. Similarly, don't try to manually cast
  747. a pointer to a new type by reblessing a pointer. This
  748. may not work like you expect and it is particularly dangerous when
  749. casting C++ objects. If you need to cast a pointer or
  750. change its value, consider writing some helper functions instead. For
  751. example:
  752. </p>
  753. <div class="code">
  754. <pre>
  755. %inline %{
  756. /* C-style cast */
  757. Bar *FooToBar(Foo *f) {
  758. return (Bar *) f;
  759. }
  760. /* C++-style cast */
  761. Foo *BarToFoo(Bar *b) {
  762. return dynamic_cast&lt;Foo*&gt;(b);
  763. }
  764. Foo *IncrFoo(Foo *f, int i) {
  765. return f+i;
  766. }
  767. %}
  768. </pre>
  769. </div>
  770. <p>
  771. Also, if working with C++, you should always try
  772. to use the new C++ style casts. For example, in the above code, the
  773. C-style cast may return a bogus result whereas as the C++-style cast will return
  774. <tt>NULL</tt> if the conversion can't be performed.
  775. </p>
  776. <p>
  777. <b>Compatibility Note:</b> In earlier versions, SWIG tried to preserve the same pointer naming conventions
  778. as XS and <tt>xsubpp</tt>. Given the advancement of the SWIG typesystem and the growing differences between
  779. SWIG and XS, this is no longer supported.
  780. </p>
  781. <H3><a name="Perl5_nn19"></a>31.4.5 Structures</H3>
  782. <p>
  783. Access to the contents of a structure are provided through a set of low-level
  784. accessor functions as described in the "SWIG Basics" chapter. For example,
  785. </p>
  786. <div class="code"><pre>
  787. struct Vector {
  788. double x,y,z;
  789. };
  790. </pre></div>
  791. <p>
  792. gets mapped into the following collection of accessor functions:
  793. </p>
  794. <div class="code"><pre>
  795. struct Vector *new_Vector();
  796. void delete_Vector(Vector *v);
  797. double Vector_x_get(Vector *obj)
  798. void Vector_x_set(Vector *obj, double x)
  799. double Vector_y_get(Vector *obj)
  800. void Vector_y_set(Vector *obj, double y)
  801. double Vector_z_get(Vector *obj)
  802. void Vector_z_set(Vector *obj, double z)
  803. </pre></div>
  804. <p>
  805. These functions are then used to access structure data from Perl as follows:
  806. </p>
  807. <div class="targetlang"><pre>
  808. $v = example::new_Vector();
  809. print example::Vector_x_get($v),"\n"; # Get x component
  810. example::Vector_x_set($v,7.8); # Change x component
  811. </pre></div>
  812. <p>
  813. Similar access is provided for unions and the data members of C++ classes.
  814. </p>
  815. <p>
  816. <tt>const</tt> members of a structure are read-only. Data members
  817. can also be forced to be read-only using the <tt>%immutable</tt> directive. For example:
  818. </p>
  819. <div class="code">
  820. <pre>
  821. struct Foo {
  822. ...
  823. %immutable;
  824. int x; /* Read-only members */
  825. char *name;
  826. %mutable;
  827. ...
  828. };
  829. </pre>
  830. </div>
  831. <p>
  832. When <tt>char *</tt> members of a structure are wrapped, the contents are assumed to be
  833. dynamically allocated using <tt>malloc</tt> or <tt>new</tt> (depending on whether or not
  834. SWIG is run with the -c++ option). When the structure member is set, the old contents will be
  835. released and a new value created. If this is not the behavior you want, you will have to use
  836. a typemap (described later).
  837. </p>
  838. <p>
  839. Array members are normally wrapped as read-only. For example,
  840. </p>
  841. <div class="code">
  842. <pre>
  843. struct Foo {
  844. int x[50];
  845. };
  846. </pre>
  847. </div>
  848. <p>
  849. produces a single accessor function like this:
  850. </p>
  851. <div class="code">
  852. <pre>
  853. int *Foo_x_get(Foo *self) {
  854. return self-&gt;x;
  855. };
  856. </pre>
  857. </div>
  858. <p>
  859. If you want to set an array member, you will need to supply a "memberin" typemap
  860. described later in this chapter. As a special case, SWIG does generate
  861. code to set array members of type <tt>char</tt> (allowing you to store a Python
  862. string in the structure).
  863. </p>
  864. <p>
  865. When structure members are wrapped, they are handled as pointers. For example,
  866. </p>
  867. <div class="code">
  868. <pre>
  869. struct Foo {
  870. ...
  871. };
  872. struct Bar {
  873. Foo f;
  874. };
  875. </pre>
  876. </div>
  877. <p>
  878. generates accessor functions such as this:
  879. </p>
  880. <div class="code">
  881. <pre>
  882. Foo *Bar_f_get(Bar *b) {
  883. return &amp;b-&gt;f;
  884. }
  885. void Bar_f_set(Bar *b, Foo *val) {
  886. b-&gt;f = *val;
  887. }
  888. </pre>
  889. </div>
  890. <H3><a name="Perl5_nn20"></a>31.4.6 C++ classes</H3>
  891. <p>
  892. C++ classes are wrapped by building a set of low level accessor functions.
  893. Consider the following class:
  894. </p>
  895. <div class="code"><pre>
  896. class List {
  897. public:
  898. List();
  899. ~List();
  900. int search(char *item);
  901. void insert(char *item);
  902. void remove(char *item);
  903. char *get(int n);
  904. int length;
  905. static void print(List *l);
  906. };
  907. </pre></div>
  908. <p>
  909. When wrapped by SWIG, the following functions are created:
  910. </p>
  911. <div class="code"><pre>
  912. List *new_List();
  913. void delete_List(List *l);
  914. int List_search(List *l, char *item);
  915. void List_insert(List *l, char *item);
  916. void List_remove(List *l, char *item);
  917. char *List_get(List *l, int n);
  918. int List_length_get(List *l);
  919. void List_length_set(List *l, int n);
  920. void List_print(List *l);
  921. </pre></div>
  922. <p>
  923. In Perl, these functions are used in a straightforward manner:
  924. </p>
  925. <div class="targetlang"><pre>
  926. use example;
  927. $l = example::new_List();
  928. example::List_insert($l,"Ale");
  929. example::List_insert($l,"Stout");
  930. example::List_insert($l,"Lager")
  931. example::List_print($l)
  932. Lager
  933. Stout
  934. Ale
  935. print example::List_length_get($l),"\n";
  936. 3
  937. </pre></div>
  938. <p>
  939. At this low level, C++ objects are really just typed pointers. Member
  940. functions are accessed by calling a C-like wrapper with an instance pointer
  941. as the first argument. Although this interface is fairly primitive, it
  942. provides direct access to C++ objects. A higher level interface using Perl proxy classes
  943. can be built using these low-level accessors. This is described shortly.
  944. </p>
  945. <H3><a name="Perl5_nn21"></a>31.4.7 C++ classes and type-checking</H3>
  946. <p>
  947. The SWIG type-checker is fully aware of C++ inheritance. Therefore, if you have
  948. classes like this
  949. </p>
  950. <div class="code">
  951. <pre>
  952. class Foo {
  953. ...
  954. };
  955. class Bar : public Foo {
  956. ...
  957. };
  958. </pre>
  959. </div>
  960. <p>
  961. and a function
  962. </p>
  963. <div class="code">
  964. <pre>
  965. void spam(Foo *f);
  966. </pre>
  967. </div>
  968. <p>
  969. then the function <tt>spam()</tt> accepts <tt>Foo *</tt> or a pointer to any class derived from <tt>Foo</tt>.
  970. If necessary, the type-checker also adjusts the value of the pointer (as is necessary when
  971. multiple inheritance is used).
  972. </p>
  973. <H3><a name="Perl5_nn22"></a>31.4.8 C++ overloaded functions</H3>
  974. <p>
  975. If you have a C++ program with overloaded functions or methods, you will need to disambiguate
  976. those methods using <tt>%rename</tt>. For example:
  977. </p>
  978. <div class="code">
  979. <pre>
  980. /* Forward renaming declarations */
  981. %rename(foo_i) foo(int);
  982. %rename(foo_d) foo(double);
  983. ...
  984. void foo(int); // Becomes 'foo_i'
  985. void foo(char *c); // Stays 'foo' (not renamed)
  986. class Spam {
  987. public:
  988. void foo(int); // Becomes 'foo_i'
  989. void foo(double); // Becomes 'foo_d'
  990. ...
  991. };
  992. </pre>
  993. </div>
  994. <p>
  995. Now, in Perl, the methods are accessed as follows:
  996. </p>
  997. <div class="targetlang">
  998. <pre>
  999. use example;
  1000. example::foo_i(3);
  1001. $s = example::new_Spam();
  1002. example::Spam_foo_i($s,3);
  1003. example::Spam_foo_d($s,3.14);
  1004. </pre>
  1005. </div>
  1006. <p>
  1007. Please refer to the "SWIG Basics" chapter for more information.
  1008. </p>
  1009. <H3><a name="Perl5_nn23"></a>31.4.9 Operators</H3>
  1010. <p>
  1011. As of version 1.3.27 SWIG automatically renames the most common C++ operators, and maps them into the perl module with the proper 'use overload ...' so you don't need to do any work.
  1012. </p>
  1013. <p>
  1014. The following C++ operators are currently supported by the Perl module:
  1015. </p>
  1016. <ul>
  1017. <li>operator++ </li>
  1018. <li>operator-- </li>
  1019. <li>operator+ </li>
  1020. <li>operator- </li>
  1021. <li>operator* </li>
  1022. <li>operator/ </li>
  1023. <li>operator== </li>
  1024. <li>operator!= </li>
  1025. <li>operator% </li>
  1026. <li>operator&gt; </li>
  1027. <li>operator&lt; </li>
  1028. <li>operator and </li>
  1029. <li>operator or </li>
  1030. </ul>
  1031. <H3><a name="Perl5_nn24"></a>31.4.10 Modules and packages</H3>
  1032. <p>
  1033. When you create a SWIG extension, everything gets placed into
  1034. a single Perl module. The name of the module is determined by the
  1035. <tt>%module</tt> directive. To use the module, do the following:
  1036. </p>
  1037. <div class="targetlang"><pre>
  1038. $ perl5
  1039. use example; # load the example module
  1040. print example::fact(4),"\n" # Call a function in it
  1041. 24
  1042. </pre></div>
  1043. <p>
  1044. Usually, a module consists of a collection of code that is contained
  1045. within a single file. A package, on the other hand, is the Perl
  1046. equivalent of a namespace. A package is a lot like a module, except
  1047. that it is independent of files. Any number of files may be part of
  1048. the same package--or a package may be broken up into a collection of
  1049. modules if you prefer to think about it in this way.
  1050. </p>
  1051. <p>
  1052. SWIG installs its functions into a package with the same name as
  1053. the module. </p>
  1054. <p>
  1055. <b>Incompatible Change:</b> previous versions of SWIG enabled you to
  1056. change the name of the package by using the -package option, this
  1057. feature has been removed in order to properly support modules that
  1058. used nested namespaces, e.g. Foo::Bar::Baz. To give your module a
  1059. nested namespace simply provide the fully qualified name in your
  1060. %module directive: </p>
  1061. <div class="code"><pre>
  1062. %module "Foo::Bar::Baz"
  1063. </pre></div>
  1064. <p>
  1065. <b>NOTE:</b> the double quotes are necessary.
  1066. </p>
  1067. <p>
  1068. Using the <tt>package</tt> option of the <tt>%module</tt> directive allows
  1069. you to specify what Perl namespace that the module will be living in when
  1070. installed. This is useful in the situation where a module maintainer
  1071. wants to split a large module into smaller pieces to make maintenance
  1072. easier, but doesn't want to have that affect the module name used by
  1073. applications. So for example, if I wanted to split <tt>XML::Xerces</tt>
  1074. into <tt>XML::Xerces::SAX</tt>, etc. , but I wanted all the applications
  1075. to be able to access the classes using the <tt>XML::Xerces</tt> namespace
  1076. I could use:
  1077. </p>
  1078. <div class="code">
  1079. <pre>
  1080. %module(package="XML::Xerces") "XML::Xerces::SAX
  1081. </pre>
  1082. </div>
  1083. <p>
  1084. And now all the applications could use the class
  1085. <tt>XML::Xerces::SAXParser</tt>. Without the <tt>package</tt> directive
  1086. splitting the module would force applications to use the class
  1087. <tt>XML::Xerces::SAX::SAXParser</tt>. This could break compatibility for
  1088. existing applications that are already using the class under the name
  1089. <tt>XML::Xerces::SAXParser</tt>.
  1090. </p>
  1091. <!--
  1092. <p>
  1093. This can be changed by giving SWIG the -package
  1094. option:
  1095. </p>
  1096. <div class="code"><pre>
  1097. $ swig -perl -package Foo example.i
  1098. </pre></div>
  1099. <p>
  1100. In this case, you still create a module called `<tt>example</tt>' exactly as before, but
  1101. all of the functions in that module will be installed into the package
  1102. `<tt>Foo</tt>.' For example:
  1103. </p>
  1104. <div class="targetlang"><pre>
  1105. use example; # Load the module like before
  1106. print Foo::fact(4),"\n"; # Call a function in package FooBar
  1107. </pre></div>
  1108. -->
  1109. <H2><a name="Perl5_nn25"></a>31.5 Input and output parameters</H2>
  1110. <p>
  1111. A common problem in some C programs is handling parameters passed as simple pointers. For
  1112. example:
  1113. </p>
  1114. <div class="code">
  1115. <pre>
  1116. void add(int x, int y, int *result) {
  1117. *result = x + y;
  1118. }
  1119. </pre>
  1120. </div>
  1121. <p>
  1122. or perhaps
  1123. </p>
  1124. <div class="code">
  1125. <pre>
  1126. int sub(int *x, int *y) {
  1127. return *x+*y;
  1128. }
  1129. </pre>
  1130. </div>
  1131. <p>
  1132. The easiest way to handle these situations is to use the <tt>typemaps.i</tt> file. For example:
  1133. </p>
  1134. <div class="code">
  1135. <pre>
  1136. %module example
  1137. %include "typemaps.i"
  1138. void add(int, int, int *OUTPUT);
  1139. int sub(int *INPUT, int *INPUT);
  1140. </pre>
  1141. </div>
  1142. <p>
  1143. In Perl, this allows you to pass simple values. For example:
  1144. </p>
  1145. <div class="targetlang">
  1146. <pre>
  1147. $a = example::add(3,4);
  1148. print "$a\n";
  1149. 7
  1150. $b = example::sub(7,4);
  1151. print "$b\n";
  1152. 3
  1153. </pre>
  1154. </div>
  1155. <p>
  1156. Notice how the <tt>INPUT</tt> parameters allow integer values to be passed instead of pointers
  1157. and how the <tt>OUTPUT</tt> parameter creates a return result.
  1158. </p>
  1159. <p>
  1160. If you don't want to use the names <tt>INPUT</tt> or <tt>OUTPUT</tt>, use the <tt>%apply</tt>
  1161. directive. For example:
  1162. </p>
  1163. <div class="code">
  1164. <pre>
  1165. %module example
  1166. %include "typemaps.i"
  1167. %apply int *OUTPUT { int *result };
  1168. %apply int *INPUT { int *x, int *y};
  1169. void add(int x, int y, int *result);
  1170. int sub(int *x, int *y);
  1171. </pre>
  1172. </div>
  1173. <p>
  1174. If a function mutates one of its parameters like this,
  1175. </p>
  1176. <div class="code">
  1177. <pre>
  1178. void negate(int *x) {
  1179. *x = -(*x);
  1180. }
  1181. </pre>
  1182. </div>
  1183. <p>
  1184. you can use <tt>INOUT</tt> like this:
  1185. </p>
  1186. <div class="code">
  1187. <pre>
  1188. %include "typemaps.i"
  1189. ...
  1190. void negate(int *INOUT);
  1191. </pre>
  1192. </div>
  1193. <p>
  1194. In Perl, a mutated parameter shows up as a return value. For example:
  1195. </p>
  1196. <div class="targetlang">
  1197. <pre>
  1198. $a = example::negate(3);
  1199. print "$a\n";
  1200. -3
  1201. </pre>
  1202. </div>
  1203. <p>
  1204. The most common use of these special typemap rules is to handle functions that
  1205. return more than one value. For example, sometimes a function returns a result
  1206. as well as a special error code:
  1207. </p>
  1208. <div class="code">
  1209. <pre>
  1210. /* send message, return number of bytes sent, along with success code */
  1211. int send_message(char *text, int len, int *success);
  1212. </pre>
  1213. </div>
  1214. <p>
  1215. To wrap such a function, simply use the <tt>OUTPUT</tt> rule above. For example:
  1216. </p>
  1217. <div class="code">
  1218. <pre>
  1219. %module example
  1220. %include "typemaps.i"
  1221. %apply int *OUTPUT { int *success };
  1222. ...
  1223. int send_message(char *text, int *success);
  1224. </pre>
  1225. </div>
  1226. <p>
  1227. When used in Perl, the function will return multiple values.
  1228. </p>
  1229. <div class="targetlang">
  1230. <pre>
  1231. ($bytes, $success) = example::send_message("Hello World");
  1232. </pre>
  1233. </div>
  1234. <p>
  1235. Another common use of multiple return values are in query functions. For example:
  1236. </p>
  1237. <div class="code">
  1238. <pre>
  1239. void get_dimensions(Matrix *m, int *rows, int *columns);
  1240. </pre>
  1241. </div>
  1242. <p>
  1243. To wrap this, you might use the following:
  1244. </p>
  1245. <div class="code">
  1246. <pre>
  1247. %module example
  1248. %include "typemaps.i"
  1249. %apply int *OUTPUT { int *rows, int *columns };
  1250. ...
  1251. void get_dimensions(Matrix *m, int *rows, *columns);
  1252. </pre>
  1253. </div>
  1254. <p>
  1255. Now, in Perl:
  1256. </p>
  1257. <div class="targetlang">
  1258. <pre>
  1259. ($r,$c) = example::get_dimensions($m);
  1260. </pre>
  1261. </div>
  1262. <p>
  1263. In certain cases, it is possible to treat Perl references as C pointers. To do this, use the <tt>REFERENCE</tt> typemap. For
  1264. example:
  1265. </p>
  1266. <div class="code">
  1267. <pre>
  1268. %module example
  1269. %include "typemaps.i"
  1270. void add(int x, int y, int *REFERENCE);
  1271. </pre>
  1272. </div>
  1273. <p>
  1274. In Perl:
  1275. </p>
  1276. <div class="targetlang">
  1277. <pre>
  1278. use example;
  1279. $c = 0.0;
  1280. example::add(3,4,\$c);
  1281. print "$c\n";
  1282. 7
  1283. </pre>
  1284. </div>
  1285. <p>
  1286. <b>Note:</b> The <tt>REFERENCE</tt> feature is only currently supported for numeric types (integers and floating point).
  1287. </p>
  1288. <H2><a name="Perl5_nn26"></a>31.6 Exception handling</H2>
  1289. <p>
  1290. The SWIG <tt>%exception</tt> directive can be used to create a
  1291. user-definable exception handler for converting exceptions in your
  1292. C/C++ program into Perl exceptions. The chapter on customization features
  1293. contains more details, but suppose you have a C++ class like the
  1294. following:
  1295. </p>
  1296. <div class="code"><pre>
  1297. class RangeError {}; // Used for an exception
  1298. class DoubleArray {
  1299. private:
  1300. int n;
  1301. double *ptr;
  1302. public:
  1303. // Create a new array of fixed size
  1304. DoubleArray(int size) {
  1305. ptr = new double[size];
  1306. n = size;
  1307. }
  1308. // Destroy an array
  1309. ~DoubleArray() {
  1310. delete ptr;
  1311. }
  1312. // Return the length of the array
  1313. int length() {
  1314. return n;
  1315. }
  1316. // Get an item from the array and perform bounds checking.
  1317. double getitem(int i) {
  1318. if ((i &gt;= 0) &amp;&amp; (i &lt; n))
  1319. return ptr[i];
  1320. else
  1321. throw RangeError();
  1322. }
  1323. // Set an item in the array and perform bounds checking.
  1324. void setitem(int i, double val) {
  1325. if ((i &gt;= 0) &amp;&amp; (i &lt; n))
  1326. ptr[i] = val;
  1327. else {
  1328. throw RangeError();
  1329. }
  1330. }
  1331. };
  1332. </pre></div>
  1333. <p>
  1334. Since several methods in this class can throw an exception
  1335. for an out-of-bounds access, you might want to catch
  1336. this in the Perl extension by writing the following in an
  1337. interface file:
  1338. </p>
  1339. <div class="code"><pre>
  1340. %exception {
  1341. try {
  1342. $action
  1343. }
  1344. catch (RangeError) {
  1345. croak("Array index out-of-bounds");
  1346. }
  1347. }
  1348. class DoubleArray {
  1349. ...
  1350. };
  1351. </pre></div>
  1352. <p>
  1353. The exception handling code is inserted directly into generated wrapper
  1354. functions. The <tt>$action</tt> variable is replaced with the C/C++
  1355. code being executed by the wrapper. When an exception handler
  1356. is defined, errors can be caught and used to gracefully generate a Perl error
  1357. instead of forcing the entire program to terminate with an uncaught error.
  1358. </p>
  1359. <p>
  1360. As shown, the exception handling code will be added to every wrapper function.
  1361. Since this is somewhat inefficient. You might consider refining the
  1362. exception handler to only apply to specific methods like this:
  1363. </p>
  1364. <div class="code">
  1365. <pre>
  1366. %exception getitem {
  1367. try {
  1368. $action
  1369. }
  1370. catch (RangeError) {
  1371. croak("Array index out-of-bounds");
  1372. }
  1373. }
  1374. %exception setitem {
  1375. try {
  1376. $action
  1377. }
  1378. catch (RangeError) {
  1379. croak("Array index out-of-bounds");
  1380. }
  1381. }
  1382. </pre>
  1383. </div>
  1384. <p>
  1385. In this case, the exception handler is only attached to methods and functions
  1386. named <tt>getitem</tt> and <tt>setitem</tt>.
  1387. </p>
  1388. <p>
  1389. If you had a lot of different methods, you can avoid extra typing by using a macro.
  1390. For example:
  1391. </p>
  1392. <div class="code">
  1393. <pre>
  1394. %define RANGE_ERROR
  1395. {
  1396. try {
  1397. $action
  1398. }
  1399. catch (RangeError) {
  1400. croak("Array index out-of-bounds");
  1401. }
  1402. }
  1403. %enddef
  1404. %exception getitem RANGE_ERROR;
  1405. %exception setitem RANGE_ERROR;
  1406. </pre>
  1407. </div>
  1408. <p>
  1409. Since SWIG's exception handling is user-definable, you are not limited to C++ exception handling.
  1410. See the chapter on "<a href="Customization.html#Customization">Customization features</a>" for more examples.
  1411. </p>
  1412. <p>
  1413. <b>Compatibility note:</b> In SWIG1.1, exceptions were defined using the older <tt>%except</tt> directive:
  1414. </p>
  1415. <div class="code">
  1416. <pre>
  1417. %except(python) {
  1418. try {
  1419. $function
  1420. }
  1421. catch (RangeError) {
  1422. croak("Array index out-of-bounds");
  1423. }
  1424. }
  1425. </pre>
  1426. </div>
  1427. <p>
  1428. This is still supported, but it is deprecated. The newer <tt>%exception</tt> directive provides the same
  1429. functionality, but it has additional capabilities that make it more powerful.
  1430. </p>
  1431. <H2><a name="Perl5_nn27"></a>31.7 Remapping datatypes with typemaps</H2>
  1432. <p>
  1433. This section describes how you can modify SWIG's default wrapping behavior
  1434. for various C/C++ datatypes using the <tt>%typemap</tt> directive. This
  1435. is an advanced topic that assumes familiarity with the Perl C API as well
  1436. as the material in the "<a href="Typemaps.html#Typemaps">Typemaps</a>" chapter.
  1437. </p>
  1438. <p>
  1439. Before proceeding, it should be stressed that typemaps are <em>not</em> a required
  1440. part of using SWIG---the default wrapping behavior is enough in most cases.
  1441. Typemaps are only used if you want to change some aspect of the primitive
  1442. C-Perl interface.
  1443. </p>
  1444. <H3><a name="Perl5_nn28"></a>31.7.1 A simple typemap example</H3>
  1445. <p>
  1446. A typemap is nothing more than a code generation rule that is attached to
  1447. a specific C datatype. For example, to convert integers from Perl to C,
  1448. you might define a typemap like this:
  1449. </p>
  1450. <div class="code"><pre>
  1451. %module example
  1452. %typemap(in) int {
  1453. $1 = (int) SvIV($input);
  1454. printf("Received an integer : %d\n", $1);
  1455. }
  1456. ...
  1457. %inline %{
  1458. extern int fact(int n);
  1459. %}
  1460. </pre></div>
  1461. <p>
  1462. Typemaps are always associated with some specific aspect of code generation.
  1463. In this case, the "in" method refers to the conversion of input arguments
  1464. to C/C++. The datatype <tt>int</tt> is the datatype to which the typemap
  1465. will be applied. The supplied C code is used to convert values. In this
  1466. code a number of special variable prefaced by a <tt>$</tt> are used. The
  1467. <tt>$1</tt> variable is placeholder for a local variable of type <tt>int</tt>.
  1468. The <tt>$input</tt> variable is the input object (usually a <tt>SV *</tt>).
  1469. </p>
  1470. <p>
  1471. When this example is used in Perl5, it will operate as follows:
  1472. </p>
  1473. <div class="targetlang"><pre>
  1474. use example;
  1475. $n = example::fact(6);
  1476. print "$n\n";
  1477. ...
  1478. Output:
  1479. Received an integer : 6
  1480. 720
  1481. </pre></div>
  1482. <p>
  1483. The application of a typemap to specific datatypes and argument names involves
  1484. more than simple text-matching--typemaps are fully integrated into the
  1485. SWIG type-system. When you define a typemap for <tt>int</tt>, that typemap
  1486. applies to <tt>int</tt> and qualified variations such as <tt>const int</tt>. In addition,
  1487. the typemap system follows <tt>typedef</tt> declarations. For example:
  1488. </p>
  1489. <div class="targetlang">
  1490. <pre>
  1491. %typemap(in) int n {
  1492. $1 = (int) SvIV($input);
  1493. printf("n = %d\n",$1);
  1494. }
  1495. %inline %{
  1496. typedef int Integer;
  1497. extern int fact(Integer n); // Above typemap is applied
  1498. %}
  1499. </pre>
  1500. </div>
  1501. <p>
  1502. It should be noted that the matching of <tt>typedef</tt> only occurs in one direction. If you
  1503. defined a typemap for <tt>Integer</tt>, it is not applied to arguments of
  1504. type <tt>int</tt>.
  1505. </p>
  1506. <p>
  1507. Typemaps can also be defined for groups of consecutive arguments. For example:
  1508. </p>
  1509. <div class="targetlang">
  1510. <pre>
  1511. %typemap(in) (char *str, unsigned len) {
  1512. $1 = SvPV($input,$2);
  1513. };
  1514. int count(char c, char *str, unsigned len);
  1515. </pre>
  1516. </div>
  1517. <p>
  1518. When a multi-argument typemap is defined, the arguments are always handled as a single
  1519. Perl object. This allows the function to be used like this (notice how the length
  1520. parameter is omitted):
  1521. </p>
  1522. <div class="targetlang">
  1523. <pre>
  1524. example::count("e","Hello World");
  1525. 1
  1526. &gt;&gt;&gt;
  1527. </pre>
  1528. </div>
  1529. <H3><a name="Perl5_nn29"></a>31.7.2 Perl5 typemaps</H3>
  1530. <p>
  1531. The previous section illustrated an "in" typemap for converting Perl objects to C.
  1532. A variety of different typemap methods are defined by the Perl module. For example,
  1533. to convert a C integer back into a Perl object, you might define an "out" typemap
  1534. like this:
  1535. </p>
  1536. <div class="targetlang">
  1537. <pre>
  1538. %typemap(out) int {
  1539. $result = sv_newmortal();
  1540. set_setiv($result, (IV) $1);
  1541. argvi++;
  1542. }
  1543. </pre>
  1544. </div>
  1545. <p>
  1546. The following typemap methods are available:
  1547. </p>
  1548. <p>
  1549. <tt>%typemap(in)</tt>
  1550. </p>
  1551. <div class="indent">
  1552. Converts Perl5 object to input function arguments.
  1553. </div>
  1554. <p>
  1555. <tt>%typemap(out)</tt>
  1556. </p>
  1557. <div class="indent">
  1558. Converts function return value to a Perl5 value.
  1559. </div>
  1560. <p>
  1561. <tt>%typemap(varin)</tt>
  1562. </p>
  1563. <div class="indent">
  1564. Converts a Perl5 object to a global variable.
  1565. </div>
  1566. <p>
  1567. <tt>%typemap(varout)</tt>
  1568. </p>
  1569. <div class="indent">
  1570. Converts a global variable to a Perl5 object.
  1571. </div>
  1572. <p>
  1573. <tt>%typemap(freearg)</tt>
  1574. </p>
  1575. <div class="indent">
  1576. Cleans up a function argument after a function call
  1577. </div>
  1578. <p>
  1579. <tt>%typemap(argout)</tt>
  1580. </p>
  1581. <div class="indent">
  1582. Output argument handling
  1583. </div>
  1584. <p>
  1585. <tt>%typemap(ret)</tt>
  1586. </p>
  1587. <div class="indent">
  1588. Clean up return value from a function.
  1589. </div>
  1590. <p>
  1591. <tt>%typemap(memberin)</tt>
  1592. </p>
  1593. <div class="indent">
  1594. Setting of C++ member data (all languages).
  1595. </div>
  1596. <p>
  1597. <tt>%typemap(memberout)</tt>
  1598. </p>
  1599. <div class="indent">
  1600. Return of C++ member data (all languages).
  1601. </div>
  1602. <p>
  1603. <tt>%typemap(check)</tt>
  1604. </p>
  1605. <div class="indent">
  1606. Check value of input parameter.
  1607. </div>
  1608. <H3><a name="Perl5_nn30"></a>31.7.3 Typemap variables</H3>
  1609. <p>
  1610. Within typemap code, a number of special variables prefaced with a <tt>$</tt> may appear.
  1611. A full list of variables can be found in the "<a href="Typemaps.html#Typemaps">Typemaps</a>" chapter.
  1612. This is a list of the most common variables:
  1613. </p>
  1614. <p>
  1615. <tt>$1</tt>
  1616. </p>
  1617. <div class="indent">
  1618. A C local variable corresponding to the actual type specified in the
  1619. <tt>%typemap</tt> directive. For input values, this is a C local variable
  1620. that's supposed to hold an argument value. For output values, this is
  1621. the raw result that's supposed to be returned to Perl.
  1622. </div>
  1623. <p>
  1624. <tt>$input</tt>
  1625. </p>
  1626. <div class="indent">
  1627. A Perl object holding the value of an argument of variable value.
  1628. </div>
  1629. <p>
  1630. <tt>$result</tt>
  1631. </p>
  1632. <div class="indent">
  1633. A Perl object that holds the result to be returned to Perl.
  1634. </div>
  1635. <p>
  1636. <tt>$1_name</tt>
  1637. </p>
  1638. <div class="indent">
  1639. The parameter name that was matched.
  1640. </div>
  1641. <p>
  1642. <tt>$1_type</tt>
  1643. </p>
  1644. <div class="indent">
  1645. The actual C datatype matched by the typemap.
  1646. </div>
  1647. <p>
  1648. <tt>$1_ltype</tt>
  1649. </p>
  1650. <div class="indent">
  1651. An assignable version of the datatype matched by the typemap (a type that can appear on the left-hand-side of
  1652. a C assignment operation). This type is stripped of qualifiers and may be an altered version of <tt>$1_type</tt>.
  1653. All arguments and local variables in wrapper functions are declared using this type so that their values can be
  1654. properly assigned.
  1655. </div>
  1656. <p>
  1657. <tt>$symname</tt>
  1658. </p>
  1659. <div class="indent">
  1660. The Perl name of the wrapper function being created.
  1661. </div>
  1662. <H3><a name="Perl5_nn31"></a>31.7.4 Useful functions</H3>
  1663. <p>
  1664. When writing typemaps, it is necessary to work directly with Perl5
  1665. objects. This, unfortunately, can be a daunting task. Consult the
  1666. "perlguts" man-page for all of the really ugly details. A short
  1667. summary of commonly used functions is provided here for reference. It
  1668. should be stressed that SWIG can be used quite effectively without
  1669. knowing any of these details--especially now that there are typemap
  1670. libraries that can already been written.
  1671. </p>
  1672. <p>
  1673. <b>Perl Integer Functions</b>
  1674. </p>
  1675. <div class="code">
  1676. <pre>
  1677. int SvIV(SV *);
  1678. void sv_setiv(SV *sv, IV value);
  1679. SV *newSViv(IV value);
  1680. int SvIOK(SV *);
  1681. </pre>
  1682. </div>
  1683. <p>
  1684. <b>Perl Floating Point Functions</b>
  1685. </p>
  1686. <div class="code">
  1687. <pre>
  1688. double SvNV(SV *);
  1689. void sv_setnv(SV *, double value);
  1690. SV *newSVnv(double value);
  1691. int SvNOK(SV *);
  1692. </pre>
  1693. </div>
  1694. <p>
  1695. <b>Perl String Functions</b>
  1696. </p>
  1697. <div class="code">
  1698. <pre>
  1699. char *SvPV(SV *, STRLEN len);
  1700. void sv_setpv(SV *, char *val);
  1701. void sv_setpvn(SV *, char *val, STRLEN len);
  1702. SV *newSVpv(char *value, STRLEN len);
  1703. int SvPOK(SV *);
  1704. void sv_catpv(SV *, char *);
  1705. void sv_catpvn(SV *, char *, STRLEN);
  1706. </pre>
  1707. </div>
  1708. <p>
  1709. <b>Perl References</b>
  1710. </p>
  1711. <div class="code">
  1712. <pre>
  1713. void sv_setref_pv(SV *, char *, void *ptr);
  1714. int sv_isobject(SV *);
  1715. SV *SvRV(SV *);
  1716. int sv_isa(SV *, char *0;
  1717. </pre>
  1718. </div>
  1719. <H2><a name="Perl5_nn32"></a>31.8 Typemap Examples</H2>
  1720. <p>
  1721. This section includes a few examples of typemaps. For more examples, you
  1722. might look at the files "<tt>perl5.swg</tt>" and "<tt>typemaps.i</tt>" in
  1723. the SWIG library.
  1724. </p>
  1725. <H3><a name="Perl5_nn33"></a>31.8.1 Converting a Perl5 array to a char **</H3>
  1726. <p>
  1727. A common problem in many C programs is the processing of command line
  1728. arguments, which are usually passed in an array of NULL terminated
  1729. strings. The following SWIG interface file allows a Perl5 array
  1730. reference to be used as a char ** datatype.
  1731. </p>
  1732. <div class="code"><pre>
  1733. %module argv
  1734. // This tells SWIG to treat char ** as a special case
  1735. %typemap(in) char ** {
  1736. AV *tempav;
  1737. I32 len;
  1738. int i;
  1739. SV **tv;
  1740. if (!SvROK($input))
  1741. croak("Argument $argnum is not a reference.");
  1742. if (SvTYPE(SvRV($input)) != SVt_PVAV)
  1743. croak("Argument $argnum is not an array.");
  1744. tempav = (AV*)SvRV($input);
  1745. len = av_len(tempav);
  1746. $1 = (char **) malloc((len+2)*sizeof(char *));
  1747. for (i = 0; i &lt;= len; i++) {
  1748. tv = av_fetch(tempav, i, 0);
  1749. $1[i] = (char *) SvPV(*tv,PL_na);
  1750. }
  1751. $1[i] = NULL;
  1752. };
  1753. // This cleans up the char ** array after the function call
  1754. %typemap(freearg) char ** {
  1755. free($1);
  1756. }
  1757. // Creates a new Perl array and places a NULL-terminated char ** into it
  1758. %typemap(out) char ** {
  1759. AV *myav;
  1760. SV **svs;
  1761. int i = 0,len = 0;
  1762. /* Figure out how many elements we have */
  1763. while ($1[len])
  1764. len++;
  1765. svs = (SV **) malloc(len*sizeof(SV *));
  1766. for (i = 0; i &lt; len ; i++) {
  1767. svs[i] = sv_newmortal();
  1768. sv_setpv((SV*)svs[i],$1[i]);
  1769. };
  1770. myav = av_make(len,svs);
  1771. free(svs);
  1772. $result = newRV_noinc((SV*)myav);
  1773. sv_2mortal($result);
  1774. argvi++;
  1775. }
  1776. // Now a few test functions
  1777. %inline %{
  1778. int print_args(char **argv) {
  1779. int i = 0;
  1780. while (argv[i]) {
  1781. printf("argv[%d] = %s\n", i,argv[i]);
  1782. i++;
  1783. }
  1784. return i;
  1785. }
  1786. // Returns a char ** list
  1787. char **get_args() {
  1788. static char *values[] = { "Dave", "Mike", "Susan", "John", "Michelle", 0};
  1789. return &amp;values[0];
  1790. }
  1791. %}
  1792. </pre></div>
  1793. <p>
  1794. When this module is compiled, the wrapped C functions can be used in a
  1795. Perl script as follows:
  1796. </p>
  1797. <div class="targetlang"><pre>
  1798. use argv;
  1799. @a = ("Dave", "Mike", "John", "Mary"); # Create an array of strings
  1800. argv::print_args(\@a); # Pass it to our C function
  1801. $b = argv::get_args(); # Get array of strings from C
  1802. print @$b,"\n"; # Print it out
  1803. </pre></div>
  1804. <H3><a name="Perl5_nn34"></a>31.8.2 Return values</H3>
  1805. <p>
  1806. Return values are placed on the argument stack of each wrapper
  1807. function. The current value of the argument stack pointer is
  1808. contained in a variable <tt>argvi</tt>. Whenever a new output value
  1809. is added, it is critical that this value be incremented. For multiple
  1810. output values, the final value of <tt>argvi</tt> should be the total
  1811. number of output values.
  1812. </p>
  1813. <p>
  1814. The total number of return values should not exceed the number of
  1815. input values unless you explicitly extend the argument stack. This
  1816. can be done using the <tt>EXTEND()</tt> macro as in:
  1817. </p>
  1818. <div class="code"><pre>
  1819. %typemap(argout) int *OUTPUT {
  1820. if (argvi &gt;= items) {
  1821. EXTEND(sp,1); /* Extend the stack by 1 object */
  1822. }
  1823. $result = sv_newmortal();
  1824. sv_setiv($target,(IV) *($1));
  1825. argvi++;
  1826. }
  1827. </pre></div>
  1828. <H3><a name="Perl5_nn35"></a>31.8.3 Returning values from arguments</H3>
  1829. <p>
  1830. Sometimes it is desirable for a function to return a value in one of
  1831. its arguments. This example describes the implementation of the <tt>OUTPUT</tt> typemap.
  1832. </p>
  1833. <div class="code"><pre>
  1834. %module return
  1835. // This tells SWIG to treat an double * argument with name 'OutDouble' as
  1836. // an output value.
  1837. %typemap(argout) double *OUTPUT {
  1838. $result = sv_newmortal();
  1839. sv_setnv($result, *$input);
  1840. argvi++; /* Increment return count -- important! */
  1841. }
  1842. // We don't care what the input value is. Ignore, but set to a temporary variable
  1843. %typemap(in,numinputs=0) double *OUTPUT(double junk) {
  1844. $1 = &amp;junk;
  1845. }
  1846. // Now a function to test it
  1847. %{
  1848. /* Returns the first two input arguments */
  1849. int multout(double a, double b, double *out1, double *out2) {
  1850. *out1 = a;
  1851. *out2 = b;
  1852. return 0;
  1853. };
  1854. %}
  1855. // If we name both parameters OutDouble both will be output
  1856. int multout(double a, double b, double *OUTPUT, double *OUTPUT);
  1857. ...
  1858. </pre></div>
  1859. <p>
  1860. When this function is called, the output arguments are appended to the stack used
  1861. to return results. This shows up an array in Perl.
  1862. For example:
  1863. </p>
  1864. <div class="targetlang"><pre>
  1865. @r = multout(7,13);
  1866. print "multout(7,13) = @r\n";
  1867. ($x,$y) = multout(7,13);
  1868. </pre></div>
  1869. <H3><a name="Perl5_nn36"></a>31.8.4 Accessing array structure members</H3>
  1870. <p>
  1871. Consider the following data structure:
  1872. </p>
  1873. <div class="code"><pre>
  1874. #define SIZE 8
  1875. typedef struct {
  1876. int values[SIZE];
  1877. ...
  1878. } Foo;
  1879. </pre></div>
  1880. <p>
  1881. By default, SWIG doesn't know how to the handle the values structure
  1882. member it's an array, not a pointer. In this case, SWIG makes the array member
  1883. read-only. Reading will simply return a pointer to the first item in the array.
  1884. To make the member writable, a "memberin" typemap can be used.
  1885. </p>
  1886. <div class="code"><pre>
  1887. %typemap(memberin) int [SIZE] {
  1888. int i;
  1889. for (i = 0; i &lt; SIZE; i++) {
  1890. $1[i] = $input[i];
  1891. }
  1892. }
  1893. </pre></div>
  1894. <p>
  1895. Whenever a <tt>int [SIZE]</tt> member is encountered in a structure
  1896. or class, this typemap provides a safe mechanism for setting its
  1897. value.
  1898. </p>
  1899. <p>
  1900. As in the previous example, the typemap can be generalized for any dimension.
  1901. For example:
  1902. </p>
  1903. <div class="code"><pre>
  1904. %typemap(memberin) int [ANY] {
  1905. int i;
  1906. for (i = 0; i &lt; $1_dim0; i++) {
  1907. $1[i] = $input[i];
  1908. }
  1909. }
  1910. </pre></div>
  1911. <p>
  1912. When setting structure members, the input object is always assumed to
  1913. be a C array of values that have already been converted from the
  1914. target language. Because of this, the <tt>memberin</tt> typemap is
  1915. almost always combined with the use of an "in" typemap. For example,
  1916. the "in" typemap in the previous section would be used to convert an
  1917. <tt>int[]</tt> array to C whereas the "memberin" typemap would be used
  1918. to copy the converted array into a C data structure.
  1919. </p>
  1920. <H3><a name="Perl5_nn37"></a>31.8.5 Turning Perl references into C pointers</H3>
  1921. <p>
  1922. A frequent confusion on the SWIG mailing list is errors caused by the
  1923. mixing of Perl references and C pointers. For example, suppose you
  1924. have a C function that modifies its arguments like this:
  1925. </p>
  1926. <div class="code"><pre>
  1927. void add(double a, double b, double *c) {
  1928. *c = a + b;
  1929. }
  1930. </pre></div>
  1931. <p>
  1932. A common misinterpretation of this function is the following Perl script:
  1933. </p>
  1934. <div class="targetlang"><pre>
  1935. # Perl script
  1936. $a = 3.5;
  1937. $b = 7.5;
  1938. $c = 0.0; # Output value
  1939. add($a,$b,\$c); # Place result in c (Except that it doesn't work)
  1940. </pre></div>
  1941. <p>
  1942. To make this work with a reference, you can use a typemap such as this:
  1943. </p>
  1944. <div class="code"><pre>
  1945. %typemap(in) double * (double dvalue) {
  1946. SV* tempsv;
  1947. if (!SvROK($input)) {
  1948. croak("expected a reference\n");
  1949. }
  1950. tempsv = SvRV($input);
  1951. if ((!SvNOK(tempsv)) &amp;&amp; (!SvIOK(tempsv))) {
  1952. croak("expected a double reference\n");
  1953. }
  1954. dvalue = SvNV(tempsv);
  1955. $1 = &amp;dvalue;
  1956. }
  1957. %typemap(argout) double * {
  1958. SV *tempsv;
  1959. tempsv = SvRV($input);
  1960. sv_setnv(tempsv, *$1);
  1961. }
  1962. </pre></div>
  1963. <p>
  1964. Now, if you place this before the add function, you can do this:
  1965. </p>
  1966. <div class="targetlang"><pre>
  1967. $a = 3.5;
  1968. $b = 7.5;
  1969. $c = 0.0;
  1970. add($a,$b,\$c); # Now it works!
  1971. print "$c\n";
  1972. </pre></div>
  1973. <H3><a name="Perl5_nn38"></a>31.8.6 Pointer handling</H3>
  1974. <p>
  1975. Occasionally, it might be necessary to convert pointer values that have
  1976. been stored using the SWIG typed-pointer representation. To convert a pointer from Perl to C, the following
  1977. function is used:
  1978. </p>
  1979. <p>
  1980. <tt>
  1981. int SWIG_ConvertPtr(SV *obj, void **ptr, swig_type_info *ty, int flags)
  1982. </tt>
  1983. </p>
  1984. <div class="indent">
  1985. Converts a Perl object <tt>obj</tt> to a C pointer. The result of the conversion is placed
  1986. into the pointer located at <tt>ptr</tt>. <tt>ty</tt> is a SWIG type descriptor structure.
  1987. <tt>flags</tt> is used to handle error checking and other aspects of conversion. <tt>flags</tt> is
  1988. currently undefined and reserved for future expansion. Returns 0 on success and -1 on error.
  1989. </div>
  1990. <p>
  1991. <tt>
  1992. void *SWIG_MakePtr(SV *obj, void *ptr, swig_type_info *ty, int flags)</tt>
  1993. </p>
  1994. <div class="indent">
  1995. Creates a new Perl pointer object. <tt>obj</tt> is a Perl SV that has been initialized to hold the result,
  1996. <tt>ptr</tt> is the pointer to convert, <tt>ty</tt> is the SWIG type descriptor structure that
  1997. describes the type, and <tt>flags</tt> is a flag that controls properties of the conversion. <tt>flags</tt> is currently undefined
  1998. and reserved.
  1999. </div>
  2000. <p>
  2001. Both of these functions require the use of a special SWIG
  2002. type-descriptor structure. This structure contains information about
  2003. the mangled name of the datatype, type-equivalence information, as
  2004. well as information about converting pointer values under C++
  2005. inheritance. For a type of <tt>Foo *</tt>, the type descriptor structure
  2006. is usually accessed as follows:
  2007. </p>
  2008. <div class="code">
  2009. <pre>
  2010. Foo *f;
  2011. if (SWIG_ConvertPtr($input, (void **) &amp;f, SWIGTYPE_p_Foo, 0) == -1) return NULL;
  2012. SV *sv = sv_newmortal();
  2013. SWIG_MakePtr(sv, f, SWIGTYPE_p_Foo, 0);
  2014. </pre>
  2015. </div>
  2016. <p>
  2017. In a typemap, the type descriptor should always be accessed using the special typemap
  2018. variable <tt>$1_descriptor</tt>. For example:
  2019. </p>
  2020. <div class="code">
  2021. <pre>
  2022. %typemap(in) Foo * {
  2023. if ((SWIG_ConvertPtr($input,(void **) &amp;$1, $1_descriptor,0)) == -1) return NULL;
  2024. }
  2025. </pre>
  2026. </div>
  2027. <p>
  2028. If necessary, the descriptor for any type can be obtained using the <tt>$descriptor()</tt> macro in a typemap.
  2029. For example:
  2030. </p>
  2031. <div class="code">
  2032. <pre>
  2033. %typemap(in) Foo * {
  2034. if ((SWIG_ConvertPtr($input,(void **) &amp;$1, $descriptor(Foo *), 0)) == -1) return NULL;
  2035. }
  2036. </pre>
  2037. </div>
  2038. <H2><a name="Perl5_nn39"></a>31.9 Proxy classes</H2>
  2039. <p>
  2040. <b>Out of date. Needs update.</b>
  2041. </p>
  2042. <p>
  2043. Using the low-level procedural interface, SWIG can also construct a
  2044. high-level object oriented interface to C structures and C++ classes.
  2045. This is done by constructing a Perl proxy class (also known as a shadow class)
  2046. that provides an OO wrapper
  2047. to the underlying code. This section describes the implementation
  2048. details of the proxy interface.
  2049. </p>
  2050. <H3><a name="Perl5_nn40"></a>31.9.1 Preliminaries</H3>
  2051. <p>
  2052. Proxy classes, are generated by default. If you want to turn them off, use the <tt>-noproxy</tt> command line option.
  2053. For example:
  2054. </p>
  2055. <div class="code">
  2056. <pre>
  2057. $ swig -c++ -perl -noproxy example.i
  2058. </pre>
  2059. </div>
  2060. <p>
  2061. When proxy classes are used, SWIG moves all of the low-level procedural wrappers to
  2062. another package name. By default, this package is named 'modulec' where 'module' is the name of the module
  2063. you provided with the <tt>%module</tt> directive. Then, in place of the original module,
  2064. SWIG creates a collection of high-leve