Commit | Line | Data |
---|---|---|
920dae64 AT |
1 | <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> |
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);"> | |
8 | <H1><a name="Ruby"></a>27 SWIG and Ruby</H1> | |
9 | <!-- INDEX --> | |
10 | <div class="sectiontoc"> | |
11 | <ul> | |
12 | <li><a href="#Ruby_nn2">Preliminaries</a> | |
13 | <ul> | |
14 | <li><a href="#Ruby_nn3">Running SWIG</a> | |
15 | <li><a href="#Ruby_nn4">Getting the right header files</a> | |
16 | <li><a href="#Ruby_nn5">Compiling a dynamic module</a> | |
17 | <li><a href="#Ruby_nn6">Using your module</a> | |
18 | <li><a href="#Ruby_nn7">Static linking</a> | |
19 | <li><a href="#Ruby_nn8">Compilation of C++ extensions</a> | |
20 | </ul> | |
21 | <li><a href="#Ruby_nn9">Building Ruby Extensions under Windows 95/NT</a> | |
22 | <ul> | |
23 | <li><a href="#Ruby_nn10">Running SWIG from Developer Studio</a> | |
24 | </ul> | |
25 | <li><a href="#Ruby_nn11">The Ruby-to-C/C++ Mapping</a> | |
26 | <ul> | |
27 | <li><a href="#Ruby_nn12">Modules</a> | |
28 | <li><a href="#Ruby_nn13">Functions</a> | |
29 | <li><a href="#Ruby_nn14">Variable Linking</a> | |
30 | <li><a href="#Ruby_nn15">Constants</a> | |
31 | <li><a href="#Ruby_nn16">Pointers</a> | |
32 | <li><a href="#Ruby_nn17">Structures</a> | |
33 | <li><a href="#Ruby_nn18">C++ classes</a> | |
34 | <li><a href="#Ruby_nn19">C++ Inheritance</a> | |
35 | <li><a href="#Ruby_nn20">C++ Overloaded Functions</a> | |
36 | <li><a href="#Ruby_nn21">C++ Operators</a> | |
37 | <li><a href="#Ruby_nn22">C++ namespaces</a> | |
38 | <li><a href="#Ruby_nn23">C++ templates</a> | |
39 | <li><a href="#ruby_cpp_smart_pointers">C++ Smart Pointers</a> | |
40 | <li><a href="#Ruby_nn25">Cross-Language Polymorphism</a> | |
41 | <ul> | |
42 | <li><a href="#Ruby_nn26">Exception Unrolling</a> | |
43 | </ul> | |
44 | </ul> | |
45 | <li><a href="#Ruby_nn27">Input and output parameters</a> | |
46 | <li><a href="#Ruby_nn29">Typemaps</a> | |
47 | <ul> | |
48 | <li><a href="#Ruby_nn30">What is a typemap?</a> | |
49 | <li><a href="#Ruby_nn31">Ruby typemaps</a> | |
50 | <li><a href="#Ruby_nn32">Typemap variables</a> | |
51 | <li><a href="#Ruby_nn33">Useful Functions</a> | |
52 | <ul> | |
53 | <li><a href="#Ruby_nn34">C Datatypes to Ruby Objects</a> | |
54 | <li><a href="#Ruby_nn35">Ruby Objects to C Datatypes</a> | |
55 | <li><a href="#Ruby_nn36">Macros for VALUE</a> | |
56 | <li><a href="#Ruby_nn37">Exceptions</a> | |
57 | <li><a href="#Ruby_nn38">Iterators</a> | |
58 | </ul> | |
59 | <li><a href="#ruby_typemap_examples">Typemap Examples</a> | |
60 | <li><a href="#Ruby_nn40">Converting a Ruby array to a char **</a> | |
61 | <li><a href="#Ruby_nn41">Collecting arguments in a hash</a> | |
62 | <li><a href="#Ruby_nn42">Pointer handling</a> | |
63 | <ul> | |
64 | <li><a href="#Ruby_nn43">Ruby Datatype Wrapping</a> | |
65 | </ul> | |
66 | </ul> | |
67 | <li><a href="#ruby_operator_overloading">Operator overloading</a> | |
68 | <ul> | |
69 | <li><a href="#Ruby_nn45">Example: STL Vector to Ruby Array</a> | |
70 | </ul> | |
71 | <li><a href="#Ruby_nn46">Advanced Topics</a> | |
72 | <ul> | |
73 | <li><a href="#Ruby_nn47">Creating Multi-Module Packages</a> | |
74 | <li><a href="#Ruby_nn48">Defining Aliases</a> | |
75 | <li><a href="#Ruby_nn49">Predicate Methods</a> | |
76 | <li><a href="#Ruby_nn50">Specifying Mixin Modules</a> | |
77 | </ul> | |
78 | <li><a href="#Ruby_nn51">Memory Management</a> | |
79 | <ul> | |
80 | <li><a href="#Ruby_nn53">Object Ownership</a> | |
81 | <li><a href="#Ruby_nn54">Object Tracking</a> | |
82 | <li><a href="#Ruby_nn55">Mark Functions</a> | |
83 | <li><a href="#Ruby_nn56">Free Functions</a> | |
84 | </ul> | |
85 | </ul> | |
86 | </div> | |
87 | <!-- INDEX --> | |
88 | ||
89 | ||
90 | ||
91 | <div class="sectiontoc"> | |
92 | <ul> | |
93 | <li> | |
94 | <a href="#Ruby_nn2">Preliminaries</a> | |
95 | <ul> | |
96 | <li> | |
97 | <a href="#Ruby_nn3">Running SWIG</a> | |
98 | <li> | |
99 | <a href="#Ruby_nn4">Getting the right header files</a> | |
100 | <li> | |
101 | <a href="#Ruby_nn5">Compiling a dynamic module</a> | |
102 | <li> | |
103 | <a href="#Ruby_nn6">Using your module</a> | |
104 | <li> | |
105 | <a href="#Ruby_nn7">Static linking</a> | |
106 | <li> | |
107 | <a href="#Ruby_nn8">Compilation of C++ extensions</a> | |
108 | </ul> | |
109 | <li> | |
110 | <a href="#Ruby_nn9">Building Ruby Extensions under Windows 95/NT</a> | |
111 | <ul> | |
112 | <li> | |
113 | <a href="#Ruby_nn10">Running SWIG from Developer Studio</a> | |
114 | </ul> | |
115 | <li> | |
116 | <a href="#Ruby_nn11">The Ruby-to-C/C++ Mapping</a> | |
117 | <ul> | |
118 | <li> | |
119 | <a href="#Ruby_nn12">Modules</a> | |
120 | <li> | |
121 | <a href="#Ruby_nn13">Functions</a> | |
122 | <li> | |
123 | <a href="#Ruby_nn14">Variable Linking</a> | |
124 | <li> | |
125 | <a href="#Ruby_nn15">Constants</a> | |
126 | <li> | |
127 | <a href="#Ruby_nn16">Pointers</a> | |
128 | <li> | |
129 | <a href="#Ruby_nn17">Structures</a> | |
130 | <li> | |
131 | <a href="#Ruby_nn18">C++ classes</a> | |
132 | <li> | |
133 | <a href="#Ruby_nn19">C++ Inheritance</a> | |
134 | <li> | |
135 | <a href="#Ruby_nn20">C++ Overloaded Functions</a> | |
136 | <li> | |
137 | <a href="#Ruby_nn21">C++ Operators</a> | |
138 | <li> | |
139 | <a href="#Ruby_nn22">C++ namespaces</a> | |
140 | <li> | |
141 | <a href="#Ruby_nn23">C++ templates</a> | |
142 | <li> | |
143 | <a href="#ruby_cpp_smart_pointers">C++ Smart Pointers</a> | |
144 | <li> | |
145 | <a href="#Ruby_nn25">Cross-Language Polymorphism</a> | |
146 | <ul> | |
147 | <li> | |
148 | <a href="#Ruby_nn26">Exception Unrolling</a> | |
149 | </ul> | |
150 | </ul> | |
151 | <li> | |
152 | <a href="#Ruby_nn27">Input and output parameters</a> | |
153 | <li> | |
154 | <a href="#Ruby_nn28">Simple exception handling </a> | |
155 | <li> | |
156 | <a href="#Ruby_nn29">Typemaps</a> | |
157 | <ul> | |
158 | <li> | |
159 | <a href="#Ruby_nn30">What is a typemap?</a> | |
160 | <li> | |
161 | <a href="#Ruby_nn31">Ruby typemaps</a> | |
162 | <li> | |
163 | <a href="#Ruby_nn32">Typemap variables</a> | |
164 | <li> | |
165 | <a href="#Ruby_nn33">Useful Functions</a> | |
166 | <ul> | |
167 | <li> | |
168 | <a href="#Ruby_nn34">C Datatypes to Ruby Objects</a> | |
169 | <li> | |
170 | <a href="#Ruby_nn35">Ruby Objects to C Datatypes</a> | |
171 | <li> | |
172 | <a href="#Ruby_nn36">Macros for VALUE</a> | |
173 | <li> | |
174 | <a href="#Ruby_nn37">Exceptions</a> | |
175 | <li> | |
176 | <a href="#Ruby_nn38">Iterators</a> | |
177 | </ul> | |
178 | <li> | |
179 | <a href="#ruby_typemap_examples">Typemap Examples</a> | |
180 | <li> | |
181 | <a href="#Ruby_nn40">Converting a Ruby array to a char **</a> | |
182 | <li> | |
183 | <a href="#Ruby_nn41">Collecting arguments in a hash</a> | |
184 | <li> | |
185 | <a href="#Ruby_nn42">Pointer handling</a> | |
186 | <ul> | |
187 | <li> | |
188 | <a href="#Ruby_nn43">Ruby Datatype Wrapping</a> | |
189 | </ul> | |
190 | </ul> | |
191 | <li> | |
192 | <a href="#ruby_operator_overloading">Operator overloading</a> | |
193 | <ul> | |
194 | <li> | |
195 | <a href="#Ruby_nn45">Example: STL Vector to Ruby Array</a> | |
196 | </ul> | |
197 | <li> | |
198 | <a href="#Ruby_nn46">Advanced Topics</a> | |
199 | <ul> | |
200 | <li> | |
201 | <a href="#Ruby_nn47">Creating Multi-Module Packages</a> | |
202 | <li> | |
203 | <a href="#Ruby_nn48">Defining Aliases</a> | |
204 | <li> | |
205 | <a href="#Ruby_nn49">Predicate Methods</a> | |
206 | <li> | |
207 | <a href="#Ruby_nn50">Specifying Mixin Modules</a> | |
208 | </ul> | |
209 | <li> | |
210 | <a href="#Ruby_nn51">Memory Management</a> | |
211 | <ul> | |
212 | <li> | |
213 | <a href="#Ruby_nn52">Mark and Sweep Garbage Collector </a> | |
214 | <li> | |
215 | <a href="#Ruby_nn53">Object Ownership</a> | |
216 | <li> | |
217 | <a href="#Ruby_nn54">Object Tracking</a> | |
218 | <li> | |
219 | <a href="#Ruby_nn55">Mark Functions</a> | |
220 | <li> | |
221 | <a href="#Ruby_nn56">Free Functions</a> | |
222 | </ul> | |
223 | </ul> | |
224 | </div> <!-- INDEX --> | |
225 | <p>This chapter describes SWIG's support of Ruby.</p> | |
226 | <H2><a name="Ruby_nn2"></a>27.1 Preliminaries</H2> | |
227 | ||
228 | ||
229 | <p> | |
230 | SWIG 1.3 is known to work with Ruby versions 1.6 and later. Given the choice, | |
231 | you should use the latest stable version of Ruby. You should also determine if | |
232 | your system supports shared libraries and dynamic loading. SWIG will work with | |
233 | or without dynamic loading, but the compilation process will vary. | |
234 | </p> | |
235 | <p>This chapter covers most SWIG features, but in less depth than is found in | |
236 | earlier chapters. At the very least, make sure you also read the "<a href="SWIG.html#SWIG">SWIG | |
237 | Basics</a>" chapter. It is also assumed that the reader has a basic | |
238 | understanding of Ruby. | |
239 | </p> | |
240 | <H3><a name="Ruby_nn3"></a>27.1.1 Running SWIG</H3> | |
241 | ||
242 | ||
243 | <p> | |
244 | To build a Ruby module, run SWIG using the <tt>-ruby</tt> option:</p> | |
245 | <div class="code"> | |
246 | <pre>$ <b>swig -ruby example.i</b> | |
247 | </pre> | |
248 | </div> | |
249 | <p> | |
250 | If building a C++ extension, add the <tt>-c++</tt> option: | |
251 | </p> | |
252 | <div class="code"> | |
253 | <pre>$ <b>swig -c++ -ruby example.i</b> | |
254 | </pre> | |
255 | </div> | |
256 | <p> | |
257 | This creates a file <tt>example_wrap.c</tt> (<tt>example_wrap.cxx</tt> if | |
258 | compiling a C++ extension) that contains all of the code needed to build a Ruby | |
259 | extension module. To finish building the module, you need to compile this file | |
260 | and link it with the rest of your program. | |
261 | </p> | |
262 | <H3><a name="Ruby_nn4"></a>27.1.2 Getting the right header files</H3> | |
263 | ||
264 | ||
265 | <p> | |
266 | In order to compile the wrapper code, the compiler needs the <tt>ruby.h</tt> header | |
267 | file. This file is usually contained in a directory such as | |
268 | </p> | |
269 | <div class="code"> | |
270 | <pre>/usr/local/lib/ruby/1.6/i686-linux/ruby.h<br></pre> | |
271 | </div> | |
272 | <p> | |
273 | The exact location may vary on your machine, but the above location is typical. | |
274 | If you are not entirely sure where Ruby is installed, you can run Ruby to find | |
275 | out. For example: | |
276 | </p> | |
277 | <div class="code"> | |
278 | <pre> | |
279 | $ <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 | |
280 | /usr/local/lib/ruby/site_ruby /usr/local/lib/ruby/1.6 /usr/local/lib/ruby/1.6/i686-linux . | |
281 | </pre> | |
282 | </div> | |
283 | <H3><a name="Ruby_nn5"></a>27.1.3 Compiling a dynamic module</H3> | |
284 | ||
285 | ||
286 | <p> | |
287 | Ruby extension modules are typically compiled into shared libraries that the | |
288 | interpreter loads dynamically at runtime. Since the exact commands for doing | |
289 | this vary from platform to platform, your best bet is to follow the steps | |
290 | described in the <tt>README.EXT</tt> file from the Ruby distribution: | |
291 | </p> | |
292 | <ol> | |
293 | <li> | |
294 | <p>Create a file called <tt>extconf.rb</tt> that looks like the following:</p> | |
295 | <div class="code"> | |
296 | <pre>require 'mkmf'<br>create_makefile('example')<br></pre> | |
297 | </div> | |
298 | </li> | |
299 | <li> | |
300 | <p>Type the following to build the extension:</p> | |
301 | <div class="code"> | |
302 | <pre>$ <b>ruby extconf.rb</b><br>$ <b>make</b><br>$ <b>make install</b> | |
303 | </pre> | |
304 | </div> | |
305 | </li> | |
306 | </ol> | |
307 | <p> | |
308 | Of course, there is the problem that mkmf does not work correctly on all | |
309 | platforms, e.g, HPUX. If you need to add your own make rules to the file that <tt>extconf.rb</tt> | |
310 | produces, you can add this: | |
311 | </p> | |
312 | <div class="code"> | |
313 | <pre>open("Makefile", "a") { |mf|<br> puts <<EOM<br> # Your make rules go here<br> EOM<br>}<br></pre> | |
314 | </div> | |
315 | <p> | |
316 | to the end of the <tt>extconf.rb</tt> file. If for some reason you don't want | |
317 | to use the standard approach, you'll need to determine the correct compiler and | |
318 | linker flags for your build platform. For example, a typical sequence of | |
319 | commands for the Linux operating system would look something like this: | |
320 | </p> | |
321 | <div class="code"> | |
322 | <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> | |
323 | </pre> | |
324 | </div> | |
325 | <p> | |
326 | For other platforms it may be necessary to compile with the <tt>-fPIC</tt> option | |
327 | to generate position-independent code. If in doubt, consult the manual pages | |
328 | for your compiler and linker to determine the correct set of options. You might | |
329 | also check the <a href="http://swig.cs.uchicago.edu/cgi-bin/wiki.pl">SWIG Wiki</a> | |
330 | for additional information. | |
331 | </p> | |
332 | <p> | |
333 | <a name="n6"></a> | |
334 | </p> | |
335 | <H3><a name="Ruby_nn6"></a>27.1.4 Using your module</H3> | |
336 | ||
337 | ||
338 | <p> | |
339 | Ruby <i>module</i> names must be capitalized, but the convention for Ruby <i>feature</i> | |
340 | names is to use lowercase names. So, for example, the <b>Etc</b> extension | |
341 | module is imported by requiring the <b>etc</b> feature: | |
342 | </p> | |
343 | <div class="code"> | |
344 | <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> | |
345 | </div> | |
346 | <p> | |
347 | To stay consistent with this practice, you should always specify a <b>lowercase</b> | |
348 | module name with SWIG's <tt>%module</tt> directive. SWIG will automatically | |
349 | correct the resulting Ruby module name for your extension. So for example, a | |
350 | SWIG interface file that begins with: | |
351 | </p> | |
352 | <div class="code"> | |
353 | <pre>%module example<br></pre> | |
354 | </div> | |
355 | <p> | |
356 | will result in an extension module using the feature name "example" and Ruby | |
357 | module name "Example". | |
358 | </p> | |
359 | <H3><a name="Ruby_nn7"></a>27.1.5 Static linking</H3> | |
360 | ||
361 | ||
362 | <p> | |
363 | An alternative approach to dynamic linking is to rebuild the Ruby interpreter | |
364 | with your extension module added to it. In the past, this approach was | |
365 | sometimes necessary due to limitations in dynamic loading support on certain | |
366 | machines. However, the situation has improved greatly over the last few years | |
367 | and you should not consider this approach unless there is really no other | |
368 | option. | |
369 | </p> | |
370 | <p>The usual procedure for adding a new module to Ruby involves finding the Ruby | |
371 | source, adding an entry to the <tt>ext/Setup</tt> file, adding your directory | |
372 | to the list of extensions in the file, and finally rebuilding Ruby. | |
373 | </p> | |
374 | <p><a name="n8"></a></p> | |
375 | <H3><a name="Ruby_nn8"></a>27.1.6 Compilation of C++ extensions</H3> | |
376 | ||
377 | ||
378 | <p> | |
379 | On most machines, C++ extension modules should be linked using the C++ | |
380 | compiler. For example: | |
381 | </p> | |
382 | <div class="code"> | |
383 | <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> | |
384 | </pre> | |
385 | </div> | |
386 | <p> | |
387 | If you've written an <tt>extconf.rb</tt> script to automatically generate a <tt>Makefile</tt> | |
388 | for your C++ extension module, keep in mind that (as of this writing) Ruby | |
389 | still uses <tt>gcc</tt> and not <tt>g++</tt> as its linker. As a result, the | |
390 | required C++ runtime library support will not be automatically linked into your | |
391 | extension module and it may fail to load on some platforms. A workaround for | |
392 | this problem is use the <tt>mkmf</tt> module's <tt>append_library()</tt> method | |
393 | to add one of the C++ runtime libraries to the list of libraries linked into | |
394 | your extension, e.g. | |
395 | </p> | |
396 | <div class="code"> | |
397 | <pre>require 'mkmf'<br>$libs = append_library($libs, "supc++")<br>create_makefile('example')<br></pre> | |
398 | </div> | |
399 | <H2><a name="Ruby_nn9"></a>27.2 Building Ruby Extensions under Windows 95/NT</H2> | |
400 | ||
401 | ||
402 | <p> | |
403 | Building a SWIG extension to Ruby under Windows 95/NT is roughly similar to the | |
404 | process used with Unix. Normally, you will want to produce a DLL that can be | |
405 | loaded into the Ruby interpreter. For all recent versions of Ruby, the | |
406 | procedure described above (i.e. using an <tt>extconf.rb</tt> script) will work | |
407 | with Windows as well; you should be able to build your code into a DLL by | |
408 | typing: | |
409 | </p> | |
410 | <div class="code"> | |
411 | <pre>C:\swigtest> <b>ruby extconf.rb</b><br>C:\swigtest> <b>nmake</b><br>C:\swigtest> <b>nmake install</b> | |
412 | </pre> | |
413 | </div> | |
414 | <p> | |
415 | The remainder of this section covers the process of compiling SWIG-generated | |
416 | Ruby extensions with Microsoft Visual C++ 6 (i.e. within the Developer Studio | |
417 | IDE, instead of using the command line tools). In order to build extensions, | |
418 | you may need to download the source distribution to the Ruby package, as you | |
419 | will need the Ruby header files. | |
420 | </p> | |
421 | <p><a name="n10"></a></p> | |
422 | <H3><a name="Ruby_nn10"></a>27.2.1 Running SWIG from Developer Studio</H3> | |
423 | ||
424 | ||
425 | <p> | |
426 | If you are developing your application within Microsoft developer studio, SWIG | |
427 | can be invoked as a custom build option. The process roughly follows these | |
428 | steps : | |
429 | </p> | |
430 | <ul> | |
431 | <li> | |
432 | Open up a new workspace and use the AppWizard to select a DLL project. | |
433 | </li> | |
434 | <li> | |
435 | Add both the SWIG interface file (the .i file), any supporting C files, and the | |
436 | name of the wrapper file that will be created by SWIG (i.e.. <tt>example_wrap.c</tt>). | |
437 | Note : If using C++, choose a different suffix for the wrapper file such as <tt>example_wrap.cxx</tt>. | |
438 | Don't worry if the wrapper file doesn't exist yet--Developer Studio will keep a | |
439 | reference to it around. | |
440 | </li> | |
441 | <li> | |
442 | Select the SWIG interface file and go to the settings menu. Under settings, | |
443 | select the "Custom Build" option. | |
444 | </li> | |
445 | <li> | |
446 | Enter "SWIG" in the description field. | |
447 | </li> | |
448 | <li> | |
449 | Enter "<tt>swig -ruby -o $(ProjDir)\$(InputName)_wrap.c $(InputPath)</tt>" in | |
450 | the "Build command(s) field". You may have to include the path to swig.exe. | |
451 | </li> | |
452 | <li> | |
453 | Enter "<tt>$(ProjDir)\$(InputName)_wrap.c</tt>" in the "Output files(s) field". | |
454 | </li> | |
455 | <li> | |
456 | Next, select the settings for the entire project and go to the C/C++ tab and | |
457 | select the Preprocessor category. Add NT=1 to the Preprocessor definitions. | |
458 | This must be set else you will get compilation errors. Also add IMPORT to the | |
459 | preprocessor definitions, else you may get runtime errors. Also add the include | |
460 | directories for your Ruby installation under "Additional include directories". | |
461 | </li> | |
462 | <li> | |
463 | Next, select the settings for the entire project and go to the Link tab and | |
464 | select the General category. Set the name of the output file to match the name | |
465 | of your Ruby module (i.e.. example.dll). Next add the Ruby library file to your | |
466 | link libraries under Object/Library modules. For example "mswin32-ruby16.lib. | |
467 | You also need to add the path to the library under the Input tab - Additional | |
468 | library path. | |
469 | </li> | |
470 | <li> | |
471 | Build your project. | |
472 | </li> | |
473 | </ul> | |
474 | <p> | |
475 | Now, assuming all went well, SWIG will be automatically invoked when you build | |
476 | your project. Any changes made to the interface file will result in SWIG being | |
477 | automatically invoked to produce a new version of the wrapper file. To run your | |
478 | new Ruby extension, simply run Ruby and use the <tt>require</tt> command as | |
479 | normal. For example if you have this ruby file run.rb:</p> | |
480 | <div class="code"> | |
481 | <pre># file: run.rb<br>require 'Example'<br><br># Call a c function<br>print "Foo = ", Example.Foo, "\n"<br></pre> | |
482 | </div> | |
483 | <p> | |
484 | Ensure the dll just built is in your path or current directory, then run the | |
485 | Ruby script from the DOS/Command prompt: | |
486 | </p> | |
487 | <div class="code"> | |
488 | <pre>C:\swigtest> <b>ruby run.rb</b><br>Foo = 3.0<br></pre> | |
489 | </div> | |
490 | <H2><a name="Ruby_nn11"></a>27.3 The Ruby-to-C/C++ Mapping</H2> | |
491 | ||
492 | ||
493 | <p> | |
494 | This section describes the basics of how SWIG maps C or C++ declarations in | |
495 | your SWIG interface files to Ruby constructs. | |
496 | </p> | |
497 | <H3><a name="Ruby_nn12"></a>27.3.1 Modules</H3> | |
498 | ||
499 | ||
500 | <p> | |
501 | The SWIG <tt>%module</tt> directive specifies the name of the Ruby module. If | |
502 | you specify: | |
503 | </p> | |
504 | <div class="code"> | |
505 | <pre>%module example</pre> | |
506 | </div> | |
507 | <p> | |
508 | then everything is wrapped into a Ruby module named <tt>Example</tt> that is | |
509 | nested directly under the global module. You can specify a more deeply nested | |
510 | module by specifying the fully-qualified module name in quotes, e.g. | |
511 | </p> | |
512 | <div class="code"> | |
513 | <pre>%module "foo::bar::spam"</pre> | |
514 | </div> | |
515 | <p> | |
516 | An alternate method of specifying a nested module name is to use the | |
517 | <span style="font-family: monospace;">-prefix</span> | |
518 | option on the SWIG command line. The prefix that you specify with this option | |
519 | will be prepended to the module name specified with the | |
520 | <span style="font-family: monospace;">%module</span> | |
521 | directive in your SWIG interface file. So for example, this declaration at the | |
522 | top of your SWIG interface file:<br> | |
523 | </p> | |
524 | <div class="code"> | |
525 | <pre>%module "foo::bar::spam"</pre> | |
526 | </div> | |
527 | <p> | |
528 | will result in a nested module name of | |
529 | <span style="font-family: monospace;">Foo::Bar::Spam</span>, but you can | |
530 | achieve the | |
531 | <span style="font-style: italic;">same</span> | |
532 | effect by specifying:<br> | |
533 | </p> | |
534 | <div class="code"> | |
535 | <pre>%module spam</pre> | |
536 | </div> | |
537 | <p> | |
538 | and then running SWIG with the | |
539 | <span style="font-family: monospace;">-prefix</span> | |
540 | command line option:<br> | |
541 | </p> | |
542 | <div class="code"> | |
543 | <pre>$ <b>swig -ruby -prefix "foo::bar::" example.i</b></pre> | |
544 | </div> | |
545 | <p> | |
546 | Starting with SWIG 1.3.20, you can also choose to wrap everything into the | |
547 | global module by specifying the <tt>-globalmodule</tt> option on the SWIG | |
548 | command line, i.e. | |
549 | </p> | |
550 | <div class="code"> | |
551 | <pre>$ <b>swig -ruby -globalmodule example.i</b></pre> | |
552 | </div> | |
553 | <p> | |
554 | Note that this does not relieve you of the requirement of specifying the SWIG | |
555 | module name with the <tt>%module</tt> directive (or the <tt>-module</tt> command-line | |
556 | option) as described earlier. | |
557 | </p> | |
558 | <p>When choosing a module name, do not use the same name as a built-in Ruby command | |
559 | or standard module name, as the results may be unpredictable. Similarly, if | |
560 | you're using the <tt>-globalmodule</tt> option to wrap everything into the | |
561 | global module, take care that the names of your constants, classes and methods | |
562 | don't conflict with any of Ruby's built-in names. | |
563 | </p> | |
564 | <H3><a name="Ruby_nn13"></a>27.3.2 Functions</H3> | |
565 | ||
566 | ||
567 | <p> | |
568 | Global functions are wrapped as Ruby module methods. For example, given the | |
569 | SWIG interface file <tt>example.i</tt>: | |
570 | </p> | |
571 | <div class="code"> | |
572 | <pre>%module example<br><br>int fact(int n);<br></pre> | |
573 | </div> | |
574 | <p> | |
575 | and C source file <tt>example.c</tt>: | |
576 | </p> | |
577 | <div class="code"> | |
578 | <pre>int fact(int n) {<br> if (n == 0)<br> return 1;<br> return (n * fact(n-1));<br>}<br></pre> | |
579 | </div> | |
580 | <p> | |
581 | SWIG will generate a method <i>fact</i> in the <i>Example</i> module that can | |
582 | be used like so: | |
583 | </p> | |
584 | <div class="code"> | |
585 | <pre>$ <b>irb</b><br>irb(main):001:0> <b>require 'example'</b><br>true<br>irb(main):002:0> <b>Example.fact(4)</b><br>24<br></pre> | |
586 | </div> | |
587 | <H3><a name="Ruby_nn14"></a>27.3.3 Variable Linking</H3> | |
588 | ||
589 | ||
590 | <p> | |
591 | C/C++ global variables are wrapped as a pair of singleton methods for the | |
592 | module: one to get the value of the global variable and one to set it. For | |
593 | example, the following SWIG interface file declares two global variables: | |
594 | </p> | |
595 | <div class="code"> | |
596 | <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> | |
597 | </div> | |
598 | <p> | |
599 | Now look at the Ruby interface:</p> | |
600 | <div class="code"> | |
601 | <pre>$ <b>irb</b><br>irb(main):001:0> <b>require 'Example'</b><br>true<br>irb(main):002:0> <b>Example.variable1 = 2</b><br>2<br>irb(main):003:0> <b>Example.Variable2 = 4 * 10.3</b><br>41.2<br>irb(main):004:0> <b>Example.Variable2</b><br>41.2<br></pre> | |
602 | </div> | |
603 | <p> | |
604 | If you make an error in variable assignment, you will receive an error message. | |
605 | For example: | |
606 | </p> | |
607 | <div class="code"> | |
608 | <pre>irb(main):005:0> <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> | |
609 | </div> | |
610 | <p> | |
611 | If a variable is declared as <tt>const</tt>, it is wrapped as a read-only | |
612 | variable. Attempts to modify its value will result in an error. | |
613 | </p> | |
614 | <p>To make ordinary variables read-only, you can also use the <tt>%immutable</tt> directive. | |
615 | For example: | |
616 | </p> | |
617 | <div class="code"> | |
618 | <pre>%immutable;<br>%inline %{<br>extern char *path;<br>%}<br>%mutable;<br></pre> | |
619 | </div> | |
620 | <p> | |
621 | The <tt>%immutable</tt> directive stays in effect until it is explicitly | |
622 | disabled using <tt>%mutable</tt>. | |
623 | </p> | |
624 | <H3><a name="Ruby_nn15"></a>27.3.4 Constants</H3> | |
625 | ||
626 | ||
627 | <p> | |
628 | C/C++ constants are wrapped as module constants initialized to the appropriate | |
629 | value. To create a constant, use <tt>#define</tt> or the <tt>%constant</tt> directive. | |
630 | For example: | |
631 | </p> | |
632 | <div class="code"> | |
633 | <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> | |
634 | </div> | |
635 | <p> | |
636 | Remember to use the :: operator in Ruby to get at these constant values, e.g. | |
637 | </p> | |
638 | <div class="code"> | |
639 | <pre>$ <b>irb</b><br>irb(main):001:0> <b>require 'Example'</b><br>true<br>irb(main):002:0> <b>Example::PI</b><br>3.14159<br></pre> | |
640 | </div> | |
641 | <H3><a name="Ruby_nn16"></a>27.3.5 Pointers</H3> | |
642 | ||
643 | ||
644 | <p> | |
645 | "Opaque" pointers to arbitrary C/C++ types (i.e. types that aren't explicitly | |
646 | declared in your SWIG interface file) are wrapped as data objects. So, for | |
647 | example, consider a SWIG interface file containing only the declarations: | |
648 | </p> | |
649 | <div class="code"> | |
650 | <pre>Foo *get_foo();<br>void set_foo(Foo *foo);<br></pre> | |
651 | </div> | |
652 | <p> | |
653 | For this case, the <i>get_foo()</i> method returns an instance of an internally | |
654 | generated Ruby class: | |
655 | </p> | |
656 | <div class="code"> | |
657 | <pre>irb(main):001:0> <b>foo = Example::get_foo()</b><br>#<SWIG::TYPE_p_Foo:0x402b1654><br></pre> | |
658 | </div> | |
659 | <p> | |
660 | A <tt>NULL</tt> pointer is always represented by the Ruby <tt>nil</tt> object. | |
661 | </p> | |
662 | <H3><a name="Ruby_nn17"></a>27.3.6 Structures</H3> | |
663 | ||
664 | ||
665 | <p> | |
666 | C/C++ structs are wrapped as Ruby classes, with accessor methods (i.e. | |
667 | "getters" and "setters") for all of the struct members. For example, this | |
668 | struct declaration: | |
669 | </p> | |
670 | <div class="code"> | |
671 | <pre>struct Vector {<br> double x, y;<br>};<br></pre> | |
672 | </div> | |
673 | <p> | |
674 | gets wrapped as a <tt>Vector</tt> class, with Ruby instance methods <tt>x</tt>, <tt> | |
675 | x=</tt>, <tt>y</tt> and <tt>y=</tt>. These methods can be used to access | |
676 | structure data from Ruby as follows: | |
677 | </p> | |
678 | <div class="code"> | |
679 | <pre>$ <b>irb</b><br>irb(main):001:0> <b>require 'Example'</b><br>true<br>irb(main):002:0> <b>f = Example::Vector.new</b><br>#<Example::Vector:0x4020b268><br>irb(main):003:0> <b>f.x = 10</b><br>nil<br>irb(main):004:0> <b>f.x</b><br>10.0<br></pre> | |
680 | </div> | |
681 | <p> | |
682 | Similar access is provided for unions and the public data members of C++ | |
683 | classes.</p> | |
684 | <p><tt>const</tt> members of a structure are read-only. Data members can also be | |
685 | forced to be read-only using the <tt>%immutable</tt> directive (in C++, <tt>private</tt> | |
686 | may also be used). For example: | |
687 | </p> | |
688 | <div class="code"> | |
689 | <pre>struct Foo {<br> ...<br> %immutable;<br> int x; /* Read-only members */<br> char *name;<br> %mutable;<br> ...<br>};<br></pre> | |
690 | </div> | |
691 | <p> | |
692 | When <tt>char *</tt> members of a structure are wrapped, the contents are | |
693 | assumed to be dynamically allocated using <tt>malloc</tt> or <tt>new</tt> (depending | |
694 | on whether or not SWIG is run with the <tt>-c++</tt> option). When the | |
695 | structure member is set, the old contents will be released and a new value | |
696 | created. If this is not the behavior you want, you will have to use a typemap | |
697 | (described shortly). | |
698 | </p> | |
699 | <p>Array members are normally wrapped as read-only. For example, this code: | |
700 | </p> | |
701 | <div class="code"> | |
702 | <pre>struct Foo {<br> int x[50];<br>};<br></pre> | |
703 | </div> | |
704 | <p> | |
705 | produces a single accessor function like this: | |
706 | </p> | |
707 | <div class="code"> | |
708 | <pre>int *Foo_x_get(Foo *self) {<br> return self->x;<br>};<br></pre> | |
709 | </div> | |
710 | <p> | |
711 | If you want to set an array member, you will need to supply a "memberin" | |
712 | typemap described in the <a href="#ruby_cpp_smart_pointers">section on typemaps</a>. | |
713 | As a special case, SWIG does generate code to set array members of type <tt>char</tt> | |
714 | (allowing you to store a Ruby string in the structure). | |
715 | </p> | |
716 | <p>When structure members are wrapped, they are handled as pointers. For example, | |
717 | </p> | |
718 | <div class="code"> | |
719 | <pre>struct Foo {<br> ...<br>};<br><br>struct Bar {<br> Foo f;<br>};<br></pre> | |
720 | </div> | |
721 | <p> | |
722 | generates accessor functions such as this: | |
723 | </p> | |
724 | <div class="code"> | |
725 | <pre>Foo *Bar_f_get(Bar *b) {<br> return &b->f;<br>}<br><br>void Bar_f_set(Bar *b, Foo *val) {<br> b->f = *val;<br>}<br></pre> | |
726 | </div> | |
727 | <H3><a name="Ruby_nn18"></a>27.3.7 C++ classes</H3> | |
728 | ||
729 | ||
730 | <p> | |
731 | Like structs, C++ classes are wrapped by creating a new Ruby class of the same | |
732 | name with accessor methods for the public class member data. Additionally, | |
733 | public member functions for the class are wrapped as Ruby instance methods, and | |
734 | public static member functions are wrapped as Ruby singleton methods. So, given | |
735 | the C++ class declaration: | |
736 | </p> | |
737 | <div class="code"> | |
738 | <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> | |
739 | </div> | |
740 | <p> | |
741 | SWIG would create a <tt>List</tt> class with: | |
742 | </p> | |
743 | <ul> | |
744 | <li> | |
745 | instance methods <i>search</i>, <i>insert</i>, <i>remove</i>, and <i>get</i>; | |
746 | </li> | |
747 | <li> | |
748 | instance methods <i>length</i> and <i>length=</i> (to get and set the value of | |
749 | the <i>length</i> data member); and, | |
750 | </li> | |
751 | <li> | |
752 | a <i>print</i> singleton method for the class. | |
753 | </li> | |
754 | </ul> | |
755 | <p> | |
756 | In Ruby, these functions are used as follows: | |
757 | </p> | |
758 | <div class="code"> | |
759 | <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> | |
760 | </div> | |
761 | <H3><a name="Ruby_nn19"></a>27.3.8 C++ Inheritance</H3> | |
762 | ||
763 | ||
764 | <p> | |
765 | The SWIG type-checker is fully aware of C++ inheritance. Therefore, if you have | |
766 | classes like this: | |
767 | </p> | |
768 | <div class="code"> | |
769 | <pre>class Parent {<br> ...<br>};<br><br>class Child : public Parent {<br> ...<br>};<br></pre> | |
770 | </div> | |
771 | <p> | |
772 | those classes are wrapped into a hierarchy of Ruby classes that reflect the | |
773 | same inheritance structure. All of the usual Ruby utility methods work | |
774 | normally: | |
775 | </p> | |
776 | <div class="code"> | |
777 | <pre>irb(main):001:0> <b>c = Child.new</b><br>#<Bar:0x4016efd4><br>irb(main):002:0> <b>c.instance_of? Child</b><br>true<br>irb(main):003:0> <b>b.instance_of? Parent</b><br>false<br>irb(main):004:0> <b>b.is_a? Child</b><br>true<br>irb(main):005:0> <b>b.is_a? Parent</b><br>true<br>irb(main):006:0> <b>Child < Parent</b><br>true<br>irb(main):007:0> <b>Child > Parent</b><br>false<br></pre> | |
778 | </div> | |
779 | <p> | |
780 | Furthermore, if you have a function like this: | |
781 | </p> | |
782 | <div class="code"> | |
783 | <pre>void spam(Parent *f);<br></pre> | |
784 | </div> | |
785 | <p> | |
786 | then the function <tt>spam()</tt> accepts <tt>Parent</tt>* or a pointer to any | |
787 | class derived from <tt>Parent</tt>. | |
788 | </p> | |
789 | <p>Until recently, the Ruby module for SWIG didn't support multiple inheritance, | |
790 | and this is still the default behavior. This doesn't mean that you can't wrap | |
791 | C++ classes which inherit from multiple base classes; it simply means that only | |
792 | the <b>first</b> base class listed in the class declaration is considered, and | |
793 | any additional base classes are ignored. As an example, consider a SWIG | |
794 | interface file with a declaration like this: | |
795 | </p> | |
796 | <div class="code"> | |
797 | <pre>class Derived : public Base1, public Base2<br>{<br> ...<br>};<br></pre> | |
798 | </div> | |
799 | <p> | |
800 | For this case, the resulting Ruby class (<tt>Derived</tt>) will only consider <tt>Base1</tt> | |
801 | as its superclass. It won't inherit any of <tt>Base2</tt>'s member functions or | |
802 | data and it won't recognize <tt>Base2</tt> as an "ancestor" of <tt>Derived</tt> | |
803 | (i.e. the <em>is_a?</em> relationship would fail). When SWIG processes this | |
804 | interface file, you'll see a warning message like: | |
805 | </p> | |
806 | <div class="code"> | |
807 | <pre>example.i:5: Warning(802): Warning for Derived: Base Base2 ignored.<br>Multiple inheritance is not supported in Ruby.<br></pre> | |
808 | </div> | |
809 | <p> | |
810 | Starting with SWIG 1.3.20, the Ruby module for SWIG provides limited support | |
811 | for multiple inheritance. Because the approach for dealing with multiple | |
812 | inheritance introduces some limitations, this is an optional feature that you | |
813 | can activate with the <tt>-minherit</tt> command-line option: | |
814 | </p> | |
815 | <div class="code"> | |
816 | <pre>$ <b>swig -c++ -ruby -minherit example.i</b></pre> | |
817 | </div> | |
818 | <p> | |
819 | Using our previous example, if your SWIG interface file contains a declaration | |
820 | like this: | |
821 | </p> | |
822 | <div class="code"> | |
823 | <pre>class Derived : public Base1, public Base2<br>{<br> ...<br>};<br></pre> | |
824 | </div> | |
825 | <p> | |
826 | and you run SWIG with the <tt>-minherit</tt> command-line option, then you will | |
827 | end up with a Ruby class <tt>Derived</tt> that appears to "inherit" the member | |
828 | data and functions from both <tt>Base1</tt> and <tt>Base2</tt>. What actually | |
829 | happens is that three different top-level classes are created, with Ruby's <tt>Object</tt> | |
830 | class as their superclass. Each of these classes defines a nested module named <tt>Impl</tt>, | |
831 | and it's in these nested <tt>Impl</tt> modules that the actual instance methods | |
832 | for the classes are defined, i.e. | |
833 | </p> | |
834 | <div class="code"> | |
835 | <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> | |
836 | </div> | |
837 | <p> | |
838 | Observe that after the nested <tt>Impl</tt> module for a class is defined, it | |
839 | is mixed-in to the class itself. Also observe that the <tt>Derived::Impl</tt> module | |
840 | first mixes-in its base classes' <tt>Impl</tt> modules, thus "inheriting" all | |
841 | of their behavior. | |
842 | </p> | |
843 | <p>The primary drawback is that, unlike the default mode of operation, neither <tt>Base1</tt> | |
844 | nor <tt>Base2</tt> is a true superclass of <tt>Derived</tt> anymore: | |
845 | </p> | |
846 | <div class="code"> | |
847 | <pre>obj = Derived.new<br>obj.is_a? Base1 # this will return false...<br>obj.is_a? Base2 # ... and so will this<br></pre> | |
848 | </div> | |
849 | <p> | |
850 | In most cases, this is not a serious problem since objects of type <tt>Derived</tt> | |
851 | will otherwise behave as though they inherit from both <tt>Base1</tt> and <tt>Base2</tt> | |
852 | (i.e. they exhibit <a href="http://c2.com/cgi/wiki?DuckTyping">"Duck Typing"</a>). | |
853 | </p> | |
854 | <H3><a name="Ruby_nn20"></a>27.3.9 C++ Overloaded Functions</H3> | |
855 | ||
856 | ||
857 | <p> | |
858 | C++ overloaded functions, methods, and constructors are mostly supported by | |
859 | SWIG. For example, if you have two functions like this: | |
860 | </p> | |
861 | <div class="code"> | |
862 | <pre>void foo(int);<br>void foo(char *c);<br></pre> | |
863 | </div> | |
864 | <p> | |
865 | You can use them in Ruby in a straightforward manner: | |
866 | </p> | |
867 | <div class="code"> | |
868 | <pre>irb(main):001:0> <b>foo(3)</b> # foo(int)<br>irb(main):002:0> <b>foo("Hello")</b> # foo(char *c)<br></pre> | |
869 | </div> | |
870 | <p>Similarly, if you have a class like this,</p> | |
871 | <div class="code"> | |
872 | <pre>class Foo {<br>public:<br> Foo();<br> Foo(const Foo &);<br> ...<br>};<br></pre> | |
873 | </div> | |
874 | <p>you can write Ruby code like this:</p> | |
875 | <div class="code"> | |
876 | <pre>irb(main):001:0> <b>f = Foo.new</b> # Create a Foo<br>irb(main):002:0> <b>g = Foo.new(f)</b> # Copy f<br></pre> | |
877 | </div> | |
878 | <p> | |
879 | Overloading support is not quite as flexible as in C++. Sometimes there are | |
880 | methods that SWIG can't disambiguate. For example: | |
881 | </p> | |
882 | <div class="code"> | |
883 | <pre>void spam(int);<br>void spam(short);<br></pre> | |
884 | </div> | |
885 | <p>or</p> | |
886 | <div class="code"> | |
887 | <pre>void foo(Bar *b);<br>void foo(Bar &b);<br></pre> | |
888 | </div> | |
889 | <p> | |
890 | If declarations such as these appear, you will get a warning message like this: | |
891 | </p> | |
892 | <div class="code"> | |
893 | <pre>example.i:12: Warning(509): Overloaded spam(short) is shadowed by spam(int)<br>at example.i:11.<br> </pre> | |
894 | </div> | |
895 | <p> | |
896 | To fix this, you either need to ignore or rename one of the methods. For | |
897 | example: | |
898 | </p> | |
899 | <div class="code"> | |
900 | <pre>%rename(spam_short) spam(short);<br>...<br>void spam(int); <br>void spam(short); // Accessed as spam_short<br></pre> | |
901 | </div> | |
902 | <p>or</p> | |
903 | <div class="code"> | |
904 | <pre>%ignore spam(short);<br>...<br>void spam(int); <br>void spam(short); // Ignored<br></pre> | |
905 | </div> | |
906 | <p> | |
907 | SWIG resolves overloaded functions and methods using a disambiguation scheme | |
908 | that ranks and sorts declarations according to a set of type-precedence rules. | |
909 | The order in which declarations appear in the input does not matter except in | |
910 | situations where ambiguity arises--in this case, the first declaration takes | |
911 | precedence. | |
912 | </p> | |
913 | <p>Please refer to the <a href="SWIGPlus.html#SWIGPlus">"SWIG and C++"</a> chapter | |
914 | for more information about overloading. <a name="n21"></a> | |
915 | </p> | |
916 | <H3><a name="Ruby_nn21"></a>27.3.10 C++ Operators</H3> | |
917 | ||
918 | ||
919 | <p> | |
920 | For the most part, overloaded operators are handled automatically by SWIG and | |
921 | do not require any special treatment on your part. So if your class declares an | |
922 | overloaded addition operator, e.g. | |
923 | </p> | |
924 | <div class="code"> | |
925 | <pre>class Complex {<br> ...<br> Complex operator+(Complex &);<br> ...<br>};<br></pre> | |
926 | </div> | |
927 | <p> | |
928 | the resulting Ruby class will also support the addition (+) method correctly. | |
929 | </p> | |
930 | <p>For cases where SWIG's built-in support is not sufficient, C++ operators can be | |
931 | wrapped using the <tt>%rename</tt> directive (available on SWIG 1.3.10 and | |
932 | later releases). All you need to do is give the operator the name of a valid | |
933 | Ruby identifier. For example: | |
934 | </p> | |
935 | <div class="code"> | |
936 | <pre>%rename(add_complex) operator+(Complex &, Complex &);<br>...<br>Complex operator+(Complex &, Complex &);<br></pre> | |
937 | </div> | |
938 | <p>Now, in Ruby, you can do this:</p> | |
939 | <div class="code"> | |
940 | <pre>a = Example::Complex.new(2, 3)<br>b = Example::Complex.new(4, -1)<br>c = Example.add_complex(a, b)<br></pre> | |
941 | </div> | |
942 | <p> | |
943 | More details about wrapping C++ operators into Ruby operators is discussed in | |
944 | the <a href="#ruby_operator_overloading">section on operator overloading</a>. | |
945 | </p> | |
946 | <H3><a name="Ruby_nn22"></a>27.3.11 C++ namespaces</H3> | |
947 | ||
948 | ||
949 | <p> | |
950 | SWIG is aware of C++ namespaces, but namespace names do not appear in the | |
951 | module nor do namespaces result in a module that is broken up into submodules | |
952 | or packages. For example, if you have a file like this, | |
953 | </p> | |
954 | <div class="code"> | |
955 | <pre>%module example<br><br>namespace foo {<br> int fact(int n);<br> struct Vector {<br> double x,y,z;<br> };<br>};<br></pre> | |
956 | </div> | |
957 | <p>it works in Ruby as follows:</p> | |
958 | <div class="code"> | |
959 | <pre>irb(main):001:0> <b>require 'example'</b><br>true<br>irb(main):002:0> <b>Example.fact(3)</b><br>6<br>irb(main):003:0> <b>v = Example::Vector.new</b><br>#<Example::Vector:0x4016f4d4><br>irb(main):004:0> <b>v.x = 3.4</b><br>3.4<br>irb(main):004:0> <b>v.y</b><br>0.0<br></pre> | |
960 | </div> | |
961 | <p> | |
962 | If your program has more than one namespace, name conflicts (if any) can be | |
963 | resolved using <tt>%rename</tt> For example: | |
964 | </p> | |
965 | <div class="code"> | |
966 | <pre>%rename(Bar_spam) Bar::spam;<br><br>namespace Foo {<br> int spam();<br>}<br><br>namespace Bar {<br> int spam();<br>}<br></pre> | |
967 | </div> | |
968 | <p> | |
969 | If you have more than one namespace and your want to keep their symbols | |
970 | separate, consider wrapping them as separate SWIG modules. For example, make | |
971 | the module name the same as the namespace and create extension modules for each | |
972 | namespace separately. If your program utilizes thousands of small deeply nested | |
973 | namespaces each with identical symbol names, well, then you get what you | |
974 | deserve. | |
975 | </p> | |
976 | <H3><a name="Ruby_nn23"></a>27.3.12 C++ templates</H3> | |
977 | ||
978 | ||
979 | <p> | |
980 | C++ templates don't present a huge problem for SWIG. However, in order to | |
981 | create wrappers, you have to tell SWIG to create wrappers for a particular | |
982 | template instantiation. To do this, you use the <tt>%template</tt> directive. | |
983 | For example: | |
984 | </p> | |
985 | <div class="code"> | |
986 | <pre>%module example<br><br>%{<br>#include "pair.h"<br>%}<br><br>template<class T1, class T2><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&, const T2&);<br> ~pair();<br>};<br><br>%template(Pairii) pair<int,int>;<br></pre> | |
987 | </div> | |
988 | <p>In Ruby:</p> | |
989 | <div class="code"> | |
990 | <pre>irb(main):001:0> <b>require 'example'</b><br>true<br>irb(main):002:0> <b>p = Example::Pairii.new(3, 4)</b><br>#<Example:Pairii:0x4016f4df><br>irb(main):003:0> <b>p.first</b><br>3<br>irb(main):004:0> <b>p.second</b><br>4<br></pre> | |
991 | </div> | |
992 | <p> | |
993 | On a related note, the standard SWIG library contains a number of modules that | |
994 | provide typemaps for standard C++ library classes (such as <tt>std::pair</tt>, <tt>std::string</tt> | |
995 | and <tt>std::vector</tt>). These library modules don't provide wrappers around | |
996 | the templates themselves, but they do make it convenient for users of your | |
997 | extension module to pass Ruby objects (such as arrays and strings) to wrapped | |
998 | C++ code that expects instances of standard C++ templates. For example, suppose | |
999 | the C++ library you're wrapping has a function that expects a vector of floats: | |
1000 | </p> | |
1001 | <div class="code"> | |
1002 | <pre>%module example<br><br>float sum(const std::vector<float>& values);<br></pre> | |
1003 | </div> | |
1004 | <p> | |
1005 | Rather than go through the hassle of writing an "in" typemap to convert an | |
1006 | array of Ruby numbers into a std::vector<float>, you can just use the <tt>std_vector.i</tt> | |
1007 | module from the standard SWIG library: | |
1008 | </p> | |
1009 | <div class="code"> | |
1010 | <pre>%module example<br><br><b>%include std_vector.i</b><br>float sum(const std::vector<float>& values);<br></pre> | |
1011 | </div> | |
1012 | <p> | |
1013 | Obviously, there is a lot more to template wrapping than shown in these | |
1014 | examples. More details can be found in the <a href="SWIGPlus.html#SWIGPlus">SWIG | |
1015 | and C++</a> chapter. | |
1016 | </p> | |
1017 | <H3><a name="ruby_cpp_smart_pointers"></a>27.3.13 C++ Smart Pointers</H3> | |
1018 | ||
1019 | ||
1020 | <p> | |
1021 | In certain C++ programs, it is common to use classes that have been wrapped by | |
1022 | so-called "smart pointers." Generally, this involves the use of a template | |
1023 | class that implements <tt>operator->()</tt> like this: | |
1024 | </p> | |
1025 | <div class="code"> | |
1026 | <pre>template<class T> class SmartPtr {<br> ...<br> T *operator->();<br> ...<br>}<br></pre> | |
1027 | </div> | |
1028 | <p>Then, if you have a class like this,</p> | |
1029 | <div class="code"> | |
1030 | <pre>class Foo {<br>public:<br> int x;<br> int bar();<br>};<br></pre> | |
1031 | </div> | |
1032 | <p>A smart pointer would be used in C++ as follows:</p> | |
1033 | <div class="code"> | |
1034 | <pre>SmartPtr<Foo> p = CreateFoo(); // Created somehow (not shown)<br>...<br>p->x = 3; // Foo::x<br>int y = p->bar(); // Foo::bar<br></pre> | |
1035 | </div> | |
1036 | <p> | |
1037 | To wrap this in Ruby, simply tell SWIG about the <tt>SmartPtr</tt> class and | |
1038 | the low-level <tt>Foo</tt> object. Make sure you instantiate <tt>SmartPtr</tt> using | |
1039 | <tt>%template</tt> if necessary. For example: | |
1040 | </p> | |
1041 | <div class="code"> | |
1042 | <pre>%module example<br>...<br>%template(SmartPtrFoo) SmartPtr<Foo>;<br>...<br></pre> | |
1043 | </div> | |
1044 | <p>Now, in Ruby, everything should just "work":</p> | |
1045 | <div class="code"> | |
1046 | <pre>irb(main):001:0> <b>p = Example::CreateFoo()</b> # Create a smart-pointer somehow<br>#<Example::SmartPtrFoo:0x4016f4df><br>irb(main):002:0> <b>p.x = 3</b> # Foo::x<br>3<br>irb(main):003:0> <b>p.bar()</b> # Foo::bar<br></pre> | |
1047 | </div> | |
1048 | <p> | |
1049 | If you ever need to access the underlying pointer returned by <tt>operator->()</tt> | |
1050 | itself, simply use the <tt>__deref__()</tt> method. For example: | |
1051 | </p> | |
1052 | <div class="code"> | |
1053 | <pre>irb(main):004:0> <b>f = p.__deref__()</b> # Returns underlying Foo *<br></pre> | |
1054 | </div> | |
1055 | <H3><a name="Ruby_nn25"></a>27.3.14 Cross-Language Polymorphism</H3> | |
1056 | ||
1057 | ||
1058 | <p> | |
1059 | SWIG's Ruby module supports cross-language polymorphism (a.k.a. the "directors" | |
1060 | feature) similar to that for SWIG's Python module. Rather than duplicate the | |
1061 | information presented in the <a href="Python.html#Python">Python</a> chapter, | |
1062 | this section just notes the differences that you need to be aware of when using | |
1063 | this feature with Ruby. | |
1064 | </p> | |
1065 | <H4><a name="Ruby_nn26"></a>27.3.14.1 Exception Unrolling</H4> | |
1066 | ||
1067 | ||
1068 | <p> | |
1069 | Whenever a C++ director class routes one of its virtual member function calls | |
1070 | to a Ruby instance method, there's always the possibility that an exception | |
1071 | will be raised in the Ruby code. By default, those exceptions are ignored, | |
1072 | which simply means that the exception will be exposed to the Ruby interpreter. | |
1073 | If you would like to change this behavior, you can use the <tt>%feature("director:except")</tt> | |
1074 | directive to indicate what action should be taken when a Ruby exception is | |
1075 | raised. The following code should suffice in most cases: | |
1076 | </p> | |
1077 | <div class="code"> | |
1078 | <pre>%feature("director:except") {<br> throw Swig::DirectorMethodException($error);<br>}<br></pre> | |
1079 | </div> | |
1080 | <p> | |
1081 | When this feature is activated, the call to the Ruby instance method is | |
1082 | "wrapped" using the <tt>rb_rescue2()</tt> function from Ruby's C API. If any | |
1083 | Ruby exception is raised, it will be caught here and a C++ exception is raised | |
1084 | in its place. | |
1085 | </p> | |
1086 | <H2><a name="Ruby_nn27"></a>27.4 Input and output parameters</H2> | |
1087 | ||
1088 | ||
1089 | <p> | |
1090 | A common problem in some C programs is handling parameters passed as simple | |
1091 | pointers. For example: | |
1092 | </p> | |
1093 | <div class="code"> | |
1094 | <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> | |
1095 | </div> | |
1096 | <p> | |
1097 | The easiest way to handle these situations is to use the <tt>typemaps.i</tt> file. | |
1098 | For example: | |
1099 | </p> | |
1100 | <div class="code"> | |
1101 | <pre>%module Example<br>%include "typemaps.i"<br><br>void add(int, int, int *OUTPUT);<br>int sub(int *INPUT, int *INPUT);<br></pre> | |
1102 | </div> | |
1103 | <p>In Ruby, this allows you to pass simple values. For example:</p> | |
1104 | <div class="code"> | |
1105 | <pre>a = Example.add(3,4)<br>puts a<br>7<br>b = Example.sub(7,4)<br>puts b<br>3<br></pre> | |
1106 | </div> | |
1107 | <p> | |
1108 | Notice how the <tt>INPUT</tt> parameters allow integer values to be passed | |
1109 | instead of pointers and how the <tt>OUTPUT</tt> parameter creates a return | |
1110 | result. | |
1111 | </p> | |
1112 | <p>If you don't want to use the names <tt>INPUT</tt> or <tt>OUTPUT</tt>, use the <tt>%apply</tt> | |
1113 | directive. For example: | |
1114 | </p> | |
1115 | <div class="code"> | |
1116 | <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> | |
1117 | </div> | |
1118 | <p> | |
1119 | If a function mutates one of its parameters like this, | |
1120 | </p> | |
1121 | <div class="code"> | |
1122 | <pre>void negate(int *x) {<br> *x = -(*x);<br>}<br></pre> | |
1123 | </div> | |
1124 | <p>you can use <tt>INOUT</tt> like this:</p> | |
1125 | <div class="code"> | |
1126 | <pre>%include "typemaps.i"<br>...<br>void negate(int *INOUT);<br></pre> | |
1127 | </div> | |
1128 | <p>In Ruby, a mutated parameter shows up as a return value. For example:</p> | |
1129 | <div class="code"> | |
1130 | <pre>a = Example.negate(3)<br>print a<br>-3<br><br></pre> | |
1131 | </div> | |
1132 | <p> | |
1133 | The most common use of these special typemap rules is to handle functions that | |
1134 | return more than one value. For example, sometimes a function returns a result | |
1135 | as well as a special error code: | |
1136 | </p> | |
1137 | <div class="code"> | |
1138 | <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> | |
1139 | </div> | |
1140 | <p> | |
1141 | To wrap such a function, simply use the <tt>OUTPUT</tt> rule above. For | |
1142 | example: | |
1143 | </p> | |
1144 | <div class="code"> | |
1145 | <pre>%module example<br>%include "typemaps.i"<br>...<br>int send_message(char *, int *OUTPUT, int *OUTPUT);<br></pre> | |
1146 | </div> | |
1147 | <p> | |
1148 | When used in Ruby, the function will return an array of multiple values. | |
1149 | </p> | |
1150 | <div class="code"> | |
1151 | <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> | |
1152 | </div> | |
1153 | <p> | |
1154 | Another way to access multiple return values is to use the <tt>%apply</tt> rule. | |
1155 | In the following example, the parameters rows and columns are related to SWIG | |
1156 | as <tt>OUTPUT</tt> values through the use of <tt>%apply</tt> | |
1157 | </p> | |
1158 | <div class="code"> | |
1159 | <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> | |
1160 | </div> | |
1161 | <p>In Ruby:</p> | |
1162 | <div class="code"> | |
1163 | <pre>r, c = Example.get_dimensions(m)<br></pre> | |
1164 | </div> | |
1165 | <H2><a name="Ruby_nn28"></a>27.5 Simple exception handling | |
1166 | </H2> | |
1167 | <p> | |
1168 | The SWIG <tt>%exception</tt> directive can be used to define a user-definable | |
1169 | exception handler that can convert C/C++ errors into Ruby exceptions. The | |
1170 | chapter on <a href="Customization.html#Customization">Customization Features</a> | |
1171 | contains more details, but suppose you have a C++ class like the following : | |
1172 | </p> | |
1173 | <div class="code"> | |
1174 | <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> // Destroy an array<br> ~DoubleArray() {<br> delete ptr;<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 >= 0) && (i < n))<br> return ptr[i];<br> else<br> throw RangeError();<br> }<br> // Set an array item and perform bounds checking.<br> void setitem(int i, double val) {<br> if ((i >= 0) && (i < n))<br> ptr[i] = val;<br> else {<br> throw RangeError();<br> }<br> }<br> };<br></pre> | |
1175 | </div> | |
1176 | <p> | |
1177 | Since several methods in this class can throw an exception for an out-of-bounds | |
1178 | access, you might want to catch this in the Ruby extension by writing the | |
1179 | following in an interface file: | |
1180 | </p> | |
1181 | <div class="code"> | |
1182 | <pre>%exception {<br> try {<br> $action<br> }<br> catch (const RangeError&) {<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> | |
1183 | </div> | |
1184 | <p> | |
1185 | The exception handling code is inserted directly into generated wrapper | |
1186 | functions. When an exception handler is defined, errors can be caught and used | |
1187 | to gracefully raise a Ruby exception instead of forcing the entire program to | |
1188 | terminate with an uncaught error. | |
1189 | </p> | |
1190 | <p>As shown, the exception handling code will be added to every wrapper function. | |
1191 | Because this is somewhat inefficient, you might consider refining the exception | |
1192 | handler to only apply to specific methods like this: | |
1193 | </p> | |
1194 | <div class="code"> | |
1195 | <pre>%exception getitem {<br> try {<br> $action<br> }<br> catch (const RangeError&) {<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&) {<br> static VALUE cpperror = rb_define_class("CPPError", rb_eStandardError);<br> rb_raise(cpperror, "Range error in setitem.");<br> }<br>}<br></pre> | |
1196 | </div> | |
1197 | <p> | |
1198 | In this case, the exception handler is only attached to methods and functions | |
1199 | named <tt>getitem</tt> and <tt>setitem</tt>. | |
1200 | </p> | |
1201 | <p>Since SWIG's exception handling is user-definable, you are not limited to C++ | |
1202 | exception handling. See the chapter on <a href="Customization.html#Customization">Customization | |
1203 | Features</a> for more examples. | |
1204 | </p> | |
1205 | <p>When raising a Ruby exception from C/C++, use the <tt>rb_raise()</tt> function | |
1206 | as shown above. The first argument passed to <tt>rb_raise()</tt> is the | |
1207 | exception type. You can raise a custom exception type (like the <tt>cpperror</tt> | |
1208 | example shown above) or one of the built-in Ruby exception types. For a list of | |
1209 | the standard Ruby exception classes, consult a Ruby reference such as <a href="http://www.rubycentral.com/book"> | |
1210 | <em>Programming Ruby</em></a>. | |
1211 | </p> | |
1212 | <H2><a name="Ruby_nn29"></a>27.5 Typemaps</H2> | |
1213 | ||
1214 | ||
1215 | <p> | |
1216 | This section describes how you can modify SWIG's default wrapping behavior for | |
1217 | various C/C++ datatypes using the <tt>%typemap</tt> directive. This is an | |
1218 | advanced topic that assumes familiarity with the Ruby C API as well as the | |
1219 | material in the "<a href="Typemaps.html#Typemaps">Typemaps</a>" chapter. | |
1220 | </p> | |
1221 | <p>Before proceeding, it should be stressed that typemaps are not a required part | |
1222 | of using SWIG---the default wrapping behavior is enough in most cases. Typemaps | |
1223 | are only used if you want to change some aspect of the primitive C-Ruby | |
1224 | interface.</p> | |
1225 | <H3><a name="Ruby_nn30"></a>27.5.1 What is a typemap?</H3> | |
1226 | ||
1227 | ||
1228 | <p> | |
1229 | A typemap is nothing more than a code generation rule that is attached to a | |
1230 | specific C datatype. For example, to convert integers from Ruby to C, you might | |
1231 | define a typemap like this: | |
1232 | </p> | |
1233 | <div class="code"> | |
1234 | <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> | |
1235 | </div> | |
1236 | <p> | |
1237 | Typemaps are always associated with some specific aspect of code generation. In | |
1238 | this case, the "in" method refers to the conversion of input arguments to | |
1239 | C/C++. The datatype <tt>int</tt> is the datatype to which the typemap will be | |
1240 | applied. The supplied C code is used to convert values. In this code a number | |
1241 | of special variables prefaced by a <tt>$</tt> are used. The <tt>$1</tt> variable | |
1242 | is placeholder for a local variable of type <tt>int</tt>. The <tt>$input</tt> variable | |
1243 | is the input Ruby object. | |
1244 | </p> | |
1245 | <p>When this example is compiled into a Ruby module, the following sample code: | |
1246 | </p> | |
1247 | <div class="code"> | |
1248 | <pre>require 'example'<br><br>puts Example.fact(6)<br></pre> | |
1249 | </div> | |
1250 | <p>prints the result:</p> | |
1251 | <div class="code"> | |
1252 | <pre>Received an integer : 6<br>720<br></pre> | |
1253 | </div> | |
1254 | <p> | |
1255 | In this example, the typemap is applied to all occurrences of the <tt>int</tt> datatype. | |
1256 | You can refine this by supplying an optional parameter name. For example: | |
1257 | </p> | |
1258 | <div class="code"> | |
1259 | <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> | |
1260 | </div> | |
1261 | <p> | |
1262 | In this case, the typemap code is only attached to arguments that exactly match | |
1263 | "<tt>int n</tt>". | |
1264 | </p> | |
1265 | <p>The application of a typemap to specific datatypes and argument names involves | |
1266 | more than simple text-matching--typemaps are fully integrated into the SWIG | |
1267 | type-system. When you define a typemap for <tt>int</tt>, that typemap applies | |
1268 | to <tt>int</tt> and qualified variations such as <tt>const int</tt>. In | |
1269 | addition, the typemap system follows <tt>typedef</tt> declarations. For | |
1270 | example: | |
1271 | </p> | |
1272 | <div class="code"> | |
1273 | <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> | |
1274 | </div> | |
1275 | <p> | |
1276 | However, the matching of <tt>typedef</tt> only occurs in one direction. If you | |
1277 | defined a typemap for <tt>Integer</tt>, it is not applied to arguments of type <tt>int</tt>. | |
1278 | </p> | |
1279 | <p>Typemaps can also be defined for groups of consecutive arguments. For example: | |
1280 | </p> | |
1281 | <div class="code"> | |
1282 | <pre>%typemap(in) (char *str, int len) {<br> $1 = STR2CSTR($input);<br> $2 = (int) RSTRING($input)->len;<br>};<br><br>int count(char c, char *str, int len);<br></pre> | |
1283 | </div> | |
1284 | <p> | |
1285 | When a multi-argument typemap is defined, the arguments are always handled as a | |
1286 | single Ruby object. This allows the function <tt>count</tt> to be used as | |
1287 | follows (notice how the length parameter is omitted): | |
1288 | </p> | |
1289 | <div class="code"> | |
1290 | <pre>puts Example.count('o','Hello World')<br>2<br></pre> | |
1291 | </div> | |
1292 | <H3><a name="Ruby_nn31"></a>27.5.2 Ruby typemaps</H3> | |
1293 | ||
1294 | ||
1295 | <p> | |
1296 | The previous section illustrated an "in" typemap for converting Ruby objects to | |
1297 | C. A variety of different typemap methods are defined by the Ruby module. For | |
1298 | example, to convert a C integer back into a Ruby object, you might define an | |
1299 | "out" typemap like this: | |
1300 | </p> | |
1301 | <div class="code"> | |
1302 | <pre>%typemap(out) int {<br> $result = INT2NUM($1);<br>}<br></pre> | |
1303 | </div> | |
1304 | <p> | |
1305 | The following list details all of the typemap methods that can be used by the | |
1306 | Ruby module: | |
1307 | </p> | |
1308 | <p><tt>%typemap(in) </tt> | |
1309 | </p> | |
1310 | <div class="indent">Converts Ruby objects to input function arguments | |
1311 | </div> | |
1312 | <p><tt>%typemap(out)</tt></p> | |
1313 | <div class="indent">Converts return value of a C function to a Ruby object | |
1314 | </div> | |
1315 | <p><tt>%typemap(varin)</tt></p> | |
1316 | <div class="indent">Assigns a C global variable from a Ruby object | |
1317 | </div> | |
1318 | <p><tt>%typemap(varout)</tt></p> | |
1319 | <div class="indent">Returns a C global variable as a Ruby object | |
1320 | </div> | |
1321 | <p><tt>%typemap(freearg)</tt></p> | |
1322 | <div class="indent">Cleans up a function argument (if necessary) | |
1323 | </div> | |
1324 | <p><tt>%typemap(argout)</tt></p> | |
1325 | <div class="indent">Output argument processing | |
1326 | </div> | |
1327 | <p><tt>%typemap(ret)</tt></p> | |
1328 | <div class="indent">Cleanup of function return values | |
1329 | </div> | |
1330 | <p><tt>%typemap(memberin)</tt></p> | |
1331 | <div class="indent">Setting of structure/class member data | |
1332 | </div> | |
1333 | <p><tt>%typemap(globalin)</tt></p> | |
1334 | <div class="indent">Setting of C global variables | |
1335 | </div> | |
1336 | <p><tt>%typemap(check)</tt></p> | |
1337 | <div class="indent">Checks function input values. | |
1338 | </div> | |
1339 | <p><tt>%typemap(default)</tt></p> | |
1340 | <div class="indent">Set a default value for an argument (making it optional). | |
1341 | </div> | |
1342 | <p><tt>%typemap(arginit)</tt></p> | |
1343 | <div class="indent">Initialize an argument to a value before any conversions occur. | |
1344 | </div> | |
1345 | <p> | |
1346 | Examples of these typemaps appears in the <a href="#ruby_typemap_examples">section | |
1347 | on typemap examples</a> | |
1348 | </p> | |
1349 | <H3><a name="Ruby_nn32"></a>27.5.3 Typemap variables</H3> | |
1350 | ||
1351 | ||
1352 | Within a typemap, a number of special variables prefaced with a <tt>$</tt> may | |
1353 | appear. A full list of variables can be found in the "<a href="Typemaps.html#Typemaps">Typemaps</a>" | |
1354 | chapter. This is a list of the most common variables: | |
1355 | <p><tt>$1</tt> | |
1356 | </p> | |
1357 | <div class="indent">A C local variable corresponding to the actual type specified | |
1358 | in the <tt>%typemap</tt> directive. For input values, this is a C local | |
1359 | variable that is supposed to hold an argument value. For output values, this is | |
1360 | the raw result that is supposed to be returned to Ruby. | |
1361 | </div> | |
1362 | <p><tt>$input</tt></p> | |
1363 | <div class="indent">A <tt>VALUE</tt> holding a raw Ruby object with an argument or | |
1364 | variable value. | |
1365 | </div> | |
1366 | <p><tt>$result</tt></p> | |
1367 | <div class="indent">A <tt>VALUE</tt> that holds the result to be returned to Ruby. | |
1368 | </div> | |
1369 | <p><tt>$1_name</tt></p> | |
1370 | <div class="indent">The parameter name that was matched. | |
1371 | </div> | |
1372 | <p><tt>$1_type</tt></p> | |
1373 | <div class="indent">The actual C datatype matched by the typemap. | |
1374 | </div> | |
1375 | <p><tt>$1_ltype</tt></p> | |
1376 | <div class="indent">An assignable version of the datatype matched by the typemap (a | |
1377 | type that can appear on the left-hand-side of a C assignment operation). This | |
1378 | type is stripped of qualifiers and may be an altered version of <tt>$1_type</tt>. | |
1379 | All arguments and local variables in wrapper functions are declared using this | |
1380 | type so that their values can be properly assigned. | |
1381 | </div> | |
1382 | <p><tt>$symname</tt></p> | |
1383 | <div class="indent">The Ruby name of the wrapper function being created. | |
1384 | </div> | |
1385 | <H3><a name="Ruby_nn33"></a>27.5.4 Useful Functions</H3> | |
1386 | ||
1387 | ||
1388 | <p> | |
1389 | When you write a typemap, you usually have to work directly with Ruby objects. | |
1390 | The following functions may prove to be useful. (These functions plus many more | |
1391 | can be found in <a href="http://www.rubycentral.com/book"><em>Programming Ruby</em></a>, | |
1392 | by David Thomas and Andrew Hunt.) | |
1393 | </p> | |
1394 | <p><a name="n34"></a></p> | |
1395 | <H4><a name="Ruby_nn34"></a>27.5.4.1 C Datatypes to Ruby Objects</H4> | |
1396 | ||
1397 | ||
1398 | <div class="code"> | |
1399 | <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> | |
1400 | </div> | |
1401 | <H4><a name="Ruby_nn35"></a>27.5.4.2 Ruby Objects to C Datatypes</H4> | |
1402 | ||
1403 | ||
1404 | <div class="code"> | |
1405 | <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> | |
1406 | </div> | |
1407 | <H4><a name="Ruby_nn36"></a>27.5.4.3 Macros for VALUE</H4> | |
1408 | ||
1409 | ||
1410 | <p> | |
1411 | <tt>RSTRING(str)->len</tt> | |
1412 | </p> | |
1413 | <div class="indent">length of the Ruby string</div> | |
1414 | <p><tt>RSTRING(str)->ptr</tt></p> | |
1415 | <div class="indent">pointer to string storage</div> | |
1416 | <p><tt>RARRAY(arr)->len</tt></p> | |
1417 | <div class="indent">length of the Ruby array</div> | |
1418 | <p><tt>RARRAY(arr)->capa</tt></p> | |
1419 | <div class="indent">capacity of the Ruby array</div> | |
1420 | <p><tt>RARRAY(arr)->ptr</tt></p> | |
1421 | <div class="indent">pointer to array storage</div> | |
1422 | <H4><a name="Ruby_nn37"></a>27.5.4.4 Exceptions</H4> | |
1423 | ||
1424 | ||
1425 | <p> | |
1426 | <tt>void rb_raise(VALUE exception, const char *fmt, ...)</tt> | |
1427 | </p> | |
1428 | <div class="indent"> | |
1429 | Raises an exception. The given format string <i>fmt</i> and remaining arguments | |
1430 | are interpreted as with <tt>printf()</tt>. | |
1431 | </div> | |
1432 | <p><tt>void rb_fatal(const char *fmt, ...)</tt></p> | |
1433 | <div class="indent"> | |
1434 | Raises a fatal exception, terminating the process. No rescue blocks are called, | |
1435 | but ensure blocks will be called. The given format string <i>fmt</i> and | |
1436 | remaining arguments are interpreted as with <tt>printf()</tt>. | |
1437 | </div> | |
1438 | <p><tt>void rb_bug(const char *fmt, ...)</tt></p> | |
1439 | <div class="indent"> | |
1440 | Terminates the process immediately -- no handlers of any sort will be called. | |
1441 | The given format string <i>fmt</i> and remaining arguments are interpreted as | |
1442 | with <tt>printf()</tt>. You should call this function only if a fatal bug has | |
1443 | been exposed. | |
1444 | </div> | |
1445 | <p><tt>void rb_sys_fail(const char *msg)</tt></p> | |
1446 | <div class="indent"> | |
1447 | Raises a platform-specific exception corresponding to the last known system | |
1448 | error, with the given string <i>msg</i>. | |
1449 | </div> | |
1450 | <p><tt>VALUE rb_rescue(VALUE (*body)(VALUE), VALUE args, VALUE(*rescue)(VALUE, VALUE), | |
1451 | VALUE rargs)</tt></p> | |
1452 | <div class="indent"> | |
1453 | Executes <i>body</i> with the given <i>args</i>. If a <tt>StandardError</tt> exception | |
1454 | is raised, then execute <i>rescue</i> with the given <i>rargs</i>. | |
1455 | </div> | |
1456 | <p><tt>VALUE rb_ensure(VALUE(*body)(VALUE), VALUE args, VALUE(*ensure)(VALUE), VALUE | |
1457 | eargs)</tt></p> | |
1458 | <div class="indent"> | |
1459 | Executes <i>body</i> with the given <i>args</i>. Whether or not an exception is | |
1460 | raised, execute <i>ensure</i> with the given <i>rargs</i> after <i>body</i> has | |
1461 | completed. | |
1462 | </div> | |
1463 | <p><tt>VALUE rb_protect(VALUE (*body)(VALUE), VALUE args, int *result)</tt></p> | |
1464 | <div class="indent"> | |
1465 | Executes <i>body</i> with the given <i>args</i> and returns nonzero in result | |
1466 | if any exception was raised. | |
1467 | </div> | |
1468 | <p><tt>void rb_notimplement()</tt></p> | |
1469 | <div class="indent"> | |
1470 | Raises a <tt>NotImpError</tt> exception to indicate that the enclosed function | |
1471 | is not implemented yet, or not available on this platform. | |
1472 | </div> | |
1473 | <p><tt>void rb_exit(int status)</tt></p> | |
1474 | <div class="indent"> | |
1475 | Exits Ruby with the given <i>status</i>. Raises a <tt>SystemExit</tt> exception | |
1476 | and calls registered exit functions and finalizers. | |
1477 | </div> | |
1478 | <p><tt>void rb_warn(const char *fmt, ...)</tt></p> | |
1479 | <div class="indent"> | |
1480 | Unconditionally issues a warning message to standard error. The given format | |
1481 | string <i>fmt</i> and remaining arguments are interpreted as with <tt>printf()</tt>. | |
1482 | </div> | |
1483 | <p><tt>void rb_warning(const char *fmt, ...)</tt></p> | |
1484 | <div class="indent"> | |
1485 | Conditionally issues a warning message to standard error if Ruby was invoked | |
1486 | with the <tt>-w</tt> flag. The given format string <i>fmt</i> and remaining | |
1487 | arguments are interpreted as with <tt>printf()</tt>. | |
1488 | </div> | |
1489 | <H4><a name="Ruby_nn38"></a>27.5.4.5 Iterators</H4> | |
1490 | ||
1491 | ||
1492 | <p> | |
1493 | <tt>void rb_iter_break()</tt> | |
1494 | </p> | |
1495 | <div class="indent"> | |
1496 | Breaks out of the enclosing iterator block. | |
1497 | </div> | |
1498 | <p><tt>VALUE rb_each(VALUE obj)</tt></p> | |
1499 | <div class="indent"> | |
1500 | Invokes the <tt>each</tt> method of the given <i>obj</i>. | |
1501 | </div> | |
1502 | <p><tt>VALUE rb_yield(VALUE arg)</tt></p> | |
1503 | <div class="indent"> | |
1504 | Transfers execution to the iterator block in the current context, passing <i>arg</i> | |
1505 | as an argument. Multiple values may be passed in an array. | |
1506 | </div> | |
1507 | <p><tt>int rb_block_given_p()</tt></p> | |
1508 | <div class="indent"> | |
1509 | Returns <tt>true</tt> if <tt>yield</tt> would execute a block in the current | |
1510 | context; that is, if a code block was passed to the current method and is | |
1511 | available to be called. | |
1512 | </div> | |
1513 | <p><tt>VALUE rb_iterate(VALUE (*method)(VALUE), VALUE args, VALUE (*block)(VALUE, | |
1514 | VALUE), VALUE arg2)</tt></p> | |
1515 | <div class="indent"> | |
1516 | Invokes <i>method</i> with argument <i>args</i> and block <i>block</i>. A <tt>yield</tt> | |
1517 | from that method will invoke <i>block</i> with the argument given to <tt>yield</tt>, | |
1518 | and a second argument <i>arg2</i>. | |
1519 | </div> | |
1520 | <p><tt>VALUE rb_catch(const char *tag, VALUE (*proc)(VALUE, VALUE), VALUE value)</tt></p> | |
1521 | <div class="indent"> | |
1522 | Equivalent to Ruby's <tt>catch</tt>. | |
1523 | </div> | |
1524 | <p><tt>void rb_throw(const char *tag, VALUE value)</tt></p> | |
1525 | <div class="indent"> | |
1526 | Equivalent to Ruby's <tt>throw</tt>. | |
1527 | </div> | |
1528 | <H3><a name="ruby_typemap_examples"></a>27.5.5 Typemap Examples</H3> | |
1529 | ||
1530 | ||
1531 | <p> | |
1532 | This section includes a few examples of typemaps. For more examples, you might | |
1533 | look at the examples in the <tt>Example/ruby</tt> directory. | |
1534 | </p> | |
1535 | <H3><a name="Ruby_nn40"></a>27.5.6 Converting a Ruby array to a char **</H3> | |
1536 | ||
1537 | ||
1538 | <p> | |
1539 | A common problem in many C programs is the processing of command line | |
1540 | arguments, which are usually passed in an array of <tt>NULL</tt> terminated | |
1541 | strings. The following SWIG interface file allows a Ruby Array instance to be | |
1542 | used as a <tt>char **</tt> object. | |
1543 | </p> | |
1544 | <div class="code"> | |
1545 | <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)->len; <br> int i;<br> $1 = (char **) malloc((size+1)*sizeof(char *));<br> /* Get the first element in memory */<br> VALUE *ptr = RARRAY($input)->ptr; <br> for (i=0; i < 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> | |
1546 | </div> | |
1547 | <p> | |
1548 | When this module is compiled, the wrapped C function now operates as follows : | |
1549 | </p> | |
1550 | <div class="code"> | |
1551 | <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> | |
1552 | </div> | |
1553 | <p> | |
1554 | In the example, two different typemaps are used. The "in" typemap is used to | |
1555 | receive an input argument and convert it to a C array. Since dynamic memory | |
1556 | allocation is used to allocate memory for the array, the "freearg" typemap is | |
1557 | used to later release this memory after the execution of the C function. | |
1558 | </p> | |
1559 | <H3><a name="Ruby_nn41"></a>27.5.7 Collecting arguments in a hash</H3> | |
1560 | ||
1561 | ||
1562 | <p> | |
1563 | Ruby's solution to the "keyword arguments" capability of some other languages | |
1564 | is to allow the programmer to pass in one or more key-value pairs as arguments | |
1565 | to a function. All of those key-value pairs are collected in a single <tt>Hash</tt> | |
1566 | argument that's presented to the function. If it makes sense, you might want to | |
1567 | provide similar functionality for your Ruby interface. For example, suppose | |
1568 | you'd like to wrap this C function that collects information about people's | |
1569 | vital statistics: | |
1570 | </p> | |
1571 | <div class="code"> | |
1572 | <pre>void setVitalStats(const char *person, int nattributes, const char **names, int *values);<br></pre> | |
1573 | </div> | |
1574 | <p> | |
1575 | and you'd like to be able to call it from Ruby by passing in an arbitrary | |
1576 | number of key-value pairs as inputs, e.g. | |
1577 | </p> | |
1578 | <div class="code"> | |
1579 | <pre>setVitalStats("Fred",<br> 'weight' => 270,<br> 'age' => 42<br> )<br></pre> | |
1580 | </div> | |
1581 | <p> | |
1582 | To make this work, you need to write a typemap that expects a Ruby <tt>Hash</tt> | |
1583 | as its input and somehow extracts the last three arguments (<i>nattributes</i>, <i>names</i> | |
1584 | and <i>values</i>) needed by your C function. Let's start with the basics: | |
1585 | </p> | |
1586 | <div class="code"> | |
1587 | <pre>%typemap(in) (int nattributes, const char **names, const int *values)<br> (VALUE keys_arr, int i, VALUE key, VALUE val) {<br>}<br> </pre> | |
1588 | </div> | |
1589 | <p> | |
1590 | This <tt>%typemap</tt> directive tells SWIG that we want to match any function | |
1591 | declaration that has the specified types and names of arguments somewhere in | |
1592 | the argument list. The fact that we specified the argument names (<i>nattributes</i>, | |
1593 | <i>names</i> and <i>values</i>) in our typemap is significant; this ensures | |
1594 | that SWIG won't try to apply this typemap to <i>other</i> functions it sees | |
1595 | that happen to have a similar declaration with different argument names. The | |
1596 | arguments that appear in the second set of parentheses (<i>keys_arr</i>, <i>i</i>, | |
1597 | <i>key</i> and <i>val</i>) define local variables that our typemap will need. | |
1598 | </p> | |
1599 | <p>Since we expect the input argument to be a <tt>Hash</tt>, let's next add a check | |
1600 | for that: | |
1601 | </p> | |
1602 | <div class="code"> | |
1603 | <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> | |
1604 | </div> | |
1605 | <p> | |
1606 | <tt>Check_Type()</tt> is just a macro (defined in the Ruby header files) that | |
1607 | confirms that the input argument is of the correct type; if it isn't, an | |
1608 | exception will be raised. | |
1609 | </p> | |
1610 | <p>The next task is to determine how many key-value pairs are present in the hash; | |
1611 | we'll assign this number to the first typemap argument (<tt>$1</tt>). This is a | |
1612 | little tricky since the Ruby/C API doesn't provide a public function for | |
1613 | querying the size of a hash, but we can get around that by calling the hash's <i>size</i> | |
1614 | method directly and converting its result to a C <tt>int</tt> value: | |
1615 | </p> | |
1616 | <div class="code"> | |
1617 | <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> | |
1618 | </div> | |
1619 | <p> | |
1620 | So now we know the number of attributes. Next we need to initialize the second | |
1621 | and third typemap arguments (i.e. the two C arrays) to <tt>NULL</tt> and set | |
1622 | the stage for extracting the keys and values from the hash: | |
1623 | </p> | |
1624 | <div class="code"> | |
1625 | <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 > 0) {<br> $2 = (char **) malloc($1*sizeof(char *));<br> $3 = (int *) malloc($1*sizeof(int));<br> }</b><br>}<br></pre> | |
1626 | </div> | |
1627 | <p> | |
1628 | There are a number of ways we could extract the keys and values from the input | |
1629 | hash, but the simplest approach is to first call the hash's <i>keys</i> method | |
1630 | (which returns a Ruby array of the keys) and then start looping over the | |
1631 | elements in that array: | |
1632 | </p> | |
1633 | <div class="code"> | |
1634 | <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 > 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 < $1; i++) {<br> }</b><br>}<br>}<br></pre> | |
1635 | </div> | |
1636 | <p> | |
1637 | Recall that <i>keys_arr</i> and <i>i</i> are local variables for this typemap. | |
1638 | For each element in the <i>keys_arr</i> array, we want to get the key itself, | |
1639 | as well as the value corresponding to that key in the hash: | |
1640 | </p> | |
1641 | <div class="code"> | |
1642 | <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 > 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 < $1; i++) {<br> <b>key = rb_ary_entry(keys_arr, i);<br> val = rb_hash_aref($input, key);</b><br>}<br>}<br>}<br></pre> | |
1643 | </div> | |
1644 | <p> | |
1645 | To be safe, we should again use the <tt>Check_Type()</tt> macro to confirm that | |
1646 | the key is a <tt>String</tt> and the value is a <tt>Fixnum</tt>: | |
1647 | </p> | |
1648 | <div class="code"> | |
1649 | <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 > 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 < $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> | |
1650 | </div> | |
1651 | <p> | |
1652 | Finally, we can convert these Ruby objects into their C equivalents and store | |
1653 | them in our local C arrays: | |
1654 | </p> | |
1655 | <div class="code"> | |
1656 | <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 > 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 < $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> | |
1657 | </div> | |
1658 | <p> | |
1659 | We're not done yet. Since we used <tt>malloc()</tt> to dynamically allocate the | |
1660 | memory used for the <i>names</i> and <i>values</i> arguments, we need to | |
1661 | provide a corresponding "freearg" typemap to free that memory so that there is | |
1662 | no memory leak. Fortunately, this typemap is a lot easier to write: | |
1663 | </p> | |
1664 | <div class="code"> | |
1665 | <pre>%typemap(freearg) (int nattributes, const char **names, const int *values) {<br> free((void *) $2);<br> free((void *) $3);<br>}<br></pre> | |
1666 | </div> | |
1667 | <p> | |
1668 | All of the code for this example, as well as a sample Ruby program that uses | |
1669 | the extension, can be found in the <tt>Examples/ruby/hashargs</tt> directory of | |
1670 | the SWIG distribution. | |
1671 | </p> | |
1672 | <H3><a name="Ruby_nn42"></a>27.5.8 Pointer handling</H3> | |
1673 | ||
1674 | ||
1675 | <p> | |
1676 | Occasionally, it might be necessary to convert pointer values that have been | |
1677 | stored using the SWIG typed-pointer representation. Since there are several | |
1678 | ways in which pointers can be represented, the following two functions are used | |
1679 | to safely perform this conversion: | |
1680 | </p> | |
1681 | <p><tt>int SWIG_ConvertPtr(VALUE obj, void **ptr, swig_type_info *ty, int flags)</tt> | |
1682 | </p> | |
1683 | <div class="indent">Converts a Ruby object <i>obj</i> to a C pointer whose address | |
1684 | is <i>ptr</i> (i.e. <i>ptr</i> is a pointer to a pointer). The third argument, <i>ty</i>, | |
1685 | is a pointer to a SWIG type descriptor structure. If <i>ty</i> is not <tt>NULL</tt>, | |
1686 | that type information is used to validate type compatibility and other aspects | |
1687 | of the type conversion. If <i>flags</i> is non-zero, any type errors | |
1688 | encountered during this validation result in a Ruby <tt>TypeError</tt> exception | |
1689 | being raised; if <i>flags</i> is zero, such type errors will cause <tt>SWIG_ConvertPtr()</tt> | |
1690 | to return -1 but not raise an exception. If <i>ty</i> is <tt>NULL</tt>, no | |
1691 | type-checking is performed. | |
1692 | </div> | |
1693 | <p> | |
1694 | <tt>VALUE SWIG_NewPointerObj(void *ptr, swig_type_info *ty, int own)</tt> | |
1695 | </p> | |
1696 | <div class="indent">Creates a new Ruby pointer object. Here, <i>ptr</i> is the | |
1697 | pointer to convert, <i>ty</i> is the SWIG type descriptor structure that | |
1698 | describes the type, and <i>own</i> is a flag that indicates whether or not Ruby | |
1699 | should take ownership of the pointer (i.e. whether Ruby should free this data | |
1700 | when the corresponding Ruby instance is garbage-collected). | |
1701 | </div> | |
1702 | <p> | |
1703 | Both of these functions require the use of a special SWIG type-descriptor | |
1704 | structure. This structure contains information about the mangled name of the | |
1705 | datatype, type-equivalence information, as well as information about converting | |
1706 | pointer values under C++ inheritance. For a type of <tt>Foo *</tt>, the type | |
1707 | descriptor structure is usually accessed as follows: | |
1708 | </p> | |
1709 | <div class="indent"> | |
1710 | <pre>Foo *foo;<br>SWIG_ConvertPtr($input, (void **) &foo, SWIGTYPE_p_Foo, 1);<br><br>VALUE obj;<br>obj = SWIG_NewPointerObj(f, SWIGTYPE_p_Foo, 0);<br></pre> | |
1711 | </div> | |
1712 | <p> | |
1713 | In a typemap, the type descriptor should always be accessed using the special | |
1714 | typemap variable <tt>$1_descriptor</tt>. For example: | |
1715 | </p> | |
1716 | <div class="indent"> | |
1717 | <pre>%typemap(in) Foo * {<br> SWIG_ConvertPtr($input, (void **) &$1, $1_descriptor, 1);<br>}<br></pre> | |
1718 | </div> | |
1719 | <H4><a name="Ruby_nn43"></a>27.5.8.1 Ruby Datatype Wrapping</H4> | |
1720 | ||
1721 | ||
1722 | <p> | |
1723 | <tt>VALUE Data_Wrap_Struct(VALUE class, void (*mark)(void *), void (*free)(void *), | |
1724 | void *ptr)</tt> | |
1725 | </p> | |
1726 | <div class="indent">Given a pointer <i>ptr</i> to some C data, and the two garbage | |
1727 | collection routines for this data (<i>mark</i> and <i>free</i>), return a <tt>VALUE</tt> | |
1728 | for the Ruby object. | |
1729 | </div> | |
1730 | <p><tt>VALUE Data_Make_Struct(VALUE class, <i>c-type</i>, void (*mark)(void *), void | |
1731 | (*free)(void *), <i>c-type</i> *ptr)</tt></p> | |
1732 | <div class="indent">Allocates a new instance of a C data type <i>c-type</i>, | |
1733 | assigns it to the pointer <i>ptr</i>, then wraps that pointer with <tt>Data_Wrap_Struct()</tt> | |
1734 | as above. | |
1735 | </div> | |
1736 | <p><tt>Data_Get_Struct(VALUE obj, <i>c-type</i>, <i>c-type</i> *ptr)</tt></p> | |
1737 | <div class="indent">Retrieves the original C pointer of type <i>c-type</i> from the | |
1738 | data object <i>obj</i> and assigns that pointer to <i>ptr</i>. | |
1739 | </div> | |
1740 | <H2><a name="ruby_operator_overloading"></a>27.6 Operator overloading</H2> | |
1741 | ||
1742 | ||
1743 | <p> | |
1744 | SWIG allows operator overloading with, by using the <tt>%extend</tt> or <tt>%rename</tt> | |
1745 | commands in SWIG and the following operator names (derived from Python): | |
1746 | </p> | |
1747 | <div class="code"> | |
1748 | <pre><b> General</b> <br>__repr__ - inspect<br>__str__ - to_s<br>__cmp__ - <=><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__ - <<<br>__rshift__ - >><br>__and__ - &<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__ - < <br>__le__ - <=<br>__eq__ - ==<br>__gt__ - ><br>__ge__ - >=<br><br></pre> | |
1749 | </div> | |
1750 | <p> | |
1751 | Note that although SWIG supports the <tt>__eq__</tt> magic method name for | |
1752 | defining an equivalence operator, there is no separate method for handling <i>inequality</i> | |
1753 | since Ruby parses the expression <i>a != b</i> as <i>!(a == b)</i>. | |
1754 | </p> | |
1755 | <H3><a name="Ruby_nn45"></a>27.6.1 Example: STL Vector to Ruby Array</H3> | |
1756 | ||
1757 | ||
1758 | <p> | |
1759 | <em><b>FIXME: This example is out of place here!</b></em> | |
1760 | </p> | |
1761 | <p>Another use for macros and type maps is to create a Ruby array from a STL vector | |
1762 | of pointers. In essence, copy of all the pointers in the vector into a Ruby | |
1763 | array. The use of the macro is to make the typemap so generic that any vector | |
1764 | with pointers can use the type map. The following is an example of how to | |
1765 | construct this type of macro/typemap and should give insight into constructing | |
1766 | similar typemaps for other STL structures: | |
1767 | </p> | |
1768 | <div class="code"> | |
1769 | <pre>%define PTR_VECTOR_TO_RUBY_ARRAY(vectorclassname, classname)<br>%typemap(ruby, 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>%typemap(ruby, 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> | |
1770 | </div> | |
1771 | <p> | |
1772 | Note, that the "<tt>c ## classname.klass"</tt> is used in the preprocessor step | |
1773 | to determine the actual object from the class name. | |
1774 | </p> | |
1775 | <p>To use the macro with a class Foo, the following is used: | |
1776 | </p> | |
1777 | <div class="code"> | |
1778 | <pre>PTR_VECTOR_TO_RUBY_ARRAY(vector<foo *="">, Foo)<br></pre> | |
1779 | </div> | |
1780 | <p> | |
1781 | It is also possible to create a STL vector of Ruby objects: | |
1782 | </p> | |
1783 | <div class="code"> | |
1784 | <pre>%define RUBY_ARRAY_TO_PTR_VECTOR(vectorclassname, classname)<br>%typemap(ruby, in) vectorclassname &, const vectorclassname & {<br> Check_Type($input, T_ARRAY);<br> vectorclassname *vec = new vectorclassname;<br> int len = RARRAY($input)->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->push_back(element);<br> }<br> $1 = vec;<br>}<br><br>%typemap(ruby, freearg) vectorclassname &, const vectorclassname & {<br> delete $1;<br>}<br>%enddef<br></pre> | |
1785 | </div> | |
1786 | <p> | |
1787 | It is also possible to create a Ruby array from a vector of static data types: | |
1788 | </p> | |
1789 | <div class="code"> | |
1790 | <pre>%define VECTOR_TO_RUBY_ARRAY(vectorclassname, classname)<br>%typemap(ruby, 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>%typemap(ruby, 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> | |
1791 | </div> | |
1792 | <H2><a name="Ruby_nn46"></a>27.7 Advanced Topics</H2> | |
1793 | ||
1794 | ||
1795 | <H3><a name="Ruby_nn47"></a>27.7.1 Creating Multi-Module Packages</H3> | |
1796 | ||
1797 | ||
1798 | <p> | |
1799 | The chapter on <a href="Modules.html">Working with Modules</a> discusses the | |
1800 | basics of creating multi-module extensions with SWIG, and in particular the | |
1801 | considerations for sharing runtime type information among the different | |
1802 | modules. | |
1803 | </p> | |
1804 | <p>As an example, consider one module's interface file (<tt>shape.i</tt>) that | |
1805 | defines our base class: | |
1806 | </p> | |
1807 | <div class="code"> | |
1808 | <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> | |
1809 | </div> | |
1810 | <p> | |
1811 | We also have a separate interface file (<tt>circle.i</tt>) that defines a | |
1812 | derived class: | |
1813 | </p> | |
1814 | <div class="code"> | |
1815 | <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> | |
1816 | </div> | |
1817 | <p> | |
1818 | We'll start by building the <b>Shape</b> extension module: | |
1819 | </p> | |
1820 | <div class="code"> | |
1821 | <pre>$ <b>swig -c++ -ruby shape.i</b> | |
1822 | </pre> | |
1823 | </div> | |
1824 | <p> | |
1825 | SWIG generates a wrapper file named <tt>shape_wrap.cxx</tt>. To compile this | |
1826 | into a dynamically loadable extension for Ruby, prepare an <tt>extconf.rb</tt> script | |
1827 | using this template: | |
1828 | </p> | |
1829 | <div class="code"> | |
1830 | <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> | |
1831 | </div> | |
1832 | <p> | |
1833 | Run this script to create a <tt>Makefile</tt> and then type <tt>make</tt> to | |
1834 | build the shared library: | |
1835 | </p> | |
1836 | <div class="code"> | |
1837 | <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> | |
1838 | </div> | |
1839 | <p> | |
1840 | Note that depending on your installation, the outputs may be slightly | |
1841 | different; these outputs are those for a Linux-based development environment. | |
1842 | The end result should be a shared library (here, <tt>shape.so</tt>) containing | |
1843 | the extension module code. Now repeat this process in a separate directory for | |
1844 | the <b>Circle</b> module: | |
1845 | </p> | |
1846 | <ol> | |
1847 | <li> | |
1848 | Run SWIG to generate the wrapper code (<tt>circle_wrap.cxx</tt>); | |
1849 | </li> | |
1850 | <li> | |
1851 | Write an <tt>extconf.rb</tt> script that your end-users can use to create a | |
1852 | platform-specific <tt>Makefile</tt> for the extension; | |
1853 | </li> | |
1854 | <li> | |
1855 | Build the shared library for this extension by typing <tt>make</tt>. | |
1856 | </li> | |
1857 | </ol> | |
1858 | <p> | |
1859 | Once you've built both of these extension modules, you can test them | |
1860 | interactively in IRB to confirm that the <tt>Shape</tt> and <tt>Circle</tt> modules | |
1861 | are properly loaded and initialized: | |
1862 | </p> | |
1863 | <div class="code"> | |
1864 | <pre>$ <b>irb</b><br>irb(main):001:0> <b>require 'shape'</b><br>true<br>irb(main):002:0> <b>require 'circle'</b><br>true<br>irb(main):003:0> <b>c = Circle::Circle.new(5, 5, 20)</b><br>#<Circle::Circle:0xa097208><br>irb(main):004:0> <b>c.kind_of? Shape::Shape</b><br>true<br>irb(main):005:0> <b>c.getX()</b><br>5.0<br></pre> | |
1865 | </div> | |
1866 | <H3><a name="Ruby_nn48"></a>27.7.2 Defining Aliases</H3> | |
1867 | ||
1868 | ||
1869 | <p> | |
1870 | It's a fairly common practice in the Ruby built-ins and standard library to | |
1871 | provide aliases for method names. For example, <em>Array#size</em> is an alias | |
1872 | for <em>Array#length</em>. If you'd like to provide an alias for one of your | |
1873 | class' instance methods, one approach is to use SWIG's <tt>%extend</tt> directive | |
1874 | to add a new method of the aliased name that calls the original function. For | |
1875 | example: | |
1876 | </p> | |
1877 | <div class="code"> | |
1878 | <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->length();<br> }<br>}<br></pre> | |
1879 | </div> | |
1880 | <p> | |
1881 | A better solution is to instead use the <tt>%alias</tt> directive (unique to | |
1882 | SWIG's Ruby module). The previous example could then be rewritten as: | |
1883 | </p> | |
1884 | <div class="code"> | |
1885 | <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></pre> | |
1886 | </div> | |
1887 | <p> | |
1888 | Multiple aliases can be associated with a method by providing a comma-separated | |
1889 | list of aliases to the <tt>%alias</tt> directive, e.g. | |
1890 | </p> | |
1891 | <div class="code"> | |
1892 | <pre>%alias MyArray::length "amount,quantity,size";</pre> | |
1893 | </div> | |
1894 | <p> | |
1895 | From an end-user's standpoint, there's no functional difference between these | |
1896 | two approaches; i.e. they should get the same result from calling either <em>MyArray#size</em> | |
1897 | or <em>MyArray#length</em>. However, when the <tt>%alias</tt> directive is | |
1898 | used, SWIG doesn't need to generate all of the wrapper code that's usually | |
1899 | associated with added methods like our <em>MyArray::size()</em> example. | |
1900 | </p> | |
1901 | <p>Note that the <tt>%alias</tt> directive is implemented using SWIG's "features" | |
1902 | mechanism and so the same name matching rules used for other kinds of features | |
1903 | apply (see the chapter on <a href="Customization.html#Customization">"Customization | |
1904 | Features"</a>) for more details).</p> | |
1905 | <H3><a name="Ruby_nn49"></a>27.7.3 Predicate Methods</H3> | |
1906 | ||
1907 | ||
1908 | <p> | |
1909 | Predicate methods in Ruby are those which return either <tt>true</tt> or <tt>false</tt>. | |
1910 | By convention, these methods' names end in a question mark; some examples from | |
1911 | built-in Ruby classes include <em>Array#empty?</em> (which returns <tt>true</tt> | |
1912 | for an array containing no elements) and <em>Object#instance_of?</em> (which | |
1913 | returns <tt>true</tt> if the object is an instance of the specified class). For | |
1914 | consistency with Ruby conventions you would also want your interface's | |
1915 | predicate methods' names to end in a question mark and return <tt>true</tt> or <tt>false</tt>. | |
1916 | </p> | |
1917 | <p>One cumbersome solution to this problem is to rename the method (using SWIG's <tt>%rename</tt> | |
1918 | directive) and provide a custom typemap that converts the function's actual | |
1919 | return type to Ruby's <tt>true</tt> or <tt>false</tt>. For example: | |
1920 | </p> | |
1921 | <div class="code"> | |
1922 | <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></pre> | |
1923 | </div> | |
1924 | <p> | |
1925 | A better solution is to instead use the <tt>%predicate</tt> directive (unique | |
1926 | to SWIG's Ruby module) to designate certain methods as predicate methods. For | |
1927 | the previous example, this would look like: | |
1928 | </p> | |
1929 | <div class="code"> | |
1930 | <pre>%predicate is_it_safe();<br><br>int is_it_safe();<br></pre> | |
1931 | </div> | |
1932 | <p>and to use this method from your Ruby code:</p> | |
1933 | <div class="code"> | |
1934 | <pre>irb(main):001:0> <b>Example::is_it_safe?</b><br>true<br></pre> | |
1935 | </div> | |
1936 | <p> | |
1937 | Note that the <tt>%predicate</tt> directive is implemented using SWIG's | |
1938 | "features" mechanism and so the same name matching rules used for other kinds | |
1939 | of features apply (see the chapter on <a href="Customization.html#Customization">"Customization | |
1940 | Features"</a>) for more details). | |
1941 | </p> | |
1942 | <H3><a name="Ruby_nn50"></a>27.7.4 Specifying Mixin Modules</H3> | |
1943 | ||
1944 | ||
1945 | <p> | |
1946 | The Ruby language doesn't support multiple inheritance, but it does allow you | |
1947 | to mix one or more modules into a class using Ruby's <tt>include</tt> method. | |
1948 | For example, if you have a Ruby class that defines an <em>each</em> instance | |
1949 | method, e.g. | |
1950 | </p> | |
1951 | <div class="code"> | |
1952 | <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> | |
1953 | </div> | |
1954 | <p> | |
1955 | then you can mix-in Ruby's <tt>Enumerable</tt> module to easily add a lot of | |
1956 | functionality to your class: | |
1957 | </p> | |
1958 | <div class="code"> | |
1959 | <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> | |
1960 | </div> | |
1961 | <p> | |
1962 | To get the same benefit for your SWIG-wrapped classes, you can use the <tt>%mixin</tt> | |
1963 | directive to specify the names of one or more modules that should be mixed-in | |
1964 | to a class. For the above example, the SWIG interface specification might look | |
1965 | like this: | |
1966 | </p> | |
1967 | <div class="code"> | |
1968 | <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> | |
1969 | </div> | |
1970 | <p> | |
1971 | Multiple modules can be mixed into a class by providing a comma-separated list | |
1972 | of module names to the <tt>%mixin</tt> directive, e.g. | |
1973 | </p> | |
1974 | <div class="code"> | |
1975 | <pre>%mixin Set "Fee,Fi,Fo,Fum";</pre> | |
1976 | </div> | |
1977 | <p> | |
1978 | Note that the <tt>%mixin</tt> directive is implemented using SWIG's "features" | |
1979 | mechanism and so the same name matching rules used for other kinds of features | |
1980 | apply (see the chapter on <a href="Customization.html#Customization">"Customization | |
1981 | Features"</a>) for more details). | |
1982 | </p> | |
1983 | <H2><a name="Ruby_nn51"></a>27.8 Memory Management</H2> | |
1984 | ||
1985 | ||
1986 | <p>One of the most common issues in generating SWIG bindings for Ruby is proper | |
1987 | memory management. The key to proper memory management is clearly defining | |
1988 | whether a wrapper Ruby object owns the underlying C struct or C++ class. There | |
1989 | are two possibilities:</p> | |
1990 | <ul> | |
1991 | <li> | |
1992 | The Ruby object is responsible for freeing the C struct or C++ object | |
1993 | </li> | |
1994 | <li> | |
1995 | The Ruby object should not free the C struct or C++ object because it will be | |
1996 | freed by the underlying C or C++ code</li> | |
1997 | </ul> | |
1998 | <p>To complicate matters, object ownership may transfer from Ruby to C++ (or vice | |
1999 | versa) depending on what function or methods are invoked. Clearly, developing a | |
2000 | SWIG wrapper requires a thorough understanding of how the underlying library | |
2001 | manages memory.</p> | |
2002 | <h3><a name="Ruby_nn52" id="Ruby_nn52"></a>27.9.1 Mark and Sweep Garbage Collector | |
2003 | </h3> | |
2004 | <p>Ruby uses a mark and sweep garbage collector. When the garbage collector runs, | |
2005 | it finds all the "root" objects, including local variables, global variables, | |
2006 | global constants, hardware registers and the C stack. For each root object, the | |
2007 | garbage collector sets its mark flag to true and calls <tt>rb_gc_mark</tt> on | |
2008 | the object. The job of <tt>rb_gc_mark</tt> is to recursively mark all the | |
2009 | objects that a Ruby object has a reference to (ignoring those objects that have | |
2010 | already been marked). Those objects, in turn, may reference other objects. This | |
2011 | process will continue until all active objects have been "marked." After the | |
2012 | mark phase comes the sweep phase. In the sweep phase, all objects that have not | |
2013 | been marked will be garbage collected. For more information about the Ruby | |
2014 | garbage collector please refer to <a href="http://rubygarden.org/ruby/ruby?GCAndExtensions"> | |
2015 | <span style="text-decoration: underline;">http://rubygarden.org/ruby/ruby?GCAndExtensions</span></a>.</p> | |
2016 | <p>The Ruby C/API provides extension developers two hooks into the garbage | |
2017 | collector - a "mark" function and a "sweep" function. By default these functions | |
2018 | are set to NULL.</p> | |
2019 | <p>If a C struct or C++ class references any other Ruby objects, then it must | |
2020 | provide a "mark" function. The "mark" function should identify any referenced | |
2021 | Ruby objects by calling the rb_gc_mark function for each one. Unsurprisingly, | |
2022 | this function will be called by the Ruby garbage during the "mark" phase.</p> | |
2023 | <p>During the sweep phase, Ruby destroys any unused objects. If any memory has been | |
2024 | allocated in creating the underlying C struct or C++ struct, then a "free" | |
2025 | function must be defined that deallocates this memory. | |
2026 | </p> | |
2027 | <H3><a name="Ruby_nn53"></a>27.8.1 Object Ownership</H3> | |
2028 | ||
2029 | ||
2030 | <p>As described above, memory management depends on clearly defining who is | |
2031 | responsible for freeing the underlying C struct or C++ class. If the Ruby | |
2032 | object is responsible for freeing the C++ object, then a "free" function must | |
2033 | be registered for the object. If the Ruby object is not responsible for freeing | |
2034 | the underlying memory, then a "free" function must not be registered for the | |
2035 | object.</p> | |
2036 | <p>For the most part, SWIG takes care of memory management issues. The rules it | |
2037 | uses are:</p> | |
2038 | <ul> | |
2039 | <li> | |
2040 | When calling a C++ object's constructor from Ruby, SWIG will assign a "free" | |
2041 | function thereby making the Ruby object responsible for freeing the C++ object</li> | |
2042 | <li> | |
2043 | When calling a C++ member function that returns a pointer, SWIG will not assign | |
2044 | a "free" function thereby making the underlying library responsible for freeing | |
2045 | the object.</li> | |
2046 | </ul> | |
2047 | <p>To make this clearer, let's look at an example. Assume we have a Foo and a Bar | |
2048 | class. | |
2049 | </p> | |
2050 | <div class="code"> | |
2051 | <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> | |
2052 | </pre> | |
2053 | </div> | |
2054 | <p>First, consider this Ruby code: | |
2055 | </p> | |
2056 | <div class="code"> | |
2057 | <pre>foo = Foo.new</pre> | |
2058 | </div> | |
2059 | <p>In this case, the Ruby code calls the underlying <tt>Foo</tt> C++ constructor, | |
2060 | thus creating a new <tt>foo</tt> object. By default, SWIG will assign the new | |
2061 | Ruby object a "free" function. When the Ruby object is garbage collected, the | |
2062 | "free" function will be called. It in turn will call <tt>Foo's</tt> destructor.</p> | |
2063 | <p>Next, consider this code: | |
2064 | </p> | |
2065 | <div class="code"> | |
2066 | <pre>bar = Bar.new<br>foo = bar.get_foo()</pre> | |
2067 | </div> | |
2068 | <p>In this case, the Ruby code calls a C++ member function, <tt>get_foo</tt>. By | |
2069 | default, SWIG will not assign the Ruby object a "free" function. Thus, when the | |
2070 | Ruby object is garbage collected the underlying C++ <tt>foo</tt> object is not | |
2071 | affected.</p> | |
2072 | <p>Unfortunately, the real world is not as simple as the examples above. For | |
2073 | example:</p> | |
2074 | <div class="code"> | |
2075 | <pre>bar = Bar.new<br>foo = bar.get_new_foo()</pre> | |
2076 | </div> | |
2077 | <p>In this case, the default SWIG behavior for calling member functions is | |
2078 | incorrect. The Ruby object should assume ownership of the returned object. This | |
2079 | can be done by using the %newobject directive. See <a href="file:///d:/msys/1.0/src/SWIG/Doc/Manual/Customization.html#ownership"> | |
2080 | Object ownership and %newobject</a> for more information. | |
2081 | </p> | |
2082 | <p>The SWIG default mappings are also incorrect in this case:</p> | |
2083 | <div class="code"> | |
2084 | <pre>foo = Foo.new<br>bar = Bar.new<br>bar.set_foo(foo)</pre> | |
2085 | </div> | |
2086 | <p>Without modification, this code will cause a segmentation fault. When the Ruby <tt>foo</tt> | |
2087 | object goes out of scope, it will free the underlying C++ <tt>foo</tt> object. | |
2088 | However, when the Ruby bar object goes out of scope, it will call the C++ bar | |
2089 | destructor which will also free the C++ <tt>foo</tt> object. The problem is | |
2090 | that object ownership is transferred from the Ruby object to the C++ object | |
2091 | when the <tt>set_foo</tt> method is called. This can be done by using the | |
2092 | special DISOWN type map, which was added to the Ruby bindings in SWIG-1.3.26.</p> | |
2093 | <p>Thus, a correct SWIG interface file correct mapping for these classes is:</p> | |
2094 | <div class="code"> | |
2095 | <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> | |
2096 | </pre> | |
2097 | </div> | |
2098 | <br> | |
2099 | <p> | |
2100 | This code can be seen in swig/examples/ruby/tracking.</p> | |
2101 | <br> | |
2102 | <H3><a name="Ruby_nn54"></a>27.8.2 Object Tracking</H3> | |
2103 | ||
2104 | ||
2105 | <p>The remaining parts of this section will use the class library shown below to | |
2106 | illustrate different memory management techniques. The class library models a | |
2107 | zoo and the animals it contains. | |
2108 | </p> | |
2109 | <div class="code"> | |
2110 | <pre>%module zoo<br><br>%{<br>#include <string><br>#include <vector><br><br>#include "zoo.h"<br>%}<br><br>class Animal<br>{<br>private:<br> typedef std::vector<Animal*> 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<animal *=""> 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->animals[i];<br> IterType iter = this->animals.begin();<br> std::advance(iter, i);<br> this->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> | |
2111 | </pre> | |
2112 | </div> | |
2113 | <p>Let's say you SWIG this code and then run IRB:<br> | |
2114 | </p> | |
2115 | <div class="code"> | |
2116 | <pre>$ <span style="font-weight: bold;">irb</span><br>irb(main):001:0> <span style="font-weight: bold;">require 'example'</span><br>=> true<br><br>irb(main):002:0> <span style="font-weight: bold;">tiger1 = Example::Animal.new("tiger1")</span><br>=> #<Example::Animal:0x2be3820><br><br>irb(main):004:0> <span style="font-weight: bold;">tiger1.get_name()</span><br>=> "tiger1"<br><br>irb(main):003:0> <span style="font-weight: bold;">zoo = Example::Zoo.new()</span><br>=> #<Example::Zoo:0x2be0a60><br><br>irb(main):006:0> <span style="font-weight: bold;">zoo.add_animal(tiger)</span><br>=> nil<br><br>irb(main):007:0> <span style="font-weight: bold;">zoo.get_num_animals()</span><br>=> 1<br><br>irb(main):007:0> <span style="font-weight: bold;">tiger2 = zoo.remove_animal(0)</span><br>=> #<Example::Animal:0x2bd4a18><br><br>irb(main):008:0> <span style="font-weight: bold;">tiger2.get_name()</span><br>=> "tiger1"<br><br>irb(main):009:0> <span style="font-weight: bold;">tiger1.equal?(tiger2)</span><br>=> false<br> | |
2117 | </pre> | |
2118 | </div> | |
2119 | <p>Pay particular attention to the code <tt>tiger1.equal?(tiger2)</tt>. Note that | |
2120 | the two Ruby objects are not the same - but they reference the same underlying | |
2121 | C++ object. This can cause problems. For example:<br> | |
2122 | </p> | |
2123 | <div class="code"> | |
2124 | <pre>irb(main):010:0> <span style="font-weight: bold;">tiger1 = nil</span><br>=> nil<br><br>irb(main):011:0> <span style="font-weight: bold;">GC.start</span><br>=> nil<br><br>irb(main):012:0> <span style="font-weight: bold;">tiger2.get_name()</span><br>(irb):12: [BUG] Segmentation fault<br> | |
2125 | </pre> | |
2126 | </div> | |
2127 | <p>After the the garbage collector runs, as a result of our call to <tt>GC.start</tt>, | |
2128 | calling<tt>tiger2.get_name()</tt> causes a segmentation fault. The problem is | |
2129 | that when <tt>tiger1</tt> is garbage collected, it frees the underlying C++ | |
2130 | object. Thus, when <tt>tiger2</tt> calls the <tt>get_name()</tt> method it | |
2131 | invokes it on a destroyed object.</p> | |
2132 | <p>This problem can be avoided if SWIG enforces a one-to-one mapping between Ruby | |
2133 | objects and C++ classes. This can be done via the use of the <tt>%trackobjects</tt> | |
2134 | functionality available in SWIG-1.3.26. and later.</p> | |
2135 | <p>When the <tt>%trackobjects</tt> is turned on, SWIG automatically keeps track of | |
2136 | mappings between C++ objects and Ruby objects. Note that enabling object | |
2137 | tracking causes a slight performance degradation. Test results show this | |
2138 | degradation to be about 3% to 5% when creating and destroying 100,000 animals | |
2139 | in a row.</p> | |
2140 | <p>Since <tt>%trackobjects</tt> is implemented as a <tt>%feature</tt>, it uses the same name matching | |
2141 | rules as other kinds of features (see the chapter on <a href="Customization.html#Customization"> | |
2142 | "Customization Features"</a>) . Thus it can be applied on a class-by-class | |
2143 | basis if needed. To fix the example above:</p> | |
2144 | <br> | |
2145 | <div class="code"> | |
2146 | <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> | |
2147 | </div> | |
2148 | <p>When this code runs we see:<br> | |
2149 | <br> | |
2150 | </p> | |
2151 | <div class="code"> | |
2152 | <pre>$ <span style="font-weight: bold;">irb</span><br>irb(main):001:0> <span style="font-weight: bold;">require 'example'</span><br>=> true<br><br>irb(main):002:0> <span style="font-weight: bold;">tiger1 = Example::Animal.new("tiger1")</span><br>=> #<Example::Animal:0x2be37d8><br><br>irb(main):003:0> <span style="font-weight: bold;">zoo = Example::Zoo.new()</span><br>=> #<Example::Zoo:0x2be0a18><br><br>irb(main):004:0> <span style="font-weight: bold;">zoo.add_animal(tiger1)</span><br>=> nil<br><br>irb(main):006:0> <span style="font-weight: bold;">tiger2 = zoo.remove_animal(0)</span><br>=> #<Example::Animal:0x2be37d8><br><br>irb(main):007:0> <span style="font-weight: bold;">tiger1.equal?(tiger2)</span><br>=> true<br><br>irb(main):008:0> <span style="font-weight: bold;">tiger1 = nil</span><br>=> nil<br><br>irb(main):009:0> <span style="font-weight: bold;">GC.start</span><br>=> nil<br><br>irb(main):010:0> <span style="font-weight: bold;">tiger.get_name()</span><br>=> "tiger1"<br>irb(main):011:0><br> | |
2153 | </pre> | |
2154 | </div> | |
2155 | <p>For those who are interested, object tracking is implemented by storing Ruby | |
2156 | objects in a hash table and keying them on C++ pointers. The underlying API is:<br> | |
2157 | </p> | |
2158 | <div class="code"> | |
2159 | <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> | |
2160 | </div> | |
2161 | <p>When an object is created, SWIG will automatically call the <tt>SWIG_RubyAddTracking</tt> | |
2162 | method. Similarly, when an object is deleted, SWIG will call the <tt>SWIG_RubyRemoveTracking</tt>. | |
2163 | When an object is returned to Ruby from C++, SWIG will use the <tt>SWIG_RubyInstanceFor</tt> | |
2164 | method to ensure a one-to-one mapping from Ruby to C++ objects. Last, the <tt>RubyUnlinkObjects</tt> | |
2165 | method unlinks a Ruby object from its underlying C++ object.</p> | |
2166 | <p>In general, you will only need to use the <tt>SWIG_RubyInstanceFor</tt>, which | |
2167 | is required for implementing mark functions as shown below. However, if you | |
2168 | implement your own free functions (see below) you may also have to call the<tt>SWIG_RubyRemoveTracking</tt> | |
2169 | and <tt>RubyUnlinkObjects</tt> methods.</p> | |
2170 | ||
2171 | <H3><a name="Ruby_nn55"></a>27.8.3 Mark Functions</H3> | |
2172 | ||
2173 | ||
2174 | <p>With a bit more testing, we see that our class library still has problems. For | |
2175 | example:<br> | |
2176 | </p> | |
2177 | <div class="code"> | |
2178 | <pre>$ <b>irb</b><br>irb(main):001:0> <span style="font-weight: bold;">require 'example'</span><br>=> true<br><br>irb(main):002:0> tiger1 = <span style="font-weight: bold;">Example::Animal.new("tiger1")</span><br>=> #<Example::Animal:0x2bea6a8><br><br>irb(main):003:0> zoo = <span style="font-weight: bold;">Example::Zoo.new()</span><br>=> #<Example::Zoo:0x2be7960><br><br>irb(main):004:0> <span style="font-weight: bold;">zoo.add_animal(tiger1)</span><br>=> nil<br><br>irb(main):007:0> <span style="font-weight: bold;">tiger1 = nil</span><br>=> nil<br><br>irb(main):007:0> <span style="font-weight: bold;">GC.start</span><br>=> nil<br><br>irb(main):005:0> <span style="font-weight: bold;">tiger2 = zoo.get_animal(0)</span><br>(irb):12: [BUG] Segmentation fault</pre> | |
2179 | </div> | |
2180 | <p>The problem is that Ruby does not know that the <tt>zoo</tt> object contains a | |
2181 | reference to a Ruby object. Thus, when Ruby garbage collects | |
2182 | <span style="font-family: monospace;">tiger1</span> | |
2183 | it frees the underlying C++ object.</p> | |
2184 | <p>This can be fixed by implementing a | |
2185 | <tt>mark</tt> function as described above in the <a href="Ruby.html#Ruby_nn52">Mark and Sweep Garbage | |
2186 | Collector</a> section. You can specify a mark function by using the <tt>%markfunc</tt> | |
2187 | directive. Since the <tt>%markfunc</tt> directive is implemented using SWIG's' | |
2188 | "features" mechanism it uses the same name matching rules as other kinds of | |
2189 | features (see the chapter on <a href="Customization.html#Customization">"Customization | |
2190 | Features"</a> for more details). | |
2191 | </p> | |
2192 | <p>A <tt>mark</tt> function takes a single argument, which is a pointer to the C++ | |
2193 | object being marked; it should, in turn, call <tt>rb_gc_mark()</tt> for any | |
2194 | instances that are reachable from the current object. The mark function for our <tt> | |
2195 | Zoo</tt> class should therefore loop over all of the C++ animal objects in | |
2196 | the zoo object, look up their Ruby object equivalent, and then call <tt>rb_gc_mark()</tt>. | |
2197 | One possible implementation is:</p> | |
2198 | <div class="code"> | |
2199 | <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->get_num_animals();<br><br> for(int i = 0; i < count; ++i) {<br> Animal* animal = zoo->get_animal(i);<br> VALUE object = SWIG_RubyInstanceFor(animal);<br><br> if (object != Qnil) {<br> rb_gc_mark(object);<br> }<br> }<br>}<br>%}<br> | |
2200 | </pre> | |
2201 | </div> | |
2202 | <p> | |
2203 | Note the <tt>mark</tt> function is dependent on the <tt>SWIG_RUBY_InstanceFor</tt> | |
2204 | method, and thus requires that <tt>%trackobjects</tt> | |
2205 | is enabled. For more information, please refer to the track_object.i test case in the SWIG test suite.</p> | |
2206 | <p>When this code is compiled we now see:</p> | |
2207 | <div class="code"> | |
2208 | <pre>$ <b>irb<br></b>irb(main):002:0> <span style="font-weight: bold;">tiger1=Example::Animal.new("tiger1")</span><br>=> #<Example::Animal:0x2be3bf8><br><br>irb(main):003:0> <span style="font-weight: bold;">Example::Zoo.new()</span><br>=> #<Example::Zoo:0x2be1780><br><br>irb(main):004:0> <span style="font-weight: bold;">zoo = Example::Zoo.new()</span><br>=> #<Example::Zoo:0x2bde9c0><br><br>irb(main):005:0> <span style="font-weight: bold;">zoo.add_animal(tiger1)</span><br>=> nil<br><br>irb(main):009:0> <span style="font-weight: bold;">tiger1 = nil</span><br>=> nil<br><br>irb(main):010:0> <span style="font-weight: bold;">GC.start</span><br>=> nil<br>irb(main):014:0> <span style="font-weight: bold;">tiger2 = zoo.get_animal(0)</span><br>=> #<Example::Animal:0x2be3bf8><br><br>irb(main):015:0> <span style="font-weight: bold;">tiger2.get_name()</span><br>=> "tiger1"<br>irb(main):016:0><br> | |
2209 | </pre> | |
2210 | </div> | |
2211 | <br> | |
2212 | <p>This code can be seen in swig/examples/ruby/mark_function.</p> | |
2213 | <H3><a name="Ruby_nn56"></a>27.8.4 Free Functions</H3> | |
2214 | ||
2215 | ||
2216 | <p>By default, SWIG creates a "free" function that is called when a Ruby object is | |
2217 | garbage collected. The free function simply calls the C++ object's destructor.</p> | |
2218 | <p>However, sometimes an appropriate destructor does not exist or special | |
2219 | processing needs to be performed before the destructor is called. Therefore, | |
2220 | SWIG allows you to manually specify a "free" function via the use of the <tt>%freefunc</tt> | |
2221 | directive. The <tt>%freefunc</tt> directive is implemented using SWIG's' | |
2222 | "features" mechanism and so the same name matching rules used for other kinds | |
2223 | of features apply (see the chapter on <a href="Customization.html#Customization">"Customization | |
2224 | Features"</a>) for more details).</p> | |
2225 | <p>IMPORTANT ! - If you define your own free function, then you must ensure that | |
2226 | you call the underlying C++ object's destructor. In addition, if object | |
2227 | tracking is activated for the object's class, you must also call the <tt>SWIG_RubyRemoveTracking</tt> | |
2228 | function (of course call this before you destroy the C++ object). Note that it | |
2229 | is harmless to call this method if object tracking if off so it is advised to | |
2230 | always call it.</p> | |
2231 | <p>Note there is a subtle interaction between object ownership and free functions. | |
2232 | A custom defined free function will only be called if the Ruby object owns the | |
2233 | underlying C++ object. This also to Ruby objects which are created, but then | |
2234 | transfer ownership to C++ objects via the use of the <tt>disown</tt> typemap | |
2235 | described above. | |
2236 | </p> | |
2237 | <p>To show how to use the <tt>%freefunc</tt> directive, let's slightly change our | |
2238 | example. Assume that the zoo object is responsible for freeing animal that it | |
2239 | contains. This means that the | |
2240 | <span style="font-family: monospace;">Zoo::add_animal</span> | |
2241 | function should be marked with a | |
2242 | <span style="font-family: monospace;">DISOWN</span> | |
2243 | typemap and the destructor should be updated as below::</p> | |
2244 | <div class="code"> | |
2245 | <pre>Zoo::~Zoo() {<br> IterType iter = this->animals.begin();<br> IterType end = this->animals.end();<br><br> for(iter; iter != end; ++iter) {<br> Animal* animal = *iter;<br> delete animal;<br> }<br>}</pre> | |
2246 | </div> | |
2247 | <p>When we use these objects in IRB we see:</p> | |
2248 | <div class="code"> | |
2249 | <pre><span style="font-weight: bold;">$irb</span><br>irb(main):002:0> <span style="font-weight: bold;">require 'example'</span><br>=> true<br><br>irb(main):003:0> <span style="font-weight: bold;">zoo = Example::Zoo.new()</span><br>=> #<Example::Zoo:0x2be0fe8><br><br>irb(main):005:0> <span style="font-weight: bold;">tiger1 = Example::Animal.new("tiger1")</span><br>=> #<Example::Animal:0x2bda760><br><br>irb(main):006:0> <span style="font-weight: bold;">zoo.add_animal(tiger1)</span><br>=> nil<br><br>irb(main):007:0> <span style="font-weight: bold;">zoo = nil</span><br>=> nil<br><br>irb(main):008:0> <span style="font-weight: bold;">GC.start</span><br>=> nil<br><br>irb(main):009:0> <span style="font-weight: bold;">tiger1.get_name()</span><br>(irb):12: [BUG] Segmentation fault<br> | |
2250 | </pre> | |
2251 | </div> | |
2252 | <p>The error happens because the C++ <tt>animal</tt> object is freed when the <tt>zoo</tt> | |
2253 | object is freed. Although this error is unavoidable, we can at least prevent | |
2254 | the segmentation fault. To do this requires enabling object tracking and | |
2255 | implementing a custom free function that calls the <tt>SWIG_RubyUnlinkObjects</tt> | |
2256 | function for each animal object that is destroyed. The <tt>SWIG_RubyUnlinkObjects</tt> | |
2257 | function notifies SWIG that a Ruby object's underlying C++ object is no longer | |
2258 | valid. Once notified, SWIG will intercept any calls from the existing Ruby | |
2259 | object to the destroyed C++ object and raise an exception.<br> | |
2260 | </p> | |
2261 | <div class="code"> | |
2262 | <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->get_num_animals();<br><br> for(int i = 0; i < count; ++i) {<br> /* Get an animal */<br> Animal* animal = zoo->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> | |
2263 | </div> | |
2264 | <p>Now when we use these objects in IRB we see:</p> | |
2265 | <div class="code"> | |
2266 | <pre><span style="font-weight: bold;">$irb</span><br>irb(main):002:0> <span style="font-weight: bold;">require 'example'</span><br>=> true<br><br>irb(main):003:0> <span style="font-weight: bold;">zoo = Example::Zoo.new()</span><br>=> #<Example::Zoo:0x2be0fe8><br><br>irb(main):005:0> <span style="font-weight: bold;">tiger1 = Example::Animal.new("tiger1")</span><br>=> #<Example::Animal:0x2bda760><br><br>irb(main):006:0> <span style="font-weight: bold;">zoo.add_animal(tiger1)</span><br>=> nil<br><br>irb(main):007:0> <span style="font-weight: bold;">zoo = nil</span><br>=> nil<br><br>irb(main):008:0> <span style="font-weight: bold;">GC.start</span><br>=> nil<br><br>irb(main):009:0> <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></pre> | |
2267 | </div> | |
2268 | <p>Notice that SWIG can now detect the underlying C++ object has been freed, and | |
2269 | thus raises a runtime exception.</p> | |
2270 | <p>This code can be seen in swig/examples/ruby/free_function.</p> | |
2271 | </body> | |
2272 | </html> |