PageRenderTime 55ms CodeModel.GetById 7ms RepoModel.GetById 0ms app.codeStats 0ms

/tags/rel-1-3-29/SWIG/Doc/Manual/Perl5.html

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