~ubuntu-branches/ubuntu/oneiric/swig1.3/oneiric

« back to all changes in this revision

Viewing changes to Doc/Manual/Ruby.html

  • Committer: Bazaar Package Importer
  • Author(s): Matthias Klose
  • Date: 2007-12-06 10:27:08 UTC
  • mfrom: (1.2.6 upstream)
  • Revision ID: james.westby@ubuntu.com-20071206102708-t37t62i45n595w0e
Tags: 1.3.33-2ubuntu1
* Merge with Debian; remaining changes:
  - Drop support for pike.
  - Use python2.5 instead of python2.4.
  - Clean Runtime/ as well.
  - Force a few environment variables.
* debian/Rules (clean): Remove Lib/ocaml/swigp4.ml.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
2
2
<html>
3
 
        <head>
4
 
                <title>SWIG and Ruby</title>
5
 
                <link rel="stylesheet" type="text/css" href="style.css">
6
 
        </head>
7
 
        <body style="background-color: rgb(255, 255, 255);">
 
3
<head>
 
4
 
 
5
 
 
6
 
 
7
 
 
8
  
 
9
 
 
10
 
 
11
  
 
12
  
 
13
  
 
14
  
 
15
  
 
16
  
 
17
  
 
18
  <title>SWIG and Ruby</title>
 
19
  <link rel="stylesheet" type="text/css" href="style.css">
 
20
</head>
 
21
 
 
22
 
 
23
<body style="background-color: rgb(255, 255, 255);">
 
24
 
 
25
 
 
26
 
 
27
 
 
28
 
8
29
<H1><a name="Ruby"></a>30 SWIG and Ruby</H1>
9
30
<!-- INDEX -->
10
31
<div class="sectiontoc">
36
57
<li><a href="#Ruby_nn21">C++ Operators</a>
37
58
<li><a href="#Ruby_nn22">C++ namespaces</a>
38
59
<li><a href="#Ruby_nn23">C++ templates</a>
 
60
<li><a href="#Ruby_nn23_1">C++ Standard Template Library (STL)</a>
 
61
<li><a href="#C_STL_Functors">C++ STL Functors</a>
 
62
<li><a href="#Ruby_C_Iterators">C++ STL Iterators</a>
39
63
<li><a href="#Ruby_nn24">C++ Smart Pointers</a>
40
64
<li><a href="#Ruby_nn25">Cross-Language Polymorphism</a>
41
65
<ul>
50
74
<li><a href="#Ruby_nn31">Getters and Setters</a>
51
75
</ul>
52
76
<li><a href="#Ruby_nn32">Input and output parameters</a>
53
 
<li><a href="#Ruby_nn33">Exception handling             </a>
 
77
<li><a href="#Ruby_nn33">Exception handling </a>
54
78
<ul>
55
 
<li><a href="#Ruby_nn34">Using the %exception directive                 </a>
 
79
<li><a href="#Ruby_nn34">Using the %exception directive </a>
 
80
<li><a href="#Ruby_nn34_2">Handling Ruby Blocks </a>
56
81
<li><a href="#Ruby_nn35">Raising exceptions </a>
57
82
<li><a href="#Ruby_nn36">Exception classes </a>
58
83
</ul>
59
84
<li><a href="#Ruby_nn37">Typemaps</a>
60
85
<ul>
61
86
<li><a href="#Ruby_nn38">What is a typemap?</a>
 
87
<li><a href="#Ruby_Typemap_scope">Typemap scope</a>
 
88
<li><a href="#Ruby_Copying_a_typemap">Copying a typemap</a>
 
89
<li><a href="#Ruby_Deleting_a_typemap">Deleting a typemap</a>
 
90
<li><a href="#Ruby_Placement_of_typemaps">Placement of typemaps</a>
62
91
<li><a href="#Ruby_nn39">Ruby typemaps</a>
 
92
<ul>
 
93
<li><a href="#Ruby_in_typemap">&nbsp;"in" typemap</a>
 
94
<li><a href="#Ruby_typecheck_typemap">"typecheck" typemap</a>
 
95
<li><a href="#Ruby_out_typemap">&nbsp;"out" typemap</a>
 
96
<li><a href="#Ruby_arginit_typemap">"arginit" typemap</a>
 
97
<li><a href="#Ruby_default_typemap">"default" typemap</a>
 
98
<li><a href="#Ruby_check_typemap">"check" typemap</a>
 
99
<li><a href="#Ruby_argout_typemap_">"argout" typemap</a>
 
100
<li><a href="#Ruby_freearg_typemap_">"freearg" typemap</a>
 
101
<li><a href="#Ruby_newfree_typemap">"newfree" typemap</a>
 
102
<li><a href="#Ruby_memberin_typemap">"memberin" typemap</a>
 
103
<li><a href="#Ruby_varin_typemap">"varin" typemap</a>
 
104
<li><a href="#Ruby_varout_typemap_">"varout" typemap</a>
 
105
<li><a href="#Ruby_throws_typemap">"throws" typemap</a>
 
106
<li><a href="#Ruby_directorin_typemap">directorin typemap</a>
 
107
<li><a href="#Ruby_directorout_typemap">directorout typemap</a>
 
108
<li><a href="#Ruby_directorargout_typemap">directorargout typemap</a>
 
109
<li><a href="#Ruby_ret_typemap">ret typemap</a>
 
110
<li><a href="#Ruby_globalin_typemap">globalin typemap</a>
 
111
</ul>
63
112
<li><a href="#Ruby_nn40">Typemap variables</a>
64
113
<li><a href="#Ruby_nn41">Useful Functions</a>
65
114
<ul>
78
127
</ul>
79
128
<li><a href="#Ruby_nn52">Example: STL Vector to Ruby Array</a>
80
129
</ul>
 
130
<li><a href="#Ruby_nn65">Docstring Features</a>
 
131
<ul>
 
132
<li><a href="#Ruby_nn66">Module docstring</a>
 
133
<li><a href="#Ruby_nn67">%feature("autodoc")</a>
 
134
<ul>
 
135
<li><a href="#Ruby_nn68">%feature("autodoc", "0")</a>
 
136
<li><a href="#Ruby_autodoc1">%feature("autodoc", "1")</a>
 
137
<li><a href="#Ruby_autodoc2">%feature("autodoc", "2")</a>
 
138
<li><a href="#Ruby_feature_autodoc3">%feature("autodoc", "3")</a>
 
139
<li><a href="#Ruby_nn70">%feature("autodoc", "docstring")</a>
 
140
</ul>
 
141
<li><a href="#Ruby_nn71">%feature("docstring")</a>
 
142
</ul>
81
143
<li><a href="#Ruby_nn53">Advanced Topics</a>
82
144
<ul>
83
145
<li><a href="#Ruby_nn54">Operator overloading</a>
86
148
</ul>
87
149
<li><a href="#Ruby_nn57">Memory Management</a>
88
150
<ul>
89
 
<li><a href="#Ruby_nn58">Mark and Sweep Garbage Collector               </a>
 
151
<li><a href="#Ruby_nn58">Mark and Sweep Garbage Collector </a>
90
152
<li><a href="#Ruby_nn59">Object Ownership</a>
91
153
<li><a href="#Ruby_nn60">Object Tracking</a>
92
154
<li><a href="#Ruby_nn61">Mark Functions</a>
93
155
<li><a href="#Ruby_nn62">Free Functions</a>
 
156
<li><a href="#Ruby_nn63">Embedded Ruby and the C++ Stack</a>
94
157
</ul>
95
158
</ul>
96
159
</div>
99
162
 
100
163
 
101
164
<p>This chapter describes SWIG's support of Ruby.</p>
 
165
 
 
166
 
 
167
 
 
168
 
 
169
 
102
170
<H2><a name="Ruby_nn2"></a>30.1 Preliminaries</H2>
103
171
 
104
172
 
105
 
                <p>
106
 
                        SWIG 1.3 is known to work with Ruby versions 1.6 and later. Given the choice, 
107
 
                        you should use the latest stable version of Ruby. You should also determine if 
108
 
                        your system supports shared libraries and dynamic loading. SWIG will work with 
109
 
                        or without dynamic loading, but the compilation process will vary.
110
 
                </p>
111
 
                <p>This chapter covers most SWIG features, but in less depth than is found in 
112
 
                        earlier chapters. At the very least, make sure you also read the "<a href="SWIG.html#SWIG">SWIG 
113
 
                                Basics</a>" chapter. It is also assumed that the reader has a basic 
114
 
                        understanding of Ruby.
115
 
                </p>
 
173
<p> SWIG 1.3 is known to work with Ruby versions 1.6 and later.
 
174
Given the choice, you should use the latest stable version of Ruby. You
 
175
should also determine if your system supports shared libraries and
 
176
dynamic loading. SWIG will work with or without dynamic loading, but
 
177
the compilation process will vary. </p>
 
178
 
 
179
 
 
180
 
 
181
 
 
182
 
 
183
<p>This chapter covers most SWIG features, but in less depth than
 
184
is found in earlier chapters. At the very least, make sure you also
 
185
read the "<a href="SWIG.html#SWIG">SWIG Basics</a>"
 
186
chapter. It is also assumed that the reader has a basic understanding
 
187
of Ruby. </p>
 
188
 
 
189
 
 
190
 
 
191
 
 
192
 
116
193
<H3><a name="Ruby_nn3"></a>30.1.1 Running SWIG</H3>
117
194
 
118
195
 
119
 
                <p>
120
 
                        To build a Ruby module, run SWIG using the <tt>-ruby</tt> option:</p>
121
 
                <div class="code">
122
 
                        <pre>$ <b>swig -ruby example.i</b>
123
 
</pre>
124
 
                </div>
125
 
                <p>
126
 
                        If building a C++ extension, add the <tt>-c++</tt> option:
127
 
                </p>
128
 
                <div class="code">
129
 
                        <pre>$ <b>swig -c++ -ruby example.i</b>
130
 
</pre>
131
 
                </div>
132
 
                <p>
133
 
                        This creates a file <tt>example_wrap.c</tt> (<tt>example_wrap.cxx</tt> if 
134
 
                        compiling a C++ extension) that contains all of the code needed to build a Ruby 
135
 
                        extension module. To finish building the module, you need to compile this file 
136
 
                        and link it with the rest of your program.
137
 
                </p>
 
196
<p> To build a Ruby module, run SWIG using the <tt>-ruby</tt>
 
197
option:</p>
 
198
 
 
199
 
 
200
 
 
201
 
 
202
 
 
203
<div class="code shell">
 
204
<pre>$ <b>swig -ruby example.i</b>
 
205
</pre>
 
206
 
 
207
 
 
208
 
 
209
 
 
210
 
 
211
</div>
 
212
 
 
213
 
 
214
 
 
215
 
 
216
 
 
217
<p> If building a C++ extension, add the <tt>-c++</tt>
 
218
option: </p>
 
219
 
 
220
 
 
221
 
 
222
 
 
223
 
 
224
<div class="code shell">
 
225
<pre>$ <b>swig -c++ -ruby example.i</b>
 
226
</pre>
 
227
 
 
228
 
 
229
 
 
230
 
 
231
 
 
232
</div>
 
233
 
 
234
 
 
235
 
 
236
 
 
237
 
 
238
<p> This creates a file <tt>example_wrap.c</tt> (<tt>example_wrap.cxx</tt>
 
239
if compiling a C++ extension) that contains all of the code needed to
 
240
build a Ruby extension module. To finish building the module, you need
 
241
to compile this file and link it with the rest of your program. </p>
 
242
 
 
243
 
 
244
 
 
245
 
 
246
 
138
247
<H3><a name="Ruby_nn4"></a>30.1.2 Getting the right header files</H3>
139
248
 
140
249
 
141
 
                <p>
142
 
                        In order to compile the wrapper code, the compiler needs the <tt>ruby.h</tt> header 
143
 
                        file. This file is usually contained in a directory such as
144
 
                </p>
145
 
                <div class="code">
146
 
                        <pre>/usr/local/lib/ruby/1.6/i686-linux/ruby.h<br></pre>
147
 
                </div>
148
 
                <p>
149
 
                        The exact location may vary on your machine, but the above location is typical. 
150
 
                        If you are not entirely sure where Ruby is installed, you can run Ruby to find 
151
 
                        out. For example:
152
 
                </p>
153
 
                <div class="code">
154
 
                        <pre>
155
 
$ <b>ruby -e 'puts $:.join("\n")'</b><br>/usr/local/lib/ruby/site_ruby/1.6 /usr/local/lib/ruby/site_ruby/1.6/i686-linux
156
 
/usr/local/lib/ruby/site_ruby /usr/local/lib/ruby/1.6 /usr/local/lib/ruby/1.6/i686-linux .
157
 
 </pre>
158
 
                </div>
 
250
<p> In order to compile the wrapper code, the compiler needs the <tt>ruby.h</tt>
 
251
header file. This file is usually contained in a directory such as </p>
 
252
 
 
253
 
 
254
 
 
255
 
 
256
 
 
257
<div class="code shell diagram">
 
258
<pre>/usr/lib/ruby/1.8/x86_64-linux-gnu/ruby.h<br>/usr/local/lib/ruby/1.6/i686-linux/ruby.h<br></pre>
 
259
 
 
260
 
 
261
 
 
262
 
 
263
 
 
264
</div>
 
265
 
 
266
 
 
267
 
 
268
 
 
269
 
 
270
<p> The exact location may vary on your machine, but the above
 
271
location is typical. If you are not entirely sure where Ruby is
 
272
installed, you can run Ruby to find out. For example: </p>
 
273
 
 
274
 
 
275
 
 
276
 
 
277
 
 
278
<div class="code shell">
 
279
<pre>$ <b>ruby -e 'puts $:.join("\n")'</b><br>/usr/local/lib/ruby/site_ruby/1.6 /usr/local/lib/ruby/site_ruby/1.6/i686-linux<br>/usr/local/lib/ruby/site_ruby /usr/local/lib/ruby/1.6 /usr/local/lib/ruby/1.6/i686-linux .<br> </pre>
 
280
 
 
281
 
 
282
 
 
283
 
 
284
 
 
285
</div>
 
286
 
 
287
 
 
288
 
 
289
 
 
290
 
159
291
<H3><a name="Ruby_nn5"></a>30.1.3 Compiling a dynamic module</H3>
160
292
 
161
293
 
162
 
                <p>
163
 
                        Ruby extension modules are typically compiled into shared libraries that the 
164
 
                        interpreter loads dynamically at runtime. Since the exact commands for doing 
165
 
                        this vary from platform to platform, your best bet is to follow the steps 
166
 
                        described in the <tt>README.EXT</tt> file from the Ruby distribution:
167
 
                </p>
168
 
                <ol>
169
 
                        <li>
170
 
                                <p>Create a file called <tt>extconf.rb</tt> that looks like the following:</p>
171
 
                                <div class="code">
172
 
                                        <pre>require 'mkmf'<br>create_makefile('example')<br></pre>
173
 
                                </div>
174
 
                        </li>
175
 
                        <li>
176
 
                                <p>Type the following to build the extension:</p>
177
 
                                <div class="code">
178
 
                                        <pre>$ <b>ruby extconf.rb</b><br>$ <b>make</b><br>$ <b>make install</b>
 
294
<p> Ruby extension modules are typically compiled into shared
 
295
libraries that the interpreter loads dynamically at runtime. Since the
 
296
exact commands for doing this vary from platform to platform, your best
 
297
bet is to follow the steps described in the <tt>README.EXT</tt>
 
298
file from the Ruby distribution: </p>
 
299
 
 
300
 
 
301
 
 
302
 
 
303
 
 
304
<ol>
 
305
 
 
306
 
 
307
 
 
308
 
 
309
 
 
310
  <li>
 
311
    
 
312
    
 
313
    
 
314
    
 
315
    <p>Create a file called <tt>extconf.rb</tt> that
 
316
looks like the following:</p>
 
317
 
 
318
 
 
319
 
 
320
 
 
321
 
 
322
    
 
323
    
 
324
    
 
325
    
 
326
    <div class="code targetlang">
 
327
    
 
328
    
 
329
    
 
330
    
 
331
    <pre>require 'mkmf'<br>create_makefile('example')<br></pre>
 
332
 
 
333
 
 
334
 
 
335
 
 
336
 
 
337
    </div>
 
338
 
 
339
 
 
340
 
 
341
 
 
342
 
 
343
  </li>
 
344
 
 
345
 
 
346
 
 
347
 
 
348
 
 
349
  <li>
 
350
    
 
351
    
 
352
    
 
353
    
 
354
    <p>Type the following to build the extension:</p>
 
355
 
 
356
 
 
357
 
 
358
 
 
359
 
 
360
    
 
361
    
 
362
    
 
363
    
 
364
    <div class="code shell">
 
365
    
 
366
    
 
367
    
 
368
    
 
369
    <pre>$ <b>ruby extconf.rb</b><br>$ <b>make</b><br>$ <b>make install</b>
179
370
    </pre>
180
 
                                </div>
181
 
                        </li>
182
 
                </ol>
183
 
                <p>
184
 
                        Of course, there is the problem that mkmf does not work correctly on all 
185
 
                        platforms, e.g, HPUX. If you need to add your own make rules to the file that <tt>extconf.rb</tt>
186
 
                        produces, you can add this:
187
 
                </p>
188
 
                <div class="code">
189
 
                        <pre>open("Makefile", "a") { |mf|<br> puts &lt;&lt;EOM<br> # Your make rules go here<br> EOM<br>}<br></pre>
190
 
                </div>
191
 
                <p>
192
 
                        to the end of the <tt>extconf.rb</tt> file. If for some reason you don't want 
193
 
                        to use the standard approach, you'll need to determine the correct compiler and 
194
 
                        linker flags for your build platform. For example, a typical sequence of 
195
 
                        commands for the Linux operating system would look something like this:
196
 
                </p>
197
 
                <div class="code">
198
 
                        <pre>$ <b>swig -ruby example.i</b><br>$ <b>gcc -c example.c</b><br>$ <b>gcc -c example_wrap.c -I/usr/local/lib/ruby/1.6/i686-linux</b> <br>$ <b>gcc -shared example.o example_wrap.o -o example.so</b>
 
371
 
 
372
 
 
373
 
 
374
 
 
375
 
 
376
    </div>
 
377
 
 
378
 
 
379
 
 
380
 
 
381
 
 
382
  </li>
 
383
 
 
384
 
 
385
 
 
386
 
 
387
 
 
388
</ol>
 
389
 
 
390
 
 
391
 
 
392
 
 
393
 
 
394
<p> Of course, there is the problem that mkmf does not work
 
395
correctly on all platforms, e.g, HPUX. If you need to add your own make
 
396
rules to the file that <tt>extconf.rb</tt> produces, you
 
397
can add this: </p>
 
398
 
 
399
 
 
400
 
 
401
 
 
402
 
 
403
<div class="code targetlang">
 
404
<pre>open("Makefile", "a") { |mf|<br> puts &lt;&lt;EOM<br> # Your make rules go here<br> EOM<br>}<br></pre>
 
405
 
 
406
 
 
407
 
 
408
 
 
409
 
 
410
</div>
 
411
 
 
412
 
 
413
 
 
414
 
 
415
 
 
416
<p> to the end of the <tt>extconf.rb</tt> file. If
 
417
for some reason you don't want to use the standard approach, you'll
 
418
need to determine the correct compiler and linker flags for your build
 
419
platform. For example, a typical sequence of commands for the Linux
 
420
operating system would look something like this: </p>
 
421
 
 
422
 
 
423
 
 
424
 
 
425
 
 
426
<div class="code shell">
 
427
<pre>$ <b>swig -ruby example.i</b><br>$ <b>gcc -c example.c</b><br>$ <b>gcc -c example_wrap.c -I/usr/local/lib/ruby/1.6/i686-linux</b> <br>$ <b>gcc -shared example.o example_wrap.o -o example.so</b>
199
428
</pre>
200
 
                </div>
201
 
                <p>
202
 
                        For other platforms it may be necessary to compile with the <tt>-fPIC</tt> option 
203
 
                        to generate position-independent code. If in doubt, consult the manual pages 
204
 
                        for your compiler and linker to determine the correct set of options. You might 
205
 
                        also check the <a href="http://www.dabeaz.com/cgi-bin/wiki.pl">SWIG Wiki</a>
206
 
                        for additional information.
207
 
                </p>
208
 
                <p>
209
 
                        <a name="n6"></a>
210
 
                </p>
 
429
 
 
430
 
 
431
 
 
432
 
 
433
 
 
434
</div>
 
435
 
 
436
 
 
437
 
 
438
 
 
439
 
 
440
<p> For other platforms it may be necessary to compile with the <tt>-fPIC</tt>
 
441
option to generate position-independent code. If in doubt, consult the
 
442
manual pages for your compiler and linker to determine the correct set
 
443
of options. You might also check the <a href="http://www.dabeaz.com/cgi-bin/wiki.pl">SWIG Wiki</a>
 
444
for additional information. </p>
 
445
 
211
446
<H3><a name="Ruby_nn6"></a>30.1.4 Using your module</H3>
212
447
 
213
448
 
214
 
                <p>
215
 
                        Ruby <i>module</i> names must be capitalized, but the convention for Ruby <i>feature</i>
216
 
                        names is to use lowercase names. So, for example, the <b>Etc</b> extension 
217
 
                        module is imported by requiring the <b>etc</b> feature:
218
 
                </p>
219
 
                <div class="code">
220
 
                        <pre># The feature name begins with a lowercase letter...<br>require 'etc'<br><br># ... but the module name begins with an uppercase letter<br>puts "Your login name: #{Etc.getlogin}"<br></pre>
221
 
                </div>
222
 
                <p>
223
 
                        To stay consistent with this practice, you should always specify a <b>lowercase</b>
224
 
                        module name with SWIG's <tt>%module</tt> directive. SWIG will automatically 
225
 
                        correct the resulting Ruby module name for your extension. So for example, a 
226
 
                        SWIG interface file that begins with:
227
 
                </p>
228
 
                <div class="code">
229
 
                        <pre>%module example<br></pre>
230
 
                </div>
231
 
                <p>
232
 
                        will result in an extension module using the feature name "example" and Ruby 
233
 
                        module name "Example".
234
 
                </p>
 
449
<p> Ruby <i>module</i> names must be capitalized,
 
450
but the convention for Ruby <i>feature</i> names is to use
 
451
lowercase names. So, for example, the <b>Etc</b> extension
 
452
module is imported by requiring the <b>etc</b> feature: </p>
 
453
 
 
454
 
 
455
 
 
456
 
 
457
 
 
458
<div class="code targetlang">
 
459
<pre># The feature name begins with a lowercase letter...<br>require 'etc'<br><br># ... but the module name begins with an uppercase letter<br>puts "Your login name: #{Etc.getlogin}"<br></pre>
 
460
 
 
461
 
 
462
 
 
463
 
 
464
 
 
465
</div>
 
466
 
 
467
 
 
468
 
 
469
 
 
470
 
 
471
<p> To stay consistent with this practice, you should always
 
472
specify a <b>lowercase</b> module name with SWIG's <tt>%module</tt>
 
473
directive. SWIG will automatically correct the resulting Ruby module
 
474
name for your extension. So for example, a SWIG interface file that
 
475
begins with: </p>
 
476
 
 
477
 
 
478
 
 
479
 
 
480
 
 
481
<div class="code">
 
482
<pre>%module example<br></pre>
 
483
 
 
484
 
 
485
 
 
486
 
 
487
 
 
488
</div>
 
489
 
 
490
 
 
491
 
 
492
 
 
493
 
 
494
<p> will result in an extension module using the feature name
 
495
"example" and Ruby module name "Example". </p>
 
496
 
 
497
 
 
498
 
 
499
 
 
500
 
235
501
<H3><a name="Ruby_nn7"></a>30.1.5 Static linking</H3>
236
502
 
237
503
 
238
 
                <p>
239
 
                        An alternative approach to dynamic linking is to rebuild the Ruby interpreter 
240
 
                        with your extension module added to it. In the past, this approach was 
241
 
                        sometimes necessary due to limitations in dynamic loading support on certain 
242
 
                        machines. However, the situation has improved greatly over the last few years 
243
 
                        and you should not consider this approach unless there is really no other 
244
 
                        option.
245
 
                </p>
246
 
                <p>The usual procedure for adding a new module to Ruby involves finding the Ruby 
247
 
                        source, adding an entry to the <tt>ext/Setup</tt> file, adding your directory 
248
 
                        to the list of extensions in the file, and finally rebuilding Ruby.
249
 
                </p>
250
 
                <p><a name="n8"></a></p>
 
504
<p> An alternative approach to dynamic linking is to rebuild the
 
505
Ruby interpreter with your extension module added to it. In the past,
 
506
this approach was sometimes necessary due to limitations in dynamic
 
507
loading support on certain machines. However, the situation has
 
508
improved greatly over the last few years and you should not consider
 
509
this approach unless there is really no other option. </p>
 
510
 
 
511
 
 
512
 
 
513
 
 
514
 
 
515
<p>The usual procedure for adding a new module to Ruby involves
 
516
finding the Ruby source, adding an entry to the <tt>ext/Setup</tt>
 
517
file, adding your directory to the list of extensions in the file, and
 
518
finally rebuilding Ruby. </p>
 
519
 
 
520
 
 
521
 
251
522
<H3><a name="Ruby_nn8"></a>30.1.6 Compilation of C++ extensions</H3>
252
523
 
253
524
 
254
 
                <p>
255
 
                        On most machines, C++ extension modules should be linked using the C++ 
256
 
                        compiler. For example:
257
 
                </p>
258
 
                <div class="code">
259
 
                        <pre>$ <b>swig -c++ -ruby example.i</b><br>$ <b>g++ -c example.cxx</b><br>$ <b>g++ -c example_wrap.cxx -I/usr/local/lib/ruby/1.6/i686-linux</b><br>$ <b>g++ -shared example.o example_wrap.o -o example.so</b>
 
525
<p> On most machines, C++ extension modules should be linked
 
526
using the C++ compiler. For example: </p>
 
527
 
 
528
 
 
529
 
 
530
 
 
531
 
 
532
<div class="code shell">
 
533
<pre>$ <b>swig -c++ -ruby example.i</b><br>$ <b>g++ -c example.cxx</b><br>$ <b>g++ -c example_wrap.cxx -I/usr/local/lib/ruby/1.6/i686-linux</b><br>$ <b>g++ -shared example.o example_wrap.o -o example.so</b>
260
534
</pre>
261
 
                </div>
262
 
                <p>
263
 
                        If you've written an <tt>extconf.rb</tt> script to automatically generate a <tt>Makefile</tt>
264
 
                        for your C++ extension module, keep in mind that (as of this writing) Ruby 
265
 
                        still uses <tt>gcc</tt> and not <tt>g++</tt> as its linker. As a result, the 
266
 
                        required C++ runtime library support will not be automatically linked into your 
267
 
                        extension module and it may fail to load on some platforms. A workaround for 
268
 
                        this problem is use the <tt>mkmf</tt> module's <tt>append_library()</tt> method 
269
 
                        to add one of the C++ runtime libraries to the list of libraries linked into 
270
 
                        your extension, e.g.
271
 
                </p>
272
 
                <div class="code">
273
 
                        <pre>require 'mkmf'<br>$libs = append_library($libs, "supc++")<br>create_makefile('example')<br></pre>
274
 
                </div>
 
535
 
 
536
 
 
537
 
 
538
 
 
539
 
 
540
</div>
 
541
 
 
542
 
 
543
 
 
544
 
 
545
 
 
546
<p> If you've written an <tt>extconf.rb</tt> script
 
547
to automatically generate a <tt>Makefile</tt> for your C++
 
548
extension module, keep in mind that (as of this writing) Ruby still
 
549
uses <tt>gcc</tt> and not <tt>g++</tt> as its
 
550
linker. As a result, the required C++ runtime library support will not
 
551
be automatically linked into your extension module and it may fail to
 
552
load on some platforms. A workaround for this problem is use the <tt>mkmf</tt>
 
553
module's <tt>append_library()</tt> method to add one of
 
554
the C++ runtime libraries to the list of libraries linked into your
 
555
extension, e.g. </p>
 
556
 
 
557
 
 
558
 
 
559
 
 
560
 
 
561
<div class="code targetlang">
 
562
<pre>require 'mkmf'<br>$libs = append_library($libs, "supc++")<br>create_makefile('example')<br></pre>
 
563
 
 
564
 
 
565
 
 
566
 
 
567
 
 
568
</div>
 
569
 
 
570
 
 
571
 
 
572
 
 
573
 
275
574
<H2><a name="Ruby_nn9"></a>30.2 Building Ruby Extensions under Windows 95/NT</H2>
276
575
 
277
576
 
278
 
                <p>
279
 
                        Building a SWIG extension to Ruby under Windows 95/NT is roughly similar to the 
280
 
                        process used with Unix. Normally, you will want to produce a DLL that can be 
281
 
                        loaded into the Ruby interpreter. For all recent versions of Ruby, the 
282
 
                        procedure described above (i.e. using an <tt>extconf.rb</tt> script) will work 
283
 
                        with Windows as well; you should be able to build your code into a DLL by 
284
 
                        typing:
285
 
                </p>
286
 
                <div class="code">
287
 
                        <pre>C:\swigtest&gt; <b>ruby extconf.rb</b><br>C:\swigtest&gt; <b>nmake</b><br>C:\swigtest&gt; <b>nmake install</b>
 
577
<p> Building a SWIG extension to Ruby under Windows 95/NT is
 
578
roughly similar to the process used with Unix. Normally, you will want
 
579
to produce a DLL that can be loaded into the Ruby interpreter. For all
 
580
recent versions of Ruby, the procedure described above (i.e. using an <tt>extconf.rb</tt>
 
581
script) will work with Windows as well; you should be able to build
 
582
your code into a DLL by typing: </p>
 
583
 
 
584
 
 
585
 
 
586
 
 
587
 
 
588
<div class="code shell">
 
589
<pre>C:\swigtest&gt; <b>ruby extconf.rb</b><br>C:\swigtest&gt; <b>nmake</b><br>C:\swigtest&gt; <b>nmake install</b>
288
590
</pre>
289
 
                </div>
290
 
                <p>
291
 
                        The remainder of this section covers the process of compiling SWIG-generated 
292
 
                        Ruby extensions with Microsoft Visual C++ 6 (i.e. within the Developer Studio 
293
 
                        IDE, instead of using the command line tools). In order to build extensions, 
294
 
                        you may need to download the source distribution to the Ruby package, as you 
295
 
                        will need the Ruby header files.
296
 
                </p>
297
 
                <p><a name="n10"></a></p>
 
591
 
 
592
 
 
593
 
 
594
 
 
595
 
 
596
</div>
 
597
 
 
598
 
 
599
 
 
600
 
 
601
 
 
602
<p> The remainder of this section covers the process of compiling
 
603
SWIG-generated Ruby extensions with Microsoft Visual C++ 6 (i.e. within
 
604
the Developer Studio IDE, instead of using the command line tools). In
 
605
order to build extensions, you may need to download the source
 
606
distribution to the Ruby package, as you will need the Ruby header
 
607
files. </p>
 
608
 
 
609
 
 
610
 
 
611
 
 
612
 
298
613
<H3><a name="Ruby_nn10"></a>30.2.1 Running SWIG from Developer Studio</H3>
299
614
 
300
615
 
301
 
                <p>
302
 
                        If you are developing your application within Microsoft developer studio, SWIG 
303
 
                        can be invoked as a custom build option. The process roughly follows these 
304
 
                        steps :
305
 
                </p>
306
 
                <ul>
307
 
                        <li>
308
 
                                Open up a new workspace and use the AppWizard to select a DLL project.
309
 
                        </li>
310
 
                        <li>
311
 
                                Add both the SWIG interface file (the .i file), any supporting C files, and the 
312
 
                                name of the wrapper file that will be created by SWIG (i.e. <tt>example_wrap.c</tt>). 
313
 
                                Note : If using C++, choose a different suffix for the wrapper file such as <tt>example_wrap.cxx</tt>. 
314
 
                                Don't worry if the wrapper file doesn't exist yet--Developer Studio will keep a 
315
 
                                reference to it around.
316
 
                        </li>
317
 
                        <li>
318
 
                                Select the SWIG interface file and go to the settings menu. Under settings, 
319
 
                                select the "Custom Build" option.
320
 
                        </li>
321
 
                        <li>
322
 
                                Enter "SWIG" in the description field.
323
 
                        </li>
324
 
                        <li>
325
 
                                Enter "<tt>swig -ruby -o $(ProjDir)\$(InputName)_wrap.c $(InputPath)</tt>" in 
326
 
                                the "Build command(s) field". You may have to include the path to swig.exe.
327
 
                        </li>
328
 
                        <li>
329
 
                                Enter "<tt>$(ProjDir)\$(InputName)_wrap.c</tt>" in the "Output files(s) field".
330
 
                        </li>
331
 
                        <li>
332
 
                                Next, select the settings for the entire project and go to the C/C++ tab and 
333
 
                                select the Preprocessor category. Add NT=1 to the Preprocessor definitions. 
334
 
                                This must be set else you will get compilation errors. Also add IMPORT to the 
335
 
                                preprocessor definitions, else you may get runtime errors. Also add the include 
336
 
                                directories for your Ruby installation under "Additional include directories".
337
 
                        </li>
338
 
                        <li>
339
 
                                Next, select the settings for the entire project and go to the Link tab and 
340
 
                                select the General category. Set the name of the output file to match the name 
341
 
                                of your Ruby module (i.e.. example.dll). Next add the Ruby library file to your 
342
 
                                link libraries under Object/Library modules. For example "mswin32-ruby16.lib. 
343
 
                                You also need to add the path to the library under the Input tab - Additional 
344
 
                                library path.
345
 
                        </li>
346
 
                        <li>
347
 
                                Build your project.
348
 
                        </li>
349
 
                </ul>
350
 
                <p>
351
 
                        Now, assuming all went well, SWIG will be automatically invoked when you build 
352
 
                        your project. Any changes made to the interface file will result in SWIG being 
353
 
                        automatically invoked to produce a new version of the wrapper file. To run your 
354
 
                        new Ruby extension, simply run Ruby and use the <tt>require</tt> command as 
355
 
                        normal. For example if you have this ruby file run.rb:</p>
356
 
                <div class="code">
357
 
                        <pre># file: run.rb<br>require 'Example'<br><br># Call a c function<br>print "Foo = ", Example.Foo, "\n"<br></pre>
358
 
                </div>
359
 
                <p>
360
 
                        Ensure the dll just built is in your path or current directory, then run the 
361
 
                        Ruby script from the DOS/Command prompt:
362
 
                </p>
363
 
                <div class="code">
364
 
                        <pre>C:\swigtest&gt; <b>ruby run.rb</b><br>Foo = 3.0<br></pre>
365
 
                </div>
 
616
<p> If you are developing your application within Microsoft
 
617
developer studio, SWIG can be invoked as a custom build option. The
 
618
process roughly follows these steps : </p>
 
619
 
 
620
 
 
621
 
 
622
 
 
623
 
 
624
<ul>
 
625
 
 
626
 
 
627
 
 
628
 
 
629
 
 
630
  <li> Open up a new workspace and use the AppWizard to select a
 
631
DLL project. </li>
 
632
 
 
633
 
 
634
 
 
635
 
 
636
 
 
637
  <li> Add both the SWIG interface file (the .i file), any
 
638
supporting C files, and the name of the wrapper file that will be
 
639
created by SWIG (i.e. <tt>example_wrap.c</tt>). Note : If
 
640
using C++, choose a different suffix for the wrapper file such as <tt>example_wrap.cxx</tt>.
 
641
Don't worry if the wrapper file doesn't exist yet--Developer Studio
 
642
will keep a reference to it around. </li>
 
643
 
 
644
 
 
645
 
 
646
 
 
647
 
 
648
  <li> Select the SWIG interface file and go to the settings
 
649
menu. Under settings, select the "Custom Build" option. </li>
 
650
 
 
651
 
 
652
 
 
653
 
 
654
 
 
655
  <li> Enter "SWIG" in the description field. </li>
 
656
 
 
657
 
 
658
 
 
659
 
 
660
 
 
661
  <li> Enter "<tt>swig -ruby -o
 
662
$(ProjDir)\$(InputName)_wrap.c $(InputPath)</tt>" in the "Build
 
663
command(s) field". You may have to include the path to swig.exe. </li>
 
664
 
 
665
 
 
666
 
 
667
 
 
668
 
 
669
  <li> Enter "<tt>$(ProjDir)\$(InputName)_wrap.c</tt>"
 
670
in the "Output files(s) field". </li>
 
671
 
 
672
 
 
673
 
 
674
 
 
675
 
 
676
  <li> Next, select the settings for the entire project and go to
 
677
the C/C++ tab and select the Preprocessor category. Add NT=1 to the
 
678
Preprocessor definitions. This must be set else you will get
 
679
compilation errors. Also add IMPORT to the preprocessor definitions,
 
680
else you may get runtime errors. Also add the include directories for
 
681
your Ruby installation under "Additional include directories". </li>
 
682
 
 
683
 
 
684
 
 
685
 
 
686
 
 
687
  <li> Next, select the settings for the entire project and go to
 
688
the Link tab and select the General category. Set the name of the
 
689
output file to match the name of your Ruby module (i.e.. example.dll).
 
690
Next add the Ruby library file to your link libraries under
 
691
Object/Library modules. For example "mswin32-ruby16.lib. You also need
 
692
to add the path to the library under the Input tab - Additional library
 
693
path. </li>
 
694
 
 
695
 
 
696
 
 
697
 
 
698
 
 
699
  <li> Build your project. </li>
 
700
 
 
701
 
 
702
 
 
703
 
 
704
 
 
705
</ul>
 
706
 
 
707
 
 
708
 
 
709
 
 
710
 
 
711
<p> Now, assuming all went well, SWIG will be automatically
 
712
invoked when you build your project. Any changes made to the interface
 
713
file will result in SWIG being automatically invoked to produce a new
 
714
version of the wrapper file. To run your new Ruby extension, simply run
 
715
Ruby and use the <tt>require</tt> command as normal. For
 
716
example if you have this ruby file run.rb:</p>
 
717
 
 
718
 
 
719
 
 
720
 
 
721
 
 
722
<div class="code targetlang">
 
723
<pre># file: run.rb<br>require 'Example'<br><br># Call a c function<br>print "Foo = ", Example.Foo, "\n"<br></pre>
 
724
 
 
725
 
 
726
 
 
727
 
 
728
 
 
729
</div>
 
730
 
 
731
 
 
732
 
 
733
 
 
734
 
 
735
<p> Ensure the dll just built is in your path or current
 
736
directory, then run the Ruby script from the DOS/Command prompt: </p>
 
737
 
 
738
 
 
739
 
 
740
 
 
741
 
 
742
<div class="code shell">
 
743
<pre>C:\swigtest&gt; <b>ruby run.rb</b><br>Foo = 3.0<br></pre>
 
744
 
 
745
 
 
746
 
 
747
 
 
748
 
 
749
</div>
 
750
 
 
751
 
 
752
 
 
753
 
 
754
 
366
755
<H2><a name="Ruby_nn11"></a>30.3 The Ruby-to-C/C++ Mapping</H2>
367
756
 
368
757
 
369
 
                <p>
370
 
                        This section describes the basics of how SWIG maps C or C++ declarations in 
371
 
                        your SWIG interface files to Ruby constructs.
372
 
                </p>
 
758
<p> This section describes the basics of how SWIG maps C or C++
 
759
declarations in your SWIG interface files to Ruby constructs. </p>
 
760
 
 
761
 
 
762
 
 
763
 
 
764
 
373
765
<H3><a name="Ruby_nn12"></a>30.3.1 Modules</H3>
374
766
 
375
767
 
376
 
                <p>
377
 
                        The SWIG <tt>%module</tt> directive specifies the name of the Ruby module. If 
378
 
                        you specify:
379
 
                </p>
380
 
                <div class="code">
381
 
                        <pre>%module example</pre>
382
 
                </div>
383
 
                <p>
384
 
                        then everything is wrapped into a Ruby module named <tt>Example</tt> that is 
385
 
                        nested directly under the global module. You can specify a more deeply nested 
386
 
                        module by specifying the fully-qualified module name in quotes, e.g.
387
 
                </p>
388
 
                <div class="code">
389
 
                        <pre>%module "foo::bar::spam"</pre>
390
 
                </div>
391
 
                <p>
392
 
                        An alternate method of specifying a nested module name is to use the
393
 
                        <span style="font-family: monospace;">-prefix</span>
394
 
                        option on the SWIG command line. The prefix that you specify with this option 
395
 
                        will be prepended to the module name specified with the
396
 
                        <span style="font-family: monospace;">%module</span>
397
 
                        directive in your SWIG interface file. So for example, this declaration at the 
398
 
                        top of your SWIG interface file:<br>
399
 
                </p>
400
 
                <div class="code">
401
 
                        <pre>%module "foo::bar::spam"</pre>
402
 
                </div>
403
 
                <p>
404
 
                        will result in a nested module name of
405
 
                        <span style="font-family: monospace;">Foo::Bar::Spam</span>, but you can 
406
 
                        achieve the
407
 
                        <span style="font-style: italic;">same</span>
408
 
                        effect by specifying:<br>
409
 
                </p>
410
 
                <div class="code">
411
 
                        <pre>%module spam</pre>
412
 
                </div>
413
 
                <p>
414
 
                        and then running SWIG with the
415
 
                        <span style="font-family: monospace;">-prefix</span>
416
 
                        command line option:<br>
417
 
                </p>
418
 
                <div class="code">
419
 
                        <pre>$ <b>swig -ruby -prefix "foo::bar::" example.i</b></pre>
420
 
                </div>
421
 
                <p>
422
 
                        Starting with SWIG 1.3.20, you can also choose to wrap everything into the 
423
 
                        global module by specifying the <tt>-globalmodule</tt> option on the SWIG 
424
 
                        command line, i.e.
425
 
                </p>
426
 
                <div class="code">
427
 
                        <pre>$ <b>swig -ruby -globalmodule example.i</b></pre>
428
 
                </div>
429
 
                <p>
430
 
                        Note that this does not relieve you of the requirement of specifying the SWIG 
431
 
                        module name with the <tt>%module</tt> directive (or the <tt>-module</tt> command-line 
432
 
                        option) as described earlier.
433
 
                </p>
434
 
                <p>When choosing a module name, do not use the same name as a built-in Ruby command 
435
 
                        or standard module name, as the results may be unpredictable. Similarly, if 
436
 
                        you're using the <tt>-globalmodule</tt> option to wrap everything into the 
437
 
                        global module, take care that the names of your constants, classes and methods 
438
 
                        don't conflict with any of Ruby's built-in names.
439
 
                </p>
 
768
<p> The SWIG <tt>%module</tt> directive specifies
 
769
the name of the Ruby module. If you specify: </p>
 
770
 
 
771
 
 
772
 
 
773
 
 
774
 
 
775
<div class="code">
 
776
<pre>%module example</pre>
 
777
 
 
778
 
 
779
 
 
780
 
 
781
 
 
782
</div>
 
783
 
 
784
 
 
785
 
 
786
 
 
787
 
 
788
<p> then everything is wrapped into a Ruby module named <tt>Example</tt>
 
789
that is nested directly under the global module. You can specify a more
 
790
deeply nested module by specifying the fully-qualified module name in
 
791
quotes, e.g. </p>
 
792
 
 
793
 
 
794
 
 
795
 
 
796
 
 
797
<div class="code">
 
798
<pre>%module "foo::bar::spam"</pre>
 
799
 
 
800
 
 
801
 
 
802
 
 
803
 
 
804
</div>
 
805
 
 
806
 
 
807
 
 
808
 
 
809
 
 
810
<p> An alternate method of specifying a nested module name is to
 
811
use the <span style="font-family: monospace;">-prefix</span>
 
812
option on the SWIG command line. The prefix that you specify with this
 
813
option will be prepended to the module name specified with the <span style="font-family: monospace;">%module</span>
 
814
directive in your SWIG interface file. So for example, this declaration
 
815
at the top of your SWIG interface file:<br>
 
816
 
 
817
 
 
818
 
 
819
 
 
820
 
 
821
</p>
 
822
 
 
823
 
 
824
 
 
825
 
 
826
 
 
827
<div class="code">
 
828
<pre>%module "foo::bar::spam"</pre>
 
829
 
 
830
 
 
831
 
 
832
 
 
833
 
 
834
</div>
 
835
 
 
836
 
 
837
 
 
838
 
 
839
 
 
840
<p> will result in a nested module name of <span style="font-family: monospace;">Foo::Bar::Spam</span>,
 
841
but you can achieve the <span style="font-style: italic;">same</span>
 
842
effect by specifying:<br>
 
843
 
 
844
 
 
845
 
 
846
 
 
847
 
 
848
</p>
 
849
 
 
850
 
 
851
 
 
852
 
 
853
 
 
854
<div class="code">
 
855
<pre>%module spam</pre>
 
856
 
 
857
 
 
858
 
 
859
 
 
860
 
 
861
</div>
 
862
 
 
863
 
 
864
 
 
865
 
 
866
 
 
867
<p> and then running SWIG with the <span style="font-family: monospace;">-prefix</span> command
 
868
line option:<br>
 
869
 
 
870
 
 
871
 
 
872
 
 
873
 
 
874
</p>
 
875
 
 
876
 
 
877
 
 
878
 
 
879
 
 
880
<div class="code shell">
 
881
<pre>$ <b>swig -ruby -prefix "foo::bar::" example.i</b></pre>
 
882
 
 
883
 
 
884
 
 
885
 
 
886
 
 
887
</div>
 
888
 
 
889
 
 
890
 
 
891
 
 
892
 
 
893
<p> Starting with SWIG 1.3.20, you can also choose to wrap
 
894
everything into the global module by specifying the <tt>-globalmodule</tt>
 
895
option on the SWIG command line, i.e. </p>
 
896
 
 
897
 
 
898
 
 
899
 
 
900
 
 
901
<div class="code shell">
 
902
<pre>$ <b>swig -ruby -globalmodule example.i</b></pre>
 
903
 
 
904
 
 
905
 
 
906
 
 
907
 
 
908
</div>
 
909
 
 
910
 
 
911
 
 
912
 
 
913
 
 
914
<p> Note that this does not relieve you of the requirement of
 
915
specifying the SWIG module name with the <tt>%module</tt>
 
916
directive (or the <tt>-module</tt> command-line option) as
 
917
described earlier. </p>
 
918
 
 
919
 
 
920
 
 
921
 
 
922
 
 
923
<p>When choosing a module name, do not use the same name as a
 
924
built-in Ruby command or standard module name, as the results may be
 
925
unpredictable. Similarly, if you're using the <tt>-globalmodule</tt>
 
926
option to wrap everything into the global module, take care that the
 
927
names of your constants, classes and methods don't conflict with any of
 
928
Ruby's built-in names. </p>
 
929
 
 
930
 
 
931
 
 
932
 
 
933
 
440
934
<H3><a name="Ruby_nn13"></a>30.3.2 Functions</H3>
441
935
 
442
936
 
443
 
                <p>
444
 
                        Global functions are wrapped as Ruby module methods. For example, given the 
445
 
                        SWIG interface file <tt>example.i</tt>:
446
 
                </p>
447
 
                <div class="code">
448
 
                        <pre>%module example<br><br>int fact(int n);<br></pre>
449
 
                </div>
450
 
                <p>
451
 
                        and C source file <tt>example.c</tt>:
452
 
                </p>
453
 
                <div class="code">
454
 
                        <pre>int fact(int n) {<br> if (n == 0)<br> return 1;<br> return (n * fact(n-1));<br>}<br></pre>
455
 
                </div>
456
 
                <p>
457
 
                        SWIG will generate a method <i>fact</i> in the <i>Example</i> module that can 
458
 
                        be used like so:
459
 
                </p>
460
 
                <div class="code">
461
 
                        <pre>$ <b>irb</b><br>irb(main):001:0&gt; <b>require 'example'</b><br>true<br>irb(main):002:0&gt; <b>Example.fact(4)</b><br>24<br></pre>
462
 
                </div>
 
937
<p> Global functions are wrapped as Ruby module methods. For
 
938
example, given the SWIG interface file <tt>example.i</tt>:
 
939
</p>
 
940
 
 
941
 
 
942
 
 
943
 
 
944
 
 
945
<div class="code">
 
946
<pre>%module example<br><br>int fact(int n);<br></pre>
 
947
 
 
948
 
 
949
 
 
950
 
 
951
 
 
952
</div>
 
953
 
 
954
 
 
955
 
 
956
 
 
957
 
 
958
<p> and C source file <tt>example.c</tt>: </p>
 
959
 
 
960
 
 
961
 
 
962
 
 
963
 
 
964
<div class="code">
 
965
<pre>int fact(int n) {<br> if (n == 0)<br> return 1;<br> return (n * fact(n-1));<br>}<br></pre>
 
966
 
 
967
 
 
968
 
 
969
 
 
970
 
 
971
</div>
 
972
 
 
973
 
 
974
 
 
975
 
 
976
 
 
977
<p> SWIG will generate a method <i>fact</i> in the <i>Example</i>
 
978
module that can be used like so: </p>
 
979
 
 
980
 
 
981
 
 
982
 
 
983
 
 
984
<div class="code targetlang">
 
985
<pre>$ <b>irb</b><br>irb(main):001:0&gt; <b>require 'example'</b><br>true<br>irb(main):002:0&gt; <b>Example.fact(4)</b><br>24<br></pre>
 
986
 
 
987
 
 
988
 
 
989
 
 
990
 
 
991
</div>
 
992
 
 
993
 
 
994
 
 
995
 
 
996
 
463
997
<H3><a name="Ruby_nn14"></a>30.3.3 Variable Linking</H3>
464
998
 
465
999
 
466
 
                <p>
467
 
                        C/C++ global variables are wrapped as a pair of singleton methods for the 
468
 
                        module: one to get the value of the global variable and one to set it. For 
469
 
                        example, the following SWIG interface file declares two global variables:
470
 
                </p>
471
 
                <div class="code">
472
 
                        <pre>// SWIG interface file with global variables<br>%module example<br>...<br>%inline %{<br>extern int variable1;<br>extern double Variable2;<br>%}<br>...<br></pre>
473
 
                </div>
474
 
                <p>
475
 
                        Now look at the Ruby interface:</p>
476
 
                <div class="code">
477
 
                        <pre>$ <b>irb</b><br>irb(main):001:0&gt; <b>require 'Example'</b><br>true<br>irb(main):002:0&gt; <b>Example.variable1 = 2</b><br>2<br>irb(main):003:0&gt; <b>Example.Variable2 = 4 * 10.3</b><br>41.2<br>irb(main):004:0&gt; <b>Example.Variable2</b><br>41.2<br></pre>
478
 
                </div>
479
 
                <p>
480
 
                        If you make an error in variable assignment, you will receive an error message. 
481
 
                        For example:
482
 
                </p>
483
 
                <div class="code">
484
 
                        <pre>irb(main):005:0&gt; <b>Example.Variable2 = "hello"</b><br>TypeError: no implicit conversion to float from string<br>from (irb):5:in `Variable2='<br>from (irb):5<br></pre>
485
 
                </div>
486
 
                <p>
487
 
                        If a variable is declared as <tt>const</tt>, it is wrapped as a read-only 
488
 
                        variable. Attempts to modify its value will result in an error.
489
 
                </p>
490
 
                <p>To make ordinary variables read-only, you can also use the <tt>%immutable</tt> directive. 
491
 
                        For example:
492
 
                </p>
493
 
                <div class="code">
494
 
                        <pre>%immutable;<br>%inline %{<br>extern char *path;<br>%}<br>%mutable;<br></pre>
495
 
                </div>
496
 
                <p>
497
 
                        The <tt>%immutable</tt> directive stays in effect until it is explicitly 
498
 
                        disabled using <tt>%mutable</tt>.
499
 
                </p>
 
1000
<p> C/C++ global variables are wrapped as a pair of singleton
 
1001
methods for the module: one to get the value of the global variable and
 
1002
one to set it. For example, the following SWIG interface file declares
 
1003
two global variables: </p>
 
1004
 
 
1005
 
 
1006
 
 
1007
 
 
1008
 
 
1009
<div class="code">
 
1010
<pre>// SWIG interface file with global variables<br>%module example<br>...<br>%inline %{<br>extern int variable1;<br>extern double Variable2;<br>%}<br>...<br></pre>
 
1011
 
 
1012
 
 
1013
 
 
1014
 
 
1015
 
 
1016
</div>
 
1017
 
 
1018
 
 
1019
 
 
1020
 
 
1021
 
 
1022
<p> Now look at the Ruby interface:</p>
 
1023
 
 
1024
 
 
1025
 
 
1026
 
 
1027
 
 
1028
<div class="code targetlang">
 
1029
<pre>$ <b>irb</b><br>irb(main):001:0&gt; <b>require 'Example'</b><br>true<br>irb(main):002:0&gt; <b>Example.variable1 = 2</b><br>2<br>irb(main):003:0&gt; <b>Example.Variable2 = 4 * 10.3</b><br>41.2<br>irb(main):004:0&gt; <b>Example.Variable2</b><br>41.2<br></pre>
 
1030
 
 
1031
 
 
1032
 
 
1033
 
 
1034
 
 
1035
</div>
 
1036
 
 
1037
 
 
1038
 
 
1039
 
 
1040
 
 
1041
<p> If you make an error in variable assignment, you will receive
 
1042
an error message. For example: </p>
 
1043
 
 
1044
 
 
1045
 
 
1046
 
 
1047
 
 
1048
<div class="code targetlang">
 
1049
<pre>irb(main):005:0&gt; <b>Example.Variable2 = "hello"</b><br>TypeError: no implicit conversion to float from string<br>from (irb):5:in `Variable2='<br>from (irb):5<br></pre>
 
1050
 
 
1051
 
 
1052
 
 
1053
 
 
1054
 
 
1055
</div>
 
1056
 
 
1057
 
 
1058
 
 
1059
 
 
1060
 
 
1061
<p> If a variable is declared as <tt>const</tt>, it
 
1062
is wrapped as a read-only variable. Attempts to modify its value will
 
1063
result in an error. </p>
 
1064
 
 
1065
 
 
1066
 
 
1067
 
 
1068
 
 
1069
<p>To make ordinary variables read-only, you can also use the <tt>%immutable</tt>
 
1070
directive. For example: </p>
 
1071
 
 
1072
 
 
1073
 
 
1074
 
 
1075
 
 
1076
<div class="code">
 
1077
<pre>%immutable;<br>%inline %{<br>extern char *path;<br>%}<br>%mutable;<br></pre>
 
1078
 
 
1079
 
 
1080
 
 
1081
 
 
1082
 
 
1083
</div>
 
1084
 
 
1085
 
 
1086
 
 
1087
 
 
1088
 
 
1089
<p> The <tt>%immutable</tt> directive stays in
 
1090
effect until it is explicitly disabled using <tt>%mutable</tt>.
 
1091
</p>
 
1092
 
 
1093
 
 
1094
 
 
1095
 
 
1096
 
500
1097
<H3><a name="Ruby_nn15"></a>30.3.4 Constants</H3>
501
1098
 
502
1099
 
503
 
                <p>
504
 
                        C/C++ constants are wrapped as module constants initialized to the appropriate 
505
 
                        value. To create a constant, use <tt>#define</tt> or the <tt>%constant</tt> directive. 
506
 
                        For example:
507
 
                </p>
508
 
                <div class="code">
509
 
                        <pre>#define PI 3.14159<br>#define VERSION "1.0"<br><br>%constant int FOO = 42;<br>%constant const char *path = "/usr/local";<br><br>const int BAR = 32;<br></pre>
510
 
                </div>
511
 
                <p>
512
 
                        Remember to use the :: operator in Ruby to get at these constant values, e.g.
513
 
                </p>
514
 
                <div class="code">
515
 
                        <pre>$ <b>irb</b><br>irb(main):001:0&gt; <b>require 'Example'</b><br>true<br>irb(main):002:0&gt; <b>Example::PI</b><br>3.14159<br></pre>
516
 
                </div>
 
1100
<p> C/C++ constants are wrapped as module constants initialized
 
1101
to the appropriate value. To create a constant, use <tt>#define</tt>
 
1102
or the <tt>%constant</tt> directive. For example: </p>
 
1103
 
 
1104
 
 
1105
 
 
1106
 
 
1107
 
 
1108
<div class="code">
 
1109
<pre>#define PI 3.14159<br>#define VERSION "1.0"<br><br>%constant int FOO = 42;<br>%constant const char *path = "/usr/local";<br><br>const int BAR = 32;<br></pre>
 
1110
 
 
1111
 
 
1112
 
 
1113
 
 
1114
 
 
1115
</div>
 
1116
 
 
1117
 
 
1118
 
 
1119
 
 
1120
 
 
1121
<p> Remember to use the :: operator in Ruby to get at these
 
1122
constant values, e.g. </p>
 
1123
 
 
1124
 
 
1125
 
 
1126
 
 
1127
 
 
1128
<div class="code targetlang">
 
1129
<pre>$ <b>irb</b><br>irb(main):001:0&gt; <b>require 'Example'</b><br>true<br>irb(main):002:0&gt; <b>Example::PI</b><br>3.14159<br></pre>
 
1130
 
 
1131
 
 
1132
 
 
1133
 
 
1134
 
 
1135
</div>
 
1136
 
 
1137
 
 
1138
 
 
1139
 
 
1140
 
517
1141
<H3><a name="Ruby_nn16"></a>30.3.5 Pointers</H3>
518
1142
 
519
1143
 
520
 
                <p>
521
 
                        "Opaque" pointers to arbitrary C/C++ types (i.e. types that aren't explicitly 
522
 
                        declared in your SWIG interface file) are wrapped as data objects. So, for 
523
 
                        example, consider a SWIG interface file containing only the declarations:
524
 
                </p>
525
 
                <div class="code">
526
 
                        <pre>Foo *get_foo();<br>void set_foo(Foo *foo);<br></pre>
527
 
                </div>
528
 
                <p>
529
 
                        For this case, the <i>get_foo()</i> method returns an instance of an internally 
530
 
                        generated Ruby class:
531
 
                </p>
532
 
                <div class="code">
533
 
                        <pre>irb(main):001:0&gt; <b>foo = Example::get_foo()</b><br>#&lt;SWIG::TYPE_p_Foo:0x402b1654&gt;<br></pre>
534
 
                </div>
535
 
                <p>
536
 
                        A <tt>NULL</tt> pointer is always represented by the Ruby <tt>nil</tt> object.
537
 
                </p>
 
1144
<p> "Opaque" pointers to arbitrary C/C++ types (i.e. types that
 
1145
aren't explicitly declared in your SWIG interface file) are wrapped as
 
1146
data objects. So, for example, consider a SWIG interface file
 
1147
containing only the declarations: </p>
 
1148
 
 
1149
 
 
1150
 
 
1151
 
 
1152
 
 
1153
<div class="code">
 
1154
<pre>Foo *get_foo();<br>void set_foo(Foo *foo);<br></pre>
 
1155
 
 
1156
 
 
1157
 
 
1158
 
 
1159
 
 
1160
</div>
 
1161
 
 
1162
 
 
1163
 
 
1164
 
 
1165
 
 
1166
<p> For this case, the <i>get_foo()</i> method
 
1167
returns an instance of an internally generated Ruby class: </p>
 
1168
 
 
1169
 
 
1170
 
 
1171
 
 
1172
 
 
1173
<div class="code targetlang">
 
1174
<pre>irb(main):001:0&gt; <b>foo = Example::get_foo()</b><br>#&lt;SWIG::TYPE_p_Foo:0x402b1654&gt;<br></pre>
 
1175
 
 
1176
 
 
1177
 
 
1178
 
 
1179
 
 
1180
</div>
 
1181
 
 
1182
 
 
1183
 
 
1184
 
 
1185
 
 
1186
<p> A <tt>NULL</tt> pointer is always represented by
 
1187
the Ruby <tt>nil</tt> object. </p>
 
1188
 
 
1189
 
 
1190
 
 
1191
 
 
1192
 
538
1193
<H3><a name="Ruby_nn17"></a>30.3.6 Structures</H3>
539
1194
 
540
1195
 
541
 
                <p>
542
 
                        C/C++ structs are wrapped as Ruby classes, with accessor methods (i.e. 
543
 
                        "getters" and "setters") for all of the struct members. For example, this 
544
 
                        struct declaration:
545
 
                </p>
546
 
                <div class="code">
547
 
                        <pre>struct Vector {<br> double x, y;<br>};<br></pre>
548
 
                </div>
549
 
                <p>
550
 
                        gets wrapped as a <tt>Vector</tt> class, with Ruby instance methods <tt>x</tt>, <tt>
551
 
                                x=</tt>, <tt>y</tt> and <tt>y=</tt>. These methods can be used to access 
552
 
                        structure data from Ruby as follows:
553
 
                </p>
554
 
                <div class="code">
555
 
                        <pre>$ <b>irb</b><br>irb(main):001:0&gt; <b>require 'Example'</b><br>true<br>irb(main):002:0&gt; <b>f = Example::Vector.new</b><br>#&lt;Example::Vector:0x4020b268&gt;<br>irb(main):003:0&gt; <b>f.x = 10</b><br>nil<br>irb(main):004:0&gt; <b>f.x</b><br>10.0<br></pre>
556
 
                </div>
557
 
                <p>
558
 
                        Similar access is provided for unions and the public data members of C++ 
559
 
                        classes.</p>
560
 
                <p><tt>const</tt> members of a structure are read-only. Data members can also be 
561
 
                        forced to be read-only using the <tt>%immutable</tt> directive (in C++, <tt>private</tt>
562
 
                        may also be used). For example:
563
 
                </p>
564
 
                <div class="code">
565
 
                        <pre>struct Foo {<br> ...<br> %immutable;<br> int x; /* Read-only members */<br> char *name;<br> %mutable;<br> ...<br>};<br></pre>
566
 
                </div>
567
 
                <p>
568
 
                        When <tt>char *</tt> members of a structure are wrapped, the contents are 
569
 
                        assumed to be dynamically allocated using <tt>malloc</tt> or <tt>new</tt> (depending 
570
 
                        on whether or not SWIG is run with the <tt>-c++</tt> option). When the 
571
 
                        structure member is set, the old contents will be released and a new value 
572
 
                        created. If this is not the behavior you want, you will have to use a typemap 
573
 
                        (described shortly).
574
 
                </p>
575
 
                <p>Array members are normally wrapped as read-only. For example, this code:
576
 
                </p>
577
 
                <div class="code">
578
 
                        <pre>struct Foo {<br> int x[50];<br>};<br></pre>
579
 
                </div>
580
 
                <p>
581
 
                        produces a single accessor function like this:
582
 
                </p>
583
 
                <div class="code">
584
 
                        <pre>int *Foo_x_get(Foo *self) {<br> return self-&gt;x;<br>};<br></pre>
585
 
                </div>
586
 
                <p>
587
 
                        If you want to set an array member, you will need to supply a "memberin" 
588
 
                        typemap described in the <a href="#ruby_cpp_smart_pointers">section on typemaps</a>. 
589
 
                        As a special case, SWIG does generate code to set array members of type <tt>char</tt>
590
 
                        (allowing you to store a Ruby string in the structure).
591
 
                </p>
592
 
                <p>When structure members are wrapped, they are handled as pointers. For example,
593
 
                </p>
594
 
                <div class="code">
595
 
                        <pre>struct Foo {<br> ...<br>};<br><br>struct Bar {<br> Foo f;<br>};<br></pre>
596
 
                </div>
597
 
                <p>
598
 
                        generates accessor functions such as this:
599
 
                </p>
600
 
                <div class="code">
601
 
                        <pre>Foo *Bar_f_get(Bar *b) {<br> return &amp;b-&gt;f;<br>}<br><br>void Bar_f_set(Bar *b, Foo *val) {<br> b-&gt;f = *val;<br>}<br></pre>
602
 
                </div>
 
1196
<p> C/C++ structs are wrapped as Ruby classes, with accessor
 
1197
methods (i.e. "getters" and "setters") for all of the struct members.
 
1198
For example, this struct declaration: </p>
 
1199
 
 
1200
 
 
1201
 
 
1202
 
 
1203
 
 
1204
<div class="code">
 
1205
<pre>struct Vector {<br> double x, y;<br>};<br></pre>
 
1206
 
 
1207
 
 
1208
 
 
1209
 
 
1210
 
 
1211
</div>
 
1212
 
 
1213
 
 
1214
 
 
1215
 
 
1216
 
 
1217
<p> gets wrapped as a <tt>Vector</tt> class, with
 
1218
Ruby instance methods <tt>x</tt>, <tt> x=</tt>,
 
1219
<tt>y</tt> and <tt>y=</tt>. These methods can
 
1220
be used to access structure data from Ruby as follows: </p>
 
1221
 
 
1222
 
 
1223
 
 
1224
 
 
1225
 
 
1226
<div class="code targetlang">
 
1227
<pre>$ <b>irb</b><br>irb(main):001:0&gt; <b>require 'Example'</b><br>true<br>irb(main):002:0&gt; <b>f = Example::Vector.new</b><br>#&lt;Example::Vector:0x4020b268&gt;<br>irb(main):003:0&gt; <b>f.x = 10</b><br>nil<br>irb(main):004:0&gt; <b>f.x</b><br>10.0<br></pre>
 
1228
 
 
1229
 
 
1230
 
 
1231
 
 
1232
 
 
1233
</div>
 
1234
 
 
1235
 
 
1236
 
 
1237
 
 
1238
 
 
1239
<p> Similar access is provided for unions and the public data
 
1240
members of C++ classes.</p>
 
1241
 
 
1242
 
 
1243
 
 
1244
 
 
1245
 
 
1246
<p><tt>const</tt> members of a structure are
 
1247
read-only. Data members can also be forced to be read-only using the <tt>%immutable</tt>
 
1248
directive (in C++, <tt>private</tt> may also be used). For
 
1249
example: </p>
 
1250
 
 
1251
 
 
1252
 
 
1253
 
 
1254
 
 
1255
<div class="code">
 
1256
<pre>struct Foo {<br> ...<br> %immutable;<br> int x; /* Read-only members */<br> char *name;<br> %mutable;<br> ...<br>};<br></pre>
 
1257
 
 
1258
 
 
1259
 
 
1260
 
 
1261
 
 
1262
</div>
 
1263
 
 
1264
 
 
1265
 
 
1266
 
 
1267
 
 
1268
<p> When <tt>char *</tt> members of a structure are
 
1269
wrapped, the contents are assumed to be dynamically allocated using <tt>malloc</tt>
 
1270
or <tt>new</tt> (depending on whether or not SWIG is run
 
1271
with the <tt>-c++</tt> option). When the structure member
 
1272
is set, the old contents will be released and a new value created. If
 
1273
this is not the behavior you want, you will have to use a typemap
 
1274
(described shortly). </p>
 
1275
 
 
1276
 
 
1277
 
 
1278
 
 
1279
 
 
1280
<p>Array members are normally wrapped as read-only. For example,
 
1281
this code: </p>
 
1282
 
 
1283
 
 
1284
 
 
1285
 
 
1286
 
 
1287
<div class="code">
 
1288
<pre>struct Foo {<br> int x[50];<br>};<br></pre>
 
1289
 
 
1290
 
 
1291
 
 
1292
 
 
1293
 
 
1294
</div>
 
1295
 
 
1296
 
 
1297
 
 
1298
 
 
1299
 
 
1300
<p> produces a single accessor function like this: </p>
 
1301
 
 
1302
 
 
1303
 
 
1304
 
 
1305
 
 
1306
<div class="code">
 
1307
<pre>int *Foo_x_get(Foo *self) {<br> return self-&gt;x;<br>};<br></pre>
 
1308
 
 
1309
 
 
1310
 
 
1311
 
 
1312
 
 
1313
</div>
 
1314
 
 
1315
 
 
1316
 
 
1317
 
 
1318
 
 
1319
<p> If you want to set an array member, you will need to supply a
 
1320
"memberin" typemap described in the <a href="#ruby_cpp_smart_pointers">section on typemaps</a>.
 
1321
As a special case, SWIG does generate code to set array members of type
 
1322
<tt>char</tt> (allowing you to store a Ruby string in the
 
1323
structure). </p>
 
1324
 
 
1325
 
 
1326
 
 
1327
 
 
1328
 
 
1329
<p>When structure members are wrapped, they are handled as
 
1330
pointers. For example, </p>
 
1331
 
 
1332
 
 
1333
 
 
1334
 
 
1335
 
 
1336
<div class="code">
 
1337
<pre>struct Foo {<br> ...<br>};<br><br>struct Bar {<br> Foo f;<br>};<br></pre>
 
1338
 
 
1339
 
 
1340
 
 
1341
 
 
1342
 
 
1343
</div>
 
1344
 
 
1345
 
 
1346
 
 
1347
 
 
1348
 
 
1349
<p> generates accessor functions such as this: </p>
 
1350
 
 
1351
 
 
1352
 
 
1353
 
 
1354
 
 
1355
<div class="code">
 
1356
<pre>Foo *Bar_f_get(Bar *b) {<br> return &amp;b-&gt;f;<br>}<br><br>void Bar_f_set(Bar *b, Foo *val) {<br> b-&gt;f = *val;<br>}<br></pre>
 
1357
 
 
1358
 
 
1359
 
 
1360
 
 
1361
 
 
1362
</div>
 
1363
 
 
1364
 
 
1365
 
 
1366
 
 
1367
 
603
1368
<H3><a name="Ruby_nn18"></a>30.3.7 C++ classes</H3>
604
1369
 
605
1370
 
606
 
                <p>
607
 
                        Like structs, C++ classes are wrapped by creating a new Ruby class of the same 
608
 
                        name with accessor methods for the public class member data. Additionally, 
609
 
                        public member functions for the class are wrapped as Ruby instance methods, and 
610
 
                        public static member functions are wrapped as Ruby singleton methods. So, given 
611
 
                        the C++ class declaration:
612
 
                </p>
613
 
                <div class="code">
614
 
                        <pre>class List {<br>public:<br> List();<br> ~List();<br> int search(char *item);<br> void insert(char *item);<br> void remove(char *item);<br> char *get(int n);<br> int length;<br> static void print(List *l);<br>};<br></pre>
615
 
                </div>
616
 
                <p>
617
 
                        SWIG would create a <tt>List</tt> class with:
618
 
                </p>
619
 
                <ul>
620
 
                        <li>
621
 
                                instance methods <i>search</i>, <i>insert</i>, <i>remove</i>, and <i>get</i>;
622
 
                        </li>
623
 
                        <li>
624
 
                                instance methods <i>length</i> and <i>length=</i> (to get and set the value of 
625
 
                                the <i>length</i> data member); and,
626
 
                        </li>
627
 
                        <li>
628
 
                                a <i>print</i> singleton method for the class.
629
 
                        </li>
630
 
                </ul>
631
 
                <p>
632
 
                        In Ruby, these functions are used as follows:
633
 
                </p>
634
 
                <div class="code">
635
 
                        <pre>require 'Example'<br><br>l = Example::List.new<br><br>l.insert("Ale")<br>l.insert("Stout")<br>l.insert("Lager")<br>Example.print(l)<br>l.length()<br>----- produces the following output <br>Lager<br>Stout<br>Ale<br>3<br></pre>
636
 
                </div>
 
1371
<p> Like structs, C++ classes are wrapped by creating a new Ruby
 
1372
class of the same name with accessor methods for the public class
 
1373
member data. Additionally, public member functions for the class are
 
1374
wrapped as Ruby instance methods, and public static member functions
 
1375
are wrapped as Ruby singleton methods. So, given the C++ class
 
1376
declaration: </p>
 
1377
 
 
1378
 
 
1379
 
 
1380
 
 
1381
 
 
1382
<div class="code">
 
1383
<pre>class List {<br>public:<br> List();<br> ~List();<br> int search(char *item);<br> void insert(char *item);<br> void remove(char *item);<br> char *get(int n);<br> int length;<br> static void print(List *l);<br>};<br></pre>
 
1384
 
 
1385
 
 
1386
 
 
1387
 
 
1388
 
 
1389
</div>
 
1390
 
 
1391
 
 
1392
 
 
1393
 
 
1394
 
 
1395
<p> SWIG would create a <tt>List</tt> class with: </p>
 
1396
 
 
1397
 
 
1398
 
 
1399
 
 
1400
 
 
1401
<ul>
 
1402
 
 
1403
 
 
1404
 
 
1405
 
 
1406
 
 
1407
  <li> instance methods <i>search</i>, <i>insert</i>,
 
1408
    <i>remove</i>, and <i>get</i>; </li>
 
1409
 
 
1410
 
 
1411
 
 
1412
 
 
1413
 
 
1414
  <li> instance methods <i>length</i> and <i>length=</i>
 
1415
(to get and set the value of the <i>length</i> data
 
1416
member); and, </li>
 
1417
 
 
1418
 
 
1419
 
 
1420
 
 
1421
 
 
1422
  <li> a <i>print</i> singleton method for the
 
1423
class. </li>
 
1424
 
 
1425
 
 
1426
 
 
1427
 
 
1428
 
 
1429
</ul>
 
1430
 
 
1431
 
 
1432
 
 
1433
 
 
1434
 
 
1435
<p> In Ruby, these functions are used as follows: </p>
 
1436
 
 
1437
 
 
1438
 
 
1439
 
 
1440
 
 
1441
<div class="code targetlang">
 
1442
<pre>require 'Example'<br><br>l = Example::List.new<br><br>l.insert("Ale")<br>l.insert("Stout")<br>l.insert("Lager")<br>Example.print(l)<br>l.length()<br>----- produces the following output <br>Lager<br>Stout<br>Ale<br>3<br></pre>
 
1443
 
 
1444
 
 
1445
 
 
1446
 
 
1447
 
 
1448
</div>
 
1449
 
 
1450
 
 
1451
 
 
1452
 
 
1453
 
637
1454
<H3><a name="Ruby_nn19"></a>30.3.8 C++ Inheritance</H3>
638
1455
 
639
1456
 
640
 
                <p>
641
 
                        The SWIG type-checker is fully aware of C++ inheritance. Therefore, if you have 
642
 
                        classes like this:
643
 
                </p>
644
 
                <div class="code">
645
 
                        <pre>class Parent {<br> ...<br>};<br><br>class Child : public Parent {<br> ...<br>};<br></pre>
646
 
                </div>
647
 
                <p>
648
 
                        those classes are wrapped into a hierarchy of Ruby classes that reflect the 
649
 
                        same inheritance structure. All of the usual Ruby utility methods work 
650
 
                        normally:
651
 
                </p>
652
 
                <div class="code">
653
 
                        <pre>irb(main):001:0&gt; <b>c = Child.new</b><br>#&lt;Bar:0x4016efd4&gt;<br>irb(main):002:0&gt; <b>c.instance_of? Child</b><br>true<br>irb(main):003:0&gt; <b>b.instance_of? Parent</b><br>false<br>irb(main):004:0&gt; <b>b.is_a? Child</b><br>true<br>irb(main):005:0&gt; <b>b.is_a? Parent</b><br>true<br>irb(main):006:0&gt; <b>Child &lt; Parent</b><br>true<br>irb(main):007:0&gt; <b>Child &gt; Parent</b><br>false<br></pre>
654
 
                </div>
655
 
                <p>
656
 
                        Furthermore, if you have a function like this:
657
 
                </p>
658
 
                <div class="code">
659
 
                        <pre>void spam(Parent *f);<br></pre>
660
 
                </div>
661
 
                <p>
662
 
                        then the function <tt>spam()</tt> accepts <tt>Parent</tt>* or a pointer to any 
663
 
                        class derived from <tt>Parent</tt>.
664
 
                </p>
665
 
                <p>Until recently, the Ruby module for SWIG didn't support multiple inheritance, 
666
 
                        and this is still the default behavior. This doesn't mean that you can't wrap 
667
 
                        C++ classes which inherit from multiple base classes; it simply means that only 
668
 
                        the <b>first</b> base class listed in the class declaration is considered, and 
669
 
                        any additional base classes are ignored. As an example, consider a SWIG 
670
 
                        interface file with a declaration like this:
671
 
                </p>
672
 
                <div class="code">
673
 
                        <pre>class Derived : public Base1, public Base2<br>{<br> ...<br>};<br></pre>
674
 
                </div>
675
 
                <p>
676
 
                        For this case, the resulting Ruby class (<tt>Derived</tt>) will only consider <tt>Base1</tt>
677
 
                        as its superclass. It won't inherit any of <tt>Base2</tt>'s member functions or 
678
 
                        data and it won't recognize <tt>Base2</tt> as an "ancestor" of <tt>Derived</tt> 
679
 
                        (i.e. the <em>is_a?</em> relationship would fail). When SWIG processes this 
680
 
                        interface file, you'll see a warning message like:
681
 
                </p>
682
 
                <div class="code">
683
 
                        <pre>example.i:5: Warning(802): Warning for Derived: Base Base2 ignored.<br>Multiple inheritance is not supported in Ruby.<br></pre>
684
 
                </div>
685
 
                <p>
686
 
                        Starting with SWIG 1.3.20, the Ruby module for SWIG provides limited support 
687
 
                        for multiple inheritance. Because the approach for dealing with multiple 
688
 
                        inheritance introduces some limitations, this is an optional feature that you 
689
 
                        can activate with the <tt>-minherit</tt> command-line option:
690
 
                </p>
691
 
                <div class="code">
692
 
                        <pre>$ <b>swig -c++ -ruby -minherit example.i</b></pre>
693
 
                </div>
694
 
                <p>
695
 
                        Using our previous example, if your SWIG interface file contains a declaration 
696
 
                        like this:
697
 
                </p>
698
 
                <div class="code">
699
 
                        <pre>class Derived : public Base1, public Base2<br>{<br> ...<br>};<br></pre>
700
 
                </div>
701
 
                <p>
702
 
                        and you run SWIG with the <tt>-minherit</tt> command-line option, then you will 
703
 
                        end up with a Ruby class <tt>Derived</tt> that appears to "inherit" the member 
704
 
                        data and functions from both <tt>Base1</tt> and <tt>Base2</tt>. What actually 
705
 
                        happens is that three different top-level classes are created, with Ruby's <tt>Object</tt>
706
 
                        class as their superclass. Each of these classes defines a nested module named <tt>Impl</tt>, 
707
 
                        and it's in these nested <tt>Impl</tt> modules that the actual instance methods 
708
 
                        for the classes are defined, i.e.
709
 
                </p>
710
 
                <div class="code">
711
 
                        <pre>class Base1<br> module Impl<br> # Define Base1 methods here<br> end<br> include Impl<br>end<br><br>class Base2<br> module Impl<br> # Define Base2 methods here<br> end<br> include Impl<br>end<br><br>class Derived<br> module Impl<br> include Base1::Impl<br> include Base2::Impl<br> # Define Derived methods here<br> end<br> include Impl<br>end<br></pre>
712
 
                </div>
713
 
                <p>
714
 
                        Observe that after the nested <tt>Impl</tt> module for a class is defined, it 
715
 
                        is mixed-in to the class itself. Also observe that the <tt>Derived::Impl</tt> module 
716
 
                        first mixes-in its base classes' <tt>Impl</tt> modules, thus "inheriting" all 
717
 
                        of their behavior.
718
 
                </p>
719
 
                <p>The primary drawback is that, unlike the default mode of operation, neither <tt>Base1</tt>
720
 
                        nor <tt>Base2</tt> is a true superclass of <tt>Derived</tt> anymore:
721
 
                </p>
722
 
                <div class="code">
723
 
                        <pre>obj = Derived.new<br>obj.is_a? Base1 # this will return false...<br>obj.is_a? Base2 # ... and so will this<br></pre>
724
 
                </div>
725
 
                <p>
726
 
                        In most cases, this is not a serious problem since objects of type <tt>Derived</tt>
727
 
                        will otherwise behave as though they inherit from both <tt>Base1</tt> and <tt>Base2</tt>
728
 
                        (i.e. they exhibit <a href="http://c2.com/cgi/wiki?DuckTyping">"Duck Typing"</a>).
729
 
                </p>
 
1457
<p> The SWIG type-checker is fully aware of C++ inheritance.
 
1458
Therefore, if you have classes like this: </p>
 
1459
 
 
1460
 
 
1461
 
 
1462
 
 
1463
 
 
1464
<div class="code">
 
1465
<pre>class Parent {<br> ...<br>};<br><br>class Child : public Parent {<br> ...<br>};<br></pre>
 
1466
 
 
1467
 
 
1468
 
 
1469
 
 
1470
 
 
1471
</div>
 
1472
 
 
1473
 
 
1474
 
 
1475
 
 
1476
 
 
1477
<p> those classes are wrapped into a hierarchy of Ruby classes
 
1478
that reflect the same inheritance structure. All of the usual Ruby
 
1479
utility methods work normally: </p>
 
1480
 
 
1481
 
 
1482
 
 
1483
 
 
1484
 
 
1485
<div class="code">
 
1486
<pre>irb(main):001:0&gt; <b>c = Child.new</b><br>#&lt;Bar:0x4016efd4&gt;<br>irb(main):002:0&gt; <b>c.instance_of? Child</b><br>true<br>irb(main):003:0&gt; <b>b.instance_of? Parent</b><br>false<br>irb(main):004:0&gt; <b>b.is_a? Child</b><br>true<br>irb(main):005:0&gt; <b>b.is_a? Parent</b><br>true<br>irb(main):006:0&gt; <b>Child &lt; Parent</b><br>true<br>irb(main):007:0&gt; <b>Child &gt; Parent</b><br>false<br></pre>
 
1487
 
 
1488
 
 
1489
 
 
1490
 
 
1491
 
 
1492
</div>
 
1493
 
 
1494
 
 
1495
 
 
1496
 
 
1497
 
 
1498
<p> Furthermore, if you have a function like this: </p>
 
1499
 
 
1500
 
 
1501
 
 
1502
 
 
1503
 
 
1504
<div class="code">
 
1505
<pre>void spam(Parent *f);<br></pre>
 
1506
 
 
1507
 
 
1508
 
 
1509
 
 
1510
 
 
1511
</div>
 
1512
 
 
1513
 
 
1514
 
 
1515
 
 
1516
 
 
1517
<p> then the function <tt>spam()</tt> accepts <tt>Parent</tt>*
 
1518
or a pointer to any class derived from <tt>Parent</tt>. </p>
 
1519
 
 
1520
 
 
1521
 
 
1522
 
 
1523
 
 
1524
<p>Until recently, the Ruby module for SWIG didn't support
 
1525
multiple inheritance, and this is still the default behavior. This
 
1526
doesn't mean that you can't wrap C++ classes which inherit from
 
1527
multiple base classes; it simply means that only the <b>first</b>
 
1528
base class listed in the class declaration is considered, and any
 
1529
additional base classes are ignored. As an example, consider a SWIG
 
1530
interface file with a declaration like this: </p>
 
1531
 
 
1532
 
 
1533
 
 
1534
 
 
1535
 
 
1536
<div class="code">
 
1537
<pre>class Derived : public Base1, public Base2<br>{<br> ...<br>};<br></pre>
 
1538
 
 
1539
 
 
1540
 
 
1541
 
 
1542
 
 
1543
</div>
 
1544
 
 
1545
 
 
1546
 
 
1547
 
 
1548
 
 
1549
<p> For this case, the resulting Ruby class (<tt>Derived</tt>)
 
1550
will only consider <tt>Base1</tt> as its superclass. It
 
1551
won't inherit any of <tt>Base2</tt>'s member functions or
 
1552
data and it won't recognize <tt>Base2</tt> as an
 
1553
"ancestor" of <tt>Derived</tt> (i.e. the <em>is_a?</em>
 
1554
relationship would fail). When SWIG processes this interface file,
 
1555
you'll see a warning message like: </p>
 
1556
 
 
1557
 
 
1558
 
 
1559
 
 
1560
 
 
1561
<div class="code shell">
 
1562
<pre>example.i:5: Warning(802): Warning for Derived: Base Base2 ignored.<br>Multiple inheritance is not supported in Ruby.<br></pre>
 
1563
 
 
1564
 
 
1565
 
 
1566
 
 
1567
 
 
1568
</div>
 
1569
 
 
1570
 
 
1571
 
 
1572
 
 
1573
 
 
1574
<p> Starting with SWIG 1.3.20, the Ruby module for SWIG provides
 
1575
limited support for multiple inheritance. Because the approach for
 
1576
dealing with multiple inheritance introduces some limitations, this is
 
1577
an optional feature that you can activate with the <tt>-minherit</tt>
 
1578
command-line option: </p>
 
1579
 
 
1580
 
 
1581
 
 
1582
 
 
1583
 
 
1584
<div class="code shell">
 
1585
<pre>$ <b>swig -c++ -ruby -minherit example.i</b></pre>
 
1586
 
 
1587
 
 
1588
 
 
1589
 
 
1590
 
 
1591
</div>
 
1592
 
 
1593
 
 
1594
 
 
1595
 
 
1596
 
 
1597
<p> Using our previous example, if your SWIG interface file
 
1598
contains a declaration like this: </p>
 
1599
 
 
1600
 
 
1601
 
 
1602
 
 
1603
 
 
1604
<div class="code">
 
1605
<pre>class Derived : public Base1, public Base2<br>{<br> ...<br>};<br></pre>
 
1606
 
 
1607
 
 
1608
 
 
1609
 
 
1610
 
 
1611
</div>
 
1612
 
 
1613
 
 
1614
 
 
1615
 
 
1616
 
 
1617
<p> and you run SWIG with the <tt>-minherit</tt>
 
1618
command-line option, then you will end up with a Ruby class <tt>Derived</tt>
 
1619
that appears to "inherit" the member data and functions from both <tt>Base1</tt>
 
1620
and <tt>Base2</tt>. What actually happens is that three
 
1621
different top-level classes are created, with Ruby's <tt>Object</tt>
 
1622
class as their superclass. Each of these classes defines a nested
 
1623
module named <tt>Impl</tt>, and it's in these nested <tt>Impl</tt>
 
1624
modules that the actual instance methods for the classes are defined,
 
1625
i.e. </p>
 
1626
 
 
1627
 
 
1628
 
 
1629
 
 
1630
 
 
1631
<div class="code targetlang">
 
1632
<pre>class Base1<br> module Impl<br> # Define Base1 methods here<br> end<br> include Impl<br>end<br><br>class Base2<br> module Impl<br> # Define Base2 methods here<br> end<br> include Impl<br>end<br><br>class Derived<br> module Impl<br> include Base1::Impl<br> include Base2::Impl<br> # Define Derived methods here<br> end<br> include Impl<br>end<br></pre>
 
1633
 
 
1634
 
 
1635
 
 
1636
 
 
1637
 
 
1638
</div>
 
1639
 
 
1640
 
 
1641
 
 
1642
 
 
1643
 
 
1644
<p> Observe that after the nested <tt>Impl</tt>
 
1645
module for a class is defined, it is mixed-in to the class itself. Also
 
1646
observe that the <tt>Derived::Impl</tt> module first
 
1647
mixes-in its base classes' <tt>Impl</tt> modules, thus
 
1648
"inheriting" all of their behavior. </p>
 
1649
 
 
1650
 
 
1651
 
 
1652
 
 
1653
 
 
1654
<p>The primary drawback is that, unlike the default mode of
 
1655
operation, neither <tt>Base1</tt> nor <tt>Base2</tt>
 
1656
is a true superclass of <tt>Derived</tt> anymore: </p>
 
1657
 
 
1658
 
 
1659
 
 
1660
 
 
1661
 
 
1662
<div class="code targetlang">
 
1663
<pre>obj = Derived.new<br>obj.is_a? Base1 # this will return false...<br>obj.is_a? Base2 # ... and so will this<br></pre>
 
1664
 
 
1665
 
 
1666
 
 
1667
 
 
1668
 
 
1669
</div>
 
1670
 
 
1671
 
 
1672
 
 
1673
 
 
1674
 
 
1675
<p> In most cases, this is not a serious problem since objects of
 
1676
type <tt>Derived</tt> will otherwise behave as though they
 
1677
inherit from both <tt>Base1</tt> and <tt>Base2</tt>
 
1678
(i.e. they exhibit <a href="http://c2.com/cgi/wiki?DuckTyping">"Duck
 
1679
Typing"</a>). </p>
 
1680
 
 
1681
 
 
1682
 
 
1683
 
 
1684
 
730
1685
<H3><a name="Ruby_nn20"></a>30.3.9 C++ Overloaded Functions</H3>
731
1686
 
732
1687
 
733
 
                <p>
734
 
                        C++ overloaded functions, methods, and constructors are mostly supported by 
735
 
                        SWIG. For example, if you have two functions like this:
736
 
                </p>
737
 
                <div class="code">
738
 
                        <pre>void foo(int);<br>void foo(char *c);<br></pre>
739
 
                </div>
740
 
                <p>
741
 
                        You can use them in Ruby in a straightforward manner:
742
 
                </p>
743
 
                <div class="code">
744
 
                        <pre>irb(main):001:0&gt; <b>foo(3)</b> # foo(int)<br>irb(main):002:0&gt; <b>foo("Hello")</b> # foo(char *c)<br></pre>
745
 
                </div>
746
 
                <p>Similarly, if you have a class like this,</p>
747
 
                <div class="code">
748
 
                        <pre>class Foo {<br>public:<br> Foo();<br> Foo(const Foo &amp;);<br> ...<br>};<br></pre>
749
 
                </div>
750
 
                <p>you can write Ruby code like this:</p>
751
 
                <div class="code">
752
 
                        <pre>irb(main):001:0&gt; <b>f = Foo.new</b> # Create a Foo<br>irb(main):002:0&gt; <b>g = Foo.new(f)</b> # Copy f<br></pre>
753
 
                </div>
754
 
                <p>
755
 
                        Overloading support is not quite as flexible as in C++. Sometimes there are 
756
 
                        methods that SWIG can't disambiguate. For example:
757
 
                </p>
758
 
                <div class="code">
759
 
                        <pre>void spam(int);<br>void spam(short);<br></pre>
760
 
                </div>
761
 
                <p>or</p>
762
 
                <div class="code">
763
 
                        <pre>void foo(Bar *b);<br>void foo(Bar &amp;b);<br></pre>
764
 
                </div>
765
 
                <p>
766
 
                        If declarations such as these appear, you will get a warning message like this:
767
 
                </p>
768
 
                <div class="code">
769
 
                        <pre>example.i:12: Warning(509): Overloaded spam(short) is shadowed by spam(int)<br>at example.i:11.<br> </pre>
770
 
                </div>
771
 
                <p>
772
 
                        To fix this, you either need to ignore or rename one of the methods. For 
773
 
                        example:
774
 
                </p>
775
 
                <div class="code">
776
 
                        <pre>%rename(spam_short) spam(short);<br>...<br>void spam(int); <br>void spam(short); // Accessed as spam_short<br></pre>
777
 
                </div>
778
 
                <p>or</p>
779
 
                <div class="code">
780
 
                        <pre>%ignore spam(short);<br>...<br>void spam(int); <br>void spam(short); // Ignored<br></pre>
781
 
                </div>
782
 
                <p>
783
 
                        SWIG resolves overloaded functions and methods using a disambiguation scheme 
784
 
                        that ranks and sorts declarations according to a set of type-precedence rules. 
785
 
                        The order in which declarations appear in the input does not matter except in 
786
 
                        situations where ambiguity arises--in this case, the first declaration takes 
787
 
                        precedence.
788
 
                </p>
789
 
                <p>Please refer to the <a href="SWIGPlus.html#SWIGPlus">"SWIG and C++"</a> chapter 
790
 
                        for more information about overloading. <a name="n21"></a>
791
 
                </p>
 
1688
<p> C++ overloaded functions, methods, and constructors are
 
1689
mostly supported by SWIG. For example, if you have two functions like
 
1690
this: </p>
 
1691
 
 
1692
 
 
1693
 
 
1694
 
 
1695
 
 
1696
<div class="code">
 
1697
<pre>void foo(int);<br>void foo(char *c);<br></pre>
 
1698
 
 
1699
 
 
1700
 
 
1701
 
 
1702
 
 
1703
</div>
 
1704
 
 
1705
 
 
1706
 
 
1707
 
 
1708
 
 
1709
<p> You can use them in Ruby in a straightforward manner: </p>
 
1710
 
 
1711
 
 
1712
 
 
1713
 
 
1714
 
 
1715
<div class="code targetlang">
 
1716
<pre>irb(main):001:0&gt; <b>foo(3)</b> # foo(int)<br>irb(main):002:0&gt; <b>foo("Hello")</b> # foo(char *c)<br></pre>
 
1717
 
 
1718
 
 
1719
 
 
1720
 
 
1721
 
 
1722
</div>
 
1723
 
 
1724
 
 
1725
 
 
1726
 
 
1727
 
 
1728
<p>Similarly, if you have a class like this,</p>
 
1729
 
 
1730
 
 
1731
 
 
1732
 
 
1733
 
 
1734
<div class="code">
 
1735
<pre>class Foo {<br>public:<br> Foo();<br> Foo(const Foo &amp;);<br> ...<br>};<br></pre>
 
1736
 
 
1737
 
 
1738
 
 
1739
 
 
1740
 
 
1741
</div>
 
1742
 
 
1743
 
 
1744
 
 
1745
 
 
1746
 
 
1747
<p>you can write Ruby code like this:</p>
 
1748
 
 
1749
 
 
1750
 
 
1751
 
 
1752
 
 
1753
<div class="code targetlang">
 
1754
<pre>irb(main):001:0&gt; <b>f = Foo.new</b> # Create a Foo<br>irb(main):002:0&gt; <b>g = Foo.new(f)</b> # Copy f<br></pre>
 
1755
 
 
1756
 
 
1757
 
 
1758
 
 
1759
 
 
1760
</div>
 
1761
 
 
1762
 
 
1763
 
 
1764
 
 
1765
 
 
1766
<p> Overloading support is not quite as flexible as in C++.
 
1767
Sometimes there are methods that SWIG can't disambiguate. For example: </p>
 
1768
 
 
1769
 
 
1770
 
 
1771
 
 
1772
 
 
1773
<div class="code">
 
1774
<pre>void spam(int);<br>void spam(short);<br></pre>
 
1775
 
 
1776
 
 
1777
 
 
1778
 
 
1779
 
 
1780
</div>
 
1781
 
 
1782
 
 
1783
 
 
1784
 
 
1785
 
 
1786
<p>or</p>
 
1787
 
 
1788
 
 
1789
 
 
1790
 
 
1791
 
 
1792
<div class="code">
 
1793
<pre>void foo(Bar *b);<br>void foo(Bar &amp;b);<br></pre>
 
1794
 
 
1795
 
 
1796
 
 
1797
 
 
1798
 
 
1799
</div>
 
1800
 
 
1801
 
 
1802
 
 
1803
 
 
1804
 
 
1805
<p> If declarations such as these appear, you will get a warning
 
1806
message like this: </p>
 
1807
 
 
1808
 
 
1809
 
 
1810
 
 
1811
 
 
1812
<div class="code shell">
 
1813
<pre>example.i:12: Warning(509): Overloaded spam(short) is shadowed by spam(int)<br>at example.i:11.<br> </pre>
 
1814
 
 
1815
 
 
1816
 
 
1817
 
 
1818
 
 
1819
</div>
 
1820
 
 
1821
 
 
1822
 
 
1823
 
 
1824
 
 
1825
<p> To fix this, you either need to ignore or rename one of the
 
1826
methods. For example: </p>
 
1827
 
 
1828
 
 
1829
 
 
1830
 
 
1831
 
 
1832
<div class="code">
 
1833
<pre>%rename(spam_short) spam(short);<br>...<br>void spam(int); <br>void spam(short); // Accessed as spam_short<br></pre>
 
1834
 
 
1835
 
 
1836
 
 
1837
 
 
1838
 
 
1839
</div>
 
1840
 
 
1841
 
 
1842
 
 
1843
 
 
1844
 
 
1845
<p>or</p>
 
1846
 
 
1847
 
 
1848
 
 
1849
 
 
1850
 
 
1851
<div class="code">
 
1852
<pre>%ignore spam(short);<br>...<br>void spam(int); <br>void spam(short); // Ignored<br></pre>
 
1853
 
 
1854
 
 
1855
 
 
1856
 
 
1857
 
 
1858
</div>
 
1859
 
 
1860
 
 
1861
 
 
1862
 
 
1863
 
 
1864
<p> SWIG resolves overloaded functions and methods using a
 
1865
disambiguation scheme that ranks and sorts declarations according to a
 
1866
set of type-precedence rules. The order in which declarations appear in
 
1867
the input does not matter except in situations where ambiguity
 
1868
arises--in this case, the first declaration takes precedence. </p>
 
1869
 
 
1870
 
 
1871
 
 
1872
 
 
1873
 
 
1874
<p>Please refer to the <a href="SWIGPlus.html#SWIGPlus">"SWIG
 
1875
and C++"</a> chapter for more information about overloading. </p>
 
1876
 
 
1877
 
 
1878
 
 
1879
 
 
1880
 
792
1881
<H3><a name="Ruby_nn21"></a>30.3.10 C++ Operators</H3>
793
1882
 
794
1883
 
795
 
                <p>
796
 
                        For the most part, overloaded operators are handled automatically by SWIG and 
797
 
                        do not require any special treatment on your part. So if your class declares an 
798
 
                        overloaded addition operator, e.g.
799
 
                </p>
800
 
                <div class="code">
801
 
                        <pre>class Complex {<br> ...<br> Complex operator+(Complex &amp;);<br> ...<br>};<br></pre>
802
 
                </div>
803
 
                <p>
804
 
                        the resulting Ruby class will also support the addition (+) method correctly.
805
 
                </p>
806
 
                <p>For cases where SWIG's built-in support is not sufficient, C++ operators can be 
807
 
                        wrapped using the <tt>%rename</tt> directive (available on SWIG 1.3.10 and 
808
 
                        later releases). All you need to do is give the operator the name of a valid 
809
 
                        Ruby identifier. For example:
810
 
                </p>
811
 
                <div class="code">
812
 
                        <pre>%rename(add_complex) operator+(Complex &amp;, Complex &amp;);<br>...<br>Complex operator+(Complex &amp;, Complex &amp;);<br></pre>
813
 
                </div>
814
 
                <p>Now, in Ruby, you can do this:</p>
815
 
                <div class="code">
816
 
                        <pre>a = Example::Complex.new(2, 3)<br>b = Example::Complex.new(4, -1)<br>c = Example.add_complex(a, b)<br></pre>
817
 
                </div>
818
 
                <p>
819
 
                        More details about wrapping C++ operators into Ruby operators is discussed in 
820
 
                        the <a href="#ruby_operator_overloading">section on operator overloading</a>.
821
 
                </p>
 
1884
<p> For the most part, overloaded operators are handled
 
1885
automatically by SWIG and do not require any special treatment on your
 
1886
part. So if your class declares an overloaded addition operator, e.g. </p>
 
1887
 
 
1888
 
 
1889
 
 
1890
 
 
1891
 
 
1892
<div class="code">
 
1893
<pre>class Complex {<br> ...<br> Complex operator+(Complex &amp;);<br> ...<br>};<br></pre>
 
1894
 
 
1895
 
 
1896
 
 
1897
 
 
1898
 
 
1899
</div>
 
1900
 
 
1901
 
 
1902
 
 
1903
 
 
1904
 
 
1905
<p> the resulting Ruby class will also support the addition (+)
 
1906
method correctly. </p>
 
1907
 
 
1908
 
 
1909
 
 
1910
 
 
1911
 
 
1912
<p>For cases where SWIG's built-in support is not sufficient, C++
 
1913
operators can be wrapped using the <tt>%rename</tt>
 
1914
directive (available on SWIG 1.3.10 and later releases). All you need
 
1915
to do is give the operator the name of a valid Ruby identifier. For
 
1916
example: </p>
 
1917
 
 
1918
 
 
1919
 
 
1920
 
 
1921
 
 
1922
<div class="code">
 
1923
<pre>%rename(add_complex) operator+(Complex &amp;, Complex &amp;);<br>...<br>Complex operator+(Complex &amp;, Complex &amp;);<br></pre>
 
1924
 
 
1925
 
 
1926
 
 
1927
 
 
1928
 
 
1929
</div>
 
1930
 
 
1931
 
 
1932
 
 
1933
 
 
1934
 
 
1935
<p>Now, in Ruby, you can do this:</p>
 
1936
 
 
1937
 
 
1938
 
 
1939
 
 
1940
 
 
1941
<div class="code targetlang">
 
1942
<pre>a = Example::Complex.new(2, 3)<br>b = Example::Complex.new(4, -1)<br>c = Example.add_complex(a, b)<br></pre>
 
1943
 
 
1944
 
 
1945
 
 
1946
 
 
1947
 
 
1948
</div>
 
1949
 
 
1950
 
 
1951
 
 
1952
 
 
1953
 
 
1954
<p> More details about wrapping C++ operators into Ruby operators
 
1955
is discussed in the <a href="#ruby_operator_overloading">section
 
1956
on operator overloading</a>. </p>
 
1957
 
 
1958
 
 
1959
 
 
1960
 
 
1961
 
822
1962
<H3><a name="Ruby_nn22"></a>30.3.11 C++ namespaces</H3>
823
1963
 
824
1964
 
825
 
                <p>
826
 
                        SWIG is aware of C++ namespaces, but namespace names do not appear in the 
827
 
                        module nor do namespaces result in a module that is broken up into submodules 
828
 
                        or packages. For example, if you have a file like this,
829
 
                </p>
830
 
                <div class="code">
831
 
                        <pre>%module example<br><br>namespace foo {<br> int fact(int n);<br> struct Vector {<br> double x,y,z;<br> };<br>};<br></pre>
832
 
                </div>
833
 
                <p>it works in Ruby as follows:</p>
834
 
                <div class="code">
835
 
                        <pre>irb(main):001:0&gt; <b>require 'example'</b><br>true<br>irb(main):002:0&gt; <b>Example.fact(3)</b><br>6<br>irb(main):003:0&gt; <b>v = Example::Vector.new</b><br>#&lt;Example::Vector:0x4016f4d4&gt;<br>irb(main):004:0&gt; <b>v.x = 3.4</b><br>3.4<br>irb(main):004:0&gt; <b>v.y</b><br>0.0<br></pre>
836
 
                </div>
837
 
                <p>
838
 
                        If your program has more than one namespace, name conflicts (if any) can be 
839
 
                        resolved using <tt>%rename</tt> For example:
840
 
                </p>
841
 
                <div class="code">
842
 
                        <pre>%rename(Bar_spam) Bar::spam;<br><br>namespace Foo {<br> int spam();<br>}<br><br>namespace Bar {<br> int spam();<br>}<br></pre>
843
 
                </div>
844
 
                <p>
845
 
                        If you have more than one namespace and your want to keep their symbols 
846
 
                        separate, consider wrapping them as separate SWIG modules. For example, make 
847
 
                        the module name the same as the namespace and create extension modules for each 
848
 
                        namespace separately. If your program utilizes thousands of small deeply nested 
849
 
                        namespaces each with identical symbol names, well, then you get what you 
850
 
                        deserve.
851
 
                </p>
 
1965
<p> SWIG is aware of C++ namespaces, but namespace names do not
 
1966
appear in the module nor do namespaces result in a module that is
 
1967
broken up into submodules or packages. For example, if you have a file
 
1968
like this, </p>
 
1969
 
 
1970
 
 
1971
 
 
1972
 
 
1973
 
 
1974
<div class="code">
 
1975
<pre>%module example<br><br>namespace foo {<br> int fact(int n);<br> struct Vector {<br> double x,y,z;<br> };<br>};<br></pre>
 
1976
 
 
1977
 
 
1978
 
 
1979
 
 
1980
 
 
1981
</div>
 
1982
 
 
1983
 
 
1984
 
 
1985
 
 
1986
 
 
1987
<p>it works in Ruby as follows:</p>
 
1988
 
 
1989
 
 
1990
 
 
1991
 
 
1992
 
 
1993
<div class="code targetlang">
 
1994
<pre>irb(main):001:0&gt; <b>require 'example'</b><br>true<br>irb(main):002:0&gt; <b>Example.fact(3)</b><br>6<br>irb(main):003:0&gt; <b>v = Example::Vector.new</b><br>#&lt;Example::Vector:0x4016f4d4&gt;<br>irb(main):004:0&gt; <b>v.x = 3.4</b><br>3.4<br>irb(main):004:0&gt; <b>v.y</b><br>0.0<br></pre>
 
1995
 
 
1996
 
 
1997
 
 
1998
 
 
1999
 
 
2000
</div>
 
2001
 
 
2002
 
 
2003
 
 
2004
 
 
2005
 
 
2006
<p> If your program has more than one namespace, name conflicts
 
2007
(if any) can be resolved using <tt>%rename</tt> For
 
2008
example: </p>
 
2009
 
 
2010
 
 
2011
 
 
2012
 
 
2013
 
 
2014
<div class="code">
 
2015
<pre>%rename(Bar_spam) Bar::spam;<br><br>namespace Foo {<br> int spam();<br>}<br><br>namespace Bar {<br> int spam();<br>}<br></pre>
 
2016
 
 
2017
 
 
2018
 
 
2019
 
 
2020
 
 
2021
</div>
 
2022
 
 
2023
 
 
2024
 
 
2025
 
 
2026
 
 
2027
<p> If you have more than one namespace and your want to keep
 
2028
their symbols separate, consider wrapping them as separate SWIG
 
2029
modules. For example, make the module name the same as the namespace
 
2030
and create extension modules for each namespace separately. If your
 
2031
program utilizes thousands of small deeply nested namespaces each with
 
2032
identical symbol names, well, then you get what you deserve. </p>
 
2033
 
 
2034
 
 
2035
 
 
2036
 
 
2037
 
852
2038
<H3><a name="Ruby_nn23"></a>30.3.12 C++ templates</H3>
853
2039
 
854
2040
 
855
 
                <p>
856
 
                        C++ templates don't present a huge problem for SWIG. However, in order to 
857
 
                        create wrappers, you have to tell SWIG to create wrappers for a particular 
858
 
                        template instantiation. To do this, you use the <tt>%template</tt> directive. 
859
 
                        For example:
860
 
                </p>
861
 
                <div class="code">
862
 
                        <pre>%module example<br><br>%{<br>#include "pair.h"<br>%}<br><br>template&lt;class T1, class T2&gt;<br>struct pair {<br> typedef T1 first_type;<br> typedef T2 second_type;<br> T1 first;<br> T2 second;<br> pair();<br> pair(const T1&amp;, const T2&amp;);<br> ~pair();<br>};<br><br>%template(Pairii) pair&lt;int,int&gt;;<br></pre>
863
 
                </div>
864
 
                <p>In Ruby:</p>
865
 
                <div class="code">
866
 
                        <pre>irb(main):001:0&gt; <b>require 'example'</b><br>true<br>irb(main):002:0&gt; <b>p = Example::Pairii.new(3, 4)</b><br>#&lt;Example:Pairii:0x4016f4df&gt;<br>irb(main):003:0&gt; <b>p.first</b><br>3<br>irb(main):004:0&gt; <b>p.second</b><br>4<br></pre>
867
 
                </div>
868
 
                <p>
869
 
                        On a related note, the standard SWIG library contains a number of modules that 
870
 
                        provide typemaps for standard C++ library classes (such as <tt>std::pair</tt>, <tt>std::string</tt>
871
 
                        and <tt>std::vector</tt>). These library modules don't provide wrappers around 
872
 
                        the templates themselves, but they do make it convenient for users of your 
873
 
                        extension module to pass Ruby objects (such as arrays and strings) to wrapped 
874
 
                        C++ code that expects instances of standard C++ templates. For example, suppose 
875
 
                        the C++ library you're wrapping has a function that expects a vector of floats:
876
 
                </p>
877
 
                <div class="code">
878
 
                        <pre>%module example<br><br>float sum(const std::vector&lt;float&gt;&amp; values);<br></pre>
879
 
                </div>
880
 
                <p>
881
 
                        Rather than go through the hassle of writing an "in" typemap to convert an 
882
 
                        array of Ruby numbers into a std::vector&lt;float&gt;, you can just use the <tt>std_vector.i</tt>
883
 
                        module from the standard SWIG library:
884
 
                </p>
885
 
                <div class="code">
886
 
                        <pre>%module example<br><br><b>%include std_vector.i</b><br>float sum(const std::vector&lt;float&gt;&amp; values);<br></pre>
887
 
                </div>
888
 
                <p>
889
 
                        Obviously, there is a lot more to template wrapping than shown in these 
890
 
                        examples. More details can be found in the <a href="SWIGPlus.html#SWIGPlus">SWIG 
891
 
                                and C++</a> chapter.
892
 
                </p>
893
 
<H3><a name="Ruby_nn24"></a>30.3.13 C++ Smart Pointers</H3>
894
 
 
895
 
 
896
 
                <p>
897
 
                        In certain C++ programs, it is common to use classes that have been wrapped by 
898
 
                        so-called "smart pointers." Generally, this involves the use of a template 
899
 
                        class that implements <tt>operator-&gt;()</tt> like this:
900
 
                </p>
901
 
                <div class="code">
902
 
                        <pre>template&lt;class T&gt; class SmartPtr {<br> ...<br> T *operator-&gt;();<br> ...<br>}<br></pre>
903
 
                </div>
904
 
                <p>Then, if you have a class like this,</p>
905
 
                <div class="code">
906
 
                        <pre>class Foo {<br>public:<br> int x;<br> int bar();<br>};<br></pre>
907
 
                </div>
908
 
                <p>A smart pointer would be used in C++ as follows:</p>
909
 
                <div class="code">
910
 
                        <pre>SmartPtr&lt;Foo&gt; p = CreateFoo(); // Created somehow (not shown)<br>...<br>p-&gt;x = 3; // Foo::x<br>int y = p-&gt;bar(); // Foo::bar<br></pre>
911
 
                </div>
912
 
                <p>
913
 
                        To wrap this in Ruby, simply tell SWIG about the <tt>SmartPtr</tt> class and 
914
 
                        the low-level <tt>Foo</tt> object. Make sure you instantiate <tt>SmartPtr</tt> using
915
 
                        <tt>%template</tt> if necessary. For example:
916
 
                </p>
917
 
                <div class="code">
918
 
                        <pre>%module example<br>...<br>%template(SmartPtrFoo) SmartPtr&lt;Foo&gt;;<br>...<br></pre>
919
 
                </div>
920
 
                <p>Now, in Ruby, everything should just "work":</p>
921
 
                <div class="code">
922
 
                        <pre>irb(main):001:0&gt; <b>p = Example::CreateFoo()</b> # Create a smart-pointer somehow<br>#&lt;Example::SmartPtrFoo:0x4016f4df&gt;<br>irb(main):002:0&gt; <b>p.x = 3</b> # Foo::x<br>3<br>irb(main):003:0&gt; <b>p.bar()</b> # Foo::bar<br></pre>
923
 
                </div>
924
 
                <p>
925
 
                        If you ever need to access the underlying pointer returned by <tt>operator-&gt;()</tt>
926
 
                        itself, simply use the <tt>__deref__()</tt> method. For example:
927
 
                </p>
928
 
                <div class="code">
929
 
                        <pre>irb(main):004:0&gt; <b>f = p.__deref__()</b> # Returns underlying Foo *<br></pre>
930
 
                </div>
931
 
<H3><a name="Ruby_nn25"></a>30.3.14 Cross-Language Polymorphism</H3>
932
 
 
933
 
 
934
 
                <p>
935
 
                        SWIG's Ruby module supports cross-language polymorphism (a.k.a. the "directors" 
936
 
                        feature) similar to that for SWIG's Python module. Rather than duplicate the 
937
 
                        information presented in the <a href="Python.html#Python">Python</a> chapter, 
938
 
                        this section just notes the differences that you need to be aware of when using 
939
 
                        this feature with Ruby.
940
 
                </p>
941
 
<H4><a name="Ruby_nn26"></a>30.3.14.1 Exception Unrolling</H4>
942
 
 
943
 
 
944
 
                <p>
945
 
                        Whenever a C++ director class routes one of its virtual member function calls 
946
 
                        to a Ruby instance method, there's always the possibility that an exception 
947
 
                        will be raised in the Ruby code. By default, those exceptions are ignored, 
948
 
                        which simply means that the exception will be exposed to the Ruby interpreter. 
949
 
                        If you would like to change this behavior, you can use the <tt>%feature("director:except")</tt>
950
 
                        directive to indicate what action should be taken when a Ruby exception is 
951
 
                        raised. The following code should suffice in most cases:
952
 
                </p>
953
 
                <div class="code">
954
 
                        <pre>%feature("director:except") {<br> throw Swig::DirectorMethodException($error);<br>}<br></pre>
955
 
                </div>
956
 
                <p>
957
 
                        When this feature is activated, the call to the Ruby instance method is 
958
 
                        "wrapped" using the <tt>rb_rescue2()</tt> function from Ruby's C API. If any 
959
 
                        Ruby exception is raised, it will be caught here and a C++ exception is raised 
960
 
                        in its place.
961
 
                </p>
 
2041
<p> C++ templates don't present a huge problem for SWIG. However,
 
2042
in order to create wrappers, you have to tell SWIG to create wrappers
 
2043
for a particular template instantiation. To do this, you use the <tt>%template</tt>
 
2044
directive. For example: </p>
 
2045
 
 
2046
 
 
2047
 
 
2048
 
 
2049
 
 
2050
<div class="code">
 
2051
<pre>%module example<br><br>%{<br>#include "pair.h"<br>%}<br><br>template&lt;class T1, class T2&gt;<br>struct pair {<br> typedef T1 first_type;<br> typedef T2 second_type;<br> T1 first;<br> T2 second;<br> pair();<br> pair(const T1&amp;, const T2&amp;);<br> ~pair();<br>};<br><br>%template(Pairii) pair&lt;int,int&gt;;<br></pre>
 
2052
 
 
2053
 
 
2054
 
 
2055
 
 
2056
 
 
2057
</div>
 
2058
 
 
2059
 
 
2060
 
 
2061
 
 
2062
 
 
2063
<p>In Ruby:</p>
 
2064
 
 
2065
 
 
2066
 
 
2067
 
 
2068
 
 
2069
<div class="code targetlang">
 
2070
<pre>irb(main):001:0&gt; <b>require 'example'</b><br>true<br>irb(main):002:0&gt; <b>p = Example::Pairii.new(3, 4)</b><br>#&lt;Example:Pairii:0x4016f4df&gt;<br>irb(main):003:0&gt; <b>p.first</b><br>3<br>irb(main):004:0&gt; <b>p.second</b><br>4<br></pre>
 
2071
 
 
2072
 
 
2073
 
 
2074
 
 
2075
 
 
2076
</div>
 
2077
 
 
2078
 
 
2079
 
 
2080
 
 
2081
 
 
2082
<H3><a name="Ruby_nn23_1"></a>30.3.13 C++ Standard Template Library (STL)</H3>
 
2083
 
 
2084
 
 
2085
<p> On a related note, the standard SWIG library contains a
 
2086
number of modules that provide typemaps for standard C++ library
 
2087
classes (such as <tt>std::pair</tt>, <tt>std::string</tt>
 
2088
and <tt>std::vector</tt>). These library modules don't
 
2089
provide wrappers around the templates themselves, but they do make it
 
2090
convenient for users of your extension module to pass Ruby objects
 
2091
(such as arrays and strings) to wrapped C++ code that expects instances
 
2092
of standard C++ templates. For example, suppose the C++ library you're
 
2093
wrapping has a function that expects a vector of floats: </p>
 
2094
 
 
2095
 
 
2096
 
 
2097
 
 
2098
 
 
2099
<div class="code">
 
2100
<pre>%module example<br><br>float sum(const std::vector&lt;float&gt;&amp; values);<br></pre>
 
2101
 
 
2102
 
 
2103
 
 
2104
 
 
2105
 
 
2106
</div>
 
2107
 
 
2108
 
 
2109
 
 
2110
 
 
2111
 
 
2112
<p> Rather than go through the hassle of writing an "in" typemap
 
2113
to convert an array of Ruby numbers into a
 
2114
std::vector&lt;float&gt;, you can just use the <tt>std_vector.i</tt>
 
2115
module from the standard SWIG library: </p>
 
2116
 
 
2117
 
 
2118
 
 
2119
 
 
2120
 
 
2121
<div class="code">
 
2122
<pre>%module example<br><br><b>%include std_vector.i</b><br>float sum(const std::vector&lt;float&gt;&amp; values);<br></pre>
 
2123
 
 
2124
 
 
2125
 
 
2126
 
 
2127
 
 
2128
</div>
 
2129
 
 
2130
 
 
2131
 
 
2132
 
 
2133
 
 
2134
<p>Ruby's STL wrappings provide additional methods to make them
 
2135
behave more similarly to Ruby's native classes.</p>
 
2136
 
 
2137
 
 
2138
 
 
2139
 
 
2140
 
 
2141
<p>Thus, you can do, for example:</p>
 
2142
 
 
2143
 
 
2144
 
 
2145
 
 
2146
 
 
2147
<div class="targetlang">
 
2148
<pre>v = IntVector.new<span class="targetlang"><br>v &lt;&lt; 2</span><span class="targetlang"><br>v &lt;&lt; 3<br>v &lt;&lt; 4<br>v.each { |x| puts x }<br><span style="font-weight: bold;"><br>=&gt; 2</span><br style="font-weight: bold;"><span style="font-weight: bold;">3</span><br style="font-weight: bold;"><span style="font-weight: bold;">4<br></span>v.delete_if { |x| x == 3 }<br><span style="font-weight: bold;">=&gt; [2,4]</span></span></pre>
 
2149
 
 
2150
 
 
2151
 
 
2152
 
 
2153
 
 
2154
</div>
 
2155
 
 
2156
 
 
2157
 
 
2158
 
 
2159
 
 
2160
<p>The SWIG Ruby module provides also the ability for all the STL
 
2161
containers to carry around Ruby native objects (Fixnum, Classes, etc)
 
2162
making them act almost like Ruby's own Array, Hash, etc. &nbsp; To
 
2163
do
 
2164
that, you need to define a container that contains a swig::GC_VALUE,
 
2165
like:</p>
 
2166
 
 
2167
 
 
2168
 
 
2169
 
 
2170
 
 
2171
<div style="font-family: monospace;" class="code">%module
 
2172
nativevector<br>
 
2173
 
 
2174
 
 
2175
 
 
2176
 
 
2177
 
 
2178
<br>
 
2179
 
 
2180
 
 
2181
 
 
2182
 
 
2183
 
 
2184
%{<br>
 
2185
 
 
2186
 
 
2187
 
 
2188
 
 
2189
 
 
2190
std::vector&lt; swig::GC_VALUE &gt; NativeVector;<br>
 
2191
 
 
2192
 
 
2193
 
 
2194
 
 
2195
 
 
2196
%}<br>
 
2197
 
 
2198
 
 
2199
 
 
2200
 
 
2201
 
 
2202
<br>
 
2203
 
 
2204
 
 
2205
 
 
2206
 
 
2207
 
 
2208
%template(NativeVector) std::vector&lt; swig::GC_VALUE &gt;;<br>
 
2209
 
 
2210
 
 
2211
 
 
2212
 
 
2213
 
 
2214
</div>
 
2215
 
 
2216
 
 
2217
 
 
2218
 
 
2219
 
 
2220
<br>
 
2221
 
 
2222
 
 
2223
 
 
2224
 
 
2225
 
 
2226
<p>This vector can then contain any Ruby object, making them
 
2227
almost identical to Ruby's own Array class.</p>
 
2228
 
 
2229
 
 
2230
 
 
2231
 
 
2232
 
 
2233
<div class="targetlang"><span style="font-family: monospace;">require 'nativevector'</span><br style="font-family: monospace;">
 
2234
 
 
2235
 
 
2236
 
 
2237
 
 
2238
 
 
2239
<span style="font-family: monospace;">include NativeVector</span><br style="font-family: monospace;">
 
2240
 
 
2241
 
 
2242
 
 
2243
 
 
2244
 
 
2245
<br style="font-family: monospace;">
 
2246
 
 
2247
 
 
2248
 
 
2249
 
 
2250
 
 
2251
<span style="font-family: monospace;">v = NativeVector.new</span><br style="font-family: monospace;">
 
2252
 
 
2253
 
 
2254
 
 
2255
 
 
2256
 
 
2257
<span style="font-family: monospace;">v &lt;&lt; 1</span><br style="font-family: monospace;">
 
2258
 
 
2259
 
 
2260
 
 
2261
 
 
2262
 
 
2263
<span style="font-family: monospace;">v &lt;&lt;
 
2264
[1,2]</span><br style="font-family: monospace;">
 
2265
 
 
2266
 
 
2267
 
 
2268
 
 
2269
 
 
2270
<span style="font-family: monospace;">v &lt;&lt;
 
2271
'hello'</span><br style="font-family: monospace;">
 
2272
 
 
2273
 
 
2274
 
 
2275
 
 
2276
 
 
2277
<br style="font-family: monospace;">
 
2278
 
 
2279
 
 
2280
 
 
2281
 
 
2282
 
 
2283
<span style="font-family: monospace;">class A; end</span><br style="font-family: monospace;">
 
2284
 
 
2285
 
 
2286
 
 
2287
 
 
2288
 
 
2289
<br style="font-family: monospace;">
 
2290
 
 
2291
 
 
2292
 
 
2293
 
 
2294
 
 
2295
<span style="font-family: monospace;">v &lt;&lt;
 
2296
A.new</span><br style="font-family: monospace;">
 
2297
 
 
2298
 
 
2299
 
 
2300
 
 
2301
 
 
2302
<br style="font-family: monospace;">
 
2303
 
 
2304
 
 
2305
 
 
2306
 
 
2307
 
 
2308
<span style="font-family: monospace;">puts v</span><br style="font-family: monospace;">
 
2309
 
 
2310
 
 
2311
 
 
2312
 
 
2313
 
 
2314
<span style="font-weight: bold; font-family: monospace;">=&gt;
 
2315
[1, [1,2], 'hello',&nbsp;#&lt;A:0x245325&gt;]</span></div>
 
2316
 
 
2317
 
 
2318
 
 
2319
 
 
2320
 
 
2321
<br>
 
2322
 
 
2323
 
 
2324
 
 
2325
 
 
2326
 
 
2327
<p>Obviously, there is a lot more to template wrapping than
 
2328
shown in these examples. More details can be found in the <a href="SWIGPlus.html#SWIGPlus">SWIG and C++</a>
 
2329
chapter.</p>
 
2330
 
 
2331
 
 
2332
 
 
2333
 
 
2334
 
 
2335
<H3><a name="C_STL_Functors"></a>30.3.14 C++ STL Functors</H3>
 
2336
 
 
2337
 
 
2338
<p>Some containers in the STL allow you to modify their default
 
2339
behavior by using so called functors or function objects.
 
2340
&nbsp;Functors are often just a very simple struct with<span style="font-family: monospace;"> operator()</span>
 
2341
redefined or an actual C/C++ function. &nbsp;This allows you, for
 
2342
example, to always keep the sort order of a STL container to your
 
2343
liking.</p>
 
2344
 
 
2345
 
 
2346
 
 
2347
 
 
2348
 
 
2349
<p>The Ruby STL mappings allows you to modify those containers
 
2350
that
 
2351
support functors using Ruby procs or methods, instead.
 
2352
&nbsp;Currently,
 
2353
this includes <span style="font-family: monospace;">std::set</span>,
 
2354
<span style="font-family: monospace;">set::map</span>,
 
2355
<span style="font-family: monospace;">std::multiset</span>
 
2356
and <span style="font-family: monospace;">std::multimap</span>.</p>
 
2357
 
 
2358
 
 
2359
 
 
2360
 
 
2361
 
 
2362
<p>The functors in swig are called<span style="font-family: monospace;"> swig::UnaryFunction</span>
 
2363
and <span style="font-family: monospace;">swig::BinaryFunction</span>.<br>
 
2364
 
 
2365
 
 
2366
 
 
2367
 
 
2368
 
 
2369
For C++ predicates (ie. functors that must return bool as a result) <span style="font-family: monospace;">swig::UnaryPredicate</span>
 
2370
and <span style="font-family: monospace;">swig::BinaryPredicate</span>
 
2371
are provided.</p>
 
2372
 
 
2373
 
 
2374
 
 
2375
 
 
2376
 
 
2377
<p>As an example, if given this swig file:</p>
 
2378
 
 
2379
 
 
2380
 
 
2381
 
 
2382
 
 
2383
<div style="font-family: monospace;" class="code">%module
 
2384
intset;<br>
 
2385
 
 
2386
 
 
2387
 
 
2388
 
 
2389
 
 
2390
<br>
 
2391
 
 
2392
 
 
2393
 
 
2394
 
 
2395
 
 
2396
%include std_set.i<br>
 
2397
 
 
2398
 
 
2399
 
 
2400
 
 
2401
 
 
2402
<br>
 
2403
 
 
2404
 
 
2405
 
 
2406
 
 
2407
 
 
2408
%typemap(IntSet)&nbsp; std::set&lt; int, swig::BinaryPredicate
 
2409
&gt;;</div>
 
2410
 
 
2411
 
 
2412
 
 
2413
 
 
2414
 
 
2415
<p>You can then use the set from Ruby with or without a proc
 
2416
object as a predicate:</p>
 
2417
 
 
2418
 
 
2419
 
 
2420
 
 
2421
 
 
2422
<div style="font-family: monospace;" class="targetlang">require
 
2423
'intset'<br>
 
2424
 
 
2425
 
 
2426
 
 
2427
 
 
2428
 
 
2429
include Intset<br>
 
2430
 
 
2431
 
 
2432
 
 
2433
 
 
2434
 
 
2435
<br>
 
2436
 
 
2437
 
 
2438
 
 
2439
 
 
2440
 
 
2441
# Default sorting behavior defined in C++<br>
 
2442
 
 
2443
 
 
2444
 
 
2445
 
 
2446
 
 
2447
a = IntSet.new<br>
 
2448
 
 
2449
 
 
2450
 
 
2451
 
 
2452
 
 
2453
a &lt;&lt; 1<br>
 
2454
 
 
2455
 
 
2456
 
 
2457
 
 
2458
 
 
2459
a &lt;&lt; 2<br>
 
2460
 
 
2461
 
 
2462
 
 
2463
 
 
2464
 
 
2465
a &lt;&lt; 3<br>
 
2466
 
 
2467
 
 
2468
 
 
2469
 
 
2470
 
 
2471
a<br>
 
2472
 
 
2473
 
 
2474
 
 
2475
 
 
2476
 
 
2477
<span style="font-weight: bold;">=&gt;
 
2478
&nbsp;[1,2,3]</span><br>
 
2479
 
 
2480
 
 
2481
 
 
2482
 
 
2483
 
 
2484
<br>
 
2485
 
 
2486
 
 
2487
 
 
2488
 
 
2489
 
 
2490
# Custom sorting behavior defined by a Ruby proc
 
2491
<div><span class="targetlang">b = IntSet.new( proc {
 
2492
|a,b| a &gt; b } )</span><br>
 
2493
 
 
2494
 
 
2495
 
 
2496
 
 
2497
 
 
2498
b&nbsp;&lt;&lt; 1<br>
 
2499
 
 
2500
 
 
2501
 
 
2502
 
 
2503
 
 
2504
b&nbsp;&lt;&lt; 2<br>
 
2505
 
 
2506
 
 
2507
 
 
2508
 
 
2509
 
 
2510
b&nbsp;&lt;&lt; 3<br>
 
2511
 
 
2512
 
 
2513
 
 
2514
 
 
2515
 
 
2516
b<br style="font-weight: bold;">
 
2517
 
 
2518
 
 
2519
 
 
2520
 
 
2521
 
 
2522
<span style="font-weight: bold;">=&gt;
 
2523
&nbsp;[3,2,1]</span> </div>
 
2524
 
 
2525
 
 
2526
 
 
2527
 
 
2528
 
 
2529
</div>
 
2530
 
 
2531
 
 
2532
 
 
2533
 
 
2534
 
 
2535
<H3><a name="Ruby_C_Iterators"></a>30.3.15 C++ STL Iterators</H3>
 
2536
 
 
2537
 
 
2538
<p>The STL is well known for the use of iterators. &nbsp;There
 
2539
are a number of iterators possible with different properties, but in
 
2540
general there are two main categories: const iterators and non-const
 
2541
iterators. &nbsp;The const iterators can access and not modify the
 
2542
values they point at, while the non-const iterators can both read and
 
2543
modify the values.</p>
 
2544
 
 
2545
 
 
2546
 
 
2547
 
 
2548
 
 
2549
<p>The Ruby STL wrappings support both type of iterators by using
 
2550
a proxy class in-between. &nbsp;This proxy class is <span style="font-family: monospace;">swig::Iterator or
 
2551
swig::ConstIterator. &nbsp;</span>Derived from them are template
 
2552
classes that need to be initialized with the actual iterator for the
 
2553
container you are wrapping and often times with the beginning and
 
2554
ending points of the iteration range.&nbsp;</p>
 
2555
 
 
2556
 
 
2557
 
 
2558
 
 
2559
 
 
2560
<p>The SWIG STL library already provides typemaps to all the
 
2561
standard containers to do this wrapping automatically for you, but if
 
2562
you have your own STL-like iterator, you will need to write your own
 
2563
typemap for them.&nbsp;&nbsp;For out typemaps, the special functions <span style="font-family: monospace;">make_const_iterator</span> and <span style="font-family: monospace;">make_nonconst_iterator</span> are provided.</p>
 
2564
 
 
2565
<p>These can be used either like:</p>
 
2566
 
 
2567
<div style="font-family: monospace;" class="code">make_const_iterator( iterator, rubyclass );<br>
 
2568
 
 
2569
make_const_iterator( iterator, iterator_begin, iterator_end, rubyclass );</div>
 
2570
 
 
2571
 
 
2572
 
 
2573
 
 
2574
 
 
2575
<p>The iterators support a <span style="font-family: monospace;">next()</span> and <span style="font-family: monospace;">previous()&nbsp;</span>member function to
 
2576
just change the iterator without returning anything. &nbsp;<span style="font-family: monospace;">previous()</span>
 
2577
should obviously only be used for bidirectional iterators. &nbsp;You
 
2578
can also advance the iterator multiple steps by using standard math
 
2579
operations like <span style="font-family: monospace;">+=</span>.</p>
 
2580
 
 
2581
<p>The
 
2582
value&nbsp;the iterator points at can be accessed with <span style="font-family: monospace;">value()</span> -- this is equivalent to dereferencing it with <span style="font-family: monospace;">*i</span>.
 
2583
&nbsp; For non-const iterators, a <span style="font-family: monospace;">value=()</span> function
 
2584
is also provided which allows you to change the value pointed by the
 
2585
iterator. &nbsp;This is equivalent to the C++ construct of dereferencing and assignment, like <span style="font-family: monospace;">*i = something</span>.&nbsp;</p>
 
2586
 
 
2587
 
 
2588
 
 
2589
 
 
2590
 
 
2591
<p>Thus, given say a vector class of doubles defined as:</p>
 
2592
 
 
2593
 
 
2594
 
 
2595
 
 
2596
 
 
2597
<div style="font-family: monospace;" class="code"><span class="code">%module doublevector</span><br class="code">
 
2598
 
 
2599
 
 
2600
 
 
2601
 
 
2602
 
 
2603
<span class="code"><br>
 
2604
 
 
2605
 
 
2606
 
 
2607
 
 
2608
 
 
2609
%include std_vector.i</span><br class="code">
 
2610
 
 
2611
 
 
2612
 
 
2613
 
 
2614
 
 
2615
<span class="code"><br>
 
2616
 
 
2617
 
 
2618
 
 
2619
 
 
2620
 
 
2621
%template(DoubleVector) std::vector&lt;double&gt;;</span></div>
 
2622
 
 
2623
 
 
2624
 
 
2625
 
 
2626
 
 
2627
<p>Its iterator can then be used from Ruby like:</p>
 
2628
 
 
2629
 
 
2630
 
 
2631
 
 
2632
 
 
2633
<div style="font-family: monospace;" class="targetlang">require
 
2634
'doublevector'<br>
 
2635
 
 
2636
 
 
2637
 
 
2638
 
 
2639
 
 
2640
include Doublevector<br>
 
2641
 
 
2642
<br>
 
2643
 
 
2644
 
 
2645
 
 
2646
 
 
2647
 
 
2648
v = DoubleVector.new<br>
 
2649
 
 
2650
 
 
2651
 
 
2652
 
 
2653
 
 
2654
v &lt;&lt; 1<br>
 
2655
 
 
2656
 
 
2657
 
 
2658
 
 
2659
 
 
2660
v &lt;&lt; 2<br>
 
2661
 
 
2662
 
 
2663
 
 
2664
 
 
2665
 
 
2666
v &lt;&lt; 3<br>
 
2667
 
 
2668
<br>
 
2669
 
 
2670
#<br>
 
2671
 
 
2672
# an elaborate and less efficient way of doing v.map! { |x| x+2 }<br>
 
2673
 
 
2674
#<br>
 
2675
 
 
2676
 
 
2677
 
 
2678
 
 
2679
 
 
2680
i = v.begin<br>
 
2681
 
 
2682
 
 
2683
 
 
2684
 
 
2685
 
 
2686
e = v.end<br>
 
2687
 
 
2688
 
 
2689
 
 
2690
 
 
2691
 
 
2692
while i != e<br>
 
2693
 
 
2694
 
 
2695
 
 
2696
 
 
2697
 
 
2698
&nbsp; val = i.value<br>
 
2699
 
 
2700
 
 
2701
 
 
2702
 
 
2703
 
 
2704
&nbsp; val += 2<br>
 
2705
 
 
2706
 
 
2707
 
 
2708
 
 
2709
 
 
2710
&nbsp; i.value = val<br>
 
2711
 
 
2712
 
 
2713
 
 
2714
 
 
2715
 
 
2716
&nbsp; i.next<br>
 
2717
 
 
2718
 
 
2719
 
 
2720
 
 
2721
 
 
2722
end<br>
 
2723
 
 
2724
 
 
2725
 
 
2726
 
 
2727
i<br>
 
2728
 
 
2729
 
 
2730
 
 
2731
 
 
2732
<span style="font-weight: bold;">&gt;&gt; [3, 4, 5 ]</span></div>
 
2733
 
 
2734
 
 
2735
 
 
2736
 
 
2737
 
 
2738
<br>
 
2739
 
 
2740
<p>If you'd rather have STL classes without any iterators, you should define<span style="font-family: monospace;"> -DSWIG_NO_EXPORT_ITERATOR_METHODS </span>when running swig.</p>
 
2741
 
 
2742
 
 
2743
 
 
2744
 
 
2745
 
 
2746
<H3><a name="Ruby_nn24"></a>30.3.16 C++ Smart Pointers</H3>
 
2747
 
 
2748
 
 
2749
<p> In certain C++ programs, it is common to use classes that
 
2750
have been wrapped by so-called "smart pointers." Generally, this
 
2751
involves the use of a template class that implements <tt>operator-&gt;()</tt>
 
2752
like this: </p>
 
2753
 
 
2754
 
 
2755
 
 
2756
 
 
2757
 
 
2758
<div class="code">
 
2759
<pre>template&lt;class T&gt; class SmartPtr {<br> ...<br> T *operator-&gt;();<br> ...<br>}<br></pre>
 
2760
 
 
2761
 
 
2762
 
 
2763
 
 
2764
 
 
2765
</div>
 
2766
 
 
2767
 
 
2768
 
 
2769
 
 
2770
 
 
2771
<p>Then, if you have a class like this,</p>
 
2772
 
 
2773
 
 
2774
 
 
2775
 
 
2776
 
 
2777
<div class="code">
 
2778
<pre>class Foo {<br>public:<br> int x;<br> int bar();<br>};<br></pre>
 
2779
 
 
2780
 
 
2781
 
 
2782
 
 
2783
 
 
2784
</div>
 
2785
 
 
2786
 
 
2787
 
 
2788
 
 
2789
 
 
2790
<p>A smart pointer would be used in C++ as follows:</p>
 
2791
 
 
2792
 
 
2793
 
 
2794
 
 
2795
 
 
2796
<div class="code">
 
2797
<pre>SmartPtr&lt;Foo&gt; p = CreateFoo(); // Created somehow (not shown)<br>...<br>p-&gt;x = 3; // Foo::x<br>int y = p-&gt;bar(); // Foo::bar<br></pre>
 
2798
 
 
2799
 
 
2800
 
 
2801
 
 
2802
 
 
2803
</div>
 
2804
 
 
2805
 
 
2806
 
 
2807
 
 
2808
 
 
2809
<p> To wrap this in Ruby, simply tell SWIG about the <tt>SmartPtr</tt>
 
2810
class and the low-level <tt>Foo</tt> object. Make sure you
 
2811
instantiate <tt>SmartPtr</tt> using <tt>%template</tt>
 
2812
if necessary. For example: </p>
 
2813
 
 
2814
 
 
2815
 
 
2816
 
 
2817
 
 
2818
<div class="code">
 
2819
<pre>%module example<br>...<br>%template(SmartPtrFoo) SmartPtr&lt;Foo&gt;;<br>...<br></pre>
 
2820
 
 
2821
 
 
2822
 
 
2823
 
 
2824
 
 
2825
</div>
 
2826
 
 
2827
 
 
2828
 
 
2829
 
 
2830
 
 
2831
<p>Now, in Ruby, everything should just "work":</p>
 
2832
 
 
2833
 
 
2834
 
 
2835
 
 
2836
 
 
2837
<div class="code targetlang">
 
2838
<pre>irb(main):001:0&gt; <b>p = Example::CreateFoo()</b> # Create a smart-pointer somehow<br>#&lt;Example::SmartPtrFoo:0x4016f4df&gt;<br>irb(main):002:0&gt; <b>p.x = 3</b> # Foo::x<br>3<br>irb(main):003:0&gt; <b>p.bar()</b> # Foo::bar<br></pre>
 
2839
 
 
2840
 
 
2841
 
 
2842
 
 
2843
 
 
2844
</div>
 
2845
 
 
2846
 
 
2847
 
 
2848
 
 
2849
 
 
2850
<p> If you ever need to access the underlying pointer returned by
 
2851
<tt>operator-&gt;()</tt> itself, simply use the <tt>__deref__()</tt>
 
2852
method. For example: </p>
 
2853
 
 
2854
 
 
2855
 
 
2856
 
 
2857
 
 
2858
<div class="code targetlang">
 
2859
<pre>irb(main):004:0&gt; <b>f = p.__deref__()</b> # Returns underlying Foo *<br></pre>
 
2860
 
 
2861
 
 
2862
 
 
2863
 
 
2864
 
 
2865
</div>
 
2866
 
 
2867
 
 
2868
 
 
2869
 
 
2870
 
 
2871
<H3><a name="Ruby_nn25"></a>30.3.17 Cross-Language Polymorphism</H3>
 
2872
 
 
2873
 
 
2874
<p> SWIG's Ruby module supports cross-language polymorphism
 
2875
(a.k.a. the "directors" feature) similar to that for SWIG's Python
 
2876
module. Rather than duplicate the information presented in the <a href="Ruby">Python</a> chapter, this
 
2877
section just notes the differences that you need to be aware of when
 
2878
using this feature with Ruby. </p>
 
2879
 
 
2880
 
 
2881
 
 
2882
 
 
2883
 
 
2884
<H4><a name="Ruby_nn26"></a>30.3.17.1 Exception Unrolling</H4>
 
2885
 
 
2886
 
 
2887
<p> Whenever a C++ director class routes one of its virtual
 
2888
member function calls to a Ruby instance method, there's always the
 
2889
possibility that an exception will be raised in the Ruby code. By
 
2890
default, those exceptions are ignored, which simply means that the
 
2891
exception will be exposed to the Ruby interpreter. If you would like to
 
2892
change this behavior, you can use the <tt>%feature("director:except")</tt>
 
2893
directive to indicate what action should be taken when a Ruby exception
 
2894
is raised. The following code should suffice in most cases: </p>
 
2895
 
 
2896
 
 
2897
 
 
2898
 
 
2899
 
 
2900
<div class="code">
 
2901
<pre>%feature("director:except") {<br> throw Swig::DirectorMethodException($error);<br>}<br></pre>
 
2902
 
 
2903
 
 
2904
 
 
2905
 
 
2906
 
 
2907
</div>
 
2908
 
 
2909
 
 
2910
 
 
2911
 
 
2912
 
 
2913
<p> When this feature is activated, the call to the Ruby instance
 
2914
method is "wrapped" using the <tt>rb_rescue2()</tt>
 
2915
function from Ruby's C API. If any Ruby exception is raised, it will be
 
2916
caught here and a C++ exception is raised in its place. </p>
 
2917
 
 
2918
 
 
2919
 
 
2920
 
 
2921
 
962
2922
<H2><a name="Ruby_nn27"></a>30.4 Naming</H2>
963
2923
 
964
2924
 
965
 
                <p>Ruby has several common naming conventions. Constants are generally in  upper case, module and class names are  in camel case and methods are in lower case with underscores. For example: </p>
966
 
                <div class="code">
967
 
                <ul>
968
 
                <li><strong>MATH::PI</strong> is a constant name</li>
969
 
            <li><strong>MyClass</strong> is a class name</li>
970
 
        <li><strong>my_method</strong> is a method name</li>
971
 
            </ul>
972
 
                </div>
973
 
        <p>Prior to version 1.3.28, SWIG did not support these Ruby conventions. The only modifications it made to names was to capitalize the first letter of constants (which includes module and class names).</p>
974
 
        <p>SWIG 1.3.28 introduces the new -autorename command line parameter. When this parameter is specified, SWIG will automatically change constant, class and method names to conform with the standard Ruby naming conventions. For example: </p>
975
 
                                        <div class="code">
976
 
                        <pre>$ <b>swig -ruby -autorename example.i</b>
 
2925
<p>Ruby has several common naming conventions. Constants are
 
2926
generally
 
2927
in upper case, module and class names are in camel case and methods are
 
2928
in lower case with underscores. For example: </p>
 
2929
 
 
2930
 
 
2931
 
 
2932
 
 
2933
 
 
2934
<div class="code">
 
2935
<ul>
 
2936
 
 
2937
 
 
2938
 
 
2939
 
 
2940
 
 
2941
  <li><strong>MATH::PI</strong> is a constant name</li>
 
2942
 
 
2943
 
 
2944
 
 
2945
 
 
2946
 
 
2947
  <li><strong>MyClass</strong> is a class name</li>
 
2948
 
 
2949
 
 
2950
 
 
2951
 
 
2952
 
 
2953
  <li><strong>my_method</strong> is a method name</li>
 
2954
 
 
2955
 
 
2956
 
 
2957
 
 
2958
 
 
2959
</ul>
 
2960
 
 
2961
 
 
2962
 
 
2963
 
 
2964
 
 
2965
</div>
 
2966
 
 
2967
 
 
2968
 
 
2969
 
 
2970
 
 
2971
<p>Prior to version 1.3.28, SWIG did not support these Ruby
 
2972
conventions. The only modifications it made to names was to capitalize
 
2973
the first letter of constants (which includes module and class names).</p>
 
2974
 
 
2975
 
 
2976
 
 
2977
 
 
2978
 
 
2979
<p>SWIG 1.3.28 introduces the new -autorename command line
 
2980
parameter.
 
2981
When this parameter is specified, SWIG will automatically change
 
2982
constant, class and method names to conform with the standard Ruby
 
2983
naming conventions. For example: </p>
 
2984
 
 
2985
 
 
2986
 
 
2987
 
 
2988
 
 
2989
<div class="code shell">
 
2990
<pre>$ <b>swig -ruby -autorename example.i</b>
977
2991
</pre>
978
 
                </div>
 
2992
 
 
2993
 
 
2994
 
 
2995
 
 
2996
 
 
2997
</div>
 
2998
 
 
2999
 
 
3000
 
 
3001
 
979
3002
 
980
3003
<p>To disable renaming use the -noautorename command line option.</p>
981
 
<p>Since this change significantly changes the wrapper code generated by SWIG, it is turned off by default in SWIG 1.3.28. However, it is planned to become the default option in future releases.</p>
 
3004
 
 
3005
 
 
3006
 
 
3007
 
 
3008
 
 
3009
<p>Since this change significantly changes the wrapper code
 
3010
generated
 
3011
by SWIG, it is turned off by default in SWIG 1.3.28. However, it is
 
3012
planned to become the default option in future releases.</p>
 
3013
 
 
3014
 
 
3015
 
 
3016
 
 
3017
 
982
3018
<H3><a name="Ruby_nn28"></a>30.4.1 Defining Aliases</H3>
983
3019
 
984
3020
 
985
 
<p> It's a fairly common practice in the Ruby built-ins and standard library to 
986
 
                  provide aliases for method names. For example, <em>Array#size</em> is an alias 
987
 
                  for <em>Array#length</em>. If you would like to provide an alias for one of your 
988
 
                  class' instance methods, one approach is to use SWIG's <tt>%extend</tt> directive 
989
 
                  to add a new method of the aliased name that calls the original function. For 
990
 
                  example: </p>
991
 
                <div class="code">
992
 
          <pre>class MyArray {<br>public:<br> // Construct an empty array<br> MyArray();<br> <br> // Return the size of this array<br> size_t length() const;<br>};<br><br>%extend MyArray {<br> // MyArray#size is an alias for MyArray#length<br> size_t size() const {<br> return $self-&gt;length();<br> }<br>}
993
 
        </pre>
994
 
  </div>
995
 
                <p> A better solution is to  use the <tt>%alias</tt> directive (unique to 
996
 
                  SWIG's Ruby module). The previous example could then be rewritten as: </p>
997
 
                <div class="code">
998
 
          <pre>// MyArray#size is an alias for MyArray#length<br>%alias MyArray::length "size";<br><br>class MyArray {<br>public:<br> // Construct an empty array<br> MyArray();<br> <br> // Return the size of this array<br> size_t length() const;<br>};<br>
999
 
        </pre>
1000
 
  </div>
1001
 
                <p> Multiple aliases can be associated with a method by providing a comma-separated 
1002
 
                  list of aliases to the <tt>%alias</tt> directive, e.g. </p>
1003
 
                <div class="code">
1004
 
          <pre>%alias MyArray::length "amount,quantity,size";</pre>
1005
 
  </div>
1006
 
                <p> From an end-user's standpoint, there's no functional difference between these 
1007
 
                  two approaches; i.e. they should get the same result from calling either <em>MyArray#size</em> or <em>MyArray#length</em>. However, when the <tt>%alias</tt> directive is 
1008
 
                  used, SWIG doesn't need to generate all of the wrapper code that's usually 
1009
 
                  associated with added methods like our <em>MyArray::size()</em> example. </p>
1010
 
                <p>Note that the <tt>%alias</tt> directive is implemented using SWIG's "features" 
1011
 
                  mechanism and so the same name matching rules used for other kinds of features 
1012
 
                  apply (see the chapter on <a href="Customization.html#Customization">"Customization 
1013
 
                    Features"</a>) for more details).</p>
 
3021
<p> It's a fairly common practice in the Ruby built-ins and
 
3022
standard library to provide aliases for method names. For example, <em>Array#size</em>
 
3023
is an alias for <em>Array#length</em>. If you would like
 
3024
to provide an alias for one of your class' instance methods, one
 
3025
approach is to use SWIG's <tt>%extend</tt> directive to
 
3026
add a new method of the aliased name that calls the original function.
 
3027
For example: </p>
 
3028
 
 
3029
 
 
3030
 
 
3031
 
 
3032
 
 
3033
<div class="code">
 
3034
<pre>class MyArray {<br>public:<br> // Construct an empty array<br> MyArray();<br> <br> // Return the size of this array<br> size_t length() const;<br>};<br><br>%extend MyArray {<br> // MyArray#size is an alias for MyArray#length<br> size_t size() const {<br> return $self-&gt;length();<br> }<br>}<br> </pre>
 
3035
 
 
3036
 
 
3037
 
 
3038
 
 
3039
 
 
3040
</div>
 
3041
 
 
3042
 
 
3043
 
 
3044
 
 
3045
 
 
3046
<p> A better solution is to use the <tt>%alias</tt>
 
3047
directive (unique to SWIG's Ruby module). The previous example could
 
3048
then be rewritten as: </p>
 
3049
 
 
3050
 
 
3051
 
 
3052
 
 
3053
 
 
3054
<div class="code">
 
3055
<pre>// MyArray#size is an alias for MyArray#length<br>%alias MyArray::length "size";<br><br>class MyArray {<br>public:<br> // Construct an empty array<br> MyArray();<br> <br> // Return the size of this array<br> size_t length() const;<br>};<br><br></pre>
 
3056
 
 
3057
 
 
3058
 
 
3059
 
 
3060
 
 
3061
</div>
 
3062
 
 
3063
 
 
3064
 
 
3065
 
 
3066
 
 
3067
<p> Multiple aliases can be associated with a method by providing
 
3068
a comma-separated list of aliases to the <tt>%alias</tt>
 
3069
directive, e.g. </p>
 
3070
 
 
3071
 
 
3072
 
 
3073
 
 
3074
 
 
3075
<div class="code">
 
3076
<pre>%alias MyArray::length "amount,quantity,size";</pre>
 
3077
 
 
3078
 
 
3079
 
 
3080
 
 
3081
 
 
3082
</div>
 
3083
 
 
3084
 
 
3085
 
 
3086
 
 
3087
 
 
3088
<p> From an end-user's standpoint, there's no functional
 
3089
difference between these two approaches; i.e. they should get the same
 
3090
result from calling either <em>MyArray#size</em> or <em>MyArray#length</em>.
 
3091
However, when the <tt>%alias</tt> directive is used, SWIG
 
3092
doesn't need to generate all of the wrapper code that's usually
 
3093
associated with added methods like our <em>MyArray::size()</em>
 
3094
example. </p>
 
3095
 
 
3096
 
 
3097
 
 
3098
 
 
3099
 
 
3100
<p>Note that the <tt>%alias</tt> directive is
 
3101
implemented using SWIG's "features" mechanism and so the same name
 
3102
matching rules used for other kinds of features apply (see the chapter
 
3103
on <a href="Customization.html#Customization">"Customization
 
3104
Features"</a>) for more details).</p>
 
3105
 
 
3106
 
 
3107
 
 
3108
 
 
3109
 
1014
3110
<H3><a name="Ruby_nn29"></a>30.4.2 Predicate Methods</H3>
1015
3111
 
1016
3112
 
1017
 
                <p> Ruby methods that return a boolean value and end in a question mark are known as predicate methods. Examples of predicate methods in standard Ruby classes include <em>Array#empty?</em> (which returns <tt>true</tt> for an array containing no elements) and <em>Object#instance_of?</em> (which 
1018
 
                  returns <tt>true</tt> if the object is an instance of the specified class). For 
1019
 
                  consistency with Ruby conventions, methods that return boolean values  should be marked as predicate methods.</p>
1020
 
                <p>One cumbersome solution to this problem is to rename the method (using SWIG's <tt>%rename</tt> directive) and provide a custom typemap that converts the function's actual 
1021
 
                  return type to Ruby's <tt>true</tt> or <tt>false</tt>. For example: </p>
1022
 
                <div class="code">
1023
 
          <pre>%rename("is_it_safe?") is_it_safe();<br><br>%typemap(out) int is_it_safe <br> "$result = ($1 != 0) ? Qtrue : Qfalse;";<br><br>int is_it_safe();<br>
1024
 
        </pre>
1025
 
  </div>
1026
 
                <p> A better solution is to  use the <tt>%predicate</tt> directive (unique 
1027
 
                  to SWIG's Ruby module) to designate a method as a predicate method. For 
1028
 
                  the previous example, this would look like: </p>
1029
 
                <div class="code">
1030
 
          <pre>%predicate is_it_safe();<br><br>int is_it_safe();<br>
1031
 
        </pre>
1032
 
  </div>
1033
 
                <p>This method would be invoked from Ruby code like this:</p>
1034
 
                <div class="code">
1035
 
          <pre>irb(main):001:0&gt; <b>Example::is_it_safe?</b><br>true<br>
1036
 
        </pre>
1037
 
  </div>
1038
 
                <p> The <tt>%predicate</tt> directive is implemented using SWIG's 
1039
 
                  "features" mechanism and so the same name matching rules used for other kinds 
1040
 
                  of features apply (see the chapter on <a href="Customization.html#Customization">"Customization 
1041
 
                    Features"</a>) for more details). </p>
 
3113
<p> Ruby methods that return a boolean value and end in a
 
3114
question mark
 
3115
are known as predicate methods. Examples of predicate methods in
 
3116
standard Ruby classes include <em>Array#empty?</em> (which
 
3117
returns <tt>true</tt> for an array containing no elements)
 
3118
and <em>Object#instance_of?</em> (which returns <tt>true</tt>
 
3119
if the object is an instance of the specified class). For consistency
 
3120
with Ruby conventions, methods that return boolean values should be
 
3121
marked as predicate methods.</p>
 
3122
 
 
3123
 
 
3124
 
 
3125
 
 
3126
 
 
3127
<p>One cumbersome solution to this problem is to rename the
 
3128
method (using SWIG's <tt>%rename</tt> directive) and
 
3129
provide a custom typemap that converts the function's actual return
 
3130
type to Ruby's <tt>true</tt> or <tt>false</tt>.
 
3131
For example: </p>
 
3132
 
 
3133
 
 
3134
 
 
3135
 
 
3136
 
 
3137
<div class="code">
 
3138
<pre>%rename("is_it_safe?") is_it_safe();<br><br>%typemap(out) int is_it_safe <br> "$result = ($1 != 0) ? Qtrue : Qfalse;";<br><br>int is_it_safe();<br><br></pre>
 
3139
 
 
3140
 
 
3141
 
 
3142
 
 
3143
 
 
3144
</div>
 
3145
 
 
3146
 
 
3147
 
 
3148
 
 
3149
 
 
3150
<p> A better solution is to use the <tt>%predicate</tt>
 
3151
directive (unique to SWIG's Ruby module) to designate a method as a
 
3152
predicate method. For the previous example, this would look like: </p>
 
3153
 
 
3154
 
 
3155
 
 
3156
 
 
3157
 
 
3158
<div class="code">
 
3159
<pre>%predicate is_it_safe();<br><br>int is_it_safe();<br><br></pre>
 
3160
 
 
3161
 
 
3162
 
 
3163
 
 
3164
 
 
3165
</div>
 
3166
 
 
3167
 
 
3168
 
 
3169
 
 
3170
 
 
3171
<p>This method would be invoked from Ruby code like this:</p>
 
3172
 
 
3173
 
 
3174
 
 
3175
 
 
3176
 
 
3177
<div class="code targetlang">
 
3178
<pre>irb(main):001:0&gt; <b>Example::is_it_safe?</b><br>true<br><br></pre>
 
3179
 
 
3180
 
 
3181
 
 
3182
 
 
3183
 
 
3184
</div>
 
3185
 
 
3186
 
 
3187
 
 
3188
 
 
3189
 
 
3190
<p> The <tt>%predicate</tt> directive is implemented
 
3191
using SWIG's "features" mechanism and so the same name matching rules
 
3192
used for other kinds of features apply (see the chapter on <a href="Customization.html#Customization">"Customization
 
3193
Features"</a>) for more details). </p>
 
3194
 
 
3195
 
 
3196
 
 
3197
 
 
3198
 
1042
3199
<H3><a name="Ruby_nn30"></a>30.4.3 Bang Methods</H3>
1043
3200
 
1044
3201
 
1045
 
        <p> Ruby methods that modify an object in-place and end in an exclamation mark are known as bang methods. An example of a bang method is  <em>Array#sort!</em> which changes the ordering of items in an array. Contrast this with  <em>Array#sort</em>, which returns a copy of the array with the items sorted instead of modifying the original array. For 
1046
 
        consistency with Ruby conventions, methods that modify objects in place should be marked as bang methods.</p>
1047
 
        <p>Bang methods can be marked using the <tt>%bang</tt> directive which is unique 
1048
 
        to the Ruby module and was introduced in SWIG 1.3.28. For example:</p>
1049
 
        <div class="code">
1050
 
          <pre>%bang sort!(arr);<br><br>int sort(int arr[]);        </pre>
1051
 
        </div>
1052
 
        <p>This method would be invoked from Ruby code like this:</p>
1053
 
        <div class="code">
1054
 
          <pre>irb(main):001:0&gt; <b>Example::sort!(arr)</b></pre>
1055
 
        </div>
1056
 
        <p> The <tt>%bang</tt> directive is implemented using SWIG's 
1057
 
          "features" mechanism and so the same name matching rules used for other kinds 
1058
 
          of features apply (see the chapter on <a href="Customization.html#Customization">"Customization 
1059
 
            Features"</a>) for more details). </p>
 
3202
<p> Ruby methods that modify an object in-place and end in an
 
3203
exclamation mark are known as bang methods. An example of a bang method
 
3204
is <em>Array#sort!</em> which changes the ordering of
 
3205
items in an array. Contrast this with <em>Array#sort</em>,
 
3206
which returns a copy of the array with the items sorted instead of
 
3207
modifying the original array. For consistency with Ruby conventions,
 
3208
methods that modify objects in place should be marked as bang methods.</p>
 
3209
 
 
3210
 
 
3211
 
 
3212
 
 
3213
 
 
3214
<p>Bang methods can be marked using the <tt>%bang</tt>
 
3215
directive which is unique to the Ruby module and was introduced in SWIG
 
3216
1.3.28. For example:</p>
 
3217
 
 
3218
 
 
3219
 
 
3220
 
 
3221
 
 
3222
<div class="code">
 
3223
<pre>%bang sort!(arr);<br><br>int sort(int arr[]); </pre>
 
3224
 
 
3225
 
 
3226
 
 
3227
 
 
3228
 
 
3229
</div>
 
3230
 
 
3231
 
 
3232
 
 
3233
 
 
3234
 
 
3235
<p>This method would be invoked from Ruby code like this:</p>
 
3236
 
 
3237
 
 
3238
 
 
3239
 
 
3240
 
 
3241
<div class="code">
 
3242
<pre>irb(main):001:0&gt; <b>Example::sort!(arr)</b></pre>
 
3243
 
 
3244
 
 
3245
 
 
3246
 
 
3247
 
 
3248
</div>
 
3249
 
 
3250
 
 
3251
 
 
3252
 
 
3253
 
 
3254
<p> The <tt>%bang</tt> directive is implemented
 
3255
using SWIG's "features" mechanism and so the same name matching rules
 
3256
used for other kinds of features apply (see the chapter on <a href="Customization.html#Customization">"Customization
 
3257
Features"</a>) for more details). </p>
 
3258
 
 
3259
 
 
3260
 
 
3261
 
 
3262
 
1060
3263
<H3><a name="Ruby_nn31"></a>30.4.4 Getters and Setters</H3>
1061
3264
 
1062
3265
 
1063
 
        <p> Often times a C++ library will expose properties through getter and setter methods. For example:</p>
1064
 
        <div class="code">
1065
 
          <pre>class Foo {
1066
 
        Foo() {}
1067
 
 
1068
 
 int getValue() { return value_; }
1069
 
 
1070
 
 void setValue(int value) { value_ = value; }
1071
 
 
1072
 
private:
1073
 
 int value_;
1074
 
};</pre>
1075
 
  </div>
1076
 
        <p>By default, SWIG will expose these methods to Ruby as <tt>get_value</tt> and <tt>set_value.</tt> However, it more natural for these methods to be exposed in Ruby as <tt>value</tt> and <tt>value=. </tt> That allows the methods to be used like this:</p>
1077
 
        <div class="code">
1078
 
          <pre>irb(main):001:0&gt; <b>foo = Foo.new()</b>
1079
 
irb(main):002:0&gt; <b>foo.value = 5</b>
1080
 
irb(main):003:0&gt; <b>puts foo.value</b></pre>
1081
 
  </div>
1082
 
        <p> This can be done by using the %rename directive:</p>
1083
 
        <div class="code">
1084
 
          <pre>%rename(&quot;value&quot;) Foo::getValue();
1085
 
%rename(&quot;value=&quot;) Foo::setValue(int value);
1086
 
</pre>
1087
 
        </div>
1088
 
        <p>&nbsp;</p>
 
3266
<p> Often times a C++ library will expose properties through
 
3267
getter and setter methods. For example:</p>
 
3268
 
 
3269
 
 
3270
 
 
3271
 
 
3272
 
 
3273
<div class="code">
 
3274
<pre>class Foo {<br>    Foo() {}<br><br> int getValue() { return value_; }<br><br> void setValue(int value) { value_ = value; }<br><br>private:<br> int value_;<br>};</pre>
 
3275
 
 
3276
 
 
3277
 
 
3278
 
 
3279
 
 
3280
</div>
 
3281
 
 
3282
 
 
3283
 
 
3284
 
 
3285
 
 
3286
<p>By default, SWIG will expose these methods to Ruby as <tt>get_value</tt>
 
3287
and <tt>set_value.</tt> However, it more natural for these
 
3288
methods to be exposed in Ruby as <tt>value</tt> and <tt>value=.
 
3289
</tt> That allows the methods to be used like this:</p>
 
3290
 
 
3291
 
 
3292
 
 
3293
 
 
3294
 
 
3295
<div class="code">
 
3296
<pre>irb(main):001:0&gt; <b>foo = Foo.new()</b><br>irb(main):002:0&gt; <b>foo.value = 5</b><br>irb(main):003:0&gt; <b>puts foo.value</b></pre>
 
3297
 
 
3298
 
 
3299
 
 
3300
 
 
3301
 
 
3302
</div>
 
3303
 
 
3304
 
 
3305
 
 
3306
 
 
3307
 
 
3308
<p> This can be done by using the %rename directive:</p>
 
3309
 
 
3310
 
 
3311
 
 
3312
 
 
3313
 
 
3314
<div class="code">
 
3315
<pre>%rename("value") Foo::getValue();<br>%rename("value=") Foo::setValue(int value);<br></pre>
 
3316
 
 
3317
 
 
3318
 
 
3319
 
 
3320
 
 
3321
</div>
 
3322
 
 
3323
 
 
3324
 
 
3325
 
 
3326
 
 
3327
<p>&nbsp;</p>
 
3328
 
 
3329
 
 
3330
 
 
3331
 
 
3332
 
1089
3333
<H2><a name="Ruby_nn32"></a>30.5 Input and output parameters</H2>
1090
3334
 
1091
3335
 
1092
 
                <p>
1093
 
                        A common problem in some C programs is handling parameters passed as simple 
1094
 
                        pointers. For example:
1095
 
                </p>
1096
 
                <div class="code">
1097
 
                        <pre>void add(int x, int y, int *result) {<br> *result = x + y;<br>}<br>or<br>int sub(int *x, int *y) {<br> return *x-*y;<br>}<br></pre>
1098
 
                </div>
1099
 
                <p>
1100
 
                        The easiest way to handle these situations is to use the <tt>typemaps.i</tt> file. 
1101
 
                        For example:
1102
 
                </p>
1103
 
                <div class="code">
1104
 
                        <pre>%module Example<br>%include "typemaps.i"<br><br>void add(int, int, int *OUTPUT);<br>int sub(int *INPUT, int *INPUT);<br></pre>
1105
 
                </div>
1106
 
                <p>In Ruby, this allows you to pass simple values. For example:</p>
1107
 
                <div class="code">
1108
 
                        <pre>a = Example.add(3,4)<br>puts a<br>7<br>b = Example.sub(7,4)<br>puts b<br>3<br></pre>
1109
 
                </div>
1110
 
                <p>
1111
 
                        Notice how the <tt>INPUT</tt> parameters allow integer values to be passed 
1112
 
                        instead of pointers and how the <tt>OUTPUT</tt> parameter creates a return 
1113
 
                        result.
1114
 
                </p>
1115
 
                <p>If you don't want to use the names <tt>INPUT</tt> or <tt>OUTPUT</tt>, use the <tt>%apply</tt>
1116
 
                        directive. For example:
1117
 
                </p>
1118
 
                <div class="code">
1119
 
                        <pre>%module Example<br>%include "typemaps.i"<br><br>%apply int *OUTPUT { int *result };<br>%apply int *INPUT { int *x, int *y};<br><br>void add(int x, int y, int *result);<br>int sub(int *x, int *y);<br></pre>
1120
 
                </div>
1121
 
                <p>
1122
 
                        If a function mutates one of its parameters like this,
1123
 
                </p>
1124
 
                <div class="code">
1125
 
                        <pre>void negate(int *x) {<br> *x = -(*x);<br>}<br></pre>
1126
 
                </div>
1127
 
                <p>you can use <tt>INOUT</tt> like this:</p>
1128
 
                <div class="code">
1129
 
                        <pre>%include "typemaps.i"<br>...<br>void negate(int *INOUT);<br></pre>
1130
 
                </div>
1131
 
                <p>In Ruby, a mutated parameter shows up as a return value. For example:</p>
1132
 
                <div class="code">
1133
 
                        <pre>a = Example.negate(3)<br>print a<br>-3<br><br></pre>
1134
 
                </div>
1135
 
                <p>
1136
 
                        The most common use of these special typemap rules is to handle functions that 
1137
 
                        return more than one value. For example, sometimes a function returns a result 
1138
 
                        as well as a special error code:
1139
 
                </p>
1140
 
                <div class="code">
1141
 
                        <pre>/* send message, return number of bytes sent, success code, and error_code */<br>int send_message(char *text, int *success, int *error_code);<br></pre>
1142
 
                </div>
1143
 
                <p>
1144
 
                        To wrap such a function, simply use the <tt>OUTPUT</tt> rule above. For 
1145
 
                        example:
1146
 
                </p>
1147
 
                <div class="code">
1148
 
                        <pre>%module example<br>%include "typemaps.i"<br>...<br>int send_message(char *, int *OUTPUT, int *OUTPUT);<br></pre>
1149
 
                </div>
1150
 
                <p>
1151
 
                        When used in Ruby, the function will return an array of multiple values.
1152
 
                </p>
1153
 
                <div class="code">
1154
 
                        <pre>bytes, success, error_code = send_message("Hello World")<br>if not success<br> print "error #{error_code} : in send_message"<br>else<br> print "Sent", bytes<br>end<br></pre>
1155
 
                </div>
1156
 
                <p>
1157
 
                        Another way to access multiple return values is to use the <tt>%apply</tt> rule. 
1158
 
                        In the following example, the parameters rows and columns are related to SWIG 
1159
 
                        as <tt>OUTPUT</tt> values through the use of <tt>%apply</tt>
1160
 
                </p>
1161
 
                <div class="code">
1162
 
                        <pre>%module Example<br>%include "typemaps.i"<br>%apply int *OUTPUT { int *rows, int *columns };<br>...<br>void get_dimensions(Matrix *m, int *rows, int*columns);<br></pre>
1163
 
                </div>
1164
 
                <p>In Ruby:</p>
1165
 
                <div class="code">
1166
 
                        <pre>r, c = Example.get_dimensions(m)<br></pre>
1167
 
                </div>
1168
 
<H2><a name="Ruby_nn33"></a>30.6 Exception handling             </H2>
1169
 
 
1170
 
 
1171
 
<H3><a name="Ruby_nn34"></a>30.6.1 Using the %exception directive               </H3>
1172
 
 
1173
 
 
1174
 
                <p>The SWIG <tt>%exception</tt> directive can be used to define a user-definable 
1175
 
                        exception handler that can convert C/C++ errors into Ruby exceptions. The 
1176
 
                        chapter on <a href="Customization.html#Customization">Customization Features</a>
1177
 
                        contains more details, but suppose you have a C++ class like the following :
1178
 
                </p>
1179
 
                <div class="code">
1180
 
                        <pre>class DoubleArray {<br> private:<br>   int n;<br>   double *ptr;<br> public:<br>   // Create a new array of fixed size<br>   DoubleArray(int size) {<br>     ptr = new double[size];<br>     n = size;<br>   }
1181
 
<br>   // Destroy an array<br>   ~DoubleArray() {<br>     delete ptr;<br>   }  
1182
 
<br>   // Return the length of the array<br>   int length() {<br>     return n;<br>   }<br><br>   // Get an array item and perform bounds checking.<br>   double getitem(int i) {<br>     if ((i &gt;= 0) &amp;&amp; (i &lt; n))<br>       return ptr[i];<br>     else<br>       throw RangeError();<br>   }
1183
 
<br>   // Set an array item and perform bounds checking.<br>   void setitem(int i, double val) {<br>     if ((i &gt;= 0) &amp;&amp; (i &lt; n))<br>       ptr[i] = val;<br>     else {<br>       throw RangeError();<br>     }<br>   }<br> };<br></pre>
1184
 
                </div>
1185
 
                <p>
1186
 
                        Since several methods in this class can throw an exception for an out-of-bounds 
1187
 
                        access, you might want to catch this in the Ruby extension by writing the 
1188
 
                        following in an interface file:
1189
 
                </p>
1190
 
                <div class="code">
1191
 
                        <pre>%exception {<br> try {<br>   $action<br> }<br> catch (const RangeError&amp;) {<br>   static VALUE cpperror = rb_define_class("CPPError", rb_eStandardError);<br>   rb_raise(cpperror, "Range error.");<br> }<br>}<br><br>class DoubleArray {<br> ...<br>};<br></pre>
1192
 
                </div>
1193
 
                <p>
1194
 
                        The exception handling code is inserted directly into generated wrapper 
1195
 
                        functions. When an exception handler is defined, errors can be caught and used 
1196
 
                        to gracefully raise a Ruby exception instead of forcing the entire program to 
1197
 
                        terminate with an uncaught error.
1198
 
                </p>
1199
 
                <p>As shown, the exception handling code will be added to every wrapper function. 
1200
 
                        Because this is somewhat inefficient, you might consider refining the exception 
1201
 
                        handler to only apply to specific methods like this:
1202
 
                </p>
1203
 
                <div class="code">
1204
 
                        <pre>%exception getitem {<br> try {<br>   $action<br> }<br> catch (const RangeError&amp;) {<br>   static VALUE cpperror = rb_define_class("CPPError", rb_eStandardError);<br>   rb_raise(cpperror, "Range error in getitem.");<br> }<br>}<br><br>%exception setitem {<br> try {<br>   $action<br> }<br> catch (const RangeError&amp;) {<br>   static VALUE cpperror = rb_define_class("CPPError", rb_eStandardError);<br>   rb_raise(cpperror, "Range error in setitem.");<br> }<br>}<br></pre>
1205
 
                </div>
1206
 
                <p>
1207
 
                        In this case, the exception handler is only attached to methods and functions 
1208
 
                        named <tt>getitem</tt> and <tt>setitem</tt>.
1209
 
                </p>
1210
 
                <p>Since SWIG's exception handling is user-definable, you are not limited to C++ 
1211
 
                        exception handling. See the chapter on <a href="Customization.html#Customization">Customization 
1212
 
                                Features</a> for more examples.
1213
 
                </p>
1214
 
<H3><a name="Ruby_nn35"></a>30.6.2 Raising exceptions </H3>
1215
 
 
1216
 
 
1217
 
                <p>There are three ways to raise exceptions from C++ code to Ruby. </p>
1218
 
                <p>The first way is to use  <tt>SWIG_exception(int code, const char *msg)</tt>. The following table shows the mappings from SWIG error codes to Ruby exceptions:</p>
1219
 
                <table summary="Mapping between SWIG error codes and Ruby exceptions." width="80%" border="1">
1220
 
      <tr>
1221
 
        <td>SWIG_MemoryError</td>
1222
 
        <td>rb_eNoMemError</td>
1223
 
      </tr>
1224
 
      <tr>
1225
 
        <td>SWIG_IOError</td>
1226
 
        <td>rb_eIOError</td>
1227
 
      </tr>
1228
 
      <tr>
1229
 
        <td>SWIG_RuntimeError</td>
1230
 
        <td>rb_eRuntimeError</td>
1231
 
      </tr>
1232
 
      <tr>
1233
 
        <td>SWIG_IndexError</td>
1234
 
        <td>rb_eIndexError</td>
1235
 
      </tr>
1236
 
      <tr>
1237
 
        <td>SWIG_TypeError</td>
1238
 
        <td>rb_eTypeError</td>
1239
 
      </tr>
1240
 
      <tr>
1241
 
        <td>SWIG_DivisionByZero</td>
1242
 
        <td>rb_eZeroDivError</td>
1243
 
      </tr>
1244
 
      <tr>
1245
 
        <td>SWIG_OverflowError</td>
1246
 
        <td>rb_eRangeError</td>
1247
 
      </tr>
1248
 
      <tr>
1249
 
        <td>SWIG_SyntaxError</td>
1250
 
        <td>rb_eSyntaxError</td>
1251
 
      </tr>
1252
 
      <tr>
1253
 
        <td>SWIG_ValueError</td>
1254
 
        <td>rb_eArgError</td>
1255
 
      </tr>
1256
 
      <tr>
1257
 
        <td>SWIG_SystemError</td>
1258
 
        <td>rb_eFatal</td>
1259
 
      </tr>
1260
 
      <tr>
1261
 
        <td>SWIG_AttributeError</td>
1262
 
        <td>rb_eRuntimeError</td>
1263
 
      </tr>
1264
 
      <tr>
1265
 
        <td>SWIG_NullReferenceError</td>
1266
 
        <td>rb_eNullReferenceError*</td>
1267
 
      </tr>
1268
 
      <tr>
1269
 
        <td>SWIG_ObjectPreviouslyDeletedError</td>
1270
 
        <td>rb_eObjectPreviouslyDeleted*</td>
1271
 
      </tr>
1272
 
      <tr>
1273
 
        <td>SWIG_UnknownError</td>
1274
 
        <td>rb_eRuntimeError</td>
1275
 
      </tr>
1276
 
      <tr>
1277
 
        <td colspan="2">* These error classes are created by SWIG and are not built-in Ruby exception classes </td>
1278
 
      </tr>
1279
 
    </table>
1280
 
        <p>The second way to raise errors is to use   <tt>SWIG_Raise(obj, type, desc)</tt>. Obj is a C++ instance of an exception class, type is a string specifying the type of exception (for example, &quot;MyError&quot;) and desc is the SWIG description of the exception class. For example: </p>
1281
 
                <p> %raise(SWIG_NewPointerObj(e, SWIGTYPE_p_AssertionFailedException, 0), &quot;:AssertionFailedException&quot;, SWIGTYPE_p_AssertionFailedException);</p>
1282
 
                <p>This is useful when you want to pass the current exception object directly to Ruby, particularly when the object is an instance of class marked as an <tt>%exceptionclass</tt> (see the next section for more information).</p>
1283
 
                <p>Last, you can raise an exception by directly calling Ruby's C api. This is done by invoking the  <tt>rb_raise()</tt> function. The first argument passed to <tt>rb_raise()</tt> is the 
1284
 
          exception type. You can raise a custom exception type or one of the built-in Ruby exception types.</p>
1285
 
<H3><a name="Ruby_nn36"></a>30.6.3 Exception classes </H3>
1286
 
 
1287
 
 
1288
 
                <p>Starting with SWIG 1.3.28, the Ruby module  supports the <tt>%exceptionclass</tt> directive, which is used to identify C++ classes that are used  as exceptions. Classes that are marked with the <tt>%exceptionclass</tt> directive are exposed in Ruby as child classes of <tt>rb_eRuntimeError</tt>. This allows C++ exceptions to be directly mapped to Ruby exceptions, providing for a more natural integration between C++ code and Ruby code.</p>
1289
 
                <div class="code">
1290
 
                  <pre> %exceptionclass CustomError;
1291
 
                
1292
 
        %inline %{
1293
 
                class CustomError { };
1294
 
        
1295
 
                class Foo { <br>           public:<br>                  void test() { throw CustomError; }
1296
 
          };
1297
 
        }
1298
 
</pre>
1299
 
                </div>
1300
 
                <p>From Ruby you can now call this method like this:
1301
 
  <div class="code">
1302
 
      <pre>foo = Foo.new
1303
 
begin
1304
 
  foo.test()
1305
 
rescue CustomError => e
1306
 
  puts "Caught custom error"
1307
 
end             </pre>
1308
 
  </div>
1309
 
                <p>For another example look at swig/Examples/ruby/exception_class.<br>
 
3336
<p> A common problem in some C programs is handling parameters
 
3337
passed as simple pointers. For example: </p>
 
3338
 
 
3339
 
 
3340
 
 
3341
 
 
3342
 
 
3343
<div class="code">
 
3344
<pre>void add(int x, int y, int *result) {<br> *result = x + y;<br>}<br>or<br>int sub(int *x, int *y) {<br> return *x-*y;<br>}<br></pre>
 
3345
 
 
3346
 
 
3347
 
 
3348
 
 
3349
 
 
3350
</div>
 
3351
 
 
3352
 
 
3353
 
 
3354
 
 
3355
 
 
3356
<p> The easiest way to handle these situations is to use the <tt>typemaps.i</tt>
 
3357
file. For example: </p>
 
3358
 
 
3359
 
 
3360
 
 
3361
 
 
3362
 
 
3363
<div class="code">
 
3364
<pre>%module Example<br>%include "typemaps.i"<br><br>void add(int, int, int *OUTPUT);<br>int sub(int *INPUT, int *INPUT);<br></pre>
 
3365
 
 
3366
 
 
3367
 
 
3368
 
 
3369
 
 
3370
</div>
 
3371
 
 
3372
 
 
3373
 
 
3374
 
 
3375
 
 
3376
<p>In Ruby, this allows you to pass simple values. For example:</p>
 
3377
 
 
3378
 
 
3379
 
 
3380
 
 
3381
 
 
3382
<div class="code targetlang">
 
3383
<pre>a = Example.add(3,4)<br>puts a<br>7<br>b = Example.sub(7,4)<br>puts b<br>3<br></pre>
 
3384
 
 
3385
 
 
3386
 
 
3387
 
 
3388
 
 
3389
</div>
 
3390
 
 
3391
 
 
3392
 
 
3393
 
 
3394
 
 
3395
<p> Notice how the <tt>INPUT</tt> parameters allow
 
3396
integer values to be passed instead of pointers and how the <tt>OUTPUT</tt>
 
3397
parameter creates a return result. </p>
 
3398
 
 
3399
 
 
3400
 
 
3401
 
 
3402
 
 
3403
<p>If you don't want to use the names <tt>INPUT</tt>
 
3404
or <tt>OUTPUT</tt>, use the <tt>%apply</tt>
 
3405
directive. For example: </p>
 
3406
 
 
3407
 
 
3408
 
 
3409
 
 
3410
 
 
3411
<div class="code">
 
3412
<pre>%module Example<br>%include "typemaps.i"<br><br>%apply int *OUTPUT { int *result };<br>%apply int *INPUT { int *x, int *y};<br><br>void add(int x, int y, int *result);<br>int sub(int *x, int *y);<br></pre>
 
3413
 
 
3414
 
 
3415
 
 
3416
 
 
3417
 
 
3418
</div>
 
3419
 
 
3420
 
 
3421
 
 
3422
 
 
3423
 
 
3424
<p> If a function mutates one of its parameters like this, </p>
 
3425
 
 
3426
 
 
3427
 
 
3428
 
 
3429
 
 
3430
<div class="code">
 
3431
<pre>void negate(int *x) {<br> *x = -(*x);<br>}<br></pre>
 
3432
 
 
3433
 
 
3434
 
 
3435
 
 
3436
 
 
3437
</div>
 
3438
 
 
3439
 
 
3440
 
 
3441
 
 
3442
 
 
3443
<p>you can use <tt>INOUT</tt> like this:</p>
 
3444
 
 
3445
 
 
3446
 
 
3447
 
 
3448
 
 
3449
<div class="code">
 
3450
<pre>%include "typemaps.i"<br>...<br>void negate(int *INOUT);<br></pre>
 
3451
 
 
3452
 
 
3453
 
 
3454
 
 
3455
 
 
3456
</div>
 
3457
 
 
3458
 
 
3459
 
 
3460
 
 
3461
 
 
3462
<p>In Ruby, a mutated parameter shows up as a return value. For
 
3463
example:</p>
 
3464
 
 
3465
 
 
3466
 
 
3467
 
 
3468
 
 
3469
<div class="code targetlang">
 
3470
<pre>a = Example.negate(3)<br>print a<br>-3<br><br></pre>
 
3471
 
 
3472
 
 
3473
 
 
3474
 
 
3475
 
 
3476
</div>
 
3477
 
 
3478
 
 
3479
 
 
3480
 
 
3481
 
 
3482
<p> The most common use of these special typemap rules is to
 
3483
handle functions that return more than one value. For example,
 
3484
sometimes a function returns a result as well as a special error code: </p>
 
3485
 
 
3486
 
 
3487
 
 
3488
 
 
3489
 
 
3490
<div class="code">
 
3491
<pre>/* send message, return number of bytes sent, success code, and error_code */<br>int send_message(char *text, int *success, int *error_code);<br></pre>
 
3492
 
 
3493
 
 
3494
 
 
3495
 
 
3496
 
 
3497
</div>
 
3498
 
 
3499
 
 
3500
 
 
3501
 
 
3502
 
 
3503
<p> To wrap such a function, simply use the <tt>OUTPUT</tt>
 
3504
rule above. For example: </p>
 
3505
 
 
3506
 
 
3507
 
 
3508
 
 
3509
 
 
3510
<div class="code">
 
3511
<pre>%module example<br>%include "typemaps.i"<br>...<br>int send_message(char *, int *OUTPUT, int *OUTPUT);<br></pre>
 
3512
 
 
3513
 
 
3514
 
 
3515
 
 
3516
 
 
3517
</div>
 
3518
 
 
3519
 
 
3520
 
 
3521
 
 
3522
 
 
3523
<p> When used in Ruby, the function will return an array of
 
3524
multiple values. </p>
 
3525
 
 
3526
 
 
3527
 
 
3528
 
 
3529
 
 
3530
<div class="code targetlang">
 
3531
<pre>bytes, success, error_code = send_message("Hello World")<br>if not success<br> print "error #{error_code} : in send_message"<br>else<br> print "Sent", bytes<br>end<br></pre>
 
3532
 
 
3533
 
 
3534
 
 
3535
 
 
3536
 
 
3537
</div>
 
3538
 
 
3539
 
 
3540
 
 
3541
 
 
3542
 
 
3543
<p> Another way to access multiple return values is to use the <tt>%apply</tt>
 
3544
rule. In the following example, the parameters rows and columns are
 
3545
related to SWIG as <tt>OUTPUT</tt> values through the use
 
3546
of <tt>%apply</tt> </p>
 
3547
 
 
3548
 
 
3549
 
 
3550
 
 
3551
 
 
3552
<div class="code">
 
3553
<pre>%module Example<br>%include "typemaps.i"<br>%apply int *OUTPUT { int *rows, int *columns };<br>...<br>void get_dimensions(Matrix *m, int *rows, int*columns);<br></pre>
 
3554
 
 
3555
 
 
3556
 
 
3557
 
 
3558
 
 
3559
</div>
 
3560
 
 
3561
 
 
3562
 
 
3563
 
 
3564
 
 
3565
<p>In Ruby:</p>
 
3566
 
 
3567
 
 
3568
 
 
3569
 
 
3570
 
 
3571
<div class="code targetlang">
 
3572
<pre>r, c = Example.get_dimensions(m)<br></pre>
 
3573
 
 
3574
 
 
3575
 
 
3576
 
 
3577
 
 
3578
</div>
 
3579
 
 
3580
 
 
3581
 
 
3582
 
 
3583
 
 
3584
<H2><a name="Ruby_nn33"></a>30.6 Exception handling </H2>
 
3585
 
 
3586
 
 
3587
<H3><a name="Ruby_nn34"></a>30.6.1 Using the %exception directive </H3>
 
3588
 
 
3589
 
 
3590
<p>The SWIG <tt>%exception</tt> directive can be
 
3591
used to define a user-definable exception handler that can convert
 
3592
C/C++ errors into Ruby exceptions. The chapter on <a href="Customization.html#Customization">Customization
 
3593
Features</a> contains more details, but suppose you have a C++
 
3594
class like the following : </p>
 
3595
 
 
3596
 
 
3597
 
 
3598
 
 
3599
 
 
3600
<div class="code">
 
3601
<pre>class DoubleArray {<br> private:<br> int n;<br> double *ptr;<br> public:<br> // Create a new array of fixed size<br> DoubleArray(int size) {<br> ptr = new double[size];<br> n = size;<br> }<br><br> // Destroy an array<br> ~DoubleArray() {<br> delete ptr;<br> } <br><br> // Return the length of the array<br> int length() {<br> return n;<br> }<br><br> // Get an array item and perform bounds checking.<br> double getitem(int i) {<br> if ((i &gt;= 0) &amp;&amp; (i &lt; n))<br> return ptr[i];<br> else<br> throw RangeError();<br> }<br><br> // Set an array item and perform bounds checking.<br> void setitem(int i, double val) {<br> if ((i &gt;= 0) &amp;&amp; (i &lt; n))<br> ptr[i] = val;<br> else {<br> throw RangeError();<br> }<br> }<br> };<br></pre>
 
3602
 
 
3603
 
 
3604
 
 
3605
 
 
3606
 
 
3607
</div>
 
3608
 
 
3609
 
 
3610
 
 
3611
 
 
3612
 
 
3613
<p> Since several methods in this class can throw an exception
 
3614
for an out-of-bounds access, you might want to catch this in the Ruby
 
3615
extension by writing the following in an interface file: </p>
 
3616
 
 
3617
 
 
3618
 
 
3619
 
 
3620
 
 
3621
<div class="code">
 
3622
<pre>%exception {<br> try {<br> $action<br> }<br> catch (const RangeError&amp;) {<br> static VALUE cpperror = rb_define_class("CPPError", rb_eStandardError);<br> rb_raise(cpperror, "Range error.");<br> }<br>}<br><br>class DoubleArray {<br> ...<br>};<br></pre>
 
3623
 
 
3624
 
 
3625
 
 
3626
 
 
3627
 
 
3628
</div>
 
3629
 
 
3630
 
 
3631
 
 
3632
 
 
3633
 
 
3634
<p> The exception handling code is inserted directly into
 
3635
generated wrapper functions. When an exception handler is defined,
 
3636
errors can be caught and used to gracefully raise a Ruby exception
 
3637
instead of forcing the entire program to terminate with an uncaught
 
3638
error. </p>
 
3639
 
 
3640
 
 
3641
 
 
3642
 
 
3643
 
 
3644
<p>As shown, the exception handling code will be added to every
 
3645
wrapper function. Because this is somewhat inefficient, you might
 
3646
consider refining the exception handler to only apply to specific
 
3647
methods like this: </p>
 
3648
 
 
3649
 
 
3650
 
 
3651
 
 
3652
 
 
3653
<div class="code">
 
3654
<pre>%exception getitem {<br> try {<br> $action<br> }<br> catch (const RangeError&amp;) {<br> static VALUE cpperror = rb_define_class("CPPError", rb_eStandardError);<br> rb_raise(cpperror, "Range error in getitem.");<br> }<br>}<br><br>%exception setitem {<br> try {<br> $action<br> }<br> catch (const RangeError&amp;) {<br> static VALUE cpperror = rb_define_class("CPPError", rb_eStandardError);<br> rb_raise(cpperror, "Range error in setitem.");<br> }<br>}<br></pre>
 
3655
 
 
3656
 
 
3657
 
 
3658
 
 
3659
 
 
3660
</div>
 
3661
 
 
3662
 
 
3663
 
 
3664
 
 
3665
 
 
3666
<p> In this case, the exception handler is only attached to
 
3667
methods and functions named <tt>getitem</tt> and <tt>setitem</tt>.
 
3668
</p>
 
3669
 
 
3670
 
 
3671
 
 
3672
 
 
3673
 
 
3674
<p>Since SWIG's exception handling is user-definable, you are not
 
3675
limited to C++ exception handling. See the chapter on <a href="Customization.html#Customization">Customization
 
3676
Features</a> for more examples.</p>
 
3677
 
 
3678
 
 
3679
 
 
3680
 
 
3681
 
 
3682
<H3><a name="Ruby_nn34_2"></a>30.6.2 Handling Ruby Blocks </H3>
 
3683
 
 
3684
 
 
3685
<p>One of the highlights of Ruby and most of its standard library
 
3686
is
 
3687
the use of blocks, which allow the easy creation of continuations and
 
3688
other niceties. &nbsp;Blocks in ruby are also often used to
 
3689
simplify the passing of many arguments to a class.</p>
 
3690
 
 
3691
 
 
3692
 
 
3693
 
 
3694
 
 
3695
<p>In order to make your class constructor support blocks, you
 
3696
can take advantage of the %exception directive, which will get run
 
3697
after the C++ class' constructor was called.&nbsp;</p>
 
3698
 
 
3699
 
 
3700
 
 
3701
 
 
3702
 
 
3703
<p>For example, this yields the class over after its
 
3704
construction:
 
3705
<br>
 
3706
 
 
3707
 
 
3708
 
 
3709
 
 
3710
 
 
3711
</p>
 
3712
 
 
3713
 
 
3714
 
 
3715
 
 
3716
 
 
3717
<div class="code">
 
3718
<pre>class Window<br>{<br>public:<br> Window(int x, int y, int w, int h);<br>// .... other methods here ....<br>};<br><br>// Add support for yielding self in the Class' constructor.<br>%exception Window::Window {<br> $action<br> if (rb_block_given_p()) {<br> rb_yield(self);<br> }<br>}</pre>
 
3719
 
 
3720
 
 
3721
 
 
3722
 
 
3723
 
 
3724
</div>
 
3725
 
 
3726
 
 
3727
 
 
3728
 
 
3729
 
 
3730
<p> Then, in ruby, it can be used like:</p>
 
3731
 
 
3732
 
 
3733
 
 
3734
 
 
3735
 
 
3736
<div style="font-family: monospace;" class="targetlang">Window.new(0,0,360,480)
 
3737
{ |w|<br>
 
3738
 
 
3739
 
 
3740
 
 
3741
 
 
3742
 
 
3743
&nbsp;&nbsp;&nbsp; w.color = Fltk::RED<br>
 
3744
 
 
3745
 
 
3746
 
 
3747
 
 
3748
 
 
3749
&nbsp;&nbsp;&nbsp; w.border = false<br>
 
3750
 
 
3751
 
 
3752
 
 
3753
 
 
3754
 
 
3755
<span class="targetlang">}</span></div>
 
3756
 
 
3757
 
 
3758
 
 
3759
 
 
3760
 
 
3761
<br>
 
3762
 
 
3763
 
 
3764
 
 
3765
 
 
3766
 
 
3767
<p>For other methods, you can usually use a dummy parameter with
 
3768
a special in typemap, like:</p>
 
3769
 
 
3770
 
 
3771
 
 
3772
 
 
3773
 
 
3774
<div class="code" style="font-family: monospace;">//<br>
 
3775
 
 
3776
 
 
3777
 
 
3778
 
 
3779
 
 
3780
// original function was:<br>
 
3781
 
 
3782
 
 
3783
 
 
3784
 
 
3785
 
 
3786
//<br>
 
3787
 
 
3788
 
 
3789
 
 
3790
 
 
3791
 
 
3792
// void func(int x);<br>
 
3793
 
 
3794
 
 
3795
 
 
3796
 
 
3797
 
 
3798
<br>
 
3799
 
 
3800
 
 
3801
 
 
3802
 
 
3803
 
 
3804
%typemap(in,numinputs=0) int RUBY_YIELD_SELF {<br>
 
3805
 
 
3806
 
 
3807
 
 
3808
 
 
3809
 
 
3810
&nbsp; &nbsp; &nbsp;if ( !rb_block_given_p() )<br>
 
3811
 
 
3812
 
 
3813
 
 
3814
 
 
3815
 
 
3816
&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;
 
3817
rb_raise("No block given");<br>
 
3818
 
 
3819
 
 
3820
 
 
3821
 
 
3822
 
 
3823
&nbsp; &nbsp; &nbsp;return rb_yield(self);<br>
 
3824
 
 
3825
 
 
3826
 
 
3827
 
 
3828
 
 
3829
}<br>
 
3830
 
 
3831
 
 
3832
 
 
3833
 
 
3834
 
 
3835
<br>
 
3836
 
 
3837
 
 
3838
 
 
3839
 
 
3840
 
 
3841
%extend {<br>
 
3842
 
 
3843
 
 
3844
 
 
3845
 
 
3846
 
 
3847
&nbsp; &nbsp; &nbsp; &nbsp; void func(int x, int
 
3848
RUBY_YIELD_SELF );<br>
 
3849
 
 
3850
 
 
3851
 
 
3852
 
 
3853
 
 
3854
}</div>
 
3855
 
 
3856
 
 
3857
 
 
3858
 
 
3859
 
 
3860
<p>For more information on typemaps, see <a href="#Ruby_nn37">Typemaps</a>.</p>
 
3861
 
 
3862
 
 
3863
<H3><a name="Ruby_nn35"></a>30.6.3 Raising exceptions </H3>
 
3864
 
 
3865
 
 
3866
<p>There are three ways to raise exceptions from C++ code to
 
3867
Ruby. </p>
 
3868
 
 
3869
 
 
3870
 
 
3871
 
 
3872
 
 
3873
<p>The first way is to use <tt>SWIG_exception(int code,
 
3874
const char *msg)</tt>. The following table shows the mappings
 
3875
from SWIG error codes to Ruby exceptions:</p>
 
3876
 
 
3877
 
 
3878
 
 
3879
 
 
3880
 
 
3881
<div class="diagram">
 
3882
<table class="diagram" summary="Mapping between SWIG error codes and Ruby exceptions." border="1" width="80%">
 
3883
 
 
3884
 
 
3885
 
 
3886
 
 
3887
 
 
3888
  <tbody>
 
3889
 
 
3890
 
 
3891
 
 
3892
 
 
3893
 
 
3894
    <tr>
 
3895
 
 
3896
 
 
3897
 
 
3898
 
 
3899
 
 
3900
      <td class="diagram" style="font-family: monospace;">
 
3901
      
 
3902
      
 
3903
      
 
3904
      
 
3905
      <div>SWIG_MemoryError</div>
 
3906
 
 
3907
 
 
3908
 
 
3909
 
 
3910
 
 
3911
      </td>
 
3912
 
 
3913
 
 
3914
 
 
3915
 
 
3916
 
 
3917
      <td style="font-family: monospace;">
 
3918
      
 
3919
      
 
3920
      
 
3921
      
 
3922
      <div>rb_eNoMemError</div>
 
3923
 
 
3924
 
 
3925
 
 
3926
 
 
3927
 
 
3928
      </td>
 
3929
 
 
3930
 
 
3931
 
 
3932
 
 
3933
 
 
3934
    </tr>
 
3935
 
 
3936
 
 
3937
 
 
3938
 
 
3939
 
 
3940
    <tr>
 
3941
 
 
3942
 
 
3943
 
 
3944
 
 
3945
 
 
3946
      <td class="diagram" style="font-family: monospace;">
 
3947
      
 
3948
      
 
3949
      
 
3950
      
 
3951
      <div>SWIG_IOError</div>
 
3952
 
 
3953
 
 
3954
 
 
3955
 
 
3956
 
 
3957
      </td>
 
3958
 
 
3959
 
 
3960
 
 
3961
 
 
3962
 
 
3963
      <td style="font-family: monospace;">
 
3964
      
 
3965
      
 
3966
      
 
3967
      
 
3968
      <div>rb_eIOError</div>
 
3969
 
 
3970
 
 
3971
 
 
3972
 
 
3973
 
 
3974
      </td>
 
3975
 
 
3976
 
 
3977
 
 
3978
 
 
3979
 
 
3980
    </tr>
 
3981
 
 
3982
 
 
3983
 
 
3984
 
 
3985
 
 
3986
    <tr>
 
3987
 
 
3988
 
 
3989
 
 
3990
 
 
3991
 
 
3992
      <td class="diagram" style="font-family: monospace;">
 
3993
      
 
3994
      
 
3995
      
 
3996
      
 
3997
      <div>SWIG_RuntimeError</div>
 
3998
 
 
3999
 
 
4000
 
 
4001
 
 
4002
 
 
4003
      </td>
 
4004
 
 
4005
 
 
4006
 
 
4007
 
 
4008
 
 
4009
      <td style="font-family: monospace;">
 
4010
      
 
4011
      
 
4012
      
 
4013
      
 
4014
      <div>rb_eRuntimeError</div>
 
4015
 
 
4016
 
 
4017
 
 
4018
 
 
4019
 
 
4020
      </td>
 
4021
 
 
4022
 
 
4023
 
 
4024
 
 
4025
 
 
4026
    </tr>
 
4027
 
 
4028
 
 
4029
 
 
4030
 
 
4031
 
 
4032
    <tr>
 
4033
 
 
4034
 
 
4035
 
 
4036
 
 
4037
 
 
4038
      <td class="diagram" style="font-family: monospace;">
 
4039
      
 
4040
      
 
4041
      
 
4042
      
 
4043
      <div>SWIG_IndexError</div>
 
4044
 
 
4045
 
 
4046
 
 
4047
 
 
4048
 
 
4049
      </td>
 
4050
 
 
4051
 
 
4052
 
 
4053
 
 
4054
 
 
4055
      <td style="font-family: monospace;">
 
4056
      
 
4057
      
 
4058
      
 
4059
      
 
4060
      <div>rb_eIndexError</div>
 
4061
 
 
4062
 
 
4063
 
 
4064
 
 
4065
 
 
4066
      </td>
 
4067
 
 
4068
 
 
4069
 
 
4070
 
 
4071
 
 
4072
    </tr>
 
4073
 
 
4074
 
 
4075
 
 
4076
 
 
4077
 
 
4078
    <tr>
 
4079
 
 
4080
 
 
4081
 
 
4082
 
 
4083
 
 
4084
      <td class="diagram" style="font-family: monospace;">
 
4085
      
 
4086
      
 
4087
      
 
4088
      
 
4089
      <div>SWIG_TypeError</div>
 
4090
 
 
4091
 
 
4092
 
 
4093
 
 
4094
 
 
4095
      </td>
 
4096
 
 
4097
 
 
4098
 
 
4099
 
 
4100
 
 
4101
      <td style="font-family: monospace;">
 
4102
      
 
4103
      
 
4104
      
 
4105
      
 
4106
      <div>rb_eTypeError</div>
 
4107
 
 
4108
 
 
4109
 
 
4110
 
 
4111
 
 
4112
      </td>
 
4113
 
 
4114
 
 
4115
 
 
4116
 
 
4117
 
 
4118
    </tr>
 
4119
 
 
4120
 
 
4121
 
 
4122
 
 
4123
 
 
4124
    <tr>
 
4125
 
 
4126
 
 
4127
 
 
4128
 
 
4129
 
 
4130
      <td class="diagram" style="font-family: monospace;">
 
4131
      
 
4132
      
 
4133
      
 
4134
      
 
4135
      <div>SWIG_DivisionByZero</div>
 
4136
 
 
4137
 
 
4138
 
 
4139
 
 
4140
 
 
4141
      </td>
 
4142
 
 
4143
 
 
4144
 
 
4145
 
 
4146
 
 
4147
      <td style="font-family: monospace;">
 
4148
      
 
4149
      
 
4150
      
 
4151
      
 
4152
      <div>rb_eZeroDivError</div>
 
4153
 
 
4154
 
 
4155
 
 
4156
 
 
4157
 
 
4158
      </td>
 
4159
 
 
4160
 
 
4161
 
 
4162
 
 
4163
 
 
4164
    </tr>
 
4165
 
 
4166
 
 
4167
 
 
4168
 
 
4169
 
 
4170
    <tr>
 
4171
 
 
4172
 
 
4173
 
 
4174
 
 
4175
 
 
4176
      <td class="diagram" style="font-family: monospace;">
 
4177
      
 
4178
      
 
4179
      
 
4180
      
 
4181
      <div>SWIG_OverflowError</div>
 
4182
 
 
4183
 
 
4184
 
 
4185
 
 
4186
 
 
4187
      </td>
 
4188
 
 
4189
 
 
4190
 
 
4191
 
 
4192
 
 
4193
      <td style="font-family: monospace;">
 
4194
      
 
4195
      
 
4196
      
 
4197
      
 
4198
      <div>rb_eRangeError</div>
 
4199
 
 
4200
 
 
4201
 
 
4202
 
 
4203
 
 
4204
      </td>
 
4205
 
 
4206
 
 
4207
 
 
4208
 
 
4209
 
 
4210
    </tr>
 
4211
 
 
4212
 
 
4213
 
 
4214
 
 
4215
 
 
4216
    <tr>
 
4217
 
 
4218
 
 
4219
 
 
4220
 
 
4221
 
 
4222
      <td class="diagram" style="font-family: monospace;">
 
4223
      
 
4224
      
 
4225
      
 
4226
      
 
4227
      <div>SWIG_SyntaxError</div>
 
4228
 
 
4229
 
 
4230
 
 
4231
 
 
4232
 
 
4233
      </td>
 
4234
 
 
4235
 
 
4236
 
 
4237
 
 
4238
 
 
4239
      <td style="font-family: monospace;">
 
4240
      
 
4241
      
 
4242
      
 
4243
      
 
4244
      <div>rb_eSyntaxError</div>
 
4245
 
 
4246
 
 
4247
 
 
4248
 
 
4249
 
 
4250
      </td>
 
4251
 
 
4252
 
 
4253
 
 
4254
 
 
4255
 
 
4256
    </tr>
 
4257
 
 
4258
 
 
4259
 
 
4260
 
 
4261
 
 
4262
    <tr>
 
4263
 
 
4264
 
 
4265
 
 
4266
 
 
4267
 
 
4268
      <td class="diagram" style="font-family: monospace;">
 
4269
      
 
4270
      
 
4271
      
 
4272
      
 
4273
      <div>SWIG_ValueError</div>
 
4274
 
 
4275
 
 
4276
 
 
4277
 
 
4278
 
 
4279
      </td>
 
4280
 
 
4281
 
 
4282
 
 
4283
 
 
4284
 
 
4285
      <td style="font-family: monospace;">
 
4286
      
 
4287
      
 
4288
      
 
4289
      
 
4290
      <div>rb_eArgError</div>
 
4291
 
 
4292
 
 
4293
 
 
4294
 
 
4295
 
 
4296
      </td>
 
4297
 
 
4298
 
 
4299
 
 
4300
 
 
4301
 
 
4302
    </tr>
 
4303
 
 
4304
 
 
4305
 
 
4306
 
 
4307
 
 
4308
    <tr>
 
4309
 
 
4310
 
 
4311
 
 
4312
 
 
4313
 
 
4314
      <td class="diagram" style="font-family: monospace;">
 
4315
      
 
4316
      
 
4317
      
 
4318
      
 
4319
      <div>SWIG_SystemError</div>
 
4320
 
 
4321
 
 
4322
 
 
4323
 
 
4324
 
 
4325
      </td>
 
4326
 
 
4327
 
 
4328
 
 
4329
 
 
4330
 
 
4331
      <td style="font-family: monospace;">
 
4332
      
 
4333
      
 
4334
      
 
4335
      
 
4336
      <div>rb_eFatal</div>
 
4337
 
 
4338
 
 
4339
 
 
4340
 
 
4341
 
 
4342
      </td>
 
4343
 
 
4344
 
 
4345
 
 
4346
 
 
4347
 
 
4348
    </tr>
 
4349
 
 
4350
 
 
4351
 
 
4352
 
 
4353
 
 
4354
    <tr>
 
4355
 
 
4356
 
 
4357
 
 
4358
 
 
4359
 
 
4360
      <td class="diagram" style="font-family: monospace;">
 
4361
      
 
4362
      
 
4363
      
 
4364
      
 
4365
      <div>SWIG_AttributeError</div>
 
4366
 
 
4367
 
 
4368
 
 
4369
 
 
4370
 
 
4371
      </td>
 
4372
 
 
4373
 
 
4374
 
 
4375
 
 
4376
 
 
4377
      <td style="font-family: monospace;">
 
4378
      
 
4379
      
 
4380
      
 
4381
      
 
4382
      <div>rb_eRuntimeError</div>
 
4383
 
 
4384
 
 
4385
 
 
4386
 
 
4387
 
 
4388
      </td>
 
4389
 
 
4390
 
 
4391
 
 
4392
 
 
4393
 
 
4394
    </tr>
 
4395
 
 
4396
 
 
4397
 
 
4398
 
 
4399
 
 
4400
    <tr>
 
4401
 
 
4402
 
 
4403
 
 
4404
 
 
4405
 
 
4406
      <td class="diagram" style="font-family: monospace;">
 
4407
      
 
4408
      
 
4409
      
 
4410
      
 
4411
      <div>SWIG_NullReferenceError</div>
 
4412
 
 
4413
 
 
4414
 
 
4415
 
 
4416
 
 
4417
      </td>
 
4418
 
 
4419
 
 
4420
 
 
4421
 
 
4422
 
 
4423
      <td style="font-family: monospace;">
 
4424
      
 
4425
      
 
4426
      
 
4427
      
 
4428
      <div>rb_eNullReferenceError*</div>
 
4429
 
 
4430
 
 
4431
 
 
4432
 
 
4433
 
 
4434
      </td>
 
4435
 
 
4436
 
 
4437
 
 
4438
 
 
4439
 
 
4440
    </tr>
 
4441
 
 
4442
 
 
4443
 
 
4444
 
 
4445
 
 
4446
    <tr>
 
4447
 
 
4448
 
 
4449
 
 
4450
 
 
4451
 
 
4452
      <td class="diagram" style="font-family: monospace;">
 
4453
      
 
4454
      
 
4455
      
 
4456
      
 
4457
      <div>SWIG_ObjectPreviouslyDeletedError</div>
 
4458
 
 
4459
 
 
4460
 
 
4461
 
 
4462
 
 
4463
      </td>
 
4464
 
 
4465
 
 
4466
 
 
4467
 
 
4468
 
 
4469
      <td style="font-family: monospace;">
 
4470
      
 
4471
      
 
4472
      
 
4473
      
 
4474
      <div>rb_eObjectPreviouslyDeleted*</div>
 
4475
 
 
4476
 
 
4477
 
 
4478
 
 
4479
 
 
4480
      </td>
 
4481
 
 
4482
 
 
4483
 
 
4484
 
 
4485
 
 
4486
    </tr>
 
4487
 
 
4488
 
 
4489
 
 
4490
 
 
4491
 
 
4492
    <tr>
 
4493
 
 
4494
 
 
4495
 
 
4496
 
 
4497
 
 
4498
      <td class="diagram" style="font-family: monospace;">
 
4499
      
 
4500
      
 
4501
      
 
4502
      
 
4503
      <div>SWIG_UnknownError</div>
 
4504
 
 
4505
 
 
4506
 
 
4507
 
 
4508
 
 
4509
      </td>
 
4510
 
 
4511
 
 
4512
 
 
4513
 
 
4514
 
 
4515
      <td style="font-family: monospace;">
 
4516
      
 
4517
      
 
4518
      
 
4519
      
 
4520
      <div>rb_eRuntimeError</div>
 
4521
 
 
4522
 
 
4523
 
 
4524
 
 
4525
 
 
4526
      </td>
 
4527
 
 
4528
 
 
4529
 
 
4530
 
 
4531
 
 
4532
    </tr>
 
4533
 
 
4534
 
 
4535
 
 
4536
 
 
4537
 
 
4538
    <tr class="diagram" style="font-family: monospace;">
 
4539
 
 
4540
 
 
4541
 
 
4542
 
 
4543
 
 
4544
      <td colspan="2">
 
4545
      
 
4546
      
 
4547
      
 
4548
      
 
4549
      <div>* These error classes are created by
 
4550
SWIG and are not built-in Ruby exception classes </div>
 
4551
 
 
4552
 
 
4553
 
 
4554
 
 
4555
 
 
4556
      </td>
 
4557
 
 
4558
 
 
4559
 
 
4560
 
 
4561
 
 
4562
    </tr>
 
4563
 
 
4564
 
 
4565
 
 
4566
 
 
4567
 
 
4568
  
 
4569
  
 
4570
  
 
4571
  
 
4572
  </tbody>
 
4573
</table>
 
4574
 
 
4575
 
 
4576
 
 
4577
 
 
4578
 
 
4579
</div>
 
4580
 
 
4581
 
 
4582
 
 
4583
 
 
4584
 
 
4585
<p>The second way to raise errors is to use <tt>SWIG_Raise(obj,
 
4586
type, desc)</tt>.
 
4587
Obj is a C++ instance of an exception class, type is a string
 
4588
specifying the type of exception (for example, "MyError") and desc is
 
4589
the SWIG description of the exception class. For example: </p>
 
4590
 
 
4591
 
 
4592
 
 
4593
 
 
4594
 
 
4595
<div style="font-family: monospace;" class="code">
 
4596
%raise(SWIG_NewPointerObj(e,
 
4597
SWIGTYPE_p_AssertionFailedException,
 
4598
0), ":AssertionFailedException", SWIGTYPE_p_AssertionFailedException);</div>
 
4599
 
 
4600
 
 
4601
 
 
4602
 
 
4603
 
 
4604
<p>This is useful when you want to pass the current exception
 
4605
object
 
4606
directly to Ruby, particularly when the object is an instance of class
 
4607
marked as an <tt>%exceptionclass</tt> (see the next
 
4608
section for more information).</p>
 
4609
 
 
4610
 
 
4611
 
 
4612
 
 
4613
 
 
4614
<p>Last, you can raise an exception by directly calling Ruby's C
 
4615
api. This is done by invoking the <tt>rb_raise()</tt>
 
4616
function. The first argument passed to <tt>rb_raise()</tt>
 
4617
is the exception type. You can raise a custom exception type or one of
 
4618
the built-in Ruby exception types.</p>
 
4619
 
 
4620
 
 
4621
 
 
4622
 
 
4623
 
 
4624
<H3><a name="Ruby_nn36"></a>30.6.4 Exception classes </H3>
 
4625
 
 
4626
 
 
4627
<p>Starting with SWIG 1.3.28, the Ruby module supports the <tt>%exceptionclass</tt>
 
4628
directive, which is used to identify C++ classes that are used as
 
4629
exceptions. Classes that are marked with the <tt>%exceptionclass</tt>
 
4630
directive are exposed in Ruby as child classes of <tt>rb_eRuntimeError</tt>.
 
4631
This allows C++ exceptions to be directly mapped to Ruby exceptions,
 
4632
providing for a more natural integration between C++ code and Ruby code.</p>
 
4633
 
 
4634
 
 
4635
 
 
4636
 
 
4637
 
 
4638
<div class="code">
 
4639
<pre>   %exceptionclass CustomError;<br>        <br>    %inline %{<br>  class CustomError { };<br>      <br>    class Foo { <br>        public:<br>     void test() { throw CustomError; }<br>  };<br>  }<br></pre>
 
4640
 
 
4641
 
 
4642
 
 
4643
 
 
4644
 
 
4645
</div>
 
4646
 
 
4647
 
 
4648
 
 
4649
 
 
4650
 
 
4651
<p>From Ruby you can now call this method like this: </p>
 
4652
 
 
4653
 
 
4654
 
 
4655
 
 
4656
 
 
4657
<div class="code targetlang">
 
4658
<pre>foo = Foo.new<br>begin<br> foo.test()<br>rescue CustomError =&gt; e<br> puts "Caught custom error"<br>end </pre>
 
4659
 
 
4660
 
 
4661
 
 
4662
 
 
4663
 
 
4664
</div>
 
4665
 
 
4666
 
 
4667
 
 
4668
 
 
4669
 
 
4670
<p>For another example look at swig/Examples/ruby/exception_class.<br>
 
4671
 
 
4672
 
 
4673
 
 
4674
 
 
4675
 
 
4676
</p>
 
4677
 
 
4678
 
 
4679
 
 
4680
 
 
4681
 
1310
4682
<H2><a name="Ruby_nn37"></a>30.7 Typemaps</H2>
1311
4683
 
1312
4684
 
1313
 
                <p>
1314
 
                        This section describes how you can modify SWIG's default wrapping behavior for 
1315
 
                        various C/C++ datatypes using the <tt>%typemap</tt> directive. This is an 
1316
 
                        advanced topic that assumes familiarity with the Ruby C API as well as the 
1317
 
                        material in the "<a href="Typemaps.html#Typemaps">Typemaps</a>" chapter.
1318
 
                </p>
1319
 
                <p>Before proceeding, it should be stressed that typemaps are not a required part 
1320
 
                        of using SWIG---the default wrapping behavior is enough in most cases. Typemaps 
1321
 
                        are only used if you want to change some aspect of the primitive C-Ruby 
1322
 
                        interface.</p>
 
4685
<p> This section describes how you can modify SWIG's default
 
4686
wrapping behavior for various C/C++ datatypes using the <tt>%typemap</tt>
 
4687
directive. This is an advanced topic that assumes familiarity with the
 
4688
Ruby C API as well as the material in the "<a href="Typemaps.html#Typemaps">Typemaps</a>"
 
4689
chapter.&nbsp;
 
4690
</p>
 
4691
 
 
4692
 
 
4693
 
 
4694
 
 
4695
 
 
4696
<p>Before proceeding, it should be stressed that typemaps are not
 
4697
a required part of using SWIG---the default wrapping behavior is enough
 
4698
in most cases. Typemaps are only used if you want to change some aspect
 
4699
of the primitive C-Ruby interface.</p>
 
4700
 
 
4701
 
 
4702
 
 
4703
 
 
4704
 
1323
4705
<H3><a name="Ruby_nn38"></a>30.7.1 What is a typemap?</H3>
1324
4706
 
1325
4707
 
1326
 
                <p>
1327
 
                        A typemap is nothing more than a code generation rule that is attached to a 
1328
 
                        specific C datatype. For example, to convert integers from Ruby to C, you might 
1329
 
                        define a typemap like this:
1330
 
                </p>
1331
 
                <div class="code">
1332
 
                        <pre>%module example<br><br>%typemap(in) int {<br> $1 = (int) NUM2INT($input);<br> printf("Received an integer : %d\n",$1);<br>}<br><br>%inline %{<br>extern int fact(int n);<br>%}<br></pre>
1333
 
                </div>
1334
 
                <p>
1335
 
                        Typemaps are always associated with some specific aspect of code generation. In 
1336
 
                        this case, the "in" method refers to the conversion of input arguments to 
1337
 
                        C/C++. The datatype <tt>int</tt> is the datatype to which the typemap will be 
1338
 
                        applied. The supplied C code is used to convert values. In this code a number 
1339
 
                        of special variables prefaced by a <tt>$</tt> are used. The <tt>$1</tt> variable 
1340
 
                        is placeholder for a local variable of type <tt>int</tt>. The <tt>$input</tt> variable 
1341
 
                        is the input Ruby object.
1342
 
                </p>
1343
 
                <p>When this example is compiled into a Ruby module, the following sample code:
1344
 
                </p>
1345
 
                <div class="code">
1346
 
                        <pre>require 'example'<br><br>puts Example.fact(6)<br></pre>
1347
 
                </div>
1348
 
                <p>prints the result:</p>
1349
 
                <div class="code">
1350
 
                        <pre>Received an integer : 6<br>720<br></pre>
1351
 
                </div>
1352
 
                <p>
1353
 
                        In this example, the typemap is applied to all occurrences of the <tt>int</tt> datatype. 
1354
 
                        You can refine this by supplying an optional parameter name. For example:
1355
 
                </p>
1356
 
                <div class="code">
1357
 
                        <pre>%module example<br><br>%typemap(in) int n {<br> $1 = (int) NUM2INT($input);<br> printf("n = %d\n",$1);<br>}<br><br>%inline %{<br>extern int fact(int n);<br>%}<br></pre>
1358
 
                </div>
1359
 
                <p>
1360
 
                        In this case, the typemap code is only attached to arguments that exactly match 
1361
 
                        "<tt>int n</tt>".
1362
 
                </p>
1363
 
                <p>The application of a typemap to specific datatypes and argument names involves 
1364
 
                        more than simple text-matching--typemaps are fully integrated into the SWIG 
1365
 
                        type-system. When you define a typemap for <tt>int</tt>, that typemap applies 
1366
 
                        to <tt>int</tt> and qualified variations such as <tt>const int</tt>. In 
1367
 
                        addition, the typemap system follows <tt>typedef</tt> declarations. For 
1368
 
                        example:
1369
 
                </p>
1370
 
                <div class="code">
1371
 
                        <pre>%typemap(in) int n {<br> $1 = (int) NUM2INT($input);<br> printf("n = %d\n",$1);<br>}<br><br>typedef int Integer;<br>extern int fact(Integer n); // Above typemap is applied<br></pre>
1372
 
                </div>
1373
 
                <p>
1374
 
                        However, the matching of <tt>typedef</tt> only occurs in one direction. If you 
1375
 
                        defined a typemap for <tt>Integer</tt>, it is not applied to arguments of type <tt>int</tt>.
1376
 
                </p>
1377
 
                <p>Typemaps can also be defined for groups of consecutive arguments. For example:
1378
 
                </p>
1379
 
                <div class="code">
1380
 
                        <pre>%typemap(in) (char *str, int len) {<br> $1 = STR2CSTR($input);<br> $2 = (int) RSTRING($input)-&gt;len;<br>};<br><br>int count(char c, char *str, int len);<br></pre>
1381
 
                </div>
1382
 
                <p>
1383
 
                        When a multi-argument typemap is defined, the arguments are always handled as a 
1384
 
                        single Ruby object. This allows the function <tt>count</tt> to be used as 
1385
 
                        follows (notice how the length parameter is omitted):
1386
 
                </p>
1387
 
                <div class="code">
1388
 
                        <pre>puts Example.count('o','Hello World')<br>2<br></pre>
1389
 
                </div>
1390
 
<H3><a name="Ruby_nn39"></a>30.7.2 Ruby typemaps</H3>
1391
 
 
1392
 
 
1393
 
                <p>
1394
 
                        The previous section illustrated an "in" typemap for converting Ruby objects to 
1395
 
                        C. A variety of different typemap methods are defined by the Ruby module. For 
1396
 
                        example, to convert a C integer back into a Ruby object, you might define an 
1397
 
                        "out" typemap like this:
1398
 
                </p>
1399
 
                <div class="code">
1400
 
                        <pre>%typemap(out) int {<br> $result = INT2NUM($1);<br>}<br></pre>
1401
 
                </div>
1402
 
                <p>
1403
 
                        The following list details all of the typemap methods that can be used by the 
1404
 
                        Ruby module:
1405
 
                </p>
1406
 
                <p><tt>%typemap(in) </tt>
1407
 
                </p>
1408
 
                <div class="indent">Converts Ruby objects to input function arguments
1409
 
                </div>
1410
 
                <p><tt>%typemap(out)</tt></p>
1411
 
                <div class="indent">Converts return value of a C function to a Ruby object
1412
 
                </div>
1413
 
                <p><tt>%typemap(varin)</tt></p>
1414
 
                <div class="indent">Assigns a C global variable from a Ruby object
1415
 
                </div>
1416
 
                <p><tt>%typemap(varout)</tt></p>
1417
 
                <div class="indent">Returns a C global variable as a Ruby object
1418
 
                </div>
1419
 
                <p><tt>%typemap(freearg)</tt></p>
1420
 
                <div class="indent">Cleans up a function argument (if necessary)
1421
 
                </div>
1422
 
                <p><tt>%typemap(argout)</tt></p>
1423
 
                <div class="indent">Output argument processing
1424
 
                </div>
1425
 
                <p><tt>%typemap(ret)</tt></p>
1426
 
                <div class="indent">Cleanup of function return values
1427
 
                </div>
1428
 
                <p><tt>%typemap(memberin)</tt></p>
1429
 
                <div class="indent">Setting of structure/class member data
1430
 
                </div>
1431
 
                <p><tt>%typemap(globalin)</tt></p>
1432
 
                <div class="indent">Setting of C global variables
1433
 
                </div>
1434
 
                <p><tt>%typemap(check)</tt></p>
1435
 
                <div class="indent">Checks function input values.
1436
 
                </div>
1437
 
                <p><tt>%typemap(default)</tt></p>
1438
 
                <div class="indent">Set a default value for an argument (making it optional).
1439
 
                </div>
1440
 
                <p><tt>%typemap(arginit)</tt></p>
1441
 
                <div class="indent">Initialize an argument to a value before any conversions occur.
1442
 
                </div>
1443
 
                <p>
1444
 
                        Examples of these typemaps appears in the <a href="#ruby_typemap_examples">section 
1445
 
                                on typemap examples</a>
1446
 
                </p>
1447
 
<H3><a name="Ruby_nn40"></a>30.7.3 Typemap variables</H3>
1448
 
 
1449
 
 
1450
 
                Within a typemap, a number of special variables prefaced with a <tt>$</tt> may 
1451
 
                appear. A full list of variables can be found in the "<a href="Typemaps.html#Typemaps">Typemaps</a>" 
1452
 
                chapter. This is a list of the most common variables:
1453
 
                <p><tt>$1</tt>
1454
 
                </p>
1455
 
                <div class="indent">A C local variable corresponding to the actual type specified 
1456
 
                        in the <tt>%typemap</tt> directive. For input values, this is a C local 
1457
 
                        variable that is supposed to hold an argument value. For output values, this is 
1458
 
                        the raw result that is supposed to be returned to Ruby.
1459
 
                </div>
1460
 
                <p><tt>$input</tt></p>
1461
 
                <div class="indent">A <tt>VALUE</tt> holding a raw Ruby object with an argument or 
1462
 
                        variable value.
1463
 
                </div>
1464
 
                <p><tt>$result</tt></p>
1465
 
                <div class="indent">A <tt>VALUE</tt> that holds the result to be returned to Ruby.
1466
 
                </div>
1467
 
                <p><tt>$1_name</tt></p>
1468
 
                <div class="indent">The parameter name that was matched.
1469
 
                </div>
1470
 
                <p><tt>$1_type</tt></p>
1471
 
                <div class="indent">The actual C datatype matched by the typemap.
1472
 
                </div>
1473
 
                <p><tt>$1_ltype</tt></p>
1474
 
                <div class="indent">An assignable version of the datatype matched by the typemap (a 
1475
 
                        type that can appear on the left-hand-side of a C assignment operation). This 
1476
 
                        type is stripped of qualifiers and may be an altered version of <tt>$1_type</tt>. 
1477
 
                        All arguments and local variables in wrapper functions are declared using this 
1478
 
                        type so that their values can be properly assigned.
1479
 
                </div>
1480
 
                <p><tt>$symname</tt></p>
1481
 
                <div class="indent">The Ruby name of the wrapper function being created.
1482
 
                </div>
1483
 
<H3><a name="Ruby_nn41"></a>30.7.4 Useful Functions</H3>
1484
 
 
1485
 
 
1486
 
                <p>
1487
 
                        When you write a typemap, you usually have to work directly with Ruby objects. 
1488
 
                        The following functions may prove to be useful. (These functions plus many more 
1489
 
                        can be found in <a href="http://www.rubycentral.com/book"><em>Programming Ruby</em></a>, 
1490
 
                        by David Thomas and Andrew Hunt.)
1491
 
                </p>
1492
 
                <p>&nbsp;</p>
1493
 
<H4><a name="Ruby_nn42"></a>30.7.4.1 C Datatypes to Ruby Objects</H4>
1494
 
 
1495
 
 
1496
 
                <div class="code">
1497
 
                        <pre>INT2NUM(long or int) - int to Fixnum or Bignum<br>INT2FIX(long or int) - int to Fixnum (faster than INT2NUM)<br>CHR2FIX(char) - char to Fixnum<br>rb_str_new2(char*) - char* to String<br>rb_float_new(double) - double to Float<br></pre>
1498
 
                </div>
1499
 
<H4><a name="Ruby_nn43"></a>30.7.4.2 Ruby Objects to C Datatypes</H4>
1500
 
 
1501
 
 
1502
 
                <div class="code">
1503
 
                        <pre> int NUM2INT(Numeric)<br> int FIX2INT(Numeric)<br> unsigned int NUM2UINT(Numeric)<br> unsigned int FIX2UINT(Numeric)<br> long NUM2LONG(Numeric)<br> long FIX2LONG(Numeric)<br>unsigned long FIX2ULONG(Numeric)<br> char NUM2CHR(Numeric or String)<br> char * STR2CSTR(String)<br> char * rb_str2cstr(String, int*length)<br> double NUM2DBL(Numeric)<br><br></pre>
1504
 
                </div>
1505
 
<H4><a name="Ruby_nn44"></a>30.7.4.3 Macros for VALUE</H4>
1506
 
 
1507
 
 
1508
 
                <p>
1509
 
                        <tt>RSTRING(str)-&gt;len</tt>
1510
 
                </p>
1511
 
                <div class="indent">length of the Ruby string</div>
1512
 
                <p><tt>RSTRING(str)-&gt;ptr</tt></p>
1513
 
                <div class="indent">pointer to string storage</div>
1514
 
                <p><tt>RARRAY(arr)-&gt;len</tt></p>
1515
 
                <div class="indent">length of the Ruby array</div>
1516
 
                <p><tt>RARRAY(arr)-&gt;capa</tt></p>
1517
 
                <div class="indent">capacity of the Ruby array</div>
1518
 
                <p><tt>RARRAY(arr)-&gt;ptr</tt></p>
1519
 
                <div class="indent">pointer to array storage</div>
1520
 
<H4><a name="Ruby_nn45"></a>30.7.4.4 Exceptions</H4>
1521
 
 
1522
 
 
1523
 
                <p>
1524
 
                        <tt>void rb_raise(VALUE exception, const char *fmt, ...)</tt>
1525
 
                </p>
1526
 
                <div class="indent">
1527
 
                        Raises an exception. The given format string <i>fmt</i> and remaining arguments 
1528
 
                        are interpreted as with <tt>printf()</tt>.
1529
 
                </div>
1530
 
                <p><tt>void rb_fatal(const char *fmt, ...)</tt></p>
1531
 
                <div class="indent">
1532
 
                        Raises a fatal exception, terminating the process. No rescue blocks are called, 
1533
 
                        but ensure blocks will be called. The given format string <i>fmt</i> and 
1534
 
                        remaining arguments are interpreted as with <tt>printf()</tt>.
1535
 
                </div>
1536
 
                <p><tt>void rb_bug(const char *fmt, ...)</tt></p>
1537
 
                <div class="indent">
1538
 
                        Terminates the process immediately -- no handlers of any sort will be called. 
1539
 
                        The given format string <i>fmt</i> and remaining arguments are interpreted as 
1540
 
                        with <tt>printf()</tt>. You should call this function only if a fatal bug has 
1541
 
                        been exposed.
1542
 
                </div>
1543
 
                <p><tt>void rb_sys_fail(const char *msg)</tt></p>
1544
 
                <div class="indent">
1545
 
                        Raises a platform-specific exception corresponding to the last known system 
1546
 
                        error, with the given string <i>msg</i>.
1547
 
                </div>
1548
 
                <p><tt>VALUE rb_rescue(VALUE (*body)(VALUE), VALUE args, VALUE(*rescue)(VALUE, VALUE), 
1549
 
                                VALUE rargs)</tt></p>
1550
 
                <div class="indent">
1551
 
                        Executes <i>body</i> with the given <i>args</i>. If a <tt>StandardError</tt> exception 
1552
 
                        is raised, then execute <i>rescue</i> with the given <i>rargs</i>.
1553
 
                </div>
1554
 
                <p><tt>VALUE rb_ensure(VALUE(*body)(VALUE), VALUE args, VALUE(*ensure)(VALUE), VALUE 
1555
 
                                eargs)</tt></p>
1556
 
                <div class="indent">
1557
 
                        Executes <i>body</i> with the given <i>args</i>. Whether or not an exception is 
1558
 
                        raised, execute <i>ensure</i> with the given <i>rargs</i> after <i>body</i> has 
1559
 
                        completed.
1560
 
                </div>
1561
 
                <p><tt>VALUE rb_protect(VALUE (*body)(VALUE), VALUE args, int *result)</tt></p>
1562
 
                <div class="indent">
1563
 
                        Executes <i>body</i> with the given <i>args</i> and returns nonzero in result 
1564
 
                        if any exception was raised.
1565
 
                </div>
1566
 
                <p><tt>void rb_notimplement()</tt></p>
1567
 
                <div class="indent">
1568
 
                        Raises a <tt>NotImpError</tt> exception to indicate that the enclosed function 
1569
 
                        is not implemented yet, or not available on this platform.
1570
 
                </div>
1571
 
                <p><tt>void rb_exit(int status)</tt></p>
1572
 
                <div class="indent">
1573
 
                        Exits Ruby with the given <i>status</i>. Raises a <tt>SystemExit</tt> exception 
1574
 
                        and calls registered exit functions and finalizers.
1575
 
                </div>
1576
 
                <p><tt>void rb_warn(const char *fmt, ...)</tt></p>
1577
 
                <div class="indent">
1578
 
                        Unconditionally issues a warning message to standard error. The given format 
1579
 
                        string <i>fmt</i> and remaining arguments are interpreted as with <tt>printf()</tt>.
1580
 
                </div>
1581
 
                <p><tt>void rb_warning(const char *fmt, ...)</tt></p>
1582
 
                <div class="indent">
1583
 
                        Conditionally issues a warning message to standard error if Ruby was invoked 
1584
 
                        with the <tt>-w</tt> flag. The given format string <i>fmt</i> and remaining 
1585
 
                        arguments are interpreted as with <tt>printf()</tt>.
1586
 
                </div>
1587
 
<H4><a name="Ruby_nn46"></a>30.7.4.5 Iterators</H4>
1588
 
 
1589
 
 
1590
 
                <p>
1591
 
                        <tt>void rb_iter_break()</tt>
1592
 
                </p>
1593
 
                <div class="indent">
1594
 
                        Breaks out of the enclosing iterator block.
1595
 
                </div>
1596
 
                <p><tt>VALUE rb_each(VALUE obj)</tt></p>
1597
 
                <div class="indent">
1598
 
                        Invokes the <tt>each</tt> method of the given <i>obj</i>.
1599
 
                </div>
1600
 
                <p><tt>VALUE rb_yield(VALUE arg)</tt></p>
1601
 
                <div class="indent">
1602
 
                        Transfers execution to the iterator block in the current context, passing <i>arg</i>
1603
 
                        as an argument. Multiple values may be passed in an array.
1604
 
                </div>
1605
 
                <p><tt>int rb_block_given_p()</tt></p>
1606
 
                <div class="indent">
1607
 
                        Returns <tt>true</tt> if <tt>yield</tt> would execute a block in the current 
1608
 
                        context; that is, if a code block was passed to the current method and is 
1609
 
                        available to be called.
1610
 
                </div>
1611
 
                <p><tt>VALUE rb_iterate(VALUE (*method)(VALUE), VALUE args, VALUE (*block)(VALUE, 
1612
 
                                VALUE), VALUE arg2)</tt></p>
1613
 
                <div class="indent">
1614
 
                        Invokes <i>method</i> with argument <i>args</i> and block <i>block</i>. A <tt>yield</tt>
1615
 
                        from that method will invoke <i>block</i> with the argument given to <tt>yield</tt>, 
1616
 
                        and a second argument <i>arg2</i>.
1617
 
                </div>
1618
 
                <p><tt>VALUE rb_catch(const char *tag, VALUE (*proc)(VALUE, VALUE), VALUE value)</tt></p>
1619
 
                <div class="indent">
1620
 
                        Equivalent to Ruby's <tt>catch</tt>.
1621
 
                </div>
1622
 
                <p><tt>void rb_throw(const char *tag, VALUE value)</tt></p>
1623
 
                <div class="indent">
1624
 
                        Equivalent to Ruby's <tt>throw</tt>.
1625
 
                </div>
1626
 
<H3><a name="Ruby_nn47"></a>30.7.5 Typemap Examples</H3>
1627
 
 
1628
 
 
1629
 
                <p>
1630
 
                        This section includes a few examples of typemaps. For more examples, you might 
1631
 
                        look at the examples in the <tt>Example/ruby</tt> directory.
1632
 
                </p>
1633
 
<H3><a name="Ruby_nn48"></a>30.7.6 Converting a Ruby array to a char **</H3>
1634
 
 
1635
 
 
1636
 
                <p>
1637
 
                        A common problem in many C programs is the processing of command line 
1638
 
                        arguments, which are usually passed in an array of <tt>NULL</tt> terminated 
1639
 
                        strings. The following SWIG interface file allows a Ruby Array instance to be 
1640
 
                        used as a <tt>char **</tt> object.
1641
 
                </p>
1642
 
                <div class="code">
1643
 
                        <pre>%module argv<br><br>// This tells SWIG to treat char ** as a special case<br>%typemap(in) char ** {<br> /* Get the length of the array */<br> int size = RARRAY($input)-&gt;len; <br> int i;<br> $1 = (char **) malloc((size+1)*sizeof(char *));<br> /* Get the first element in memory */<br> VALUE *ptr = RARRAY($input)-&gt;ptr; <br> for (i=0; i &lt; size; i++, ptr++)<br> /* Convert Ruby Object String to char* */<br> $1[i]= STR2CSTR(*ptr); <br> $1[i]=NULL; /* End of list */<br>}<br><br>// This cleans up the char ** array created before <br>// the function call<br><br>%typemap(freearg) char ** {<br> free((char *) $1);<br>}<br><br>// Now a test function<br>%inline %{<br>int print_args(char **argv) {<br> int i = 0;<br> while (argv[i]) {<br> printf("argv[%d] = %s\n", i,argv[i]);<br> i++;<br> }<br> return i;<br>}<br>%}<br><br></pre>
1644
 
                </div>
1645
 
                <p>
1646
 
                        When this module is compiled, the wrapped C function now operates as follows :
1647
 
                </p>
1648
 
                <div class="code">
1649
 
                        <pre>require 'Argv'<br>Argv.print_args(["Dave","Mike","Mary","Jane","John"])<br>argv[0] = Dave<br>argv[1] = Mike<br>argv[2] = Mary<br>argv[3] = Jane<br>argv[4] = John<br></pre>
1650
 
                </div>
1651
 
                <p>
1652
 
                        In the example, two different typemaps are used. The "in" typemap is used to 
1653
 
                        receive an input argument and convert it to a C array. Since dynamic memory 
1654
 
                        allocation is used to allocate memory for the array, the "freearg" typemap is 
1655
 
                        used to later release this memory after the execution of the C function.
1656
 
                </p>
1657
 
<H3><a name="Ruby_nn49"></a>30.7.7 Collecting arguments in a hash</H3>
1658
 
 
1659
 
 
1660
 
                <p>
1661
 
                        Ruby's solution to the "keyword arguments" capability of some other languages 
1662
 
                        is to allow the programmer to pass in one or more key-value pairs as arguments 
1663
 
                        to a function. All of those key-value pairs are collected in a single <tt>Hash</tt>
1664
 
                        argument that's presented to the function. If it makes sense, you might want to 
1665
 
                        provide similar functionality for your Ruby interface. For example, suppose 
1666
 
                        you'd like to wrap this C function that collects information about people's 
1667
 
                        vital statistics:
1668
 
                </p>
1669
 
                <div class="code">
1670
 
                        <pre>void setVitalStats(const char *person, int nattributes, const char **names, int *values);<br></pre>
1671
 
                </div>
1672
 
                <p>
1673
 
                        and you'd like to be able to call it from Ruby by passing in an arbitrary 
1674
 
                        number of key-value pairs as inputs, e.g.
1675
 
                </p>
1676
 
                <div class="code">
1677
 
                        <pre>setVitalStats("Fred",<br> 'weight' =&gt; 270,<br>  'age' =&gt; 42<br>      )<br></pre>
1678
 
                </div>
1679
 
                <p>
1680
 
                        To make this work, you need to write a typemap that expects a Ruby <tt>Hash</tt>
1681
 
                        as its input and somehow extracts the last three arguments (<i>nattributes</i>, <i>names</i>
1682
 
                        and <i>values</i>) needed by your C function. Let's start with the basics:
1683
 
                </p>
1684
 
                <div class="code">
1685
 
                        <pre>%typemap(in) (int nattributes, const char **names, const int *values)<br> (VALUE keys_arr, int i, VALUE key, VALUE val) {<br>}<br> </pre>
1686
 
                </div>
1687
 
                <p>
1688
 
                        This <tt>%typemap</tt> directive tells SWIG that we want to match any function 
1689
 
                        declaration that has the specified types and names of arguments somewhere in 
1690
 
                        the argument list. The fact that we specified the argument names (<i>nattributes</i>,
1691
 
                        <i>names</i> and <i>values</i>) in our typemap is significant; this ensures 
1692
 
                        that SWIG won't try to apply this typemap to <i>other</i> functions it sees 
1693
 
                        that happen to have a similar declaration with different argument names. The 
1694
 
                        arguments that appear in the second set of parentheses (<i>keys_arr</i>, <i>i</i>,
1695
 
                        <i>key</i> and <i>val</i>) define local variables that our typemap will need.
1696
 
                </p>
1697
 
                <p>Since we expect the input argument to be a <tt>Hash</tt>, let's next add a check 
1698
 
                        for that:
1699
 
                </p>
1700
 
                <div class="code">
1701
 
                        <pre>%typemap(in) (int nattributes, const char **names, const int *values)<br> (VALUE keys_arr, int i, VALUE key, VALUE val) {<br> <b>Check_Type($input, T_HASH);</b><br>}<br></pre>
1702
 
                </div>
1703
 
                <p>
1704
 
                        <tt>Check_Type()</tt> is just a macro (defined in the Ruby header files) that 
1705
 
                        confirms that the input argument is of the correct type; if it isn't, an 
1706
 
                        exception will be raised.
1707
 
                </p>
1708
 
                <p>The next task is to determine how many key-value pairs are present in the hash; 
1709
 
                        we'll assign this number to the first typemap argument (<tt>$1</tt>). This is a 
1710
 
                        little tricky since the Ruby/C API doesn't provide a public function for 
1711
 
                        querying the size of a hash, but we can get around that by calling the hash's <i>size</i>
1712
 
                        method directly and converting its result to a C <tt>int</tt> value:
1713
 
                </p>
1714
 
                <div class="code">
1715
 
                        <pre>%typemap(in) (int nattributes, const char **names, const int *values)<br> (VALUE keys_arr, int i, VALUE key, VALUE val) {<br> Check_Type($input, T_HASH);<br> <b>$1 = NUM2INT(rb_funcall($input, rb_intern("size"), 0, NULL));</b><br>}<br></pre>
1716
 
                </div>
1717
 
                <p>
1718
 
                        So now we know the number of attributes. Next we need to initialize the second 
1719
 
                        and third typemap arguments (i.e. the two C arrays) to <tt>NULL</tt> and set 
1720
 
                        the stage for extracting the keys and values from the hash:
1721
 
                </p>
1722
 
                <div class="code">
1723
 
                        <pre>%typemap(in) (int nattributes, const char **names, const int *values)<br> (VALUE keys_arr, int i, VALUE key, VALUE val) {<br> Check_Type($input, T_HASH);<br> $1 = NUM2INT(rb_funcall($input, rb_intern("size"), 0, NULL));<br> <b>$2 = NULL;<br> $3 = NULL;<br> if ($1 &gt; 0) {<br> $2 = (char **) malloc($1*sizeof(char *));<br> $3 = (int *) malloc($1*sizeof(int));<br> }</b><br>}<br></pre>
1724
 
                </div>
1725
 
                <p>
1726
 
                        There are a number of ways we could extract the keys and values from the input 
1727
 
                        hash, but the simplest approach is to first call the hash's <i>keys</i> method 
1728
 
                        (which returns a Ruby array of the keys) and then start looping over the 
1729
 
                        elements in that array:
1730
 
                </p>
1731
 
                <div class="code">
1732
 
                        <pre>%typemap(in) (int nattributes, const char **names, const int *values)<br> (VALUE keys_arr, int i, VALUE key, VALUE val) {<br> Check_Type($input, T_HASH);<br> $1 = NUM2INT(rb_funcall($input, rb_intern("size"), 0, NULL));<br> $2 = NULL;<br> $3 = NULL;<br> if ($1 &gt; 0) {<br> $2 = (char **) malloc($1*sizeof(char *));<br> $3 = (int *) malloc($1*sizeof(int));<br> <b>keys_arr = rb_funcall($input, rb_intern("keys"), 0, NULL);<br> for (i = 0; i &lt; $1; i++) {<br> }</b><br>}<br>}<br></pre>
1733
 
                </div>
1734
 
                <p>
1735
 
                        Recall that <i>keys_arr</i> and <i>i</i> are local variables for this typemap. 
1736
 
                        For each element in the <i>keys_arr</i> array, we want to get the key itself, 
1737
 
                        as well as the value corresponding to that key in the hash:
1738
 
                </p>
1739
 
                <div class="code">
1740
 
                        <pre>%typemap(in) (int nattributes, const char **names, const int *values)<br> (VALUE keys_arr, int i, VALUE key, VALUE val) {<br> Check_Type($input, T_HASH);<br> $1 = NUM2INT(rb_funcall($input, rb_intern("size"), 0, NULL));<br> $2 = NULL;<br> $3 = NULL;<br> if ($1 &gt; 0) {<br> $2 = (char **) malloc($1*sizeof(char *));<br> $3 = (int *) malloc($1*sizeof(int));<br> keys_arr = rb_funcall($input, rb_intern("keys"), 0, NULL);<br> for (i = 0; i &lt; $1; i++) {<br> <b>key = rb_ary_entry(keys_arr, i);<br> val = rb_hash_aref($input, key);</b><br>}<br>}<br>}<br></pre>
1741
 
                </div>
1742
 
                <p>
1743
 
                        To be safe, we should again use the <tt>Check_Type()</tt> macro to confirm that 
1744
 
                        the key is a <tt>String</tt> and the value is a <tt>Fixnum</tt>:
1745
 
                </p>
1746
 
                <div class="code">
1747
 
                        <pre>%typemap(in) (int nattributes, const char **names, const int *values)<br> (VALUE keys_arr, int i, VALUE key, VALUE val) {<br> Check_Type($input, T_HASH);<br> $1 = NUM2INT(rb_funcall($input, rb_intern("size"), 0, NULL));<br> $2 = NULL;<br> $3 = NULL;<br> if ($1 &gt; 0) {<br> $2 = (char **) malloc($1*sizeof(char *));<br> $3 = (int *) malloc($1*sizeof(int));<br> keys_arr = rb_funcall($input, rb_intern("keys"), 0, NULL);<br> for (i = 0; i &lt; $1; i++) {<br> key = rb_ary_entry(keys_arr, i);<br> val = rb_hash_aref($input, key);<br> <b>Check_Type(key, T_STRING);<br> Check_Type(val, T_FIXNUM);</b><br>}<br>}<br>}<br></pre>
1748
 
                </div>
1749
 
                <p>
1750
 
                        Finally, we can convert these Ruby objects into their C equivalents and store 
1751
 
                        them in our local C arrays:
1752
 
                </p>
1753
 
                <div class="code">
1754
 
                        <pre>%typemap(in) (int nattributes, const char **names, const int *values)<br> (VALUE keys_arr, int i, VALUE key, VALUE val) {<br> Check_Type($input, T_HASH);<br> $1 = NUM2INT(rb_funcall($input, rb_intern("size"), 0, NULL));<br> $2 = NULL;<br> $3 = NULL;<br> if ($1 &gt; 0) {<br> $2 = (char **) malloc($1*sizeof(char *));<br> $3 = (int *) malloc($1*sizeof(int));<br> keys_arr = rb_funcall($input, rb_intern("keys"), 0, NULL);<br> for (i = 0; i &lt; $1; i++) {<br> key = rb_ary_entry(keys_arr, i);<br> val = rb_hash_aref($input, key);<br> Check_Type(key, T_STRING);<br> Check_Type(val, T_FIXNUM);<br> <b>$2[i] = STR2CSTR(key);<br> $3[i] = NUM2INT(val);</b><br>}<br>}<br>}<br></pre>
1755
 
                </div>
1756
 
                <p>
1757
 
                        We're not done yet. Since we used <tt>malloc()</tt> to dynamically allocate the 
1758
 
                        memory used for the <i>names</i> and <i>values</i> arguments, we need to 
1759
 
                        provide a corresponding "freearg" typemap to free that memory so that there is 
1760
 
                        no memory leak. Fortunately, this typemap is a lot easier to write:
1761
 
                </p>
1762
 
                <div class="code">
1763
 
                        <pre>%typemap(freearg) (int nattributes, const char **names, const int *values) {<br> free((void *) $2);<br> free((void *) $3);<br>}<br></pre>
1764
 
                </div>
1765
 
                <p>
1766
 
                        All of the code for this example, as well as a sample Ruby program that uses 
1767
 
                        the extension, can be found in the <tt>Examples/ruby/hashargs</tt> directory of 
1768
 
                        the SWIG distribution.
1769
 
                </p>
1770
 
<H3><a name="Ruby_nn50"></a>30.7.8 Pointer handling</H3>
1771
 
 
1772
 
 
1773
 
                <p>
1774
 
                        Occasionally, it might be necessary to convert pointer values that have been 
1775
 
                        stored using the SWIG typed-pointer representation. Since there are several 
1776
 
                        ways in which pointers can be represented, the following two functions are used 
1777
 
                        to safely perform this conversion:
1778
 
                </p>
1779
 
                <p><tt>int SWIG_ConvertPtr(VALUE obj, void **ptr, swig_type_info *ty, int flags)</tt>
1780
 
                </p>
1781
 
                <div class="indent">Converts a Ruby object <i>obj</i> to a C pointer whose address 
1782
 
                        is <i>ptr</i> (i.e. <i>ptr</i> is a pointer to a pointer). The third argument, <i>ty</i>, 
1783
 
                        is a pointer to a SWIG type descriptor structure. If <i>ty</i> is not <tt>NULL</tt>, 
1784
 
                        that type information is used to validate type compatibility and other aspects 
1785
 
                        of the type conversion. If <i>flags</i> is non-zero, any type errors 
1786
 
                        encountered during this validation result in a Ruby <tt>TypeError</tt> exception 
1787
 
                        being raised; if <i>flags</i> is zero, such type errors will cause <tt>SWIG_ConvertPtr()</tt>
1788
 
                        to return -1 but not raise an exception. If <i>ty</i> is <tt>NULL</tt>, no 
1789
 
                        type-checking is performed.
1790
 
                </div>
1791
 
                <p>
1792
 
                        <tt>VALUE SWIG_NewPointerObj(void *ptr, swig_type_info *ty, int own)</tt>
1793
 
                </p>
1794
 
                <div class="indent">Creates a new Ruby pointer object. Here, <i>ptr</i> is the 
1795
 
                        pointer to convert, <i>ty</i> is the SWIG type descriptor structure that 
1796
 
                        describes the type, and <i>own</i> is a flag that indicates whether or not Ruby 
1797
 
                        should take ownership of the pointer (i.e. whether Ruby should free this data 
1798
 
                        when the corresponding Ruby instance is garbage-collected).
1799
 
                </div>
1800
 
                <p>
1801
 
                        Both of these functions require the use of a special SWIG type-descriptor 
1802
 
                        structure. This structure contains information about the mangled name of the 
1803
 
                        datatype, type-equivalence information, as well as information about converting 
1804
 
                        pointer values under C++ inheritance. For a type of <tt>Foo *</tt>, the type 
1805
 
                        descriptor structure is usually accessed as follows:
1806
 
                </p>
1807
 
                <div class="indent">
1808
 
                        <pre>Foo *foo;<br>SWIG_ConvertPtr($input, (void **) &amp;foo, SWIGTYPE_p_Foo, 1);<br><br>VALUE obj;<br>obj = SWIG_NewPointerObj(f, SWIGTYPE_p_Foo, 0);<br></pre>
1809
 
                </div>
1810
 
                <p>
1811
 
                        In a typemap, the type descriptor should always be accessed using the special 
1812
 
                        typemap variable <tt>$1_descriptor</tt>. For example:
1813
 
                </p>
1814
 
                <div class="indent">
1815
 
                        <pre>%typemap(in) Foo * {<br> SWIG_ConvertPtr($input, (void **) &amp;$1, $1_descriptor, 1);<br>}<br></pre>
1816
 
                </div>
1817
 
<H4><a name="Ruby_nn51"></a>30.7.8.1 Ruby Datatype Wrapping</H4>
1818
 
 
1819
 
 
1820
 
                <p>
1821
 
                        <tt>VALUE Data_Wrap_Struct(VALUE class, void (*mark)(void *), void (*free)(void *), 
1822
 
                                void *ptr)</tt>
1823
 
                </p>
1824
 
                <div class="indent">Given a pointer <i>ptr</i> to some C data, and the two garbage 
1825
 
                        collection routines for this data (<i>mark</i> and <i>free</i>), return a <tt>VALUE</tt>
1826
 
                        for the Ruby object.
1827
 
                </div>
1828
 
                <p><tt>VALUE Data_Make_Struct(VALUE class, <i>c-type</i>, void (*mark)(void *), void 
1829
 
                                (*free)(void *), <i>c-type</i> *ptr)</tt></p>
1830
 
                <div class="indent">Allocates a new instance of a C data type <i>c-type</i>, 
1831
 
                        assigns it to the pointer <i>ptr</i>, then wraps that pointer with <tt>Data_Wrap_Struct()</tt>
1832
 
                        as above.
1833
 
                </div>
1834
 
                <p><tt>Data_Get_Struct(VALUE obj, <i>c-type</i>, <i>c-type</i> *ptr)</tt></p>
1835
 
                <div class="indent">Retrieves the original C pointer of type <i>c-type</i> from the 
1836
 
                        data object <i>obj</i> and assigns that pointer to <i>ptr</i>.
1837
 
                </div>
1838
 
<H3><a name="Ruby_nn52"></a>30.7.9 Example: STL Vector to Ruby Array</H3>
1839
 
 
1840
 
 
1841
 
    <p><em><b>FIXME: This example is out of place here!</b></em></p>
1842
 
    <p>Another use for macros and type maps is to create a Ruby array from a STL vector 
1843
 
                        of pointers. In essence, copy of all the pointers in the vector into a Ruby 
1844
 
                        array. The use of the macro is to make the typemap so generic that any vector 
1845
 
                        with pointers can use the type map. The following is an example of how to 
1846
 
                        construct this type of macro/typemap and should give insight into constructing 
1847
 
                        similar typemaps for other STL structures:
1848
 
        </p>
1849
 
                <div class="code">
1850
 
                        <pre>%define PTR_VECTOR_TO_RUBY_ARRAY(vectorclassname, classname)<br>%typemap(out) vectorclassname &amp;, const vectorclassname &amp; {<br> VALUE arr = rb_ary_new2($1-&gt;size());<br> vectorclassname::iterator i = $1-&gt;begin(), iend = $1-&gt;end();<br> for ( ; i!=iend; i++ )<br> rb_ary_push(arr, Data_Wrap_Struct(c ## classname.klass, 0, 0, *i));<br> $result = arr;<br>}<br>%typemap(out) vectorclassname, const vectorclassname {<br> VALUE arr = rb_ary_new2($1.size());<br> vectorclassname::iterator i = $1.begin(), iend = $1.end();<br> for ( ; i!=iend; i++ )<br> rb_ary_push(arr, Data_Wrap_Struct(c ## classname.klass, 0, 0, *i));<br> $result = arr;<br>}<br>%enddef<br></pre>
1851
 
                </div>
1852
 
                <p>
1853
 
                        Note, that the "<tt>c ## classname.klass"</tt> is used in the preprocessor step 
1854
 
                        to determine the actual object from the class name.
1855
 
                </p>
1856
 
                <p>To use the macro with a class Foo, the following is used:
1857
 
                </p>
1858
 
                <div class="code">
1859
 
                        <pre>PTR_VECTOR_TO_RUBY_ARRAY(vector&lt;foo *=""&gt;, Foo)<br></pre>
1860
 
                </div>
1861
 
                <p>
1862
 
                        It is also possible to create a STL vector of Ruby objects:
1863
 
                </p>
1864
 
                <div class="code">
1865
 
                        <pre>%define RUBY_ARRAY_TO_PTR_VECTOR(vectorclassname, classname)<br>%typemap(in) vectorclassname &amp;, const vectorclassname &amp; {<br> Check_Type($input, T_ARRAY);<br> vectorclassname *vec = new vectorclassname;<br> int len = RARRAY($input)-&gt;len;<br> for (int i=0; i!=len; i++) {<br> VALUE inst = rb_ary_entry($input, i);<br> //The following _should_ work but doesn't on HPUX<br> // Check_Type(inst, T_DATA);<br> classname *element = NULL;<br> Data_Get_Struct(inst, classname, element);<br> vec-&gt;push_back(element);<br> }<br> $1 = vec;<br>}<br><br>%typemap(freearg) vectorclassname &amp;, const vectorclassname &amp; {<br> delete $1;<br>}<br>%enddef<br></pre>
1866
 
                </div>
1867
 
                <p>
1868
 
                        It is also possible to create a Ruby array from a vector of static data types:
1869
 
                </p>
1870
 
                <div class="code">
1871
 
                        <pre>%define VECTOR_TO_RUBY_ARRAY(vectorclassname, classname)<br>%typemap(out) vectorclassname &amp;, const vectorclassname &amp; {<br> VALUE arr = rb_ary_new2($1-&gt;size()); <br> vectorclassname::iterator i = $1-&gt;begin(), iend = $1-&gt;end();<br> for ( ; i!=iend; i++ )<br> rb_ary_push(arr, Data_Wrap_Struct(c ## classname.klass, 0, 0, &amp;(*i)));<br> $result = arr;<br>}<br>%typemap(out) vectorclassname, const vectorclassname {<br> VALUE arr = rb_ary_new2($1.size()); <br> vectorclassname::iterator i = $1.begin(), iend = $1.end();<br> for ( ; i!=iend; i++ )<br> rb_ary_push(arr, Data_Wrap_Struct(c ## classname.klass, 0, 0, &amp;(*i)));<br> $result = arr;<br>}<br>%enddef<br></pre>
1872
 
                </div>
1873
 
 
1874
 
<H2><a name="Ruby_nn53"></a>30.8 Advanced Topics</H2>
1875
 
 
1876
 
 
1877
 
<H3><a name="Ruby_nn54"></a>30.8.1 Operator overloading</H3>
1878
 
 
1879
 
 
1880
 
<p>
1881
 
                        SWIG allows operator overloading with, by using the <tt>%extend</tt> or <tt>%rename</tt>
1882
 
                        commands in SWIG and the following operator names (derived from Python):
1883
 
        </p>
1884
 
                <div class="code">
1885
 
                        <pre><b> General</b> <br>__repr__ - inspect<br>__str__ - to_s<br>__cmp__ - &lt;=&gt;<br>__hash__ - hash<br>__nonzero__ - nonzero?<br><br><b> Callable</b> <br>__call__ - call<br><br><b> Collection</b> <br>__len__ - length<br>__getitem__ - []<br>__setitem__ - []=<br><br><b> Numeric</b> <br>__add__ - +<br>__sub__ - -<br>__mul__ - *<br>__div__ - /<br>__mod__ - %<br>__divmod__ - divmod<br>__pow__ - **<br>__lshift__ - &lt;&lt;<br>__rshift__ - &gt;&gt;<br>__and__ - &amp;<br>__xor__ - ^<br>__or__ - |<br>__neg__ - -@<br>__pos__ - +@<br>__abs__ - abs<br>__invert__ - ~<br>__int__ - to_i<br>__float__ - to_f<br>__coerce__ - coerce<br><br><b>Additions in 1.3.13 </b> <br>__lt__ - &lt; <br>__le__ - &lt;=<br>__eq__ - ==<br>__gt__ - &gt;<br>__ge__ - &gt;=<br><br></pre>
1886
 
                </div>
1887
 
                <p>
1888
 
                        Note that although SWIG supports the <tt>__eq__</tt> magic method name for 
1889
 
                        defining an equivalence operator, there is no separate method for handling <i>inequality</i>
1890
 
                        since Ruby parses the expression <i>a != b</i> as <i>!(a == b)</i>.
1891
 
                </p>
1892
 
<H3><a name="Ruby_nn55"></a>30.8.2 Creating Multi-Module Packages</H3>
1893
 
 
1894
 
 
1895
 
<p>
1896
 
                        The chapter on <a href="Modules.html">Working with Modules</a> discusses the 
1897
 
                        basics of creating multi-module extensions with SWIG, and in particular the 
1898
 
                        considerations for sharing runtime type information among the different 
1899
 
                        modules.
1900
 
        </p>
1901
 
                <p>As an example, consider one module's interface file (<tt>shape.i</tt>) that 
1902
 
                        defines our base class:
1903
 
                </p>
1904
 
                <div class="code">
1905
 
                        <pre>%module shape<br><br>%{<br>#include "Shape.h"<br>%}<br><br>class Shape {<br>protected:<br> double xpos;<br> double ypos;<br>protected:<br> Shape(double x, double y);<br>public:<br> double getX() const;<br> double getY() const;<br>};<br></pre>
1906
 
                </div>
1907
 
                <p>
1908
 
                        We also have a separate interface file (<tt>circle.i</tt>) that defines a 
1909
 
                        derived class:
1910
 
                </p>
1911
 
                <div class="code">
1912
 
                        <pre>%module circle<br><br>%{<br>#include "Shape.h"<br>#include "Circle.h"<br>%}<br><br>// Import the base class definition from Shape module<br>%import shape.i<br><br>class Circle : public Shape {<br>protected:<br> double radius;<br>public:<br> Circle(double x, double y, double r);<br> double getRadius() const;<br>};<br></pre>
1913
 
                </div>
1914
 
                <p>
1915
 
                        We'll start by building the <b>Shape</b> extension module:
1916
 
                </p>
1917
 
                <div class="code">
1918
 
                        <pre>$ <b>swig -c++ -ruby shape.i</b>
1919
 
</pre>
1920
 
                </div>
1921
 
                <p>
1922
 
                        SWIG generates a wrapper file named <tt>shape_wrap.cxx</tt>. To compile this 
1923
 
                        into a dynamically loadable extension for Ruby, prepare an <tt>extconf.rb</tt> script 
1924
 
                        using this template:
1925
 
                </p>
1926
 
                <div class="code">
1927
 
                        <pre>require 'mkmf'<br><br># Since the SWIG runtime support library for Ruby<br># depends on the Ruby library, make sure it's in the list<br># of libraries.<br>$libs = append_library($libs, Config::CONFIG['RUBY_INSTALL_NAME'])<br><br># Create the makefile<br>create_makefile('shape')<br></pre>
1928
 
                </div>
1929
 
                <p>
1930
 
                        Run this script to create a <tt>Makefile</tt> and then type <tt>make</tt> to 
1931
 
                        build the shared library:
1932
 
                </p>
1933
 
                <div class="code">
1934
 
                        <pre>$ <b>ruby extconf.rb</b><br>creating Makefile<br>$ <b>make</b><br>g++ -fPIC -g -O2 -I. -I/usr/local/lib/ruby/1.7/i686-linux \<br>-I. -c shape_wrap.cxx<br>gcc -shared -L/usr/local/lib -o shape.so shape_wrap.o -L. \<br>-lruby -lruby -lc<br></pre>
1935
 
                </div>
1936
 
                <p>
1937
 
                        Note that depending on your installation, the outputs may be slightly 
1938
 
                        different; these outputs are those for a Linux-based development environment. 
1939
 
                        The end result should be a shared library (here, <tt>shape.so</tt>) containing 
1940
 
                        the extension module code. Now repeat this process in a separate directory for 
1941
 
                        the <b>Circle</b> module:
1942
 
                </p>
1943
 
                <ol>
1944
 
                        <li>
1945
 
                                Run SWIG to generate the wrapper code (<tt>circle_wrap.cxx</tt>);
1946
 
                        </li>
1947
 
                        <li>
1948
 
                                Write an <tt>extconf.rb</tt> script that your end-users can use to create a 
1949
 
                                platform-specific <tt>Makefile</tt> for the extension;
1950
 
                        </li>
1951
 
                        <li>
1952
 
                                Build the shared library for this extension by typing <tt>make</tt>.
1953
 
                        </li>
1954
 
                </ol>
1955
 
                <p>
1956
 
                        Once you've built both of these extension modules, you can test them 
1957
 
                        interactively in IRB to confirm that the <tt>Shape</tt> and <tt>Circle</tt> modules 
1958
 
                        are properly loaded and initialized:
1959
 
                </p>
1960
 
                <div class="code">
1961
 
                        <pre>$ <b>irb</b><br>irb(main):001:0&gt; <b>require 'shape'</b><br>true<br>irb(main):002:0&gt; <b>require 'circle'</b><br>true<br>irb(main):003:0&gt; <b>c = Circle::Circle.new(5, 5, 20)</b><br>#&lt;Circle::Circle:0xa097208&gt;<br>irb(main):004:0&gt; <b>c.kind_of? Shape::Shape</b><br>true<br>irb(main):005:0&gt; <b>c.getX()</b><br>5.0<br></pre>
1962
 
                </div>
1963
 
 
1964
 
<H3><a name="Ruby_nn56"></a>30.8.3 Specifying Mixin Modules</H3>
1965
 
 
1966
 
 
1967
 
                <p>
1968
 
                        The Ruby language doesn't support multiple inheritance, but it does allow you 
1969
 
                        to mix one or more modules into a class using Ruby's <tt>include</tt> method. 
1970
 
                        For example, if you have a Ruby class that defines an <em>each</em> instance 
1971
 
                        method, e.g.
1972
 
                </p>
1973
 
                <div class="code">
1974
 
                        <pre>class Set<br> def initialize<br> @members = []<br> end<br> <br> def each<br> @members.each { |m| yield m }<br> end<br>end<br></pre>
1975
 
                </div>
1976
 
                <p>
1977
 
                        then you can mix-in Ruby's <tt>Enumerable</tt> module to easily add a lot of 
1978
 
                        functionality to your class:
1979
 
                </p>
1980
 
                <div class="code">
1981
 
                        <pre>class Set<br> <b>include Enumerable</b><br>def initialize<br>@members = []<br>end<br>def each<br>@members.each { |m| yield m }<br>end<br>end<br></pre>
1982
 
                </div>
1983
 
                <p>
1984
 
                        To get the same benefit for your SWIG-wrapped classes, you can use the <tt>%mixin</tt>
1985
 
                        directive to specify the names of one or more modules that should be mixed-in 
1986
 
                        to a class. For the above example, the SWIG interface specification might look 
1987
 
                        like this:
1988
 
                </p>
1989
 
                <div class="code">
1990
 
                        <pre>%mixin Set "Enumerable";<br><br>class Set {<br>public:<br> // Constructor<br> Set();<br> <br> // Iterates through set members<br> void each();<br>};<br></pre>
1991
 
                </div>
1992
 
                <p>
1993
 
                        Multiple modules can be mixed into a class by providing a comma-separated list 
1994
 
                        of module names to the <tt>%mixin</tt> directive, e.g.
1995
 
                </p>
1996
 
                <div class="code">
1997
 
                        <pre>%mixin Set "Fee,Fi,Fo,Fum";</pre>
1998
 
                </div>
1999
 
                <p>
2000
 
                        Note that the <tt>%mixin</tt> directive is implemented using SWIG's "features" 
2001
 
                        mechanism and so the same name matching rules used for other kinds of features 
2002
 
                        apply (see the chapter on <a href="Customization.html#Customization">"Customization 
2003
 
                                Features"</a>) for more details).
2004
 
                </p>
2005
 
<H2><a name="Ruby_nn57"></a>30.9 Memory Management</H2>
2006
 
 
2007
 
 
2008
 
                <p>One of the most common issues in generating SWIG bindings for Ruby is proper 
2009
 
                        memory management. The key to proper memory management is clearly defining 
2010
 
                        whether a wrapper Ruby object owns the underlying C struct or C++ class. There 
2011
 
                        are two possibilities:</p>
2012
 
                <ul>
2013
 
                        <li>
2014
 
                                The Ruby object is responsible for freeing the C struct or C++ object
2015
 
                        </li>
2016
 
                        <li>
2017
 
                                The Ruby object should not free the C struct or C++ object because it will be 
2018
 
                                freed by the underlying C or C++ code</li>
2019
 
                </ul>
2020
 
                <p>To complicate matters, object ownership may transfer from Ruby to C++ (or vice 
2021
 
                        versa) depending on what function or methods are invoked. Clearly, developing a 
2022
 
                        SWIG wrapper requires a thorough understanding of how the underlying library 
2023
 
                        manages memory.</p>
2024
 
<H3><a name="Ruby_nn58"></a>30.9.1 Mark and Sweep Garbage Collector             </H3>
2025
 
 
2026
 
 
2027
 
                <p>Ruby uses a mark and sweep garbage collector. When the garbage collector runs, 
2028
 
                        it finds all the "root" objects, including local variables, global variables, 
2029
 
                        global constants, hardware registers and the C stack. For each root object, the 
2030
 
                        garbage collector sets its mark flag to true and calls <tt>rb_gc_mark</tt> on 
2031
 
                        the object. The job of <tt>rb_gc_mark</tt> is to recursively mark all the 
2032
 
                        objects that a Ruby object has a reference to (ignoring those objects that have 
2033
 
                        already been marked). Those objects, in turn, may reference other objects. This 
2034
 
                        process will continue until all active objects have been "marked." After the 
2035
 
                        mark phase comes the sweep phase. In the sweep phase, all objects that have not 
2036
 
                        been marked will be garbage collected. For more information about the Ruby 
2037
 
                        garbage collector please refer to <a href="http://rubygarden.org/ruby/ruby?GCAndExtensions">
2038
 
                                <span style="text-decoration: underline;">http://rubygarden.org/ruby/ruby?GCAndExtensions</span></a>.</p>
2039
 
                <p>The Ruby C/API provides extension developers two hooks into the garbage 
2040
 
                        collector - a "mark" function and a "sweep" function. By default these functions 
2041
 
                        are set to NULL.</p>
2042
 
                <p>If a C struct or C++ class references any other Ruby objects, then it must 
2043
 
                        provide a "mark" function. The "mark" function should identify any referenced 
2044
 
                        Ruby objects by calling the rb_gc_mark function for each one. Unsurprisingly, 
2045
 
                        this function will be called by the Ruby garbage during the "mark" phase.</p>
2046
 
                <p>During the sweep phase, Ruby destroys any unused objects. If any memory has been 
2047
 
                        allocated in creating the underlying C struct or C++ struct, then a "free" 
2048
 
                        function must be defined that deallocates this memory.
2049
 
                </p>
2050
 
<H3><a name="Ruby_nn59"></a>30.9.2 Object Ownership</H3>
2051
 
 
2052
 
 
2053
 
                <p>As described above, memory management depends on clearly defining who is 
2054
 
                        responsible for freeing the underlying C struct or C++ class. If the Ruby 
2055
 
                        object is responsible for freeing the C++ object, then a "free" function must 
2056
 
                        be registered for the object. If the Ruby object is not responsible for freeing 
2057
 
                        the underlying memory, then a "free" function must not be registered for the 
2058
 
                        object.</p>
2059
 
                <p>For the most part, SWIG takes care of memory management issues. The rules it 
2060
 
                        uses are:</p>
2061
 
                <ul>
2062
 
                        <li>
2063
 
                                When calling a C++ object's constructor from Ruby, SWIG will assign a "free" 
2064
 
                                function thereby making the Ruby object responsible for freeing the C++ object</li>
2065
 
                        <li>
2066
 
                                When calling a C++ member function that returns a pointer, SWIG will not assign 
2067
 
                                a "free" function thereby making the underlying library responsible for freeing 
2068
 
                                the object.</li>
2069
 
                </ul>
2070
 
                <p>To make this clearer, let's look at an example. Assume we have a Foo and a Bar 
2071
 
                        class.
2072
 
                </p>
2073
 
                <div class="code">
2074
 
                        <pre>/* File "RubyOwernshipExample.h" */<br><br>class Foo<br>{<br>public:<br> Foo() {}<br> ~Foo() {}<br>};<br><br>class Bar<br>{<br> Foo *foo_;<br>public:<br> Bar(): foo_(new Foo) {}<br> ~Bar() { delete foo_; }<br> Foo* get_foo() { return foo_; }<br> Foo* get_new_foo() { return new Foo; }<br> void set_foo(Foo *foo) { delete foo_; foo_ = foo; }<br>};<br>
2075
 
</pre>
2076
 
                </div>
2077
 
                <p>First, consider this Ruby code:
2078
 
                </p>
2079
 
                <div class="code">
2080
 
                        <pre>foo = Foo.new</pre>
2081
 
                </div>
2082
 
                <p>In this case, the Ruby code calls the underlying <tt>Foo</tt> C++ constructor, 
2083
 
                        thus creating a new <tt>foo</tt> object. By default, SWIG will assign the new 
2084
 
                        Ruby object a "free" function. When the Ruby object is garbage collected, the 
2085
 
                        "free" function will be called. It in turn will call <tt>Foo's</tt> destructor.</p>
2086
 
                <p>Next, consider this code:
2087
 
                </p>
2088
 
                <div class="code">
2089
 
                        <pre>bar = Bar.new<br>foo = bar.get_foo()</pre>
2090
 
                </div>
2091
 
                <p>In this case, the Ruby code calls a C++ member function, <tt>get_foo</tt>. By 
2092
 
                        default, SWIG will not assign the Ruby object a "free" function. Thus, when the 
2093
 
                        Ruby object is garbage collected the underlying C++ <tt>foo</tt> object is not 
2094
 
                        affected.</p>
2095
 
                <p>Unfortunately, the real world is not as simple as the examples above. For 
2096
 
                        example:</p>
2097
 
                <div class="code">
2098
 
                        <pre>bar = Bar.new<br>foo = bar.get_new_foo()</pre>
2099
 
                </div>
2100
 
                <p>In this case, the default SWIG behavior for calling member functions is 
2101
 
                        incorrect. The Ruby object should assume ownership of the returned object. This 
2102
 
                        can be done by using the %newobject directive. See <a href="file:///d:/msys/1.0/src/SWIG/Doc/Manual/Customization.html#ownership">
2103
 
                                Object ownership and %newobject</a> for more information.
2104
 
                </p>
2105
 
                <p>The SWIG default mappings are also incorrect in this case:</p>
2106
 
                <div class="code">
2107
 
                        <pre>foo = Foo.new<br>bar = Bar.new<br>bar.set_foo(foo)</pre>
2108
 
                </div>
2109
 
                <p>Without modification, this code will cause a segmentation fault. When the Ruby <tt>foo</tt>
2110
 
                        object goes out of scope, it will free the underlying C++ <tt>foo</tt> object. 
2111
 
                        However, when the Ruby bar object goes out of scope, it will call the C++ bar 
2112
 
                        destructor which will also free the C++ <tt>foo</tt> object. The problem is 
2113
 
                        that object ownership is transferred from the Ruby object to the C++ object 
2114
 
                        when the <tt>set_foo</tt> method is called. This can be done by using the 
2115
 
                        special DISOWN type map, which was added to the Ruby bindings in SWIG-1.3.26.</p>
2116
 
                <p>Thus, a correct SWIG interface file correct mapping for these classes is:</p>
2117
 
                <div class="code">
2118
 
                        <pre>/* File RubyOwnershipExample.i */<br><br>%module RubyOwnershipExample<br><br>%{<br>#include "RubyOwnershipExample.h"<br>%}<br><br>class Foo<br>{<br>public:<br> Foo();<br> ~Foo();<br>};<br><br>class Bar<br>{<br> Foo *foo_;<br>public:<br> Bar();<br> ~Bar();<br> Foo* get_foo();<br><br><span style="font-weight: bold;"> %newobject get_new_foo;</span><br> Foo* get_new_foo();<br><br><span style="font-weight: bold;"> %apply SWIGTYPE *DISOWN {Foo *foo};</span><br> void set_foo(Foo *foo);<br><span style="font-weight: bold;"> %clear Foo *foo;</span><br>};<br>
2119
 
</pre>
2120
 
                </div>
2121
 
                <br>
2122
 
                <p>
2123
 
                        This code can be seen in swig/examples/ruby/tracking.</p>
2124
 
                <br>
2125
 
<H3><a name="Ruby_nn60"></a>30.9.3 Object Tracking</H3>
2126
 
 
2127
 
 
2128
 
                <p>The remaining parts of this section will use the class library shown below to 
2129
 
                        illustrate different memory management techniques. The class library models a 
2130
 
                        zoo and the animals it contains.
2131
 
                </p>
2132
 
                <div class="code">
2133
 
                        <pre>%module zoo<br><br>%{<br>#include &lt;string&gt;<br>#include &lt;vector&gt;<br><br>#include "zoo.h"<br>%}<br><br>class Animal<br>{<br>private:<br> typedef std::vector&lt;Animal*&gt; AnimalsType;<br> typedef AnimalsType::iterator IterType;<br>protected:<br> AnimalsType animals;<br>protected:<br> std::string name_;<br>public:<br> // Construct an animal with this name<br> Animal(const char* name) : name_(name) {}<br> <br> // Return the animal's name<br> const char* get_name() const { return name.c_str(); }<br>};<br><br>class Zoo<br>{<br>protected:<br> std::vector&lt;animal *=""&gt; animals;<br> <br>public:<br> // Construct an empty zoo<br> Zoo() {}<br> <br> /* Create a new animal. */<br> static Animal* Zoo::create_animal(const char* name)<br> {<br> return new Animal(name);<br> }<br><br> // Add a new animal to the zoo<br> void add_animal(Animal* animal) {<br> animals.push_back(animal); <br> }<br><br> Animal* remove_animal(size_t i) {<br> Animal* result = this-&gt;animals[i];<br> IterType iter = this-&gt;animals.begin();<br> std::advance(iter, i);<br> this-&gt;animals.erase(iter);<br><br> return result;<br> }<br> <br> // Return the number of animals in the zoo<br> size_t get_num_animals() const {<br> return animals.size(); <br> }<br> <br> // Return a pointer to the ith animal<br> Animal* get_animal(size_t i) const {<br> return animals[i]; <br> }<br>};<br>
2134
 
</pre>
2135
 
                </div>
2136
 
                <p>Let's say you SWIG this code and then run IRB:<br>
2137
 
                </p>
2138
 
                <div class="code">
2139
 
                        <pre>$ <span style="font-weight: bold;">irb</span><br>irb(main):001:0&gt; <span style="font-weight: bold;">require 'example'</span><br>=&gt; true<br><br>irb(main):002:0&gt; <span style="font-weight: bold;">tiger1 = Example::Animal.new("tiger1")</span><br>=&gt; #&lt;Example::Animal:0x2be3820&gt;<br><br>irb(main):004:0&gt; <span style="font-weight: bold;">tiger1.get_name()</span><br>=&gt; "tiger1"<br><br>irb(main):003:0&gt; <span style="font-weight: bold;">zoo = Example::Zoo.new()</span><br>=&gt; #&lt;Example::Zoo:0x2be0a60&gt;<br><br>irb(main):006:0&gt; <span style="font-weight: bold;">zoo.add_animal(tiger)</span><br>=&gt; nil<br><br>irb(main):007:0&gt; <span style="font-weight: bold;">zoo.get_num_animals()</span><br>=&gt; 1<br><br>irb(main):007:0&gt; <span style="font-weight: bold;">tiger2 = zoo.remove_animal(0)</span><br>=&gt; #&lt;Example::Animal:0x2bd4a18&gt;<br><br>irb(main):008:0&gt; <span style="font-weight: bold;">tiger2.get_name()</span><br>=&gt; "tiger1"<br><br>irb(main):009:0&gt; <span style="font-weight: bold;">tiger1.equal?(tiger2)</span><br>=&gt; false<br>
2140
 
</pre>
2141
 
                </div>
2142
 
                <p>Pay particular attention to the code <tt>tiger1.equal?(tiger2)</tt>. Note that 
2143
 
                        the two Ruby objects are not the same - but they reference the same underlying 
2144
 
                        C++ object. This can cause problems. For example:<br>
2145
 
                </p>
2146
 
                <div class="code">
2147
 
                        <pre>irb(main):010:0&gt; <span style="font-weight: bold;">tiger1 = nil</span><br>=&gt; nil<br><br>irb(main):011:0&gt; <span style="font-weight: bold;">GC.start</span><br>=&gt; nil<br><br>irb(main):012:0&gt; <span style="font-weight: bold;">tiger2.get_name()</span><br>(irb):12: [BUG] Segmentation fault<br>
2148
 
</pre>
2149
 
                </div>
2150
 
                <p>After the the garbage collector runs, as a result of our call to <tt>GC.start</tt>, 
2151
 
                        calling<tt>tiger2.get_name()</tt> causes a segmentation fault. The problem is 
2152
 
                        that when <tt>tiger1</tt> is garbage collected, it frees the underlying C++ 
2153
 
                        object. Thus, when <tt>tiger2</tt> calls the <tt>get_name()</tt> method it 
2154
 
                        invokes it on a destroyed object.</p>
2155
 
                <p>This problem can be avoided if SWIG enforces a one-to-one mapping between Ruby 
2156
 
                        objects and C++ classes. This can be done via the use of the <tt>%trackobjects</tt>
2157
 
                        functionality available in SWIG-1.3.26. and later.</p>
2158
 
                <p>When the <tt>%trackobjects</tt> is turned on, SWIG automatically keeps track of 
2159
 
                        mappings between C++ objects and Ruby objects. Note that enabling object 
2160
 
                        tracking causes a slight performance degradation. Test results show this 
2161
 
                        degradation to be about 3% to 5% when creating and destroying 100,000 animals 
2162
 
                        in a row.</p>
2163
 
                <p>Since <tt>%trackobjects</tt> is implemented as a <tt>%feature</tt>, it uses the same name matching 
2164
 
                        rules as other kinds of features (see the chapter on <a href="Customization.html#Customization">
2165
 
                                "Customization Features"</a>) . Thus it can be applied on a class-by-class 
2166
 
                        basis if needed. To fix the example above:</p>
2167
 
                <br>
2168
 
                <div class="code">
2169
 
                        <pre>%module example<br><br>%{<br>#include "example.h"<br>%}<br><br><span style="font-weight: bold;">/* Tell SWIG that create_animal creates a new object */</span><br><span style="font-weight: bold;">%newobject Zoo::create_animal;</span><br><br><span style="font-weight: bold;">/* Tell SWIG to keep track of mappings between C/C++ structs/classes. */</span><br style="font-weight: bold;"><span style="font-weight: bold;">%trackobjects;</span><br><br>%include "example.h"</pre>
2170
 
                </div>
2171
 
                <p>When this code runs we see:<br>
2172
 
                        <br>
2173
 
                </p>
2174
 
                <div class="code">
2175
 
                        <pre>$ <span style="font-weight: bold;">irb</span><br>irb(main):001:0&gt; <span style="font-weight: bold;">require 'example'</span><br>=&gt; true<br><br>irb(main):002:0&gt; <span style="font-weight: bold;">tiger1 = Example::Animal.new("tiger1")</span><br>=&gt; #&lt;Example::Animal:0x2be37d8&gt;<br><br>irb(main):003:0&gt; <span style="font-weight: bold;">zoo = Example::Zoo.new()</span><br>=&gt; #&lt;Example::Zoo:0x2be0a18&gt;<br><br>irb(main):004:0&gt; <span style="font-weight: bold;">zoo.add_animal(tiger1)</span><br>=&gt; nil<br><br>irb(main):006:0&gt; <span style="font-weight: bold;">tiger2 = zoo.remove_animal(0)</span><br>=&gt; #&lt;Example::Animal:0x2be37d8&gt;<br><br>irb(main):007:0&gt; <span style="font-weight: bold;">tiger1.equal?(tiger2)</span><br>=&gt; true<br><br>irb(main):008:0&gt; <span style="font-weight: bold;">tiger1 = nil</span><br>=&gt; nil<br><br>irb(main):009:0&gt; <span style="font-weight: bold;">GC.start</span><br>=&gt; nil<br><br>irb(main):010:0&gt; <span style="font-weight: bold;">tiger.get_name()</span><br>=&gt; "tiger1"<br>irb(main):011:0&gt;<br>
2176
 
</pre>
2177
 
                </div>
2178
 
                <p>For those who are interested, object tracking is implemented by storing Ruby 
2179
 
                        objects in a hash table and keying them on C++ pointers. The underlying API is:<br>
2180
 
                </p>
2181
 
                <div class="code">
2182
 
                        <pre>static void SWIG_RubyAddTracking(void* ptr, VALUE object);<br>static VALUE SWIG_RubyInstanceFor(void* ptr) ;<br>static void SWIG_RubyRemoveTracking(void* ptr);<br>static void SWIG_RubyUnlinkObjects(void* ptr);</pre>
2183
 
                </div>
2184
 
                <p>When an object is created, SWIG will automatically call the <tt>SWIG_RubyAddTracking</tt>
2185
 
                        method. Similarly, when an object is deleted, SWIG will call the <tt>SWIG_RubyRemoveTracking</tt>. 
2186
 
                        When an object is returned to Ruby from C++, SWIG will use the <tt>SWIG_RubyInstanceFor</tt>
2187
 
                        method to ensure a one-to-one mapping from Ruby to C++ objects. Last, the <tt>RubyUnlinkObjects</tt>
2188
 
                        method unlinks a Ruby object from its underlying C++ object.</p>
2189
 
                <p>In general, you will only need to use the <tt>SWIG_RubyInstanceFor</tt>, which 
2190
 
                        is required for implementing mark functions as shown below. However, if you 
2191
 
                        implement your own free functions (see below) you may also have to call the<tt>SWIG_RubyRemoveTracking</tt>
2192
 
                        and <tt>RubyUnlinkObjects</tt> methods.</p>
2193
 
 
2194
 
<H3><a name="Ruby_nn61"></a>30.9.4 Mark Functions</H3>
2195
 
 
2196
 
 
2197
 
                <p>With a bit more testing, we see that our class library still has problems. For 
2198
 
                        example:<br>
2199
 
                </p>
2200
 
                <div class="code">
2201
 
                        <pre>$ <b>irb</b><br>irb(main):001:0&gt; <span style="font-weight: bold;">require 'example'</span><br>=&gt; true<br><br>irb(main):002:0&gt; tiger1 = <span style="font-weight: bold;">Example::Animal.new("tiger1")</span><br>=&gt; #&lt;Example::Animal:0x2bea6a8&gt;<br><br>irb(main):003:0&gt; zoo = <span style="font-weight: bold;">Example::Zoo.new()</span><br>=&gt; #&lt;Example::Zoo:0x2be7960&gt;<br><br>irb(main):004:0&gt; <span style="font-weight: bold;">zoo.add_animal(tiger1)</span><br>=&gt; nil<br><br>irb(main):007:0&gt; <span style="font-weight: bold;">tiger1 = nil</span><br>=&gt; nil<br><br>irb(main):007:0&gt; <span style="font-weight: bold;">GC.start</span><br>=&gt; nil<br><br>irb(main):005:0&gt; <span style="font-weight: bold;">tiger2 = zoo.get_animal(0)</span><br>(irb):12: [BUG] Segmentation fault</pre>
2202
 
                </div>
2203
 
                <p>The problem is that Ruby does not know that the <tt>zoo</tt> object contains a 
2204
 
                        reference to a Ruby object. Thus, when Ruby garbage collects
2205
 
                        <span style="font-family: monospace;">tiger1</span>
2206
 
                        it frees the underlying C++ object.</p>
2207
 
                <p>This can be fixed by implementing a
2208
 
                        <tt>mark</tt> function as described above in the <a href="Ruby.html#Ruby_nn52">Mark and Sweep Garbage 
2209
 
                                Collector</a> section. You can specify a mark function by using the <tt>%markfunc</tt>
2210
 
                        directive. Since the <tt>%markfunc</tt> directive is implemented using SWIG's' 
2211
 
                        "features" mechanism it uses the same name matching rules as other kinds of 
2212
 
                        features (see the chapter on <a href="Customization.html#Customization">"Customization 
2213
 
                                Features"</a> for more details).
2214
 
                </p>
2215
 
                <p>A <tt>mark</tt> function takes a single argument, which is a pointer to the C++ 
2216
 
                        object being marked; it should, in turn, call <tt>rb_gc_mark()</tt> for any 
2217
 
                        instances that are reachable from the current object. The mark function for our <tt>
2218
 
                                Zoo</tt> class should therefore loop over all of the C++ animal objects in 
2219
 
                        the zoo object, look up their Ruby object equivalent, and then call <tt>rb_gc_mark()</tt>. 
2220
 
                        One possible implementation is:</p>
2221
 
                <div class="code">
2222
 
                        <pre>%module example<br><br>%{<br>#include "example.h"<br>%}<br><br>/* Keep track of mappings between C/C++ structs/classes<br> and Ruby objects so we can implement a mark function. */<br><span style="font-weight: bold;">%trackobjects;</span><br><br>/* Specify the mark function */<br><span style="font-weight: bold;">%markfunc Zoo "mark_Zoo";</span><br><br>%include "example.h"<br><br>%header %{<br><br>static void mark_Zoo(void* ptr) {<br> Zoo* zoo = (Zoo*) ptr;<br><br> /* Loop over each object and tell the garbage collector<br> that we are holding a reference to them. */<br> int count = zoo-&gt;get_num_animals();<br><br> for(int i = 0; i &lt; count; ++i) {<br>   Animal* animal = zoo-&gt;get_animal(i);<br>   VALUE object = SWIG_RubyInstanceFor(animal);<br><br>   if (object != Qnil) {<br>     rb_gc_mark(object);<br>   }<br> }<br>}<br>%}<br>
2223
 
</pre>
2224
 
                </div>
2225
 
                <p>
2226
 
                        Note the <tt>mark</tt> function is dependent on the <tt>SWIG_RUBY_InstanceFor</tt>
2227
 
                        method, and thus requires that <tt>%trackobjects</tt>
2228
 
                        is enabled. For more information, please refer to the track_object.i test case in the SWIG test suite.</p>
2229
 
                <p>When this code is compiled we now see:</p>
2230
 
                <div class="code">
2231
 
                        <pre>$ <b>irb<br></b>irb(main):002:0&gt; <span style="font-weight: bold;">tiger1=Example::Animal.new("tiger1")</span><br>=&gt; #&lt;Example::Animal:0x2be3bf8&gt;<br><br>irb(main):003:0&gt; <span style="font-weight: bold;">Example::Zoo.new()</span><br>=&gt; #&lt;Example::Zoo:0x2be1780&gt;<br><br>irb(main):004:0&gt; <span style="font-weight: bold;">zoo = Example::Zoo.new()</span><br>=&gt; #&lt;Example::Zoo:0x2bde9c0&gt;<br><br>irb(main):005:0&gt; <span style="font-weight: bold;">zoo.add_animal(tiger1)</span><br>=&gt; nil<br><br>irb(main):009:0&gt; <span style="font-weight: bold;">tiger1 = nil</span><br>=&gt; nil<br><br>irb(main):010:0&gt; <span style="font-weight: bold;">GC.start</span><br>=&gt; nil<br>irb(main):014:0&gt; <span style="font-weight: bold;">tiger2 = zoo.get_animal(0)</span><br>=&gt; #&lt;Example::Animal:0x2be3bf8&gt;<br><br>irb(main):015:0&gt; <span style="font-weight: bold;">tiger2.get_name()</span><br>=&gt; "tiger1"<br>irb(main):016:0&gt;<br>
2232
 
</pre>
2233
 
                </div>
2234
 
                <br>
2235
 
                <p>This code can be seen in swig/examples/ruby/mark_function.</p>
2236
 
<H3><a name="Ruby_nn62"></a>30.9.5 Free Functions</H3>
2237
 
 
2238
 
 
2239
 
                <p>By default, SWIG creates a "free" function that is called when a Ruby object is 
2240
 
                        garbage collected. The free function simply calls the C++ object's destructor.</p>
2241
 
                <p>However, sometimes an appropriate destructor does not exist or special 
2242
 
                        processing needs to be performed before the destructor is called. Therefore, 
2243
 
                        SWIG allows you to manually specify a "free" function via the use of the <tt>%freefunc</tt>
2244
 
                        directive. The <tt>%freefunc</tt> directive is implemented using SWIG's' 
2245
 
                        "features" mechanism and so the same name matching rules used for other kinds 
2246
 
                        of features apply (see the chapter on <a href="Customization.html#Customization">"Customization 
2247
 
                                Features"</a>) for more details).</p>
2248
 
                <p>IMPORTANT ! - If you define your own free function, then you must ensure that 
2249
 
                        you call the underlying C++ object's destructor. In addition, if object 
2250
 
                        tracking is activated for the object's class, you must also call the <tt>SWIG_RubyRemoveTracking</tt>
2251
 
                        function (of course call this before you destroy the C++ object). Note that it 
2252
 
                        is harmless to call this method if object tracking if off so it is advised to 
2253
 
                        always call it.</p>
2254
 
                <p>Note there is a subtle interaction between object ownership and free functions. 
2255
 
                        A custom defined free function will only be called if the Ruby object owns the 
2256
 
                        underlying C++ object. This also to Ruby objects which are created, but then 
2257
 
                        transfer ownership to C++ objects via the use of the <tt>disown</tt> typemap 
2258
 
                        described above.
2259
 
                </p>
2260
 
                <p>To show how to use the <tt>%freefunc</tt> directive, let's slightly change our 
2261
 
                        example. Assume that the zoo object is responsible for freeing animal that it 
2262
 
                        contains. This means that the
2263
 
                        <span style="font-family: monospace;">Zoo::add_animal</span>
2264
 
                        function should be marked with a
2265
 
                        <span style="font-family: monospace;">DISOWN</span>
2266
 
                        typemap and the destructor should be updated as below::</p>
2267
 
                <div class="code">
2268
 
                        <pre>Zoo::~Zoo() {<br> IterType iter = this-&gt;animals.begin();<br> IterType end = this-&gt;animals.end();<br><br> for(iter; iter != end; ++iter) {<br> Animal* animal = *iter;<br> delete animal;<br> }<br>}</pre>
2269
 
                </div>
2270
 
                <p>When we use these objects in IRB we see:</p>
2271
 
                <div class="code">
2272
 
                        <pre><span style="font-weight: bold;">$irb</span><br>irb(main):002:0&gt; <span style="font-weight: bold;">require 'example'</span><br>=&gt; true<br><br>irb(main):003:0&gt; <span style="font-weight: bold;">zoo = Example::Zoo.new()</span><br>=&gt; #&lt;Example::Zoo:0x2be0fe8&gt;<br><br>irb(main):005:0&gt; <span style="font-weight: bold;">tiger1 = Example::Animal.new("tiger1")</span><br>=&gt; #&lt;Example::Animal:0x2bda760&gt;<br><br>irb(main):006:0&gt; <span style="font-weight: bold;">zoo.add_animal(tiger1)</span><br>=&gt; nil<br><br>irb(main):007:0&gt; <span style="font-weight: bold;">zoo = nil</span><br>=&gt; nil<br><br>irb(main):008:0&gt; <span style="font-weight: bold;">GC.start</span><br>=&gt; nil<br><br>irb(main):009:0&gt; <span style="font-weight: bold;">tiger1.get_name()</span><br>(irb):12: [BUG] Segmentation fault<br>
2273
 
                </pre>
2274
 
                </div>
2275
 
                <p>The error happens because the C++ <tt>animal</tt> object is freed when the <tt>zoo</tt>
2276
 
                        object is freed. Although this error is unavoidable, we can at least prevent 
2277
 
                        the segmentation fault. To do this requires enabling object tracking and 
2278
 
                        implementing a custom free function that calls the <tt>SWIG_RubyUnlinkObjects</tt>
2279
 
                        function for each animal object that is destroyed. The <tt>SWIG_RubyUnlinkObjects</tt>
2280
 
                        function notifies SWIG that a Ruby object's underlying C++ object is no longer 
2281
 
                        valid. Once notified, SWIG will intercept any calls from the existing Ruby 
2282
 
                        object to the destroyed C++ object and raise an exception.<br>
2283
 
                </p>
2284
 
                <div class="code">
2285
 
                        <pre>%module example<br><br>%{<br>#include "example.h"<br>%}<br><br>/* Specify that ownership is transferred to the zoo<br>     when calling add_animal */<br>%apply SWIGTYPE *DISOWN { Animal* animal };<br><br>/* Track objects */<br>%trackobjects;<br><br>/* Specify the mark function */<br>%freefunc Zoo "free_Zoo";<br><br>%include "example.h"<br><br>%header %{<br> static void free_Zoo(void* ptr) {<br> Zoo* zoo = (Zoo*) ptr;<br><br> /* Loop over each animal */<br> int count = zoo-&gt;get_num_animals();<br><br> for(int i = 0; i &lt; count; ++i) {<br> /* Get an animal */<br> Animal* animal = zoo-&gt;get_animal(i);<br><br> /* Unlink the Ruby object from the C++ object */<br> SWIG_RubyUnlinkObjects(animal);<br><br> /* Now remove the tracking for this animal */<br> SWIG_RubyRemoveTracking(animal);<br> }<br><br> /* Now call SWIG_RemoveMapping for the zoo */<br> SWIG_RemoveMapping(ptr);<br> <br> /* Now free the zoo which will free the animals it contains */<br> delete zoo;<br> }<br>%} </pre>
2286
 
                </div>
2287
 
                <p>Now when we use these objects in IRB we see:</p>
2288
 
                <div class="code">
2289
 
                        <pre><span style="font-weight: bold;">$irb</span><br>irb(main):002:0&gt; <span style="font-weight: bold;">require 'example'</span><br>=&gt; true<br><br>irb(main):003:0&gt; <span style="font-weight: bold;">zoo = Example::Zoo.new()</span><br>=&gt; #&lt;Example::Zoo:0x2be0fe8&gt;<br><br>irb(main):005:0&gt; <span style="font-weight: bold;">tiger1 = Example::Animal.new("tiger1")</span><br>=&gt; #&lt;Example::Animal:0x2bda760&gt;<br><br>irb(main):006:0&gt; <span style="font-weight: bold;">zoo.add_animal(tiger1)</span><br>=&gt; nil<br><br>irb(main):007:0&gt; <span style="font-weight: bold;">zoo = nil</span><br>=&gt; nil<br><br>irb(main):008:0&gt; <span style="font-weight: bold;">GC.start</span><br>=&gt; nil<br><br>irb(main):009:0&gt; <span style="font-weight: bold;">tiger1.get_name()</span><br>RuntimeError: This Animal * already released<br> from (irb):10:in `get_name'<br> from (irb):10<br>irb(main):011:0&gt;</pre>
2290
 
                </div>
2291
 
                <p>Notice that SWIG can now detect the underlying C++ object has been freed, and 
2292
 
                        thus raises a runtime exception.</p>
2293
 
                <p>This code can be seen in swig/examples/ruby/free_function.</p>
2294
 
        </body>
 
4708
<p> A typemap is nothing more than a code generation rule that is
 
4709
attached to a specific C datatype. The general form of this declaration
 
4710
is as follows ( parts enclosed in [...] are optional
 
4711
):&nbsp;&nbsp; &nbsp;</p>
 
4712
 
 
4713
 
 
4714
 
 
4715
 
 
4716
 
 
4717
<div class="code"><span style="font-family: monospace;" class="code">%typemap( method [, modifiers...] ) typelist
 
4718
code; </span></div>
 
4719
 
 
4720
 
 
4721
 
 
4722
 
 
4723
 
 
4724
<p><em> method</em> is a simply a name that specifies
 
4725
what kind of typemap is being defined. It is usually a name like <tt>"in"</tt>,
 
4726
<tt>"out"</tt>, or <tt>"argout"</tt> (or its
 
4727
director variations). The purpose of these methods is described later.</p>
 
4728
 
 
4729
 
 
4730
 
 
4731
 
 
4732
 
 
4733
<p><em> modifiers</em> is an optional comma separated
 
4734
list of <tt>
 
4735
name="value"</tt> values. These are sometimes to attach extra
 
4736
information to a typemap and is often target-language dependent.</p>
 
4737
 
 
4738
 
 
4739
 
 
4740
 
 
4741
 
 
4742
<p><em> typelist</em> is a list of the C++ type
 
4743
patterns that the typemap will match. The general form of this list is
 
4744
as follows:</p>
 
4745
 
 
4746
 
 
4747
 
 
4748
 
 
4749
 
 
4750
<div class="diagram">
 
4751
<pre>typelist : typepattern [, typepattern, typepattern, ... ] ;<br><br>typepattern : type [ (parms) ]<br> | type name [ (parms) ]<br> | ( typelist ) [ (parms) ]<br></pre>
 
4752
 
 
4753
 
 
4754
 
 
4755
 
 
4756
 
 
4757
</div>
 
4758
 
 
4759
 
 
4760
 
 
4761
 
 
4762
 
 
4763
<p> Each type pattern is either a simple type, a simple type and
 
4764
argument name, or a list of types in the case of multi-argument
 
4765
typemaps. In addition, each type pattern can be parameterized with a
 
4766
list of temporary variables (parms). The purpose of these variables
 
4767
will be explained shortly.</p>
 
4768
 
 
4769
 
 
4770
 
 
4771
 
 
4772
 
 
4773
<p><em>code</em> specifies the C code used in the
 
4774
typemap. It can take any one of the following forms:</p>
 
4775
 
 
4776
 
 
4777
 
 
4778
 
 
4779
 
 
4780
<div class="diagram">
 
4781
<pre>code : { ... }<br> | " ... "<br> | %{ ... %}<br></pre>
 
4782
 
 
4783
 
 
4784
 
 
4785
 
 
4786
 
 
4787
</div>
 
4788
 
 
4789
 
 
4790
 
 
4791
 
 
4792
 
 
4793
<p>For example, to convert integers
 
4794
from Ruby to C, you might define a typemap like this: </p>
 
4795
 
 
4796
 
 
4797
 
 
4798
 
 
4799
 
 
4800
<div class="code">
 
4801
<pre>%module example<br><br>%typemap(in) int {<br> $1 = (int) NUM2INT($input);<br> printf("Received an integer : %d\n",$1);<br>}<br><br>%inline %{<br>extern int fact(int n);<br>%}<br></pre>
 
4802
 
 
4803
 
 
4804
 
 
4805
 
 
4806
 
 
4807
</div>
 
4808
 
 
4809
 
 
4810
 
 
4811
 
 
4812
 
 
4813
<p> Typemaps are always associated with some specific aspect of
 
4814
code generation. In this case, the "in" method refers to the conversion
 
4815
of input arguments to C/C++. The datatype <tt>int</tt> is
 
4816
the datatype to which the typemap will be applied. The supplied C code
 
4817
is used to convert values. In this code a number of special variables
 
4818
prefaced by a <tt>$</tt> are used. The <tt>$1</tt>
 
4819
variable is placeholder for a local variable of type <tt>int</tt>.
 
4820
The <tt>$input</tt> variable is the input Ruby object. </p>
 
4821
 
 
4822
 
 
4823
 
 
4824
 
 
4825
 
 
4826
<p>When this example is compiled into a Ruby module, the
 
4827
following sample code: </p>
 
4828
 
 
4829
 
 
4830
 
 
4831
 
 
4832
 
 
4833
<div class="code targetlang">
 
4834
<pre>require 'example'<br><br>puts Example.fact(6)<br></pre>
 
4835
 
 
4836
 
 
4837
 
 
4838
 
 
4839
 
 
4840
</div>
 
4841
 
 
4842
 
 
4843
 
 
4844
 
 
4845
 
 
4846
<p>prints the result:</p>
 
4847
 
 
4848
 
 
4849
 
 
4850
 
 
4851
 
 
4852
<div class="code shell">
 
4853
<pre>Received an integer : 6<br>720<br></pre>
 
4854
 
 
4855
 
 
4856
 
 
4857
 
 
4858
 
 
4859
</div>
 
4860
 
 
4861
 
 
4862
 
 
4863
 
 
4864
 
 
4865
<p> In this example, the typemap is applied to all occurrences of
 
4866
the <tt>int</tt> datatype. You can refine this by
 
4867
supplying an optional parameter name. For example: </p>
 
4868
 
 
4869
 
 
4870
 
 
4871
 
 
4872
 
 
4873
<div class="code">
 
4874
<pre>%module example<br><br>%typemap(in) int n {<br> $1 = (int) NUM2INT($input);<br> printf("n = %d\n",$1);<br>}<br><br>%inline %{<br>extern int fact(int n);<br>%}<br></pre>
 
4875
 
 
4876
 
 
4877
 
 
4878
 
 
4879
 
 
4880
</div>
 
4881
 
 
4882
 
 
4883
 
 
4884
 
 
4885
 
 
4886
<p> In this case, the typemap code is only attached to arguments
 
4887
that exactly match "<tt>int n</tt>". </p>
 
4888
 
 
4889
 
 
4890
 
 
4891
 
 
4892
 
 
4893
<p>The application of a typemap to specific datatypes and
 
4894
argument names involves more than simple text-matching--typemaps are
 
4895
fully integrated into the SWIG type-system. When you define a typemap
 
4896
for <tt>int</tt>, that typemap applies to <tt>int</tt>
 
4897
and qualified variations such as <tt>const int</tt>. In
 
4898
addition, the typemap system follows <tt>typedef</tt>
 
4899
declarations. For example: </p>
 
4900
 
 
4901
 
 
4902
 
 
4903
 
 
4904
 
 
4905
<div class="code">
 
4906
<pre>%typemap(in) int n {<br> $1 = (int) NUM2INT($input);<br> printf("n = %d\n",$1);<br>}<br><br>typedef int Integer;<br>extern int fact(Integer n); // Above typemap is applied<br></pre>
 
4907
 
 
4908
 
 
4909
 
 
4910
 
 
4911
 
 
4912
</div>
 
4913
 
 
4914
 
 
4915
 
 
4916
 
 
4917
 
 
4918
<p> However, the matching of <tt>typedef</tt> only
 
4919
occurs in one direction. If you defined a typemap for <tt>Integer</tt>,
 
4920
it is not applied to arguments of type <tt>int</tt>. </p>
 
4921
 
 
4922
 
 
4923
 
 
4924
 
 
4925
 
 
4926
<p>Typemaps can also be defined for groups of consecutive
 
4927
arguments. For example: </p>
 
4928
 
 
4929
 
 
4930
 
 
4931
 
 
4932
 
 
4933
<div class="code">
 
4934
<pre>%typemap(in) (char *str, int len) {<br> $1 = STR2CSTR($input);<br> $2 = (int) RSTRING($input)-&gt;len;<br>};<br><br>int count(char c, char *str, int len);<br></pre>
 
4935
 
 
4936
 
 
4937
 
 
4938
 
 
4939
 
 
4940
</div>
 
4941
 
 
4942
 
 
4943
 
 
4944
 
 
4945
 
 
4946
<p> When a multi-argument typemap is defined, the arguments are
 
4947
always handled as a single Ruby object. This allows the function <tt>count</tt>
 
4948
to be used as follows (notice how the length parameter is omitted): </p>
 
4949
 
 
4950
 
 
4951
 
 
4952
 
 
4953
 
 
4954
<div class="code targetlang">
 
4955
<pre>puts Example.count('o','Hello World')<br>2<br></pre>
 
4956
 
 
4957
 
 
4958
 
 
4959
 
 
4960
 
 
4961
</div>
 
4962
 
 
4963
 
 
4964
 
 
4965
 
 
4966
 
 
4967
<H3><a name="Ruby_Typemap_scope"></a>30.7.2 Typemap scope</H3>
 
4968
 
 
4969
 
 
4970
<p> Once defined, a typemap remains in effect for all of the
 
4971
declarations that follow. A typemap may be redefined for different
 
4972
sections of an input file. For example:</p>
 
4973
 
 
4974
 
 
4975
 
 
4976
 
 
4977
 
 
4978
<div class="code">
 
4979
<pre>// typemap1<br>%typemap(in) int {<br>...<br>}<br><br>int fact(int); // typemap1<br>int gcd(int x, int y); // typemap1<br><br>// typemap2<br>%typemap(in) int {<br>...<br>}<br><br>int isprime(int); // typemap2<br></pre>
 
4980
 
 
4981
 
 
4982
 
 
4983
 
 
4984
 
 
4985
</div>
 
4986
 
 
4987
 
 
4988
 
 
4989
 
 
4990
 
 
4991
<p> One exception to the typemap scoping rules pertains to the <tt>
 
4992
%extend</tt> declaration. <tt>%extend</tt> is used
 
4993
to attach new declarations to a class or structure definition. Because
 
4994
of this, all of the declarations in an <tt>%extend</tt>
 
4995
block are subject to the typemap rules that are in effect at the point
 
4996
where the class itself is defined. For example:</p>
 
4997
 
 
4998
 
 
4999
 
 
5000
 
 
5001
 
 
5002
<div class="code">
 
5003
<pre>class Foo {<br> ...<br>};<br><br>%typemap(in) int {<br> ...<br>}<br><br>%extend Foo {<br> int blah(int x); // typemap has no effect. Declaration is attached to Foo which <br> // appears before the %typemap declaration.<br>};<br></pre>
 
5004
 
 
5005
 
 
5006
 
 
5007
 
 
5008
 
 
5009
</div>
 
5010
 
 
5011
 
 
5012
 
 
5013
 
 
5014
 
 
5015
<H3><a name="Ruby_Copying_a_typemap"></a>30.7.3 Copying a typemap</H3>
 
5016
 
 
5017
 
 
5018
<p> A typemap is copied by using assignment. For example:</p>
 
5019
 
 
5020
 
 
5021
 
 
5022
 
 
5023
 
 
5024
<div class="code">
 
5025
<pre>%typemap(in) Integer = int;<br></pre>
 
5026
 
 
5027
 
 
5028
 
 
5029
 
 
5030
 
 
5031
</div>
 
5032
 
 
5033
 
 
5034
 
 
5035
 
 
5036
 
 
5037
<p> or this:</p>
 
5038
 
 
5039
 
 
5040
 
 
5041
 
 
5042
 
 
5043
<div class="code">
 
5044
<pre>%typemap(in) Integer, Number, int32_t = int;<br></pre>
 
5045
 
 
5046
 
 
5047
 
 
5048
 
 
5049
 
 
5050
</div>
 
5051
 
 
5052
 
 
5053
 
 
5054
 
 
5055
 
 
5056
<p> Types are often managed by a collection of different
 
5057
typemaps. For example:</p>
 
5058
 
 
5059
 
 
5060
 
 
5061
 
 
5062
 
 
5063
<div class="code">
 
5064
<pre>%typemap(in) int { ... }<br>%typemap(out) int { ... }<br>%typemap(varin) int { ... }<br>%typemap(varout) int { ... }<br></pre>
 
5065
 
 
5066
 
 
5067
 
 
5068
 
 
5069
 
 
5070
</div>
 
5071
 
 
5072
 
 
5073
 
 
5074
 
 
5075
 
 
5076
<p> To copy all of these typemaps to a new type, use <tt>%apply</tt>.
 
5077
For example:</p>
 
5078
 
 
5079
 
 
5080
 
 
5081
 
 
5082
 
 
5083
<div class="code">
 
5084
<pre>%apply int { Integer }; // Copy all int typemaps to Integer<br>%apply int { Integer, Number }; // Copy all int typemaps to both Integer and Number<br></pre>
 
5085
 
 
5086
 
 
5087
 
 
5088
 
 
5089
 
 
5090
</div>
 
5091
 
 
5092
 
 
5093
 
 
5094
 
 
5095
 
 
5096
<p> The patterns for <tt>%apply</tt> follow the same
 
5097
rules as for <tt>
 
5098
%typemap</tt>. For example:</p>
 
5099
 
 
5100
 
 
5101
 
 
5102
 
 
5103
 
 
5104
<div class="code">
 
5105
<pre>%apply int *output { Integer *output }; // Typemap with name<br>%apply (char *buf, int len) { (char *buffer, int size) }; // Multiple arguments<br></pre>
 
5106
 
 
5107
 
 
5108
 
 
5109
 
 
5110
 
 
5111
</div>
 
5112
 
 
5113
 
 
5114
 
 
5115
 
 
5116
 
 
5117
<H3><a name="Ruby_Deleting_a_typemap"></a>30.7.4 Deleting a typemap</H3>
 
5118
 
 
5119
 
 
5120
<p> A typemap can be deleted by simply defining no code. For
 
5121
example:</p>
 
5122
 
 
5123
 
 
5124
 
 
5125
 
 
5126
 
 
5127
<div class="code">
 
5128
<pre>%typemap(in) int; // Clears typemap for int<br>%typemap(in) int, long, short; // Clears typemap for int, long, short<br>%typemap(in) int *output; <br></pre>
 
5129
 
 
5130
 
 
5131
 
 
5132
 
 
5133
 
 
5134
</div>
 
5135
 
 
5136
 
 
5137
 
 
5138
 
 
5139
 
 
5140
<p> The <tt>%clear</tt> directive clears all
 
5141
typemaps for a given type. For example:</p>
 
5142
 
 
5143
 
 
5144
 
 
5145
 
 
5146
 
 
5147
<div class="code">
 
5148
<pre>%clear int; // Removes all types for int<br>%clear int *output, long *output;<br></pre>
 
5149
 
 
5150
 
 
5151
 
 
5152
 
 
5153
 
 
5154
</div>
 
5155
 
 
5156
 
 
5157
 
 
5158
 
 
5159
 
 
5160
<p><b> Note:</b> Since SWIG's default behavior is
 
5161
defined by typemaps, clearing a fundamental type like <tt>int</tt>
 
5162
will make that type unusable unless you also define a new set of
 
5163
typemaps immediately after the clear operation.</p>
 
5164
 
 
5165
 
 
5166
 
 
5167
 
 
5168
 
 
5169
<H3><a name="Ruby_Placement_of_typemaps"></a>30.7.5 Placement of typemaps</H3>
 
5170
 
 
5171
 
 
5172
<p> Typemap declarations can be declared in the global scope,
 
5173
within a C++ namespace, and within a C++ class. For example:</p>
 
5174
 
 
5175
 
 
5176
 
 
5177
 
 
5178
 
 
5179
<div class="code">
 
5180
<pre>%typemap(in) int {<br> ...<br>}<br><br>namespace std {<br> class string;<br> %typemap(in) string {<br> ...<br> }<br>}<br><br>class Bar {<br>public:<br> typedef const int &amp; const_reference;<br> %typemap(out) const_reference {<br> ...<br> }<br>};<br></pre>
 
5181
 
 
5182
 
 
5183
 
 
5184
 
 
5185
 
 
5186
</div>
 
5187
 
 
5188
 
 
5189
 
 
5190
 
 
5191
 
 
5192
<p> When a typemap appears inside a namespace or class, it stays
 
5193
in effect until the end of the SWIG input (just like before). However,
 
5194
the typemap takes the local scope into account. Therefore, this code</p>
 
5195
 
 
5196
 
 
5197
 
 
5198
 
 
5199
 
 
5200
<div class="code">
 
5201
<pre>namespace std {<br> class string;<br> %typemap(in) string {<br> ...<br> }<br>}<br></pre>
 
5202
 
 
5203
 
 
5204
 
 
5205
 
 
5206
 
 
5207
</div>
 
5208
 
 
5209
 
 
5210
 
 
5211
 
 
5212
 
 
5213
<p> is really defining a typemap for the type <tt>std::string</tt>.
 
5214
You could have code like this:</p>
 
5215
 
 
5216
 
 
5217
 
 
5218
 
 
5219
 
 
5220
<div class="code">
 
5221
<pre>namespace std {<br> class string;<br> %typemap(in) string { /* std::string */<br> ...<br> }<br>}<br><br>namespace Foo {<br> class string;<br> %typemap(in) string { /* Foo::string */<br> ...<br> }<br>}<br></pre>
 
5222
 
 
5223
 
 
5224
 
 
5225
 
 
5226
 
 
5227
</div>
 
5228
 
 
5229
 
 
5230
 
 
5231
 
 
5232
 
 
5233
<p> In this case, there are two completely distinct typemaps that
 
5234
apply to two completely different types (<tt>std::string</tt>
 
5235
and <tt>
 
5236
Foo::string</tt>).</p>
 
5237
 
 
5238
 
 
5239
 
 
5240
 
 
5241
 
 
5242
<p> It should be noted that for scoping to work, SWIG has to know
 
5243
that <tt>
 
5244
string</tt> is a typename defined within a particular namespace.
 
5245
In this example, this is done using the class declaration <tt>class
 
5246
string</tt>
 
5247
.</p>
 
5248
 
 
5249
 
 
5250
 
 
5251
 
 
5252
 
 
5253
<H3><a name="Ruby_nn39"></a>30.7.6 Ruby typemaps</H3>
 
5254
 
 
5255
 
 
5256
<p>The following list details all of the typemap methods that
 
5257
can be used by the Ruby module: </p>
 
5258
 
 
5259
 
 
5260
 
 
5261
 
 
5262
 
 
5263
<H4><a name="Ruby_in_typemap"></a>30.7.6.1 &nbsp;"in" typemap</H4>
 
5264
 
 
5265
 
 
5266
<p>Converts Ruby objects to input
 
5267
function arguments. For example:
 
5268
</p>
 
5269
 
 
5270
 
 
5271
 
 
5272
 
 
5273
 
 
5274
<div class="code">
 
5275
<pre>%typemap(in) int {<br> $1 = NUM2INT($input);<br>}<br></pre>
 
5276
 
 
5277
 
 
5278
 
 
5279
 
 
5280
 
 
5281
</div>
 
5282
 
 
5283
 
 
5284
 
 
5285
 
 
5286
 
 
5287
<p> The following special variables are available:</p>
 
5288
 
 
5289
 
 
5290
 
 
5291
 
 
5292
 
 
5293
<div class="diagram">
 
5294
<table border="1" cellpadding="2" cellspacing="2" width="100%" summary="Special variables - in typemap">
 
5295
 
 
5296
 
 
5297
 
 
5298
 
 
5299
 
 
5300
  <tbody>
 
5301
 
 
5302
 
 
5303
 
 
5304
 
 
5305
 
 
5306
    <tr>
 
5307
 
 
5308
 
 
5309
 
 
5310
 
 
5311
 
 
5312
      <td style="font-family: monospace;">$input </td>
 
5313
 
 
5314
 
 
5315
 
 
5316
 
 
5317
 
 
5318
      <td style="font-family: monospace;"> Input object
 
5319
holding value to be converted.</td>
 
5320
 
 
5321
 
 
5322
 
 
5323
 
 
5324
 
 
5325
    </tr>
 
5326
 
 
5327
 
 
5328
 
 
5329
 
 
5330
 
 
5331
    <tr>
 
5332
 
 
5333
 
 
5334
 
 
5335
 
 
5336
 
 
5337
      <td style="font-family: monospace;">$symname </td>
 
5338
 
 
5339
 
 
5340
 
 
5341
 
 
5342
 
 
5343
      <td style="font-family: monospace;"> Name of
 
5344
function/method being wrapped</td>
 
5345
 
 
5346
 
 
5347
 
 
5348
 
 
5349
 
 
5350
    </tr>
 
5351
 
 
5352
 
 
5353
 
 
5354
 
 
5355
 
 
5356
    <tr>
 
5357
 
 
5358
 
 
5359
 
 
5360
 
 
5361
 
 
5362
      <td style="font-family: monospace;">$1...n </td>
 
5363
 
 
5364
 
 
5365
 
 
5366
 
 
5367
 
 
5368
      <td style="font-family: monospace;"> Argument being
 
5369
sent to the function</td>
 
5370
 
 
5371
 
 
5372
 
 
5373
 
 
5374
 
 
5375
    </tr>
 
5376
 
 
5377
 
 
5378
 
 
5379
 
 
5380
 
 
5381
    <tr>
 
5382
 
 
5383
 
 
5384
 
 
5385
 
 
5386
 
 
5387
      <td style="font-family: monospace;">$1_name </td>
 
5388
 
 
5389
 
 
5390
 
 
5391
 
 
5392
 
 
5393
      <td style="font-family: monospace;"> Name of the
 
5394
argument (if provided)</td>
 
5395
 
 
5396
 
 
5397
 
 
5398
 
 
5399
 
 
5400
    </tr>
 
5401
 
 
5402
 
 
5403
 
 
5404
 
 
5405
 
 
5406
    <tr>
 
5407
 
 
5408
 
 
5409
 
 
5410
 
 
5411
 
 
5412
      <td style="font-family: monospace;">$1_type </td>
 
5413
 
 
5414
 
 
5415
 
 
5416
 
 
5417
 
 
5418
      <td style="font-family: monospace;"> The actual C
 
5419
datatype matched by the typemap.</td>
 
5420
 
 
5421
 
 
5422
 
 
5423
 
 
5424
 
 
5425
    </tr>
 
5426
 
 
5427
 
 
5428
 
 
5429
 
 
5430
 
 
5431
    <tr>
 
5432
 
 
5433
 
 
5434
 
 
5435
 
 
5436
 
 
5437
      <td style="font-family: monospace;">$1_ltype </td>
 
5438
 
 
5439
 
 
5440
 
 
5441
 
 
5442
 
 
5443
      <td style="font-family: monospace;"> The assignable
 
5444
version of the C datatype matched by the typemap.</td>
 
5445
 
 
5446
 
 
5447
 
 
5448
 
 
5449
 
 
5450
    </tr>
 
5451
 
 
5452
 
 
5453
 
 
5454
 
 
5455
 
 
5456
  
 
5457
  
 
5458
  
 
5459
  
 
5460
  </tbody>
 
5461
</table>
 
5462
 
 
5463
 
 
5464
 
 
5465
 
 
5466
 
 
5467
</div>
 
5468
 
 
5469
 
 
5470
 
 
5471
 
 
5472
 
 
5473
<p> This is probably the most commonly redefined typemap because
 
5474
it can be used to implement customized conversions.</p>
 
5475
 
 
5476
 
 
5477
 
 
5478
 
 
5479
 
 
5480
<p> In addition, the "in" typemap allows the number of converted
 
5481
arguments to be specified. For example:</p>
 
5482
 
 
5483
 
 
5484
 
 
5485
 
 
5486
 
 
5487
<div class="code">
 
5488
<pre>// Ignored argument.<br>%typemap(in, numinputs=0) int *out (int temp) {<br> $1 = &amp;temp;<br>}<br></pre>
 
5489
 
 
5490
 
 
5491
 
 
5492
 
 
5493
 
 
5494
</div>
 
5495
 
 
5496
 
 
5497
 
 
5498
 
 
5499
 
 
5500
<p> At this time, only zero or one arguments may be converted.</p>
 
5501
 
 
5502
 
 
5503
 
 
5504
 
 
5505
 
 
5506
<H4><a name="Ruby_typecheck_typemap"></a>30.7.6.2 "typecheck" typemap</H4>
 
5507
 
 
5508
 
 
5509
<p> The "typecheck" typemap is used to support overloaded
 
5510
functions and methods. It merely checks an argument to see whether or
 
5511
not it matches a specific type. For example:</p>
 
5512
 
 
5513
 
 
5514
 
 
5515
 
 
5516
 
 
5517
<div class="code">
 
5518
<pre>%typemap(typecheck,precedence=SWIG_TYPECHECK_INTEGER) int {<br> $1 = FIXNUM_P($input) ? 1 : 0;<br>}<br></pre>
 
5519
 
 
5520
 
 
5521
 
 
5522
 
 
5523
 
 
5524
</div>
 
5525
 
 
5526
 
 
5527
 
 
5528
 
 
5529
 
 
5530
<p> For typechecking, the $1 variable is always a simple integer
 
5531
that is set to 1 or 0 depending on whether or not the input argument is
 
5532
the correct type.</p>
 
5533
 
 
5534
 
 
5535
 
 
5536
 
 
5537
 
 
5538
<p> If you define new "in" typemaps<em> and</em> your
 
5539
program uses overloaded methods, you should also define a collection of
 
5540
"typecheck" typemaps. More details about this follow in a later section
 
5541
on "Typemaps and Overloading."</p>
 
5542
 
 
5543
 
 
5544
 
 
5545
 
 
5546
 
 
5547
<H4><a name="Ruby_out_typemap"></a>30.7.6.3 &nbsp;"out" typemap</H4>
 
5548
 
 
5549
 
 
5550
<p>Converts return value of a C function
 
5551
to a Ruby object.</p>
 
5552
 
 
5553
 
 
5554
 
 
5555
 
 
5556
 
 
5557
<div class="code"><tt><br>
 
5558
 
 
5559
 
 
5560
 
 
5561
 
 
5562
 
 
5563
%typemap(out) int {<br>
 
5564
 
 
5565
 
 
5566
 
 
5567
 
 
5568
 
 
5569
&nbsp; &nbsp;$result = INT2NUM( $1 );<br>
 
5570
 
 
5571
 
 
5572
 
 
5573
 
 
5574
 
 
5575
}<br>
 
5576
 
 
5577
 
 
5578
 
 
5579
 
 
5580
 
 
5581
</tt></div>
 
5582
 
 
5583
 
 
5584
 
 
5585
 
 
5586
 
 
5587
<p> The following special variables are available.</p>
 
5588
 
 
5589
 
 
5590
 
 
5591
 
 
5592
 
 
5593
<div class="diagram">
 
5594
<table border="1" cellpadding="2" cellspacing="2" width="100%" summary="Special variables - out typemap">
 
5595
 
 
5596
 
 
5597
 
 
5598
 
 
5599
 
 
5600
  <tbody>
 
5601
 
 
5602
 
 
5603
 
 
5604
 
 
5605
 
 
5606
    <tr>
 
5607
 
 
5608
 
 
5609
 
 
5610
 
 
5611
 
 
5612
      <td style="font-family: monospace;">$result </td>
 
5613
 
 
5614
 
 
5615
 
 
5616
 
 
5617
 
 
5618
      <td style="font-family: monospace;"> Result object
 
5619
returned to target language.</td>
 
5620
 
 
5621
 
 
5622
 
 
5623
 
 
5624
 
 
5625
    </tr>
 
5626
 
 
5627
 
 
5628
 
 
5629
 
 
5630
 
 
5631
    <tr>
 
5632
 
 
5633
 
 
5634
 
 
5635
 
 
5636
 
 
5637
      <td style="font-family: monospace;">$symname </td>
 
5638
 
 
5639
 
 
5640
 
 
5641
 
 
5642
 
 
5643
      <td style="font-family: monospace;"> Name of
 
5644
function/method being wrapped</td>
 
5645
 
 
5646
 
 
5647
 
 
5648
 
 
5649
 
 
5650
    </tr>
 
5651
 
 
5652
 
 
5653
 
 
5654
 
 
5655
 
 
5656
    <tr>
 
5657
 
 
5658
 
 
5659
 
 
5660
 
 
5661
 
 
5662
      <td style="font-family: monospace;">$1...n </td>
 
5663
 
 
5664
 
 
5665
 
 
5666
 
 
5667
 
 
5668
      <td style="font-family: monospace;"> Argument being
 
5669
wrapped</td>
 
5670
 
 
5671
 
 
5672
 
 
5673
 
 
5674
 
 
5675
    </tr>
 
5676
 
 
5677
 
 
5678
 
 
5679
 
 
5680
 
 
5681
    <tr>
 
5682
 
 
5683
 
 
5684
 
 
5685
 
 
5686
 
 
5687
      <td style="font-family: monospace;">$1_name </td>
 
5688
 
 
5689
 
 
5690
 
 
5691
 
 
5692
 
 
5693
      <td style="font-family: monospace;"> Name of the
 
5694
argument (if provided)</td>
 
5695
 
 
5696
 
 
5697
 
 
5698
 
 
5699
 
 
5700
    </tr>
 
5701
 
 
5702
 
 
5703
 
 
5704
 
 
5705
 
 
5706
    <tr>
 
5707
 
 
5708
 
 
5709
 
 
5710
 
 
5711
 
 
5712
      <td style="font-family: monospace;">$1_type </td>
 
5713
 
 
5714
 
 
5715
 
 
5716
 
 
5717
 
 
5718
      <td style="font-family: monospace;"> The actual C
 
5719
datatype matched by the typemap.</td>
 
5720
 
 
5721
 
 
5722
 
 
5723
 
 
5724
 
 
5725
    </tr>
 
5726
 
 
5727
 
 
5728
 
 
5729
 
 
5730
 
 
5731
    <tr>
 
5732
 
 
5733
 
 
5734
 
 
5735
 
 
5736
 
 
5737
      <td style="font-family: monospace;">$1_ltype </td>
 
5738
 
 
5739
 
 
5740
 
 
5741
 
 
5742
 
 
5743
      <td style="font-family: monospace;"> The assignable
 
5744
version of the C datatype matched by the typemap.</td>
 
5745
 
 
5746
 
 
5747
 
 
5748
 
 
5749
 
 
5750
    </tr>
 
5751
 
 
5752
 
 
5753
 
 
5754
 
 
5755
 
 
5756
  
 
5757
  
 
5758
  
 
5759
  
 
5760
  </tbody>
 
5761
</table>
 
5762
 
 
5763
 
 
5764
 
 
5765
 
 
5766
 
 
5767
</div>
 
5768
 
 
5769
 
 
5770
 
 
5771
 
 
5772
 
 
5773
<br>
 
5774
 
 
5775
 
 
5776
 
 
5777
 
 
5778
 
 
5779
<H4><a name="Ruby_arginit_typemap"></a>30.7.6.4 "arginit" typemap</H4>
 
5780
 
 
5781
 
 
5782
<p> The "arginit" typemap is used to set the initial value of a
 
5783
function argument--before any conversion has occurred. This is not
 
5784
normally necessary, but might be useful in highly specialized
 
5785
applications. For example:</p>
 
5786
 
 
5787
 
 
5788
 
 
5789
 
 
5790
 
 
5791
<div class="code">
 
5792
<pre>// Set argument to NULL before any conversion occurs<br>%typemap(arginit) int *data {<br> $1 = NULL;<br>}<br></pre>
 
5793
 
 
5794
 
 
5795
 
 
5796
 
 
5797
 
 
5798
</div>
 
5799
 
 
5800
 
 
5801
 
 
5802
 
 
5803
 
 
5804
<H4><a name="Ruby_default_typemap"></a>30.7.6.5 "default" typemap</H4>
 
5805
 
 
5806
 
 
5807
<p> The "default" typemap is used to turn an argument into a
 
5808
default argument. For example:</p>
 
5809
 
 
5810
 
 
5811
 
 
5812
 
 
5813
 
 
5814
<div class="code">
 
5815
<pre>%typemap(default) int flags {<br> $1 = DEFAULT_FLAGS;<br>}<br>...<br>int foo(int x, int y, int flags);<br></pre>
 
5816
 
 
5817
 
 
5818
 
 
5819
 
 
5820
 
 
5821
</div>
 
5822
 
 
5823
 
 
5824
 
 
5825
 
 
5826
 
 
5827
<p> The primary use of this typemap is to either change the
 
5828
wrapping of default arguments or specify a default argument in a
 
5829
language where they aren't supported (like C). Target languages that do
 
5830
not support optional arguments, such as Java and C#, effectively ignore
 
5831
the value specified by this typemap as all arguments must be given.</p>
 
5832
 
 
5833
 
 
5834
 
 
5835
 
 
5836
 
 
5837
<p> Once a default typemap has been applied to an argument, all
 
5838
arguments that follow must have default values. See the <a href="http://www.swig.org/Doc1.3/SWIGDocumentation.html#SWIG_default_args">
 
5839
Default/optional arguments</a> section for further information on
 
5840
default argument wrapping.</p>
 
5841
 
 
5842
 
 
5843
 
 
5844
 
 
5845
 
 
5846
<H4><a name="Ruby_check_typemap"></a>30.7.6.6 "check" typemap</H4>
 
5847
 
 
5848
 
 
5849
<p> The "check" typemap is used to supply value checking code
 
5850
during argument conversion. The typemap is applied<em> after</em>
 
5851
arguments have been converted. For example:</p>
 
5852
 
 
5853
 
 
5854
 
 
5855
 
 
5856
 
 
5857
<div class="code">
 
5858
<pre>%typemap(check) int positive {<br> if ($1 &lt;= 0) {<br> SWIG_exception(SWIG_ValueError,"Expected positive value.");<br> }<br>}<br></pre>
 
5859
 
 
5860
 
 
5861
 
 
5862
 
 
5863
 
 
5864
</div>
 
5865
 
 
5866
 
 
5867
 
 
5868
 
 
5869
 
 
5870
<H4><a name="Ruby_argout_typemap_"></a>30.7.6.7 "argout" typemap</H4>
 
5871
 
 
5872
 
 
5873
<p> The "argout" typemap is used to return values from arguments.
 
5874
This is most commonly used to write wrappers for C/C++ functions that
 
5875
need to return multiple values. The "argout" typemap is almost always
 
5876
combined with an "in" typemap---possibly to ignore the input value. For
 
5877
example:</p>
 
5878
 
 
5879
 
 
5880
 
 
5881
 
 
5882
 
 
5883
<div class="code">
 
5884
<pre>/* Set the input argument to point to a temporary variable */<br>%typemap(in, numinputs=0) int *out (int temp) {<br> $1 = &amp;temp;<br>}<br><br>%typemap(argout, fragment="output_helper") int *out {<br> // Append output value $1 to $result (assuming a single integer in this case)<br> $result = output_helper( $result, INT2NUM(*$1) );<br>}<br></pre>
 
5885
 
 
5886
 
 
5887
 
 
5888
 
 
5889
 
 
5890
</div>
 
5891
 
 
5892
 
 
5893
 
 
5894
 
 
5895
 
 
5896
<p> The following special variables are available.</p>
 
5897
 
 
5898
 
 
5899
 
 
5900
 
 
5901
 
 
5902
<div class="diagram">
 
5903
<table border="1" cellpadding="2" cellspacing="2" width="100%" summary="Special variables - argout typemap">
 
5904
 
 
5905
 
 
5906
 
 
5907
 
 
5908
 
 
5909
  <tbody>
 
5910
 
 
5911
 
 
5912
 
 
5913
 
 
5914
 
 
5915
    <tr>
 
5916
 
 
5917
 
 
5918
 
 
5919
 
 
5920
 
 
5921
      <td style="font-family: monospace;">$result </td>
 
5922
 
 
5923
 
 
5924
 
 
5925
 
 
5926
 
 
5927
      <td style="font-family: monospace;"> Result object
 
5928
returned to target language.</td>
 
5929
 
 
5930
 
 
5931
 
 
5932
 
 
5933
 
 
5934
    </tr>
 
5935
 
 
5936
 
 
5937
 
 
5938
 
 
5939
 
 
5940
    <tr>
 
5941
 
 
5942
 
 
5943
 
 
5944
 
 
5945
 
 
5946
      <td style="font-family: monospace;">$input </td>
 
5947
 
 
5948
 
 
5949
 
 
5950
 
 
5951
 
 
5952
      <td style="font-family: monospace;"> The original
 
5953
input object passed.</td>
 
5954
 
 
5955
 
 
5956
 
 
5957
 
 
5958
 
 
5959
    </tr>
 
5960
 
 
5961
 
 
5962
 
 
5963
 
 
5964
 
 
5965
    <tr>
 
5966
 
 
5967
 
 
5968
 
 
5969
 
 
5970
 
 
5971
      <td style="font-family: monospace;">$symname </td>
 
5972
 
 
5973
 
 
5974
 
 
5975
 
 
5976
 
 
5977
      <td style="font-family: monospace;"> Name of
 
5978
function/method being wrapped.</td>
 
5979
 
 
5980
 
 
5981
 
 
5982
 
 
5983
 
 
5984
    </tr>
 
5985
 
 
5986
 
 
5987
 
 
5988
 
 
5989
 
 
5990
  
 
5991
  
 
5992
  
 
5993
  
 
5994
  </tbody>
 
5995
</table>
 
5996
 
 
5997
 
 
5998
 
 
5999
 
 
6000
 
 
6001
</div>
 
6002
 
 
6003
 
 
6004
 
 
6005
 
 
6006
 
 
6007
<p> The code supplied to the "argout" typemap is always placed
 
6008
after the "out" typemap. If multiple return values are used, the extra
 
6009
return values are often appended to return value of the function.</p>
 
6010
 
 
6011
 
 
6012
 
 
6013
 
 
6014
 
 
6015
<p>Output helper is a fragment that usually defines a macro to
 
6016
some function like SWIG_Ruby_AppendOutput.</p>
 
6017
 
 
6018
 
 
6019
 
 
6020
 
 
6021
 
 
6022
<p> See the <tt>typemaps.i</tt> library for examples.</p>
 
6023
 
 
6024
 
 
6025
 
 
6026
 
 
6027
 
 
6028
<H4><a name="Ruby_freearg_typemap_"></a>30.7.6.8 "freearg" typemap</H4>
 
6029
 
 
6030
 
 
6031
<p> The "freearg" typemap is used to cleanup argument data. It is
 
6032
only used when an argument might have allocated resources that need to
 
6033
be cleaned up when the wrapper function exits. The "freearg" typemap
 
6034
usually cleans up argument resources allocated by the "in" typemap. For
 
6035
example:</p>
 
6036
 
 
6037
 
 
6038
 
 
6039
 
 
6040
 
 
6041
<div class="code">
 
6042
<pre>// Get a list of integers<br>%typemap(in) int *items {<br> int nitems = Length($input); <br> $1 = (int *) malloc(sizeof(int)*nitems);<br>}<br>// Free the list <br>%typemap(freearg) int *items {<br> free($1);<br>}<br></pre>
 
6043
 
 
6044
 
 
6045
 
 
6046
 
 
6047
 
 
6048
</div>
 
6049
 
 
6050
 
 
6051
 
 
6052
 
 
6053
 
 
6054
<p> The "freearg" typemap inserted at the end of the wrapper
 
6055
function, just before control is returned back to the target language.
 
6056
This code is also placed into a special variable <tt>$cleanup</tt>
 
6057
that may be used in other typemaps whenever a wrapper function needs to
 
6058
abort prematurely.</p>
 
6059
 
 
6060
 
 
6061
 
 
6062
 
 
6063
 
 
6064
<H4><a name="Ruby_newfree_typemap"></a>30.7.6.9 "newfree" typemap</H4>
 
6065
 
 
6066
 
 
6067
<p> The "newfree" typemap is used in conjunction with the <tt>%newobject</tt>
 
6068
directive and is used to deallocate memory used by the return result of
 
6069
a function. For example:</p>
 
6070
 
 
6071
 
 
6072
 
 
6073
 
 
6074
 
 
6075
<div class="code">
 
6076
<pre>%typemap(newfree) string * {<br> delete $1;<br>}<br>%typemap(out) string * {<br> $result = PyString_FromString($1-&gt;c_str());<br>}<br>...<br><br>%newobject foo;<br>...<br>string *foo();<br></pre>
 
6077
 
 
6078
 
 
6079
 
 
6080
 
 
6081
 
 
6082
</div>
 
6083
 
 
6084
 
 
6085
 
 
6086
 
 
6087
 
 
6088
<p> See <a href="http://www.swig.org/Doc1.3/SWIGDocumentation.html#ownership">Object
 
6089
ownership and %newobject</a> for further details.</p>
 
6090
 
 
6091
 
 
6092
 
 
6093
 
 
6094
 
 
6095
<H4><a name="Ruby_memberin_typemap"></a>30.7.6.10 "memberin" typemap</H4>
 
6096
 
 
6097
 
 
6098
<p> The "memberin" typemap is used to copy data from<em> an
 
6099
already converted input value</em> into a structure member. It is
 
6100
typically used to handle array members and other special cases. For
 
6101
example:</p>
 
6102
 
 
6103
 
 
6104
 
 
6105
 
 
6106
 
 
6107
<div class="code">
 
6108
<pre>%typemap(memberin) int [4] {<br> memmove($1, $input, 4*sizeof(int));<br>}<br></pre>
 
6109
 
 
6110
 
 
6111
 
 
6112
 
 
6113
 
 
6114
</div>
 
6115
 
 
6116
 
 
6117
 
 
6118
 
 
6119
 
 
6120
<p> It is rarely necessary to write "memberin" typemaps---SWIG
 
6121
already provides a default implementation for arrays, strings, and
 
6122
other objects.</p>
 
6123
 
 
6124
 
 
6125
 
 
6126
 
 
6127
 
 
6128
<H4><a name="Ruby_varin_typemap"></a>30.7.6.11 "varin" typemap</H4>
 
6129
 
 
6130
 
 
6131
<p> The "varin" typemap is used to convert objects in the target
 
6132
language to C for the purposes of assigning to a C/C++ global variable.
 
6133
This is implementation specific.</p>
 
6134
 
 
6135
 
 
6136
 
 
6137
 
 
6138
 
 
6139
<H4><a name="Ruby_varout_typemap_"></a>30.7.6.12 "varout" typemap</H4>
 
6140
 
 
6141
 
 
6142
<p> The "varout" typemap is used to convert a C/C++ object to an
 
6143
object in the target language when reading a C/C++ global variable.
 
6144
This is implementation specific.</p>
 
6145
 
 
6146
 
 
6147
 
 
6148
 
 
6149
 
 
6150
<H4><a name="Ruby_throws_typemap"></a>30.7.6.13 "throws" typemap</H4>
 
6151
 
 
6152
 
 
6153
<p> The "throws" typemap is only used when SWIG parses a C++
 
6154
method with an exception specification or has the <tt>%catches</tt>
 
6155
feature attached to the method. It provides a default mechanism for
 
6156
handling C++ methods that have declared the exceptions they will throw.
 
6157
The purpose of this typemap is to convert a C++ exception into an error
 
6158
or exception in the target language. It is slightly different to the
 
6159
other typemaps as it is based around the exception type rather than the
 
6160
type of a parameter or variable. For example:</p>
 
6161
 
 
6162
 
 
6163
 
 
6164
 
 
6165
 
 
6166
<div class="code">
 
6167
<pre>%typemap(throws) const char * %{<br> rb_raise(rb_eRuntimeError, $1);<br> SWIG_fail;<br>%}<br>void bar() throw (const char *);<br></pre>
 
6168
 
 
6169
 
 
6170
 
 
6171
 
 
6172
 
 
6173
</div>
 
6174
 
 
6175
 
 
6176
 
 
6177
 
 
6178
 
 
6179
<p> As can be seen from the generated code below, SWIG generates
 
6180
an exception handler with the catch block comprising the "throws"
 
6181
typemap content.</p>
 
6182
 
 
6183
 
 
6184
 
 
6185
 
 
6186
 
 
6187
<div class="code">
 
6188
<pre>...<br>try {<br> bar();<br>}<br>catch(char const *_e) {<br> rb_raise(rb_eRuntimeError, _e);<br> SWIG_fail;<br>}<br>...<br></pre>
 
6189
 
 
6190
 
 
6191
 
 
6192
 
 
6193
 
 
6194
</div>
 
6195
 
 
6196
 
 
6197
 
 
6198
 
 
6199
 
 
6200
<p> Note that if your methods do not have an exception
 
6201
specification yet they do throw exceptions, SWIG cannot know how to
 
6202
deal with them. For a neat way to handle these, see the <a href="http://www.swig.org/Doc1.3/SWIGDocumentation.html#exception">Exception
 
6203
handling with %exception</a> section.</p>
 
6204
 
 
6205
 
 
6206
 
 
6207
 
 
6208
 
 
6209
<H4><a name="Ruby_directorin_typemap"></a>30.7.6.14 directorin typemap</H4>
 
6210
 
 
6211
 
 
6212
<p>Converts C++ objects in director
 
6213
member functions to ruby objects.&nbsp;It is roughly the opposite
 
6214
of the "in" typemap, making its typemap rule often similar to the "out"
 
6215
typemap.
 
6216
</p>
 
6217
 
 
6218
 
 
6219
 
 
6220
 
 
6221
 
 
6222
<div class="code"><tt><br>
 
6223
 
 
6224
 
 
6225
 
 
6226
 
 
6227
 
 
6228
%typemap(directorin) int {<br>
 
6229
 
 
6230
 
 
6231
 
 
6232
 
 
6233
 
 
6234
&nbsp; &nbsp; &nbsp;$result = INT2NUM($1);<br>
 
6235
 
 
6236
 
 
6237
 
 
6238
 
 
6239
 
 
6240
}<br>
 
6241
 
 
6242
 
 
6243
 
 
6244
 
 
6245
 
 
6246
</tt></div>
 
6247
 
 
6248
 
 
6249
 
 
6250
 
 
6251
 
 
6252
<p> The following special variables are available.</p>
 
6253
 
 
6254
 
 
6255
 
 
6256
 
 
6257
 
 
6258
<div class="diagram">
 
6259
<table border="1" cellpadding="2" cellspacing="2" width="100%" summary="Special variables - directorin typemap">
 
6260
 
 
6261
 
 
6262
 
 
6263
 
 
6264
 
 
6265
  <tbody>
 
6266
 
 
6267
 
 
6268
 
 
6269
 
 
6270
 
 
6271
    <tr>
 
6272
 
 
6273
 
 
6274
 
 
6275
 
 
6276
 
 
6277
      <td style="font-family: monospace;">$result </td>
 
6278
 
 
6279
 
 
6280
 
 
6281
 
 
6282
 
 
6283
      <td style="font-family: monospace;"> Result object
 
6284
returned to target language.</td>
 
6285
 
 
6286
 
 
6287
 
 
6288
 
 
6289
 
 
6290
    </tr>
 
6291
 
 
6292
 
 
6293
 
 
6294
 
 
6295
 
 
6296
    <tr>
 
6297
 
 
6298
 
 
6299
 
 
6300
 
 
6301
 
 
6302
      <td style="font-family: monospace;">$symname </td>
 
6303
 
 
6304
 
 
6305
 
 
6306
 
 
6307
 
 
6308
      <td style="font-family: monospace;"> Name of
 
6309
function/method being wrapped</td>
 
6310
 
 
6311
 
 
6312
 
 
6313
 
 
6314
 
 
6315
    </tr>
 
6316
 
 
6317
 
 
6318
 
 
6319
 
 
6320
 
 
6321
    <tr>
 
6322
 
 
6323
 
 
6324
 
 
6325
 
 
6326
 
 
6327
      <td style="font-family: monospace;">$1...n </td>
 
6328
 
 
6329
 
 
6330
 
 
6331
 
 
6332
 
 
6333
      <td style="font-family: monospace;"> Argument being
 
6334
wrapped</td>
 
6335
 
 
6336
 
 
6337
 
 
6338
 
 
6339
 
 
6340
    </tr>
 
6341
 
 
6342
 
 
6343
 
 
6344
 
 
6345
 
 
6346
    <tr>
 
6347
 
 
6348
 
 
6349
 
 
6350
 
 
6351
 
 
6352
      <td style="font-family: monospace;">$1_name </td>
 
6353
 
 
6354
 
 
6355
 
 
6356
 
 
6357
 
 
6358
      <td style="font-family: monospace;"> Name of the
 
6359
argument (if provided)</td>
 
6360
 
 
6361
 
 
6362
 
 
6363
 
 
6364
 
 
6365
    </tr>
 
6366
 
 
6367
 
 
6368
 
 
6369
 
 
6370
 
 
6371
    <tr>
 
6372
 
 
6373
 
 
6374
 
 
6375
 
 
6376
 
 
6377
      <td style="font-family: monospace;">$1_type </td>
 
6378
 
 
6379
 
 
6380
 
 
6381
 
 
6382
 
 
6383
      <td style="font-family: monospace;"> The actual C
 
6384
datatype matched by the typemap.</td>
 
6385
 
 
6386
 
 
6387
 
 
6388
 
 
6389
 
 
6390
    </tr>
 
6391
 
 
6392
 
 
6393
 
 
6394
 
 
6395
 
 
6396
    <tr>
 
6397
 
 
6398
 
 
6399
 
 
6400
 
 
6401
 
 
6402
      <td style="font-family: monospace;">$1_ltype </td>
 
6403
 
 
6404
 
 
6405
 
 
6406
 
 
6407
 
 
6408
      <td style="font-family: monospace;"> The assignable
 
6409
version of the C datatype matched by the typemap.</td>
 
6410
 
 
6411
 
 
6412
 
 
6413
 
 
6414
 
 
6415
    </tr>
 
6416
 
 
6417
 
 
6418
 
 
6419
 
 
6420
 
 
6421
    <tr>
 
6422
 
 
6423
 
 
6424
 
 
6425
 
 
6426
 
 
6427
      <td style="font-family: monospace;">this </td>
 
6428
 
 
6429
 
 
6430
 
 
6431
 
 
6432
 
 
6433
      <td style="font-family: monospace;"> C++ this,
 
6434
referring to the class itself.</td>
 
6435
 
 
6436
 
 
6437
 
 
6438
 
 
6439
 
 
6440
    </tr>
 
6441
 
 
6442
 
 
6443
 
 
6444
 
 
6445
 
 
6446
  
 
6447
  
 
6448
  
 
6449
  
 
6450
  </tbody>
 
6451
</table>
 
6452
 
 
6453
 
 
6454
 
 
6455
 
 
6456
 
 
6457
</div>
 
6458
 
 
6459
 
 
6460
 
 
6461
 
 
6462
 
 
6463
<H4><a name="Ruby_directorout_typemap"></a>30.7.6.15 directorout typemap</H4>
 
6464
 
 
6465
 
 
6466
<p>Converts Ruby objects in director
 
6467
member functions to C++ objects. &nbsp;It is roughly the opposite
 
6468
of the "out" typemap, making its rule often similar to the "in"
 
6469
typemap.
 
6470
</p>
 
6471
 
 
6472
 
 
6473
 
 
6474
 
 
6475
 
 
6476
<div class="code"><tt style="font-family: monospace;"><br>
 
6477
 
 
6478
 
 
6479
 
 
6480
 
 
6481
 
 
6482
%typemap(directorout) int {</tt><tt><br>
 
6483
 
 
6484
 
 
6485
 
 
6486
 
 
6487
 
 
6488
&nbsp; &nbsp;$result =&nbsp;NUM2INT($1);</tt><br>
 
6489
 
 
6490
 
 
6491
 
 
6492
 
 
6493
 
 
6494
<tt style="font-family: monospace;">}<br>
 
6495
 
 
6496
 
 
6497
 
 
6498
 
 
6499
 
 
6500
</tt></div>
 
6501
 
 
6502
 
 
6503
 
 
6504
 
 
6505
 
 
6506
<p> The following special variables are available:</p>
 
6507
 
 
6508
 
 
6509
 
 
6510
 
 
6511
 
 
6512
<div class="diagram">
 
6513
<table border="1" cellpadding="2" cellspacing="2" width="100%" summary="Special variables - directorout typemap">
 
6514
 
 
6515
 
 
6516
 
 
6517
 
 
6518
 
 
6519
  <tbody>
 
6520
 
 
6521
 
 
6522
 
 
6523
 
 
6524
 
 
6525
    <tr>
 
6526
 
 
6527
 
 
6528
 
 
6529
 
 
6530
 
 
6531
      <td style="font-family: monospace;">$symname </td>
 
6532
 
 
6533
 
 
6534
 
 
6535
 
 
6536
 
 
6537
      <td style="font-family: monospace;"> Name of
 
6538
function/method being wrapped</td>
 
6539
 
 
6540
 
 
6541
 
 
6542
 
 
6543
 
 
6544
    </tr>
 
6545
 
 
6546
 
 
6547
 
 
6548
 
 
6549
 
 
6550
    <tr>
 
6551
 
 
6552
 
 
6553
 
 
6554
 
 
6555
 
 
6556
      <td style="font-family: monospace;">$1...n </td>
 
6557
 
 
6558
 
 
6559
 
 
6560
 
 
6561
 
 
6562
      <td style="font-family: monospace;"> Argument being
 
6563
sent to the function</td>
 
6564
 
 
6565
 
 
6566
 
 
6567
 
 
6568
 
 
6569
    </tr>
 
6570
 
 
6571
 
 
6572
 
 
6573
 
 
6574
 
 
6575
    <tr>
 
6576
 
 
6577
 
 
6578
 
 
6579
 
 
6580
 
 
6581
      <td style="font-family: monospace;">$1_name </td>
 
6582
 
 
6583
 
 
6584
 
 
6585
 
 
6586
 
 
6587
      <td style="font-family: monospace;"> Name of the
 
6588
argument (if provided)</td>
 
6589
 
 
6590
 
 
6591
 
 
6592
 
 
6593
 
 
6594
    </tr>
 
6595
 
 
6596
 
 
6597
 
 
6598
 
 
6599
 
 
6600
    <tr>
 
6601
 
 
6602
 
 
6603
 
 
6604
 
 
6605
 
 
6606
      <td style="font-family: monospace;">$1_type </td>
 
6607
 
 
6608
 
 
6609
 
 
6610
 
 
6611
 
 
6612
      <td style="font-family: monospace;"> The actual C
 
6613
datatype matched by the typemap.</td>
 
6614
 
 
6615
 
 
6616
 
 
6617
 
 
6618
 
 
6619
    </tr>
 
6620
 
 
6621
 
 
6622
 
 
6623
 
 
6624
 
 
6625
    <tr>
 
6626
 
 
6627
 
 
6628
 
 
6629
 
 
6630
 
 
6631
      <td style="font-family: monospace;">$1_ltype </td>
 
6632
 
 
6633
 
 
6634
 
 
6635
 
 
6636
 
 
6637
      <td style="font-family: monospace;"> The assignable
 
6638
version of the C datatype matched by the typemap.</td>
 
6639
 
 
6640
 
 
6641
 
 
6642
 
 
6643
 
 
6644
    </tr>
 
6645
 
 
6646
 
 
6647
 
 
6648
 
 
6649
 
 
6650
    <tr>
 
6651
 
 
6652
 
 
6653
 
 
6654
 
 
6655
 
 
6656
      <td style="font-family: monospace;">this </td>
 
6657
 
 
6658
 
 
6659
 
 
6660
 
 
6661
 
 
6662
      <td style="font-family: monospace;"> C++ this,
 
6663
referring to the class itself.</td>
 
6664
 
 
6665
 
 
6666
 
 
6667
 
 
6668
 
 
6669
    </tr>
 
6670
 
 
6671
 
 
6672
 
 
6673
 
 
6674
 
 
6675
  
 
6676
  
 
6677
  
 
6678
  
 
6679
  </tbody>
 
6680
</table>
 
6681
 
 
6682
 
 
6683
 
 
6684
 
 
6685
 
 
6686
</div>
 
6687
 
 
6688
 
 
6689
 
 
6690
 
 
6691
 
 
6692
<p>Currently, the directorout nor the out typemap support the
 
6693
option&nbsp;<span style="font-family: monospace;">numoutputs</span>,
 
6694
but the Ruby module provides that functionality through a %feature
 
6695
directive. &nbsp;Thus, a function can be made to return "nothing"
 
6696
if you do:</p>
 
6697
 
 
6698
 
 
6699
 
 
6700
 
 
6701
 
 
6702
<div style="font-family: monospace;" class="code">%feature("numoutputs","0")
 
6703
MyClass::function;</div>
 
6704
 
 
6705
 
 
6706
 
 
6707
 
 
6708
 
 
6709
<p>This feature can be useful if a function returns a status
 
6710
code, which you want to discard but still use the typemap to raise an
 
6711
exception.<br>
 
6712
 
 
6713
 
 
6714
 
 
6715
 
 
6716
 
 
6717
</p>
 
6718
 
 
6719
 
 
6720
 
 
6721
 
 
6722
 
 
6723
<H4><a name="Ruby_directorargout_typemap"></a>30.7.6.16 directorargout typemap</H4>
 
6724
 
 
6725
 
 
6726
<p>Output argument processing in director
 
6727
member functions.</p>
 
6728
 
 
6729
 
 
6730
 
 
6731
 
 
6732
 
 
6733
<div class="code"><tt style="font-family: monospace;">%typemap(directorargout,
 
6734
fragment="output_helper") int {</tt><tt><br>
 
6735
 
 
6736
 
 
6737
 
 
6738
 
 
6739
 
 
6740
$result = output_helper( $result, NUM2INT($1) );</tt><br>
 
6741
 
 
6742
 
 
6743
 
 
6744
 
 
6745
 
 
6746
<tt style="font-family: monospace;">}</tt></div>
 
6747
 
 
6748
 
 
6749
 
 
6750
 
 
6751
 
 
6752
<p> The following special variables are available:</p>
 
6753
 
 
6754
 
 
6755
 
 
6756
 
 
6757
 
 
6758
<div class="diagram">
 
6759
<table style="text-align: left; width: 100%;" border="1" cellpadding="2" cellspacing="2" summary="Special variables - directorargout typemap">
 
6760
 
 
6761
 
 
6762
 
 
6763
 
 
6764
 
 
6765
  <tbody>
 
6766
 
 
6767
 
 
6768
 
 
6769
 
 
6770
 
 
6771
    <tr>
 
6772
 
 
6773
 
 
6774
 
 
6775
 
 
6776
 
 
6777
      <td style="font-family: monospace;">$result</td>
 
6778
 
 
6779
 
 
6780
 
 
6781
 
 
6782
 
 
6783
      <td style="font-family: monospace;">Result that the
 
6784
director function returns</td>
 
6785
 
 
6786
 
 
6787
 
 
6788
 
 
6789
 
 
6790
    </tr>
 
6791
 
 
6792
 
 
6793
 
 
6794
 
 
6795
 
 
6796
    <tr>
 
6797
 
 
6798
 
 
6799
 
 
6800
 
 
6801
 
 
6802
      <td style="font-family: monospace;">$symname</td>
 
6803
 
 
6804
 
 
6805
 
 
6806
 
 
6807
 
 
6808
      <td style="font-family: monospace;">name of the
 
6809
function/method being wrapped</td>
 
6810
 
 
6811
 
 
6812
 
 
6813
 
 
6814
 
 
6815
    </tr>
 
6816
 
 
6817
 
 
6818
 
 
6819
 
 
6820
 
 
6821
    <tr>
 
6822
 
 
6823
 
 
6824
 
 
6825
 
 
6826
 
 
6827
      <td style="font-family: monospace;">$1...n</td>
 
6828
 
 
6829
 
 
6830
 
 
6831
 
 
6832
 
 
6833
      <td style="font-family: monospace;">Argument being
 
6834
sent to the function</td>
 
6835
 
 
6836
 
 
6837
 
 
6838
 
 
6839
 
 
6840
    </tr>
 
6841
 
 
6842
 
 
6843
 
 
6844
 
 
6845
 
 
6846
    <tr>
 
6847
 
 
6848
 
 
6849
 
 
6850
 
 
6851
 
 
6852
      <td style="font-family: monospace;">$1_name</td>
 
6853
 
 
6854
 
 
6855
 
 
6856
 
 
6857
 
 
6858
      <td style="font-family: monospace;">Name of the
 
6859
argument (if provided)</td>
 
6860
 
 
6861
 
 
6862
 
 
6863
 
 
6864
 
 
6865
    </tr>
 
6866
 
 
6867
 
 
6868
 
 
6869
 
 
6870
 
 
6871
    <tr>
 
6872
 
 
6873
 
 
6874
 
 
6875
 
 
6876
 
 
6877
      <td style="font-family: monospace;">$1_type</td>
 
6878
 
 
6879
 
 
6880
 
 
6881
 
 
6882
 
 
6883
      <td style="font-family: monospace;">The actual C
 
6884
datatype matched by the typemap</td>
 
6885
 
 
6886
 
 
6887
 
 
6888
 
 
6889
 
 
6890
    </tr>
 
6891
 
 
6892
 
 
6893
 
 
6894
 
 
6895
 
 
6896
    <tr>
 
6897
 
 
6898
 
 
6899
 
 
6900
 
 
6901
 
 
6902
      <td style="font-family: monospace;">$1_ltype</td>
 
6903
 
 
6904
 
 
6905
 
 
6906
 
 
6907
 
 
6908
      <td style="font-family: monospace;">The assignable
 
6909
version of the C datatype matched by the typemap</td>
 
6910
 
 
6911
 
 
6912
 
 
6913
 
 
6914
 
 
6915
    </tr>
 
6916
 
 
6917
 
 
6918
 
 
6919
 
 
6920
 
 
6921
    <tr>
 
6922
 
 
6923
 
 
6924
 
 
6925
 
 
6926
 
 
6927
      <td style="font-family: monospace;">this</td>
 
6928
 
 
6929
 
 
6930
 
 
6931
 
 
6932
 
 
6933
      <td style="font-family: monospace;">C++ this,
 
6934
referring to the instance of the class itself</td>
 
6935
 
 
6936
 
 
6937
 
 
6938
 
 
6939
 
 
6940
    </tr>
 
6941
 
 
6942
 
 
6943
 
 
6944
 
 
6945
 
 
6946
  
 
6947
  
 
6948
  
 
6949
  
 
6950
  </tbody>
 
6951
</table>
 
6952
 
 
6953
 
 
6954
 
 
6955
 
 
6956
 
 
6957
</div>
 
6958
 
 
6959
 
 
6960
 
 
6961
 
 
6962
 
 
6963
<H4><a name="Ruby_ret_typemap"></a>30.7.6.17 ret typemap</H4>
 
6964
 
 
6965
 
 
6966
<p>Cleanup of function return values
 
6967
</p>
 
6968
 
 
6969
 
 
6970
 
 
6971
 
 
6972
 
 
6973
<H4><a name="Ruby_globalin_typemap"></a>30.7.6.18 globalin typemap</H4>
 
6974
 
 
6975
 
 
6976
<p>Setting of C global variables
 
6977
</p>
 
6978
 
 
6979
 
 
6980
 
 
6981
 
 
6982
 
 
6983
<H3><a name="Ruby_nn40"></a>30.7.7 Typemap variables</H3>
 
6984
 
 
6985
 
 
6986
<p>
 
6987
Within a typemap, a number of special variables prefaced with a <tt>$</tt>
 
6988
may appear. A full list of variables can be found in the "<a href="Typemaps.html#Typemaps">Typemaps</a>" chapter.
 
6989
This is a list of the most common variables:
 
6990
</p>
 
6991
 
 
6992
 
 
6993
 
 
6994
 
 
6995
 
 
6996
<p><tt>$1</tt> </p>
 
6997
 
 
6998
 
 
6999
 
 
7000
 
 
7001
 
 
7002
<div class="indent">A C local variable corresponding to
 
7003
the actual type specified in the <tt>%typemap</tt>
 
7004
directive. For input values, this is a C local variable that is
 
7005
supposed to hold an argument value. For output values, this is the raw
 
7006
result that is supposed to be returned to Ruby. </div>
 
7007
 
 
7008
 
 
7009
 
 
7010
 
 
7011
 
 
7012
<p><tt>$input</tt></p>
 
7013
 
 
7014
 
 
7015
 
 
7016
 
 
7017
 
 
7018
<div class="indent">A <tt>VALUE</tt> holding
 
7019
a raw Ruby object with an argument or variable value. </div>
 
7020
 
 
7021
 
 
7022
 
 
7023
 
 
7024
 
 
7025
<p><tt>$result</tt></p>
 
7026
 
 
7027
 
 
7028
 
 
7029
 
 
7030
 
 
7031
<div class="indent">A <tt>VALUE</tt> that
 
7032
holds the result to be returned to Ruby. </div>
 
7033
 
 
7034
 
 
7035
 
 
7036
 
 
7037
 
 
7038
<p><tt>$1_name</tt></p>
 
7039
 
 
7040
 
 
7041
 
 
7042
 
 
7043
 
 
7044
<div class="indent">The parameter name that was matched. </div>
 
7045
 
 
7046
 
 
7047
 
 
7048
 
 
7049
 
 
7050
<p><tt>$1_type</tt></p>
 
7051
 
 
7052
 
 
7053
 
 
7054
 
 
7055
 
 
7056
<div class="indent">The actual C datatype matched by the
 
7057
typemap. </div>
 
7058
 
 
7059
 
 
7060
 
 
7061
 
 
7062
 
 
7063
<p><tt>$1_ltype</tt></p>
 
7064
 
 
7065
 
 
7066
 
 
7067
 
 
7068
 
 
7069
<div class="indent">An assignable version of the datatype
 
7070
matched by the typemap (a type that can appear on the left-hand-side of
 
7071
a C assignment operation). This type is stripped of qualifiers and may
 
7072
be an altered version of <tt>$1_type</tt>. All arguments
 
7073
and local variables in wrapper functions are declared using this type
 
7074
so that their values can be properly assigned. </div>
 
7075
 
 
7076
 
 
7077
 
 
7078
 
 
7079
 
 
7080
<p><tt>$symname</tt></p>
 
7081
 
 
7082
 
 
7083
 
 
7084
 
 
7085
 
 
7086
<div class="indent">The Ruby name of the wrapper function
 
7087
being created. </div>
 
7088
 
 
7089
 
 
7090
 
 
7091
 
 
7092
 
 
7093
<H3><a name="Ruby_nn41"></a>30.7.8 Useful Functions</H3>
 
7094
 
 
7095
 
 
7096
<p> When you write a typemap, you usually have to work directly
 
7097
with Ruby objects. The following functions may prove to be useful.
 
7098
(These functions plus many more can be found in <a href="http://www.rubycentral.com/book"><em>Programming
 
7099
Ruby</em></a>, by David Thomas and Andrew Hunt.)&nbsp;</p>
 
7100
<p>In addition, we list equivalent functions that Swig defines, which
 
7101
provide a language neutral conversion (these functions are defined for
 
7102
each swig language supported). &nbsp;If you are trying to create a swig
 
7103
file that will work under multiple languages, it is recommended you
 
7104
stick to the swig functions instead of the native Ruby functions.
 
7105
&nbsp;That should help you avoid having to rewrite a lot of typemaps
 
7106
across multiple languages.</p>
 
7107
 
 
7108
 
 
7109
 
 
7110
 
 
7111
 
 
7112
 
 
7113
 
 
7114
 
 
7115
 
 
7116
 
 
7117
<H4><a name="Ruby_nn42"></a>30.7.8.1 C Datatypes to Ruby Objects</H4>
 
7118
 
 
7119
 
 
7120
<div class="diagram">
 
7121
<table style="width: 100%;" border="1" cellpadding="2" cellspacing="2" summary="Datatypes">
 
7122
 
 
7123
  <tbody>
 
7124
    <tr>
 
7125
      <th style="font-weight: bold;">RUBY</th>
 
7126
      <th style="font-weight: bold;">Swig</th>
 
7127
      <td></td>
 
7128
    </tr>
 
7129
    <tr>
 
7130
      <td style="font-family: monospace;">INT2NUM(long or int) </td>
 
7131
      <td style="font-family: monospace;">SWIG_From_int(int x)</td>
 
7132
      <td> int to Fixnum or Bignum</td>
 
7133
    </tr>
 
7134
 
 
7135
    <tr>
 
7136
      <td style="font-family: monospace;">INT2FIX(long or int) </td>
 
7137
      <td style="font-family: monospace;"></td>
 
7138
      <td> int to Fixnum (faster than INT2NUM)</td>
 
7139
    </tr>
 
7140
 
 
7141
    <tr>
 
7142
      <td style="font-family: monospace;">CHR2FIX(char) </td>
 
7143
      <td style="font-family: monospace;">SWIG_From_char(char x)</td>
 
7144
      <td> char to Fixnum</td>
 
7145
    </tr>
 
7146
 
 
7147
    <tr>
 
7148
      <td style="font-family: monospace;">rb_str_new2(char*) </td>
 
7149
      <td style="font-family: monospace;">SWIG_FromCharPtrAndSize(char*, size_t)</td>
 
7150
      <td> char* to String</td>
 
7151
    </tr>
 
7152
 
 
7153
    <tr>
 
7154
      <td style="font-family: monospace;">rb_float_new(double) </td>
 
7155
      <td style="font-family: monospace;">SWIG_From_double(double),<br>
 
7156
SWIG_From_float(float)</td>
 
7157
      <td>float/double to Float</td>
 
7158
    </tr>
 
7159
 
 
7160
  </tbody>
 
7161
</table>
 
7162
 
 
7163
 
 
7164
 
 
7165
 
 
7166
 
 
7167
</div>
 
7168
 
 
7169
 
 
7170
 
 
7171
 
 
7172
 
 
7173
<H4><a name="Ruby_nn43"></a>30.7.8.2 Ruby Objects to C Datatypes</H4>
 
7174
 
 
7175
 
 
7176
<p>Here, while the Ruby versions return the value directly, the SWIG
 
7177
versions do not, but return a status value to indicate success (<span style="font-family: monospace;">SWIG_OK</span>). While more akward to use, this allows you to write typemaps that report more helpful error messages, like:</p>
 
7178
<div style="font-family: monospace;" class="code"><br>
 
7179
%typemap(in) size_t (int ok)<br>
 
7180
&nbsp; <br>
 
7181
&nbsp; ok = SWIG_AsVal_size_t($input, &amp;$1);<br>
 
7182
&nbsp; if (!SWIG_IsOK(ok)) {<br>
 
7183
&nbsp;&nbsp;&nbsp; SWIG_exception_fail(SWIG_ArgError(ok),
 
7184
Ruby_Format_TypeError( "$1_name", "$1_type","$symname", $argnum, $input
 
7185
));<br>
 
7186
&nbsp; &nbsp;}<br>
 
7187
<br>
 
7188
} </div>
 
7189
<div style="font-family: monospace;">&nbsp;&nbsp;</div>
 
7190
<div class="diagram">
 
7191
<table border="1" cellpadding="2" cellspacing="2" width="100%" summary="Ruby objects">
 
7192
 
 
7193
  <tbody>
 
7194
    <tr>
 
7195
      <td style="font-family: monospace;">int NUM2INT(Numeric)</td>
 
7196
      <td style="font-family: monospace;">SWIG_AsVal_int(VALUE, int*)</td>
 
7197
    </tr>
 
7198
 
 
7199
    <tr>
 
7200
      <td style="font-family: monospace;">int FIX2INT(Numeric)</td>
 
7201
      <td style="font-family: monospace;">SWIG_AsVal_int(VALUE, int*)</td>
 
7202
    </tr>
 
7203
 
 
7204
    <tr>
 
7205
      <td style="font-family: monospace;">unsigned int NUM2UINT(Numeric)</td>
 
7206
      <td style="font-family: monospace;">SWIG_AsVal_unsigned_SS_int(VALUE, int*)</td>
 
7207
    </tr>
 
7208
 
 
7209
    <tr>
 
7210
      <td style="font-family: monospace;">unsigned int FIX2UINT(Numeric)</td>
 
7211
      <td style="font-family: monospace;">SWIG_AsVal_unsigned_SS_int(VALUE, int*)</td>
 
7212
    </tr>
 
7213
 
 
7214
    <tr>
 
7215
      <td style="font-family: monospace;">long NUM2LONG(Numeric)</td>
 
7216
      <td style="font-family: monospace;">SWIG_AsVal_long(VALUE, long*)</td>
 
7217
    </tr>
 
7218
 
 
7219
    <tr>
 
7220
      <td style="font-family: monospace;">long FIX2LONG(Numeric)</td>
 
7221
      <td style="font-family: monospace;">SWIG_AsVal_long(VALUE, long*)</td>
 
7222
    </tr>
 
7223
 
 
7224
    <tr>
 
7225
      <td style="font-family: monospace;">unsigned long FIX2ULONG(Numeric)</td>
 
7226
      <td style="font-family: monospace;">SWIG_AsVal_unsigned_SS_long(VALUE, unsigned long*)</td>
 
7227
    </tr>
 
7228
 
 
7229
    <tr>
 
7230
      <td style="font-family: monospace;">char NUM2CHR(Numeric or String)</td>
 
7231
      <td style="font-family: monospace;">SWIG_AsVal_char(VALUE, int*)</td>
 
7232
    </tr>
 
7233
 
 
7234
    <tr>
 
7235
      <td style="font-family: monospace;">char * STR2CSTR(String)</td>
 
7236
      <td style="font-family: monospace;">SWIG_AsCharPtrAndSize(VALUE, char*, size_t, int* alloc)</td>
 
7237
    </tr>
 
7238
 
 
7239
    <tr>
 
7240
      <td style="font-family: monospace;">char * rb_str2cstr(String, int*length)</td>
 
7241
      <td style="font-family: monospace;"></td>
 
7242
    </tr>
 
7243
 
 
7244
    <tr>
 
7245
      <td style="font-family: monospace;">double NUM2DBL(Numeric)</td>
 
7246
      <td style="font-family: monospace;">(double) SWIG_AsVal_int(VALUE) or similar</td>
 
7247
    </tr>
 
7248
 
 
7249
  </tbody>
 
7250
</table>
 
7251
 
 
7252
 
 
7253
 
 
7254
 
 
7255
 
 
7256
</div>
 
7257
 
 
7258
 
 
7259
 
 
7260
 
 
7261
 
 
7262
<H4><a name="Ruby_nn44"></a>30.7.8.3 Macros for VALUE</H4>
 
7263
 
 
7264
 
 
7265
<p> <tt>RSTRING_LEN(str)</tt> </p>
 
7266
 
 
7267
 
 
7268
 
 
7269
 
 
7270
 
 
7271
<div class="indent">length of the Ruby string</div>
 
7272
 
 
7273
 
 
7274
 
 
7275
 
 
7276
 
 
7277
<p><tt>RSTRING_PTR(str)</tt></p>
 
7278
 
 
7279
 
 
7280
 
 
7281
 
 
7282
 
 
7283
<div class="indent">pointer to string storage</div>
 
7284
 
 
7285
 
 
7286
 
 
7287
 
 
7288
 
 
7289
<p><tt>RARRAY_LEN(arr)</tt></p>
 
7290
 
 
7291
 
 
7292
 
 
7293
 
 
7294
 
 
7295
<div class="indent">length of the Ruby array</div>
 
7296
 
 
7297
 
 
7298
 
 
7299
 
 
7300
 
 
7301
<p><tt>RARRAY(arr)-&gt;capa</tt></p>
 
7302
 
 
7303
 
 
7304
 
 
7305
 
 
7306
 
 
7307
<div class="indent">capacity of the Ruby array</div>
 
7308
 
 
7309
 
 
7310
 
 
7311
 
 
7312
 
 
7313
<p><tt>RARRAY_PTR(arr)</tt></p>
 
7314
 
 
7315
 
 
7316
 
 
7317
 
 
7318
 
 
7319
<div class="indent">pointer to array storage</div>
 
7320
 
 
7321
 
 
7322
 
 
7323
 
 
7324
 
 
7325
<H4><a name="Ruby_nn45"></a>30.7.8.4 Exceptions</H4>
 
7326
 
 
7327
 
 
7328
<p> <tt>void rb_raise(VALUE exception, const char *fmt,
 
7329
...)</tt> </p>
 
7330
 
 
7331
 
 
7332
 
 
7333
 
 
7334
 
 
7335
<div class="indent"> Raises an exception. The given format
 
7336
string <i>fmt</i> and remaining arguments are interpreted
 
7337
as with <tt>printf()</tt>. </div>
 
7338
 
 
7339
 
 
7340
 
 
7341
 
 
7342
 
 
7343
<p><tt>void rb_fatal(const char *fmt, ...)</tt></p>
 
7344
 
 
7345
 
 
7346
 
 
7347
 
 
7348
 
 
7349
<div class="indent"> Raises a fatal exception, terminating
 
7350
the process. No rescue blocks are called, but ensure blocks will be
 
7351
called. The given format string <i>fmt</i> and remaining
 
7352
arguments are interpreted as with <tt>printf()</tt>. </div>
 
7353
 
 
7354
 
 
7355
 
 
7356
 
 
7357
 
 
7358
<p><tt>void rb_bug(const char *fmt, ...)</tt></p>
 
7359
 
 
7360
 
 
7361
 
 
7362
 
 
7363
 
 
7364
<div class="indent"> Terminates the process immediately --
 
7365
no handlers of any sort will be called. The given format string <i>fmt</i>
 
7366
and remaining arguments are interpreted as with <tt>printf()</tt>.
 
7367
You should call this function only if a fatal bug has been exposed. </div>
 
7368
 
 
7369
 
 
7370
 
 
7371
 
 
7372
 
 
7373
<p><tt>void rb_sys_fail(const char *msg)</tt></p>
 
7374
 
 
7375
 
 
7376
 
 
7377
 
 
7378
 
 
7379
<div class="indent"> Raises a platform-specific exception
 
7380
corresponding to the last known system error, with the given string <i>msg</i>.
 
7381
</div>
 
7382
 
 
7383
 
 
7384
 
 
7385
 
 
7386
 
 
7387
<p><tt>VALUE rb_rescue(VALUE (*body)(VALUE), VALUE args,
 
7388
VALUE(*rescue)(VALUE, VALUE), VALUE rargs)</tt></p>
 
7389
 
 
7390
 
 
7391
 
 
7392
 
 
7393
 
 
7394
<div class="indent"> Executes <i>body</i>
 
7395
with the given <i>args</i>. If a <tt>StandardError</tt>
 
7396
exception is raised, then execute <i>rescue</i> with the
 
7397
given <i>rargs</i>. </div>
 
7398
 
 
7399
 
 
7400
 
 
7401
 
 
7402
 
 
7403
<p><tt>VALUE rb_ensure(VALUE(*body)(VALUE), VALUE args,
 
7404
VALUE(*ensure)(VALUE), VALUE eargs)</tt></p>
 
7405
 
 
7406
 
 
7407
 
 
7408
 
 
7409
 
 
7410
<div class="indent"> Executes <i>body</i>
 
7411
with the given <i>args</i>. Whether or not an exception is
 
7412
raised, execute <i>ensure</i> with the given <i>rargs</i>
 
7413
after <i>body</i> has completed. </div>
 
7414
 
 
7415
 
 
7416
 
 
7417
 
 
7418
 
 
7419
<p><tt>VALUE rb_protect(VALUE (*body)(VALUE), VALUE args,
 
7420
int *result)</tt></p>
 
7421
 
 
7422
 
 
7423
 
 
7424
 
 
7425
 
 
7426
<div class="indent"> Executes <i>body</i>
 
7427
with the given <i>args</i> and returns nonzero in result
 
7428
if any exception was raised. </div>
 
7429
 
 
7430
 
 
7431
 
 
7432
 
 
7433
 
 
7434
<p><tt>void rb_notimplement()</tt></p>
 
7435
 
 
7436
 
 
7437
 
 
7438
 
 
7439
 
 
7440
<div class="indent"> Raises a <tt>NotImpError</tt>
 
7441
exception to indicate that the enclosed function is not implemented
 
7442
yet, or not available on this platform. </div>
 
7443
 
 
7444
 
 
7445
 
 
7446
 
 
7447
 
 
7448
<p><tt>void rb_exit(int status)</tt></p>
 
7449
 
 
7450
 
 
7451
 
 
7452
 
 
7453
 
 
7454
<div class="indent"> Exits Ruby with the given <i>status</i>.
 
7455
Raises a <tt>SystemExit</tt> exception and calls
 
7456
registered exit functions and finalizers. </div>
 
7457
 
 
7458
 
 
7459
 
 
7460
 
 
7461
 
 
7462
<p><tt>void rb_warn(const char *fmt, ...)</tt></p>
 
7463
 
 
7464
 
 
7465
 
 
7466
 
 
7467
 
 
7468
<div class="indent"> Unconditionally issues a warning
 
7469
message to standard error. The given format string <i>fmt</i>
 
7470
and remaining arguments are interpreted as with <tt>printf()</tt>.
 
7471
</div>
 
7472
 
 
7473
 
 
7474
 
 
7475
 
 
7476
 
 
7477
<p><tt>void rb_warning(const char *fmt, ...)</tt></p>
 
7478
 
 
7479
 
 
7480
 
 
7481
 
 
7482
 
 
7483
<div class="indent"> Conditionally issues a warning
 
7484
message to standard error if Ruby was invoked with the <tt>-w</tt>
 
7485
flag. The given format string <i>fmt</i> and remaining
 
7486
arguments are interpreted as with <tt>printf()</tt>. </div>
 
7487
 
 
7488
 
 
7489
 
 
7490
 
 
7491
 
 
7492
<H4><a name="Ruby_nn46"></a>30.7.8.5 Iterators</H4>
 
7493
 
 
7494
 
 
7495
<p> <tt>void rb_iter_break()</tt> </p>
 
7496
 
 
7497
 
 
7498
 
 
7499
 
 
7500
 
 
7501
<div class="indent"> Breaks out of the enclosing iterator
 
7502
block. </div>
 
7503
 
 
7504
 
 
7505
 
 
7506
 
 
7507
 
 
7508
<p><tt>VALUE rb_each(VALUE obj)</tt></p>
 
7509
 
 
7510
 
 
7511
 
 
7512
 
 
7513
 
 
7514
<div class="indent"> Invokes the <tt>each</tt>
 
7515
method of the given <i>obj</i>. </div>
 
7516
 
 
7517
 
 
7518
 
 
7519
 
 
7520
 
 
7521
<p><tt>VALUE rb_yield(VALUE arg)</tt></p>
 
7522
 
 
7523
 
 
7524
 
 
7525
 
 
7526
 
 
7527
<div class="indent"> Transfers execution to the iterator
 
7528
block in the current context, passing <i>arg</i> as an
 
7529
argument. Multiple values may be passed in an array. </div>
 
7530
 
 
7531
 
 
7532
 
 
7533
 
 
7534
 
 
7535
<p><tt>int rb_block_given_p()</tt></p>
 
7536
 
 
7537
 
 
7538
 
 
7539
 
 
7540
 
 
7541
<div class="indent"> Returns <tt>true</tt> if
 
7542
<tt>yield</tt> would execute a block in the current
 
7543
context; that is, if a code block was passed to the current method and
 
7544
is available to be called. </div>
 
7545
 
 
7546
 
 
7547
 
 
7548
 
 
7549
 
 
7550
<p><tt>VALUE rb_iterate(VALUE (*method)(VALUE), VALUE args,
 
7551
VALUE (*block)(VALUE, VALUE), VALUE arg2)</tt></p>
 
7552
 
 
7553
 
 
7554
 
 
7555
 
 
7556
 
 
7557
<div class="indent"> Invokes <i>method</i>
 
7558
with argument <i>args</i> and block <i>block</i>.
 
7559
A <tt>yield</tt> from that method will invoke <i>block</i>
 
7560
with the argument given to <tt>yield</tt>, and a second
 
7561
argument <i>arg2</i>. </div>
 
7562
 
 
7563
 
 
7564
 
 
7565
 
 
7566
 
 
7567
<p><tt>VALUE rb_catch(const char *tag, VALUE (*proc)(VALUE,
 
7568
VALUE), VALUE value)</tt></p>
 
7569
 
 
7570
 
 
7571
 
 
7572
 
 
7573
 
 
7574
<div class="indent"> Equivalent to Ruby's <tt>catch</tt>.
 
7575
</div>
 
7576
 
 
7577
 
 
7578
 
 
7579
 
 
7580
 
 
7581
<p><tt>void rb_throw(const char *tag, VALUE value)</tt></p>
 
7582
 
 
7583
 
 
7584
 
 
7585
 
 
7586
 
 
7587
<div class="indent"> Equivalent to Ruby's <tt>throw</tt>.
 
7588
</div>
 
7589
 
 
7590
 
 
7591
 
 
7592
 
 
7593
 
 
7594
<H3><a name="Ruby_nn47"></a>30.7.9 Typemap Examples</H3>
 
7595
 
 
7596
 
 
7597
<p> This section includes a few examples of typemaps. For more
 
7598
examples, you might look at the examples in the <tt>Example/ruby</tt>
 
7599
directory. </p>
 
7600
 
 
7601
 
 
7602
 
 
7603
 
 
7604
 
 
7605
<H3><a name="Ruby_nn48"></a>30.7.10 Converting a Ruby array to a char **</H3>
 
7606
 
 
7607
 
 
7608
<p> A common problem in many C programs is the processing of
 
7609
command line arguments, which are usually passed in an array of <tt>NULL</tt>
 
7610
terminated strings. The following SWIG interface file allows a Ruby
 
7611
Array instance to be used as a <tt>char **</tt> object. </p>
 
7612
 
 
7613
 
 
7614
 
 
7615
 
 
7616
 
 
7617
<div class="code">
 
7618
<pre>%module argv<br><br>// This tells SWIG to treat char ** as a special case<br>%typemap(in) char ** {<br> /* Get the length of the array */<br> int size = RARRAY($input)-&gt;len; <br> int i;<br> $1 = (char **) malloc((size+1)*sizeof(char *));<br> /* Get the first element in memory */<br> VALUE *ptr = RARRAY($input)-&gt;ptr; <br> for (i=0; i &lt; size; i++, ptr++)<br> /* Convert Ruby Object String to char* */<br> $1[i]= STR2CSTR(*ptr); <br> $1[i]=NULL; /* End of list */<br>}<br><br>// This cleans up the char ** array created before <br>// the function call<br><br>%typemap(freearg) char ** {<br> free((char *) $1);<br>}<br><br>// Now a test function<br>%inline %{<br>int print_args(char **argv) {<br> int i = 0;<br> while (argv[i]) {<br> printf("argv[%d] = %s\n", i,argv[i]);<br> i++;<br> }<br> return i;<br>}<br>%}<br><br></pre>
 
7619
 
 
7620
 
 
7621
 
 
7622
 
 
7623
 
 
7624
</div>
 
7625
 
 
7626
 
 
7627
 
 
7628
 
 
7629
 
 
7630
<p> When this module is compiled, the wrapped C function now
 
7631
operates as follows : </p>
 
7632
 
 
7633
 
 
7634
 
 
7635
 
 
7636
 
 
7637
<div class="code targetlang">
 
7638
<pre>require 'Argv'<br>Argv.print_args(["Dave","Mike","Mary","Jane","John"])<br>argv[0] = Dave<br>argv[1] = Mike<br>argv[2] = Mary<br>argv[3] = Jane<br>argv[4] = John<br></pre>
 
7639
 
 
7640
 
 
7641
 
 
7642
 
 
7643
 
 
7644
</div>
 
7645
 
 
7646
 
 
7647
 
 
7648
 
 
7649
 
 
7650
<p> In the example, two different typemaps are used. The "in"
 
7651
typemap is used to receive an input argument and convert it to a C
 
7652
array. Since dynamic memory allocation is used to allocate memory for
 
7653
the array, the "freearg" typemap is used to later release this memory
 
7654
after the execution of the C function. </p>
 
7655
 
 
7656
 
 
7657
 
 
7658
 
 
7659
 
 
7660
<H3><a name="Ruby_nn49"></a>30.7.11 Collecting arguments in a hash</H3>
 
7661
 
 
7662
 
 
7663
<p> Ruby's solution to the "keyword arguments" capability of some
 
7664
other languages is to allow the programmer to pass in one or more
 
7665
key-value pairs as arguments to a function. All of those key-value
 
7666
pairs are collected in a single <tt>Hash</tt> argument
 
7667
that's presented to the function. If it makes sense, you might want to
 
7668
provide similar functionality for your Ruby interface. For example,
 
7669
suppose you'd like to wrap this C function that collects information
 
7670
about people's vital statistics: </p>
 
7671
 
 
7672
 
 
7673
 
 
7674
 
 
7675
 
 
7676
<div class="code">
 
7677
<pre>void setVitalStats(const char *person, int nattributes, const char **names, int *values);<br></pre>
 
7678
 
 
7679
 
 
7680
 
 
7681
 
 
7682
 
 
7683
</div>
 
7684
 
 
7685
 
 
7686
 
 
7687
 
 
7688
 
 
7689
<p> and you'd like to be able to call it from Ruby by passing in
 
7690
an arbitrary number of key-value pairs as inputs, e.g. </p>
 
7691
 
 
7692
 
 
7693
 
 
7694
 
 
7695
 
 
7696
<div class="code targetlang">
 
7697
<pre>setVitalStats("Fred",<br> 'weight' =&gt; 270,<br>  'age' =&gt; 42<br>      )<br></pre>
 
7698
 
 
7699
 
 
7700
 
 
7701
 
 
7702
 
 
7703
</div>
 
7704
 
 
7705
 
 
7706
 
 
7707
 
 
7708
 
 
7709
<p> To make this work, you need to write a typemap that expects a
 
7710
Ruby <tt>Hash</tt> as its input and somehow extracts the
 
7711
last three arguments (<i>nattributes</i>, <i>names</i>
 
7712
and <i>values</i>) needed by your C function. Let's start
 
7713
with the basics: </p>
 
7714
 
 
7715
 
 
7716
 
 
7717
 
 
7718
 
 
7719
<div class="code">
 
7720
<pre>%typemap(in) (int nattributes, const char **names, const int *values)<br> (VALUE keys_arr, int i, VALUE key, VALUE val) {<br>}<br> </pre>
 
7721
 
 
7722
 
 
7723
 
 
7724
 
 
7725
 
 
7726
</div>
 
7727
 
 
7728
 
 
7729
 
 
7730
 
 
7731
 
 
7732
<p> This <tt>%typemap</tt> directive tells SWIG that
 
7733
we want to match any function declaration that has the specified types
 
7734
and names of arguments somewhere in the argument list. The fact that we
 
7735
specified the argument names (<i>nattributes</i>, <i>names</i>
 
7736
and <i>values</i>) in our typemap is significant; this
 
7737
ensures that SWIG won't try to apply this typemap to <i>other</i>
 
7738
functions it sees that happen to have a similar declaration with
 
7739
different argument names. The arguments that appear in the second set
 
7740
of parentheses (<i>keys_arr</i>, <i>i</i>, <i>key</i>
 
7741
and <i>val</i>) define local variables that our typemap
 
7742
will need. </p>
 
7743
 
 
7744
 
 
7745
 
 
7746
 
 
7747
 
 
7748
<p>Since we expect the input argument to be a <tt>Hash</tt>,
 
7749
let's next add a check for that: </p>
 
7750
 
 
7751
 
 
7752
 
 
7753
 
 
7754
 
 
7755
<div class="code">
 
7756
<pre>%typemap(in) (int nattributes, const char **names, const int *values)<br> (VALUE keys_arr, int i, VALUE key, VALUE val) {<br> <b>Check_Type($input, T_HASH);</b><br>}<br></pre>
 
7757
 
 
7758
 
 
7759
 
 
7760
 
 
7761
 
 
7762
</div>
 
7763
 
 
7764
 
 
7765
 
 
7766
 
 
7767
 
 
7768
<p> <tt>Check_Type()</tt> is just a macro (defined
 
7769
in the Ruby header files) that confirms that the input argument is of
 
7770
the correct type; if it isn't, an exception will be raised. </p>
 
7771
 
 
7772
 
 
7773
 
 
7774
 
 
7775
 
 
7776
<p>The next task is to determine how many key-value pairs are
 
7777
present in the hash; we'll assign this number to the first typemap
 
7778
argument (<tt>$1</tt>). This is a little tricky since the
 
7779
Ruby/C API doesn't provide a public function for querying the size of a
 
7780
hash, but we can get around that by calling the hash's <i>size</i>
 
7781
method directly and converting its result to a C <tt>int</tt>
 
7782
value: </p>
 
7783
 
 
7784
 
 
7785
 
 
7786
 
 
7787
 
 
7788
<div class="code">
 
7789
<pre>%typemap(in) (int nattributes, const char **names, const int *values)<br> (VALUE keys_arr, int i, VALUE key, VALUE val) {<br> Check_Type($input, T_HASH);<br> <b>$1 = NUM2INT(rb_funcall($input, rb_intern("size"), 0, NULL));</b><br>}<br></pre>
 
7790
 
 
7791
 
 
7792
 
 
7793
 
 
7794
 
 
7795
</div>
 
7796
 
 
7797
 
 
7798
 
 
7799
 
 
7800
 
 
7801
<p> So now we know the number of attributes. Next we need to
 
7802
initialize the second and third typemap arguments (i.e. the two C
 
7803
arrays) to <tt>NULL</tt> and set the stage for extracting
 
7804
the keys and values from the hash: </p>
 
7805
 
 
7806
 
 
7807
 
 
7808
 
 
7809
 
 
7810
<div class="code">
 
7811
<pre>%typemap(in) (int nattributes, const char **names, const int *values)<br> (VALUE keys_arr, int i, VALUE key, VALUE val) {<br> Check_Type($input, T_HASH);<br> $1 = NUM2INT(rb_funcall($input, rb_intern("size"), 0, NULL));<br> <b>$2 = NULL;<br> $3 = NULL;<br> if ($1 &gt; 0) {<br> $2 = (char **) malloc($1*sizeof(char *));<br> $3 = (int *) malloc($1*sizeof(int));<br> }</b><br>}<br></pre>
 
7812
 
 
7813
 
 
7814
 
 
7815
 
 
7816
 
 
7817
</div>
 
7818
 
 
7819
 
 
7820
 
 
7821
 
 
7822
 
 
7823
<p> There are a number of ways we could extract the keys and
 
7824
values from the input hash, but the simplest approach is to first call
 
7825
the hash's <i>keys</i> method (which returns a Ruby array
 
7826
of the keys) and then start looping over the elements in that array: </p>
 
7827
 
 
7828
 
 
7829
 
 
7830
 
 
7831
 
 
7832
<div class="code">
 
7833
<pre>%typemap(in) (int nattributes, const char **names, const int *values)<br> (VALUE keys_arr, int i, VALUE key, VALUE val) {<br> Check_Type($input, T_HASH);<br> $1 = NUM2INT(rb_funcall($input, rb_intern("size"), 0, NULL));<br> $2 = NULL;<br> $3 = NULL;<br> if ($1 &gt; 0) {<br> $2 = (char **) malloc($1*sizeof(char *));<br> $3 = (int *) malloc($1*sizeof(int));<br> <b>keys_arr = rb_funcall($input, rb_intern("keys"), 0, NULL);<br> for (i = 0; i &lt; $1; i++) {<br> }</b><br>}<br>}<br></pre>
 
7834
 
 
7835
 
 
7836
 
 
7837
 
 
7838
 
 
7839
</div>
 
7840
 
 
7841
 
 
7842
 
 
7843
 
 
7844
 
 
7845
<p> Recall that <i>keys_arr</i> and <i>i</i>
 
7846
are local variables for this typemap. For each element in the <i>keys_arr</i>
 
7847
array, we want to get the key itself, as well as the value
 
7848
corresponding to that key in the hash: </p>
 
7849
 
 
7850
 
 
7851
 
 
7852
 
 
7853
 
 
7854
<div class="code">
 
7855
<pre>%typemap(in) (int nattributes, const char **names, const int *values)<br> (VALUE keys_arr, int i, VALUE key, VALUE val) {<br> Check_Type($input, T_HASH);<br> $1 = NUM2INT(rb_funcall($input, rb_intern("size"), 0, NULL));<br> $2 = NULL;<br> $3 = NULL;<br> if ($1 &gt; 0) {<br> $2 = (char **) malloc($1*sizeof(char *));<br> $3 = (int *) malloc($1*sizeof(int));<br> keys_arr = rb_funcall($input, rb_intern("keys"), 0, NULL);<br> for (i = 0; i &lt; $1; i++) {<br> <b>key = rb_ary_entry(keys_arr, i);<br> val = rb_hash_aref($input, key);</b><br>}<br>}<br>}<br></pre>
 
7856
 
 
7857
 
 
7858
 
 
7859
 
 
7860
 
 
7861
</div>
 
7862
 
 
7863
 
 
7864
 
 
7865
 
 
7866
 
 
7867
<p> To be safe, we should again use the <tt>Check_Type()</tt>
 
7868
macro to confirm that the key is a <tt>String</tt> and the
 
7869
value is a <tt>Fixnum</tt>: </p>
 
7870
 
 
7871
 
 
7872
 
 
7873
 
 
7874
 
 
7875
<div class="code">
 
7876
<pre>%typemap(in) (int nattributes, const char **names, const int *values)<br> (VALUE keys_arr, int i, VALUE key, VALUE val) {<br> Check_Type($input, T_HASH);<br> $1 = NUM2INT(rb_funcall($input, rb_intern("size"), 0, NULL));<br> $2 = NULL;<br> $3 = NULL;<br> if ($1 &gt; 0) {<br> $2 = (char **) malloc($1*sizeof(char *));<br> $3 = (int *) malloc($1*sizeof(int));<br> keys_arr = rb_funcall($input, rb_intern("keys"), 0, NULL);<br> for (i = 0; i &lt; $1; i++) {<br> key = rb_ary_entry(keys_arr, i);<br> val = rb_hash_aref($input, key);<br> <b>Check_Type(key, T_STRING);<br> Check_Type(val, T_FIXNUM);</b><br>}<br>}<br>}<br></pre>
 
7877
 
 
7878
 
 
7879
 
 
7880
 
 
7881
 
 
7882
</div>
 
7883
 
 
7884
 
 
7885
 
 
7886
 
 
7887
 
 
7888
<p> Finally, we can convert these Ruby objects into their C
 
7889
equivalents and store them in our local C arrays: </p>
 
7890
 
 
7891
 
 
7892
 
 
7893
 
 
7894
 
 
7895
<div class="code">
 
7896
<pre>%typemap(in) (int nattributes, const char **names, const int *values)<br> (VALUE keys_arr, int i, VALUE key, VALUE val) {<br> Check_Type($input, T_HASH);<br> $1 = NUM2INT(rb_funcall($input, rb_intern("size"), 0, NULL));<br> $2 = NULL;<br> $3 = NULL;<br> if ($1 &gt; 0) {<br> $2 = (char **) malloc($1*sizeof(char *));<br> $3 = (int *) malloc($1*sizeof(int));<br> keys_arr = rb_funcall($input, rb_intern("keys"), 0, NULL);<br> for (i = 0; i &lt; $1; i++) {<br> key = rb_ary_entry(keys_arr, i);<br> val = rb_hash_aref($input, key);<br> Check_Type(key, T_STRING);<br> Check_Type(val, T_FIXNUM);<br> <b>$2[i] = STR2CSTR(key);<br> $3[i] = NUM2INT(val);</b><br>}<br>}<br>}<br></pre>
 
7897
 
 
7898
 
 
7899
 
 
7900
 
 
7901
 
 
7902
</div>
 
7903
 
 
7904
 
 
7905
 
 
7906
 
 
7907
 
 
7908
<p> We're not done yet. Since we used <tt>malloc()</tt>
 
7909
to dynamically allocate the memory used for the <i>names</i>
 
7910
and <i>values</i> arguments, we need to provide a
 
7911
corresponding "freearg" typemap to free that memory so that there is no
 
7912
memory leak. Fortunately, this typemap is a lot easier to write: </p>
 
7913
 
 
7914
 
 
7915
 
 
7916
 
 
7917
 
 
7918
<div class="code">
 
7919
<pre>%typemap(freearg) (int nattributes, const char **names, const int *values) {<br> free((void *) $2);<br> free((void *) $3);<br>}<br></pre>
 
7920
 
 
7921
 
 
7922
 
 
7923
 
 
7924
 
 
7925
</div>
 
7926
 
 
7927
 
 
7928
 
 
7929
 
 
7930
 
 
7931
<p> All of the code for this example, as well as a sample Ruby
 
7932
program that uses the extension, can be found in the <tt>Examples/ruby/hashargs</tt>
 
7933
directory of the SWIG distribution. </p>
 
7934
 
 
7935
 
 
7936
 
 
7937
 
 
7938
 
 
7939
<H3><a name="Ruby_nn50"></a>30.7.12 Pointer handling</H3>
 
7940
 
 
7941
 
 
7942
<p> Occasionally, it might be necessary to convert pointer values
 
7943
that have been stored using the SWIG typed-pointer representation.
 
7944
Since there are several ways in which pointers can be represented, the
 
7945
following two functions are used to safely perform this conversion: </p>
 
7946
 
 
7947
 
 
7948
 
 
7949
 
 
7950
 
 
7951
<p><tt>int SWIG_ConvertPtr(VALUE obj, void **ptr,
 
7952
swig_type_info *ty, int flags)</tt> </p>
 
7953
 
 
7954
 
 
7955
 
 
7956
 
 
7957
 
 
7958
<div class="indent">Converts a Ruby object <i>obj</i>
 
7959
to a C pointer whose address is <i>ptr</i> (i.e. <i>ptr</i>
 
7960
is a pointer to a pointer). The third argument, <i>ty</i>,
 
7961
is a pointer to a SWIG type descriptor structure. If <i>ty</i>
 
7962
is not <tt>NULL</tt>, that type information is used to
 
7963
validate type compatibility and other aspects of the type conversion.
 
7964
If <i>flags</i> is non-zero, any type errors encountered
 
7965
during this validation result in a Ruby <tt>TypeError</tt>
 
7966
exception being raised; if <i>flags</i> is zero, such type
 
7967
errors will cause <tt>SWIG_ConvertPtr()</tt> to return -1
 
7968
but not raise an exception. If <i>ty</i> is <tt>NULL</tt>,
 
7969
no type-checking is performed. </div>
 
7970
 
 
7971
 
 
7972
 
 
7973
 
 
7974
 
 
7975
<p> <tt>VALUE SWIG_NewPointerObj(void *ptr, swig_type_info
 
7976
*ty, int own)</tt> </p>
 
7977
 
 
7978
 
 
7979
 
 
7980
 
 
7981
 
 
7982
<div class="indent">Creates a new Ruby pointer object.
 
7983
Here, <i>ptr</i> is the pointer to convert, <i>ty</i>
 
7984
is the SWIG type descriptor structure that describes the type, and <i>own</i>
 
7985
is a flag that indicates whether or not Ruby should take ownership of
 
7986
the pointer (i.e. whether Ruby should free this data when the
 
7987
corresponding Ruby instance is garbage-collected). </div>
 
7988
 
 
7989
 
 
7990
 
 
7991
 
 
7992
 
 
7993
<p> Both of these functions require the use of a special SWIG
 
7994
type-descriptor structure. This structure contains information about
 
7995
the mangled name of the datatype, type-equivalence information, as well
 
7996
as information about converting pointer values under C++ inheritance.
 
7997
For a type of <tt>Foo *</tt>, the type descriptor
 
7998
structure is usually accessed as follows: </p>
 
7999
 
 
8000
 
 
8001
 
 
8002
 
 
8003
 
 
8004
<div class="indent code">
 
8005
<pre>Foo *foo;<br>SWIG_ConvertPtr($input, (void **) &amp;foo, SWIGTYPE_p_Foo, 1);<br><br>VALUE obj;<br>obj = SWIG_NewPointerObj(f, SWIGTYPE_p_Foo, 0);<br></pre>
 
8006
 
 
8007
 
 
8008
 
 
8009
 
 
8010
 
 
8011
</div>
 
8012
 
 
8013
 
 
8014
 
 
8015
 
 
8016
 
 
8017
<p> In a typemap, the type descriptor should always be accessed
 
8018
using the special typemap variable <tt>$1_descriptor</tt>.
 
8019
For example: </p>
 
8020
 
 
8021
 
 
8022
 
 
8023
 
 
8024
 
 
8025
<div class="indent code">
 
8026
<pre>%typemap(in) Foo * {<br> SWIG_ConvertPtr($input, (void **) &amp;$1, $1_descriptor, 1);<br>}<br></pre>
 
8027
 
 
8028
 
 
8029
 
 
8030
 
 
8031
 
 
8032
</div>
 
8033
 
 
8034
 
 
8035
 
 
8036
 
 
8037
 
 
8038
<H4><a name="Ruby_nn51"></a>30.7.12.1 Ruby Datatype Wrapping</H4>
 
8039
 
 
8040
 
 
8041
<p> <tt>VALUE Data_Wrap_Struct(VALUE class, void
 
8042
(*mark)(void *), void (*free)(void *), void *ptr)</tt> </p>
 
8043
 
 
8044
 
 
8045
 
 
8046
 
 
8047
 
 
8048
<div class="indent">Given a pointer <i>ptr</i>
 
8049
to some C data, and the two garbage collection routines for this data (<i>mark</i>
 
8050
and <i>free</i>), return a <tt>VALUE</tt> for
 
8051
the Ruby object. </div>
 
8052
 
 
8053
 
 
8054
 
 
8055
 
 
8056
 
 
8057
<p><tt>VALUE Data_Make_Struct(VALUE class, <i>c-type</i>,
 
8058
void (*mark)(void *), void (*free)(void *), <i>c-type</i>
 
8059
*ptr)</tt></p>
 
8060
 
 
8061
 
 
8062
 
 
8063
 
 
8064
 
 
8065
<div class="indent">Allocates a new instance of a C data
 
8066
type <i>c-type</i>, assigns it to the pointer <i>ptr</i>,
 
8067
then wraps that pointer with <tt>Data_Wrap_Struct()</tt>
 
8068
as above. </div>
 
8069
 
 
8070
 
 
8071
 
 
8072
 
 
8073
 
 
8074
<p><tt>Data_Get_Struct(VALUE obj, <i>c-type</i>,
 
8075
<i>c-type</i> *ptr)</tt></p>
 
8076
 
 
8077
 
 
8078
 
 
8079
 
 
8080
 
 
8081
<div class="indent">Retrieves the original C pointer of
 
8082
type <i>c-type</i> from the data object <i>obj</i>
 
8083
and assigns that pointer to <i>ptr</i>. </div>
 
8084
 
 
8085
 
 
8086
 
 
8087
 
 
8088
 
 
8089
<H3><a name="Ruby_nn52"></a>30.7.13 Example: STL Vector to Ruby Array</H3>
 
8090
 
 
8091
 
 
8092
<p>Another use for macros and type maps is to create a Ruby array
 
8093
from a STL vector of pointers. In essence, copy of all the pointers in
 
8094
the vector into a Ruby array. The use of the macro is to make the
 
8095
typemap so generic that any vector with pointers can use the type map.
 
8096
The following is an example of how to construct this type of
 
8097
macro/typemap and should give insight into constructing similar
 
8098
typemaps for other STL structures: </p>
 
8099
 
 
8100
 
 
8101
 
 
8102
 
 
8103
 
 
8104
<div class="code">
 
8105
<pre>%define PTR_VECTOR_TO_RUBY_ARRAY(vectorclassname, classname)<br>%typemap(out) vectorclassname &amp;, const vectorclassname &amp; {<br> VALUE arr = rb_ary_new2($1-&gt;size());<br> vectorclassname::iterator i = $1-&gt;begin(), iend = $1-&gt;end();<br> for ( ; i!=iend; i++ )<br> rb_ary_push(arr, Data_Wrap_Struct(c ## classname.klass, 0, 0, *i));<br> $result = arr;<br>}<br>%typemap(out) vectorclassname, const vectorclassname {<br> VALUE arr = rb_ary_new2($1.size());<br> vectorclassname::iterator i = $1.begin(), iend = $1.end();<br> for ( ; i!=iend; i++ )<br> rb_ary_push(arr, Data_Wrap_Struct(c ## classname.klass, 0, 0, *i));<br> $result = arr;<br>}<br>%enddef<br></pre>
 
8106
 
 
8107
 
 
8108
 
 
8109
 
 
8110
 
 
8111
</div>
 
8112
 
 
8113
 
 
8114
 
 
8115
 
 
8116
 
 
8117
<p> Note, that the "<tt>c ## classname.klass"</tt> is
 
8118
used in the preprocessor step to determine the actual object from the
 
8119
class name. </p>
 
8120
 
 
8121
 
 
8122
 
 
8123
 
 
8124
 
 
8125
<p>To use the macro with a class Foo, the following is used: </p>
 
8126
 
 
8127
 
 
8128
 
 
8129
 
 
8130
 
 
8131
<div class="code">
 
8132
<pre>PTR_VECTOR_TO_RUBY_ARRAY(vector&lt;foo *=""&gt;, Foo)<br></pre>
 
8133
 
 
8134
 
 
8135
 
 
8136
 
 
8137
 
 
8138
</div>
 
8139
 
 
8140
 
 
8141
 
 
8142
 
 
8143
 
 
8144
<p> It is also possible to create a STL vector of Ruby objects: </p>
 
8145
 
 
8146
 
 
8147
 
 
8148
 
 
8149
 
 
8150
<div class="code">
 
8151
<pre>%define RUBY_ARRAY_TO_PTR_VECTOR(vectorclassname, classname)<br>%typemap(in) vectorclassname &amp;, const vectorclassname &amp; {<br> Check_Type($input, T_ARRAY);<br> vectorclassname *vec = new vectorclassname;<br> int len = RARRAY($input)-&gt;len;<br> for (int i=0; i!=len; i++) {<br> VALUE inst = rb_ary_entry($input, i);<br> //The following _should_ work but doesn't on HPUX<br> // Check_Type(inst, T_DATA);<br> classname *element = NULL;<br> Data_Get_Struct(inst, classname, element);<br> vec-&gt;push_back(element);<br> }<br> $1 = vec;<br>}<br><br>%typemap(freearg) vectorclassname &amp;, const vectorclassname &amp; {<br> delete $1;<br>}<br>%enddef<br></pre>
 
8152
 
 
8153
 
 
8154
 
 
8155
 
 
8156
 
 
8157
</div>
 
8158
 
 
8159
 
 
8160
 
 
8161
 
 
8162
 
 
8163
<p> It is also possible to create a Ruby array from a vector of
 
8164
static data types: </p>
 
8165
 
 
8166
 
 
8167
 
 
8168
 
 
8169
 
 
8170
<div class="code">
 
8171
<pre>%define VECTOR_TO_RUBY_ARRAY(vectorclassname, classname)<br>%typemap(out) vectorclassname &amp;, const vectorclassname &amp; {<br> VALUE arr = rb_ary_new2($1-&gt;size()); <br> vectorclassname::iterator i = $1-&gt;begin(), iend = $1-&gt;end();<br> for ( ; i!=iend; i++ )<br> rb_ary_push(arr, Data_Wrap_Struct(c ## classname.klass, 0, 0, &amp;(*i)));<br> $result = arr;<br>}<br>%typemap(out) vectorclassname, const vectorclassname {<br> VALUE arr = rb_ary_new2($1.size()); <br> vectorclassname::iterator i = $1.begin(), iend = $1.end();<br> for ( ; i!=iend; i++ )<br> rb_ary_push(arr, Data_Wrap_Struct(c ## classname.klass, 0, 0, &amp;(*i)));<br> $result = arr;<br>}<br>%enddef<br></pre>
 
8172
 
 
8173
 
 
8174
 
 
8175
 
 
8176
 
 
8177
</div>
 
8178
 
 
8179
 
 
8180
 
 
8181
 
 
8182
 
 
8183
<br>
 
8184
 
 
8185
 
 
8186
 
 
8187
 
 
8188
 
 
8189
Note that this is mostly an example of typemaps. If you want to use the
 
8190
STL with ruby, you are advised to use the standard swig STL library,
 
8191
which does much more than this. &nbsp;Refer to the section called
 
8192
the<a href="#Ruby_nn23_1"> C++ Standard Template Library</a>.<br>
 
8193
 
 
8194
 
 
8195
 
 
8196
 
 
8197
 
 
8198
<H2><a name="Ruby_nn65"></a>30.8 Docstring Features</H2>
 
8199
 
 
8200
 
 
8201
<p>
 
8202
Using ri and rdoc web pages in Ruby libraries is a common practice.
 
8203
Given the way that SWIG generates the extensions by default, your users
 
8204
will normally not get
 
8205
any documentation for it, even if they run 'rdoc' on the resulting .c
 
8206
or .cxx file.</p>
 
8207
 
 
8208
 
 
8209
 
 
8210
 
 
8211
 
 
8212
<p>The features described in this section make it easy for you to
 
8213
add
 
8214
rdoc strings to your modules, functions and methods that can then be
 
8215
read by Ruby's rdoc tool to generate html web pages, ri documentation,
 
8216
Windows chm file and an .xml description.</p>
 
8217
 
 
8218
 
 
8219
 
 
8220
 
 
8221
 
 
8222
<p>rdoc can then be run from a console or shell window on a swig
 
8223
generated file.&nbsp;</p>
 
8224
 
 
8225
 
 
8226
 
 
8227
 
 
8228
 
 
8229
<p>For example, to generate html web pages from a C++ file, you'd
 
8230
do:&nbsp;</p>
 
8231
 
 
8232
 
 
8233
 
 
8234
 
 
8235
 
 
8236
<div class="code shell"><span style="font-family: monospace; font-weight: bold;">
 
8237
$
 
8238
rdoc&nbsp;-E cxx=c -f html file_wrap.cxx</span></div>
 
8239
 
 
8240
 
 
8241
 
 
8242
 
 
8243
 
 
8244
<p>To
 
8245
generate ri documentation from a c wrap file, you could do:</p>
 
8246
 
 
8247
 
 
8248
 
 
8249
 
 
8250
 
 
8251
<div class="code shell"><span style="font-family: monospace; font-weight: bold;">$ rdoc
 
8252
-r&nbsp;file_wrap.c</span>
 
8253
</div>
 
8254
 
 
8255
 
 
8256
 
 
8257
 
 
8258
 
 
8259
<H3><a name="Ruby_nn66"></a>30.8.1 Module docstring</H3>
 
8260
 
 
8261
 
 
8262
<p>
 
8263
Ruby allows a docstring at the beginning of the&nbsp;file
 
8264
before any other statements, and it is typically used to give a
 
8265
general description of the entire module. SWIG supports this by
 
8266
setting an option of the <tt>%module</tt> directive. For
 
8267
example:
 
8268
</p>
 
8269
 
 
8270
 
 
8271
 
 
8272
 
 
8273
 
 
8274
<div class="code">
 
8275
<pre>%module(docstring="This is the example module's docstring") example<br></pre>
 
8276
 
 
8277
 
 
8278
 
 
8279
 
 
8280
 
 
8281
</div>
 
8282
 
 
8283
 
 
8284
 
 
8285
 
 
8286
 
 
8287
<p>
 
8288
When you have more than just a line or so then you can retain the easy
 
8289
readability of the <tt>%module</tt> directive by using a
 
8290
macro. For example:
 
8291
</p>
 
8292
 
 
8293
 
 
8294
 
 
8295
 
 
8296
 
 
8297
<div class="code">
 
8298
<pre>%define DOCSTRING<br>"The `XmlResource` class allows program resources defining menus, <br>layout of controls on a panel, etc. to be loaded from an XML file."<br>%enddef<br><br>%module(docstring=DOCSTRING) xrc<br></pre>
 
8299
 
 
8300
 
 
8301
 
 
8302
 
 
8303
 
 
8304
</div>
 
8305
 
 
8306
 
 
8307
 
 
8308
 
 
8309
 
 
8310
<H3><a name="Ruby_nn67"></a>30.8.2 %feature("autodoc")</H3>
 
8311
 
 
8312
 
 
8313
<p>Since SWIG does know everything about the function it wraps,
 
8314
it is possible to generate an rdoc containing the parameter types,
 
8315
names
 
8316
and default values. Since Ruby ships with one of the best documentation
 
8317
systems of any language, it makes sense to take advantage of it.
 
8318
</p>
 
8319
 
 
8320
 
 
8321
 
 
8322
 
 
8323
 
 
8324
<p>SWIG's Ruby module provides support for the "autodoc"
 
8325
feature,
 
8326
which when attached to a node in the parse tree will cause an rdoc
 
8327
comment
 
8328
to be generated in the wrapper file that includes the name of the
 
8329
function, parameter
 
8330
names, default values if any, and return type if any. There are also
 
8331
several options for autodoc controlled by the value given to the
 
8332
feature, described below.
 
8333
</p>
 
8334
 
 
8335
 
 
8336
 
 
8337
 
 
8338
 
 
8339
<H4><a name="Ruby_nn68"></a>30.8.2.1 %feature("autodoc", "0")</H4>
 
8340
 
 
8341
 
 
8342
<p>
 
8343
When the "0" option is given then the types of the parameters will
 
8344
<em>not</em> be included in the autodoc string. For
 
8345
example, given
 
8346
this function prototype:
 
8347
</p>
 
8348
 
 
8349
 
 
8350
 
 
8351
 
 
8352
 
 
8353
<div class="code">
 
8354
<pre>%feature("autodoc", "0");<br>bool function_name(int x, int y, Foo* foo=NULL, Bar* bar=NULL);<br></pre>
 
8355
 
 
8356
 
 
8357
 
 
8358
 
 
8359
 
 
8360
</div>
 
8361
 
 
8362
 
 
8363
 
 
8364
 
 
8365
 
 
8366
<p>
 
8367
Then Ruby code like this will be generated:
 
8368
</p>
 
8369
 
 
8370
 
 
8371
 
 
8372
 
 
8373
 
 
8374
<div class="targetlang">
 
8375
<pre>function_name(x, y, foo=nil, bar=nil) -&gt; bool<br> ...<br></pre>
 
8376
 
 
8377
 
 
8378
 
 
8379
 
 
8380
 
 
8381
</div>
 
8382
 
 
8383
 
 
8384
 
 
8385
 
 
8386
 
 
8387
<H4><a name="Ruby_autodoc1"></a>30.8.2.2 %feature("autodoc", "1")</H4>
 
8388
 
 
8389
 
 
8390
<p>
 
8391
When the "1" option is used then the parameter types <em>will</em>
 
8392
be used in the rdoc string. In addition, an attempt is made to
 
8393
simplify the type name such that it makes more sense to the Ruby
 
8394
user. Pointer, reference and const info is removed,
 
8395
<tt>%rename</tt>'s are evaluated, etc. (This is not always
 
8396
successful, but works most of the time. See the next section for what
 
8397
to do when it doesn't.) Given the example above, then turning on the
 
8398
parameter types with the "1" option will result in rdoc code like
 
8399
this:
 
8400
</p>
 
8401
 
 
8402
 
 
8403
 
 
8404
 
 
8405
 
 
8406
<div class="targetlang">
 
8407
<pre>function_name(int x, int y, Foo foo=nil, Bar bar=nil) -&gt; bool<br> ...<br></pre>
 
8408
 
 
8409
 
 
8410
 
 
8411
 
 
8412
 
 
8413
</div>
 
8414
 
 
8415
 
 
8416
 
 
8417
 
 
8418
 
 
8419
<H4><a name="Ruby_autodoc2"></a>30.8.2.3 %feature("autodoc", "2")</H4>
 
8420
 
 
8421
 
 
8422
<p>
 
8423
When the "2" option is used then the parameter types will not
 
8424
be
 
8425
used in the rdoc string. However, they will be listed in full after the
 
8426
function. &nbsp;Given the example above, then turning on the
 
8427
parameter types with the "2" option will result in Ruby code like
 
8428
this:
 
8429
</p>
 
8430
 
 
8431
 
 
8432
 
 
8433
 
 
8434
 
 
8435
<H4><a name="Ruby_feature_autodoc3"></a>30.8.2.4 %feature("autodoc", "3")</H4>
 
8436
 
 
8437
 
 
8438
<p>
 
8439
When the "3" option is used then the function will be documented using
 
8440
a combination of "1" and "2" above. &nbsp;Given the example above,
 
8441
then turning on the
 
8442
parameter types with the "2" option will result in Ruby code like
 
8443
this:
 
8444
</p>
 
8445
 
 
8446
 
 
8447
 
 
8448
 
 
8449
 
 
8450
<div class="targetlang">
 
8451
<pre>function_name(int x, int y, Foo foo=nil, Bar bar=nil) -&gt; bool<br><br>Parameters:<br>    x - int<br>     y - int<br>     foo - Foo<br>   bar - Bar<br></pre>
 
8452
 
 
8453
 
 
8454
 
 
8455
 
 
8456
 
 
8457
</div>
 
8458
 
 
8459
 
 
8460
 
 
8461
 
 
8462
 
 
8463
<H4><a name="Ruby_nn70"></a>30.8.2.5 %feature("autodoc", "docstring")</H4>
 
8464
 
 
8465
 
 
8466
<p>
 
8467
Finally, there are times when the automatically generated autodoc
 
8468
string will make no sense for a Ruby programmer, particularly when a
 
8469
typemap is involved. So if you give an explicit value for the autodoc
 
8470
feature then that string will be used in place of the automatically
 
8471
generated string. For example:
 
8472
</p>
 
8473
 
 
8474
 
 
8475
 
 
8476
 
 
8477
 
 
8478
<div class="code">
 
8479
<pre>%feature("autodoc", "GetPosition() -&gt; (x, y)") GetPosition;<br>void GetPosition(int* OUTPUT, int* OUTPUT);<br></pre>
 
8480
 
 
8481
 
 
8482
 
 
8483
 
 
8484
 
 
8485
</div>
 
8486
 
 
8487
 
 
8488
 
 
8489
 
 
8490
 
 
8491
<H3><a name="Ruby_nn71"></a>30.8.3 %feature("docstring")</H3>
 
8492
 
 
8493
 
 
8494
<p>
 
8495
In addition to the autodoc strings described above, you can also
 
8496
attach any arbitrary descriptive text to a node in the parse tree with
 
8497
the "docstring" feature. When the proxy module is generated then any
 
8498
docstring associated with classes, function or methods are output.
 
8499
If an item already has an autodoc string then it is combined with the
 
8500
docstring and they are output together. </p>
 
8501
 
 
8502
 
 
8503
 
 
8504
 
 
8505
 
 
8506
<H2><a name="Ruby_nn53"></a>30.9 Advanced Topics</H2>
 
8507
 
 
8508
 
 
8509
<H3><a name="Ruby_nn54"></a>30.9.1 Operator overloading</H3>
 
8510
 
 
8511
 
 
8512
<p> SWIG allows operator overloading with, by using the <tt>%extend</tt>
 
8513
or <tt>%rename</tt> commands in SWIG and the following
 
8514
operator names (derived from Python): </p>
 
8515
 
 
8516
 
 
8517
 
 
8518
 
 
8519
 
 
8520
<div class="code diagram">
 
8521
<table style="width: 100%; font-family: monospace;" border="1" cellpadding="2" cellspacing="2" summary="operator names">
 
8522
 
 
8523
 
 
8524
 
 
8525
 
 
8526
 
 
8527
  <tbody>
 
8528
 
 
8529
 
 
8530
 
 
8531
 
 
8532
 
 
8533
    <tr>
 
8534
 
 
8535
 
 
8536
 
 
8537
 
 
8538
 
 
8539
      <td><b> General</b></td>
 
8540
 
 
8541
 
 
8542
 
 
8543
 
 
8544
 
 
8545
    </tr>
 
8546
 
 
8547
 
 
8548
 
 
8549
 
 
8550
 
 
8551
    <tr>
 
8552
 
 
8553
 
 
8554
 
 
8555
 
 
8556
 
 
8557
      <td>__repr__ </td>
 
8558
 
 
8559
 
 
8560
 
 
8561
 
 
8562
 
 
8563
      <td> inspect</td>
 
8564
 
 
8565
 
 
8566
 
 
8567
 
 
8568
 
 
8569
    </tr>
 
8570
 
 
8571
 
 
8572
 
 
8573
 
 
8574
 
 
8575
    <tr>
 
8576
 
 
8577
 
 
8578
 
 
8579
 
 
8580
 
 
8581
      <td>__str__ </td>
 
8582
 
 
8583
 
 
8584
 
 
8585
 
 
8586
 
 
8587
      <td> to_s</td>
 
8588
 
 
8589
 
 
8590
 
 
8591
 
 
8592
 
 
8593
    </tr>
 
8594
 
 
8595
 
 
8596
 
 
8597
 
 
8598
 
 
8599
    <tr>
 
8600
 
 
8601
 
 
8602
 
 
8603
 
 
8604
 
 
8605
      <td>__cmp__ </td>
 
8606
 
 
8607
 
 
8608
 
 
8609
 
 
8610
 
 
8611
      <td> &lt;=&gt;</td>
 
8612
 
 
8613
 
 
8614
 
 
8615
 
 
8616
 
 
8617
    </tr>
 
8618
 
 
8619
 
 
8620
 
 
8621
 
 
8622
 
 
8623
    <tr>
 
8624
 
 
8625
 
 
8626
 
 
8627
 
 
8628
 
 
8629
      <td>__hash__ </td>
 
8630
 
 
8631
 
 
8632
 
 
8633
 
 
8634
 
 
8635
      <td> hash</td>
 
8636
 
 
8637
 
 
8638
 
 
8639
 
 
8640
 
 
8641
    </tr>
 
8642
 
 
8643
 
 
8644
 
 
8645
 
 
8646
 
 
8647
    <tr>
 
8648
 
 
8649
 
 
8650
 
 
8651
 
 
8652
 
 
8653
      <td>__nonzero__ </td>
 
8654
 
 
8655
 
 
8656
 
 
8657
 
 
8658
 
 
8659
      <td> nonzero?</td>
 
8660
 
 
8661
 
 
8662
 
 
8663
 
 
8664
 
 
8665
    </tr>
 
8666
 
 
8667
 
 
8668
 
 
8669
 
 
8670
 
 
8671
    <tr>
 
8672
 
 
8673
 
 
8674
 
 
8675
 
 
8676
 
 
8677
      <td></td>
 
8678
 
 
8679
 
 
8680
 
 
8681
 
 
8682
 
 
8683
    </tr>
 
8684
 
 
8685
 
 
8686
 
 
8687
 
 
8688
 
 
8689
    <tr>
 
8690
 
 
8691
 
 
8692
 
 
8693
 
 
8694
 
 
8695
      <td><b> Callable</b></td>
 
8696
 
 
8697
 
 
8698
 
 
8699
 
 
8700
 
 
8701
    </tr>
 
8702
 
 
8703
 
 
8704
 
 
8705
 
 
8706
 
 
8707
    <tr>
 
8708
 
 
8709
 
 
8710
 
 
8711
 
 
8712
 
 
8713
      <td>__call__ </td>
 
8714
 
 
8715
 
 
8716
 
 
8717
 
 
8718
 
 
8719
      <td> call</td>
 
8720
 
 
8721
 
 
8722
 
 
8723
 
 
8724
 
 
8725
    </tr>
 
8726
 
 
8727
 
 
8728
 
 
8729
 
 
8730
 
 
8731
    <tr>
 
8732
 
 
8733
 
 
8734
 
 
8735
 
 
8736
 
 
8737
      <td></td>
 
8738
 
 
8739
 
 
8740
 
 
8741
 
 
8742
 
 
8743
    </tr>
 
8744
 
 
8745
 
 
8746
 
 
8747
 
 
8748
 
 
8749
    <tr>
 
8750
 
 
8751
 
 
8752
 
 
8753
 
 
8754
 
 
8755
      <td><b> Collection</b></td>
 
8756
 
 
8757
 
 
8758
 
 
8759
 
 
8760
 
 
8761
    </tr>
 
8762
 
 
8763
 
 
8764
 
 
8765
 
 
8766
 
 
8767
    <tr>
 
8768
 
 
8769
 
 
8770
 
 
8771
 
 
8772
 
 
8773
      <td>__len__ </td>
 
8774
 
 
8775
 
 
8776
 
 
8777
 
 
8778
 
 
8779
      <td> length</td>
 
8780
 
 
8781
 
 
8782
 
 
8783
 
 
8784
 
 
8785
    </tr>
 
8786
 
 
8787
 
 
8788
 
 
8789
 
 
8790
 
 
8791
    <tr>
 
8792
 
 
8793
 
 
8794
 
 
8795
 
 
8796
 
 
8797
      <td>__getitem__ </td>
 
8798
 
 
8799
 
 
8800
 
 
8801
 
 
8802
 
 
8803
      <td> []</td>
 
8804
 
 
8805
 
 
8806
 
 
8807
 
 
8808
 
 
8809
    </tr>
 
8810
 
 
8811
 
 
8812
 
 
8813
 
 
8814
 
 
8815
    <tr>
 
8816
 
 
8817
 
 
8818
 
 
8819
 
 
8820
 
 
8821
      <td>__setitem__ </td>
 
8822
 
 
8823
 
 
8824
 
 
8825
 
 
8826
 
 
8827
      <td> []=</td>
 
8828
 
 
8829
 
 
8830
 
 
8831
 
 
8832
 
 
8833
    </tr>
 
8834
 
 
8835
 
 
8836
 
 
8837
 
 
8838
 
 
8839
    <tr>
 
8840
 
 
8841
 
 
8842
 
 
8843
 
 
8844
 
 
8845
      <td></td>
 
8846
 
 
8847
 
 
8848
 
 
8849
 
 
8850
 
 
8851
    </tr>
 
8852
 
 
8853
 
 
8854
 
 
8855
 
 
8856
 
 
8857
    <tr>
 
8858
 
 
8859
 
 
8860
 
 
8861
 
 
8862
 
 
8863
      <td><b> Numeric</b></td>
 
8864
 
 
8865
 
 
8866
 
 
8867
 
 
8868
 
 
8869
    </tr>
 
8870
 
 
8871
 
 
8872
 
 
8873
 
 
8874
 
 
8875
    <tr>
 
8876
 
 
8877
 
 
8878
 
 
8879
 
 
8880
 
 
8881
      <td>__add__ </td>
 
8882
 
 
8883
 
 
8884
 
 
8885
 
 
8886
 
 
8887
      <td> +</td>
 
8888
 
 
8889
 
 
8890
 
 
8891
 
 
8892
 
 
8893
    </tr>
 
8894
 
 
8895
 
 
8896
 
 
8897
 
 
8898
 
 
8899
    <tr>
 
8900
 
 
8901
 
 
8902
 
 
8903
 
 
8904
 
 
8905
      <td>__sub__ </td>
 
8906
 
 
8907
 
 
8908
 
 
8909
 
 
8910
 
 
8911
      <td> -</td>
 
8912
 
 
8913
 
 
8914
 
 
8915
 
 
8916
 
 
8917
      <td></td>
 
8918
 
 
8919
 
 
8920
 
 
8921
 
 
8922
 
 
8923
    </tr>
 
8924
 
 
8925
 
 
8926
 
 
8927
 
 
8928
 
 
8929
    <tr>
 
8930
 
 
8931
 
 
8932
 
 
8933
 
 
8934
 
 
8935
      <td>__mul__ </td>
 
8936
 
 
8937
 
 
8938
 
 
8939
 
 
8940
 
 
8941
      <td> *</td>
 
8942
 
 
8943
 
 
8944
 
 
8945
 
 
8946
 
 
8947
    </tr>
 
8948
 
 
8949
 
 
8950
 
 
8951
 
 
8952
 
 
8953
    <tr>
 
8954
 
 
8955
 
 
8956
 
 
8957
 
 
8958
 
 
8959
      <td>__div__ </td>
 
8960
 
 
8961
 
 
8962
 
 
8963
 
 
8964
 
 
8965
      <td> /</td>
 
8966
 
 
8967
 
 
8968
 
 
8969
 
 
8970
 
 
8971
    </tr>
 
8972
 
 
8973
 
 
8974
 
 
8975
 
 
8976
 
 
8977
    <tr>
 
8978
 
 
8979
 
 
8980
 
 
8981
 
 
8982
 
 
8983
      <td>__mod__ </td>
 
8984
 
 
8985
 
 
8986
 
 
8987
 
 
8988
 
 
8989
      <td> %</td>
 
8990
 
 
8991
 
 
8992
 
 
8993
 
 
8994
 
 
8995
    </tr>
 
8996
 
 
8997
 
 
8998
 
 
8999
 
 
9000
 
 
9001
    <tr>
 
9002
 
 
9003
 
 
9004
 
 
9005
 
 
9006
 
 
9007
      <td>__divmod__ </td>
 
9008
 
 
9009
 
 
9010
 
 
9011
 
 
9012
 
 
9013
      <td> divmod</td>
 
9014
 
 
9015
 
 
9016
 
 
9017
 
 
9018
 
 
9019
    </tr>
 
9020
 
 
9021
 
 
9022
 
 
9023
 
 
9024
 
 
9025
    <tr>
 
9026
 
 
9027
 
 
9028
 
 
9029
 
 
9030
 
 
9031
      <td>__pow__ </td>
 
9032
 
 
9033
 
 
9034
 
 
9035
 
 
9036
 
 
9037
      <td> **</td>
 
9038
 
 
9039
 
 
9040
 
 
9041
 
 
9042
 
 
9043
    </tr>
 
9044
 
 
9045
 
 
9046
 
 
9047
 
 
9048
 
 
9049
    <tr>
 
9050
 
 
9051
 
 
9052
 
 
9053
 
 
9054
 
 
9055
      <td>__lshift__ </td>
 
9056
 
 
9057
 
 
9058
 
 
9059
 
 
9060
 
 
9061
      <td> &lt;&lt;</td>
 
9062
 
 
9063
 
 
9064
 
 
9065
 
 
9066
 
 
9067
    </tr>
 
9068
 
 
9069
 
 
9070
 
 
9071
 
 
9072
 
 
9073
    <tr>
 
9074
 
 
9075
 
 
9076
 
 
9077
 
 
9078
 
 
9079
      <td>__rshift__ </td>
 
9080
 
 
9081
 
 
9082
 
 
9083
 
 
9084
 
 
9085
      <td> &gt;&gt;</td>
 
9086
 
 
9087
 
 
9088
 
 
9089
 
 
9090
 
 
9091
    </tr>
 
9092
 
 
9093
 
 
9094
 
 
9095
 
 
9096
 
 
9097
    <tr>
 
9098
 
 
9099
 
 
9100
 
 
9101
 
 
9102
 
 
9103
      <td>__and__ </td>
 
9104
 
 
9105
 
 
9106
 
 
9107
 
 
9108
 
 
9109
      <td> &amp;</td>
 
9110
 
 
9111
 
 
9112
 
 
9113
 
 
9114
 
 
9115
    </tr>
 
9116
 
 
9117
 
 
9118
 
 
9119
 
 
9120
 
 
9121
    <tr>
 
9122
 
 
9123
 
 
9124
 
 
9125
 
 
9126
 
 
9127
      <td>__xor__ </td>
 
9128
 
 
9129
 
 
9130
 
 
9131
 
 
9132
 
 
9133
      <td> ^</td>
 
9134
 
 
9135
 
 
9136
 
 
9137
 
 
9138
 
 
9139
    </tr>
 
9140
 
 
9141
 
 
9142
 
 
9143
 
 
9144
 
 
9145
    <tr>
 
9146
 
 
9147
 
 
9148
 
 
9149
 
 
9150
 
 
9151
      <td>__or__ </td>
 
9152
 
 
9153
 
 
9154
 
 
9155
 
 
9156
 
 
9157
      <td> |</td>
 
9158
 
 
9159
 
 
9160
 
 
9161
 
 
9162
 
 
9163
    </tr>
 
9164
 
 
9165
 
 
9166
 
 
9167
 
 
9168
 
 
9169
    <tr>
 
9170
 
 
9171
 
 
9172
 
 
9173
 
 
9174
 
 
9175
      <td>__neg__ </td>
 
9176
 
 
9177
 
 
9178
 
 
9179
 
 
9180
 
 
9181
      <td> -@</td>
 
9182
 
 
9183
 
 
9184
 
 
9185
 
 
9186
 
 
9187
      <td></td>
 
9188
 
 
9189
 
 
9190
 
 
9191
 
 
9192
 
 
9193
    </tr>
 
9194
 
 
9195
 
 
9196
 
 
9197
 
 
9198
 
 
9199
    <tr>
 
9200
 
 
9201
 
 
9202
 
 
9203
 
 
9204
 
 
9205
      <td>__pos__ </td>
 
9206
 
 
9207
 
 
9208
 
 
9209
 
 
9210
 
 
9211
      <td> +@</td>
 
9212
 
 
9213
 
 
9214
 
 
9215
 
 
9216
 
 
9217
    </tr>
 
9218
 
 
9219
 
 
9220
 
 
9221
 
 
9222
 
 
9223
    <tr>
 
9224
 
 
9225
 
 
9226
 
 
9227
 
 
9228
 
 
9229
      <td>__abs__ </td>
 
9230
 
 
9231
 
 
9232
 
 
9233
 
 
9234
 
 
9235
      <td> abs</td>
 
9236
 
 
9237
 
 
9238
 
 
9239
 
 
9240
 
 
9241
    </tr>
 
9242
 
 
9243
 
 
9244
 
 
9245
 
 
9246
 
 
9247
    <tr>
 
9248
 
 
9249
 
 
9250
 
 
9251
 
 
9252
 
 
9253
      <td>__invert__ </td>
 
9254
 
 
9255
 
 
9256
 
 
9257
 
 
9258
 
 
9259
      <td> ~</td>
 
9260
 
 
9261
 
 
9262
 
 
9263
 
 
9264
 
 
9265
    </tr>
 
9266
 
 
9267
 
 
9268
 
 
9269
 
 
9270
 
 
9271
    <tr>
 
9272
 
 
9273
 
 
9274
 
 
9275
 
 
9276
 
 
9277
      <td>__int__ </td>
 
9278
 
 
9279
 
 
9280
 
 
9281
 
 
9282
 
 
9283
      <td> to_i</td>
 
9284
 
 
9285
 
 
9286
 
 
9287
 
 
9288
 
 
9289
    </tr>
 
9290
 
 
9291
 
 
9292
 
 
9293
 
 
9294
 
 
9295
    <tr>
 
9296
 
 
9297
 
 
9298
 
 
9299
 
 
9300
 
 
9301
      <td>__float__ </td>
 
9302
 
 
9303
 
 
9304
 
 
9305
 
 
9306
 
 
9307
      <td> to_f</td>
 
9308
 
 
9309
 
 
9310
 
 
9311
 
 
9312
 
 
9313
    </tr>
 
9314
 
 
9315
 
 
9316
 
 
9317
 
 
9318
 
 
9319
    <tr>
 
9320
 
 
9321
 
 
9322
 
 
9323
 
 
9324
 
 
9325
      <td>__coerce__ </td>
 
9326
 
 
9327
 
 
9328
 
 
9329
 
 
9330
 
 
9331
      <td> coerce</td>
 
9332
 
 
9333
 
 
9334
 
 
9335
 
 
9336
 
 
9337
    </tr>
 
9338
 
 
9339
 
 
9340
 
 
9341
 
 
9342
 
 
9343
    <tr>
 
9344
 
 
9345
 
 
9346
 
 
9347
 
 
9348
 
 
9349
      <td></td>
 
9350
 
 
9351
 
 
9352
 
 
9353
 
 
9354
 
 
9355
    </tr>
 
9356
 
 
9357
 
 
9358
 
 
9359
 
 
9360
 
 
9361
    <tr>
 
9362
 
 
9363
 
 
9364
 
 
9365
 
 
9366
 
 
9367
      <td><b>Additions in 1.3.13 </b></td>
 
9368
 
 
9369
 
 
9370
 
 
9371
 
 
9372
 
 
9373
    </tr>
 
9374
 
 
9375
 
 
9376
 
 
9377
 
 
9378
 
 
9379
    <tr>
 
9380
 
 
9381
 
 
9382
 
 
9383
 
 
9384
 
 
9385
      <td>__lt__ </td>
 
9386
 
 
9387
 
 
9388
 
 
9389
 
 
9390
 
 
9391
      <td> &lt;</td>
 
9392
 
 
9393
 
 
9394
 
 
9395
 
 
9396
 
 
9397
    </tr>
 
9398
 
 
9399
 
 
9400
 
 
9401
 
 
9402
 
 
9403
    <tr>
 
9404
 
 
9405
 
 
9406
 
 
9407
 
 
9408
 
 
9409
      <td>__le__ </td>
 
9410
 
 
9411
 
 
9412
 
 
9413
 
 
9414
 
 
9415
      <td> &lt;=</td>
 
9416
 
 
9417
 
 
9418
 
 
9419
 
 
9420
 
 
9421
    </tr>
 
9422
 
 
9423
 
 
9424
 
 
9425
 
 
9426
 
 
9427
    <tr>
 
9428
 
 
9429
 
 
9430
 
 
9431
 
 
9432
 
 
9433
      <td>__eq__ </td>
 
9434
 
 
9435
 
 
9436
 
 
9437
 
 
9438
 
 
9439
      <td> ==</td>
 
9440
 
 
9441
 
 
9442
 
 
9443
 
 
9444
 
 
9445
    </tr>
 
9446
 
 
9447
 
 
9448
 
 
9449
 
 
9450
 
 
9451
    <tr>
 
9452
 
 
9453
 
 
9454
 
 
9455
 
 
9456
 
 
9457
      <td>__gt__ </td>
 
9458
 
 
9459
 
 
9460
 
 
9461
 
 
9462
 
 
9463
      <td> &gt;</td>
 
9464
 
 
9465
 
 
9466
 
 
9467
 
 
9468
 
 
9469
    </tr>
 
9470
 
 
9471
 
 
9472
 
 
9473
 
 
9474
 
 
9475
    <tr>
 
9476
 
 
9477
 
 
9478
 
 
9479
 
 
9480
 
 
9481
      <td>__ge__ </td>
 
9482
 
 
9483
 
 
9484
 
 
9485
 
 
9486
 
 
9487
      <td> &gt;=</td>
 
9488
 
 
9489
 
 
9490
 
 
9491
 
 
9492
 
 
9493
    </tr>
 
9494
 
 
9495
 
 
9496
 
 
9497
 
 
9498
 
 
9499
  
 
9500
  
 
9501
  
 
9502
  
 
9503
  </tbody>
 
9504
</table>
 
9505
 
 
9506
 
 
9507
 
 
9508
 
 
9509
 
 
9510
</div>
 
9511
 
 
9512
 
 
9513
 
 
9514
 
 
9515
 
 
9516
<p> Note that although SWIG supports the <tt>__eq__</tt>
 
9517
magic method name for defining an equivalence operator, there is no
 
9518
separate method for handling <i>inequality</i> since Ruby
 
9519
parses the expression <i>a != b</i> as <i>!(a == b)</i>.
 
9520
</p>
 
9521
 
 
9522
 
 
9523
 
 
9524
 
 
9525
 
 
9526
<H3><a name="Ruby_nn55"></a>30.9.2 Creating Multi-Module Packages</H3>
 
9527
 
 
9528
 
 
9529
<p> The chapter on <a href="Modules.html">Working
 
9530
with Modules</a> discusses the basics of creating multi-module
 
9531
extensions with SWIG, and in particular the considerations for sharing
 
9532
runtime type information among the different modules. </p>
 
9533
 
 
9534
 
 
9535
 
 
9536
 
 
9537
 
 
9538
<p>As an example, consider one module's interface file (<tt>shape.i</tt>)
 
9539
that defines our base class: </p>
 
9540
 
 
9541
 
 
9542
 
 
9543
 
 
9544
 
 
9545
<div class="code">
 
9546
<pre>%module shape<br><br>%{<br>#include "Shape.h"<br>%}<br><br>class Shape {<br>protected:<br> double xpos;<br> double ypos;<br>protected:<br> Shape(double x, double y);<br>public:<br> double getX() const;<br> double getY() const;<br>};<br></pre>
 
9547
 
 
9548
 
 
9549
 
 
9550
 
 
9551
 
 
9552
</div>
 
9553
 
 
9554
 
 
9555
 
 
9556
 
 
9557
 
 
9558
<p> We also have a separate interface file (<tt>circle.i</tt>)
 
9559
that defines a derived class: </p>
 
9560
 
 
9561
 
 
9562
 
 
9563
 
 
9564
 
 
9565
<div class="code">
 
9566
<pre>%module circle<br><br>%{<br>#include "Shape.h"<br>#include "Circle.h"<br>%}<br><br>// Import the base class definition from Shape module<br>%import shape.i<br><br>class Circle : public Shape {<br>protected:<br> double radius;<br>public:<br> Circle(double x, double y, double r);<br> double getRadius() const;<br>};<br></pre>
 
9567
 
 
9568
 
 
9569
 
 
9570
 
 
9571
 
 
9572
</div>
 
9573
 
 
9574
 
 
9575
 
 
9576
 
 
9577
 
 
9578
<p> We'll start by building the <b>Shape</b>
 
9579
extension module: </p>
 
9580
 
 
9581
 
 
9582
 
 
9583
 
 
9584
 
 
9585
<div class="code shell">
 
9586
<pre>$ <b>swig -c++ -ruby shape.i</b>
 
9587
</pre>
 
9588
 
 
9589
 
 
9590
 
 
9591
 
 
9592
 
 
9593
</div>
 
9594
 
 
9595
 
 
9596
 
 
9597
 
 
9598
 
 
9599
<p> SWIG generates a wrapper file named <tt>shape_wrap.cxx</tt>.
 
9600
To compile this into a dynamically loadable extension for Ruby, prepare
 
9601
an <tt>extconf.rb</tt> script using this template: </p>
 
9602
 
 
9603
 
 
9604
 
 
9605
 
 
9606
 
 
9607
<div class="code targetlang">
 
9608
<pre>require 'mkmf'<br><br># Since the SWIG runtime support library for Ruby<br># depends on the Ruby library, make sure it's in the list<br># of libraries.<br>$libs = append_library($libs, Config::CONFIG['RUBY_INSTALL_NAME'])<br><br># Create the makefile<br>create_makefile('shape')<br></pre>
 
9609
 
 
9610
 
 
9611
 
 
9612
 
 
9613
 
 
9614
</div>
 
9615
 
 
9616
 
 
9617
 
 
9618
 
 
9619
 
 
9620
<p> Run this script to create a <tt>Makefile</tt>
 
9621
and then type <tt>make</tt> to build the shared library: </p>
 
9622
 
 
9623
 
 
9624
 
 
9625
 
 
9626
 
 
9627
<div class="code targetlang">
 
9628
<pre>$ <b>ruby extconf.rb</b><br>creating Makefile<br>$ <b>make</b><br>g++ -fPIC -g -O2 -I. -I/usr/local/lib/ruby/1.7/i686-linux \<br>-I. -c shape_wrap.cxx<br>gcc -shared -L/usr/local/lib -o shape.so shape_wrap.o -L. \<br>-lruby -lruby -lc<br></pre>
 
9629
 
 
9630
 
 
9631
 
 
9632
 
 
9633
 
 
9634
</div>
 
9635
 
 
9636
 
 
9637
 
 
9638
 
 
9639
 
 
9640
<p> Note that depending on your installation, the outputs may be
 
9641
slightly different; these outputs are those for a Linux-based
 
9642
development environment. The end result should be a shared library
 
9643
(here, <tt>shape.so</tt>) containing the extension module
 
9644
code. Now repeat this process in a separate directory for the <b>Circle</b>
 
9645
module: </p>
 
9646
 
 
9647
 
 
9648
 
 
9649
 
 
9650
 
 
9651
<ol>
 
9652
 
 
9653
 
 
9654
 
 
9655
 
 
9656
 
 
9657
  <li> Run SWIG to generate the wrapper code (<tt>circle_wrap.cxx</tt>);
 
9658
  </li>
 
9659
 
 
9660
 
 
9661
 
 
9662
 
 
9663
 
 
9664
  <li> Write an <tt>extconf.rb</tt> script that your
 
9665
end-users can use to create a platform-specific <tt>Makefile</tt>
 
9666
for the extension; </li>
 
9667
 
 
9668
 
 
9669
 
 
9670
 
 
9671
 
 
9672
  <li> Build the shared library for this extension by typing <tt>make</tt>.
 
9673
  </li>
 
9674
 
 
9675
 
 
9676
 
 
9677
 
 
9678
 
 
9679
</ol>
 
9680
 
 
9681
 
 
9682
 
 
9683
 
 
9684
 
 
9685
<p> Once you've built both of these extension modules, you can
 
9686
test them interactively in IRB to confirm that the <tt>Shape</tt>
 
9687
and <tt>Circle</tt> modules are properly loaded and
 
9688
initialized: </p>
 
9689
 
 
9690
 
 
9691
 
 
9692
 
 
9693
 
 
9694
<div class="code targetlang">
 
9695
<pre>$ <b>irb</b><br>irb(main):001:0&gt; <b>require 'shape'</b><br>true<br>irb(main):002:0&gt; <b>require 'circle'</b><br>true<br>irb(main):003:0&gt; <b>c = Circle::Circle.new(5, 5, 20)</b><br>#&lt;Circle::Circle:0xa097208&gt;<br>irb(main):004:0&gt; <b>c.kind_of? Shape::Shape</b><br>true<br>irb(main):005:0&gt; <b>c.getX()</b><br>5.0<br></pre>
 
9696
 
 
9697
 
 
9698
 
 
9699
 
 
9700
 
 
9701
</div>
 
9702
 
 
9703
 
 
9704
 
 
9705
 
 
9706
 
 
9707
<H3><a name="Ruby_nn56"></a>30.9.3 Specifying Mixin Modules</H3>
 
9708
 
 
9709
 
 
9710
<p> The Ruby language doesn't support multiple inheritance, but
 
9711
it does allow you to mix one or more modules into a class using Ruby's <tt>include</tt>
 
9712
method. For example, if you have a Ruby class that defines an <em>each</em>
 
9713
instance method, e.g. </p>
 
9714
 
 
9715
 
 
9716
 
 
9717
 
 
9718
 
 
9719
<div class="code targetlang">
 
9720
<pre>class Set<br> def initialize<br> @members = []<br> end<br> <br> def each<br> @members.each { |m| yield m }<br> end<br>end<br></pre>
 
9721
 
 
9722
 
 
9723
 
 
9724
 
 
9725
 
 
9726
</div>
 
9727
 
 
9728
 
 
9729
 
 
9730
 
 
9731
 
 
9732
<p> then you can mix-in Ruby's <tt>Enumerable</tt>
 
9733
module to easily add a lot of functionality to your class: </p>
 
9734
 
 
9735
 
 
9736
 
 
9737
 
 
9738
 
 
9739
<div class="code targetlang">
 
9740
<pre>class Set<br> <b>include Enumerable</b><br>def initialize<br>@members = []<br>end<br>def each<br>@members.each { |m| yield m }<br>end<br>end<br></pre>
 
9741
 
 
9742
 
 
9743
 
 
9744
 
 
9745
 
 
9746
</div>
 
9747
 
 
9748
 
 
9749
 
 
9750
 
 
9751
 
 
9752
<p> To get the same benefit for your SWIG-wrapped classes, you
 
9753
can use the <tt>%mixin</tt> directive to specify the names
 
9754
of one or more modules that should be mixed-in to a class. For the
 
9755
above example, the SWIG interface specification might look like this: </p>
 
9756
 
 
9757
 
 
9758
 
 
9759
 
 
9760
 
 
9761
<div class="code">
 
9762
<pre>%mixin Set "Enumerable";<br><br>class Set {<br>public:<br> // Constructor<br> Set();<br> <br> // Iterates through set members<br> void each();<br>};<br></pre>
 
9763
 
 
9764
 
 
9765
 
 
9766
 
 
9767
 
 
9768
</div>
 
9769
 
 
9770
 
 
9771
 
 
9772
 
 
9773
 
 
9774
<p> Multiple modules can be mixed into a class by providing a
 
9775
comma-separated list of module names to the <tt>%mixin</tt>
 
9776
directive, e.g. </p>
 
9777
 
 
9778
 
 
9779
 
 
9780
 
 
9781
 
 
9782
<div class="code">
 
9783
<pre>%mixin Set "Fee,Fi,Fo,Fum";</pre>
 
9784
 
 
9785
 
 
9786
 
 
9787
 
 
9788
 
 
9789
</div>
 
9790
 
 
9791
 
 
9792
 
 
9793
 
 
9794
 
 
9795
<p> Note that the <tt>%mixin</tt> directive is
 
9796
implemented using SWIG's "features" mechanism and so the same name
 
9797
matching rules used for other kinds of features apply (see the chapter
 
9798
on <a href="Customization.html#Customization">"Customization
 
9799
Features"</a>) for more details). </p>
 
9800
 
 
9801
 
 
9802
 
 
9803
 
 
9804
 
 
9805
<H2><a name="Ruby_nn57"></a>30.10 Memory Management</H2>
 
9806
 
 
9807
 
 
9808
<p>One of the most common issues in generating SWIG bindings for
 
9809
Ruby is proper memory management. The key to proper memory management
 
9810
is clearly defining whether a wrapper Ruby object owns the underlying C
 
9811
struct or C++ class. There are two possibilities:</p>
 
9812
 
 
9813
 
 
9814
 
 
9815
 
 
9816
 
 
9817
<ul>
 
9818
 
 
9819
 
 
9820
 
 
9821
 
 
9822
 
 
9823
  <li> The Ruby object is responsible for freeing the C struct or
 
9824
C++ object </li>
 
9825
 
 
9826
 
 
9827
 
 
9828
 
 
9829
 
 
9830
  <li> The Ruby object should not free the C struct or C++ object
 
9831
because it will be freed by the underlying C or C++ code</li>
 
9832
 
 
9833
 
 
9834
 
 
9835
 
 
9836
 
 
9837
</ul>
 
9838
 
 
9839
 
 
9840
 
 
9841
 
 
9842
 
 
9843
<p>To complicate matters, object ownership may transfer from Ruby
 
9844
to C++ (or vice versa) depending on what function or methods are
 
9845
invoked. Clearly, developing a SWIG wrapper requires a thorough
 
9846
understanding of how the underlying library manages memory.</p>
 
9847
 
 
9848
 
 
9849
 
 
9850
 
 
9851
 
 
9852
<H3><a name="Ruby_nn58"></a>30.10.1 Mark and Sweep Garbage Collector </H3>
 
9853
 
 
9854
 
 
9855
<p>Ruby uses a mark and sweep garbage collector. When the garbage
 
9856
collector runs, it finds all the "root" objects, including local
 
9857
variables, global variables, global constants, hardware registers and
 
9858
the C stack. For each root object, the garbage collector sets its mark
 
9859
flag to true and calls <tt>rb_gc_mark</tt> on the object.
 
9860
The job of <tt>rb_gc_mark</tt> is to recursively mark all
 
9861
the objects that a Ruby object has a reference to (ignoring those
 
9862
objects that have already been marked). Those objects, in turn, may
 
9863
reference other objects. This process will continue until all active
 
9864
objects have been "marked." After the mark phase comes the sweep phase.
 
9865
In the sweep phase, all objects that have not been marked will be
 
9866
garbage collected. For more information about the Ruby garbage
 
9867
collector please refer to <a href="http://rubygarden.org/ruby/ruby?GCAndExtensions"> <span style="text-decoration: underline;">http://rubygarden.org/ruby/ruby?GCAndExtensions</span></a>.</p>
 
9868
 
 
9869
 
 
9870
 
 
9871
 
 
9872
 
 
9873
<p>The Ruby C/API provides extension developers two hooks into
 
9874
the garbage collector - a "mark" function and a "sweep" function. By
 
9875
default these functions are set to NULL.</p>
 
9876
 
 
9877
 
 
9878
 
 
9879
 
 
9880
 
 
9881
<p>If a C struct or C++ class references any other Ruby objects,
 
9882
then it must provide a "mark" function. The "mark" function should
 
9883
identify any referenced Ruby objects by calling the rb_gc_mark function
 
9884
for each one. Unsurprisingly, this function will be called by the Ruby
 
9885
garbage during the "mark" phase.</p>
 
9886
 
 
9887
 
 
9888
 
 
9889
 
 
9890
 
 
9891
<p>During the sweep phase, Ruby destroys any unused objects. If
 
9892
any memory has been allocated in creating the underlying C struct or
 
9893
C++ struct, then a "free" function must be defined that deallocates
 
9894
this memory. </p>
 
9895
 
 
9896
 
 
9897
 
 
9898
 
 
9899
 
 
9900
<H3><a name="Ruby_nn59"></a>30.10.2 Object Ownership</H3>
 
9901
 
 
9902
 
 
9903
<p>As described above, memory management depends on clearly
 
9904
defining who is responsible for freeing the underlying C struct or C++
 
9905
class. If the Ruby object is responsible for freeing the C++ object,
 
9906
then a "free" function must be registered for the object. If the Ruby
 
9907
object is not responsible for freeing the underlying memory, then a
 
9908
"free" function must not be registered for the object.</p>
 
9909
 
 
9910
 
 
9911
 
 
9912
 
 
9913
 
 
9914
<p>For the most part, SWIG takes care of memory management
 
9915
issues. The rules it uses are:</p>
 
9916
 
 
9917
 
 
9918
 
 
9919
 
 
9920
 
 
9921
<ul>
 
9922
 
 
9923
 
 
9924
 
 
9925
 
 
9926
 
 
9927
  <li> When calling a C++ object's constructor from Ruby, SWIG
 
9928
will assign a "free" function thereby making the Ruby object
 
9929
responsible for freeing the C++ object</li>
 
9930
 
 
9931
 
 
9932
 
 
9933
 
 
9934
 
 
9935
  <li> When calling a C++ member function that returns a pointer,
 
9936
SWIG will not assign a "free" function thereby making the underlying
 
9937
library responsible for freeing the object.</li>
 
9938
 
 
9939
 
 
9940
 
 
9941
 
 
9942
 
 
9943
</ul>
 
9944
 
 
9945
 
 
9946
 
 
9947
 
 
9948
 
 
9949
<p>To make this clearer, let's look at an example. Assume we have
 
9950
a Foo and a Bar class. </p>
 
9951
 
 
9952
 
 
9953
 
 
9954
 
 
9955
 
 
9956
<div class="code">
 
9957
<pre>/* File "RubyOwernshipExample.h" */<br><br>class Foo<br>{<br>public:<br> Foo() {}<br> ~Foo() {}<br>};<br><br>class Bar<br>{<br> Foo *foo_;<br>public:<br> Bar(): foo_(new Foo) {}<br> ~Bar() { delete foo_; }<br> Foo* get_foo() { return foo_; }<br> Foo* get_new_foo() { return new Foo; }<br> void set_foo(Foo *foo) { delete foo_; foo_ = foo; }<br>};<br><br></pre>
 
9958
 
 
9959
 
 
9960
 
 
9961
 
 
9962
 
 
9963
</div>
 
9964
 
 
9965
 
 
9966
 
 
9967
 
 
9968
 
 
9969
<p>First, consider this Ruby code: </p>
 
9970
 
 
9971
 
 
9972
 
 
9973
 
 
9974
 
 
9975
<div class="code targetlang">
 
9976
<pre>foo = Foo.new</pre>
 
9977
 
 
9978
 
 
9979
 
 
9980
 
 
9981
 
 
9982
</div>
 
9983
 
 
9984
 
 
9985
 
 
9986
 
 
9987
 
 
9988
<p>In this case, the Ruby code calls the underlying <tt>Foo</tt>
 
9989
C++ constructor, thus creating a new <tt>foo</tt> object.
 
9990
By default, SWIG will assign the new Ruby object a "free" function.
 
9991
When the Ruby object is garbage collected, the "free" function will be
 
9992
called. It in turn will call <tt>Foo's</tt> destructor.</p>
 
9993
 
 
9994
 
 
9995
 
 
9996
 
 
9997
 
 
9998
<p>Next, consider this code: </p>
 
9999
 
 
10000
 
 
10001
 
 
10002
 
 
10003
 
 
10004
<div class="code targetlang">
 
10005
<pre>bar = Bar.new<br>foo = bar.get_foo()</pre>
 
10006
 
 
10007
 
 
10008
 
 
10009
 
 
10010
 
 
10011
</div>
 
10012
 
 
10013
 
 
10014
 
 
10015
 
 
10016
 
 
10017
<p>In this case, the Ruby code calls a C++ member function, <tt>get_foo</tt>.
 
10018
By default, SWIG will not assign the Ruby object a "free" function.
 
10019
Thus, when the Ruby object is garbage collected the underlying C++ <tt>foo</tt>
 
10020
object is not affected.</p>
 
10021
 
 
10022
 
 
10023
 
 
10024
 
 
10025
 
 
10026
<p>Unfortunately, the real world is not as simple as the examples
 
10027
above. For example:</p>
 
10028
 
 
10029
 
 
10030
 
 
10031
 
 
10032
 
 
10033
<div class="code targetlang">
 
10034
<pre>bar = Bar.new<br>foo = bar.get_new_foo()</pre>
 
10035
 
 
10036
 
 
10037
 
 
10038
 
 
10039
 
 
10040
</div>
 
10041
 
 
10042
 
 
10043
 
 
10044
 
 
10045
 
 
10046
<p>In this case, the default SWIG behavior for calling member
 
10047
functions is incorrect. The Ruby object should assume ownership of the
 
10048
returned object. This can be done by using the %newobject directive.
 
10049
See <a href="file:///d:/msys/1.0/src/SWIG/Doc/Manual/Customization.html#ownership">
 
10050
Object ownership and %newobject</a> for more information. </p>
 
10051
 
 
10052
 
 
10053
 
 
10054
 
 
10055
 
 
10056
<p>The SWIG default mappings are also incorrect in this case:</p>
 
10057
 
 
10058
 
 
10059
 
 
10060
 
 
10061
 
 
10062
<div class="code targetlang">
 
10063
<pre>foo = Foo.new<br>bar = Bar.new<br>bar.set_foo(foo)</pre>
 
10064
 
 
10065
 
 
10066
 
 
10067
 
 
10068
 
 
10069
</div>
 
10070
 
 
10071
 
 
10072
 
 
10073
 
 
10074
 
 
10075
<p>Without modification, this code will cause a segmentation
 
10076
fault. When the Ruby <tt>foo</tt> object goes out of
 
10077
scope, it will free the underlying C++ <tt>foo</tt>
 
10078
object. However, when the Ruby bar object goes out of scope, it will
 
10079
call the C++ bar destructor which will also free the C++ <tt>foo</tt>
 
10080
object. The problem is that object ownership is transferred from the
 
10081
Ruby object to the C++ object when the <tt>set_foo</tt>
 
10082
method is called. This can be done by using the special DISOWN type
 
10083
map, which was added to the Ruby bindings in SWIG-1.3.26.</p>
 
10084
 
 
10085
 
 
10086
 
 
10087
 
 
10088
 
 
10089
<p>Thus, a correct SWIG interface file correct mapping for these
 
10090
classes is:</p>
 
10091
 
 
10092
 
 
10093
 
 
10094
 
 
10095
 
 
10096
<div class="code">
 
10097
<pre>/* File RubyOwnershipExample.i */<br><br>%module RubyOwnershipExample<br><br>%{<br>#include "RubyOwnershipExample.h"<br>%}<br><br>class Foo<br>{<br>public:<br> Foo();<br> ~Foo();<br>};<br><br>class Bar<br>{<br> Foo *foo_;<br>public:<br> Bar();<br> ~Bar();<br> Foo* get_foo();<br><br><span style="font-weight: bold;"> %newobject get_new_foo;</span><br> Foo* get_new_foo();<br><br><span style="font-weight: bold;"> %apply SWIGTYPE *DISOWN {Foo *foo};</span><br> void set_foo(Foo *foo);<br><span style="font-weight: bold;"> %clear Foo *foo;</span><br>};<br><br></pre>
 
10098
 
 
10099
 
 
10100
 
 
10101
 
 
10102
 
 
10103
</div>
 
10104
 
 
10105
 
 
10106
 
 
10107
 
 
10108
 
 
10109
<br>
 
10110
 
 
10111
 
 
10112
 
 
10113
 
 
10114
 
 
10115
<p> This code can be seen in swig/examples/ruby/tracking.</p>
 
10116
 
 
10117
 
 
10118
 
 
10119
 
 
10120
 
 
10121
<br>
 
10122
 
 
10123
 
 
10124
 
 
10125
 
 
10126
 
 
10127
<H3><a name="Ruby_nn60"></a>30.10.3 Object Tracking</H3>
 
10128
 
 
10129
 
 
10130
<p>The remaining parts of this section will use the class library
 
10131
shown below to illustrate different memory management techniques. The
 
10132
class library models a zoo and the animals it contains. </p>
 
10133
 
 
10134
 
 
10135
 
 
10136
 
 
10137
 
 
10138
<div class="code">
 
10139
<pre>%module zoo<br><br>%{<br>#include &lt;string&gt;<br>#include &lt;vector&gt;<br><br>#include "zoo.h"<br>%}<br><br>class Animal<br>{<br>private:<br> typedef std::vector&lt;Animal*&gt; AnimalsType;<br> typedef AnimalsType::iterator IterType;<br>protected:<br> AnimalsType animals;<br>protected:<br> std::string name_;<br>public:<br> // Construct an animal with this name<br> Animal(const char* name) : name_(name) {}<br> <br> // Return the animal's name<br> const char* get_name() const { return name.c_str(); }<br>};<br><br>class Zoo<br>{<br>protected:<br> std::vector&lt;animal *=""&gt; animals;<br> <br>public:<br> // Construct an empty zoo<br> Zoo() {}<br> <br> /* Create a new animal. */<br> static Animal* Zoo::create_animal(const char* name)<br> {<br> return new Animal(name);<br> }<br><br> // Add a new animal to the zoo<br> void add_animal(Animal* animal) {<br> animals.push_back(animal); <br> }<br><br> Animal* remove_animal(size_t i) {<br> Animal* result = this-&gt;animals[i];<br> IterType iter = this-&gt;animals.begin();<br> std::advance(iter, i);<br> this-&gt;animals.erase(iter);<br><br> return result;<br> }<br> <br> // Return the number of animals in the zoo<br> size_t get_num_animals() const {<br> return animals.size(); <br> }<br> <br> // Return a pointer to the ith animal<br> Animal* get_animal(size_t i) const {<br> return animals[i]; <br> }<br>};<br><br></pre>
 
10140
 
 
10141
 
 
10142
 
 
10143
 
 
10144
 
 
10145
</div>
 
10146
 
 
10147
 
 
10148
 
 
10149
 
 
10150
 
 
10151
<p>Let's say you SWIG this code and then run IRB:<br>
 
10152
 
 
10153
 
 
10154
 
 
10155
 
 
10156
 
 
10157
</p>
 
10158
 
 
10159
 
 
10160
 
 
10161
 
 
10162
 
 
10163
<div class="code targetlang">
 
10164
<pre>$ <span style="font-weight: bold;">irb</span><br>irb(main):001:0&gt; <span style="font-weight: bold;">require 'example'</span><br>=&gt; true<br><br>irb(main):002:0&gt; <span style="font-weight: bold;">tiger1 = Example::Animal.new("tiger1")</span><br>=&gt; #&lt;Example::Animal:0x2be3820&gt;<br><br>irb(main):004:0&gt; <span style="font-weight: bold;">tiger1.get_name()</span><br>=&gt; "tiger1"<br><br>irb(main):003:0&gt; <span style="font-weight: bold;">zoo = Example::Zoo.new()</span><br>=&gt; #&lt;Example::Zoo:0x2be0a60&gt;<br><br>irb(main):006:0&gt; <span style="font-weight: bold;">zoo.add_animal(tiger)</span><br>=&gt; nil<br><br>irb(main):007:0&gt; <span style="font-weight: bold;">zoo.get_num_animals()</span><br>=&gt; 1<br><br>irb(main):007:0&gt; <span style="font-weight: bold;">tiger2 = zoo.remove_animal(0)</span><br>=&gt; #&lt;Example::Animal:0x2bd4a18&gt;<br><br>irb(main):008:0&gt; <span style="font-weight: bold;">tiger2.get_name()</span><br>=&gt; "tiger1"<br><br>irb(main):009:0&gt; <span style="font-weight: bold;">tiger1.equal?(tiger2)</span><br>=&gt; false<br><br></pre>
 
10165
 
 
10166
 
 
10167
 
 
10168
 
 
10169
 
 
10170
</div>
 
10171
 
 
10172
 
 
10173
 
 
10174
 
 
10175
 
 
10176
<p>Pay particular attention to the code <tt>tiger1.equal?(tiger2)</tt>.
 
10177
Note that the two Ruby objects are not the same - but they reference
 
10178
the same underlying C++ object. This can cause problems. For example:<br>
 
10179
 
 
10180
 
 
10181
 
 
10182
 
 
10183
 
 
10184
</p>
 
10185
 
 
10186
 
 
10187
 
 
10188
 
 
10189
 
 
10190
<div class="code targetlang">
 
10191
<pre>irb(main):010:0&gt; <span style="font-weight: bold;">tiger1 = nil</span><br>=&gt; nil<br><br>irb(main):011:0&gt; <span style="font-weight: bold;">GC.start</span><br>=&gt; nil<br><br>irb(main):012:0&gt; <span style="font-weight: bold;">tiger2.get_name()</span><br>(irb):12: [BUG] Segmentation fault<br><br></pre>
 
10192
 
 
10193
 
 
10194
 
 
10195
 
 
10196
 
 
10197
</div>
 
10198
 
 
10199
 
 
10200
 
 
10201
 
 
10202
 
 
10203
<p>After the the garbage collector runs, as a result of our call
 
10204
to <tt>GC.start</tt>, calling<tt>tiger2.get_name()</tt>
 
10205
causes a segmentation fault. The problem is that when <tt>tiger1</tt>
 
10206
is garbage collected, it frees the underlying C++ object. Thus, when <tt>tiger2</tt>
 
10207
calls the <tt>get_name()</tt> method it invokes it on a
 
10208
destroyed object.</p>
 
10209
 
 
10210
 
 
10211
 
 
10212
 
 
10213
 
 
10214
<p>This problem can be avoided if SWIG enforces a one-to-one
 
10215
mapping between Ruby objects and C++ classes. This can be done via the
 
10216
use of the <tt>%trackobjects</tt> functionality available
 
10217
in SWIG-1.3.26. and later.</p>
 
10218
 
 
10219
 
 
10220
 
 
10221
 
 
10222
 
 
10223
<p>When the <tt>%trackobjects</tt> is turned on,
 
10224
SWIG automatically keeps track of mappings between C++ objects and Ruby
 
10225
objects. Note that enabling object tracking causes a slight performance
 
10226
degradation. Test results show this degradation to be about 3% to 5%
 
10227
when creating and destroying 100,000 animals in a row.</p>
 
10228
 
 
10229
 
 
10230
 
 
10231
 
 
10232
 
 
10233
<p>Since <tt>%trackobjects</tt> is implemented as a <tt>%feature</tt>,
 
10234
it uses the same name matching rules as other kinds of features (see
 
10235
the chapter on <a href="Customization.html#Customization">
 
10236
"Customization Features"</a>) . Thus it can be applied on a
 
10237
class-by-class basis if needed. To fix the example above:</p>
 
10238
 
 
10239
 
 
10240
 
 
10241
 
 
10242
 
 
10243
<br>
 
10244
 
 
10245
 
 
10246
 
 
10247
 
 
10248
 
 
10249
<div class="code">
 
10250
<pre>%module example<br><br>%{<br>#include "example.h"<br>%}<br><br><span style="font-weight: bold;">/* Tell SWIG that create_animal creates a new object */</span><br><span style="font-weight: bold;">%newobject Zoo::create_animal;</span><br><br><span style="font-weight: bold;">/* Tell SWIG to keep track of mappings between C/C++ structs/classes. */</span><br style="font-weight: bold;"><span style="font-weight: bold;">%trackobjects;</span><br><br>%include "example.h"</pre>
 
10251
 
 
10252
 
 
10253
 
 
10254
 
 
10255
 
 
10256
</div>
 
10257
 
 
10258
 
 
10259
 
 
10260
 
 
10261
 
 
10262
<p>When this code runs we see:<br>
 
10263
 
 
10264
 
 
10265
 
 
10266
 
 
10267
 
 
10268
<br>
 
10269
 
 
10270
 
 
10271
 
 
10272
 
 
10273
 
 
10274
</p>
 
10275
 
 
10276
 
 
10277
 
 
10278
 
 
10279
 
 
10280
<div class="code targetlang">
 
10281
<pre>$ <span style="font-weight: bold;">irb</span><br>irb(main):001:0&gt; <span style="font-weight: bold;">require 'example'</span><br>=&gt; true<br><br>irb(main):002:0&gt; <span style="font-weight: bold;">tiger1 = Example::Animal.new("tiger1")</span><br>=&gt; #&lt;Example::Animal:0x2be37d8&gt;<br><br>irb(main):003:0&gt; <span style="font-weight: bold;">zoo = Example::Zoo.new()</span><br>=&gt; #&lt;Example::Zoo:0x2be0a18&gt;<br><br>irb(main):004:0&gt; <span style="font-weight: bold;">zoo.add_animal(tiger1)</span><br>=&gt; nil<br><br>irb(main):006:0&gt; <span style="font-weight: bold;">tiger2 = zoo.remove_animal(0)</span><br>=&gt; #&lt;Example::Animal:0x2be37d8&gt;<br><br>irb(main):007:0&gt; <span style="font-weight: bold;">tiger1.equal?(tiger2)</span><br>=&gt; true<br><br>irb(main):008:0&gt; <span style="font-weight: bold;">tiger1 = nil</span><br>=&gt; nil<br><br>irb(main):009:0&gt; <span style="font-weight: bold;">GC.start</span><br>=&gt; nil<br><br>irb(main):010:0&gt; <span style="font-weight: bold;">tiger.get_name()</span><br>=&gt; "tiger1"<br>irb(main):011:0&gt;<br><br></pre>
 
10282
 
 
10283
 
 
10284
 
 
10285
 
 
10286
 
 
10287
</div>
 
10288
 
 
10289
 
 
10290
 
 
10291
 
 
10292
 
 
10293
<p>For those who are interested, object tracking is implemented
 
10294
by storing Ruby objects in a hash table and keying them on C++
 
10295
pointers. The underlying API is:<br>
 
10296
 
 
10297
 
 
10298
 
 
10299
 
 
10300
 
 
10301
</p>
 
10302
 
 
10303
 
 
10304
 
 
10305
 
 
10306
 
 
10307
<div class="code">
 
10308
<pre>static void SWIG_RubyAddTracking(void* ptr, VALUE object);<br>static VALUE SWIG_RubyInstanceFor(void* ptr) ;<br>static void SWIG_RubyRemoveTracking(void* ptr);<br>static void SWIG_RubyUnlinkObjects(void* ptr);</pre>
 
10309
 
 
10310
 
 
10311
 
 
10312
 
 
10313
 
 
10314
</div>
 
10315
 
 
10316
 
 
10317
 
 
10318
 
 
10319
 
 
10320
<p>When an object is created, SWIG will automatically call the <tt>SWIG_RubyAddTracking</tt>
 
10321
method. Similarly, when an object is deleted, SWIG will call the <tt>SWIG_RubyRemoveTracking</tt>.
 
10322
When an object is returned to Ruby from C++, SWIG will use the <tt>SWIG_RubyInstanceFor</tt>
 
10323
method to ensure a one-to-one mapping from Ruby to C++ objects. Last,
 
10324
the <tt>RubyUnlinkObjects</tt> method unlinks a Ruby
 
10325
object from its underlying C++ object.</p>
 
10326
 
 
10327
 
 
10328
 
 
10329
 
 
10330
 
 
10331
<p>In general, you will only need to use the <tt>SWIG_RubyInstanceFor</tt>,
 
10332
which is required for implementing mark functions as shown below.
 
10333
However, if you implement your own free functions (see below) you may
 
10334
also have to call the<tt> SWIG_RubyRemoveTracking</tt> and <tt>RubyUnlinkObjects</tt>
 
10335
methods.</p>
 
10336
 
 
10337
 
 
10338
 
 
10339
 
 
10340
 
 
10341
<H3><a name="Ruby_nn61"></a>30.10.4 Mark Functions</H3>
 
10342
 
 
10343
 
 
10344
<p>With a bit more testing, we see that our class library still
 
10345
has problems. For example:<br>
 
10346
 
 
10347
 
 
10348
 
 
10349
 
 
10350
 
 
10351
</p>
 
10352
 
 
10353
 
 
10354
 
 
10355
 
 
10356
 
 
10357
<div class="targetlang">
 
10358
<pre>$ <b>irb</b><br>irb(main):001:0&gt; <span style="font-weight: bold;">require 'example'</span><br>=&gt; true<br><br>irb(main):002:0&gt; tiger1 = <span style="font-weight: bold;">Example::Animal.new("tiger1")</span><br>=&gt; #&lt;Example::Animal:0x2bea6a8&gt;<br><br>irb(main):003:0&gt; zoo = <span style="font-weight: bold;">Example::Zoo.new()</span><br>=&gt; #&lt;Example::Zoo:0x2be7960&gt;<br><br>irb(main):004:0&gt; <span style="font-weight: bold;">zoo.add_animal(tiger1)</span><br>=&gt; nil<br><br>irb(main):007:0&gt; <span style="font-weight: bold;">tiger1 = nil</span><br>=&gt; nil<br><br>irb(main):007:0&gt; <span style="font-weight: bold;">GC.start</span><br>=&gt; nil<br><br>irb(main):005:0&gt; <span style="font-weight: bold;">tiger2 = zoo.get_animal(0)</span><br>(irb):12: [BUG] Segmentation fault</pre>
 
10359
 
 
10360
 
 
10361
 
 
10362
 
 
10363
 
 
10364
</div>
 
10365
 
 
10366
 
 
10367
 
 
10368
 
 
10369
 
 
10370
<p>The problem is that Ruby does not know that the <tt>zoo</tt>
 
10371
object contains a reference to a Ruby object. Thus, when Ruby garbage
 
10372
collects <span style="font-family: monospace;">tiger1</span>
 
10373
it frees the underlying C++ object.</p>
 
10374
 
 
10375
 
 
10376
 
 
10377
 
 
10378
 
 
10379
<p>This can be fixed by implementing a <tt>mark</tt>
 
10380
function as described above in the <a href="Ruby.html#Ruby_nn52">Mark
 
10381
and Sweep Garbage Collector</a> section. You can specify a mark
 
10382
function by using the <tt>%markfunc</tt> directive. Since
 
10383
the <tt>%markfunc</tt> directive is implemented using
 
10384
SWIG's' "features" mechanism it uses the same name matching rules as
 
10385
other kinds of features (see the chapter on <a href="Customization.html#Customization">"Customization
 
10386
Features"</a> for more details). </p>
 
10387
 
 
10388
 
 
10389
 
 
10390
 
 
10391
 
 
10392
<p>A <tt>mark</tt> function takes a single argument,
 
10393
which is a pointer to the C++ object being marked; it should, in turn,
 
10394
call <tt>rb_gc_mark()</tt> for any instances that are
 
10395
reachable from the current object. The mark function for our <tt>
 
10396
Zoo</tt> class should therefore loop over all of the C++ animal
 
10397
objects in the zoo object, look up their Ruby object equivalent, and
 
10398
then call <tt>rb_gc_mark()</tt>. One possible
 
10399
implementation is:</p>
 
10400
 
 
10401
 
 
10402
 
 
10403
 
 
10404
 
 
10405
<div class="code">
 
10406
<pre>%module example<br><br>%{<br>#include "example.h"<br>%}<br><br>/* Keep track of mappings between C/C++ structs/classes<br> and Ruby objects so we can implement a mark function. */<br><span style="font-weight: bold;">%trackobjects;</span><br><br>/* Specify the mark function */<br><span style="font-weight: bold;">%markfunc Zoo "mark_Zoo";</span><br><br>%include "example.h"<br><br>%header %{<br><br>static void mark_Zoo(void* ptr) {<br> Zoo* zoo = (Zoo*) ptr;<br><br> /* Loop over each object and tell the garbage collector<br> that we are holding a reference to them. */<br> int count = zoo-&gt;get_num_animals();<br><br> for(int i = 0; i &lt; count; ++i) {<br> Animal* animal = zoo-&gt;get_animal(i);<br> VALUE object = SWIG_RubyInstanceFor(animal);<br><br> if (object != Qnil) {<br> rb_gc_mark(object);<br> }<br> }<br>}<br>%}<br><br></pre>
 
10407
 
 
10408
 
 
10409
 
 
10410
 
 
10411
 
 
10412
</div>
 
10413
 
 
10414
 
 
10415
 
 
10416
 
 
10417
 
 
10418
<p> Note the <tt>mark</tt> function is dependent on
 
10419
the <tt>SWIG_RUBY_InstanceFor</tt> method, and thus
 
10420
requires that <tt>%trackobjects</tt> is enabled. For more
 
10421
information, please refer to the track_object.i test case in the SWIG
 
10422
test suite.</p>
 
10423
 
 
10424
 
 
10425
 
 
10426
 
 
10427
 
 
10428
<p>When this code is compiled we now see:</p>
 
10429
 
 
10430
 
 
10431
 
 
10432
 
 
10433
 
 
10434
<div class="targetlang">
 
10435
<pre>$ <b>irb<br></b>irb(main):002:0&gt; <span style="font-weight: bold;">tiger1=Example::Animal.new("tiger1")</span><br>=&gt; #&lt;Example::Animal:0x2be3bf8&gt;<br><br>irb(main):003:0&gt; <span style="font-weight: bold;">Example::Zoo.new()</span><br>=&gt; #&lt;Example::Zoo:0x2be1780&gt;<br><br>irb(main):004:0&gt; <span style="font-weight: bold;">zoo = Example::Zoo.new()</span><br>=&gt; #&lt;Example::Zoo:0x2bde9c0&gt;<br><br>irb(main):005:0&gt; <span style="font-weight: bold;">zoo.add_animal(tiger1)</span><br>=&gt; nil<br><br>irb(main):009:0&gt; <span style="font-weight: bold;">tiger1 = nil</span><br>=&gt; nil<br><br>irb(main):010:0&gt; <span style="font-weight: bold;">GC.start</span><br>=&gt; nil<br>irb(main):014:0&gt; <span style="font-weight: bold;">tiger2 = zoo.get_animal(0)</span><br>=&gt; #&lt;Example::Animal:0x2be3bf8&gt;<br><br>irb(main):015:0&gt; <span style="font-weight: bold;">tiger2.get_name()</span><br>=&gt; "tiger1"<br>irb(main):016:0&gt;<br><br></pre>
 
10436
 
 
10437
 
 
10438
 
 
10439
 
 
10440
 
 
10441
</div>
 
10442
 
 
10443
 
 
10444
 
 
10445
 
 
10446
 
 
10447
<br>
 
10448
 
 
10449
 
 
10450
 
 
10451
 
 
10452
 
 
10453
<p>This code can be seen in swig/examples/ruby/mark_function.</p>
 
10454
 
 
10455
 
 
10456
 
 
10457
 
 
10458
 
 
10459
<H3><a name="Ruby_nn62"></a>30.10.5 Free Functions</H3>
 
10460
 
 
10461
 
 
10462
<p>By default, SWIG creates a "free" function that is called when
 
10463
a Ruby object is garbage collected. The free function simply calls the
 
10464
C++ object's destructor.</p>
 
10465
 
 
10466
 
 
10467
 
 
10468
 
 
10469
 
 
10470
<p>However, sometimes an appropriate destructor does not exist or
 
10471
special processing needs to be performed before the destructor is
 
10472
called. Therefore, SWIG allows you to manually specify a "free"
 
10473
function via the use of the <tt>%freefunc</tt> directive.
 
10474
The <tt>%freefunc</tt> directive is implemented using
 
10475
SWIG's' "features" mechanism and so the same name matching rules used
 
10476
for other kinds of features apply (see the chapter on <a href="Customization.html#Customization">"Customization
 
10477
Features"</a>) for more details).</p>
 
10478
 
 
10479
 
 
10480
 
 
10481
 
 
10482
 
 
10483
<p>IMPORTANT ! - If you define your own free function, then you
 
10484
must ensure that you call the underlying C++ object's destructor. In
 
10485
addition, if object tracking is activated for the object's class, you
 
10486
must also call the <tt>SWIG_RubyRemoveTracking</tt>
 
10487
function (of course call this before you destroy the C++ object). Note
 
10488
that it is harmless to call this method if object tracking if off so it
 
10489
is advised to always call it.</p>
 
10490
 
 
10491
 
 
10492
 
 
10493
 
 
10494
 
 
10495
<p>Note there is a subtle interaction between object ownership
 
10496
and free functions. A custom defined free function will only be called
 
10497
if the Ruby object owns the underlying C++ object. This also to Ruby
 
10498
objects which are created, but then transfer ownership to C++ objects
 
10499
via the use of the <tt>disown</tt> typemap described
 
10500
above. </p>
 
10501
 
 
10502
 
 
10503
 
 
10504
 
 
10505
 
 
10506
<p>To show how to use the <tt>%freefunc</tt>
 
10507
directive, let's slightly change our example. Assume that the zoo
 
10508
object is responsible for freeing animal that it contains. This means
 
10509
that the <span style="font-family: monospace;">Zoo::add_animal</span>
 
10510
function should be marked with a <span style="font-family: monospace;">DISOWN</span> typemap
 
10511
and the destructor should be updated as below::</p>
 
10512
 
 
10513
 
 
10514
 
 
10515
 
 
10516
 
 
10517
<div class="code">
 
10518
<pre>Zoo::~Zoo() {<br> IterType iter = this-&gt;animals.begin();<br> IterType end = this-&gt;animals.end();<br><br> for(iter; iter != end; ++iter) {<br> Animal* animal = *iter;<br> delete animal;<br> }<br>}</pre>
 
10519
 
 
10520
 
 
10521
 
 
10522
 
 
10523
 
 
10524
</div>
 
10525
 
 
10526
 
 
10527
 
 
10528
 
 
10529
 
 
10530
<p>When we use these objects in IRB we see:</p>
 
10531
 
 
10532
 
 
10533
 
 
10534
 
 
10535
 
 
10536
<div class="code targetlang">
 
10537
<pre class="targetlang"><span style="font-weight: bold;">$irb</span><br>irb(main):002:0&gt; <span style="font-weight: bold;">require 'example'</span><br>=&gt; true<br><br>irb(main):003:0&gt; <span style="font-weight: bold;">zoo = Example::Zoo.new()</span><br>=&gt; #&lt;Example::Zoo:0x2be0fe8&gt;<br><br>irb(main):005:0&gt; <span style="font-weight: bold;">tiger1 = Example::Animal.new("tiger1")</span><br>=&gt; #&lt;Example::Animal:0x2bda760&gt;<br><br>irb(main):006:0&gt; <span style="font-weight: bold;">zoo.add_animal(tiger1)</span><br>=&gt; nil<br><br>irb(main):007:0&gt; <span style="font-weight: bold;">zoo = nil</span><br>=&gt; nil<br><br>irb(main):008:0&gt; <span style="font-weight: bold;">GC.start</span><br>=&gt; nil<br><br>irb(main):009:0&gt; <span style="font-weight: bold;">tiger1.get_name()</span><br>(irb):12: [BUG] Segmentation fault<br><br></pre>
 
10538
 
 
10539
 
 
10540
 
 
10541
 
 
10542
 
 
10543
</div>
 
10544
 
 
10545
 
 
10546
 
 
10547
 
 
10548
 
 
10549
<p>The error happens because the C++ <tt>animal</tt>
 
10550
object is freed when the <tt>zoo</tt> object is freed.
 
10551
Although this error is unavoidable, we can at least prevent the
 
10552
segmentation fault. To do this requires enabling object tracking and
 
10553
implementing a custom free function that calls the <tt>SWIG_RubyUnlinkObjects</tt>
 
10554
function for each animal object that is destroyed. The <tt>SWIG_RubyUnlinkObjects</tt>
 
10555
function notifies SWIG that a Ruby object's underlying C++ object is no
 
10556
longer valid. Once notified, SWIG will intercept any calls from the
 
10557
existing Ruby object to the destroyed C++ object and raise an exception.<br>
 
10558
 
 
10559
 
 
10560
 
 
10561
 
 
10562
 
 
10563
</p>
 
10564
 
 
10565
 
 
10566
 
 
10567
 
 
10568
 
 
10569
<div class="code">
 
10570
<pre>%module example<br><br>%{<br>#include "example.h"<br>%}<br><br>/* Specify that ownership is transferred to the zoo<br>     when calling add_animal */<br>%apply SWIGTYPE *DISOWN { Animal* animal };<br><br>/* Track objects */<br>%trackobjects;<br><br>/* Specify the mark function */<br>%freefunc Zoo "free_Zoo";<br><br>%include "example.h"<br><br>%header %{<br> static void free_Zoo(void* ptr) {<br> Zoo* zoo = (Zoo*) ptr;<br><br> /* Loop over each animal */<br> int count = zoo-&gt;get_num_animals();<br><br> for(int i = 0; i &lt; count; ++i) {<br> /* Get an animal */<br> Animal* animal = zoo-&gt;get_animal(i);<br><br> /* Unlink the Ruby object from the C++ object */<br> SWIG_RubyUnlinkObjects(animal);<br><br> /* Now remove the tracking for this animal */<br> SWIG_RubyRemoveTracking(animal);<br> }<br><br> /* Now call SWIG_RemoveMapping for the zoo */<br> SWIG_RemoveMapping(ptr);<br> <br> /* Now free the zoo which will free the animals it contains */<br> delete zoo;<br> }<br>%} </pre>
 
10571
 
 
10572
 
 
10573
 
 
10574
 
 
10575
 
 
10576
</div>
 
10577
 
 
10578
 
 
10579
 
 
10580
 
 
10581
 
 
10582
<p>Now when we use these objects in IRB we see:</p>
 
10583
 
 
10584
 
 
10585
 
 
10586
 
 
10587
 
 
10588
<div class="code targetlang">
 
10589
<pre><span style="font-weight: bold;">$irb</span><br>irb(main):002:0&gt; <span style="font-weight: bold;">require 'example'</span><br>=&gt; true<br><br>irb(main):003:0&gt; <span style="font-weight: bold;">zoo = Example::Zoo.new()</span><br>=&gt; #&lt;Example::Zoo:0x2be0fe8&gt;<br><br>irb(main):005:0&gt; <span style="font-weight: bold;">tiger1 = Example::Animal.new("tiger1")</span><br>=&gt; #&lt;Example::Animal:0x2bda760&gt;<br><br>irb(main):006:0&gt; <span style="font-weight: bold;">zoo.add_animal(tiger1)</span><br>=&gt; nil<br><br>irb(main):007:0&gt; <span style="font-weight: bold;">zoo = nil</span><br>=&gt; nil<br><br>irb(main):008:0&gt; <span style="font-weight: bold;">GC.start</span><br>=&gt; nil<br><br>irb(main):009:0&gt; <span style="font-weight: bold;">tiger1.get_name()</span><br>RuntimeError: This Animal * already released<br> from (irb):10:in `get_name'<br> from (irb):10<br>irb(main):011:0&gt;</pre>
 
10590
 
 
10591
 
 
10592
 
 
10593
 
 
10594
 
 
10595
</div>
 
10596
 
 
10597
 
 
10598
 
 
10599
 
 
10600
 
 
10601
<p>Notice that SWIG can now detect the underlying C++ object has
 
10602
been freed, and thus raises a runtime exception.</p>
 
10603
 
 
10604
 
 
10605
 
 
10606
 
 
10607
 
 
10608
<p>This code can be seen in swig/examples/ruby/free_function.</p>
 
10609
 
 
10610
 
 
10611
 
 
10612
 
 
10613
 
 
10614
<H3><a name="Ruby_nn63"></a>30.10.6 Embedded Ruby and the C++ Stack</H3>
 
10615
 
 
10616
 
 
10617
<p>As has been said, the Ruby GC runs and marks objects before
 
10618
its
 
10619
sweep phase. &nbsp;When the garbage collector is called, it will
 
10620
also
 
10621
try to mark any Ruby objects (VALUE) it finds in the machine registers
 
10622
and in the C++ stack.</p>
 
10623
 
 
10624
 
 
10625
 
 
10626
 
 
10627
 
 
10628
<p>The stack is basically the history of the functions that have
 
10629
been
 
10630
called and also contains local variables, such as the ones you define
 
10631
whenever you do inside a function:</p>
 
10632
 
 
10633
 
 
10634
 
 
10635
 
 
10636
 
 
10637
<div class="diagram">VALUE obj; </div>
 
10638
 
 
10639
 
 
10640
 
 
10641
 
 
10642
 
 
10643
<p>For ruby to determine where its stack space begins, during
 
10644
initialization a normal Ruby interpreter will call the ruby_init()
 
10645
function which in turn will call a function called Init_stack or
 
10646
similar. &nbsp;This function will store a pointer to the location
 
10647
where
 
10648
the stack points at at that point in time.</p>
 
10649
 
 
10650
 
 
10651
 
 
10652
 
 
10653
 
 
10654
<p>ruby_init() is presumed to always be called within the main()
 
10655
function of your program and whenever the GC is called, ruby will
 
10656
assume that the memory between the current location in memory and the
 
10657
pointer that was stored previously represents the stack, which may
 
10658
contain local (and temporary) VALUE ruby objects. &nbsp; Ruby will
 
10659
then be careful not to remove any of those objects in that location.</p>
 
10660
 
 
10661
 
 
10662
 
 
10663
 
 
10664
 
 
10665
<p>So far so good. &nbsp;For a normal Ruby session, all the
 
10666
above is
 
10667
completely transparent and magic to the extensions developer.
 
10668
&nbsp;&nbsp;</p>
 
10669
 
 
10670
 
 
10671
 
 
10672
 
 
10673
 
 
10674
<p>However, with an embedded Ruby, it may not always be possible
 
10675
to
 
10676
modify main() to make sure ruby_init() is called there. &nbsp; As
 
10677
such,
 
10678
ruby_init() will likely end up being called from within some other
 
10679
function. &nbsp;This can lead Ruby to measure incorrectly where the
 
10680
stack begins and&nbsp;can result in Ruby incorrectly collecting
 
10681
those
 
10682
temporary VALUE objects that are created once another&nbsp;function
 
10683
is
 
10684
called. &nbsp;The end result: random crashes and segmentation
 
10685
faults.</p>
 
10686
 
 
10687
 
 
10688
 
 
10689
 
 
10690
 
 
10691
<p>This problem will often be seen in director functions that are
 
10692
used for callbacks, for example. &nbsp;</p>
 
10693
 
 
10694
 
 
10695
 
 
10696
 
 
10697
 
 
10698
<p>To solve the problem, SWIG can now generate code with director
 
10699
functions&nbsp;containing the optional macros SWIG_INIT_STACK and
 
10700
SWIG_RELEASE_STACK. &nbsp; These macros will try to force Ruby to
 
10701
reinitiliaze the beginning of the stack&nbsp;the first time a
 
10702
director
 
10703
function is called. &nbsp;This will lead Ruby to measure and not
 
10704
collect any VALUE objects defined from that point on. &nbsp;</p>
 
10705
 
 
10706
 
 
10707
 
 
10708
 
 
10709
 
 
10710
<p>To mark functions to either reset the ruby stack or not, you
 
10711
can use:</p>
 
10712
 
 
10713
 
 
10714
 
 
10715
 
 
10716
 
 
10717
<div class="indent code" style="font-family: monospace;">%initstack
 
10718
&nbsp; Class::memberfunction; &nbsp;// only re-init the stack
 
10719
in this director method<br>
 
10720
 
 
10721
 
 
10722
 
 
10723
 
 
10724
 
 
10725
%ignorestack Class::memberfunction; &nbsp;// do not re-init the
 
10726
stack in this director method<br>
 
10727
 
 
10728
 
 
10729
 
 
10730
 
 
10731
 
 
10732
%initstack &nbsp; Class; &nbsp; &nbsp; &nbsp;
 
10733
&nbsp; &nbsp; &nbsp; &nbsp; // init the stack on all
 
10734
the methods of this class<br>
 
10735
 
 
10736
 
 
10737
 
 
10738
 
 
10739
 
 
10740
%initstack; &nbsp; // all director functions will
 
10741
re-init the stack</div>
 
10742
 
 
10743
 
 
10744
</body>
2295
10745
</html>