import source from 1.3.40
[external/swig.git] / Doc / Manual / SWIGDocumentation.html
1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
2 <HTML>
3 <HEAD>
4 <TITLE>SWIG-1.3 Documentation</TITLE>
5 <META HTTP-EQUIV="Content-Type" CONTENT="text/html; CHARSET=iso-iso-8859-1">
6 <STYLE TYPE="text/css"><!--
7 div.sectiontoc {
8   border-style: dotted;
9   border-width: 2px;
10   padding: 2pt;
11 }
12
13 h2 { 
14   padding: 3px;
15   color: #000000;
16   border-bottom: 2px 
17   solid #dddddd; 
18 }
19
20 h3, h4 {
21   margin-left: 1em;
22 }
23
24 p,li,table,dl {
25   margin-left: 2em;
26   margin-right: 2em;
27 }
28
29 div.indent {
30   margin-left: 4em;
31   margin-right: 4em;
32 }
33
34 div.code {
35   border-style: solid; 
36   border-width: 1px; 
37   padding: 2pt; 
38   margin-left: 4em;
39   margin-right: 4em;
40   background-color: #F0FFFF;
41 }
42
43 div.targetlang {
44   border-style: solid; 
45   border-width: 1px; 
46   padding: 2pt; 
47   margin-left: 4em;
48   margin-right: 4em;
49   background-color: #d7f6bb;
50 }
51
52
53 div.shell {
54   border-style: solid; 
55   border-width: 1px; 
56   padding: 2pt; 
57   margin-left: 4em;
58   margin-right: 4em;
59   background-color: #DCDCDC;
60 }
61
62 div.diagram {
63   border-style: solid; 
64   border-width: 1px; 
65   padding: 2pt; 
66   margin-left: 4em;
67   margin-right: 4em;
68   background-color: #FFEBCD;
69 }
70
71 ul li p {
72   margin-left: 0;
73   margin-right: 0;
74 }
75
76 ol li p {
77   margin-left: 0;
78   margin-right: 0;
79 }
80
81 dl dd p {
82   margin-left: 0;
83   margin-right: 0;
84 }
85
86 div.indent p {
87   margin-left: 0;
88   margin-right: 0;
89 }
90
91
92 BODY { font-family: serif }
93 H1 { font-family: sans-serif }
94 H2 { font-family: sans-serif }
95 H3 { font-family: sans-serif }
96 H4 { font-family: sans-serif }
97 H5 { font-family: sans-serif }
98 H6 { font-family: sans-serif }
99 SUB { font-size: smaller }
100 SUP { font-size: smaller }
101 PRE { font-family: monospace }
102 --></STYLE>
103 </HEAD>
104 <BODY BGCOLOR="#ffffff" LINK="#0000ff" VLINK="#0000ff" ALINK="#0000ff">
105 <CENTER><A HREF="#CONTENTS"><IMG SRC="swig16.png" BORDER="0" WIDTH="167" HEIGHT="85" ALT="SWIG-1.3 Documentation"><BR>
106 <H1>SWIG-1.3 Documentation</H1></A><BR>
107 </CENTER>
108 <HR NOSHADE>
109 <H1 ALIGN="CENTER"><A NAME="CONTENTS">Table of Contents</A></H1>
110 <BR>
111 <BR><B><A HREF="#Sections">SWIG-1.3 Development Documentation</A></B>
112 <UL>
113 <LI><A HREF="#1_1">Sections</A>
114 <UL>
115 <LI><A HREF="#1_1_1">SWIG Core Documentation</A></LI>
116 <LI><A HREF="#1_1_2">Language Module Documentation</A></LI>
117 <LI><A HREF="#1_1_3">Developer Documentation</A></LI>
118 <LI><A HREF="#1_1_4">Documentation that has not yet been updated</A></LI>
119 </UL>
120 </LI>
121 </UL>
122 <B><A HREF="#Preface">1 Preface</A></B>
123 <UL>
124 <LI><A HREF="#Preface_nn2">1.1 Introduction</A></LI>
125 <LI><A HREF="#Preface_nn3">1.2 Special Introduction for Version 1.3</A></LI>
126 <LI><A HREF="#Preface_nn4">1.3 SWIG Versions</A></LI>
127 <LI><A HREF="#Preface_nn5">1.4 SWIG resources</A></LI>
128 <LI><A HREF="#Preface_nn6">1.5 Prerequisites</A></LI>
129 <LI><A HREF="#Preface_nn7">1.6 Organization of this manual</A></LI>
130 <LI><A HREF="#Preface_nn8">1.7 How to avoid reading the manual</A></LI>
131 <LI><A HREF="#Preface_nn9">1.8 Backwards Compatibility</A></LI>
132 <LI><A HREF="#Preface_nn10">1.9 Credits</A></LI>
133 <LI><A HREF="#Preface_nn11">1.10 Bug reports</A></LI>
134 </UL>
135 <B><A HREF="#Introduction">2 Introduction</A></B>
136 <UL>
137 <LI><A HREF="#Introduction_nn2">2.1 What is SWIG?</A></LI>
138 <LI><A HREF="#Introduction_nn3">2.2 Why use SWIG?</A></LI>
139 <LI><A HREF="#Introduction_nn4">2.3 A SWIG example</A>
140 <UL>
141 <LI><A HREF="#Introduction_nn5">2.3.1 SWIG interface file</A></LI>
142 <LI><A HREF="#Introduction_nn6">2.3.2 The swig command</A></LI>
143 <LI><A HREF="#Introduction_nn7">2.3.3 Building a Perl5 module</A></LI>
144 <LI><A HREF="#Introduction_nn8">2.3.4 Building a Python module</A></LI>
145 <LI><A HREF="#Introduction_nn9">2.3.5 Shortcuts</A></LI>
146 </UL>
147 </LI>
148 <LI><A HREF="#Introduction_nn10">2.4 Supported C/C++ language features</A>
149 </LI>
150 <LI><A HREF="#Introduction_nn11">2.5 Non-intrusive interface building</A>
151 </LI>
152 <LI><A HREF="#Introduction_build_system">2.6 Incorporating SWIG into a
153  build system</A></LI>
154 <LI><A HREF="#Introduction_nn12">2.7 Hands off code generation</A></LI>
155 <LI><A HREF="#Introduction_nn13">2.8 SWIG and freedom</A></LI>
156 </UL>
157 <B><A HREF="#Windows">3 Getting started on Windows</A></B>
158 <UL>
159 <LI><A HREF="#Windows_installation">3.1 Installation on Windows</A>
160 <UL>
161 <LI><A HREF="#Windows_executable">3.1.1 Windows Executable</A></LI>
162 </UL>
163 </LI>
164 <LI><A HREF="#Windows_examples">3.2 SWIG Windows Examples</A>
165 <UL>
166 <LI><A HREF="#Windows_visual_studio">3.2.1 Instructions for using the
167  Examples with Visual Studio</A>
168 <UL>
169 <LI><A HREF="#Windows_csharp">3.2.1.1 C#</A></LI>
170 <LI><A HREF="#Windows_java">3.2.1.2 Java</A></LI>
171 <LI><A HREF="#Windows_perl">3.2.1.3 Perl</A></LI>
172 <LI><A HREF="#Windows_python">3.2.1.4 Python</A></LI>
173 <LI><A HREF="#Windows_tcl">3.2.1.5 TCL</A></LI>
174 <LI><A HREF="#Windows_r">3.2.1.6 R</A></LI>
175 <LI><A HREF="#Windows_ruby">3.2.1.7 Ruby</A></LI>
176 </UL>
177 </LI>
178 <LI><A HREF="#Windows_other_compilers">3.2.2 Instructions for using the
179  Examples with other compilers</A></LI>
180 </UL>
181 </LI>
182 <LI><A HREF="#Windows_cygwin_mingw">3.3 SWIG on Cygwin and MinGW</A>
183 <UL>
184 <LI><A HREF="#Windows_swig_exe">3.3.1 Building swig.exe on Windows</A>
185 <UL>
186 <LI><A HREF="#Windows_mingw_msys">3.3.1.1 Building swig.exe using MinGW
187  and MSYS</A></LI>
188 <LI><A HREF="#Windows_cygwin">3.3.1.2 Building swig.exe using Cygwin</A></LI>
189 <LI><A HREF="#Windows_building_alternatives">3.3.1.3 Building swig.exe
190  alternatives</A></LI>
191 </UL>
192 </LI>
193 <LI><A HREF="#Windows_examples_cygwin">3.3.2 Running the examples on
194  Windows using Cygwin</A></LI>
195 </UL>
196 </LI>
197 <LI><A HREF="#Windows_interface_file">3.4 Microsoft extensions and other
198  Windows quirks</A></LI>
199 </UL>
200 <B><A HREF="#Scripting">4 Scripting Languages</A></B>
201 <UL>
202 <LI><A HREF="#Scripting_nn2">4.1 The two language view of the world</A></LI>
203 <LI><A HREF="#Scripting_nn3">4.2 How does a scripting language talk to
204  C?</A>
205 <UL>
206 <LI><A HREF="#Scripting_nn4">4.2.1 Wrapper functions</A></LI>
207 <LI><A HREF="#Scripting_nn5">4.2.2 Variable linking</A></LI>
208 <LI><A HREF="#Scripting_nn6">4.2.3 Constants</A></LI>
209 <LI><A HREF="#Scripting_nn7">4.2.4 Structures and classes</A></LI>
210 <LI><A HREF="#Scripting_nn8">4.2.5 Proxy classes</A></LI>
211 </UL>
212 </LI>
213 <LI><A HREF="#Scripting_nn9">4.3 Building scripting language extensions</A>
214 <UL>
215 <LI><A HREF="#Scripting_nn10">4.3.1 Shared libraries and dynamic loading</A>
216 </LI>
217 <LI><A HREF="#Scripting_nn11">4.3.2 Linking with shared libraries</A></LI>
218 <LI><A HREF="#Scripting_nn12">4.3.3 Static linking</A></LI>
219 </UL>
220 </LI>
221 </UL>
222 <B><A HREF="#SWIG">5 SWIG Basics</A></B>
223 <UL>
224 <LI><A HREF="#SWIG_nn2">5.1 Running SWIG</A>
225 <UL>
226 <LI><A HREF="#SWIG_nn3">5.1.1 Input format</A></LI>
227 <LI><A HREF="#output">5.1.2 SWIG Output</A></LI>
228 <LI><A HREF="#SWIG_nn5">5.1.3 Comments</A></LI>
229 <LI><A HREF="#SWIG_nn6">5.1.4 C Preprocessor</A></LI>
230 <LI><A HREF="#SWIG_nn7">5.1.5 SWIG Directives</A></LI>
231 <LI><A HREF="#SWIG_nn8">5.1.6 Parser Limitations</A></LI>
232 </UL>
233 </LI>
234 <LI><A HREF="#SWIG_nn9">5.2 Wrapping Simple C Declarations</A>
235 <UL>
236 <LI><A HREF="#SWIG_nn10">5.2.1 Basic Type Handling</A></LI>
237 <LI><A HREF="#SWIG_nn11">5.2.2 Global Variables</A></LI>
238 <LI><A HREF="#SWIG_nn12">5.2.3 Constants</A></LI>
239 <LI><A HREF="#SWIG_nn13">5.2.4 A brief word about const</A></LI>
240 <LI><A HREF="#SWIG_nn14">5.2.5 A cautionary tale of char *</A></LI>
241 </UL>
242 </LI>
243 <LI><A HREF="#SWIG_nn15">5.3 Pointers and complex objects</A>
244 <UL>
245 <LI><A HREF="#SWIG_nn16">5.3.1 Simple pointers</A></LI>
246 <LI><A HREF="#SWIG_nn17">5.3.2 Run time pointer type checking</A></LI>
247 <LI><A HREF="#SWIG_nn18">5.3.3 Derived types, structs, and classes</A></LI>
248 <LI><A HREF="#SWIG_nn19">5.3.4 Undefined datatypes</A></LI>
249 <LI><A HREF="#SWIG_nn20">5.3.5 Typedef</A></LI>
250 </UL>
251 </LI>
252 <LI><A HREF="#SWIG_nn21">5.4 Other Practicalities</A>
253 <UL>
254 <LI><A HREF="#SWIG_nn22">5.4.1 Passing structures by value</A></LI>
255 <LI><A HREF="#SWIG_nn23">5.4.2 Return by value</A></LI>
256 <LI><A HREF="#SWIG_nn24">5.4.3 Linking to structure variables</A></LI>
257 <LI><A HREF="#SWIG_nn25">5.4.4 Linking to char *</A></LI>
258 <LI><A HREF="#SWIG_nn26">5.4.5 Arrays</A></LI>
259 <LI><A HREF="#SWIG_readonly_variables">5.4.6 Creating read-only
260  variables</A></LI>
261 <LI><A HREF="#SWIG_rename_ignore">5.4.7 Renaming and ignoring
262  declarations</A></LI>
263 <LI><A HREF="#SWIG_default_args">5.4.8 Default/optional arguments</A></LI>
264 <LI><A HREF="#SWIG_nn30">5.4.9 Pointers to functions and callbacks</A></LI>
265 </UL>
266 </LI>
267 <LI><A HREF="#SWIG_nn31">5.5 Structures and unions</A>
268 <UL>
269 <LI><A HREF="#SWIG_nn32">5.5.1 Typedef and structures</A></LI>
270 <LI><A HREF="#SWIG_nn33">5.5.2 Character strings and structures</A></LI>
271 <LI><A HREF="#SWIG_nn34">5.5.3 Array members</A></LI>
272 <LI><A HREF="#SWIG_structure_data_members">5.5.4 Structure data members</A>
273 </LI>
274 <LI><A HREF="#SWIG_nn36">5.5.5 C constructors and destructors</A></LI>
275 <LI><A HREF="#SWIG_adding_member_functions">5.5.6 Adding member
276  functions to C structures</A></LI>
277 <LI><A HREF="#SWIG_nested_structs">5.5.7 Nested structures</A></LI>
278 <LI><A HREF="#SWIG_nn39">5.5.8 Other things to note about structure
279  wrapping</A></LI>
280 </UL>
281 </LI>
282 <LI><A HREF="#SWIG_nn40">5.6 Code Insertion</A>
283 <UL>
284 <LI><A HREF="#SWIG_nn41">5.6.1 The output of SWIG</A></LI>
285 <LI><A HREF="#SWIG_nn42">5.6.2 Code insertion blocks</A></LI>
286 <LI><A HREF="#SWIG_nn43">5.6.3 Inlined code blocks</A></LI>
287 <LI><A HREF="#SWIG_nn44">5.6.4 Initialization blocks</A></LI>
288 </UL>
289 </LI>
290 <LI><A HREF="#SWIG_nn45">5.7 An Interface Building Strategy</A>
291 <UL>
292 <LI><A HREF="#SWIG_nn46">5.7.1 Preparing a C program for SWIG</A></LI>
293 <LI><A HREF="#SWIG_nn47">5.7.2 The SWIG interface file</A></LI>
294 <LI><A HREF="#SWIG_nn48">5.7.3 Why use separate interface files?</A></LI>
295 <LI><A HREF="#SWIG_nn49">5.7.4 Getting the right header files</A></LI>
296 <LI><A HREF="#SWIG_nn50">5.7.5 What to do with main()</A></LI>
297 </UL>
298 </LI>
299 </UL>
300 <B><A HREF="#SWIGPlus">6 SWIG and C++</A></B>
301 <UL>
302 <LI><A HREF="#SWIGPlus_nn2">6.1 Comments on C++ Wrapping</A></LI>
303 <LI><A HREF="#SWIGPlus_nn3">6.2 Approach</A></LI>
304 <LI><A HREF="#SWIGPlus_nn4">6.3 Supported C++ features</A></LI>
305 <LI><A HREF="#SWIGPlus_nn5">6.4 Command line options and compilation</A></LI>
306 <LI><A HREF="#SWIGPlus_nn38">6.5 Proxy classes</A>
307 <UL>
308 <LI><A HREF="#SWIGPlus_nn39">6.5.1 Construction of proxy classes</A></LI>
309 <LI><A HREF="#SWIGPlus_nn40">6.5.2 Resource management in proxies</A></LI>
310 <LI><A HREF="#SWIGPlus_nn41">6.5.3 Language specific details</A></LI>
311 </UL>
312 </LI>
313 <LI><A HREF="#SWIGPlus_nn6">6.6 Simple C++ wrapping</A>
314 <UL>
315 <LI><A HREF="#SWIGPlus_nn7">6.6.1 Constructors and destructors</A></LI>
316 <LI><A HREF="#SWIGPlus_nn8">6.6.2 Default constructors, copy
317  constructors and implicit destructors</A></LI>
318 <LI><A HREF="#SWIGPlus_nn9">6.6.3 When constructor wrappers aren't
319  created</A></LI>
320 <LI><A HREF="#SWIGPlus_nn10">6.6.4 Copy constructors</A></LI>
321 <LI><A HREF="#SWIGPlus_nn11">6.6.5 Member functions</A></LI>
322 <LI><A HREF="#SWIGPlus_nn12">6.6.6 Static members</A></LI>
323 <LI><A HREF="#SWIGPlus_member_data">6.6.7 Member data</A></LI>
324 </UL>
325 </LI>
326 <LI><A HREF="#SWIGPlus_default_args">6.7 Default arguments</A></LI>
327 <LI><A HREF="#SWIGPlus_nn15">6.8 Protection</A></LI>
328 <LI><A HREF="#SWIGPlus_nn16">6.9 Enums and constants</A></LI>
329 <LI><A HREF="#SWIGPlus_nn17">6.10 Friends</A></LI>
330 <LI><A HREF="#SWIGPlus_nn18">6.11 References and pointers</A></LI>
331 <LI><A HREF="#SWIGPlus_nn19">6.12 Pass and return by value</A></LI>
332 <LI><A HREF="#SWIGPlus_nn20">6.13 Inheritance</A></LI>
333 <LI><A HREF="#SWIGPlus_nn21">6.14 A brief discussion of multiple
334  inheritance, pointers, and type checking</A></LI>
335 <LI><A HREF="#SWIGPlus_overloaded_methods">6.15 Wrapping Overloaded
336  Functions and Methods</A>
337 <UL>
338 <LI><A HREF="#SWIGPlus_nn24">6.15.1 Dispatch function generation</A></LI>
339 <LI><A HREF="#SWIGPlus_nn25">6.15.2 Ambiguity in Overloading</A></LI>
340 <LI><A HREF="#ambiguity_resolution_renaming">6.15.3 Ambiguity resolution
341  and renaming</A></LI>
342 <LI><A HREF="#SWIGPlus_nn27">6.15.4 Comments on overloading</A></LI>
343 </UL>
344 </LI>
345 <LI><A HREF="#SWIGPlus_nn28">6.16 Wrapping overloaded operators</A></LI>
346 <LI><A HREF="#SWIGPlus_class_extension">6.17 Class extension</A></LI>
347 <LI><A HREF="#SWIGPlus_nn30">6.18 Templates</A></LI>
348 <LI><A HREF="#SWIGPlus_nn31">6.19 Namespaces</A></LI>
349 <LI><A HREF="#SWIGPlus_renaming_templated_types_namespaces">6.20
350  Renaming templated types in namespaces</A></LI>
351 <LI><A HREF="#SWIGPlus_exception_specifications">6.21 Exception
352  specifications</A></LI>
353 <LI><A HREF="#SWIGPlus_catches">6.22 Exception handling with %catches</A>
354 </LI>
355 <LI><A HREF="#SWIGPlus_nn33">6.23 Pointers to Members</A></LI>
356 <LI><A HREF="#SWIGPlus_nn34">6.24 Smart pointers and operator-&gt;()</A></LI>
357 <LI><A HREF="#SWIGPlus_nn35">6.25 Using declarations and inheritance</A></LI>
358 <LI><A HREF="#SWIGPlus_nested_classes">6.26 Nested classes</A></LI>
359 <LI><A HREF="#SWIGPlus_nn37">6.27 A brief rant about const-correctness</A>
360 </LI>
361 <LI><A HREF="#SWIGPlus_nn42">6.28 Where to go for more information</A></LI>
362 </UL>
363 <B><A HREF="#Preprocessor">7 Preprocessing</A></B>
364 <UL>
365 <LI><A HREF="#Preprocessor_nn2">7.1 File inclusion</A></LI>
366 <LI><A HREF="#Preprocessor_nn3">7.2 File imports</A></LI>
367 <LI><A HREF="#Preprocessor_condition_compilation">7.3 Conditional
368  Compilation</A></LI>
369 <LI><A HREF="#Preprocessor_nn5">7.4 Macro Expansion</A></LI>
370 <LI><A HREF="#Preprocessor_nn6">7.5 SWIG Macros</A></LI>
371 <LI><A HREF="#Preprocessor_nn7">7.6 C99 and GNU Extensions</A></LI>
372 <LI><A HREF="#Preprocessor_nn8">7.7 Preprocessing and %{ ... %} &amp; &quot; ...
373  &quot; delimiters</A></LI>
374 <LI><A HREF="#Preprocessor_nn9">7.8 Preprocessing and { ... } delimiters</A>
375 </LI>
376 <LI><A HREF="#Preprocessor_typemap_delimiters">7.9 Preprocessor and
377  Typemaps</A></LI>
378 <LI><A HREF="#Preprocessor_nn10">7.10 Viewing preprocessor output</A></LI>
379 <LI><A HREF="#Preprocessor_warning_error">7.11 The #error and #warning
380  directives</A></LI>
381 </UL>
382 <B><A HREF="#Library">8 SWIG library</A></B>
383 <UL>
384 <LI><A HREF="#Library_nn2">8.1 The %include directive and library search
385  path</A></LI>
386 <LI><A HREF="#Library_nn3">8.2 C Arrays and Pointers</A>
387 <UL>
388 <LI><A HREF="#Library_nn4">8.2.1 cpointer.i</A></LI>
389 <LI><A HREF="#Library_carrays">8.2.2 carrays.i</A></LI>
390 <LI><A HREF="#Library_nn6">8.2.3 cmalloc.i</A></LI>
391 <LI><A HREF="#Library_nn7">8.2.4 cdata.i</A></LI>
392 </UL>
393 </LI>
394 <LI><A HREF="#Library_nn8">8.3 C String Handling</A>
395 <UL>
396 <LI><A HREF="#Library_nn9">8.3.1 Default string handling</A></LI>
397 <LI><A HREF="#Library_nn10">8.3.2 Passing binary data</A></LI>
398 <LI><A HREF="#Library_nn11">8.3.3 Using %newobject to release memory</A></LI>
399 <LI><A HREF="#Library_nn12">8.3.4 cstring.i</A></LI>
400 </UL>
401 </LI>
402 <LI><A HREF="#Library_stl_cpp_library">8.4 STL/C++ Library</A>
403 <UL>
404 <LI><A HREF="#Library_nn14">8.4.1 std_string.i</A></LI>
405 <LI><A HREF="#Library_nn15">8.4.2 std_vector.i</A></LI>
406 <LI><A HREF="#Library_stl_exceptions">8.4.3 STL exceptions</A></LI>
407 </UL>
408 </LI>
409 <LI><A HREF="#Library_nn16">8.5 Utility Libraries</A>
410 <UL>
411 <LI><A HREF="#Library_nn17">8.5.1 exception.i</A></LI>
412 </UL>
413 </LI>
414 </UL>
415 <B><A HREF="#Arguments">9 Argument Handling</A></B>
416 <UL>
417 <LI><A HREF="#Arguments_nn2">9.1 The typemaps.i library</A>
418 <UL>
419 <LI><A HREF="#Arguments_nn3">9.1.1 Introduction</A></LI>
420 <LI><A HREF="#Arguments_nn4">9.1.2 Input parameters</A></LI>
421 <LI><A HREF="#Arguments_nn5">9.1.3 Output parameters</A></LI>
422 <LI><A HREF="#Arguments_nn6">9.1.4 Input/Output parameters</A></LI>
423 <LI><A HREF="#Arguments_nn7">9.1.5 Using different names</A></LI>
424 </UL>
425 </LI>
426 <LI><A HREF="#Arguments_nn8">9.2 Applying constraints to input values</A>
427 <UL>
428 <LI><A HREF="#Arguments_nn9">9.2.1 Simple constraint example</A></LI>
429 <LI><A HREF="#Arguments_nn10">9.2.2 Constraint methods</A></LI>
430 <LI><A HREF="#Arguments_nn11">9.2.3 Applying constraints to new
431  datatypes</A></LI>
432 </UL>
433 </LI>
434 </UL>
435 <B><A HREF="#Typemaps">10 Typemaps</A></B>
436 <UL>
437 <LI><A HREF="#Typemaps_nn2">10.1 Introduction</A>
438 <UL>
439 <LI><A HREF="#Typemaps_nn3">10.1.1 Type conversion</A></LI>
440 <LI><A HREF="#Typemaps_nn4">10.1.2 Typemaps</A></LI>
441 <LI><A HREF="#Typemaps_nn5">10.1.3 Pattern matching</A></LI>
442 <LI><A HREF="#Typemaps_nn6">10.1.4 Reusing typemaps</A></LI>
443 <LI><A HREF="#Typemaps_nn7">10.1.5 What can be done with typemaps?</A></LI>
444 <LI><A HREF="#Typemaps_nn8">10.1.6 What can't be done with typemaps?</A></LI>
445 <LI><A HREF="#Typemaps_nn9">10.1.7 The rest of this chapter</A></LI>
446 </UL>
447 </LI>
448 <LI><A HREF="#Typemaps_nn10">10.2 Typemap specifications</A>
449 <UL>
450 <LI><A HREF="#Typemaps_defining">10.2.1 Defining a typemap</A></LI>
451 <LI><A HREF="#Typemaps_nn12">10.2.2 Typemap scope</A></LI>
452 <LI><A HREF="#Typemaps_nn13">10.2.3 Copying a typemap</A></LI>
453 <LI><A HREF="#Typemaps_nn14">10.2.4 Deleting a typemap</A></LI>
454 <LI><A HREF="#Typemaps_nn15">10.2.5 Placement of typemaps</A></LI>
455 </UL>
456 </LI>
457 <LI><A HREF="#Typemaps_pattern_matching">10.3 Pattern matching rules</A>
458 <UL>
459 <LI><A HREF="#Typemaps_nn17">10.3.1 Basic matching rules</A></LI>
460 <LI><A HREF="#Typemaps_nn18">10.3.2 Typedef reductions</A></LI>
461 <LI><A HREF="#Typemaps_nn19">10.3.3 Default typemaps</A></LI>
462 <LI><A HREF="#Typemaps_mixed_default">10.3.4 Mixed default typemaps</A></LI>
463 <LI><A HREF="#Typemaps_nn20">10.3.5 Multi-arguments typemaps</A></LI>
464 </UL>
465 </LI>
466 <LI><A HREF="#Typemaps_nn21">10.4 Code generation rules</A>
467 <UL>
468 <LI><A HREF="#Typemaps_nn22">10.4.1 Scope</A></LI>
469 <LI><A HREF="#Typemaps_nn23">10.4.2 Declaring new local variables</A></LI>
470 <LI><A HREF="#Typemaps_special_variables">10.4.3 Special variables</A></LI>
471 <LI><A HREF="#Typemaps_special_variable_macros">10.4.4 Special variable
472  macros</A>
473 <UL>
474 <LI><A HREF="#Typemaps_special_macro_descriptor">10.4.4.1
475  $descriptor(type)</A></LI>
476 <LI><A HREF="#Typemaps_special_macro_typemap">10.4.4.2 $typemap(method,
477  typepattern)</A></LI>
478 </UL>
479 </LI>
480 </UL>
481 </LI>
482 <LI><A HREF="#Typemaps_nn25">10.5 Common typemap methods</A>
483 <UL>
484 <LI><A HREF="#Typemaps_nn26">10.5.1 &quot;in&quot; typemap</A></LI>
485 <LI><A HREF="#Typemaps_nn27">10.5.2 &quot;typecheck&quot; typemap</A></LI>
486 <LI><A HREF="#Typemaps_nn28">10.5.3 &quot;out&quot; typemap</A></LI>
487 <LI><A HREF="#Typemaps_nn29">10.5.4 &quot;arginit&quot; typemap</A></LI>
488 <LI><A HREF="#Typemaps_nn30">10.5.5 &quot;default&quot; typemap</A></LI>
489 <LI><A HREF="#Typemaps_nn31">10.5.6 &quot;check&quot; typemap</A></LI>
490 <LI><A HREF="#Typemaps_nn32">10.5.7 &quot;argout&quot; typemap</A></LI>
491 <LI><A HREF="#Typemaps_nn33">10.5.8 &quot;freearg&quot; typemap</A></LI>
492 <LI><A HREF="#Typemaps_nn34">10.5.9 &quot;newfree&quot; typemap</A></LI>
493 <LI><A HREF="#Typemaps_nn35">10.5.10 &quot;memberin&quot; typemap</A></LI>
494 <LI><A HREF="#Typemaps_nn36">10.5.11 &quot;varin&quot; typemap</A></LI>
495 <LI><A HREF="#Typemaps_nn37">10.5.12 &quot;varout&quot; typemap</A></LI>
496 <LI><A HREF="#throws_typemap">10.5.13 &quot;throws&quot; typemap</A></LI>
497 </UL>
498 </LI>
499 <LI><A HREF="#Typemaps_nn39">10.6 Some typemap examples</A>
500 <UL>
501 <LI><A HREF="#Typemaps_nn40">10.6.1 Typemaps for arrays</A></LI>
502 <LI><A HREF="#Typemaps_nn41">10.6.2 Implementing constraints with
503  typemaps</A></LI>
504 </UL>
505 </LI>
506 <LI><A HREF="#Typemaps_nn43">10.7 Typemaps for multiple languages</A></LI>
507 <LI><A HREF="#Typemaps_optimal">10.8 Optimal code generation when
508  returning by value</A></LI>
509 <LI><A HREF="#Typemaps_multi_argument_typemaps">10.9 Multi-argument
510  typemaps</A></LI>
511 <LI><A HREF="#runtime_type_checker">10.10 The run-time type checker</A>
512 <UL>
513 <LI><A HREF="#Typemaps_nn45">10.10.1 Implementation</A></LI>
514 <LI><A HREF="#Typemaps_runtime_type_checker_usage">10.10.2 Usage</A></LI>
515 </UL>
516 </LI>
517 <LI><A HREF="#Typemaps_overloading">10.11 Typemaps and overloading</A></LI>
518 <LI><A HREF="#Typemaps_nn48">10.12 More about %apply and %clear</A></LI>
519 <LI><A HREF="#Typemaps_nn49">10.13 Reducing wrapper code size</A></LI>
520 <LI><A HREF="#Typemaps_nn47">10.14 Passing data between typemaps</A></LI>
521 <LI><A HREF="#Typemaps_nn52">10.15 C++ &quot;this&quot; pointer</A></LI>
522 <LI><A HREF="#Typemaps_nn51">10.16 Where to go for more information?</A></LI>
523 </UL>
524 <B><A HREF="#Customization">11 Customization Features</A></B>
525 <UL>
526 <LI><A HREF="#exception">11.1 Exception handling with %exception</A>
527 <UL>
528 <LI><A HREF="#Customization_nn3">11.1.1 Handling exceptions in C code</A>
529 </LI>
530 <LI><A HREF="#Customization_nn4">11.1.2 Exception handling with
531  longjmp()</A></LI>
532 <LI><A HREF="#Customization_nn5">11.1.3 Handling C++ exceptions</A></LI>
533 <LI><A HREF="#Customization_allowexcept">11.1.4 Exception handlers for
534  variables</A></LI>
535 <LI><A HREF="#Customization_nn6">11.1.5 Defining different exception
536  handlers</A></LI>
537 <LI><A HREF="#Customization_exception_special_variables">11.1.6 Special
538  variables for %exception</A></LI>
539 <LI><A HREF="#Customization_nn7">11.1.7 Using The SWIG exception library</A>
540 </LI>
541 </UL>
542 </LI>
543 <LI><A HREF="#ownership">11.2 Object ownership and %newobject</A></LI>
544 <LI><A HREF="#features">11.3 Features and the %feature directive</A>
545 <UL>
546 <LI><A HREF="#Customization_feature_attributes">11.3.1 Feature
547  attributes</A></LI>
548 <LI><A HREF="#Customization_feature_flags">11.3.2 Feature flags</A></LI>
549 <LI><A HREF="#Customization_clearing_features">11.3.3 Clearing features</A>
550 </LI>
551 <LI><A HREF="#Customization_features_default_args">11.3.4 Features and
552  default arguments</A></LI>
553 <LI><A HREF="#features_example">11.3.5 Feature example</A></LI>
554 </UL>
555 </LI>
556 </UL>
557 <B><A HREF="#Contract">12 Contracts</A></B>
558 <UL>
559 <LI><A HREF="#Contract_nn2">12.1 The %contract directive</A></LI>
560 <LI><A HREF="#Contract_nn3">12.2 %contract and classes</A></LI>
561 <LI><A HREF="#Contract_nn4">12.3 Constant aggregation and
562  %aggregate_check</A></LI>
563 <LI><A HREF="#Contract_nn5">12.4 Notes</A></LI>
564 </UL>
565 <B><A HREF="#Varargs">13 Variable Length Arguments</A></B>
566 <UL>
567 <LI><A HREF="#Varargs_nn2">13.1 Introduction</A></LI>
568 <LI><A HREF="#Varargs_nn3">13.2 The Problem</A></LI>
569 <LI><A HREF="#Varargs_nn4">13.3 Default varargs support</A></LI>
570 <LI><A HREF="#Varargs_nn5">13.4 Argument replacement using %varargs</A></LI>
571 <LI><A HREF="#Varargs_nn6">13.5 Varargs and typemaps</A></LI>
572 <LI><A HREF="#Varargs_nn7">13.6 Varargs wrapping with libffi</A></LI>
573 <LI><A HREF="#Varargs_nn8">13.7 Wrapping of va_list</A></LI>
574 <LI><A HREF="#Varargs_nn9">13.8 C++ Issues</A></LI>
575 <LI><A HREF="#Varargs_nn10">13.9 Discussion</A></LI>
576 </UL>
577 <B><A HREF="#Warnings">14 Warning Messages</A></B>
578 <UL>
579 <LI><A HREF="#Warnings_nn2">14.1 Introduction</A></LI>
580 <LI><A HREF="#Warnings_suppression">14.2 Warning message suppression</A></LI>
581 <LI><A HREF="#Warnings_nn4">14.3 Enabling extra warnings</A></LI>
582 <LI><A HREF="#Warnings_nn5">14.4 Issuing a warning message</A></LI>
583 <LI><A HREF="#Warnings_symbolic_symbols">14.5 Symbolic symbols</A></LI>
584 <LI><A HREF="#Warnings_nn6">14.6 Commentary</A></LI>
585 <LI><A HREF="#Warnings_nn7">14.7 Warnings as errors</A></LI>
586 <LI><A HREF="#Warnings_nn8">14.8 Message output format</A></LI>
587 <LI><A HREF="#Warnings_nn9">14.9 Warning number reference</A>
588 <UL>
589 <LI><A HREF="#Warnings_nn10">14.9.1 Deprecated features (100-199)</A></LI>
590 <LI><A HREF="#Warnings_nn11">14.9.2 Preprocessor (200-299)</A></LI>
591 <LI><A HREF="#Warnings_nn12">14.9.3 C/C++ Parser (300-399)</A></LI>
592 <LI><A HREF="#Warnings_nn13">14.9.4 Types and typemaps (400-499)</A></LI>
593 <LI><A HREF="#Warnings_nn14">14.9.5 Code generation (500-599)</A></LI>
594 <LI><A HREF="#Warnings_nn15">14.9.6 Language module specific (800-899)</A>
595 </LI>
596 <LI><A HREF="#Warnings_nn16">14.9.7 User defined (900-999)</A></LI>
597 </UL>
598 </LI>
599 <LI><A HREF="#Warnings_nn17">14.10 History</A></LI>
600 </UL>
601 <B><A HREF="#Modules">15 Working with Modules</A></B>
602 <UL>
603 <LI><A HREF="#Modules_introduction">15.1 Modules Introduction</A></LI>
604 <LI><A HREF="#Modules_nn1">15.2 Basics</A></LI>
605 <LI><A HREF="#Modules_nn2">15.3 The SWIG runtime code</A></LI>
606 <LI><A HREF="#external_run_time">15.4 External access to the runtime</A></LI>
607 <LI><A HREF="#Modules_nn4">15.5 A word of caution about static libraries</A>
608 </LI>
609 <LI><A HREF="#Modules_nn5">15.6 References</A></LI>
610 <LI><A HREF="#Modules_nn6">15.7 Reducing the wrapper file size</A></LI>
611 </UL>
612 <B><A HREF="#CCache">16 Using SWIG with ccache - ccache-swig(1) manpage</A>
613 </B>
614 <UL>
615 <LI><A HREF="#CCache_nn2">16.1 NAME</A></LI>
616 <LI><A HREF="#CCache_nn3">16.2 SYNOPSIS</A></LI>
617 <LI><A HREF="#CCache_nn4">16.3 DESCRIPTION</A></LI>
618 <LI><A HREF="#CCache_nn5">16.4 OPTIONS SUMMARY</A></LI>
619 <LI><A HREF="#CCache_nn6">16.5 OPTIONS</A></LI>
620 <LI><A HREF="#CCache_nn7">16.6 INSTALLATION</A></LI>
621 <LI><A HREF="#CCache_nn8">16.7 EXTRA OPTIONS</A></LI>
622 <LI><A HREF="#CCache_nn9">16.8 ENVIRONMENT VARIABLES</A></LI>
623 <LI><A HREF="#CCache_nn10">16.9 CACHE SIZE MANAGEMENT</A></LI>
624 <LI><A HREF="#CCache_nn11">16.10 CACHE COMPRESSION</A></LI>
625 <LI><A HREF="#CCache_nn12">16.11 HOW IT WORKS</A></LI>
626 <LI><A HREF="#CCache_nn13">16.12 USING CCACHE WITH DISTCC</A></LI>
627 <LI><A HREF="#CCache_nn14">16.13 SHARING A CACHE</A></LI>
628 <LI><A HREF="#CCache_nn15">16.14 HISTORY</A></LI>
629 <LI><A HREF="#CCache_nn16">16.15 DIFFERENCES FROM COMPILERCACHE</A></LI>
630 <LI><A HREF="#CCache_nn17">16.16 CREDITS</A></LI>
631 <LI><A HREF="#CCache_nn18">16.17 AUTHOR</A></LI>
632 </UL>
633 <B><A HREF="#Allegrocl_nn1">17 SWIG and Allegro Common Lisp</A></B>
634 <UL>
635 <LI><A HREF="#Allegrocl_nn2">17.1 Basics</A>
636 <UL>
637 <LI><A HREF="#Allegrocl_nn3">17.1.1 Running Swig</A></LI>
638 <LI><A HREF="#Allegrocl_nn4">17.1.2 Command Line Options</A></LI>
639 <LI><A HREF="#Allegrocl_nn5">17.1.3 Inserting user code into generated
640  files</A></LI>
641 </UL>
642 </LI>
643 <LI><A HREF="#Allegrocl_nn6">17.2 Wrapping Overview</A>
644 <UL>
645 <LI><A HREF="#Allegrocl_nn7">17.2.1 Function Wrapping</A></LI>
646 <LI><A HREF="#Allegrocl_nn8">17.2.2 Foreign Wrappers</A></LI>
647 <LI><A HREF="#Allegrocl_nn9">17.2.3 FFI Wrappers</A></LI>
648 <LI><A HREF="#Allegrocl_nn10">17.2.4 Non-overloaded Defuns</A></LI>
649 <LI><A HREF="#Allegrocl_nn11">17.2.5 Overloaded Defuns</A></LI>
650 <LI><A HREF="#Allegrocl_nn12">17.2.6 What about constant and variable
651  access?</A></LI>
652 <LI><A HREF="#Allegrocl_nn13">17.2.7 Object Wrapping</A></LI>
653 </UL>
654 </LI>
655 <LI><A HREF="#Allegrocl_nn14">17.3 Wrapping Details</A>
656 <UL>
657 <LI><A HREF="#Allegrocl_nn15">17.3.1 Namespaces</A></LI>
658 <LI><A HREF="#Allegrocl_nn16">17.3.2 Constants</A></LI>
659 <LI><A HREF="#Allegrocl_nn17">17.3.3 Variables</A></LI>
660 <LI><A HREF="#Allegrocl_nn18">17.3.4 Enumerations</A></LI>
661 <LI><A HREF="#Allegrocl_nn19">17.3.5 Arrays</A></LI>
662 <LI><A HREF="#Allegrocl_nn20">17.3.6 Classes and Structs and Unions (oh
663  my!)</A>
664 <UL>
665 <LI><A HREF="#Allegrocl_nn21">17.3.6.1 CLOS wrapping of</A></LI>
666 <LI><A HREF="#Allegrocl_nn22">17.3.6.2 CLOS Inheritance</A></LI>
667 <LI><A HREF="#Allegrocl_nn23">17.3.6.3 Member fields and functions</A></LI>
668 <LI><A HREF="#Allegrocl_nn24">17.3.6.4 Why not directly access C++
669  classes using foreign types?</A></LI>
670 </UL>
671 </LI>
672 <LI><A HREF="#Allegrocl_nn25">17.3.7 Templates</A>
673 <UL>
674 <LI><A HREF="#Allegrocl_nn26">17.3.7.1 Generating wrapper code for
675  templates</A></LI>
676 <LI><A HREF="#Allegrocl_nn27">17.3.7.2 Implicit Template instantiation</A>
677 </LI>
678 </UL>
679 </LI>
680 <LI><A HREF="#Allegrocl_nn28">17.3.8 Typedef, Templates, and Synonym
681  Types</A>
682 <UL>
683 <LI><A HREF="#Allegrocl_nn29">17.3.8.1 Choosing a primary type</A></LI>
684 </UL>
685 </LI>
686 <LI><A HREF="#Allegrocl_nn30">17.3.9 Function overloading/Parameter
687  defaulting</A></LI>
688 <LI><A HREF="#Allegrocl_nn31">17.3.10 Operator wrapping and Operator
689  overloading</A></LI>
690 <LI><A HREF="#Allegrocl_nn32">17.3.11 Varargs</A></LI>
691 <LI><A HREF="#Allegrocl_nn33">17.3.12 C++ Exceptions</A></LI>
692 <LI><A HREF="#Allegrocl_nn34">17.3.13 Pass by value, pass by reference</A>
693 </LI>
694 </UL>
695 </LI>
696 <LI><A HREF="#Allegrocl_nn35">17.4 Typemaps</A>
697 <UL>
698 <LI><A HREF="#Allegrocl_nn36">17.4.1 Code Generation in the C++ Wrapper</A>
699 <UL>
700 <LI><A HREF="#Allegrocl_nn37">17.4.1.1 IN Typemap</A></LI>
701 <LI><A HREF="#Allegrocl_nn38">17.4.1.2 OUT Typemap</A></LI>
702 <LI><A HREF="#Allegrocl_nn39">17.4.1.3 CTYPE Typemap</A></LI>
703 </UL>
704 </LI>
705 <LI><A HREF="#Allegrocl_nn40">17.4.2 Code generation in Lisp wrappers</A>
706 <UL>
707 <LI><A HREF="#Allegrocl_nn41">17.4.2.1 LIN Typemap</A></LI>
708 <LI><A HREF="#Allegrocl_nn42">17.4.2.2 LOUT Typemap</A></LI>
709 <LI><A HREF="#Allegrocl_nn43">17.4.2.3 FFITYPE Typemap</A></LI>
710 <LI><A HREF="#Allegrocl_nn44">17.4.2.4 LISPTYPE Typemap</A></LI>
711 <LI><A HREF="#Allegrocl_nn45">17.4.2.5 LISPCLASS Typemap</A></LI>
712 </UL>
713 </LI>
714 <LI><A HREF="#Allegrocl_nn46">17.4.3 Modifying SWIG behavior using
715  typemaps</A></LI>
716 </UL>
717 </LI>
718 <LI><A HREF="#Allegrocl_nn47">17.5 Identifier Converter functions</A>
719 <UL>
720 <LI><A HREF="#Allegrocl_nn48">17.5.1 Creating symbols in the lisp
721  environment</A></LI>
722 <LI><A HREF="#Allegrocl_nn49">17.5.2 Existing identifier-converter
723  functions</A>
724 <UL>
725 <LI><A HREF="#Allegrocl_nn50">17.5.2.1 identifier-convert-null</A></LI>
726 <LI><A HREF="#Allegrocl_nn51">17.5.2.2 identifier-convert-lispify</A></LI>
727 <LI><A HREF="#Allegrocl_nn52">17.5.2.3 Default identifier to symbol
728  conversions</A></LI>
729 </UL>
730 </LI>
731 <LI><A HREF="#Allegrocl_nn53">17.5.3 Defining your own
732  identifier-converter</A></LI>
733 <LI><A HREF="#Allegrocl_nn54">17.5.4 Instructing SWIG to use a
734  particular identifier-converter</A></LI>
735 </UL>
736 </LI>
737 </UL>
738 <B><A HREF="#CSharp">18 SWIG and C#</A></B>
739 <UL>
740 <LI><A HREF="#csharp_introduction">18.1 Introduction</A></LI>
741 <LI><A HREF="#csharp_differences_java">18.2 Differences to the Java
742  module</A></LI>
743 <LI><A HREF="#CSharp_arrays">18.3 C# Arrays</A>
744 <UL>
745 <LI><A HREF="#CSharp_arrays_swig_library">18.3.1 The SWIG C arrays
746  library</A></LI>
747 <LI><A HREF="#CSharp_arrays_pinvoke_default_array_marshalling">18.3.2
748  Managed arrays using P/Invoke default array marshalling</A></LI>
749 <LI><A HREF="#CSharp_arrays_pinning">18.3.3 Managed arrays using pinning</A>
750 </LI>
751 </UL>
752 </LI>
753 <LI><A HREF="#csharp_exceptions">18.4 C# Exceptions</A>
754 <UL>
755 <LI><A HREF="#csharp_exception_example_check_typemap">18.4.1 C#
756  exception example using &quot;check&quot; typemap</A></LI>
757 <LI><A HREF="#csharp_exception_example_percent_exception">18.4.2 C#
758  exception example using %exception</A></LI>
759 <LI><A HREF="#csharp_exception_example_exception_specifications">18.4.3
760  C# exception example using exception specifications</A></LI>
761 <LI><A HREF="#csharp_custom_application_exception">18.4.4 Custom C#
762  ApplicationException example</A></LI>
763 </UL>
764 </LI>
765 <LI><A HREF="#csharp_directors">18.5 C# Directors</A>
766 <UL>
767 <LI><A HREF="#csharp_directors_example">18.5.1 Directors example</A></LI>
768 <LI><A HREF="#csharp_directors_implementation">18.5.2 Directors
769  implementation</A></LI>
770 <LI><A HREF="#csharp_director_caveats">18.5.3 Director caveats</A></LI>
771 </UL>
772 </LI>
773 <LI><A HREF="#csharp_typemap_examples">18.6 C# Typemap examples</A>
774 <UL>
775 <LI><A HREF="#csharp_memory_management_member_variables">18.6.1 Memory
776  management when returning references to member variables</A></LI>
777 <LI><A HREF="#csharp_memory_management_objects">18.6.2 Memory management
778  for objects passed to the C++ layer</A></LI>
779 <LI><A HREF="#csharp_date_marshalling">18.6.3 Date marshalling using the
780  csin typemap and associated attributes</A></LI>
781 <LI><A HREF="#csharp_date_properties">18.6.4 A date example
782  demonstrating marshalling of C# properties</A></LI>
783 <LI><A HREF="#csharp_partial_classes">18.6.5 Turning wrapped classes
784  into partial classes</A></LI>
785 <LI><A HREF="#csharp_extending_proxy_class">18.6.6 Extending proxy
786  classes with additional C# code</A></LI>
787 </UL>
788 </LI>
789 </UL>
790 <B><A HREF="#Chicken">19 SWIG and Chicken</A></B>
791 <UL>
792 <LI><A HREF="#Chicken_nn2">19.1 Preliminaries</A>
793 <UL>
794 <LI><A HREF="#Chicken_nn3">19.1.1 Running SWIG in C mode</A></LI>
795 <LI><A HREF="#Chicken_nn4">19.1.2 Running SWIG in C++ mode</A></LI>
796 </UL>
797 </LI>
798 <LI><A HREF="#Chicken_nn5">19.2 Code Generation</A>
799 <UL>
800 <LI><A HREF="#Chicken_nn6">19.2.1 Naming Conventions</A></LI>
801 <LI><A HREF="#Chicken_nn7">19.2.2 Modules</A></LI>
802 <LI><A HREF="#Chicken_nn8">19.2.3 Constants and Variables</A></LI>
803 <LI><A HREF="#Chicken_nn9">19.2.4 Functions</A></LI>
804 <LI><A HREF="#Chicken_nn10">19.2.5 Exceptions</A></LI>
805 </UL>
806 </LI>
807 <LI><A HREF="#Chicken_nn11">19.3 TinyCLOS</A></LI>
808 <LI><A HREF="#Chicken_nn12">19.4 Linkage</A>
809 <UL>
810 <LI><A HREF="#Chicken_nn13">19.4.1 Static binary or shared library
811  linked at compile time</A></LI>
812 <LI><A HREF="#Chicken_nn14">19.4.2 Building chicken extension libraries</A>
813 </LI>
814 <LI><A HREF="#Chicken_nn15">19.4.3 Linking multiple SWIG modules with
815  TinyCLOS</A></LI>
816 </UL>
817 </LI>
818 <LI><A HREF="#Chicken_nn16">19.5 Typemaps</A></LI>
819 <LI><A HREF="#Chicken_nn17">19.6 Pointers</A>
820 <UL>
821 <LI><A HREF="#collection">19.6.1 Garbage collection</A></LI>
822 </UL>
823 </LI>
824 <LI><A HREF="#Chicken_nn18">19.7 Unsupported features and known problems</A>
825 <UL>
826 <LI><A HREF="#Chicken_nn19">19.7.1 TinyCLOS problems with Chicken
827  version &lt;= 1.92</A></LI>
828 </UL>
829 </LI>
830 </UL>
831 <B><A HREF="#Guile">20 SWIG and Guile</A></B>
832 <UL>
833 <LI><A HREF="#Guile_nn2">20.1 Meaning of &quot;Module&quot;</A></LI>
834 <LI><A HREF="#Guile_nn3">20.2 Using the SCM or GH Guile API</A></LI>
835 <LI><A HREF="#Guile_nn4">20.3 Linkage</A>
836 <UL>
837 <LI><A HREF="#Guile_nn5">20.3.1 Simple Linkage</A></LI>
838 <LI><A HREF="#Guile_nn6">20.3.2 Passive Linkage</A></LI>
839 <LI><A HREF="#Guile_nn7">20.3.3 Native Guile Module Linkage</A></LI>
840 <LI><A HREF="#Guile_nn8">20.3.4 Old Auto-Loading Guile Module Linkage</A>
841 </LI>
842 <LI><A HREF="#Guile_nn9">20.3.5 Hobbit4D Linkage</A></LI>
843 </UL>
844 </LI>
845 <LI><A HREF="#Guile_nn10">20.4 Underscore Folding</A></LI>
846 <LI><A HREF="#Guile_nn11">20.5 Typemaps</A></LI>
847 <LI><A HREF="#Guile_nn12">20.6 Representation of pointers as smobs</A>
848 <UL>
849 <LI><A HREF="#Guile_nn13">20.6.1 GH Smobs</A></LI>
850 <LI><A HREF="#Guile_nn14">20.6.2 SCM Smobs</A></LI>
851 <LI><A HREF="#Guile_nn15">20.6.3 Garbage Collection</A></LI>
852 </UL>
853 </LI>
854 <LI><A HREF="#Guile_nn16">20.7 Exception Handling</A></LI>
855 <LI><A HREF="#Guile_nn17">20.8 Procedure documentation</A></LI>
856 <LI><A HREF="#Guile_nn18">20.9 Procedures with setters</A></LI>
857 <LI><A HREF="#Guile_nn19">20.10 GOOPS Proxy Classes</A>
858 <UL>
859 <LI><A HREF="#Guile_nn20">20.10.1 Naming Issues</A></LI>
860 <LI><A HREF="#Guile_nn21">20.10.2 Linking</A></LI>
861 </UL>
862 </LI>
863 </UL>
864 <B><A HREF="#Java">21 SWIG and Java</A></B>
865 <UL>
866 <LI><A HREF="#java_overview">21.1 Overview</A></LI>
867 <LI><A HREF="#java_preliminaries">21.2 Preliminaries</A>
868 <UL>
869 <LI><A HREF="#running_swig">21.2.1 Running SWIG</A></LI>
870 <LI><A HREF="#java_commandline">21.2.2 Additional Commandline Options</A>
871 </LI>
872 <LI><A HREF="#getting_right_headers">21.2.3 Getting the right header
873  files</A></LI>
874 <LI><A HREF="#compiling_dynamic">21.2.4 Compiling a dynamic module</A></LI>
875 <LI><A HREF="#using_module">21.2.5 Using your module</A></LI>
876 <LI><A HREF="#dynamic_linking_problems">21.2.6 Dynamic linking problems</A>
877 </LI>
878 <LI><A HREF="#compilation_problems_cpp">21.2.7 Compilation problems and
879  compiling with C++</A></LI>
880 <LI><A HREF="#building_windows">21.2.8 Building on Windows</A>
881 <UL>
882 <LI><A HREF="#visual_studio">21.2.8.1 Running SWIG from Visual Studio</A>
883 </LI>
884 <LI><A HREF="#nmake">21.2.8.2 Using NMAKE</A></LI>
885 </UL>
886 </LI>
887 </UL>
888 </LI>
889 <LI><A HREF="#java_basic_tour">21.3 A tour of basic C/C++ wrapping</A>
890 <UL>
891 <LI><A HREF="#module_packages_classes">21.3.1 Modules, packages and
892  generated Java classes</A></LI>
893 <LI><A HREF="#functions">21.3.2 Functions</A></LI>
894 <LI><A HREF="#global_variables">21.3.3 Global variables</A></LI>
895 <LI><A HREF="#constants">21.3.4 Constants</A></LI>
896 <LI><A HREF="#enumerations">21.3.5 Enumerations</A>
897 <UL>
898 <LI><A HREF="#anonymous_enums">21.3.5.1 Anonymous enums</A></LI>
899 <LI><A HREF="#typesafe_enums">21.3.5.2 Typesafe enums</A></LI>
900 <LI><A HREF="#proper_enums">21.3.5.3 Proper Java enums</A></LI>
901 <LI><A HREF="#typeunsafe_enums">21.3.5.4 Type unsafe enums</A></LI>
902 <LI><A HREF="#simple_enums">21.3.5.5 Simple enums</A></LI>
903 </UL>
904 </LI>
905 <LI><A HREF="#pointers">21.3.6 Pointers</A></LI>
906 <LI><A HREF="#structures">21.3.7 Structures</A></LI>
907 <LI><A HREF="#classes">21.3.8 C++ classes</A></LI>
908 <LI><A HREF="#inheritance">21.3.9 C++ inheritance</A></LI>
909 <LI><A HREF="#pointers_refs_arrays">21.3.10 Pointers, references, arrays
910  and pass by value</A>
911 <UL>
912 <LI><A HREF="#null_pointers">21.3.10.1 Null pointers</A></LI>
913 </UL>
914 </LI>
915 <LI><A HREF="#overloaded_functions">21.3.11 C++ overloaded functions</A></LI>
916 <LI><A HREF="#java_default_arguments">21.3.12 C++ default arguments</A></LI>
917 <LI><A HREF="#namespaces">21.3.13 C++ namespaces</A></LI>
918 <LI><A HREF="#templates">21.3.14 C++ templates</A></LI>
919 <LI><A HREF="#smart_pointers">21.3.15 C++ Smart Pointers</A></LI>
920 </UL>
921 </LI>
922 <LI><A HREF="#further_details">21.4 Further details on the generated
923  Java classes</A>
924 <UL>
925 <LI><A HREF="#imclass">21.4.1 The intermediary JNI class</A>
926 <UL>
927 <LI><A HREF="#imclass_pragmas">21.4.1.1 The intermediary JNI class
928  pragmas</A></LI>
929 </UL>
930 </LI>
931 <LI><A HREF="#java_module_class">21.4.2 The Java module class</A>
932 <UL>
933 <LI><A HREF="#module_class_pragmas">21.4.2.1 The Java module class
934  pragmas</A></LI>
935 </UL>
936 </LI>
937 <LI><A HREF="#java_proxy_classes">21.4.3 Java proxy classes</A>
938 <UL>
939 <LI><A HREF="#memory_management">21.4.3.1 Memory management</A></LI>
940 <LI><A HREF="#inheritance_mirroring">21.4.3.2 Inheritance</A></LI>
941 <LI><A HREF="#proxy_classes_gc">21.4.3.3 Proxy classes and garbage
942  collection</A></LI>
943 <LI><A HREF="#java_pgcpp">21.4.3.4 The premature garbage collection
944  prevention parameter for proxy class marshalling</A></LI>
945 <LI><A HREF="#java_multithread_libraries">21.4.3.5 Single threaded
946  applications and thread safety</A></LI>
947 </UL>
948 </LI>
949 <LI><A HREF="#type_wrapper_classes">21.4.4 Type wrapper classes</A></LI>
950 <LI><A HREF="#enum_classes">21.4.5 Enum classes</A>
951 <UL>
952 <LI><A HREF="#typesafe_enums_classes">21.4.5.1 Typesafe enum classes</A></LI>
953 <LI><A HREF="#proper_enums_classes">21.4.5.2 Proper Java enum classes</A>
954 </LI>
955 <LI><A HREF="#typeunsafe_enums_classes">21.4.5.3 Type unsafe enum
956  classes</A></LI>
957 </UL>
958 </LI>
959 </UL>
960 </LI>
961 <LI><A HREF="#java_directors">21.5 Cross language polymorphism using
962  directors</A>
963 <UL>
964 <LI><A HREF="#java_enabling_directors">21.5.1 Enabling directors</A></LI>
965 <LI><A HREF="#java_directors_classes">21.5.2 Director classes</A></LI>
966 <LI><A HREF="#java_directors_overhead">21.5.3 Overhead and code bloat</A>
967 </LI>
968 <LI><A HREF="#java_directors_example">21.5.4 Simple directors example</A>
969 </LI>
970 <LI><A HREF="#java_directors_threading">21.5.5 Director threading issues</A>
971 </LI>
972 </UL>
973 </LI>
974 <LI><A HREF="#java_allprotected">21.6 Accessing protected members</A></LI>
975 <LI><A HREF="#common_customization">21.7 Common customization features</A>
976 <UL>
977 <LI><A HREF="#helper_functions">21.7.1 C/C++ helper functions</A></LI>
978 <LI><A HREF="#class_extension">21.7.2 Class extension with %extend</A></LI>
979 <LI><A HREF="#exception_handling">21.7.3 Exception handling with
980  %exception and %javaexception</A></LI>
981 <LI><A HREF="#method_access">21.7.4 Method access with
982  %javamethodmodifiers</A></LI>
983 </UL>
984 </LI>
985 <LI><A HREF="#tips_techniques">21.8 Tips and techniques</A>
986 <UL>
987 <LI><A HREF="#input_output_parameters">21.8.1 Input and output
988  parameters using primitive pointers and references</A></LI>
989 <LI><A HREF="#simple_pointers">21.8.2 Simple pointers</A></LI>
990 <LI><A HREF="#c_arrays">21.8.3 Wrapping C arrays with Java arrays</A></LI>
991 <LI><A HREF="#unbounded_c_arrays">21.8.4 Unbounded C Arrays</A></LI>
992 <LI><A HREF="#java_heap_allocations">21.8.5 Overriding new and delete to
993  allocate from Java heap</A></LI>
994 </UL>
995 </LI>
996 <LI><A HREF="#java_typemaps">21.9 Java typemaps</A>
997 <UL>
998 <LI><A HREF="#default_primitive_type_mappings">21.9.1 Default primitive
999  type mappings</A></LI>
1000 <LI><A HREF="#Java_default_non_primitive_typemaps">21.9.2 Default
1001  typemaps for non-primitive types</A></LI>
1002 <LI><A HREF="#jvm64">21.9.3 Sixty four bit JVMs</A></LI>
1003 <LI><A HREF="#what_is_typemap">21.9.4 What is a typemap?</A></LI>
1004 <LI><A HREF="#typemaps_c_to_java_types">21.9.5 Typemaps for mapping
1005  C/C++ types to Java types</A></LI>
1006 <LI><A HREF="#typemap_attributes">21.9.6 Java typemap attributes</A></LI>
1007 <LI><A HREF="#special_variables">21.9.7 Java special variables</A></LI>
1008 <LI><A HREF="#typemaps_for_c_and_cpp">21.9.8 Typemaps for both C and C++
1009  compilation</A></LI>
1010 <LI><A HREF="#java_code_typemaps">21.9.9 Java code typemaps</A></LI>
1011 <LI><A HREF="#java_directors_typemaps">21.9.10 Director specific
1012  typemaps</A></LI>
1013 </UL>
1014 </LI>
1015 <LI><A HREF="#typemap_examples">21.10 Typemap Examples</A>
1016 <UL>
1017 <LI><A HREF="#simpler_enum_classes">21.10.1 Simpler Java enums for enums
1018  without initializers</A></LI>
1019 <LI><A HREF="#exception_typemap">21.10.2 Handling C++ exception
1020  specifications as Java exceptions</A></LI>
1021 <LI><A HREF="#nan_exception_typemap">21.10.3 NaN Exception - exception
1022  handling for a particular type</A></LI>
1023 <LI><A HREF="#converting_java_string_arrays">21.10.4 Converting Java
1024  String arrays to char **</A></LI>
1025 <LI><A HREF="#expanding_java_object">21.10.5 Expanding a Java object to
1026  multiple arguments</A></LI>
1027 <LI><A HREF="#using_typemaps_return_arguments">21.10.6 Using typemaps to
1028  return arguments</A></LI>
1029 <LI><A HREF="#adding_downcasts">21.10.7 Adding Java downcasts to
1030  polymorphic return types</A></LI>
1031 <LI><A HREF="#adding_equals_method">21.10.8 Adding an equals method to
1032  the Java classes</A></LI>
1033 <LI><A HREF="#void_pointers">21.10.9 Void pointers and a common Java
1034  base class</A></LI>
1035 <LI><A HREF="#struct_pointer_pointer">21.10.10 Struct pointer to pointer</A>
1036 </LI>
1037 <LI><A HREF="#java_memory_management_member_variables">21.10.11 Memory
1038  management when returning references to member variables</A></LI>
1039 <LI><A HREF="#java_memory_management_objects">21.10.12 Memory management
1040  for objects passed to the C++ layer</A></LI>
1041 <LI><A HREF="#java_date_marshalling">21.10.13 Date marshalling using the
1042  javain typemap and associated attributes</A></LI>
1043 </UL>
1044 </LI>
1045 <LI><A HREF="#java_directors_faq">21.11 Living with Java Directors</A></LI>
1046 <LI><A HREF="#odds_ends">21.12 Odds and ends</A>
1047 <UL>
1048 <LI><A HREF="#javadoc_comments">21.12.1 JavaDoc comments</A></LI>
1049 <LI><A HREF="#functional_interface">21.12.2 Functional interface without
1050  proxy classes</A></LI>
1051 <LI><A HREF="#using_own_jni_functions">21.12.3 Using your own JNI
1052  functions</A></LI>
1053 <LI><A HREF="#performance">21.12.4 Performance concerns and hints</A></LI>
1054 <LI><A HREF="#java_debugging">21.12.5 Debugging</A></LI>
1055 </UL>
1056 </LI>
1057 <LI><A HREF="#java_examples">21.13 Examples</A></LI>
1058 </UL>
1059 <B><A HREF="#Lisp_nn1">22 SWIG and Common Lisp</A></B>
1060 <UL>
1061 <LI><A HREF="#Lisp_nn2">22.1 Allegro Common Lisp</A></LI>
1062 <LI><A HREF="#Lisp_nn3">22.2 Common Foreign Function Interface(CFFI)</A>
1063 <UL>
1064 <LI><A HREF="#Lisp_nn4">22.2.1 Additional Commandline Options</A></LI>
1065 <LI><A HREF="#Lisp_nn5">22.2.2 Generating CFFI bindings</A></LI>
1066 <LI><A HREF="#Lisp_nn6">22.2.3 Generating CFFI bindings for C++ code</A></LI>
1067 <LI><A HREF="#Lisp_nn7">22.2.4 Inserting user code into generated files</A>
1068 </LI>
1069 </UL>
1070 </LI>
1071 <LI><A HREF="#Lisp_nn8">22.3 CLISP</A>
1072 <UL>
1073 <LI><A HREF="#Lisp_nn9">22.3.1 Additional Commandline Options</A></LI>
1074 <LI><A HREF="#Lisp_nn10">22.3.2 Details on CLISP bindings</A></LI>
1075 </UL>
1076 </LI>
1077 <LI><A HREF="#Lisp_nn11">22.4 UFFI</A></LI>
1078 </UL>
1079 <B><A HREF="#Lua_nn1">23 SWIG and Lua</A></B>
1080 <UL>
1081 <LI><A HREF="#Lua_nn2">23.1 Preliminaries</A></LI>
1082 <LI><A HREF="#Lua_nn3">23.2 Running SWIG</A>
1083 <UL>
1084 <LI><A HREF="#Lua_nn4">23.2.1 Compiling and Linking and Interpreter</A></LI>
1085 <LI><A HREF="#Lua_nn5">23.2.2 Compiling a dynamic module</A></LI>
1086 <LI><A HREF="#Lua_nn6">23.2.3 Using your module</A></LI>
1087 </UL>
1088 </LI>
1089 <LI><A HREF="#Lua_nn7">23.3 A tour of basic C/C++ wrapping</A>
1090 <UL>
1091 <LI><A HREF="#Lua_nn8">23.3.1 Modules</A></LI>
1092 <LI><A HREF="#Lua_nn9">23.3.2 Functions</A></LI>
1093 <LI><A HREF="#Lua_nn10">23.3.3 Global variables</A></LI>
1094 <LI><A HREF="#Lua_nn11">23.3.4 Constants and enums</A></LI>
1095 <LI><A HREF="#Lua_nn12">23.3.5 Pointers</A></LI>
1096 <LI><A HREF="#Lua_nn13">23.3.6 Structures</A></LI>
1097 <LI><A HREF="#Lua_nn14">23.3.7 C++ classes</A></LI>
1098 <LI><A HREF="#Lua_nn15">23.3.8 C++ inheritance</A></LI>
1099 <LI><A HREF="#Lua_nn16">23.3.9 Pointers, references, values, and arrays</A>
1100 </LI>
1101 <LI><A HREF="#Lua_nn17">23.3.10 C++ overloaded functions</A></LI>
1102 <LI><A HREF="#Lua_nn18">23.3.11 C++ operators</A></LI>
1103 <LI><A HREF="#Lua_nn19">23.3.12 Class extension with %extend</A></LI>
1104 <LI><A HREF="#Lua_nn20">23.3.13 C++ templates</A></LI>
1105 <LI><A HREF="#Lua_nn21">23.3.14 C++ Smart Pointers</A></LI>
1106 <LI><A HREF="#Lua_nn22">23.3.15 C++ Exceptions</A></LI>
1107 </UL>
1108 </LI>
1109 <LI><A HREF="#Lua_nn23">23.4 Typemaps</A>
1110 <UL>
1111 <LI><A HREF="#Lua_nn24">23.4.1 What is a typemap?</A></LI>
1112 <LI><A HREF="#Lua_nn25">23.4.2 Using typemaps</A></LI>
1113 <LI><A HREF="#Lua_nn26">23.4.3 Typemaps and arrays</A></LI>
1114 <LI><A HREF="#Lua_nn27">23.4.4 Typemaps and pointer-pointer functions</A>
1115 </LI>
1116 </UL>
1117 </LI>
1118 <LI><A HREF="#Lua_nn28">23.5 Writing typemaps</A>
1119 <UL>
1120 <LI><A HREF="#Lua_nn29">23.5.1 Typemaps you can write</A></LI>
1121 <LI><A HREF="#Lua_nn30">23.5.2 SWIG's Lua-C API</A></LI>
1122 </UL>
1123 </LI>
1124 <LI><A HREF="#Lua_nn31">23.6 Customization of your Bindings</A>
1125 <UL>
1126 <LI><A HREF="#Lua_nn32">23.6.1 Writing your own custom wrappers</A></LI>
1127 <LI><A HREF="#Lua_nn33">23.6.2 Adding additional Lua code</A></LI>
1128 </UL>
1129 </LI>
1130 <LI><A HREF="#Lua_nn34">23.7 Details on the Lua binding</A>
1131 <UL>
1132 <LI><A HREF="#Lua_nn35">23.7.1 Binding global data into the module.</A></LI>
1133 <LI><A HREF="#Lua_nn36">23.7.2 Userdata and Metatables</A></LI>
1134 <LI><A HREF="#Lua_nn37">23.7.3 Memory management</A></LI>
1135 </UL>
1136 </LI>
1137 </UL>
1138 <B><A HREF="#Modula3">24 SWIG and Modula-3</A></B>
1139 <UL>
1140 <LI><A HREF="#modula3_overview">24.1 Overview</A>
1141 <UL>
1142 <LI><A HREF="#whyscripting">24.1.1 Why not scripting ?</A></LI>
1143 <LI><A HREF="#whymodula3">24.1.2 Why Modula-3 ?</A></LI>
1144 <LI><A HREF="#whycpp">24.1.3 Why C / C++ ?</A></LI>
1145 <LI><A HREF="#whyswig">24.1.4 Why SWIG ?</A></LI>
1146 </UL>
1147 </LI>
1148 <LI><A HREF="#conception">24.2 Conception</A>
1149 <UL>
1150 <LI><A HREF="#cinterface">24.2.1 Interfaces to C libraries</A></LI>
1151 <LI><A HREF="#cppinterface">24.2.2 Interfaces to C++ libraries</A></LI>
1152 </UL>
1153 </LI>
1154 <LI><A HREF="#preliminaries">24.3 Preliminaries</A>
1155 <UL>
1156 <LI><A HREF="#compilers">24.3.1 Compilers</A></LI>
1157 <LI><A HREF="#commandline">24.3.2 Additional Commandline Options</A></LI>
1158 </UL>
1159 </LI>
1160 <LI><A HREF="#modula3_typemaps">24.4 Modula-3 typemaps</A>
1161 <UL>
1162 <LI><A HREF="#inoutparam">24.4.1 Inputs and outputs</A></LI>
1163 <LI><A HREF="#ordinals">24.4.2 Subranges, Enumerations, Sets</A></LI>
1164 <LI><A HREF="#class">24.4.3 Objects</A></LI>
1165 <LI><A HREF="#imports">24.4.4 Imports</A></LI>
1166 <LI><A HREF="#exceptions">24.4.5 Exceptions</A></LI>
1167 <LI><A HREF="#typemap_example">24.4.6 Example</A></LI>
1168 </UL>
1169 </LI>
1170 <LI><A HREF="#hints">24.5 More hints to the generator</A>
1171 <UL>
1172 <LI><A HREF="#features">24.5.1 Features</A></LI>
1173 <LI><A HREF="#pragmas">24.5.2 Pragmas</A></LI>
1174 </UL>
1175 </LI>
1176 <LI><A HREF="#remarks">24.6 Remarks</A></LI>
1177 </UL>
1178 <B><A HREF="#MzScheme">25 SWIG and MzScheme</A></B>
1179 <UL>
1180 <LI><A HREF="#MzScheme_nn2">25.1 Creating native MzScheme structures</A></LI>
1181 </UL>
1182 <B><A HREF="#Ocaml">26 SWIG and Ocaml</A></B>
1183 <UL>
1184 <LI><A HREF="#Ocaml_nn2">26.1 Preliminaries</A>
1185 <UL>
1186 <LI><A HREF="#Ocaml_nn3">26.1.1 Running SWIG</A></LI>
1187 <LI><A HREF="#Ocaml_nn4">26.1.2 Compiling the code</A></LI>
1188 <LI><A HREF="#Ocaml_nn5">26.1.3 The camlp4 module</A></LI>
1189 <LI><A HREF="#Ocaml_nn6">26.1.4 Using your module</A></LI>
1190 <LI><A HREF="#Ocaml_nn7">26.1.5 Compilation problems and compiling with
1191  C++</A></LI>
1192 </UL>
1193 </LI>
1194 <LI><A HREF="#Ocaml_nn8">26.2 The low-level Ocaml/C interface</A>
1195 <UL>
1196 <LI><A HREF="#Ocaml_nn9">26.2.1 The generated module</A></LI>
1197 <LI><A HREF="#Ocaml_nn10">26.2.2 Enums</A>
1198 <UL>
1199 <LI><A HREF="#Ocaml_nn11">26.2.2.1 Enum typing in Ocaml</A></LI>
1200 </UL>
1201 </LI>
1202 <LI><A HREF="#Ocaml_nn12">26.2.3 Arrays</A>
1203 <UL>
1204 <LI><A HREF="#Ocaml_nn13">26.2.3.1 Simple types of bounded arrays</A></LI>
1205 <LI><A HREF="#Ocaml_nn14">26.2.3.2 Complex and unbounded arrays</A></LI>
1206 <LI><A HREF="#Ocaml_nn15">26.2.3.3 Using an object</A></LI>
1207 <LI><A HREF="#Ocaml_nn16">26.2.3.4 Example typemap for a function taking
1208  float * and int</A></LI>
1209 </UL>
1210 </LI>
1211 <LI><A HREF="#Ocaml_nn17">26.2.4 C++ Classes</A>
1212 <UL>
1213 <LI><A HREF="#Ocaml_nn18">26.2.4.1 STL vector and string Example</A></LI>
1214 <LI><A HREF="#Ocaml_nn19">26.2.4.2 C++ Class Example</A></LI>
1215 <LI><A HREF="#Ocaml_nn20">26.2.4.3 Compiling the example</A></LI>
1216 <LI><A HREF="#Ocaml_nn21">26.2.4.4 Sample Session</A></LI>
1217 </UL>
1218 </LI>
1219 <LI><A HREF="#Ocaml_nn22">26.2.5 Director Classes</A>
1220 <UL>
1221 <LI><A HREF="#Ocaml_nn23">26.2.5.1 Director Introduction</A></LI>
1222 <LI><A HREF="#Ocaml_nn24">26.2.5.2 Overriding Methods in Ocaml</A></LI>
1223 <LI><A HREF="#Ocaml_nn25">26.2.5.3 Director Usage Example</A></LI>
1224 <LI><A HREF="#Ocaml_nn26">26.2.5.4 Creating director objects</A></LI>
1225 <LI><A HREF="#Ocaml_nn27">26.2.5.5 Typemaps for directors, directorin,
1226  directorout, directorargout</A></LI>
1227 <LI><A HREF="#Ocaml_nn28">26.2.5.6 directorin typemap</A></LI>
1228 <LI><A HREF="#Ocaml_nn29">26.2.5.7 directorout typemap</A></LI>
1229 <LI><A HREF="#Ocaml_nn30">26.2.5.8 directorargout typemap</A></LI>
1230 </UL>
1231 </LI>
1232 <LI><A HREF="#Ocaml_nn31">26.2.6 Exceptions</A></LI>
1233 </UL>
1234 </LI>
1235 </UL>
1236 <B><A HREF="#Octave">27 SWIG and Octave</A></B>
1237 <UL>
1238 <LI><A HREF="#Octave_nn2">27.1 Preliminaries</A></LI>
1239 <LI><A HREF="#Octave_nn3">27.2 Running SWIG</A>
1240 <UL>
1241 <LI><A HREF="#Octave_nn5">27.2.1 Compiling a dynamic module</A></LI>
1242 <LI><A HREF="#Octave_nn6">27.2.2 Using your module</A></LI>
1243 </UL>
1244 </LI>
1245 <LI><A HREF="#Octave_nn7">27.3 A tour of basic C/C++ wrapping</A>
1246 <UL>
1247 <LI><A HREF="#Octave_nn8">27.3.1 Modules</A></LI>
1248 <LI><A HREF="#Octave_nn9">27.3.2 Functions</A></LI>
1249 <LI><A HREF="#Octave_nn10">27.3.3 Global variables</A></LI>
1250 <LI><A HREF="#Octave_nn11">27.3.4 Constants and enums</A></LI>
1251 <LI><A HREF="#Octave_nn12">27.3.5 Pointers</A></LI>
1252 <LI><A HREF="#Octave_nn13">27.3.6 Structures and C++ classes</A></LI>
1253 <LI><A HREF="#Octave_nn15">27.3.7 C++ inheritance</A></LI>
1254 <LI><A HREF="#Octave_nn17">27.3.8 C++ overloaded functions</A></LI>
1255 <LI><A HREF="#Octave_nn18">27.3.9 C++ operators</A></LI>
1256 <LI><A HREF="#Octave_nn19">27.3.10 Class extension with %extend</A></LI>
1257 <LI><A HREF="#Octave_nn20">27.3.11 C++ templates</A></LI>
1258 <LI><A HREF="#Octave_nn21">27.3.12 C++ Smart Pointers</A></LI>
1259 <LI><A HREF="#Octave_nn22">27.3.13 Directors (calling Octave from C++
1260  code)</A></LI>
1261 <LI><A HREF="#Octave_nn23">27.3.14 Threads</A></LI>
1262 <LI><A HREF="#Octave_nn24">27.3.15 Memory management</A></LI>
1263 <LI><A HREF="#Octave_nn25">27.3.16 STL support</A></LI>
1264 <LI><A HREF="#Octave_nn26">27.3.17 Matrix typemaps</A></LI>
1265 </UL>
1266 </LI>
1267 </UL>
1268 <B><A HREF="#Perl5">28 SWIG and Perl5</A></B>
1269 <UL>
1270 <LI><A HREF="#Perl5_nn2">28.1 Overview</A></LI>
1271 <LI><A HREF="#Perl5_nn3">28.2 Preliminaries</A>
1272 <UL>
1273 <LI><A HREF="#Perl5_nn4">28.2.1 Getting the right header files</A></LI>
1274 <LI><A HREF="#Perl5_nn5">28.2.2 Compiling a dynamic module</A></LI>
1275 <LI><A HREF="#Perl5_nn6">28.2.3 Building a dynamic module with MakeMaker</A>
1276 </LI>
1277 <LI><A HREF="#Perl5_nn7">28.2.4 Building a static version of Perl</A></LI>
1278 <LI><A HREF="#Perl5_nn8">28.2.5 Using the module</A></LI>
1279 <LI><A HREF="#Perl5_nn9">28.2.6 Compilation problems and compiling with
1280  C++</A></LI>
1281 <LI><A HREF="#Perl5_nn10">28.2.7 Compiling for 64-bit platforms</A></LI>
1282 </UL>
1283 </LI>
1284 <LI><A HREF="#Perl5_nn11">28.3 Building Perl Extensions under Windows</A>
1285 <UL>
1286 <LI><A HREF="#Perl5_nn12">28.3.1 Running SWIG from Developer Studio</A></LI>
1287 <LI><A HREF="#Perl5_nn13">28.3.2 Using other compilers</A></LI>
1288 </UL>
1289 </LI>
1290 <LI><A HREF="#Perl5_nn14">28.4 The low-level interface</A>
1291 <UL>
1292 <LI><A HREF="#Perl5_nn15">28.4.1 Functions</A></LI>
1293 <LI><A HREF="#Perl5_nn16">28.4.2 Global variables</A></LI>
1294 <LI><A HREF="#Perl5_nn17">28.4.3 Constants</A></LI>
1295 <LI><A HREF="#Perl5_nn18">28.4.4 Pointers</A></LI>
1296 <LI><A HREF="#Perl5_nn19">28.4.5 Structures</A></LI>
1297 <LI><A HREF="#Perl5_nn20">28.4.6 C++ classes</A></LI>
1298 <LI><A HREF="#Perl5_nn21">28.4.7 C++ classes and type-checking</A></LI>
1299 <LI><A HREF="#Perl5_nn22">28.4.8 C++ overloaded functions</A></LI>
1300 <LI><A HREF="#Perl5_nn23">28.4.9 Operators</A></LI>
1301 <LI><A HREF="#Perl5_nn24">28.4.10 Modules and packages</A></LI>
1302 </UL>
1303 </LI>
1304 <LI><A HREF="#Perl5_nn25">28.5 Input and output parameters</A></LI>
1305 <LI><A HREF="#Perl5_nn26">28.6 Exception handling</A></LI>
1306 <LI><A HREF="#Perl5_nn27">28.7 Remapping datatypes with typemaps</A>
1307 <UL>
1308 <LI><A HREF="#Perl5_nn28">28.7.1 A simple typemap example</A></LI>
1309 <LI><A HREF="#Perl5_nn29">28.7.2 Perl5 typemaps</A></LI>
1310 <LI><A HREF="#Perl5_nn30">28.7.3 Typemap variables</A></LI>
1311 <LI><A HREF="#Perl5_nn31">28.7.4 Useful functions</A></LI>
1312 </UL>
1313 </LI>
1314 <LI><A HREF="#Perl5_nn32">28.8 Typemap Examples</A>
1315 <UL>
1316 <LI><A HREF="#Perl5_nn33">28.8.1 Converting a Perl5 array to a char **</A>
1317 </LI>
1318 <LI><A HREF="#Perl5_nn34">28.8.2 Return values</A></LI>
1319 <LI><A HREF="#Perl5_nn35">28.8.3 Returning values from arguments</A></LI>
1320 <LI><A HREF="#Perl5_nn36">28.8.4 Accessing array structure members</A></LI>
1321 <LI><A HREF="#Perl5_nn37">28.8.5 Turning Perl references into C pointers</A>
1322 </LI>
1323 <LI><A HREF="#Perl5_nn38">28.8.6 Pointer handling</A></LI>
1324 </UL>
1325 </LI>
1326 <LI><A HREF="#Perl5_nn39">28.9 Proxy classes</A>
1327 <UL>
1328 <LI><A HREF="#Perl5_nn40">28.9.1 Preliminaries</A></LI>
1329 <LI><A HREF="#Perl5_nn41">28.9.2 Structure and class wrappers</A></LI>
1330 <LI><A HREF="#Perl5_nn42">28.9.3 Object Ownership</A></LI>
1331 <LI><A HREF="#Perl5_nn43">28.9.4 Nested Objects</A></LI>
1332 <LI><A HREF="#Perl5_nn44">28.9.5 Proxy Functions</A></LI>
1333 <LI><A HREF="#Perl5_nn45">28.9.6 Inheritance</A></LI>
1334 <LI><A HREF="#Perl5_nn46">28.9.7 Modifying the proxy methods</A></LI>
1335 </UL>
1336 </LI>
1337 <LI><A HREF="#Perl5_nn47">28.10 Adding additional Perl code</A></LI>
1338 </UL>
1339 <B><A HREF="#Php">29 SWIG and PHP</A></B>
1340 <UL>
1341 <LI><A HREF="#Php_nn1">29.1 Generating PHP Extensions</A>
1342 <UL>
1343 <LI><A HREF="#Php_nn1_1">29.1.1 Building a loadable extension</A></LI>
1344 <LI><A HREF="#Php_nn1_3">29.1.2 Using PHP Extensions</A></LI>
1345 </UL>
1346 </LI>
1347 <LI><A HREF="#Php_nn2">29.2 Basic PHP interface</A>
1348 <UL>
1349 <LI><A HREF="#Php_nn2_1">29.2.1 Constants</A></LI>
1350 <LI><A HREF="#Php_nn2_2">29.2.2 Global Variables</A></LI>
1351 <LI><A HREF="#Php_nn2_3">29.2.3 Functions</A></LI>
1352 <LI><A HREF="#Php_nn2_4">29.2.4 Overloading</A></LI>
1353 <LI><A HREF="#Php_nn2_5">29.2.5 Pointers and References</A></LI>
1354 <LI><A HREF="#Php_nn2_6">29.2.6 Structures and C++ classes</A>
1355 <UL>
1356 <LI><A HREF="#Php_nn2_6_1">29.2.6.1 Using -noproxy</A></LI>
1357 <LI><A HREF="#Php_nn2_6_2">29.2.6.2 Constructors and Destructors</A></LI>
1358 <LI><A HREF="#Php_nn2_6_3">29.2.6.3 Static Member Variables</A></LI>
1359 <LI><A HREF="#Php_nn2_6_4">29.2.6.4 Static Member Functions</A></LI>
1360 </UL>
1361 </LI>
1362 <LI><A HREF="#Php_nn2_7">29.2.7 PHP Pragmas, Startup and Shutdown code</A>
1363 </LI>
1364 </UL>
1365 </LI>
1366 <LI><A HREF="#Php_nn3">29.3 Cross language polymorphism</A>
1367 <UL>
1368 <LI><A HREF="#Php_nn3_1">29.3.1 Enabling directors</A></LI>
1369 <LI><A HREF="#Php_nn3_2">29.3.2 Director classes</A></LI>
1370 <LI><A HREF="#Php_nn3_3">29.3.3 Ownership and object destruction</A></LI>
1371 <LI><A HREF="#Php_nn3_4">29.3.4 Exception unrolling</A></LI>
1372 <LI><A HREF="#Php_nn3_5">29.3.5 Overhead and code bloat</A></LI>
1373 <LI><A HREF="#Php_nn3_6">29.3.6 Typemaps</A></LI>
1374 <LI><A HREF="#Php_nn3_7">29.3.7 Miscellaneous</A></LI>
1375 </UL>
1376 </LI>
1377 </UL>
1378 <B><A HREF="#Pike">30 SWIG and Pike</A></B>
1379 <UL>
1380 <LI><A HREF="#Pike_nn2">30.1 Preliminaries</A>
1381 <UL>
1382 <LI><A HREF="#Pike_nn3">30.1.1 Running SWIG</A></LI>
1383 <LI><A HREF="#Pike_nn4">30.1.2 Getting the right header files</A></LI>
1384 <LI><A HREF="#Pike_nn5">30.1.3 Using your module</A></LI>
1385 </UL>
1386 </LI>
1387 <LI><A HREF="#Pike_nn6">30.2 Basic C/C++ Mapping</A>
1388 <UL>
1389 <LI><A HREF="#Pike_nn7">30.2.1 Modules</A></LI>
1390 <LI><A HREF="#Pike_nn8">30.2.2 Functions</A></LI>
1391 <LI><A HREF="#Pike_nn9">30.2.3 Global variables</A></LI>
1392 <LI><A HREF="#Pike_nn10">30.2.4 Constants and enumerated types</A></LI>
1393 <LI><A HREF="#Pike_nn11">30.2.5 Constructors and Destructors</A></LI>
1394 <LI><A HREF="#Pike_nn12">30.2.6 Static Members</A></LI>
1395 </UL>
1396 </LI>
1397 </UL>
1398 <B><A HREF="#Python">31 SWIG and Python</A></B>
1399 <UL>
1400 <LI><A HREF="#Python_nn2">31.1 Overview</A></LI>
1401 <LI><A HREF="#Python_nn3">31.2 Preliminaries</A>
1402 <UL>
1403 <LI><A HREF="#Python_nn4">31.2.1 Running SWIG</A></LI>
1404 <LI><A HREF="#Python_nn6">31.2.2 Using distutils</A></LI>
1405 <LI><A HREF="#Python_nn7">31.2.3 Hand compiling a dynamic module</A></LI>
1406 <LI><A HREF="#Python_nn8">31.2.4 Static linking</A></LI>
1407 <LI><A HREF="#Python_nn9">31.2.5 Using your module</A></LI>
1408 <LI><A HREF="#Python_nn10">31.2.6 Compilation of C++ extensions</A></LI>
1409 <LI><A HREF="#Python_nn11">31.2.7 Compiling for 64-bit platforms</A></LI>
1410 <LI><A HREF="#Python_nn12">31.2.8 Building Python Extensions under
1411  Windows</A></LI>
1412 </UL>
1413 </LI>
1414 <LI><A HREF="#Python_nn13">31.3 A tour of basic C/C++ wrapping</A>
1415 <UL>
1416 <LI><A HREF="#Python_nn14">31.3.1 Modules</A></LI>
1417 <LI><A HREF="#Python_nn15">31.3.2 Functions</A></LI>
1418 <LI><A HREF="#Python_nn16">31.3.3 Global variables</A></LI>
1419 <LI><A HREF="#Python_nn17">31.3.4 Constants and enums</A></LI>
1420 <LI><A HREF="#Python_nn18">31.3.5 Pointers</A></LI>
1421 <LI><A HREF="#Python_nn19">31.3.6 Structures</A></LI>
1422 <LI><A HREF="#Python_nn20">31.3.7 C++ classes</A></LI>
1423 <LI><A HREF="#Python_nn21">31.3.8 C++ inheritance</A></LI>
1424 <LI><A HREF="#Python_nn22">31.3.9 Pointers, references, values, and
1425  arrays</A></LI>
1426 <LI><A HREF="#Python_nn23">31.3.10 C++ overloaded functions</A></LI>
1427 <LI><A HREF="#Python_nn24">31.3.11 C++ operators</A></LI>
1428 <LI><A HREF="#Python_nn25">31.3.12 C++ namespaces</A></LI>
1429 <LI><A HREF="#Python_nn26">31.3.13 C++ templates</A></LI>
1430 <LI><A HREF="#Python_nn27">31.3.14 C++ Smart Pointers</A></LI>
1431 <LI><A HREF="#Python_nn27a">31.3.15 C++ Reference Counted Objects
1432  (ref/unref)</A></LI>
1433 </UL>
1434 </LI>
1435 <LI><A HREF="#Python_nn28">31.4 Further details on the Python class
1436  interface</A>
1437 <UL>
1438 <LI><A HREF="#Python_nn29">31.4.1 Proxy classes</A></LI>
1439 <LI><A HREF="#Python_nn30">31.4.2 Memory management</A></LI>
1440 <LI><A HREF="#Python_nn31">31.4.3 Python 2.2 and classic classes</A></LI>
1441 </UL>
1442 </LI>
1443 <LI><A HREF="#Python_directors">31.5 Cross language polymorphism</A>
1444 <UL>
1445 <LI><A HREF="#Python_nn33">31.5.1 Enabling directors</A></LI>
1446 <LI><A HREF="#Python_nn34">31.5.2 Director classes</A></LI>
1447 <LI><A HREF="#Python_nn35">31.5.3 Ownership and object destruction</A></LI>
1448 <LI><A HREF="#Python_nn36">31.5.4 Exception unrolling</A></LI>
1449 <LI><A HREF="#Python_nn37">31.5.5 Overhead and code bloat</A></LI>
1450 <LI><A HREF="#Python_nn38">31.5.6 Typemaps</A></LI>
1451 <LI><A HREF="#Python_nn39">31.5.7 Miscellaneous</A></LI>
1452 </UL>
1453 </LI>
1454 <LI><A HREF="#Python_nn40">31.6 Common customization features</A>
1455 <UL>
1456 <LI><A HREF="#Python_nn41">31.6.1 C/C++ helper functions</A></LI>
1457 <LI><A HREF="#Python_nn42">31.6.2 Adding additional Python code</A></LI>
1458 <LI><A HREF="#Python_nn43">31.6.3 Class extension with %extend</A></LI>
1459 <LI><A HREF="#Python_nn44">31.6.4 Exception handling with %exception</A></LI>
1460 </UL>
1461 </LI>
1462 <LI><A HREF="#Python_nn45">31.7 Tips and techniques</A>
1463 <UL>
1464 <LI><A HREF="#Python_nn46">31.7.1 Input and output parameters</A></LI>
1465 <LI><A HREF="#Python_nn47">31.7.2 Simple pointers</A></LI>
1466 <LI><A HREF="#Python_nn48">31.7.3 Unbounded C Arrays</A></LI>
1467 <LI><A HREF="#Python_nn49">31.7.4 String handling</A></LI>
1468 <LI><A HREF="#Python_nn50">31.7.5 Arrays</A></LI>
1469 <LI><A HREF="#Python_nn51">31.7.6 String arrays</A></LI>
1470 <LI><A HREF="#Python_nn52">31.7.7 STL wrappers</A></LI>
1471 </UL>
1472 </LI>
1473 <LI><A HREF="#Python_nn53">31.8 Typemaps</A>
1474 <UL>
1475 <LI><A HREF="#Python_nn54">31.8.1 What is a typemap?</A></LI>
1476 <LI><A HREF="#Python_nn55">31.8.2 Python typemaps</A></LI>
1477 <LI><A HREF="#Python_nn56">31.8.3 Typemap variables</A></LI>
1478 <LI><A HREF="#Python_nn57">31.8.4 Useful Python Functions</A></LI>
1479 </UL>
1480 </LI>
1481 <LI><A HREF="#Python_nn58">31.9 Typemap Examples</A>
1482 <UL>
1483 <LI><A HREF="#Python_nn59">31.9.1 Converting Python list to a char **</A>
1484 </LI>
1485 <LI><A HREF="#Python_nn60">31.9.2 Expanding a Python object into
1486  multiple arguments</A></LI>
1487 <LI><A HREF="#Python_nn61">31.9.3 Using typemaps to return arguments</A></LI>
1488 <LI><A HREF="#Python_nn62">31.9.4 Mapping Python tuples into small
1489  arrays</A></LI>
1490 <LI><A HREF="#Python_nn63">31.9.5 Mapping sequences to C arrays</A></LI>
1491 <LI><A HREF="#Python_nn64">31.9.6 Pointer handling</A></LI>
1492 </UL>
1493 </LI>
1494 <LI><A HREF="#Python_nn65">31.10 Docstring Features</A>
1495 <UL>
1496 <LI><A HREF="#Python_nn66">31.10.1 Module docstring</A></LI>
1497 <LI><A HREF="#Python_nn67">31.10.2 %feature(&quot;autodoc&quot;)</A>
1498 <UL>
1499 <LI><A HREF="#Python_nn68">31.10.2.1 %feature(&quot;autodoc&quot;, &quot;0&quot;)</A></LI>
1500 <LI><A HREF="#Python_nn69">31.10.2.2 %feature(&quot;autodoc&quot;, &quot;1&quot;)</A></LI>
1501 <LI><A HREF="#Python_nn70">31.10.2.3 %feature(&quot;autodoc&quot;, &quot;docstring&quot;)</A>
1502 </LI>
1503 </UL>
1504 </LI>
1505 <LI><A HREF="#Python_nn71">31.10.3 %feature(&quot;docstring&quot;)</A></LI>
1506 </UL>
1507 </LI>
1508 <LI><A HREF="#Python_nn72">31.11 Python Packages</A></LI>
1509 <LI><A HREF="#Python_python3support">31.12 Python 3 Support</A>
1510 <UL>
1511 <LI><A HREF="#Python_nn74">31.12.1 Function annotation</A></LI>
1512 <LI><A HREF="#Python_nn75">31.12.2 Buffer interface</A></LI>
1513 <LI><A HREF="#Python_nn76">31.12.3 Abstract base classes</A></LI>
1514 </UL>
1515 </LI>
1516 </UL>
1517 <B><A HREF="#Ruby">32 SWIG and Ruby</A></B>
1518 <UL>
1519 <LI><A HREF="#Ruby_nn2">32.1 Preliminaries</A>
1520 <UL>
1521 <LI><A HREF="#Ruby_nn3">32.1.1 Running SWIG</A></LI>
1522 <LI><A HREF="#Ruby_nn4">32.1.2 Getting the right header files</A></LI>
1523 <LI><A HREF="#Ruby_nn5">32.1.3 Compiling a dynamic module</A></LI>
1524 <LI><A HREF="#Ruby_nn6">32.1.4 Using your module</A></LI>
1525 <LI><A HREF="#Ruby_nn7">32.1.5 Static linking</A></LI>
1526 <LI><A HREF="#Ruby_nn8">32.1.6 Compilation of C++ extensions</A></LI>
1527 </UL>
1528 </LI>
1529 <LI><A HREF="#Ruby_nn9">32.2 Building Ruby Extensions under Windows
1530  95/NT</A>
1531 <UL>
1532 <LI><A HREF="#Ruby_nn10">32.2.1 Running SWIG from Developer Studio</A></LI>
1533 </UL>
1534 </LI>
1535 <LI><A HREF="#Ruby_nn11">32.3 The Ruby-to-C/C++ Mapping</A>
1536 <UL>
1537 <LI><A HREF="#Ruby_nn12">32.3.1 Modules</A></LI>
1538 <LI><A HREF="#Ruby_nn13">32.3.2 Functions</A></LI>
1539 <LI><A HREF="#Ruby_nn14">32.3.3 Variable Linking</A></LI>
1540 <LI><A HREF="#Ruby_nn15">32.3.4 Constants</A></LI>
1541 <LI><A HREF="#Ruby_nn16">32.3.5 Pointers</A></LI>
1542 <LI><A HREF="#Ruby_nn17">32.3.6 Structures</A></LI>
1543 <LI><A HREF="#Ruby_nn18">32.3.7 C++ classes</A></LI>
1544 <LI><A HREF="#Ruby_nn19">32.3.8 C++ Inheritance</A></LI>
1545 <LI><A HREF="#Ruby_nn20">32.3.9 C++ Overloaded Functions</A></LI>
1546 <LI><A HREF="#Ruby_nn21">32.3.10 C++ Operators</A></LI>
1547 <LI><A HREF="#Ruby_nn22">32.3.11 C++ namespaces</A></LI>
1548 <LI><A HREF="#Ruby_nn23">32.3.12 C++ templates</A></LI>
1549 <LI><A HREF="#Ruby_nn23_1">32.3.13 C++ Standard Template Library (STL)</A>
1550 </LI>
1551 <LI><A HREF="#C_STL_Functors">32.3.14 C++ STL Functors</A></LI>
1552 <LI><A HREF="#Ruby_C_Iterators">32.3.15 C++ STL Iterators</A></LI>
1553 <LI><A HREF="#Ruby_nn24">32.3.16 C++ Smart Pointers</A></LI>
1554 <LI><A HREF="#Ruby_nn25">32.3.17 Cross-Language Polymorphism</A>
1555 <UL>
1556 <LI><A HREF="#Ruby_nn26">32.3.17.1 Exception Unrolling</A></LI>
1557 </UL>
1558 </LI>
1559 </UL>
1560 </LI>
1561 <LI><A HREF="#Ruby_nn27">32.4 Naming</A>
1562 <UL>
1563 <LI><A HREF="#Ruby_nn28">32.4.1 Defining Aliases</A></LI>
1564 <LI><A HREF="#Ruby_nn29">32.4.2 Predicate Methods</A></LI>
1565 <LI><A HREF="#Ruby_nn30">32.4.3 Bang Methods</A></LI>
1566 <LI><A HREF="#Ruby_nn31">32.4.4 Getters and Setters</A></LI>
1567 </UL>
1568 </LI>
1569 <LI><A HREF="#Ruby_nn32">32.5 Input and output parameters</A></LI>
1570 <LI><A HREF="#Ruby_nn33">32.6 Exception handling</A>
1571 <UL>
1572 <LI><A HREF="#Ruby_nn34">32.6.1 Using the %exception directive</A></LI>
1573 <LI><A HREF="#Ruby_nn34_2">32.6.2 Handling Ruby Blocks</A></LI>
1574 <LI><A HREF="#Ruby_nn35">32.6.3 Raising exceptions</A></LI>
1575 <LI><A HREF="#Ruby_nn36">32.6.4 Exception classes</A></LI>
1576 </UL>
1577 </LI>
1578 <LI><A HREF="#Ruby_nn37">32.7 Typemaps</A>
1579 <UL>
1580 <LI><A HREF="#Ruby_nn38">32.7.1 What is a typemap?</A></LI>
1581 <LI><A HREF="#Ruby_Typemap_scope">32.7.2 Typemap scope</A></LI>
1582 <LI><A HREF="#Ruby_Copying_a_typemap">32.7.3 Copying a typemap</A></LI>
1583 <LI><A HREF="#Ruby_Deleting_a_typemap">32.7.4 Deleting a typemap</A></LI>
1584 <LI><A HREF="#Ruby_Placement_of_typemaps">32.7.5 Placement of typemaps</A>
1585 </LI>
1586 <LI><A HREF="#Ruby_nn39">32.7.6 Ruby typemaps</A>
1587 <UL>
1588 <LI><A HREF="#Ruby_in_typemap">32.7.6.1 &nbsp;&quot;in&quot; typemap</A></LI>
1589 <LI><A HREF="#Ruby_typecheck_typemap">32.7.6.2 &quot;typecheck&quot; typemap</A></LI>
1590 <LI><A HREF="#Ruby_out_typemap">32.7.6.3 &nbsp;&quot;out&quot; typemap</A></LI>
1591 <LI><A HREF="#Ruby_arginit_typemap">32.7.6.4 &quot;arginit&quot; typemap</A></LI>
1592 <LI><A HREF="#Ruby_default_typemap">32.7.6.5 &quot;default&quot; typemap</A></LI>
1593 <LI><A HREF="#Ruby_check_typemap">32.7.6.6 &quot;check&quot; typemap</A></LI>
1594 <LI><A HREF="#Ruby_argout_typemap_">32.7.6.7 &quot;argout&quot; typemap</A></LI>
1595 <LI><A HREF="#Ruby_freearg_typemap_">32.7.6.8 &quot;freearg&quot; typemap</A></LI>
1596 <LI><A HREF="#Ruby_newfree_typemap">32.7.6.9 &quot;newfree&quot; typemap</A></LI>
1597 <LI><A HREF="#Ruby_memberin_typemap">32.7.6.10 &quot;memberin&quot; typemap</A></LI>
1598 <LI><A HREF="#Ruby_varin_typemap">32.7.6.11 &quot;varin&quot; typemap</A></LI>
1599 <LI><A HREF="#Ruby_varout_typemap_">32.7.6.12 &quot;varout&quot; typemap</A></LI>
1600 <LI><A HREF="#Ruby_throws_typemap">32.7.6.13 &quot;throws&quot; typemap</A></LI>
1601 <LI><A HREF="#Ruby_directorin_typemap">32.7.6.14 directorin typemap</A></LI>
1602 <LI><A HREF="#Ruby_directorout_typemap">32.7.6.15 directorout typemap</A>
1603 </LI>
1604 <LI><A HREF="#Ruby_directorargout_typemap">32.7.6.16 directorargout
1605  typemap</A></LI>
1606 <LI><A HREF="#Ruby_ret_typemap">32.7.6.17 ret typemap</A></LI>
1607 <LI><A HREF="#Ruby_globalin_typemap">32.7.6.18 globalin typemap</A></LI>
1608 </UL>
1609 </LI>
1610 <LI><A HREF="#Ruby_nn40">32.7.7 Typemap variables</A></LI>
1611 <LI><A HREF="#Ruby_nn41">32.7.8 Useful Functions</A>
1612 <UL>
1613 <LI><A HREF="#Ruby_nn42">32.7.8.1 C Datatypes to Ruby Objects</A></LI>
1614 <LI><A HREF="#Ruby_nn43">32.7.8.2 Ruby Objects to C Datatypes</A></LI>
1615 <LI><A HREF="#Ruby_nn44">32.7.8.3 Macros for VALUE</A></LI>
1616 <LI><A HREF="#Ruby_nn45">32.7.8.4 Exceptions</A></LI>
1617 <LI><A HREF="#Ruby_nn46">32.7.8.5 Iterators</A></LI>
1618 </UL>
1619 </LI>
1620 <LI><A HREF="#Ruby_nn47">32.7.9 Typemap Examples</A></LI>
1621 <LI><A HREF="#Ruby_nn48">32.7.10 Converting a Ruby array to a char **</A>
1622 </LI>
1623 <LI><A HREF="#Ruby_nn49">32.7.11 Collecting arguments in a hash</A></LI>
1624 <LI><A HREF="#Ruby_nn50">32.7.12 Pointer handling</A>
1625 <UL>
1626 <LI><A HREF="#Ruby_nn51">32.7.12.1 Ruby Datatype Wrapping</A></LI>
1627 </UL>
1628 </LI>
1629 <LI><A HREF="#Ruby_nn52">32.7.13 Example: STL Vector to Ruby Array</A></LI>
1630 </UL>
1631 </LI>
1632 <LI><A HREF="#Ruby_nn65">32.8 Docstring Features</A>
1633 <UL>
1634 <LI><A HREF="#Ruby_nn66">32.8.1 Module docstring</A></LI>
1635 <LI><A HREF="#Ruby_nn67">32.8.2 %feature(&quot;autodoc&quot;)</A>
1636 <UL>
1637 <LI><A HREF="#Ruby_nn68">32.8.2.1 %feature(&quot;autodoc&quot;, &quot;0&quot;)</A></LI>
1638 <LI><A HREF="#Ruby_autodoc1">32.8.2.2 %feature(&quot;autodoc&quot;, &quot;1&quot;)</A></LI>
1639 <LI><A HREF="#Ruby_autodoc2">32.8.2.3 %feature(&quot;autodoc&quot;, &quot;2&quot;)</A></LI>
1640 <LI><A HREF="#Ruby_feature_autodoc3">32.8.2.4 %feature(&quot;autodoc&quot;, &quot;3&quot;)</A>
1641 </LI>
1642 <LI><A HREF="#Ruby_nn70">32.8.2.5 %feature(&quot;autodoc&quot;, &quot;docstring&quot;)</A></LI>
1643 </UL>
1644 </LI>
1645 <LI><A HREF="#Ruby_nn71">32.8.3 %feature(&quot;docstring&quot;)</A></LI>
1646 </UL>
1647 </LI>
1648 <LI><A HREF="#Ruby_nn53">32.9 Advanced Topics</A>
1649 <UL>
1650 <LI><A HREF="#Ruby_nn54">32.9.1 Operator overloading</A></LI>
1651 <LI><A HREF="#Ruby_nn55">32.9.2 Creating Multi-Module Packages</A></LI>
1652 <LI><A HREF="#Ruby_nn56">32.9.3 Specifying Mixin Modules</A></LI>
1653 </UL>
1654 </LI>
1655 <LI><A HREF="#Ruby_nn57">32.10 Memory Management</A>
1656 <UL>
1657 <LI><A HREF="#Ruby_nn58">32.10.1 Mark and Sweep Garbage Collector</A></LI>
1658 <LI><A HREF="#Ruby_nn59">32.10.2 Object Ownership</A></LI>
1659 <LI><A HREF="#Ruby_nn60">32.10.3 Object Tracking</A></LI>
1660 <LI><A HREF="#Ruby_nn61">32.10.4 Mark Functions</A></LI>
1661 <LI><A HREF="#Ruby_nn62">32.10.5 Free Functions</A></LI>
1662 <LI><A HREF="#Ruby_nn63">32.10.6 Embedded Ruby and the C++ Stack</A></LI>
1663 </UL>
1664 </LI>
1665 </UL>
1666 <B><A HREF="#Tcl">33 SWIG and Tcl</A></B>
1667 <UL>
1668 <LI><A HREF="#Tcl_nn2">33.1 Preliminaries</A>
1669 <UL>
1670 <LI><A HREF="#Tcl_nn3">33.1.1 Getting the right header files</A></LI>
1671 <LI><A HREF="#Tcl_nn4">33.1.2 Compiling a dynamic module</A></LI>
1672 <LI><A HREF="#Tcl_nn5">33.1.3 Static linking</A></LI>
1673 <LI><A HREF="#Tcl_nn6">33.1.4 Using your module</A></LI>
1674 <LI><A HREF="#Tcl_nn7">33.1.5 Compilation of C++ extensions</A></LI>
1675 <LI><A HREF="#Tcl_nn8">33.1.6 Compiling for 64-bit platforms</A></LI>
1676 <LI><A HREF="#Tcl_nn9">33.1.7 Setting a package prefix</A></LI>
1677 <LI><A HREF="#Tcl_nn10">33.1.8 Using namespaces</A></LI>
1678 </UL>
1679 </LI>
1680 <LI><A HREF="#Tcl_nn11">33.2 Building Tcl/Tk Extensions under Windows
1681  95/NT</A>
1682 <UL>
1683 <LI><A HREF="#Tcl_nn12">33.2.1 Running SWIG from Developer Studio</A></LI>
1684 <LI><A HREF="#Tcl_nn13">33.2.2 Using NMAKE</A></LI>
1685 </UL>
1686 </LI>
1687 <LI><A HREF="#Tcl_nn14">33.3 A tour of basic C/C++ wrapping</A>
1688 <UL>
1689 <LI><A HREF="#Tcl_nn15">33.3.1 Modules</A></LI>
1690 <LI><A HREF="#Tcl_nn16">33.3.2 Functions</A></LI>
1691 <LI><A HREF="#Tcl_nn17">33.3.3 Global variables</A></LI>
1692 <LI><A HREF="#Tcl_nn18">33.3.4 Constants and enums</A></LI>
1693 <LI><A HREF="#Tcl_nn19">33.3.5 Pointers</A></LI>
1694 <LI><A HREF="#Tcl_nn20">33.3.6 Structures</A></LI>
1695 <LI><A HREF="#Tcl_nn21">33.3.7 C++ classes</A></LI>
1696 <LI><A HREF="#Tcl_nn22">33.3.8 C++ inheritance</A></LI>
1697 <LI><A HREF="#Tcl_nn23">33.3.9 Pointers, references, values, and arrays</A>
1698 </LI>
1699 <LI><A HREF="#Tcl_nn24">33.3.10 C++ overloaded functions</A></LI>
1700 <LI><A HREF="#Tcl_nn25">33.3.11 C++ operators</A></LI>
1701 <LI><A HREF="#Tcl_nn26">33.3.12 C++ namespaces</A></LI>
1702 <LI><A HREF="#Tcl_nn27">33.3.13 C++ templates</A></LI>
1703 <LI><A HREF="#Tcl_nn28">33.3.14 C++ Smart Pointers</A></LI>
1704 </UL>
1705 </LI>
1706 <LI><A HREF="#Tcl_nn29">33.4 Further details on the Tcl class interface</A>
1707 <UL>
1708 <LI><A HREF="#Tcl_nn30">33.4.1 Proxy classes</A></LI>
1709 <LI><A HREF="#Tcl_nn31">33.4.2 Memory management</A></LI>
1710 </UL>
1711 </LI>
1712 <LI><A HREF="#Tcl_nn32">33.5 Input and output parameters</A></LI>
1713 <LI><A HREF="#Tcl_nn33">33.6 Exception handling</A></LI>
1714 <LI><A HREF="#Tcl_nn34">33.7 Typemaps</A>
1715 <UL>
1716 <LI><A HREF="#Tcl_nn35">33.7.1 What is a typemap?</A></LI>
1717 <LI><A HREF="#Tcl_nn36">33.7.2 Tcl typemaps</A></LI>
1718 <LI><A HREF="#Tcl_nn37">33.7.3 Typemap variables</A></LI>
1719 <LI><A HREF="#Tcl_nn38">33.7.4 Converting a Tcl list to a char **</A></LI>
1720 <LI><A HREF="#Tcl_nn39">33.7.5 Returning values in arguments</A></LI>
1721 <LI><A HREF="#Tcl_nn40">33.7.6 Useful functions</A></LI>
1722 <LI><A HREF="#Tcl_nn41">33.7.7 Standard typemaps</A></LI>
1723 <LI><A HREF="#Tcl_nn42">33.7.8 Pointer handling</A></LI>
1724 </UL>
1725 </LI>
1726 <LI><A HREF="#Tcl_nn43">33.8 Turning a SWIG module into a Tcl Package.</A>
1727 </LI>
1728 <LI><A HREF="#Tcl_nn44">33.9 Building new kinds of Tcl interfaces (in
1729  Tcl)</A>
1730 <UL>
1731 <LI><A HREF="#Tcl_nn45">33.9.1 Proxy classes</A></LI>
1732 </UL>
1733 </LI>
1734 <LI><A HREF="#Tcl_nn46">33.10 Tcl/Tk Stubs</A></LI>
1735 </UL>
1736 <B><A HREF="#R">34 SWIG and R</A></B>
1737 <UL>
1738 <LI><A HREF="#R_nn2">34.1 Bugs</A></LI>
1739 <LI><A HREF="#R_nn3">34.2 Using R and SWIG</A></LI>
1740 <LI><A HREF="#R_nn4">34.3 Precompiling large R files</A></LI>
1741 <LI><A HREF="#R_nn5">34.4 General policy</A></LI>
1742 <LI><A HREF="#R_language_conventions">34.5 Language conventions</A></LI>
1743 <LI><A HREF="#R_nn6">34.6 C++ classes</A></LI>
1744 <LI><A HREF="#R_nn7">34.7 Enumerations</A></LI>
1745 </UL>
1746 <B><A HREF="#Extending">35 Extending SWIG to support new languages</A></B>
1747 <UL>
1748 <LI><A HREF="#Extending_nn2">35.1 Introduction</A></LI>
1749 <LI><A HREF="#Extending_nn3">35.2 Prerequisites</A></LI>
1750 <LI><A HREF="#Extending_nn4">35.3 The Big Picture</A></LI>
1751 <LI><A HREF="#Extending_nn5">35.4 Execution Model</A>
1752 <UL>
1753 <LI><A HREF="#Extending_nn6">35.4.1 Preprocessing</A></LI>
1754 <LI><A HREF="#Extending_nn7">35.4.2 Parsing</A></LI>
1755 <LI><A HREF="#Extending_nn8">35.4.3 Parse Trees</A></LI>
1756 <LI><A HREF="#Extending_nn9">35.4.4 Attribute namespaces</A></LI>
1757 <LI><A HREF="#Extending_nn10">35.4.5 Symbol Tables</A></LI>
1758 <LI><A HREF="#Extending_nn11">35.4.6 The %feature directive</A></LI>
1759 <LI><A HREF="#Extending_nn12">35.4.7 Code Generation</A></LI>
1760 <LI><A HREF="#Extending_nn13">35.4.8 SWIG and XML</A></LI>
1761 </UL>
1762 </LI>
1763 <LI><A HREF="#Extending_nn14">35.5 Primitive Data Structures</A>
1764 <UL>
1765 <LI><A HREF="#Extending_nn15">35.5.1 Strings</A></LI>
1766 <LI><A HREF="#Extending_nn16">35.5.2 Hashes</A></LI>
1767 <LI><A HREF="#Extending_nn17">35.5.3 Lists</A></LI>
1768 <LI><A HREF="#Extending_nn18">35.5.4 Common operations</A></LI>
1769 <LI><A HREF="#Extending_nn19">35.5.5 Iterating over Lists and Hashes</A></LI>
1770 <LI><A HREF="#Extending_nn20">35.5.6 I/O</A></LI>
1771 </UL>
1772 </LI>
1773 <LI><A HREF="#Extending_nn21">35.6 Navigating and manipulating parse
1774  trees</A></LI>
1775 <LI><A HREF="#Extending_nn22">35.7 Working with attributes</A></LI>
1776 <LI><A HREF="#Extending_nn23">35.8 Type system</A>
1777 <UL>
1778 <LI><A HREF="#Extending_nn24">35.8.1 String encoding of types</A></LI>
1779 <LI><A HREF="#Extending_nn25">35.8.2 Type construction</A></LI>
1780 <LI><A HREF="#Extending_nn26">35.8.3 Type tests</A></LI>
1781 <LI><A HREF="#Extending_nn27">35.8.4 Typedef and inheritance</A></LI>
1782 <LI><A HREF="#Extending_nn28">35.8.5 Lvalues</A></LI>
1783 <LI><A HREF="#Extending_nn29">35.8.6 Output functions</A></LI>
1784 </UL>
1785 </LI>
1786 <LI><A HREF="#Extending_nn30">35.9 Parameters</A></LI>
1787 <LI><A HREF="#Extending_nn31">35.10 Writing a Language Module</A>
1788 <UL>
1789 <LI><A HREF="#Extending_nn32">35.10.1 Execution model</A></LI>
1790 <LI><A HREF="#Extending_nn33">35.10.2 Starting out</A></LI>
1791 <LI><A HREF="#Extending_nn34">35.10.3 Command line options</A></LI>
1792 <LI><A HREF="#Extending_nn35">35.10.4 Configuration and preprocessing</A>
1793 </LI>
1794 <LI><A HREF="#Extending_nn36">35.10.5 Entry point to code generation</A></LI>
1795 <LI><A HREF="#Extending_nn37">35.10.6 Module I/O and wrapper skeleton</A>
1796 </LI>
1797 <LI><A HREF="#Extending_nn38">35.10.7 Low-level code generators</A></LI>
1798 <LI><A HREF="#Extending_nn39">35.10.8 Configuration files</A></LI>
1799 <LI><A HREF="#Extending_nn40">35.10.9 Runtime support</A></LI>
1800 <LI><A HREF="#Extending_nn41">35.10.10 Standard library files</A></LI>
1801 <LI><A HREF="#Extending_nn42">35.10.11 Examples and test cases</A></LI>
1802 <LI><A HREF="#Extending_nn43">35.10.12 Documentation</A></LI>
1803 <LI><A HREF="#Extending_prerequisites">35.10.13 Prerequisites for adding
1804  a new language module to the SWIG distribution</A></LI>
1805 <LI><A HREF="#Extending_coding_style_guidelines">35.10.14 Coding style
1806  guidelines</A></LI>
1807 </UL>
1808 </LI>
1809 <LI><A HREF="#Extending_nn44">35.11 Typemaps</A>
1810 <UL>
1811 <LI><A HREF="#Extending_nn45">35.11.1 Proxy classes</A></LI>
1812 </UL>
1813 </LI>
1814 <LI><A HREF="#Extending_nn46">35.12 Guide to parse tree nodes</A></LI>
1815 </UL>
1816 <HR NOSHADE>
1817 <H1><A name="Sections"></A>SWIG-1.3 Development Documentation</H1>
1818  Last update : SWIG-1.3.40 (18 August 2009)
1819 <H2><A NAME="1_1">Sections</A></H2>
1820 <P> The SWIG documentation is being updated to reflect new SWIG features
1821  and enhancements. However, this update process is not quite
1822  finished--there is a lot of old SWIG-1.1 documentation and it is taking
1823  some time to update all of it. Please pardon our dust (or volunteer to
1824  help!).</P>
1825 <H3><A NAME="1_1_1">SWIG Core Documentation</A></H3>
1826 <UL>
1827 <LI><A href="#Preface">Preface</A></LI>
1828 <LI><A href="#Introduction">Introduction</A></LI>
1829 <LI><A href="#Windows">Getting started on Windows</A></LI>
1830 <LI><A href="#Scripting">Scripting</A></LI>
1831 <LI><A href="#SWIG">SWIG Basics</A> (Read this!)</LI>
1832 <LI><A href="#SWIGPlus">SWIG and C++</A></LI>
1833 <LI><A href="#Preprocessor">The SWIG preprocessor</A></LI>
1834 <LI><A href="#Library">The SWIG Library</A></LI>
1835 <LI><A href="#Arguments">Argument handling</A></LI>
1836 <LI><A href="#Typemaps">Typemaps</A></LI>
1837 <LI><A href="#Customization">Customization features</A></LI>
1838 <LI><A href="#Contract">Contracts</A></LI>
1839 <LI><A href="#Varargs">Variable length arguments</A></LI>
1840 <LI><A href="#Warnings">Warning messages</A></LI>
1841 <LI><A href="#Modules">Working with Modules</A></LI>
1842 <LI><A href="#CCache">Using SWIG with ccache</A></LI>
1843 </UL>
1844 <H3><A NAME="1_1_2">Language Module Documentation</A></H3>
1845 <UL>
1846 <LI><A href="#Allegrocl_nn1">Allegro CL support</A></LI>
1847 <LI><A href="#CSharp">C# support</A></LI>
1848 <LI><A href="#Chicken">Chicken support</A></LI>
1849 <LI><A href="#Guile">Guile support</A></LI>
1850 <LI><A href="#Java">Java support</A></LI>
1851 <LI><A href="#Lua_nn1">Lua support</A></LI>
1852 <LI><A href="#Lisp_nn1">Common Lisp support</A></LI>
1853 <LI><A href="#Modula3">Modula3 support</A></LI>
1854 <LI><A href="#MzScheme">MzScheme support</A></LI>
1855 <LI><A href="#Ocaml">Ocaml support</A></LI>
1856 <LI><A href="#Octave">Octave support</A></LI>
1857 <LI><A href="#Perl5">Perl5 support</A></LI>
1858 <LI><A href="#Php">PHP support</A></LI>
1859 <LI><A href="#Pike">Pike support</A></LI>
1860 <LI><A href="#Python">Python support</A></LI>
1861 <LI><A href="#Ruby">Ruby support</A></LI>
1862 <LI><A href="#R">R support</A></LI>
1863 <LI><A href="#Tcl">Tcl support</A></LI>
1864 </UL>
1865 <H3><A NAME="1_1_3">Developer Documentation</A></H3>
1866 <UL>
1867 <LI><A href="#Extending">Extending SWIG</A></LI>
1868 </UL>
1869 <H3><A NAME="1_1_4">Documentation that has not yet been updated</A></H3>
1870 <P> This documentation has not been completely updated from SWIG-1.1,
1871  but most of the topics still apply to the current release. Make sure
1872  you read the <A href="#SWIG">SWIG Basics</A> chapter before reading any
1873  of these chapters. Also, SWIG-1.3.10 features extensive changes to the
1874  implementation of typemaps. Make sure you read the <A href="#Typemaps">
1875 Typemaps</A> chapter above if you are using this feature.</P>
1876 <UL>
1877 <LI><A href="Advanced.html#Advanced">Advanced topics</A> (see <A href="#Modules">
1878 Modules</A> for updated information).</LI>
1879 </UL>
1880 <HR NOSHADE>
1881 <H1><A name="Preface"></A>1 Preface</H1>
1882
1883 <!-- INDEX -->
1884 <DIV class="sectiontoc">
1885 <UL>
1886 <LI><A href="#Preface_nn2">Introduction</A></LI>
1887 <LI><A href="#Preface_nn3">Special Introduction for Version 1.3</A></LI>
1888 <LI><A href="#Preface_nn4">SWIG Versions</A></LI>
1889 <LI><A href="#Preface_nn5">SWIG resources</A></LI>
1890 <LI><A href="#Preface_nn6">Prerequisites</A></LI>
1891 <LI><A href="#Preface_nn7">Organization of this manual</A></LI>
1892 <LI><A href="#Preface_nn8">How to avoid reading the manual</A></LI>
1893 <LI><A href="#Preface_nn9">Backwards Compatibility</A></LI>
1894 <LI><A href="#Preface_nn10">Credits</A></LI>
1895 <LI><A href="#Preface_nn11">Bug reports</A></LI>
1896 </UL>
1897 </DIV>
1898 <!-- INDEX -->
1899 <H2><A name="Preface_nn2"></A>1.1 Introduction</H2>
1900 <P> SWIG (Simplified Wrapper and Interface Generator) is a software
1901  development tool for building scripting language interfaces to C and
1902  C++ programs. Originally developed in 1995, SWIG was first used by
1903  scientists in the Theoretical Physics Division at Los Alamos National
1904  Laboratory for building user interfaces to simulation codes running on
1905  the Connection Machine 5 supercomputer. In this environment, scientists
1906  needed to work with huge amounts of simulation data, complex hardware,
1907  and a constantly changing code base. The use of a scripting language
1908  interface provided a simple yet highly flexible foundation for solving
1909  these types of problems. SWIG simplifies development by largely
1910  automating the task of scripting language integration--allowing
1911  developers and users to focus on more important problems.</P>
1912 <P> Although SWIG was originally developed for scientific applications,
1913  it has since evolved into a general purpose tool that is used in a wide
1914  variety of applications--in fact almost anything where C/C++
1915  programming is involved.</P>
1916 <H2><A name="Preface_nn3"></A>1.2 Special Introduction for Version 1.3</H2>
1917 <P> Since SWIG was released in 1996, its user base and applicability has
1918  continued to grow. Although its rate of development has varied, an
1919  active development effort has continued to make improvements to the
1920  system. Today, nearly a dozen developers are working to create
1921  SWIG-2.0---a system that aims to provide wrapping support for nearly
1922  all of the ANSI C++ standard and approximately ten target languages
1923  including Guile, Java, Mzscheme, Ocaml, Perl, Pike, PHP, Python, Ruby,
1924  and Tcl.</P>
1925 <H2><A name="Preface_nn4"></A>1.3 SWIG Versions</H2>
1926 <P> For several years, the most stable version of SWIG has been release
1927  1.1p5. Starting with version 1.3, a new version numbering scheme has
1928  been adopted. Odd version numbers (1.3, 1.5, etc.) represent
1929  development versions of SWIG. Even version numbers (1.4, 1.6, etc.)
1930  represent stable releases. Currently, developers are working to create
1931  a stable SWIG-2.0 release. Don't let the development status of SWIG-1.3
1932  scare you---it is much more stable (and capable) than SWIG-1.1p5.</P>
1933 <H2><A name="Preface_nn5"></A>1.4 SWIG resources</H2>
1934 <P> The official location of SWIG related material is</P>
1935 <DIV class="shell">
1936 <PRE>
1937 <A href="http://www.swig.org">http://www.swig.org</A>
1938 </PRE>
1939 </DIV>
1940 <P> This site contains the latest version of the software, users guide,
1941  and information regarding bugs, installation problems, and
1942  implementation tricks.</P>
1943 <P> You can also subscribe to the swig-user mailing list by visiting the
1944  page</P>
1945 <DIV class="shell">
1946 <PRE>
1947 <A href="http://www.swig.org/mail.html">http://www.swig.org/mail.html</A>
1948 </PRE>
1949 </DIV>
1950 <P> The mailing list often discusses some of the more technical aspects
1951  of SWIG along with information about beta releases and future work.</P>
1952 <P> SVN access to the latest version of SWIG is also available. More
1953  information about this can be obtained at:</P>
1954 <DIV class="shell">
1955 <PRE>
1956 <A href="http://www.swig.org/svn.html">http://www.swig.org/svn.html</A>
1957 </PRE>
1958 </DIV>
1959 <H2><A name="Preface_nn6"></A>1.5 Prerequisites</H2>
1960 <P> This manual assumes that you know how to write C/C++ programs and
1961  that you have at least heard of scripting languages such as Tcl,
1962  Python, and Perl. A detailed knowledge of these scripting languages is
1963  not required although some familiarity won't hurt. No prior experience
1964  with building C extensions to these languages is required---after all,
1965  this is what SWIG does automatically. However, you should be reasonably
1966  familiar with the use of compilers, linkers, and makefiles since making
1967  scripting language extensions is somewhat more complicated than writing
1968  a normal C program.</P>
1969 <P> Recent SWIG releases have become significantly more capable in their
1970  C++ handling--especially support for advanced features like namespaces,
1971  overloaded operators, and templates. Whenever possible, this manual
1972  tries to cover the technicalities of this interface. However, this
1973  isn't meant to be a tutorial on C++ programming. For many of the gory
1974  details, you will almost certainly want to consult a good C++
1975  reference. If you don't program in C++, you may just want to skip those
1976  parts of the manual.</P>
1977 <H2><A name="Preface_nn7"></A>1.6 Organization of this manual</H2>
1978 <P> The first few chapters of this manual describe SWIG in general and
1979  provide an overview of its capabilities. The remaining chapters are
1980  devoted to specific SWIG language modules and are self contained. Thus,
1981  if you are using SWIG to build Python interfaces, you can probably skip
1982  to that chapter and find almost everything you need to know. Caveat: we
1983  are currently working on a documentation rewrite and many of the older
1984  language module chapters are still somewhat out of date.</P>
1985 <H2><A name="Preface_nn8"></A>1.7 How to avoid reading the manual</H2>
1986 <P> If you hate reading manuals, glance at the &quot;Introduction&quot; which
1987  contains a few simple examples. These examples contain about 95% of
1988  everything you need to know to use SWIG. After that, simply use the
1989  language-specific chapters as a reference. The SWIG distribution also
1990  comes with a large directory of examples that illustrate different
1991  topics.</P>
1992 <H2><A name="Preface_nn9"></A>1.8 Backwards Compatibility</H2>
1993 <P> If you are a previous user of SWIG, don't expect recent versions of
1994  SWIG to provide backwards compatibility. In fact, backwards
1995  compatibility issues may arise even between successive 1.3.x releases.
1996  Although these incompatibilities are regrettable, SWIG-1.3 is an active
1997  development project. The primary goal of this effort is to make SWIG
1998  better---a process that would simply be impossible if the developers
1999  are constantly bogged down with backwards compatibility issues.</P>
2000 <P> On a positive note, a few incompatibilities are a small price to pay
2001  for the large number of new features that have been added---namespaces,
2002  templates, smart pointers, overloaded methods, operators, and more.</P>
2003 <P> If you need to work with different versions of SWIG and backwards
2004  compatibility is an issue, you can use the SWIG_VERSION preprocessor
2005  symbol which holds the version of SWIG being executed. SWIG_VERSION is
2006  a hexadecimal integer such as 0x010311 (corresponding to SWIG-1.3.11).
2007  This can be used in an interface file to define different typemaps,
2008  take advantage of different features etc:</P>
2009 <DIV class="code">
2010 <PRE>
2011 #if SWIG_VERSION &gt;= 0x010311
2012 /* Use some fancy new feature */
2013 #endif
2014 </PRE>
2015 </DIV>
2016 <P> Note: The version symbol is not defined in the generated SWIG
2017  wrapper file. The SWIG preprocessor has defined SWIG_VERSION since
2018  SWIG-1.3.11.</P>
2019 <H2><A name="Preface_nn10"></A>1.9 Credits</H2>
2020 <P> SWIG is an unfunded project that would not be possible without the
2021  contributions of many people. Most recent SWIG development has been
2022  supported by Matthias K&ouml;ppe, William Fulton, Lyle Johnson, Richard
2023  Palmer, Thien-Thi Nguyen, Jason Stewart, Loic Dachary, Masaki
2024  Fukushima, Luigi Ballabio, Sam Liddicott, Art Yerkes, Marcelo Matus,
2025  Harco de Hilster, John Lenz, and Surendra Singhi.</P>
2026 <P> Historically, the following people contributed to early versions of
2027  SWIG. Peter Lomdahl, Brad Holian, Shujia Zhou, Niels Jensen, and Tim
2028  Germann at Los Alamos National Laboratory were the first users. Patrick
2029  Tullmann at the University of Utah suggested the idea of automatic
2030  documentation generation. John Schmidt and Kurtis Bleeker at the
2031  University of Utah tested out the early versions. Chris Johnson
2032  supported SWIG's developed at the University of Utah. John Buckman,
2033  Larry Virden, and Tom Schwaller provided valuable input on the first
2034  releases and improving the portability of SWIG. David Fletcher and Gary
2035  Holt have provided a great deal of input on improving SWIG's Perl5
2036  implementation. Kevin Butler contributed the first Windows NT port.</P>
2037 <H2><A name="Preface_nn11"></A>1.10 Bug reports</H2>
2038 <P> Although every attempt has been made to make SWIG bug-free, we are
2039  also trying to make feature improvements that may introduce bugs. To
2040  report a bug, either send mail to the SWIG developer list at the <A href="http://www.swig.org/mail.html">
2041 swig-devel mailing list</A> or report a bug at the <A href="http://www.swig.org/bugs.html">
2042 SWIG bug tracker</A>. In your report, be as specific as possible,
2043  including (if applicable), error messages, tracebacks (if a core dump
2044  occurred), corresponding portions of the SWIG interface file used, and
2045  any important pieces of the SWIG generated wrapper code. We can only
2046  fix bugs if we know about them.</P>
2047 <HR NOSHADE>
2048 <H1><A name="Introduction"></A>2 Introduction</H1>
2049
2050 <!-- INDEX -->
2051 <DIV class="sectiontoc">
2052 <UL>
2053 <LI><A href="#Introduction_nn2">What is SWIG?</A></LI>
2054 <LI><A href="#Introduction_nn3">Why use SWIG?</A></LI>
2055 <LI><A href="#Introduction_nn4">A SWIG example</A>
2056 <UL>
2057 <LI><A href="#Introduction_nn5">SWIG interface file</A></LI>
2058 <LI><A href="#Introduction_nn6">The swig command</A></LI>
2059 <LI><A href="#Introduction_nn7">Building a Perl5 module</A></LI>
2060 <LI><A href="#Introduction_nn8">Building a Python module</A></LI>
2061 <LI><A href="#Introduction_nn9">Shortcuts</A></LI>
2062 </UL>
2063 </LI>
2064 <LI><A href="#Introduction_nn10">Supported C/C++ language features</A></LI>
2065 <LI><A href="#Introduction_nn11">Non-intrusive interface building</A></LI>
2066 <LI><A href="#Introduction_build_system">Incorporating SWIG into a build
2067  system</A></LI>
2068 <LI><A href="#Introduction_nn12">Hands off code generation</A></LI>
2069 <LI><A href="#Introduction_nn13">SWIG and freedom</A></LI>
2070 </UL>
2071 </DIV>
2072 <!-- INDEX -->
2073 <H2><A name="Introduction_nn2"></A>2.1 What is SWIG?</H2>
2074 <P> SWIG is a software development tool that simplifies the task of
2075  interfacing different languages to C and C++ programs. In a nutshell,
2076  SWIG is a compiler that takes C declarations and creates the wrappers
2077  needed to access those declarations from other languages including
2078  including Perl, Python, Tcl, Ruby, Guile, and Java. SWIG normally
2079  requires no modifications to existing code and can often be used to
2080  build a usable interface in only a few minutes. Possible applications
2081  of SWIG include:</P>
2082 <UL>
2083 <LI>Building interpreted interfaces to existing C programs.</LI>
2084 <LI>Rapid prototyping and application development.</LI>
2085 <LI>Interactive debugging.</LI>
2086 <LI>Reengineering or refactoring of legacy software into a scripting
2087  language components.</LI>
2088 <LI>Making a graphical user interface (using Tk for example).</LI>
2089 <LI>Testing of C libraries and programs (using scripts).</LI>
2090 <LI>Building high performance C modules for scripting languages.</LI>
2091 <LI>Making C programming more enjoyable (or tolerable depending on your
2092  point of view).</LI>
2093 <LI>Impressing your friends.</LI>
2094 <LI>Obtaining vast sums of research funding (although obviously not
2095  applicable to the author).</LI>
2096 </UL>
2097 <P> SWIG was originally designed to make it extremely easy for
2098  scientists and engineers to build extensible scientific software
2099  without having to get a degree in software engineering. Because of
2100  this, the use of SWIG tends to be somewhat informal and ad-hoc (e.g.,
2101  SWIG does not require users to provide formal interface specifications
2102  as you would find in a dedicated IDL compiler). Although this style of
2103  development isn't appropriate for every project, it is particularly
2104  well suited to software development in the small; especially the
2105  research and development work that is commonly found in scientific and
2106  engineering projects.</P>
2107 <H2><A name="Introduction_nn3"></A>2.2 Why use SWIG?</H2>
2108 <P> As stated in the previous section, the primary purpose of SWIG is to
2109  simplify the task of integrating C/C++ with other programming
2110  languages. However, why would anyone want to do that? To answer that
2111  question, it is useful to list a few strengths of C/C++ programming:</P>
2112 <UL>
2113 <LI>Excellent support for writing programming libraries.</LI>
2114 <LI>High performance (number crunching, data processing, graphics,
2115  etc.).</LI>
2116 <LI>Systems programming and systems integration.</LI>
2117 <LI>Large user community and software base.</LI>
2118 </UL>
2119 <P> Next, let's list a few problems with C/C++ programming</P>
2120 <UL>
2121 <LI>Writing a user interface is rather painful (i.e., consider
2122  programming with MFC, X11, GTK, or any number of other libraries).</LI>
2123 <LI>Testing is time consuming (the compile/debug cycle).</LI>
2124 <LI>Not easy to reconfigure or customize without recompilation.</LI>
2125 <LI>Modularization can be tricky.</LI>
2126 <LI>Security concerns (buffer overflow for instance).</LI>
2127 </UL>
2128 <P> To address these limitations, many programmers have arrived at the
2129  conclusion that it is much easier to use different programming
2130  languages for different tasks. For instance, writing a graphical user
2131  interface may be significantly easier in a scripting language like
2132  Python or Tcl (consider the reasons why millions of programmers have
2133  used languages like Visual Basic if you need more proof). An
2134  interactive interpreter might also serve as a useful debugging and
2135  testing tool. Other languages like Java might greatly simplify the task
2136  of writing distributed computing software. The key point is that
2137  different programming languages offer different strengths and
2138  weaknesses. Moreover, it is extremely unlikely that any programming is
2139  ever going to be perfect. Therefore, by combining languages together,
2140  you can utilize the best features of each language and greatly simplify
2141  certain aspects of software development.</P>
2142 <P> From the standpoint of C/C++, a lot of people use SWIG because they
2143  want to break out of the traditional monolithic C programming model
2144  which usually results in programs that resemble this:</P>
2145 <UL>
2146 <LI>A collection of functions and variables that do something useful.</LI>
2147 <LI>A <TT>main()</TT> program that starts everything.</LI>
2148 <LI>A horrible collection of hacks that form some kind of user interface
2149  (but which no-one really wants to touch).</LI>
2150 </UL>
2151 <P> Instead of going down that route, incorporating C/C++ into a higher
2152  level language often results in a more modular design, less code,
2153  better flexibility, and increased programmer productivity.</P>
2154 <P> SWIG tries to make the problem of C/C++ integration as painless as
2155  possible. This allows you to focus on the underlying C program and
2156  using the high-level language interface, but not the tedious and
2157  complex chore of making the two languages talk to each other. At the
2158  same time, SWIG recognizes that all applications are different.
2159  Therefore, it provides a wide variety of customization features that
2160  let you change almost every aspect of the language bindings. This is
2161  the main reason why SWIG has such a large user manual ;-).</P>
2162 <H2><A name="Introduction_nn4"></A>2.3 A SWIG example</H2>
2163 <P> The best way to illustrate SWIG is with a simple example. Consider
2164  the following C code:</P>
2165 <DIV class="code">
2166 <PRE>
2167 /* File : example.c */
2168
2169 double  My_variable  = 3.0;
2170
2171 /* Compute factorial of n */
2172 int  fact(int n) {
2173         if (n &lt;= 1) return 1;
2174         else return n*fact(n-1);
2175 }
2176
2177 /* Compute n mod m */
2178 int my_mod(int n, int m) {
2179         return(n % m);
2180 }
2181 </PRE>
2182 </DIV>
2183 <P> Suppose that you wanted to access these functions and the global
2184  variable <TT>My_variable</TT> from Tcl. You start by making a SWIG
2185  interface file as shown below (by convention, these files carry a .i
2186  suffix) :</P>
2187 <H3><A name="Introduction_nn5"></A>2.3.1 SWIG interface file</H3>
2188 <DIV class="code">
2189 <PRE>
2190 /* File : example.i */
2191 %module example
2192 %{
2193 /* Put headers and other declarations here */
2194 extern double My_variable;
2195 extern int    fact(int);
2196 extern int    my_mod(int n, int m);
2197 %}
2198
2199 extern double My_variable;
2200 extern int    fact(int);
2201 extern int    my_mod(int n, int m);
2202 </PRE>
2203 </DIV>
2204 <P> The interface file contains ANSI C function prototypes and variable
2205  declarations. The <TT>%module</TT> directive defines the name of the
2206  module that will be created by SWIG. The <TT>%{,%}</TT> block provides
2207  a location for inserting additional code such as C header files or
2208  additional C declarations.</P>
2209 <H3><A name="Introduction_nn6"></A>2.3.2 The swig command</H3>
2210 <P> SWIG is invoked using the <TT>swig</TT> command. We can use this to
2211  build a Tcl module (under Linux) as follows :</P>
2212 <DIV class="shell">
2213 <PRE>
2214 unix &gt; <B>swig -tcl example.i</B>
2215 unix &gt; <B>gcc -c -fpic example.c example_wrap.c -I/usr/local/include</B>
2216 unix &gt; <B>gcc -shared example.o example_wrap.o -o example.so</B>
2217 unix &gt; <B>tclsh</B>
2218 % <B>load ./example.so</B>
2219 % <B>fact 4</B>
2220 24
2221 % <B>my_mod 23 7</B>
2222 2
2223 % <B>expr $My_variable + 4.5</B>
2224 7.5
2225 %
2226 </PRE>
2227 </DIV>
2228 <P> The <TT>swig</TT> command produced a new file called <TT>
2229 example_wrap.c</TT> that should be compiled along with the <TT>example.c</TT>
2230  file. Most operating systems and scripting languages now support
2231  dynamic loading of modules. In our example, our Tcl module has been
2232  compiled into a shared library that can be loaded into Tcl. When
2233  loaded, Tcl can now access the functions and variables declared in the
2234  SWIG interface. A look at the file <TT>example_wrap.c</TT> reveals a
2235  hideous mess. However, you almost never need to worry about it.</P>
2236 <H3><A name="Introduction_nn7"></A>2.3.3 Building a Perl5 module</H3>
2237 <P> Now, let's turn these functions into a Perl5 module. Without making
2238  any changes type the following (shown for Solaris):</P>
2239 <DIV class="shell">
2240 <PRE>
2241 unix &gt; <B>swig -perl5 example.i</B>
2242 unix &gt; <B>gcc -c example.c example_wrap.c \
2243         -I/usr/local/lib/perl5/sun4-solaris/5.003/CORE</B>
2244 unix &gt; <B>ld -G example.o example_wrap.o -o example.so</B>           # This is for Solaris
2245 unix &gt; <B>perl5.003
2246 use example;
2247 print example::fact(4), &quot;\n&quot;;
2248 print example::my_mod(23,7), &quot;\n&quot;;
2249 print $example::My_variable + 4.5, &quot;\n&quot;;
2250 &lt;ctrl-d&gt;</B>
2251 24
2252 2
2253 7.5
2254 unix &gt;
2255 </PRE>
2256 </DIV>
2257 <H3><A name="Introduction_nn8"></A>2.3.4 Building a Python module</H3>
2258 <P> Finally, let's build a module for Python (shown for Irix).</P>
2259 <DIV class="shell">
2260 <PRE>
2261 unix &gt; <B>swig -python example.i</B>
2262 unix &gt; <B>gcc -c -fpic example.c example_wrap.c -I/usr/local/include/python2.0</B>
2263 unix &gt; <B>gcc -shared example.o example_wrap.o -o _example.so</B>
2264 unix &gt; <B>python</B>
2265 Python 2.0 (#6, Feb 21 2001, 13:29:45)
2266 [GCC egcs-2.91.66 19990314/Linux (egcs-1.1.2 release)] on linux2
2267 Type &quot;copyright&quot;, &quot;credits&quot; or &quot;license&quot; for more information.     
2268 &gt;&gt;&gt; <B>import example</B>
2269 &gt;&gt;&gt; <B>example.fact(4)</B>
2270 24
2271 &gt;&gt;&gt; <B>example.my_mod(23,7)</B>
2272 2
2273 &gt;&gt;&gt; <B>example.cvar.My_variable + 4.5</B>
2274 7.5
2275 </PRE>
2276 </DIV>
2277 <H3><A name="Introduction_nn9"></A>2.3.5 Shortcuts</H3>
2278 <P> To the truly lazy programmer, one may wonder why we needed the extra
2279  interface file at all. As it turns out, you can often do without it.
2280  For example, you could also build a Perl5 module by just running SWIG
2281  on the C header file and specifying a module name as follows</P>
2282 <DIV class="shell">
2283 <PRE>
2284 unix &gt; <B>swig -perl5 -module example example.h</B>
2285 unix &gt; <B>gcc -c example.c example_wrap.c \
2286         -I/usr/local/lib/perl5/sun4-solaris/5.003/CORE</B>
2287 unix &gt; <B>ld -G example.o example_wrap.o -o example.so</B>
2288 unix &gt; <B>perl5.003
2289 use example;
2290 print example::fact(4), &quot;\n&quot;;
2291 print example::my_mod(23,7), &quot;\n&quot;;
2292 print $example::My_variable + 4.5, &quot;\n&quot;;
2293 &lt;ctrl-d&gt;</B>
2294 24
2295 2
2296 7.5
2297 </PRE>
2298 </DIV>
2299 <H2><A name="Introduction_nn10"></A>2.4 Supported C/C++ language
2300  features</H2>
2301 <P> A primary goal of the SWIG project is to make the language binding
2302  process extremely easy. Although a few simple examples have been shown,
2303  SWIG is quite capable in supporting most of C++. Some of the major
2304  features include:</P>
2305 <UL>
2306 <LI>Full C99 preprocessing.</LI>
2307 <LI>All ANSI C and C++ datatypes.</LI>
2308 <LI>Functions, variables, and constants.</LI>
2309 <LI>Classes.</LI>
2310 <LI>Single and multiple inheritance.</LI>
2311 <LI>Overloaded functions and methods.</LI>
2312 <LI>Overloaded operators.</LI>
2313 <LI>C++ templates (including member templates, specialization, and
2314  partial specialization).</LI>
2315 <LI>Namespaces.</LI>
2316 <LI>Variable length arguments.</LI>
2317 <LI>C++ smart pointers.</LI>
2318 </UL>
2319 <P> Currently, the only major C++ feature not supported is nested
2320  classes--a limitation that will be removed in a future release.</P>
2321 <P> It is important to stress that SWIG is not a simplistic C++ lexing
2322  tool like several apparently similar wrapper generation tools. SWIG not
2323  only parses C++, it implements the full C++ type system and it is able
2324  to understand C++ semantics. SWIG generates its wrappers with full
2325  knowledge of this information. As a result, you will find SWIG to be
2326  just as capable of dealing with nasty corner cases as it is in wrapping
2327  simple C++ code. In fact, SWIG is able handle C++ code that stresses
2328  the very limits of many C++ compilers.</P>
2329 <H2><A name="Introduction_nn11"></A>2.5 Non-intrusive interface building</H2>
2330 <P> When used as intended, SWIG requires minimal (if any) modification
2331  to existing C or C++ code. This makes SWIG extremely easy to use with
2332  existing packages and promotes software reuse and modularity. By making
2333  the C/C++ code independent of the high level interface, you can change
2334  the interface and reuse the code in other applications. It is also
2335  possible to support different types of interfaces depending on the
2336  application.</P>
2337 <H2><A name="Introduction_build_system"></A>2.6 Incorporating SWIG into
2338  a build system</H2>
2339 <P> SWIG is a command line tool and as such can be incorporated into any
2340  build system that supports invoking external tools/compilers. SWIG is
2341  most commonly invoked from within a Makefile, but is also known to be
2342  invoked from from popular IDEs such as Microsoft Visual Studio.</P>
2343 <P> If you are using the GNU Autotools (<A href="http://www.gnu.org/software/autoconf">
2344 Autoconf</A>/ <A href="http://www.gnu.org/software/automake">Automake</A>
2345 / <A href="http://www.gnu.org/software/libtool">Libtool</A>) to
2346  configure SWIG use in your project, the SWIG Autoconf macros can be
2347  used. The primary macro is <TT>ac_pkg_swig</TT>, see <A href="http://www.gnu.org/software/ac-archive/htmldoc/ac_pkg_swig.html">
2348 http://www.gnu.org/software/ac-archive/htmldoc/ac_pkg_swig.html</A>. The
2349  <TT>ac_python_devel</TT> macro is also helpful for generating Python
2350  extensions. See the <A href="http://www.gnu.org/software/ac-archive/htmldoc/index.html">
2351 Autoconf Macro Archive</A> for further information on this and other
2352  Autoconf macros.</P>
2353 <P> There is growing support for SWIG in some build tools, for example <A
2354 href="http://www.cmake.org">CMake</A> is a cross-platform, open-source
2355  build manager with built in support for SWIG. CMake can detect the SWIG
2356  executable and many of the target language libraries for linking
2357  against. CMake knows how to build shared libraries and loadable modules
2358  on many different operating systems. This allows easy cross platform
2359  SWIG development. It also can generate the custom commands necessary
2360  for driving SWIG from IDE's and makefiles. All of this can be done from
2361  a single cross platform input file. The following example is a CMake
2362  input file for creating a python wrapper for the SWIG interface file,
2363  example.i:</P>
2364 <DIV class="code">
2365 <PRE>
2366
2367 # This is a CMake example for Python
2368
2369 FIND_PACKAGE(SWIG REQUIRED)
2370 INCLUDE(${SWIG_USE_FILE})
2371
2372 FIND_PACKAGE(PythonLibs)
2373 INCLUDE_DIRECTORIES(${PYTHON_INCLUDE_PATH})
2374
2375 INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR})
2376
2377 SET(CMAKE_SWIG_FLAGS &quot;&quot;)
2378
2379 SET_SOURCE_FILES_PROPERTIES(example.i PROPERTIES CPLUSPLUS ON)
2380 SET_SOURCE_FILES_PROPERTIES(example.i PROPERTIES SWIG_FLAGS &quot;-includeall&quot;)
2381 SWIG_ADD_MODULE(example python example.i example.cxx)
2382 SWIG_LINK_LIBRARIES(example ${PYTHON_LIBRARIES})
2383
2384 </PRE>
2385 </DIV>
2386 <P> The above example will generate native build files such as
2387  makefiles, nmake files and Visual Studio projects which will invoke
2388  SWIG and compile the generated C++ files into _example.so (UNIX) or
2389  _example.pyd (Windows). For other target languages on Windows a dll,
2390  instead of a .pyd file, is usually generated.</P>
2391 <H2><A name="Introduction_nn12"></A>2.7 Hands off code generation</H2>
2392 <P> SWIG is designed to produce working code that needs no
2393  hand-modification (in fact, if you look at the output, you probably
2394  won't want to modify it). You should think of your target language
2395  interface being defined entirely by the input to SWIG, not the
2396  resulting output file. While this approach may limit flexibility for
2397  hard-core hackers, it allows others to forget about the low-level
2398  implementation details.</P>
2399 <H2><A name="Introduction_nn13"></A>2.8 SWIG and freedom</H2>
2400 <P> No, this isn't a special section on the sorry state of world
2401  politics. However, it may be useful to know that SWIG was written with
2402  a certain &quot;philosophy&quot; about programming---namely that programmers are
2403  smart and that tools should just stay out of their way. Because of
2404  that, you will find that SWIG is extremely permissive in what it lets
2405  you get away with. In fact, you can use SWIG to go well beyond
2406  &quot;shooting yourself in the foot&quot; if dangerous programming is your goal.
2407  On the other hand, this kind of freedom may be exactly what is needed
2408  to work with complicated and unusual C/C++ applications.</P>
2409 <P> Ironically, the freedom that SWIG provides is countered by an
2410  extremely conservative approach to code generation. At it's core, SWIG
2411  tries to distill even the most advanced C++ code down to a small
2412  well-defined set of interface building techniques based on ANSI C
2413  programming. Because of this, you will find that SWIG interfaces can be
2414  easily compiled by virtually every C/C++ compiler and that they can be
2415  used on any platform. Again, this is an important part of staying out
2416  of the programmer's way----the last thing any developer wants to do is
2417  to spend their time debugging the output of a tool that relies on
2418  non-portable or unreliable programming features.</P>
2419 <HR NOSHADE>
2420 <H1><A name="Windows"></A>3 Getting started on Windows</H1>
2421
2422 <!-- INDEX -->
2423 <DIV class="sectiontoc">
2424 <UL>
2425 <LI><A href="#Windows_installation">Installation on Windows</A>
2426 <UL>
2427 <LI><A href="#Windows_executable">Windows Executable</A></LI>
2428 </UL>
2429 </LI>
2430 <LI><A href="#Windows_examples">SWIG Windows Examples</A>
2431 <UL>
2432 <LI><A href="#Windows_visual_studio">Instructions for using the Examples
2433  with Visual Studio</A>
2434 <UL>
2435 <LI><A href="#Windows_csharp">C#</A></LI>
2436 <LI><A href="#Windows_java">Java</A></LI>
2437 <LI><A href="#Windows_perl">Perl</A></LI>
2438 <LI><A href="#Windows_python">Python</A></LI>
2439 <LI><A href="#Windows_tcl">TCL</A></LI>
2440 <LI><A href="#Windows_r">R</A></LI>
2441 <LI><A href="#Windows_ruby">Ruby</A></LI>
2442 </UL>
2443 </LI>
2444 <LI><A href="#Windows_other_compilers">Instructions for using the
2445  Examples with other compilers</A></LI>
2446 </UL>
2447 </LI>
2448 <LI><A href="#Windows_cygwin_mingw">SWIG on Cygwin and MinGW</A>
2449 <UL>
2450 <LI><A href="#Windows_swig_exe">Building swig.exe on Windows</A>
2451 <UL>
2452 <LI><A href="#Windows_mingw_msys">Building swig.exe using MinGW and MSYS</A>
2453 </LI>
2454 <LI><A href="#Windows_cygwin">Building swig.exe using Cygwin</A></LI>
2455 <LI><A href="#Windows_building_alternatives">Building swig.exe
2456  alternatives</A></LI>
2457 </UL>
2458 </LI>
2459 <LI><A href="#Windows_examples_cygwin">Running the examples on Windows
2460  using Cygwin</A></LI>
2461 </UL>
2462 </LI>
2463 <LI><A href="#Windows_interface_file">Microsoft extensions and other
2464  Windows quirks</A></LI>
2465 </UL>
2466 </DIV>
2467 <!-- INDEX -->
2468 <P> This chapter describes SWIG usage on Microsoft Windows. Installing
2469  SWIG and running the examples is covered as well as building the SWIG
2470  executable. Usage within the Unix like environments MinGW and Cygwin is
2471  also detailed.</P>
2472 <H2><A name="Windows_installation"></A>3.1 Installation on Windows</H2>
2473 <P> SWIG does not come with the usual Windows type installation program,
2474  however it is quite easy to get started. The main steps are:</P>
2475 <UL>
2476 <LI>Download the swigwin zip package from the <A href="http://www.swig.org">
2477 SWIG website</A> and unzip into a directory. This is all that needs
2478  downloading for the Windows platform.</LI>
2479 <LI>Set environment variables as described in the <A href="#Windows_examples">
2480 SWIG Windows Examples</A> section in order to run examples using Visual
2481  C++.</LI>
2482 </UL>
2483 <H3><A name="Windows_executable"></A>3.1.1 Windows Executable</H3>
2484 <P> The swigwin distribution contains the SWIG Windows executable,
2485  swig.exe, which will run on 32 bit versions of Windows, ie Windows
2486  95/98/ME/NT/2000/XP. If you want to build your own swig.exe have a look
2487  at <A href="#Windows_swig_exe">Building swig.exe on Windows</A>.</P>
2488 <H2><A name="Windows_examples"></A>3.2 SWIG Windows Examples</H2>
2489 <P> Using Microsoft Visual C++ is the most common approach to compiling
2490  and linking SWIG's output. The Examples directory has a few Visual C++
2491  project files (.dsp files). These were produced by Visual C++ 6,
2492  although they should also work in Visual C++ 5. Later versions of
2493  Visual Studio should also be able to open and convert these project
2494  files. The C# examples come with .NET 2003 solution (.sln) and project
2495  files instead of Visual C++ 6 project files. The project files have
2496  been set up to execute SWIG in a custom build rule for the SWIG
2497  interface (.i) file. Alternatively run the <A href="#Windows_examples_cygwin">
2498 examples using Cygwin</A>.</P>
2499 <P> More information on each of the examples is available with the
2500  examples distributed with SWIG (Examples/index.html).</P>
2501 <H3><A name="Windows_visual_studio"></A>3.2.1 Instructions for using the
2502  Examples with Visual Studio</H3>
2503 <P> Ensure the SWIG executable is as supplied in the SWIG root directory
2504  in order for the examples to work. Most languages require some
2505  environment variables to be set<B> before</B> running Visual C++. Note
2506  that Visual C++ must be re-started to pick up any changes in
2507  environment variables. Open up an example .dsp file, Visual C++ will
2508  create a workspace for you (.dsw file). Ensure the Release build is
2509  selected then do a Rebuild All from the Build menu. The required
2510  environment variables are displayed with their current values.</P>
2511 <P> The list of required environment variables for each module language
2512  is also listed below. They are usually set from the Control Panel and
2513  System properties, but this depends on which flavour of Windows you are
2514  running. If you don't want to use environment variables then change all
2515  occurrences of the environment variables in the .dsp files with hard
2516  coded values. If you are interested in how the project files are set up
2517  there is explanatory information in some of the language module's
2518  documentation.</P>
2519 <H4><A name="Windows_csharp"></A>3.2.1.1 C#</H4>
2520 <P> The C# examples do not require any environment variables to be set
2521  as a C# project file is included. Just open up the .sln solution file
2522  in Visual Studio .NET 2003 or later, select Release Build, and do a
2523  Rebuild All from the Build menu. The accompanying C# and C++ project
2524  files are automatically used by the solution file.</P>
2525 <H4><A name="Windows_java"></A>3.2.1.2 Java</H4>
2526 <P><B> <TT>JAVA_INCLUDE</TT></B> : Set this to the directory containing
2527  jni.h
2528 <BR><B> <TT>JAVA_BIN</TT></B> : Set this to the bin directory containing
2529  javac.exe</P>
2530 <P> Example using JDK1.3:
2531 <BR> <TT>JAVA_INCLUDE: D:\jdk1.3\include
2532 <BR> JAVA_BIN: D:\jdk1.3\bin
2533 <BR></TT></P>
2534 <H4><A name="Windows_perl"></A>3.2.1.3 Perl</H4>
2535 <P><B> <TT>PERL5_INCLUDE</TT></B> : Set this to the directory containing
2536  perl.h
2537 <BR><B> <TT>PERL5_LIB</TT></B> : Set this to the Perl library including
2538  path for linking</P>
2539 <P> Example using nsPerl 5.004_04:</P>
2540 <P> <TT>PERL5_INCLUDE: D:\nsPerl5.004_04\lib\CORE
2541 <BR> PERL5_LIB: D:\nsPerl5.004_04\lib\CORE\perl.lib
2542 <BR></TT></P>
2543 <H4><A name="Windows_python"></A>3.2.1.4 Python</H4>
2544 <P><B> <TT>PYTHON_INCLUDE</TT></B> : Set this to the directory that
2545  contains python.h
2546 <BR><B> <TT>PYTHON_LIB</TT></B> : Set this to the python library
2547  including path for linking</P>
2548 <P> Example using Python 2.1.1:
2549 <BR> <TT>PYTHON_INCLUDE: D:\python21\include
2550 <BR> PYTHON_LIB: D:\python21\libs\python21.lib
2551 <BR></TT></P>
2552 <H4><A name="Windows_tcl"></A>3.2.1.5 TCL</H4>
2553 <P><B> <TT>TCL_INCLUDE</TT></B> : Set this to the directory containing
2554  tcl.h
2555 <BR><B> <TT>TCL_LIB</TT></B> : Set this to the TCL library including
2556  path for linking</P>
2557 <P> Example using ActiveTcl 8.3.3.3
2558 <BR> <TT>TCL_INCLUDE: D:\tcl\include
2559 <BR> TCL_LIB: D:\tcl\lib\tcl83.lib
2560 <BR></TT></P>
2561 <H4><A name="Windows_r"></A>3.2.1.6 R</H4>
2562 <P><B> <TT>R_INCLUDE</TT></B> : Set this to the directory containing R.h
2563 <BR><B> <TT>R_LIB</TT></B> : Set this to the R library (Rdll.lib)
2564  including path for linking. The library needs to be built as described
2565  in the R README.packages file (the pexports.exe approach is the
2566  easiest).</P>
2567 <P> Example using R 2.5.1:
2568 <BR> <TT>R_INCLUDE: C:\Program Files\R\R-2.5.1\include
2569 <BR> R_LIB: C:\Program Files\R\R-2.5.1\bin\Rdll.lib
2570 <BR></TT></P>
2571 <H4><A name="Windows_ruby"></A>3.2.1.7 Ruby</H4>
2572 <P><B> <TT>RUBY_INCLUDE</TT></B> : Set this to the directory containing
2573  ruby.h
2574 <BR><B> <TT>RUBY_LIB</TT></B> : Set this to the ruby library including
2575  path for linking</P>
2576 <P> Example using Ruby 1.6.4:
2577 <BR> <TT>RUBY_INCLUDE: D:\ruby\lib\ruby\1.6\i586-mswin32
2578 <BR> RUBY_LIB: D:\ruby\lib\mswin32-ruby16.lib
2579 <BR></TT></P>
2580 <H3><A name="Windows_other_compilers"></A>3.2.2 Instructions for using
2581  the Examples with other compilers</H3>
2582 <P> If you do not have access to Visual C++ you will have to set up
2583  project files / Makefiles for your chosen compiler. There is a section
2584  in each of the language modules detailing what needs setting up using
2585  Visual C++ which may be of some guidance. Alternatively you may want to
2586  use Cygwin as described in the following section.</P>
2587 <H2><A name="Windows_cygwin_mingw"></A>3.3 SWIG on Cygwin and MinGW</H2>
2588 <P> SWIG can also be compiled and run using <A href="http://www.cygwin.com">
2589 Cygwin</A> or <A href="http://www.mingw.org">MinGW</A> which provides a
2590  Unix like front end to Windows and comes free with gcc, an ANSI C/C++
2591  compiler. However, this is not a recommended approach as the prebuilt
2592  executable is supplied.</P>
2593 <H3><A name="Windows_swig_exe"></A>3.3.1 Building swig.exe on Windows</H3>
2594 <P> If you want to replicate the build of swig.exe that comes with the
2595  download, follow the MinGW instructions below. This is not necessary to
2596  use the supplied swig.exe. This information is provided for those that
2597  want to modify the SWIG source code in a Windows environment. Normally
2598  this is not needed, so most people will want to ignore this section.</P>
2599 <H4><A name="Windows_mingw_msys"></A>3.3.1.1 Building swig.exe using
2600  MinGW and MSYS</H4>
2601 <P> The short abbreviated instructions follow...</P>
2602 <UL>
2603 <LI>Install MinGW and MSYS from the <A href="http://www.mingw.org">MinGW</A>
2604  site. This provides a Unix environment on Windows.</LI>
2605 <LI>Follow the usual Unix instructions in the README file in the SWIG
2606  root directory to build swig.exe from the MinGW command prompt.</LI>
2607 </UL>
2608 <P> The step by step instructions to download and install MinGW and
2609  MSYS, then download and build the latest version of SWIG from SVN
2610  follow... Note that the instructions for obtaining SWIG from SVN are
2611  also online at <A href="http://www.swig.org/svn.html">SWIG SVN</A>.</P>
2612 <P><B> Pitfall note:</B> Execute the steps in the order shown and don't
2613  use spaces in path names. In fact it is best to use the default
2614  installation directories.</P>
2615 <OL>
2616 <LI> Download the following packages from the <A href="http://www.mingw.org/download.shtml">
2617 MinGW download page</A> or <A href="http://sourceforge.net/projects/mingw/files/">
2618 MinGW SourceForge download page</A>. Note that at the time of writing,
2619  the majority of these are in the Current release list and some are in
2620  the Snapshot or Previous release list.
2621 <UL>
2622 <LI>MinGW-3.1.0-1.exe</LI>
2623 <LI>MSYS-1.0.11-2004.04.30-1.exe</LI>
2624 <LI>msysDTK-1.0.1.exe</LI>
2625 <LI>bison-2.0-MSYS.tar.gz</LI>
2626 <LI>msys-autoconf-2.59.tar.bz2</LI>
2627 <LI>msys-automake-1.8.2.tar.bz2</LI>
2628 </UL>
2629 </LI>
2630 <LI> Install MinGW-3.1.0-1.exe (C:\MinGW is default location.)</LI>
2631 <LI> Install MSYS-1.0.11-2004.04.30-1.exe. Make sure you install it on
2632  the same windows drive letter as MinGW (C:\msys\1.0 is default). In the
2633  post install script,
2634 <UL>
2635 <LI>Answer y to the &quot;do you wish to continue with the post install?&quot;</LI>
2636 <LI>Answer y to the &quot;do you have MinGW installed?&quot;</LI>
2637 <LI>Type in the the folder in which you installed MinGW (C:/MinGW is
2638  default)</LI>
2639 </UL>
2640 </LI>
2641 <LI> Install msysDTK-1.0.1.exe to the same folder that you installed
2642  MSYS (C:\msys\1.0 is default).</LI>
2643 <LI> Copy the following to the MSYS install folder (C:\msys\1.0 is
2644  default):
2645 <UL>
2646 <LI>msys-automake-1.8.2.tar.bz2</LI>
2647 <LI>msys-autoconf-2.59.tar.bz2</LI>
2648 <LI>bison-2.0-MSYS.tar.gz</LI>
2649 </UL>
2650 </LI>
2651 <LI> Start the MSYS command prompt and execute:<DIV class="shell">
2652 <PRE>
2653 cd /
2654 tar -jxf msys-automake-1.8.2.tar.bz2 
2655 tar -jxf msys-autoconf-2.59.tar.bz2
2656 tar -zxf bison-2.0-MSYS.tar.gz   
2657 </PRE>
2658 </DIV></LI>
2659 <LI> To get the latest SWIG SVN (version from Subversion source
2660  control), type in the following:<DIV class="shell">
2661 <PRE>
2662 mkdir /usr/src
2663 cd /usr/src
2664 svn co https://swig.svn.sourceforge.net/svnroot/swig/trunk swig
2665 </PRE>
2666 </DIV><B> Pitfall note:</B> If you want to check out SWIG to a different
2667  folder to the proposed /usr/src/swig, do not use MSYS emulated windows
2668  drive letters, because the autotools will fail miserably on those.</LI>
2669 <LI> You are now ready to build SWIG. Execute the following commands to
2670  build swig.exe:<DIV class="shell">
2671 <PRE>
2672 cd /usr/src/swig
2673 ./autogen.sh
2674 ./configure
2675 make
2676 </PRE>
2677 </DIV></LI>
2678 </OL>
2679 <H4><A name="Windows_cygwin"></A>3.3.1.2 Building swig.exe using Cygwin</H4>
2680 <P> Note that SWIG can also be built using Cygwin. However, SWIG will
2681  then require the Cygwin DLL when executing. Follow the Unix
2682  instructions in the README file in the SWIG root directory. Note that
2683  the Cygwin environment will also allow one to regenerate the autotool
2684  generated files which are supplied with the release distribution. These
2685  files are generated using the <TT>autogen.sh</TT> script and will only
2686  need regenerating in circumstances such as changing the build system.</P>
2687 <H4><A name="Windows_building_alternatives"></A>3.3.1.3 Building
2688  swig.exe alternatives</H4>
2689 <P> If you don't want to install Cygwin or MinGW, use a different
2690  compiler to build SWIG. For example, all the source code files can be
2691  added to a Visual C++ project file in order to build swig.exe from the
2692  Visual C++ IDE.</P>
2693 <H3><A name="Windows_examples_cygwin"></A>3.3.2 Running the examples on
2694  Windows using Cygwin</H3>
2695 <P> The examples and test-suite work as successfully on Cygwin as on any
2696  other Unix operating system. The modules which are known to work are
2697  Python, Tcl, Perl, Ruby, Java and C#. Follow the Unix instructions in
2698  the README file in the SWIG root directory to build the examples.</P>
2699 <H2><A name="Windows_interface_file"></A>3.4 Microsoft extensions and
2700  other Windows quirks</H2>
2701 <P> A common problem when using SWIG on Windows are the Microsoft
2702  function calling conventions which are not in the C++ standard. SWIG
2703  parses ISO C/C++ so cannot deal with proprietary conventions such as <TT>
2704 __declspec(dllimport)</TT>, <TT>__stdcall</TT> etc. There is a Windows
2705  interface file, <TT>windows.i</TT>, to deal with these calling
2706  conventions though. The file also contains typemaps for handling
2707  commonly used Windows specific types such as <TT>__int64</TT>, <TT>BOOL</TT>
2708 , <TT>DWORD</TT> etc. Include it like you would any other interface
2709  file, for example:</P>
2710 <DIV class="code">
2711 <PRE>
2712 %include &lt;windows.i&gt;
2713
2714 __declspec(dllexport) ULONG __stdcall foo(DWORD, __int32);
2715 </PRE>
2716 </DIV><HR NOSHADE>
2717 <H1><A name="Scripting"></A>4 Scripting Languages</H1>
2718
2719 <!-- INDEX -->
2720 <DIV class="sectiontoc">
2721 <UL>
2722 <LI><A href="#Scripting_nn2">The two language view of the world</A></LI>
2723 <LI><A href="#Scripting_nn3">How does a scripting language talk to C?</A>
2724 <UL>
2725 <LI><A href="#Scripting_nn4">Wrapper functions</A></LI>
2726 <LI><A href="#Scripting_nn5">Variable linking</A></LI>
2727 <LI><A href="#Scripting_nn6">Constants</A></LI>
2728 <LI><A href="#Scripting_nn7">Structures and classes</A></LI>
2729 <LI><A href="#Scripting_nn8">Proxy classes</A></LI>
2730 </UL>
2731 </LI>
2732 <LI><A href="#Scripting_nn9">Building scripting language extensions</A>
2733 <UL>
2734 <LI><A href="#Scripting_nn10">Shared libraries and dynamic loading</A></LI>
2735 <LI><A href="#Scripting_nn11">Linking with shared libraries</A></LI>
2736 <LI><A href="#Scripting_nn12">Static linking</A></LI>
2737 </UL>
2738 </LI>
2739 </UL>
2740 </DIV>
2741 <!-- INDEX -->
2742 <P> This chapter provides a brief overview of scripting language
2743  extension programming and the mechanisms by which scripting language
2744  interpreters access C and C++ code.</P>
2745 <H2><A name="Scripting_nn2"></A>4.1 The two language view of the world</H2>
2746 <P> When a scripting language is used to control a C program, the
2747  resulting system tends to look as follows:</P>
2748 <CENTER><IMG alt="Scripting language input - C/C++ functions output" HEIGHT="149"
2749 src="ch2.1.png" WIDTH="377"></CENTER>
2750 <P> In this programming model, the scripting language interpreter is
2751  used for high level control whereas the underlying functionality of the
2752  C/C++ program is accessed through special scripting language
2753  &quot;commands.&quot; If you have ever tried to write your own simple command
2754  interpreter, you might view the scripting language approach to be a
2755  highly advanced implementation of that. Likewise, If you have ever used
2756  a package such as MATLAB or IDL, it is a very similar model--the
2757  interpreter executes user commands and scripts. However, most of the
2758  underlying functionality is written in a low-level language like C or
2759  Fortran.</P>
2760 <P> The two-language model of computing is extremely powerful because it
2761  exploits the strengths of each language. C/C++ can be used for maximal
2762  performance and complicated systems programming tasks. Scripting
2763  languages can be used for rapid prototyping, interactive debugging,
2764  scripting, and access to high-level data structures such associative
2765  arrays.</P>
2766 <H2><A name="Scripting_nn3"></A>4.2 How does a scripting language talk
2767  to C?</H2>
2768 <P> Scripting languages are built around a parser that knows how to
2769  execute commands and scripts. Within this parser, there is a mechanism
2770  for executing commands and accessing variables. Normally, this is used
2771  to implement the builtin features of the language. However, by
2772  extending the interpreter, it is usually possible to add new commands
2773  and variables. To do this, most languages define a special API for
2774  adding new commands. Furthermore, a special foreign function interface
2775  defines how these new commands are supposed to hook into the
2776  interpreter.</P>
2777 <P> Typically, when you add a new command to a scripting interpreter you
2778  need to do two things; first you need to write a special &quot;wrapper&quot;
2779  function that serves as the glue between the interpreter and the
2780  underlying C function. Then you need to give the interpreter
2781  information about the wrapper by providing details about the name of
2782  the function, arguments, and so forth. The next few sections illustrate
2783  the process.</P>
2784 <H3><A name="Scripting_nn4"></A>4.2.1 Wrapper functions</H3>
2785 <P> Suppose you have an ordinary C function like this :</P>
2786 <DIV class="code">
2787 <PRE>
2788 int fact(int n) {
2789         if (n &lt;= 1) return 1;
2790         else return n*fact(n-1);
2791 }
2792 </PRE>
2793 </DIV>
2794 <P> In order to access this function from a scripting language, it is
2795  necessary to write a special &quot;wrapper&quot; function that serves as the glue
2796  between the scripting language and the underlying C function. A wrapper
2797  function must do three things :</P>
2798 <UL>
2799 <LI>Gather function arguments and make sure they are valid.</LI>
2800 <LI>Call the C function.</LI>
2801 <LI>Convert the return value into a form recognized by the scripting
2802  language.</LI>
2803 </UL>
2804 <P> As an example, the Tcl wrapper function for the <TT>fact()</TT>
2805  function above example might look like the following :</P>
2806 <DIV class="code">
2807 <PRE>
2808 int wrap_fact(ClientData clientData, Tcl_Interp *interp,
2809                 int argc, char *argv[]) {
2810         int result;
2811         int arg0;
2812         if (argc != 2) {
2813                 interp-&gt;result = &quot;wrong # args&quot;;
2814                 return TCL_ERROR;
2815         }
2816         arg0 = atoi(argv[1]);
2817         result = fact(arg0);
2818         sprintf(interp-&gt;result,&quot;%d&quot;, result);
2819         return TCL_OK;
2820 }
2821
2822 </PRE>
2823 </DIV>
2824 <P> Once you have created a wrapper function, the final step is to tell
2825  the scripting language about the new function. This is usually done in
2826  an initialization function called by the language when the module is
2827  loaded. For example, adding the above function to the Tcl interpreter
2828  requires code like the following :</P>
2829 <DIV class="code">
2830 <PRE>
2831 int Wrap_Init(Tcl_Interp *interp) {
2832         Tcl_CreateCommand(interp, &quot;fact&quot;, wrap_fact, (ClientData) NULL,
2833                                 (Tcl_CmdDeleteProc *) NULL);
2834         return TCL_OK;
2835 }
2836 </PRE>
2837 </DIV>
2838 <P> When executed, Tcl will now have a new command called &quot;<TT>fact</TT>
2839 &quot; that you can use like any other Tcl command.</P>
2840 <P> Although the process of adding a new function to Tcl has been
2841  illustrated, the procedure is almost identical for Perl and Python.
2842  Both require special wrappers to be written and both need additional
2843  initialization code. Only the specific details are different.</P>
2844 <H3><A name="Scripting_nn5"></A>4.2.2 Variable linking</H3>
2845 <P> Variable linking refers to the problem of mapping a C/C++ global
2846  variable to a variable in the scripting language interpreter. For
2847  example, suppose you had the following variable:</P>
2848 <DIV class="code">
2849 <PRE>
2850 double Foo = 3.5;
2851 </PRE>
2852 </DIV>
2853 <P> It might be nice to access it from a script as follows (shown for
2854  Perl):</P>
2855 <DIV class="targetlang">
2856 <PRE>
2857 $a = $Foo * 2.3;   # Evaluation
2858 $Foo = $a + 2.0;   # Assignment
2859 </PRE>
2860 </DIV>
2861 <P> To provide such access, variables are commonly manipulated using a
2862  pair of get/set functions. For example, whenever the value of a
2863  variable is read, a &quot;get&quot; function is invoked. Similarly, whenever the
2864  value of a variable is changed, a &quot;set&quot; function is called.</P>
2865 <P> In many languages, calls to the get/set functions can be attached to
2866  evaluation and assignment operators. Therefore, evaluating a variable
2867  such as <TT>$Foo</TT> might implicitly call the get function.
2868  Similarly, typing <TT>$Foo = 4</TT> would call the underlying set
2869  function to change the value.</P>
2870 <H3><A name="Scripting_nn6"></A>4.2.3 Constants</H3>
2871 <P> In many cases, a C program or library may define a large collection
2872  of constants. For example:</P>
2873 <DIV class="code">
2874 <PRE>
2875 #define RED   0xff0000
2876 #define BLUE  0x0000ff
2877 #define GREEN 0x00ff00
2878 </PRE>
2879 </DIV>
2880 <P> To make constants available, their values can be stored in scripting
2881  language variables such as <TT>$RED</TT>, <TT>$BLUE</TT>, and <TT>
2882 $GREEN</TT>. Virtually all scripting languages provide C functions for
2883  creating variables so installing constants is usually a trivial
2884  exercise.</P>
2885 <H3><A name="Scripting_nn7"></A>4.2.4 Structures and classes</H3>
2886 <P> Although scripting languages have no trouble accessing simple
2887  functions and variables, accessing C/C++ structures and classes present
2888  a different problem. This is because the implementation of structures
2889  is largely related to the problem of data representation and layout.
2890  Furthermore, certain language features are difficult to map to an
2891  interpreter. For instance, what does C++ inheritance mean in a Perl
2892  interface?</P>
2893 <P> The most straightforward technique for handling structures is to
2894  implement a collection of accessor functions that hide the underlying
2895  representation of a structure. For example,</P>
2896 <DIV class="code">
2897 <PRE>
2898 struct Vector {
2899         Vector();
2900         ~Vector();
2901         double x,y,z;
2902 };
2903
2904 </PRE>
2905 </DIV>
2906 <P> can be transformed into the following set of functions :</P>
2907 <DIV class="code">
2908 <PRE>
2909 Vector *new_Vector();
2910 void delete_Vector(Vector *v);
2911 double Vector_x_get(Vector *v);
2912 double Vector_y_get(Vector *v);
2913 double Vector_z_get(Vector *v);
2914 void Vector_x_set(Vector *v, double x);
2915 void Vector_y_set(Vector *v, double y);
2916 void Vector_z_set(Vector *v, double z);
2917
2918 </PRE>
2919 </DIV>
2920 <P> Now, from an interpreter these function might be used as follows:</P>
2921 <DIV class="targetlang">
2922 <PRE>
2923 % set v [new_Vector]
2924 % Vector_x_set $v 3.5
2925 % Vector_y_get $v
2926 % delete_Vector $v
2927 % ...
2928 </PRE>
2929 </DIV>
2930 <P> Since accessor functions provide a mechanism for accessing the
2931  internals of an object, the interpreter does not need to know anything
2932  about the actual representation of a <TT>Vector</TT>.</P>
2933 <H3><A name="Scripting_nn8"></A>4.2.5 Proxy classes</H3>
2934 <P> In certain cases, it is possible to use the low-level accessor
2935  functions to create a proxy class, also known as a shadow class. A
2936  proxy class is a special kind of object that gets created in a
2937  scripting language to access a C/C++ class (or struct) in a way that
2938  looks like the original structure (that is, it proxies the real C++
2939  class). For example, if you have the following C definition :</P>
2940 <DIV class="code">
2941 <PRE>
2942 class Vector {
2943 public:
2944         Vector();
2945         ~Vector();
2946         double x,y,z;
2947 };
2948 </PRE>
2949 </DIV>
2950 <P> A proxy classing mechanism would allow you to access the structure
2951  in a more natural manner from the interpreter. For example, in Python,
2952  you might want to do this:</P>
2953 <DIV class="targetlang">
2954 <PRE>
2955 &gt;&gt;&gt; v = Vector()
2956 &gt;&gt;&gt; v.x = 3
2957 &gt;&gt;&gt; v.y = 4
2958 &gt;&gt;&gt; v.z = -13
2959 &gt;&gt;&gt; ...
2960 &gt;&gt;&gt; del v
2961 </PRE>
2962 </DIV>
2963 <P> Similarly, in Perl5 you may want the interface to work like this:</P>
2964 <DIV class="targetlang">
2965 <PRE>
2966 $v = new Vector;
2967 $v-&gt;{x} = 3;
2968 $v-&gt;{y} = 4;
2969 $v-&gt;{z} = -13;
2970
2971 </PRE>
2972 </DIV>
2973 <P> Finally, in Tcl :</P>
2974 <DIV class="targetlang">
2975 <PRE>
2976 Vector v
2977 v configure -x 3 -y 4 -z 13
2978
2979 </PRE>
2980 </DIV>
2981 <P> When proxy classes are used, two objects are at really work--one in
2982  the scripting language, and an underlying C/C++ object. Operations
2983  affect both objects equally and for all practical purposes, it appears
2984  as if you are simply manipulating a C/C++ object.</P>
2985 <H2><A name="Scripting_nn9"></A>4.3 Building scripting language
2986  extensions</H2>
2987 <P> The final step in using a scripting language with your C/C++
2988  application is adding your extensions to the scripting language itself.
2989  There are two primary approaches for doing this. The preferred
2990  technique is to build a dynamically loadable extension in the form a
2991  shared library. Alternatively, you can recompile the scripting language
2992  interpreter with your extensions added to it.</P>
2993 <H3><A name="Scripting_nn10"></A>4.3.1 Shared libraries and dynamic
2994  loading</H3>
2995 <P> To create a shared library or DLL, you often need to look at the
2996  manual pages for your compiler and linker. However, the procedure for a
2997  few common machines is shown below:</P>
2998 <DIV class="shell">
2999 <PRE>
3000 # Build a shared library for Solaris
3001 gcc -c example.c example_wrap.c -I/usr/local/include
3002 ld -G example.o example_wrap.o -o example.so
3003
3004 # Build a shared library for Linux
3005 gcc -fpic -c example.c example_wrap.c -I/usr/local/include
3006 gcc -shared example.o example_wrap.o -o example.so
3007
3008 # Build a shared library for Irix
3009 gcc -c example.c example_wrap.c -I/usr/local/include
3010 ld -shared example.o example_wrap.o -o example.so
3011
3012 </PRE>
3013 </DIV>
3014 <P> To use your shared library, you simply use the corresponding command
3015  in the scripting language (load, import, use, etc...). This will import
3016  your module and allow you to start using it. For example:</P>
3017 <DIV class="targetlang">
3018 <PRE>
3019 % load ./example.so
3020 % fact 4
3021 24
3022 %
3023 </PRE>
3024 </DIV>
3025 <P> When working with C++ codes, the process of building shared
3026  libraries may be more complicated--primarily due to the fact that C++
3027  modules may need additional code in order to operate correctly. On many
3028  machines, you can build a shared C++ module by following the above
3029  procedures, but changing the link line to the following :</P>
3030 <DIV class="shell">
3031 <PRE>
3032 c++ -shared example.o example_wrap.o -o example.so
3033 </PRE>
3034 </DIV>
3035 <H3><A name="Scripting_nn11"></A>4.3.2 Linking with shared libraries</H3>
3036 <P> When building extensions as shared libraries, it is not uncommon for
3037  your extension to rely upon other shared libraries on your machine. In
3038  order for the extension to work, it needs to be able to find all of
3039  these libraries at run-time. Otherwise, you may get an error such as
3040  the following :</P>
3041 <DIV class="targetlang">
3042 <PRE>
3043 &gt;&gt;&gt; import graph
3044 Traceback (innermost last):
3045   File &quot;&lt;stdin&gt;&quot;, line 1, in ?
3046   File &quot;/home/sci/data1/beazley/graph/graph.py&quot;, line 2, in ?
3047     import graphc
3048 ImportError:  1101:/home/sci/data1/beazley/bin/python: rld: Fatal Error: cannot 
3049 successfully map soname 'libgraph.so' under any of the filenames /usr/lib/libgraph.so:/
3050 lib/libgraph.so:/lib/cmplrs/cc/libgraph.so:/usr/lib/cmplrs/cc/libgraph.so:
3051 &gt;&gt;&gt;
3052 </PRE>
3053 </DIV>
3054 <P> What this error means is that the extension module created by SWIG
3055  depends upon a shared library called &quot;<TT>libgraph.so</TT>&quot; that the
3056  system was unable to locate. To fix this problem, there are a few
3057  approaches you can take.</P>
3058 <UL>
3059 <LI>Link your extension and explicitly tell the linker where the
3060  required libraries are located. Often times, this can be done with a
3061  special linker flag such as <TT>-R</TT>, <TT>-rpath</TT>, etc. This is
3062  not implemented in a standard manner so read the man pages for your
3063  linker to find out more about how to set the search path for shared
3064  libraries.</LI>
3065 <LI>Put shared libraries in the same directory as the executable. This
3066  technique is sometimes required for correct operation on non-Unix
3067  platforms.</LI>
3068 <LI>Set the UNIX environment variable <TT>LD_LIBRARY_PATH</TT> to the
3069  directory where shared libraries are located before running Python.
3070  Although this is an easy solution, it is not recommended. Consider
3071  setting the path using linker options instead.</LI>
3072 </UL>
3073 <H3><A name="Scripting_nn12"></A>4.3.3 Static linking</H3>
3074 <P> With static linking, you rebuild the scripting language interpreter
3075  with extensions. The process usually involves compiling a short main
3076  program that adds your customized commands to the language and starts
3077  the interpreter. You then link your program with a library to produce a
3078  new scripting language executable.</P>
3079 <P> Although static linking is supported on all platforms, this is not
3080  the preferred technique for building scripting language extensions. In
3081  fact, there are very few practical reasons for doing this--consider
3082  using shared libraries instead.</P>
3083 <HR NOSHADE>
3084 <H1><A name="SWIG"></A>5 SWIG Basics</H1>
3085
3086 <!-- INDEX -->
3087 <DIV class="sectiontoc">
3088 <UL>
3089 <LI><A href="#SWIG_nn2">Running SWIG</A>
3090 <UL>
3091 <LI><A href="#SWIG_nn3">Input format</A></LI>
3092 <LI><A href="#output">SWIG Output</A></LI>
3093 <LI><A href="#SWIG_nn5">Comments</A></LI>
3094 <LI><A href="#SWIG_nn6">C Preprocessor</A></LI>
3095 <LI><A href="#SWIG_nn7">SWIG Directives</A></LI>
3096 <LI><A href="#SWIG_nn8">Parser Limitations</A></LI>
3097 </UL>
3098 </LI>
3099 <LI><A href="#SWIG_nn9">Wrapping Simple C Declarations</A>
3100 <UL>
3101 <LI><A href="#SWIG_nn10">Basic Type Handling</A></LI>
3102 <LI><A href="#SWIG_nn11">Global Variables</A></LI>
3103 <LI><A href="#SWIG_nn12">Constants</A></LI>
3104 <LI><A href="#SWIG_nn13">A brief word about <TT>const</TT></A></LI>
3105 <LI><A href="#SWIG_nn14">A cautionary tale of <TT>char *</TT></A></LI>
3106 </UL>
3107 </LI>
3108 <LI><A href="#SWIG_nn15">Pointers and complex objects</A>
3109 <UL>
3110 <LI><A href="#SWIG_nn16">Simple pointers</A></LI>
3111 <LI><A href="#SWIG_nn17">Run time pointer type checking</A></LI>
3112 <LI><A href="#SWIG_nn18">Derived types, structs, and classes</A></LI>
3113 <LI><A href="#SWIG_nn19">Undefined datatypes</A></LI>
3114 <LI><A href="#SWIG_nn20">Typedef</A></LI>
3115 </UL>
3116 </LI>
3117 <LI><A href="#SWIG_nn21">Other Practicalities</A>
3118 <UL>
3119 <LI><A href="#SWIG_nn22">Passing structures by value</A></LI>
3120 <LI><A href="#SWIG_nn23">Return by value</A></LI>
3121 <LI><A href="#SWIG_nn24">Linking to structure variables</A></LI>
3122 <LI><A href="#SWIG_nn25">Linking to <TT>char *</TT></A></LI>
3123 <LI><A href="#SWIG_nn26">Arrays</A></LI>
3124 <LI><A href="#SWIG_readonly_variables">Creating read-only variables</A></LI>
3125 <LI><A href="#SWIG_rename_ignore">Renaming and ignoring declarations</A></LI>
3126 <LI><A href="#SWIG_default_args">Default/optional arguments</A></LI>
3127 <LI><A href="#SWIG_nn30">Pointers to functions and callbacks</A></LI>
3128 </UL>
3129 </LI>
3130 <LI><A href="#SWIG_nn31">Structures and unions</A>
3131 <UL>
3132 <LI><A href="#SWIG_nn32">Typedef and structures</A></LI>
3133 <LI><A href="#SWIG_nn33">Character strings and structures</A></LI>
3134 <LI><A href="#SWIG_nn34">Array members</A></LI>
3135 <LI><A href="#SWIG_structure_data_members">Structure data members</A></LI>
3136 <LI><A href="#SWIG_nn36">C constructors and destructors</A></LI>
3137 <LI><A href="#SWIG_adding_member_functions">Adding member functions to C
3138  structures</A></LI>
3139 <LI><A href="#SWIG_nested_structs">Nested structures</A></LI>
3140 <LI><A href="#SWIG_nn39">Other things to note about structure wrapping</A>
3141 </LI>
3142 </UL>
3143 </LI>
3144 <LI><A href="#SWIG_nn40">Code Insertion</A>
3145 <UL>
3146 <LI><A href="#SWIG_nn41">The output of SWIG</A></LI>
3147 <LI><A href="#SWIG_nn42">Code insertion blocks</A></LI>
3148 <LI><A href="#SWIG_nn43">Inlined code blocks</A></LI>
3149 <LI><A href="#SWIG_nn44">Initialization blocks</A></LI>
3150 </UL>
3151 </LI>
3152 <LI><A href="#SWIG_nn45">An Interface Building Strategy</A>
3153 <UL>
3154 <LI><A href="#SWIG_nn46">Preparing a C program for SWIG</A></LI>
3155 <LI><A href="#SWIG_nn47">The SWIG interface file</A></LI>
3156 <LI><A href="#SWIG_nn48">Why use separate interface files?</A></LI>
3157 <LI><A href="#SWIG_nn49">Getting the right header files</A></LI>
3158 <LI><A href="#SWIG_nn50">What to do with main()</A></LI>
3159 </UL>
3160 </LI>
3161 </UL>
3162 </DIV>
3163 <!-- INDEX -->
3164 <P> This chapter describes the basic operation of SWIG, the structure of
3165  its input files, and how it handles standard ANSI C declarations. C++
3166  support is described in the next chapter. However, C++ programmers
3167  should still read this chapter to understand the basics. Specific
3168  details about each target language are described in later chapters.</P>
3169 <H2><A name="SWIG_nn2"></A>5.1 Running SWIG</H2>
3170 <P> To run SWIG, use the <TT>swig</TT> command with options options and
3171  a filename like this:</P>
3172 <DIV class="shell">
3173 <PRE>
3174 swig [ <EM>options</EM> ] filename
3175 </PRE>
3176 </DIV>
3177 <P> where <TT>filename</TT> is a SWIG interface file or a C/C++ header
3178  file. Below is a subset of<EM> options</EM> that can be used.
3179  Additional options are also defined for each target language. A full
3180  list can be obtained by typing <TT>swig -help</TT> or <TT>swig -<EM>
3181 lang</EM> -help</TT>.</P>
3182 <DIV class="shell">
3183 <PRE>
3184 -allegrocl            Generate ALLEGROCL wrappers
3185 -chicken              Generate CHICKEN wrappers
3186 -clisp                Generate CLISP wrappers
3187 -cffi                 Generate CFFI wrappers
3188 -csharp               Generate C# wrappers
3189 -guile                Generate Guile wrappers
3190 -java                 Generate Java wrappers
3191 -lua                  Generate Lua wrappers
3192 -modula3              Generate Modula 3 wrappers
3193 -mzscheme             Generate Mzscheme wrappers
3194 -ocaml                Generate Ocaml wrappers
3195 -perl                 Generate Perl wrappers
3196 -php                  Generate PHP wrappers
3197 -pike                 Generate Pike wrappers
3198 -python               Generate Python wrappers
3199 -r                    Generate R (aka GNU S) wrappers
3200 -ruby                 Generate Ruby wrappers
3201 -sexp                 Generate Lisp S-Expressions wrappers
3202 -tcl                  Generate Tcl wrappers
3203 -uffi                 Generate Common Lisp / UFFI wrappers
3204 -xml                  Generate XML wrappers
3205
3206 -c++                  Enable C++ parsing
3207 -D<EM>symbol</EM>              Define a preprocessor symbol
3208 -Fstandard            Display error/warning messages in commonly used format
3209 -Fmicrosoft           Display error/warning messages in Microsoft format
3210 -help                 Display all options
3211 -I<EM>dir</EM>                 Add a directory to the file include path
3212 -l<EM>file</EM>                Include a SWIG library file.
3213 -module <EM>name</EM>          Set the name of the SWIG module
3214 -o <EM>outfile</EM>            Name of output file
3215 -outcurrentdir        Set default output dir to current dir instead of input file's path
3216 -outdir <EM>dir</EM>           Set language specific files output directory
3217 -swiglib              Show location of SWIG library
3218 -version              Show SWIG version number
3219
3220 </PRE>
3221 </DIV>
3222 <H3><A name="SWIG_nn3"></A>5.1.1 Input format</H3>
3223 <P> As input, SWIG expects a file containing ANSI C/C++ declarations and
3224  special SWIG directives. More often than not, this is a special SWIG
3225  interface file which is usually denoted with a special <TT>.i</TT> or <TT>
3226 .swg</TT> suffix. In certain cases, SWIG can be used directly on raw
3227  header files or source files. However, this is not the most typical
3228  case and there are several reasons why you might not want to do this
3229  (described later).</P>
3230 <P> The most common format of a SWIG interface is as follows:</P>
3231 <DIV class="code">
3232 <PRE>
3233 %module mymodule 
3234 %{
3235 #include &quot;myheader.h&quot;
3236 %}
3237 // Now list ANSI C/C++ declarations
3238 int foo;
3239 int bar(int x);
3240 ...
3241 </PRE>
3242 </DIV>
3243 <P> The module name is supplied using the special <TT>%module</TT>
3244  directive. Modules are described further in the <A href="#Modules_introduction">
3245 Modules Introduction</A> section.</P>
3246 <P> Everything in the <TT>%{ ... %}</TT> block is simply copied verbatim
3247  to the resulting wrapper file created by SWIG. This section is almost
3248  always used to include header files and other declarations that are
3249  required to make the generated wrapper code compile. It is important to
3250  emphasize that just because you include a declaration in a SWIG input
3251  file, that declaration does<EM> not</EM> automatically appear in the
3252  generated wrapper code---therefore you need to make sure you include
3253  the proper header files in the <TT>%{ ... %}</TT> section. It should be
3254  noted that the text enclosed in <TT>%{ ... %}</TT> is not parsed or
3255  interpreted by SWIG. The <TT>%{...%}</TT> syntax and semantics in SWIG
3256  is analogous to that of the declarations section used in input files to
3257  parser generation tools such as yacc or bison.</P>
3258 <H3><A name="output"></A>5.1.2 SWIG Output</H3>
3259 <P> The output of SWIG is a C/C++ file that contains all of the wrapper
3260  code needed to build an extension module. SWIG may generate some
3261  additional files depending on the target language. By default, an input
3262  file with the name <TT>file.i</TT> is transformed into a file <TT>
3263 file_wrap.c</TT> or <TT>file_wrap.cxx</TT> (depending on whether or not
3264  the <TT>-c++</TT> option has been used). The name of the output file
3265  can be changed using the <TT>-o</TT> option. In certain cases, file
3266  suffixes are used by the compiler to determine the source language (C,
3267  C++, etc.). Therefore, you have to use the <TT>-o</TT> option to change
3268  the suffix of the SWIG-generated wrapper file if you want something
3269  different than the default. For example:</P>
3270 <DIV class="shell">
3271 <PRE>
3272 $ swig -c++ -python -o example_wrap.cpp example.i
3273 </PRE>
3274 </DIV>
3275 <P> The C/C++ output file created by SWIG often contains everything that
3276  is needed to construct a extension module for the target scripting
3277  language. SWIG is not a stub compiler nor is it usually necessary to
3278  edit the output file (and if you look at the output, you probably won't
3279  want to). To build the final extension module, the SWIG output file is
3280  compiled and linked with the rest of your C/C++ program to create a
3281  shared library.</P>
3282 <P> Many target languages will also generate proxy class files in the
3283  target language. The default output directory for these language
3284  specific files is the same directory as the generated C/C++ file. This
3285  can be modified using the <TT>-outdir</TT> option. For example:</P>
3286 <DIV class="shell">
3287 <PRE>
3288 $ swig -c++ -python -outdir pyfiles -o cppfiles/example_wrap.cpp example.i
3289 </PRE>
3290 </DIV>
3291 <P> If the directories <TT>cppfiles</TT> and <TT>pyfiles</TT> exist, the
3292  following will be generated:</P>
3293 <DIV class="shell">
3294 <PRE>
3295 cppfiles/example_wrap.cpp
3296 pyfiles/example.py
3297 </PRE>
3298 </DIV>
3299 <P> If the <TT>-outcurrentdir</TT> option is used (without <TT>-o</TT>)
3300  then SWIG behaves like a typical C/C++ compiler and the default output
3301  directory is then the current directory. Without this option the
3302  default output directory is the path to the input file. If <TT>-o</TT>
3303  and <TT>-outcurrentdir</TT> are used together, <TT>-outcurrentdir</TT>
3304  is effectively ignored as the output directory for the language files
3305  is the same directory as the generated C/C++ file if not overidden with
3306  <TT>-outdir</TT>.</P>
3307 <H3><A name="SWIG_nn5"></A>5.1.3 Comments</H3>
3308 <P> C and C++ style comments may appear anywhere in interface files. In
3309  previous versions of SWIG, comments were used to generate documentation
3310  files. However, this feature is currently under repair and will
3311  reappear in a later SWIG release.</P>
3312 <H3><A name="SWIG_nn6"></A>5.1.4 C Preprocessor</H3>
3313 <P> Like C, SWIG preprocesses all input files through an enhanced
3314  version of the C preprocessor. All standard preprocessor features are
3315  supported including file inclusion, conditional compilation and macros.
3316  However, <TT>#include</TT> statements are ignored unless the <TT>
3317 -includeall</TT> command line option has been supplied. The reason for
3318  disabling includes is that SWIG is sometimes used to process raw C
3319  header files. In this case, you usually only want the extension module
3320  to include functions in the supplied header file rather than everything
3321  that might be included by that header file (i.e., system headers, C
3322  library functions, etc.).</P>
3323 <P> It should also be noted that the SWIG preprocessor skips all text
3324  enclosed inside a <TT>%{...%}</TT> block. In addition, the preprocessor
3325  includes a number of macro handling enhancements that make it more
3326  powerful than the normal C preprocessor. These extensions are described
3327  in the &quot;<A href="#Preprocessor">Preprocessor</A>&quot; chapter.</P>
3328 <H3><A name="SWIG_nn7"></A>5.1.5 SWIG Directives</H3>
3329 <P> Most of SWIG's operation is controlled by special directives that
3330  are always preceded by a &quot;<TT>%</TT>&quot; to distinguish them from normal C
3331  declarations. These directives are used to give SWIG hints or to alter
3332  SWIG's parsing behavior in some manner.</P>
3333 <P> Since SWIG directives are not legal C syntax, it is generally not
3334  possible to include them in header files. However, SWIG directives can
3335  be included in C header files using conditional compilation like this:</P>
3336 <DIV class="code">
3337 <PRE>
3338 /* header.h  --- Some header file */
3339
3340 /* SWIG directives -- only seen if SWIG is running */ 
3341 #ifdef SWIG
3342 %module foo
3343 #endif
3344 </PRE>
3345 </DIV>
3346 <P> <TT>SWIG</TT> is a special preprocessing symbol defined by SWIG when
3347  it is parsing an input file.</P>
3348 <H3><A name="SWIG_nn8"></A>5.1.6 Parser Limitations</H3>
3349 <P> Although SWIG can parse most C/C++ declarations, it does not provide
3350  a complete C/C++ parser implementation. Most of these limitations
3351  pertain to very complicated type declarations and certain advanced C++
3352  features. Specifically, the following features are not currently
3353  supported:</P>
3354 <UL>
3355 <LI>Non-conventional type declarations. For example, SWIG does not
3356  support declarations such as the following (even though this is legal
3357  C):<DIV class="code">
3358 <PRE>
3359 /* Non-conventional placement of storage specifier (extern) */
3360 const int extern Number;
3361
3362 /* Extra declarator grouping */
3363 Matrix (foo);    // A global variable
3364
3365 /* Extra declarator grouping in parameters */
3366 void bar(Spam (Grok)(Doh));
3367
3368 </PRE>
3369 </DIV>
3370 <P> In practice, few (if any) C programmers actually write code like
3371  this since this style is never featured in programming books. However,
3372  if you're feeling particularly obfuscated, you can certainly break SWIG
3373  (although why would you want to?).</P>
3374 </LI>
3375 <LI>Running SWIG on C++ source files (what would appear in a .C or .cxx
3376  file) is not recommended. Even though SWIG can parse C++ class
3377  declarations, it ignores declarations that are decoupled from their
3378  original class definition (the declarations are parsed, but a lot of
3379  warning messages may be generated). For example:<DIV class="code">
3380 <PRE>
3381 /* Not supported by SWIG */
3382 int foo::bar(int) {
3383     ... whatever ...
3384 }
3385 </PRE>
3386 </DIV></LI>
3387 <LI>Certain advanced features of C++ such as nested classes are not yet
3388  supported. Please see the section on using SWIG with C++ for more
3389  information.</LI>
3390 </UL>
3391 <P> In the event of a parsing error, conditional compilation can be used
3392  to skip offending code. For example:</P>
3393 <DIV class="code">
3394 <PRE>
3395 #ifndef SWIG
3396 ... some bad declarations ...
3397 #endif
3398 </PRE>
3399 </DIV>
3400 <P> Alternatively, you can just delete the offending code from the
3401  interface file.</P>
3402 <P> One of the reasons why SWIG does not provide a full C++ parser
3403  implementation is that it has been designed to work with incomplete
3404  specifications and to be very permissive in its handling of C/C++
3405  datatypes (e.g., SWIG can generate interfaces even when there are
3406  missing class declarations or opaque datatypes). Unfortunately, this
3407  approach makes it extremely difficult to implement certain parts of a
3408  C/C++ parser as most compilers use type information to assist in the
3409  parsing of more complex declarations (for the truly curious, the
3410  primary complication in the implementation is that the SWIG parser does
3411  not utilize a separate<EM> typedef-name</EM> terminal symbol as
3412  described on p. 234 of K&amp;R).</P>
3413 <H2><A name="SWIG_nn9"></A>5.2 Wrapping Simple C Declarations</H2>
3414 <P> SWIG wraps simple C declarations by creating an interface that
3415  closely matches the way in which the declarations would be used in a C
3416  program. For example, consider the following interface file:</P>
3417 <DIV class="code">
3418 <PRE>
3419 %module example
3420
3421 %inline %{
3422 extern double sin(double x);
3423 extern int strcmp(const char *, const char *);
3424 extern int Foo;
3425 %}
3426 #define STATUS 50
3427 #define VERSION &quot;1.1&quot;
3428 </PRE>
3429 </DIV>
3430 <P> In this file, there are two functions <TT>sin()</TT> and <TT>
3431 strcmp()</TT>, a global variable <TT>Foo</TT>, and two constants <TT>
3432 STATUS</TT> and <TT>VERSION</TT>. When SWIG creates an extension module,
3433  these declarations are accessible as scripting language functions,
3434  variables, and constants respectively. For example, in Tcl:</P>
3435 <DIV class="targetlang">
3436 <PRE>
3437 % sin 3
3438 5.2335956
3439 % strcmp Dave Mike
3440 -1
3441 % puts $Foo
3442 42
3443 % puts $STATUS
3444 50
3445 % puts $VERSION
3446 1.1
3447 </PRE>
3448 </DIV>
3449 <P> Or in Python:</P>
3450 <DIV class="targetlang">
3451 <PRE>
3452 &gt;&gt;&gt; example.sin(3)
3453 5.2335956
3454 &gt;&gt;&gt; example.strcmp('Dave','Mike')
3455 -1
3456 &gt;&gt;&gt; print example.cvar.Foo
3457 42
3458 &gt;&gt;&gt; print example.STATUS
3459 50
3460 &gt;&gt;&gt; print example.VERSION
3461 1.1
3462 </PRE>
3463 </DIV>
3464 <P> Whenever possible, SWIG creates an interface that closely matches
3465  the underlying C/C++ code. However, due to subtle differences between
3466  languages, run-time environments, and semantics, it is not always
3467  possible to do so. The next few sections describes various aspects of
3468  this mapping.</P>
3469 <H3><A name="SWIG_nn10"></A>5.2.1 Basic Type Handling</H3>
3470 <P> In order to build an interface, SWIG has to convert C/C++ datatypes
3471  to equivalent types in the target language. Generally, scripting
3472  languages provide a more limited set of primitive types than C.
3473  Therefore, this conversion process involves a certain amount of type
3474  coercion.</P>
3475 <P> Most scripting languages provide a single integer type that is
3476  implemented using the <TT>int</TT> or <TT>long</TT> datatype in C. The
3477  following list shows all of the C datatypes that SWIG will convert to
3478  and from integers in the target language:</P>
3479 <DIV class="code">
3480 <PRE>
3481 int
3482 short
3483 long
3484 unsigned
3485 signed
3486 unsigned short
3487 unsigned long
3488 unsigned char
3489 signed char
3490 bool
3491 </PRE>
3492 </DIV>
3493 <P> When an integral value is converted from C, a cast is used to
3494  convert it to the representation in the target language. Thus, a 16 bit
3495  short in C may be promoted to a 32 bit integer. When integers are
3496  converted in the other direction, the value is cast back into the
3497  original C type. If the value is too large to fit, it is silently
3498  truncated.
3499 <!-- Dave: Maybe we should fix this -->
3500 </P>
3501 <P> <TT>unsigned char</TT> and <TT>signed char</TT> are special cases
3502  that are handled as small 8-bit integers. Normally, the <TT>char</TT>
3503  datatype is mapped as a one-character ASCII string.</P>
3504 <P> The <TT>bool</TT> datatype is cast to and from an integer value of 0
3505  and 1 unless the target language provides a special boolean type.</P>
3506 <P> Some care is required when working with large integer values. Most
3507  scripting languages use 32-bit integers so mapping a 64-bit long
3508  integer may lead to truncation errors. Similar problems may arise with
3509  32 bit unsigned integers (which may appear as large negative numbers).
3510  As a rule of thumb, the <TT>int</TT> datatype and all variations of <TT>
3511 char</TT> and <TT>short</TT> datatypes are safe to use. For <TT>unsigned
3512  int</TT> and <TT>long</TT> datatypes, you will need to carefully check
3513  the correct operation of your program after it has been wrapped with
3514  SWIG.</P>
3515 <P> Although the SWIG parser supports the <TT>long long</TT> datatype,
3516  not all language modules support it. This is because <TT>long long</TT>
3517  usually exceeds the integer precision available in the target language.
3518  In certain modules such as Tcl and Perl5, <TT>long long</TT> integers
3519  are encoded as strings. This allows the full range of these numbers to
3520  be represented. However, it does not allow <TT>long long</TT> values to
3521  be used in arithmetic expressions. It should also be noted that
3522  although <TT>long long</TT> is part of the ISO C99 standard, it is not
3523  universally supported by all C compilers. Make sure you are using a
3524  compiler that supports <TT>long long</TT> before trying to use this
3525  type with SWIG.</P>
3526 <P> SWIG recognizes the following floating point types :</P>
3527 <DIV class="code">
3528 <PRE>
3529 float
3530 double
3531 </PRE>
3532 </DIV>
3533 <P> Floating point numbers are mapped to and from the natural
3534  representation of floats in the target language. This is almost always
3535  a C <TT>double</TT>. The rarely used datatype of <TT>long double</TT>
3536  is not supported by SWIG.</P>
3537 <P> The <TT>char</TT> datatype is mapped into a NULL terminated ASCII
3538  string with a single character. When used in a scripting language it
3539  shows up as a tiny string containing the character value. When
3540  converting the value back into C, SWIG takes a character string from
3541  the scripting language and strips off the first character as the char
3542  value. Thus if the value &quot;foo&quot; is assigned to a <TT>char</TT> datatype,
3543  it gets the value `f'.</P>
3544 <P> The <TT>char *</TT> datatype is handled as a NULL-terminated ASCII
3545  string. SWIG maps this into a 8-bit character string in the target
3546  scripting language. SWIG converts character strings in the target
3547  language to NULL terminated strings before passing them into C/C++. The
3548  default handling of these strings does not allow them to have embedded
3549  NULL bytes. Therefore, the <TT>char *</TT> datatype is not generally
3550  suitable for passing binary data. However, it is possible to change
3551  this behavior by defining a SWIG typemap. See the chapter on <A href="#Typemaps">
3552 Typemaps</A> for details about this.</P>
3553 <P> At this time, SWIG provides limited support for Unicode and
3554  wide-character strings (the C <TT>wchar_t</TT> type). Some languages
3555  provide typemaps for wchar_t, but bear in mind these might not be
3556  portable across different operating systems. This is a delicate topic
3557  that is poorly understood by many programmers and not implemented in a
3558  consistent manner across languages. For those scripting languages that
3559  provide Unicode support, Unicode strings are often available in an
3560  8-bit representation such as UTF-8 that can be mapped to the <TT>char *</TT>
3561  type (in which case the SWIG interface will probably work). If the
3562  program you are wrapping uses Unicode, there is no guarantee that
3563  Unicode characters in the target language will use the same internal
3564  representation (e.g., UCS-2 vs. UCS-4). You may need to write some
3565  special conversion functions.</P>
3566 <H3><A name="SWIG_nn11"></A>5.2.2 Global Variables</H3>
3567 <P> Whenever possible, SWIG maps C/C++ global variables into scripting
3568  language variables. For example,</P>
3569 <DIV class="code">
3570 <PRE>
3571 %module example
3572 double foo;
3573
3574 </PRE>
3575 </DIV>
3576 <P> results in a scripting language variable like this:</P>
3577 <DIV class="code">
3578 <PRE>
3579 # Tcl
3580 set foo [3.5]                   ;# Set foo to 3.5
3581 puts $foo                       ;# Print the value of foo
3582
3583 # Python
3584 cvar.foo = 3.5                  # Set foo to 3.5
3585 print cvar.foo                  # Print value of foo
3586
3587 # Perl
3588 $foo = 3.5;                     # Set foo to 3.5
3589 print $foo,&quot;\n&quot;;                # Print value of foo
3590
3591 # Ruby
3592 Module.foo = 3.5               # Set foo to 3.5
3593 print Module.foo, &quot;\n&quot;         # Print value of foo
3594 </PRE>
3595 </DIV>
3596 <P> Whenever the scripting language variable is used, the underlying C
3597  global variable is accessed. Although SWIG makes every attempt to make
3598  global variables work like scripting language variables, it is not
3599  always possible to do so. For instance, in Python, all global variables
3600  must be accessed through a special variable object known as <TT>cvar</TT>
3601  (shown above). In Ruby, variables are accessed as attributes of the
3602  module. Other languages may convert variables to a pair of accessor
3603  functions. For example, the Java module generates a pair of functions <TT>
3604 double get_foo()</TT> and <TT>set_foo(double val)</TT> that are used to
3605  manipulate the value.</P>
3606 <P> Finally, if a global variable has been declared as <TT>const</TT>,
3607  it only supports read-only access. Note: this behavior is new to
3608  SWIG-1.3. Earlier versions of SWIG incorrectly handled <TT>const</TT>
3609  and created constants instead.</P>
3610 <H3><A name="SWIG_nn12"></A>5.2.3 Constants</H3>
3611 <P> Constants can be created using <TT>#define</TT>, enumerations, or a
3612  special <TT>%constant</TT> directive. The following interface file
3613  shows a few valid constant declarations :</P>
3614 <DIV class="code">
3615 <PRE>
3616 #define I_CONST       5               // An integer constant
3617 #define PI            3.14159         // A Floating point constant
3618 #define S_CONST       &quot;hello world&quot;   // A string constant
3619 #define NEWLINE       '\n'            // Character constant
3620
3621 enum boolean {NO=0, YES=1};
3622 enum months {JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG,
3623              SEP, OCT, NOV, DEC};
3624 %constant double BLAH = 42.37;
3625 #define PI_4 PI/4
3626 #define FLAGS 0x04 | 0x08 | 0x40
3627
3628 </PRE>
3629 </DIV>
3630 <P> In <TT>#define</TT> declarations, the type of a constant is inferred
3631  by syntax. For example, a number with a decimal point is assumed to be
3632  floating point. In addition, SWIG must be able to fully resolve all of
3633  the symbols used in a <TT>#define</TT> in order for a constant to
3634  actually be created. This restriction is necessary because <TT>#define</TT>
3635  is also used to define preprocessor macros that are definitely not
3636  meant to be part of the scripting language interface. For example:</P>
3637 <DIV class="code">
3638 <PRE>
3639 #define EXTERN extern
3640
3641 EXTERN void foo();
3642 </PRE>
3643 </DIV>
3644 <P> In this case, you probably don't want to create a constant called <TT>
3645 EXTERN</TT> (what would the value be?). In general, SWIG will not create
3646  constants for macros unless the value can be completely determined by
3647  the preprocessor. For instance, in the above example, the declaration</P>
3648 <DIV class="code">
3649 <PRE>
3650 #define PI_4  PI/4
3651 </PRE>
3652 </DIV>
3653 <P> defines a constant because <TT>PI</TT> was already defined as a
3654  constant and the value is known. However, for the same conservative
3655  reasons even a constant with a simple cast will be ignored, such as</P>
3656 <DIV class="code">
3657 <PRE>
3658 #define F_CONST (double) 5            // A floating pointer constant with cast
3659 </PRE>
3660 </DIV>
3661 <P> The use of constant expressions is allowed, but SWIG does not
3662  evaluate them. Rather, it passes them through to the output file and
3663  lets the C compiler perform the final evaluation (SWIG does perform a
3664  limited form of type-checking however).</P>
3665 <P> For enumerations, it is critical that the original enum definition
3666  be included somewhere in the interface file (either in a header file or
3667  in the <TT>%{,%}</TT> block). SWIG only translates the enumeration into
3668  code needed to add the constants to a scripting language. It needs the
3669  original enumeration declaration in order to get the correct enum
3670  values as assigned by the C compiler.</P>
3671 <P> The <TT>%constant</TT> directive is used to more precisely create
3672  constants corresponding to different C datatypes. Although it is not
3673  usually not needed for simple values, it is more useful when working
3674  with pointers and other more complex datatypes. Typically, <TT>
3675 %constant</TT> is only used when you want to add constants to the
3676  scripting language interface that are not defined in the original
3677  header file.</P>
3678 <H3><A name="SWIG_nn13"></A>5.2.4 A brief word about <TT>const</TT></H3>
3679 <P> A common confusion with C programming is the semantic meaning of the
3680  <TT>const</TT> qualifier in declarations--especially when it is mixed
3681  with pointers and other type modifiers. In fact, previous versions of
3682  SWIG handled <TT>const</TT> incorrectly--a situation that SWIG-1.3.7
3683  and newer releases have fixed.</P>
3684 <P> Starting with SWIG-1.3, all variable declarations, regardless of any
3685  use of <TT>const</TT>, are wrapped as global variables. If a
3686  declaration happens to be declared as <TT>const</TT>, it is wrapped as
3687  a read-only variable. To tell if a variable is <TT>const</TT> or not,
3688  you need to look at the right-most occurrence of the <TT>const</TT>
3689  qualifier (that appears before the variable name). If the right-most <TT>
3690 const</TT> occurs after all other type modifiers (such as pointers),
3691  then the variable is <TT>const</TT>. Otherwise, it is not.</P>
3692 <P> Here are some examples of <TT>const</TT> declarations.</P>
3693 <DIV class="code">
3694 <PRE>
3695 const char a;           // A constant character
3696 char const b;           // A constant character (the same)
3697 char *const c;          // A constant pointer to a character
3698 const char *const d;    // A constant pointer to a constant character
3699 </PRE>
3700 </DIV>
3701 <P> Here is an example of a declaration that is not <TT>const</TT>:</P>
3702 <DIV class="code">
3703 <PRE>
3704 const char *e;          // A pointer to a constant character.  The pointer
3705                         // may be modified.
3706 </PRE>
3707 </DIV>
3708 <P> In this case, the pointer <TT>e</TT> can change---it's only the
3709  value being pointed to that is read-only.</P>
3710 <P><B> Compatibility Note:</B> One reason for changing SWIG to handle <TT>
3711 const</TT> declarations as read-only variables is that there are many
3712  situations where the value of a <TT>const</TT> variable might change.
3713  For example, a library might export a symbol as <TT>const</TT> in its
3714  public API to discourage modification, but still allow the value to
3715  change through some other kind of internal mechanism. Furthermore,
3716  programmers often overlook the fact that with a constant declaration
3717  like <TT>char *const</TT>, the underlying data being pointed to can be
3718  modified--it's only the pointer itself that is constant. In an embedded
3719  system, a <TT>const</TT> declaration might refer to a read-only memory
3720  address such as the location of a memory-mapped I/O device port (where
3721  the value changes, but writing to the port is not supported by the
3722  hardware). Rather than trying to build a bunch of special cases into
3723  the <TT>const</TT> qualifier, the new interpretation of <TT>const</TT>
3724  as &quot;read-only&quot; is simple and exactly matches the actual semantics of <TT>
3725 const</TT> in C/C++. If you really want to create a constant as in older
3726  versions of SWIG, use the <TT>%constant</TT> directive instead. For
3727  example:</P>
3728 <DIV class="code">
3729 <PRE>
3730 %constant double PI = 3.14159;
3731 </PRE>
3732 </DIV>
3733 <P> or</P>
3734 <DIV class="code">
3735 <PRE>
3736 #ifdef SWIG
3737 #define const %constant
3738 #endif
3739 const double foo = 3.4;
3740 const double bar = 23.4;
3741 const int    spam = 42;
3742 #ifdef SWIG
3743 #undef const
3744 #endif
3745 ...
3746
3747 </PRE>
3748 </DIV>
3749 <H3><A name="SWIG_nn14"></A>5.2.5 A cautionary tale of <TT>char *</TT></H3>
3750 <P> Before going any further, there is one bit of caution involving <TT>
3751 char *</TT> that must now be mentioned. When strings are passed from a
3752  scripting language to a C <TT>char *</TT>, the pointer usually points
3753  to string data stored inside the interpreter. It is almost always a
3754  really bad idea to modify this data. Furthermore, some languages may
3755  explicitly disallow it. For instance, in Python, strings are supposed
3756  be immutable. If you violate this, you will probably receive a vast
3757  amount of wrath when you unleash your module on the world.</P>
3758 <P> The primary source of problems are functions that might modify
3759  string data in place. A classic example would be a function like this:</P>
3760 <DIV class="code">
3761 <PRE>
3762 char *strcat(char *s, const char *t)
3763 </PRE>
3764 </DIV>
3765 <P> Although SWIG will certainly generate a wrapper for this, its
3766  behavior will be undefined. In fact, it will probably cause your
3767  application to crash with a segmentation fault or other memory related
3768  problem. This is because <TT>s</TT> refers to some internal data in the
3769  target language---data that you shouldn't be touching.</P>
3770 <P> The bottom line: don't rely on <TT>char *</TT> for anything other
3771  than read-only input values. However, it must be noted that you could
3772  change the behavior of SWIG using <A href="#Typemaps">typemaps</A>.</P>
3773 <H2><A name="SWIG_nn15"></A>5.3 Pointers and complex objects</H2>
3774 <P> Most C programs manipulate arrays, structures, and other types of
3775  objects. This section discusses the handling of these datatypes.</P>
3776 <H3><A name="SWIG_nn16"></A>5.3.1 Simple pointers</H3>
3777 <P> Pointers to primitive C datatypes such as</P>
3778 <DIV class="code">
3779 <PRE>
3780 int *
3781 double ***
3782 char **
3783 </PRE>
3784 </DIV>
3785 <P> are fully supported by SWIG. Rather than trying to convert the data
3786  being pointed to into a scripting representation, SWIG simply encodes
3787  the pointer itself into a representation that contains the actual value
3788  of the pointer and a type-tag. Thus, the SWIG representation of the
3789  above pointers (in Tcl), might look like this:</P>
3790 <DIV class="targetlang">
3791 <PRE>
3792 _10081012_p_int
3793 _1008e124_ppp_double
3794 _f8ac_pp_char
3795 </PRE>
3796 </DIV>
3797 <P> A NULL pointer is represented by the string &quot;NULL&quot; or the value 0
3798  encoded with type information.</P>
3799 <P> All pointers are treated as opaque objects by SWIG. Thus, a pointer
3800  may be returned by a function and passed around to other C functions as
3801  needed. For all practical purposes, the scripting language interface
3802  works in exactly the same way as you would use the pointer in a C
3803  program. The only difference is that there is no mechanism for
3804  dereferencing the pointer since this would require the target language
3805  to understand the memory layout of the underlying object.</P>
3806 <P> The scripting language representation of a pointer value should
3807  never be manipulated directly. Even though the values shown look like
3808  hexadecimal addresses, the numbers used may differ from the actual
3809  machine address (e.g., on little-endian machines, the digits may appear
3810  in reverse order). Furthermore, SWIG does not normally map pointers
3811  into high-level objects such as associative arrays or lists (for
3812  example, converting an <TT>int *</TT> into an list of integers). There
3813  are several reasons why SWIG does not do this:</P>
3814 <UL>
3815 <LI>There is not enough information in a C declaration to properly map
3816  pointers into higher level constructs. For example, an <TT>int *</TT>
3817  may indeed be an array of integers, but if it contains ten million
3818  elements, converting it into a list object is probably a bad idea.</LI>
3819 <LI>The underlying semantics associated with a pointer is not known by
3820  SWIG. For instance, an <TT>int *</TT> might not be an array at
3821  all--perhaps it is an output value!</LI>
3822 <LI>By handling all pointers in a consistent manner, the implementation
3823  of SWIG is greatly simplified and less prone to error.</LI>
3824 </UL>
3825 <H3><A name="SWIG_nn17"></A>5.3.2 Run time pointer type checking</H3>
3826 <P> By allowing pointers to be manipulated from a scripting language,
3827  extension modules effectively bypass compile-time type checking in the
3828  C/C++ compiler. To prevent errors, a type signature is encoded into all
3829  pointer values and is used to perform run-time type checking. This
3830  type-checking process is an integral part of SWIG and can not be
3831  disabled or modified without using typemaps (described in later
3832  chapters).</P>
3833 <P> Like C, <TT>void *</TT> matches any kind of pointer. Furthermore, <TT>
3834 NULL</TT> pointers can be passed to any function that expects to receive
3835  a pointer. Although this has the potential to cause a crash, <TT>NULL</TT>
3836  pointers are also sometimes used as sentinel values or to denote a
3837  missing/empty value. Therefore, SWIG leaves NULL pointer checking up to
3838  the application.</P>
3839 <H3><A name="SWIG_nn18"></A>5.3.3 Derived types, structs, and classes</H3>
3840 <P> For everything else (structs, classes, arrays, etc...) SWIG applies
3841  a very simple rule :</P>
3842 <CENTER><B> Everything else is a pointer</B></CENTER>
3843 <P> In other words, SWIG manipulates everything else by reference. This
3844  model makes sense because most C/C++ programs make heavy use of
3845  pointers and SWIG can use the type-checked pointer mechanism already
3846  present for handling pointers to basic datatypes.</P>
3847 <P> Although this probably sounds complicated, it's really quite simple.
3848  Suppose you have an interface file like this :</P>
3849 <DIV class="code">
3850 <PRE>
3851 %module fileio
3852 FILE *fopen(char *, char *);
3853 int fclose(FILE *);
3854 unsigned fread(void *ptr, unsigned size, unsigned nobj, FILE *);
3855 unsigned fwrite(void *ptr, unsigned size, unsigned nobj, FILE *);
3856 void *malloc(int nbytes);
3857 void free(void *);
3858
3859 </PRE>
3860 </DIV>
3861 <P> In this file, SWIG doesn't know what a <TT>FILE</TT> is, but since
3862  it's used as a pointer, so it doesn't really matter what it is. If you
3863  wrapped this module into Python, you can use the functions just like
3864  you expect :</P>
3865 <DIV class="targetlang">
3866 <PRE>
3867 # Copy a file 
3868 def filecopy(source,target):
3869         f1 = fopen(source,&quot;r&quot;)
3870         f2 = fopen(target,&quot;w&quot;)
3871         buffer = malloc(8192)
3872         nbytes = fread(buffer,8192,1,f1)
3873         while (nbytes &gt; 0):
3874                 fwrite(buffer,8192,1,f2)
3875                 nbytes = fread(buffer,8192,1,f1)
3876         free(buffer)
3877
3878 </PRE>
3879 </DIV>
3880 <P> In this case <TT>f1</TT>, <TT>f2</TT>, and <TT>buffer</TT> are all
3881  opaque objects containing C pointers. It doesn't matter what value they
3882  contain--our program works just fine without this knowledge.</P>
3883 <H3><A name="SWIG_nn19"></A>5.3.4 Undefined datatypes</H3>
3884 <P> When SWIG encounters an undeclared datatype, it automatically
3885  assumes that it is a structure or class. For example, suppose the
3886  following function appeared in a SWIG input file:</P>
3887 <DIV class="code">
3888 <PRE>
3889 void matrix_multiply(Matrix *a, Matrix *b, Matrix *c);
3890 </PRE>
3891 </DIV>
3892 <P> SWIG has no idea what a &quot;<TT>Matrix</TT>&quot; is. However, it is
3893  obviously a pointer to something so SWIG generates a wrapper using its
3894  generic pointer handling code.</P>
3895 <P> Unlike C or C++, SWIG does not actually care whether <TT>Matrix</TT>
3896  has been previously defined in the interface file or not. This allows
3897  SWIG to generate interfaces from only partial or limited information.
3898  In some cases, you may not care what a <TT>Matrix</TT> really is as
3899  long as you can pass an opaque reference to one around in the scripting
3900  language interface.</P>
3901 <P> An important detail to mention is that SWIG will gladly generate
3902  wrappers for an interface when there are unspecified type names.
3903  However,<B> all unspecified types are internally handled as pointers to
3904  structures or classes!</B> For example, consider the following
3905  declaration:</P>
3906 <DIV class="code">
3907 <PRE>
3908 void foo(size_t num);
3909 </PRE>
3910 </DIV>
3911 <P> If <TT>size_t</TT> is undeclared, SWIG generates wrappers that
3912  expect to receive a type of <TT>size_t *</TT> (this mapping is
3913  described shortly). As a result, the scripting interface might behave
3914  strangely. For example:</P>
3915 <DIV class="code">
3916 <PRE>
3917 foo(40);
3918 TypeError: expected a _p_size_t.
3919 </PRE>
3920 </DIV>
3921 <P> The only way to fix this problem is to make sure you properly
3922  declare type names using <TT>typedef</TT>.</P>
3923
3924 <!-- We might want to add an error reporting flag to swig -->
3925 <H3><A name="SWIG_nn20"></A>5.3.5 Typedef</H3>
3926 <P> Like C, <TT>typedef</TT> can be used to define new type names in
3927  SWIG. For example:</P>
3928 <DIV class="code">
3929 <PRE>
3930 typedef unsigned int size_t;
3931 </PRE>
3932 </DIV>
3933 <P> <TT>typedef</TT> definitions appearing in a SWIG interface are not
3934  propagated to the generated wrapper code. Therefore, they either need
3935  to be defined in an included header file or placed in the declarations
3936  section like this:</P>
3937 <DIV class="code">
3938 <PRE>
3939 %{
3940 /* Include in the generated wrapper file */
3941 typedef unsigned int size_t;
3942 %}
3943 /* Tell SWIG about it */
3944 typedef unsigned int size_t;
3945 </PRE>
3946 </DIV>
3947 <P> or</P>
3948 <DIV class="code">
3949 <PRE>
3950 %inline %{
3951 typedef unsigned int size_t;
3952 %}
3953 </PRE>
3954 </DIV>
3955 <P> In certain cases, you might be able to include other header files to
3956  collect type information. For example:</P>
3957 <DIV class="code">
3958 <PRE>
3959 %module example
3960 %import &quot;sys/types.h&quot;
3961 </PRE>
3962 </DIV>
3963 <P> In this case, you might run SWIG as follows:</P>
3964 <DIV class="shell">
3965 <PRE>
3966 $ swig -I/usr/include -includeall example.i
3967 </PRE>
3968 </DIV>
3969 <P> It should be noted that your mileage will vary greatly here. System
3970  headers are notoriously complicated and may rely upon a variety of
3971  non-standard C coding extensions (e.g., such as special directives to
3972  GCC). Unless you exactly specify the right include directories and
3973  preprocessor symbols, this may not work correctly (you will have to
3974  experiment).</P>
3975 <P> SWIG tracks <TT>typedef</TT> declarations and uses this information
3976  for run-time type checking. For instance, if you use the above <TT>
3977 typedef</TT> and had the following function declaration:</P>
3978 <DIV class="code">
3979 <PRE>
3980 void foo(unsigned int *ptr);
3981 </PRE>
3982 </DIV>
3983 <P> The corresponding wrapper function will accept arguments of type <TT>
3984 unsigned int *</TT> or <TT>size_t *</TT>.</P>
3985 <H2><A name="SWIG_nn21"></A>5.4 Other Practicalities</H2>
3986 <P> So far, this chapter has presented almost everything you need to
3987  know to use SWIG for simple interfaces. However, some C programs use
3988  idioms that are somewhat more difficult to map to a scripting language
3989  interface. This section describes some of these issues.</P>
3990 <H3><A name="SWIG_nn22"></A>5.4.1 Passing structures by value</H3>
3991 <P> Sometimes a C function takes structure parameters that are passed by
3992  value. For example, consider the following function:</P>
3993 <DIV class="code">
3994 <PRE>
3995 double dot_product(Vector a, Vector b);
3996 </PRE>
3997 </DIV>
3998 <P> To deal with this, SWIG transforms the function to use pointers by
3999  creating a wrapper equivalent to the following:</P>
4000 <DIV class="code">
4001 <PRE>
4002 double wrap_dot_product(Vector *a, Vector *b) {
4003     Vector x = *a;
4004     Vector y = *b;
4005     return dot_product(x,y);
4006 }
4007 </PRE>
4008 </DIV>
4009 <P> In the target language, the <TT>dot_product()</TT> function now
4010  accepts pointers to Vectors instead of Vectors. For the most part, this
4011  transformation is transparent so you might not notice.</P>
4012 <H3><A name="SWIG_nn23"></A>5.4.2 Return by value</H3>
4013 <P> C functions that return structures or classes datatypes by value are
4014  more difficult to handle. Consider the following function:</P>
4015 <DIV class="code">
4016 <PRE>
4017 Vector cross_product(Vector v1, Vector v2);
4018 </PRE>
4019 </DIV>
4020 <P> This function wants to return <TT>Vector</TT>, but SWIG only really
4021  supports pointers. As a result, SWIG creates a wrapper like this:</P>
4022 <DIV class="code">
4023 <PRE>
4024 Vector *wrap_cross_product(Vector *v1, Vector *v2) {
4025         Vector x = *v1;
4026         Vector y = *v2;
4027         Vector *result;
4028         result = (Vector *) malloc(sizeof(Vector));
4029         *(result) = cross(x,y);
4030         return result;
4031 }
4032 </PRE>
4033 </DIV>
4034 <P> or if SWIG was run with the <TT>-c++</TT> option:</P>
4035 <DIV class="code">
4036 <PRE>
4037 Vector *wrap_cross(Vector *v1, Vector *v2) {
4038         Vector x = *v1;
4039         Vector y = *v2;
4040         Vector *result = new Vector(cross(x,y)); // Uses default copy constructor
4041         return result;
4042 }
4043 </PRE>
4044 </DIV>
4045 <P> In both cases, SWIG allocates a new object and returns a reference
4046  to it. It is up to the user to delete the returned object when it is no
4047  longer in use. Clearly, this will leak memory if you are unaware of the
4048  implicit memory allocation and don't take steps to free the result.
4049  That said, it should be noted that some language modules can now
4050  automatically track newly created objects and reclaim memory for you.
4051  Consult the documentation for each language module for more details.</P>
4052 <P> It should also be noted that the handling of pass/return by value in
4053  C++ has some special cases. For example, the above code fragments don't
4054  work correctly if <TT>Vector</TT> doesn't define a default constructor.
4055  The section on SWIG and C++ has more information about this case.</P>
4056 <H3><A name="SWIG_nn24"></A>5.4.3 Linking to structure variables</H3>
4057 <P> When global variables or class members involving structures are
4058  encountered, SWIG handles them as pointers. For example, a global
4059  variable like this</P>
4060 <DIV class="code">
4061 <PRE>
4062 Vector unit_i;
4063 </PRE>
4064 </DIV>
4065 <P> gets mapped to an underlying pair of set/get functions like this :</P>
4066 <DIV class="code">
4067 <PRE>
4068 Vector *unit_i_get() {
4069         return &amp;unit_i;
4070 }
4071 void unit_i_set(Vector *value) {
4072         unit_i = *value;
4073 }
4074 </PRE>
4075 </DIV>
4076 <P> Again some caution is in order. A global variable created in this
4077  manner will show up as a pointer in the target scripting language. It
4078  would be an extremely bad idea to free or destroy such a pointer. Also,
4079  C++ classes must supply a properly defined copy constructor in order
4080  for assignment to work correctly.</P>
4081 <H3><A name="SWIG_nn25"></A>5.4.4 Linking to <TT>char *</TT></H3>
4082 <P> When a global variable of type <TT>char *</TT> appears, SWIG uses <TT>
4083 malloc()</TT> or <TT>new</TT> to allocate memory for the new value.
4084  Specifically, if you have a variable like this</P>
4085 <DIV class="code">
4086 <PRE>
4087 char *foo;
4088 </PRE>
4089 </DIV>
4090 <P> SWIG generates the following code:</P>
4091 <DIV class="code">
4092 <PRE>
4093 /* C mode */
4094 void foo_set(char *value) {
4095    if (foo) free(foo);
4096    foo = (char *) malloc(strlen(value)+1);
4097    strcpy(foo,value);
4098 }
4099
4100 /* C++ mode.  When -c++ option is used */
4101 void foo_set(char *value) {
4102    if (foo) delete [] foo;
4103    foo = new char[strlen(value)+1];
4104    strcpy(foo,value);
4105 }
4106 </PRE>
4107 </DIV>
4108 <P> If this is not the behavior that you want, consider making the
4109  variable read-only using the <TT>%immutable</TT> directive.
4110  Alternatively, you might write a short assist-function to set the value
4111  exactly like you want. For example:</P>
4112 <DIV class="code">
4113 <PRE>
4114 %inline %{
4115   void set_foo(char *value) {
4116        strncpy(foo,value, 50);
4117    }
4118 %}
4119 </PRE>
4120 </DIV>
4121 <P> Note: If you write an assist function like this, you will have to
4122  call it as a function from the target scripting language (it does not
4123  work like a variable). For example, in Python you will have to write:</P>
4124 <DIV class="targetlang">
4125 <PRE>
4126 &gt;&gt;&gt; set_foo(&quot;Hello World&quot;)
4127 </PRE>
4128 </DIV>
4129 <P> A common mistake with <TT>char *</TT> variables is to link to a
4130  variable declared like this:</P>
4131 <DIV class="code">
4132 <PRE>
4133 char *VERSION = &quot;1.0&quot;;
4134 </PRE>
4135 </DIV>
4136 <P> In this case, the variable will be readable, but any attempt to
4137  change the value results in a segmentation or general protection fault.
4138  This is due to the fact that SWIG is trying to release the old value
4139  using <TT>free</TT> or <TT>delete</TT> when the string literal value
4140  currently assigned to the variable wasn't allocated using <TT>malloc()</TT>
4141  or <TT>new</TT>. To fix this behavior, you can either mark the variable
4142  as read-only, write a typemap (as described in Chapter 6), or write a
4143  special set function as shown. Another alternative is to declare the
4144  variable as an array:</P>
4145 <DIV class="code">
4146 <PRE>
4147 char VERSION[64] = &quot;1.0&quot;;
4148 </PRE>
4149 </DIV>
4150 <P> When variables of type <TT>const char *</TT> are declared, SWIG
4151  still generates functions for setting and getting the value. However,
4152  the default behavior does<EM> not</EM> release the previous contents
4153  (resulting in a possible memory leak). In fact, you may get a warning
4154  message such as this when wrapping such a variable:</P>
4155 <DIV class="shell">
4156 <PRE>
4157 example.i:20. Typemap warning. Setting const char * variable may leak memory
4158 </PRE>
4159 </DIV>
4160 <P> The reason for this behavior is that <TT>const char *</TT> variables
4161  are often used to point to string literals. For example:</P>
4162 <DIV class="code">
4163 <PRE>
4164 const char *foo = &quot;Hello World\n&quot;;
4165 </PRE>
4166 </DIV>
4167 <P> Therefore, it's a really bad idea to call <TT>free()</TT> on such a
4168  pointer. On the other hand, it<EM> is</EM> legal to change the pointer
4169  to point to some other value. When setting a variable of this type,
4170  SWIG allocates a new string (using malloc or new) and changes the
4171  pointer to point to the new value. However, repeated modifications of
4172  the value will result in a memory leak since the old value is not
4173  released.</P>
4174 <H3><A name="SWIG_nn26"></A>5.4.5 Arrays</H3>
4175 <P> Arrays are fully supported by SWIG, but they are always handled as
4176  pointers instead of mapping them to a special array object or list in
4177  the target language. Thus, the following declarations :</P>
4178 <DIV class="code">
4179 <PRE>
4180 int foobar(int a[40]);
4181 void grok(char *argv[]);
4182 void transpose(double a[20][20]);
4183 </PRE>
4184 </DIV>
4185 <P> are processed as if they were really declared like this:</P>
4186 <DIV class="code">
4187 <PRE>
4188 int foobar(int *a);
4189 void grok(char **argv);
4190 void transpose(double (*a)[20]);
4191 </PRE>
4192 </DIV>
4193 <P> Like C, SWIG does not perform array bounds checking. It is up to the
4194  user to make sure the pointer points a suitably allocated region of
4195  memory.</P>
4196 <P> Multi-dimensional arrays are transformed into a pointer to an array
4197  of one less dimension. For example:</P>
4198 <DIV class="code">
4199 <PRE>
4200 int [10];         // Maps to int *
4201 int [10][20];     // Maps to int (*)[20]
4202 int [10][20][30]; // Maps to int (*)[20][30]
4203 </PRE>
4204 </DIV>
4205 <P> It is important to note that in the C type system, a
4206  multidimensional array <TT>a[][]</TT> is<B> NOT</B> equivalent to a
4207  single pointer <TT>*a</TT> or a double pointer such as <TT>**a</TT>.
4208  Instead, a pointer to an array is used (as shown above) where the
4209  actual value of the pointer is the starting memory location of the
4210  array. The reader is strongly advised to dust off their C book and
4211  re-read the section on arrays before using them with SWIG.</P>
4212 <P> Array variables are supported, but are read-only by default. For
4213  example:</P>
4214 <DIV class="code">
4215 <PRE>
4216 int   a[100][200];
4217 </PRE>
4218 </DIV>
4219 <P> In this case, reading the variable 'a' returns a pointer of type <TT>
4220 int (*)[200]</TT> that points to the first element of the array <TT>
4221 &amp;a[0][0]</TT>. Trying to modify 'a' results in an error. This is because
4222  SWIG does not know how to copy data from the target language into the
4223  array. To work around this limitation, you may want to write a few
4224  simple assist functions like this:</P>
4225 <DIV class="code">
4226 <PRE>
4227 %inline %{
4228 void a_set(int i, int j, int val) {
4229    a[i][j] = val;
4230 }
4231 int a_get(int i, int j) {
4232    return a[i][j];
4233 }
4234 %}
4235 </PRE>
4236 </DIV>
4237 <P> To dynamically create arrays of various sizes and shapes, it may be
4238  useful to write some helper functions in your interface. For example:</P>
4239 <DIV class="code">
4240 <PRE>
4241 // Some array helpers
4242 %inline %{
4243   /* Create any sort of [size] array */
4244   int *int_array(int size) {
4245      return (int *) malloc(size*sizeof(int));
4246   }
4247   /* Create a two-dimension array [size][10] */
4248   int (*int_array_10(int size))[10] {
4249      return (int (*)[10]) malloc(size*10*sizeof(int));
4250   }
4251 %}
4252 </PRE>
4253 </DIV>
4254 <P> Arrays of <TT>char</TT> are handled as a special case by SWIG. In
4255  this case, strings in the target language can be stored in the array.
4256  For example, if you have a declaration like this,</P>
4257 <DIV class="code">
4258 <PRE>
4259 char pathname[256];
4260 </PRE>
4261 </DIV>
4262 <P> SWIG generates functions for both getting and setting the value that
4263  are equivalent to the following code:</P>
4264 <DIV class="code">
4265 <PRE>
4266 char *pathname_get() {
4267    return pathname;
4268 }
4269 void pathname_set(char *value) {
4270    strncpy(pathname,value,256);
4271 }
4272 </PRE>
4273 </DIV>
4274 <P> In the target language, the value can be set like a normal variable.</P>
4275 <H3><A name="SWIG_readonly_variables"></A>5.4.6 Creating read-only
4276  variables</H3>
4277 <P> A read-only variable can be created by using the <TT>%immutable</TT>
4278  directive as shown :</P>
4279 <DIV class="code">
4280 <PRE>
4281 // File : interface.i
4282
4283 int     a;                      // Can read/write
4284 %immutable;
4285 int     b,c,d                   // Read only variables
4286 %mutable;
4287 double  x,y                     // read/write
4288 </PRE>
4289 </DIV>
4290 <P> The <TT>%immutable</TT> directive enables read-only mode until it is
4291  explicitly disabled using the <TT>%mutable</TT> directive. As an
4292  alternative to turning read-only mode off and on like this, individual
4293  declarations can also be tagged as immutable. For example:</P>
4294 <DIV class="code">
4295 <PRE>
4296 %immutable x;                   // Make x read-only
4297 ...
4298 double x;                       // Read-only (from earlier %immutable directive)
4299 double y;                       // Read-write
4300 ...
4301 </PRE>
4302 </DIV>
4303 <P> The <TT>%mutable</TT> and <TT>%immutable</TT> directives are
4304  actually <A href="#features">%feature directives</A> defined like this:</P>
4305 <DIV class="code">
4306 <PRE>
4307 #define %immutable   %feature(&quot;immutable&quot;)
4308 #define %mutable     %feature(&quot;immutable&quot;,&quot;&quot;)
4309 </PRE>
4310 </DIV>
4311 <P> If you wanted to make all wrapped variables read-only, barring one
4312  or two, it might be easier to take this approach:</P>
4313 <DIV class="code">
4314 <PRE>
4315 %immutable;                     // Make all variables read-only
4316 %feature(&quot;immutable&quot;,&quot;0&quot;) x;    // except, make x read/write
4317 ...
4318 double x;
4319 double y;
4320 double z;
4321 ...
4322 </PRE>
4323 </DIV>
4324 <P> Read-only variables are also created when declarations are declared
4325  as <TT>const</TT>. For example:</P>
4326 <DIV class="code">
4327 <PRE>
4328 const int foo;               /* Read only variable */
4329 char * const version=&quot;1.0&quot;;  /* Read only variable */
4330 </PRE>
4331 </DIV>
4332 <P><B> Compatibility note:</B> Read-only access used to be controlled by
4333  a pair of directives <TT>%readonly</TT> and <TT>%readwrite</TT>.
4334  Although these directives still work, they generate a warning message.
4335  Simply change the directives to <TT>%immutable;</TT> and <TT>%mutable;</TT>
4336  to silence the warning. Don't forget the extra semicolon!</P>
4337 <H3><A name="SWIG_rename_ignore"></A>5.4.7 Renaming and ignoring
4338  declarations</H3>
4339 <P> Normally, the name of a C declaration is used when that declaration
4340  is wrapped into the target language. However, this may generate a
4341  conflict with a keyword or already existing function in the scripting
4342  language. To resolve a name conflict, you can use the <TT>%rename</TT>
4343  directive as shown :</P>
4344 <DIV class="code">
4345 <PRE>
4346 // interface.i
4347
4348 %rename(my_print) print;
4349 extern void print(char *);
4350
4351 %rename(foo) a_really_long_and_annoying_name;
4352 extern int a_really_long_and_annoying_name;
4353
4354 </PRE>
4355 </DIV>
4356 <P> SWIG still calls the correct C function, but in this case the
4357  function <TT>print()</TT> will really be called &quot;<TT>my_print()</TT>&quot;
4358  in the target language.</P>
4359 <P> The placement of the <TT>%rename</TT> directive is arbitrary as long
4360  as it appears before the declarations to be renamed. A common technique
4361  is to write code for wrapping a header file like this:</P>
4362 <DIV class="code">
4363 <PRE>
4364 // interface.i
4365
4366 %rename(my_print) print;
4367 %rename(foo) a_really_long_and_annoying_name;
4368
4369 %include &quot;header.h&quot;
4370 </PRE>
4371 </DIV>
4372 <P> <TT>%rename</TT> applies a renaming operation to all future
4373  occurrences of a name. The renaming applies to functions, variables,
4374  class and structure names, member functions, and member data. For
4375  example, if you had two-dozen C++ classes, all with a member function
4376  named `print' (which is a keyword in Python), you could rename them all
4377  to `output' by specifying :</P>
4378 <DIV class="code">
4379 <PRE>
4380 %rename(output) print; // Rename all `print' functions to `output'
4381 </PRE>
4382 </DIV>
4383 <P> SWIG does not normally perform any checks to see if the functions it
4384  wraps are already defined in the target scripting language. However, if
4385  you are careful about namespaces and your use of modules, you can
4386  usually avoid these problems.</P>
4387 <P> Closely related to <TT>%rename</TT> is the <TT>%ignore</TT>
4388  directive. <TT>%ignore</TT> instructs SWIG to ignore declarations that
4389  match a given identifier. For example:</P>
4390 <DIV class="code">
4391 <PRE>
4392 %ignore print;         // Ignore all declarations named print
4393 %ignore _HAVE_FOO_H;   // Ignore an include guard constant
4394 ...
4395 %include &quot;foo.h&quot;       // Grab a header file
4396 ...
4397 </PRE>
4398 </DIV>
4399 <P> Any function, variable etc which matches <TT>%ignore</TT> will not
4400  be wrapped and therefore will not be available from the target
4401  language. A common usage of <TT>%ignore</TT> is to selectively remove
4402  certain declarations from a header file without having to add
4403  conditional compilation to the header. However, it should be stressed
4404  that this only works for simple declarations. If you need to remove a
4405  whole section of problematic code, the SWIG preprocessor should be used
4406  instead.</P>
4407 <P> More powerful variants of <TT>%rename</TT> and <TT>%ignore</TT>
4408  directives can be used to help wrap C++ overloaded functions and
4409  methods or C++ methods which use default arguments. This is described
4410  in the <A href="#ambiguity_resolution_renaming">Ambiguity resolution
4411  and renaming</A> section in the C++ chapter.</P>
4412 <P><B> Compatibility note:</B> Older versions of SWIG provided a special
4413  <TT>%name</TT> directive for renaming declarations. For example:</P>
4414 <DIV class="code">
4415 <PRE>
4416 %name(output) extern void print(char *);
4417 </PRE>
4418 </DIV>
4419 <P> This directive is still supported, but it is deprecated and should
4420  probably be avoided. The <TT>%rename</TT> directive is more powerful
4421  and better supports wrapping of raw header file information.</P>
4422 <H3><A name="SWIG_default_args"></A>5.4.8 Default/optional arguments</H3>
4423 <P> SWIG supports default arguments in both C and C++ code. For example:</P>
4424 <DIV class="code">
4425 <PRE>
4426 int plot(double x, double y, int color=WHITE);
4427 </PRE>
4428 </DIV>
4429 <P> In this case, SWIG generates wrapper code where the default
4430  arguments are optional in the target language. For example, this
4431  function could be used in Tcl as follows :</P>
4432 <DIV class="targetlang">
4433 <PRE>
4434 % plot -3.4 7.5                                 # Use default value
4435 % plot -3.4 7.5 10                              # set color to 10 instead
4436
4437 </PRE>
4438 </DIV>
4439 <P> Although the ANSI C standard does not allow default arguments,
4440  default arguments specified in a SWIG interface work with both C and
4441  C++.</P>
4442 <P><B> Note:</B> There is a subtle semantic issue concerning the use of
4443  default arguments and the SWIG generated wrapper code. When default
4444  arguments are used in C code, the default values are emitted into the
4445  wrappers and the function is invoked with a full set of arguments. This
4446  is different to when wrapping C++ where an overloaded wrapper method is
4447  generated for each defaulted argument. Please refer to the section on <A
4448 href="#SWIGPlus_default_args">default arguments</A> in the C++ chapter
4449  for further details.</P>
4450 <H3><A name="SWIG_nn30"></A>5.4.9 Pointers to functions and callbacks</H3>
4451 <P> Occasionally, a C library may include functions that expect to
4452  receive pointers to functions--possibly to serve as callbacks. SWIG
4453  provides full support for function pointers provided that the callback
4454  functions are defined in C and not in the target language. For example,
4455  consider a function like this:</P>
4456 <DIV class="code">
4457 <PRE>
4458 int binary_op(int a, int b, int (*op)(int,int));
4459 </PRE>
4460 </DIV>
4461 <P> When you first wrap something like this into an extension module,
4462  you may find the function to be impossible to use. For instance, in
4463  Python:</P>
4464 <DIV class="targetlang">
4465 <PRE>
4466 &gt;&gt;&gt; def add(x,y):
4467 ...     return x+y
4468 ...
4469 &gt;&gt;&gt; binary_op(3,4,add)
4470 Traceback (most recent call last):
4471   File &quot;&lt;stdin&gt;&quot;, line 1, in ?
4472 TypeError: Type error. Expected _p_f_int_int__int
4473 &gt;&gt;&gt;
4474 </PRE>
4475 </DIV>
4476 <P> The reason for this error is that SWIG doesn't know how to map a
4477  scripting language function into a C callback. However, existing C
4478  functions can be used as arguments provided you install them as
4479  constants. One way to do this is to use the <TT>%constant</TT>
4480  directive like this:</P>
4481 <DIV class="code">
4482 <PRE>
4483 /* Function with a callback */
4484 int binary_op(int a, int b, int (*op)(int,int));
4485
4486 /* Some callback functions */
4487 %constant int add(int,int);
4488 %constant int sub(int,int);
4489 %constant int mul(int,int);
4490 </PRE>
4491 </DIV>
4492 <P> In this case, <TT>add</TT>, <TT>sub</TT>, and <TT>mul</TT> become
4493  function pointer constants in the target scripting language. This
4494  allows you to use them as follows:</P>
4495 <DIV class="targetlang">
4496 <PRE>
4497 &gt;&gt;&gt; binary_op(3,4,add)
4498 7
4499 &gt;&gt;&gt; binary_op(3,4,mul)
4500 12
4501 &gt;&gt;&gt;
4502 </PRE>
4503 </DIV>
4504 <P> Unfortunately, by declaring the callback functions as constants,
4505  they are no longer accessible as functions. For example:</P>
4506 <DIV class="targetlang">
4507 <PRE>
4508 &gt;&gt;&gt; add(3,4)
4509 Traceback (most recent call last):
4510   File &quot;&lt;stdin&gt;&quot;, line 1, in ?
4511 TypeError: object is not callable: '_ff020efc_p_f_int_int__int'
4512 &gt;&gt;&gt;
4513 </PRE>
4514 </DIV>
4515 <P> If you want to make a function available as both a callback function
4516  and a function, you can use the <TT>%callback</TT> and <TT>%nocallback</TT>
4517  directives like this:</P>
4518 <DIV class="code">
4519 <PRE>
4520 /* Function with a callback */
4521 int binary_op(int a, int b, int (*op)(int,int));
4522
4523 /* Some callback functions */
4524 %callback(&quot;%s_cb&quot;);
4525 int add(int,int);
4526 int sub(int,int);
4527 int mul(int,int);
4528 %nocallback;
4529 </PRE>
4530 </DIV>
4531 <P> The argument to <TT>%callback</TT> is a printf-style format string
4532  that specifies the naming convention for the callback constants (<TT>%s</TT>
4533  gets replaced by the function name). The callback mode remains in
4534  effect until it is explicitly disabled using <TT>%nocallback</TT>. When
4535  you do this, the interface now works as follows:</P>
4536 <DIV class="targetlang">
4537 <PRE>
4538 &gt;&gt;&gt; binary_op(3,4,add_cb)
4539 7
4540 &gt;&gt;&gt; binary_op(3,4,mul_cb)
4541 12
4542 &gt;&gt;&gt; add(3,4)
4543 7
4544 &gt;&gt;&gt; mul(3,4)
4545 12
4546 </PRE>
4547 </DIV>
4548 <P> Notice that when the function is used as a callback, special names
4549  such as <TT>add_cb</TT> is used instead. To call the function normally,
4550  just use the original function name such as <TT>add()</TT>.</P>
4551 <P> SWIG provides a number of extensions to standard C printf formatting
4552  that may be useful in this context. For instance, the following
4553  variation installs the callbacks as all upper-case constants such as <TT>
4554 ADD</TT>, <TT>SUB</TT>, and <TT>MUL</TT>:</P>
4555 <DIV class="code">
4556 <PRE>
4557 /* Some callback functions */
4558 %callback(&quot;%(upper)s&quot;);
4559 int add(int,int);
4560 int sub(int,int);
4561 int mul(int,int);
4562 %nocallback;
4563 </PRE>
4564 </DIV>
4565 <P> A format string of <TT>&quot;%(lower)s&quot;</TT> converts all characters to
4566  lower-case. A string of <TT>&quot;%(title)s&quot;</TT> capitalizes the first
4567  character and converts the rest to lower case.</P>
4568 <P> And now, a final note about function pointer support. Although SWIG
4569  does not normally allow callback functions to be written in the target
4570  language, this can be accomplished with the use of typemaps and other
4571  advanced SWIG features. This is described in a later chapter.</P>
4572 <H2><A name="SWIG_nn31"></A>5.5 Structures and unions</H2>
4573 <P> This section describes the behavior of SWIG when processing ANSI C
4574  structures and union declarations. Extensions to handle C++ are
4575  described in the next section.</P>
4576 <P> If SWIG encounters the definition of a structure or union, it
4577  creates a set of accessor functions. Although SWIG does not need
4578  structure definitions to build an interface, providing definitions make
4579  it possible to access structure members. The accessor functions
4580  generated by SWIG simply take a pointer to an object and allow access
4581  to an individual member. For example, the declaration :</P>
4582 <DIV class="code">
4583 <PRE>
4584 struct Vector {
4585         double x,y,z;
4586 }
4587
4588 </PRE>
4589 </DIV>
4590 <P> gets transformed into the following set of accessor functions :</P>
4591 <DIV class="code">
4592 <PRE>
4593 double Vector_x_get(struct Vector *obj) {
4594         return obj-&gt;x;
4595 }
4596 double Vector_y_get(struct Vector *obj) { 
4597         return obj-&gt;y;
4598 }
4599 double Vector_z_get(struct Vector *obj) { 
4600         return obj-&gt;z;
4601 }
4602 void Vector_x_set(struct Vector *obj, double value) {
4603         obj-&gt;x = value;
4604 }
4605 void Vector_y_set(struct Vector *obj, double value) {
4606         obj-&gt;y = value;
4607 }
4608 void Vector_z_set(struct Vector *obj, double value) {
4609         obj-&gt;z = value;
4610 }
4611 </PRE>
4612 </DIV>
4613 <P> In addition, SWIG creates default constructor and destructor
4614  functions if none are defined in the interface. For example:</P>
4615 <DIV class="code">
4616 <PRE>
4617 struct Vector *new_Vector() {
4618     return (Vector *) calloc(1,sizeof(struct Vector));
4619 }
4620 void delete_Vector(struct Vector *obj) {
4621     free(obj);
4622 }
4623 </PRE>
4624 </DIV>
4625 <P> Using these low-level accessor functions, an object can be minimally
4626  manipulated from the target language using code like this:</P>
4627 <DIV class="code">
4628 <PRE>
4629 v = new_Vector()
4630 Vector_x_set(v,2)
4631 Vector_y_set(v,10)
4632 Vector_z_set(v,-5)
4633 ...
4634 delete_Vector(v)
4635 </PRE>
4636 </DIV>
4637 <P> However, most of SWIG's language modules also provide a high-level
4638  interface that is more convenient. Keep reading.</P>
4639 <H3><A name="SWIG_nn32"></A>5.5.1 Typedef and structures</H3>
4640 <P> SWIG supports the following construct which is quite common in C
4641  programs :</P>
4642 <DIV class="code">
4643 <PRE>
4644 typedef struct {
4645         double x,y,z;
4646 } Vector;
4647
4648 </PRE>
4649 </DIV>
4650 <P> When encountered, SWIG assumes that the name of the object is
4651  `Vector' and creates accessor functions like before. The only
4652  difference is that the use of <TT>typedef</TT> allows SWIG to drop the <TT>
4653 struct</TT> keyword on its generated code. For example:</P>
4654 <DIV class="code">
4655 <PRE>
4656 double Vector_x_get(Vector *obj) {
4657         return obj-&gt;x;
4658 }
4659 </PRE>
4660 </DIV>
4661 <P> If two different names are used like this :</P>
4662 <DIV class="code">
4663 <PRE>
4664 typedef struct vector_struct {
4665         double x,y,z;
4666 } Vector;
4667
4668 </PRE>
4669 </DIV>
4670 <P> the name <TT>Vector</TT> is used instead of <TT>vector_struct</TT>
4671  since this is more typical C programming style. If declarations defined
4672  later in the interface use the type <TT>struct vector_struct</TT>, SWIG
4673  knows that this is the same as <TT>Vector</TT> and it generates the
4674  appropriate type-checking code.</P>
4675 <H3><A name="SWIG_nn33"></A>5.5.2 Character strings and structures</H3>
4676 <P> Structures involving character strings require some care. SWIG
4677  assumes that all members of type <TT>char *</TT> have been dynamically
4678  allocated using <TT>malloc()</TT> and that they are NULL-terminated
4679  ASCII strings. When such a member is modified, the previously contents
4680  will be released, and the new contents allocated. For example :</P>
4681 <DIV class="code">
4682 <PRE>
4683 %module mymodule
4684 ...
4685 struct Foo {
4686         char *name;
4687         ...
4688 }
4689
4690 </PRE>
4691 </DIV>
4692 <P> This results in the following accessor functions :</P>
4693 <DIV class="code">
4694 <PRE>
4695 char *Foo_name_get(Foo *obj) {
4696         return Foo-&gt;name;
4697 }
4698
4699 char *Foo_name_set(Foo *obj, char *c) {
4700         if (obj-&gt;name) free(obj-&gt;name);
4701         obj-&gt;name = (char *) malloc(strlen(c)+1);
4702         strcpy(obj-&gt;name,c);
4703         return obj-&gt;name;
4704 }
4705 </PRE>
4706 </DIV>
4707 <P> If this behavior differs from what you need in your applications,
4708  the SWIG &quot;memberin&quot; typemap can be used to change it. See the typemaps
4709  chapter for further details.</P>
4710 <P> Note: If the <TT>-c++</TT> option is used, <TT>new</TT> and <TT>
4711 delete</TT> are used to perform memory allocation.</P>
4712 <H3><A name="SWIG_nn34"></A>5.5.3 Array members</H3>
4713 <P> Arrays may appear as the members of structures, but they will be
4714  read-only. SWIG will write an accessor function that returns the
4715  pointer to the first element of the array, but will not write a
4716  function to change the contents of the array itself. When this
4717  situation is detected, SWIG may generate a warning message such as the
4718  following :</P>
4719 <DIV class="shell">
4720 <PRE>
4721 interface.i:116. Warning. Array member will be read-only
4722 </PRE>
4723 </DIV>
4724 <P> To eliminate the warning message, typemaps can be used, but this is
4725  discussed in a later chapter. In many cases, the warning message is
4726  harmless.</P>
4727 <H3><A name="SWIG_structure_data_members"></A>5.5.4 Structure data
4728  members</H3>
4729 <P> Occasionally, a structure will contain data members that are
4730  themselves structures. For example:</P>
4731 <DIV class="code">
4732 <PRE>
4733 typedef struct Foo {
4734    int x;
4735 } Foo;
4736
4737 typedef struct Bar {
4738    int y;
4739    Foo f;           /* struct member */
4740 } Bar;
4741 </PRE>
4742 </DIV>
4743 <P> When a structure member is wrapped, it is handled as a pointer,
4744  unless the <TT>%naturalvar</TT> directive is used where it is handled
4745  more like a C++ reference (see <A href="#SWIGPlus_member_data">C++
4746  Member data</A>). The accessors to the member variable as a pointer is
4747  effectively wrapped as follows:</P>
4748 <DIV class="code">
4749 <PRE>
4750 Foo *Bar_f_get(Bar *b) {
4751    return &amp;b-&gt;f;
4752 }
4753 void Bar_f_set(Bar *b, Foo *value) {
4754    b-&gt;f = *value;
4755 }
4756 </PRE>
4757 </DIV>
4758 <P> The reasons for this are somewhat subtle but have to do with the
4759  problem of modifying and accessing data inside the data member. For
4760  example, suppose you wanted to modify the value of <TT>f.x</TT> of a <TT>
4761 Bar</TT> object like this:</P>
4762 <DIV class="code">
4763 <PRE>
4764 Bar *b;
4765 b-&gt;f.x = 37;
4766 </PRE>
4767 </DIV>
4768 <P> Translating this assignment to function calls (as would be used
4769  inside the scripting language interface) results in the following code:</P>
4770 <DIV class="code">
4771 <PRE>
4772 Bar *b;
4773 Foo_x_set(Bar_f_get(b),37);
4774 </PRE>
4775 </DIV>
4776 <P> In this code, if the <TT>Bar_f_get()</TT> function were to return a <TT>
4777 Foo</TT> instead of a <TT>Foo *</TT>, then the resulting modification
4778  would be applied to a<EM> copy</EM> of <TT>f</TT> and not the data
4779  member <TT>f</TT> itself. Clearly that's not what you want!</P>
4780 <P> It should be noted that this transformation to pointers only occurs
4781  if SWIG knows that a data member is a structure or class. For instance,
4782  if you had a structure like this,</P>
4783 <DIV class="code">
4784 <PRE>
4785 struct Foo {
4786    WORD   w;
4787 };
4788 </PRE>
4789 </DIV>
4790 <P> and nothing was known about <TT>WORD</TT>, then SWIG will generate
4791  more normal accessor functions like this:</P>
4792 <DIV class="code">
4793 <PRE>
4794 WORD Foo_w_get(Foo *f) {
4795     return f-&gt;w;
4796 }
4797 void Foo_w_set(FOO *f, WORD value) {
4798     f-&gt;w = value;
4799 }
4800 </PRE>
4801 </DIV>
4802 <P><B> Compatibility Note:</B> SWIG-1.3.11 and earlier releases
4803  transformed all non-primitive member datatypes to pointers. Starting in
4804  SWIG-1.3.12, this transformation<EM> only</EM> occurs if a datatype is
4805  known to be a structure, class, or union. This is unlikely to break
4806  existing code. However, if you need to tell SWIG that an undeclared
4807  datatype is really a struct, simply use a forward struct declaration
4808  such as <TT>&quot;struct Foo;&quot;</TT>.</P>
4809 <H3><A name="SWIG_nn36"></A>5.5.5 C constructors and destructors</H3>
4810 <P> When wrapping structures, it is generally useful to have a mechanism
4811  for creating and destroying objects. If you don't do anything, SWIG
4812  will automatically generate functions for creating and destroying
4813  objects using <TT>malloc()</TT> and <TT>free()</TT>. Note: the use of <TT>
4814 malloc()</TT> only applies when SWIG is used on C code (i.e., when the <TT>
4815 -c++</TT> option is<EM> not</EM> supplied on the command line). C++ is
4816  handled differently.</P>
4817 <P> If you don't want SWIG to generate default constructors for your
4818  interfaces, you can use the <TT>%nodefaultctor</TT> directive or the <TT>
4819 -nodefaultctor</TT> command line option. For example:</P>
4820 <DIV class="shell">
4821 <PRE>
4822 swig -nodefaultctor example.i 
4823 </PRE>
4824 </DIV>
4825 <P> or</P>
4826 <DIV class="code">
4827 <PRE>
4828 %module foo
4829 ...
4830 %nodefaultctor;        // Don't create default constructors
4831 ... declarations ...
4832 %clearnodefaultctor;   // Re-enable default constructors
4833 </PRE>
4834 </DIV>
4835 <P> If you need more precise control, <TT>%nodefaultctor</TT> can
4836  selectively target individual structure definitions. For example:</P>
4837 <DIV class="code">
4838 <PRE>
4839 %nodefaultctor Foo;      // No default constructor for Foo
4840 ...
4841 struct Foo {             // No default constructor generated.
4842 };
4843
4844 struct Bar {             // Default constructor generated.
4845 };
4846 </PRE>
4847 </DIV>
4848 <P> Since ignoring the implicit or default destructors most of the times
4849  produce memory leaks, SWIG will always try to generate them. If needed,
4850  however, you can selectively disable the generation of the
4851  default/implicit destructor by using <TT>%nodefaultdtor</TT></P>
4852 <DIV class="code">
4853 <PRE>
4854 %nodefaultdtor Foo; // No default/implicit destructor for Foo
4855 ...
4856 struct Foo {              // No default destructor is generated.
4857 };
4858
4859 struct Bar {              // Default destructor generated.
4860 };
4861 </PRE>
4862 </DIV>
4863 <P><B> Compatibility note:</B> Prior to SWIG-1.3.7, SWIG did not
4864  generate default constructors or destructors unless you explicitly
4865  turned them on using <TT>-make_default</TT>. However, it appears that
4866  most users want to have constructor and destructor functions so it has
4867  now been enabled as the default behavior.</P>
4868 <P><B> Note:</B> There are also the <TT>-nodefault</TT> option and <TT>
4869 %nodefault</TT> directive, which disable both the default or implicit
4870  destructor generation. This could lead to memory leaks across the
4871  target languages, and is highly recommended you don't use them.</P>
4872 <H3><A name="SWIG_adding_member_functions"></A>5.5.6 Adding member
4873  functions to C structures</H3>
4874 <P> Most languages provide a mechanism for creating classes and
4875  supporting object oriented programming. From a C standpoint, object
4876  oriented programming really just boils down to the process of attaching
4877  functions to structures. These functions normally operate on an
4878  instance of the structure (or object). Although there is a natural
4879  mapping of C++ to such a scheme, there is no direct mechanism for
4880  utilizing it with C code. However, SWIG provides a special <TT>%extend</TT>
4881  directive that makes it possible to attach methods to C structures for
4882  purposes of building an object oriented interface. Suppose you have a C
4883  header file with the following declaration :</P>
4884 <DIV class="code">
4885 <PRE>
4886 /* file : vector.h */
4887 ...
4888 typedef struct {
4889         double x,y,z;
4890 } Vector;
4891
4892 </PRE>
4893 </DIV>
4894 <P> You can make a <TT>Vector</TT> look a lot like a class by writing a
4895  SWIG interface like this:</P>
4896 <DIV class="code">
4897 <PRE>
4898 // file : vector.i
4899 %module mymodule
4900 %{
4901 #include &quot;vector.h&quot;
4902 %}
4903
4904 %include &quot;vector.h&quot;          // Just grab original C header file
4905 %extend Vector {             // Attach these functions to struct Vector
4906         Vector(double x, double y, double z) {
4907                 Vector *v;
4908                 v = (Vector *) malloc(sizeof(Vector));
4909                 v-&gt;x = x;
4910                 v-&gt;y = y;
4911                 v-&gt;z = z;
4912                 return v;
4913         }
4914         ~Vector() {
4915                 free($self);
4916         }
4917         double magnitude() {
4918                 return sqrt($self-&gt;x*$self-&gt;x+$self-&gt;y*$self-&gt;y+$self-&gt;z*$self-&gt;z);
4919         }
4920         void print() {
4921                 printf(&quot;Vector [%g, %g, %g]\n&quot;, $self-&gt;x,$self-&gt;y,$self-&gt;z);
4922         }
4923 };
4924
4925 </PRE>
4926 </DIV>
4927 <P> Note the usage of the <TT>$self</TT> special variable. Its usage is
4928  identical to a C++ 'this' pointer and should be used whenever access to
4929  the struct instance is required. Also note that C++ constructor and
4930  destructor syntax has been used to simulate a constructor and
4931  destructor, even for C code. There is one subtle difference to a normal
4932  C++ constructor implementation though and that is although the
4933  constructor declaration is as per a normal C++ constructor, the newly
4934  constructed object must be returned<B> as if</B> the constructor
4935  declaration had a return value, a <TT>Vector *</TT> in this case.</P>
4936 <P> Now, when used with proxy classes in Python, you can do things like
4937  this :</P>
4938 <DIV class="targetlang">
4939 <PRE>
4940 &gt;&gt;&gt; v = Vector(3,4,0)                 # Create a new vector
4941 &gt;&gt;&gt; print v.magnitude()                # Print magnitude
4942 5.0
4943 &gt;&gt;&gt; v.print()                  # Print it out
4944 [ 3, 4, 0 ]
4945 &gt;&gt;&gt; del v                      # Destroy it
4946 </PRE>
4947 </DIV>
4948 <P> The <TT>%extend</TT> directive can also be used inside the
4949  definition of the Vector structure. For example:</P>
4950 <DIV class="code">
4951 <PRE>
4952 // file : vector.i
4953 %module mymodule
4954 %{
4955 #include &quot;vector.h&quot;
4956 %}
4957
4958 typedef struct {
4959         double x,y,z;
4960         %extend {
4961                 Vector(double x, double y, double z) { ... }
4962                 ~Vector() { ... }
4963                 ...
4964         }
4965 } Vector;
4966 </PRE>
4967 </DIV>
4968 <P> Finally, <TT>%extend</TT> can be used to access externally written
4969  functions provided they follow the naming convention used in this
4970  example :</P>
4971 <DIV class="code">
4972 <PRE>
4973 /* File : vector.c */
4974 /* Vector methods */
4975 #include &quot;vector.h&quot;
4976 Vector *new_Vector(double x, double y, double z) {
4977         Vector *v;
4978         v = (Vector *) malloc(sizeof(Vector));
4979         v-&gt;x = x;
4980         v-&gt;y = y;
4981         v-&gt;z = z;
4982         return v;
4983 }
4984 void delete_Vector(Vector *v) {
4985         free(v);
4986 }
4987
4988 double Vector_magnitude(Vector *v) {
4989         return sqrt(v-&gt;x*v-&gt;x+v-&gt;y*v-&gt;y+v-&gt;z*v-&gt;z);
4990 }
4991
4992 // File : vector.i
4993 // Interface file
4994 %module mymodule
4995 %{
4996 #include &quot;vector.h&quot;
4997 %}
4998
4999 typedef struct {
5000         double x,y,z;
5001         %extend {
5002                 Vector(int,int,int); // This calls new_Vector()
5003                ~Vector();            // This calls delete_Vector()
5004                 double magnitude();  // This will call Vector_magnitude()
5005                 ...
5006         }
5007 } Vector;
5008 </PRE>
5009 </DIV>
5010 <P> A little known feature of the <TT>%extend</TT> directive is that it
5011  can also be used to add synthesized attributes or to modify the
5012  behavior of existing data attributes. For example, suppose you wanted
5013  to make <TT>magnitude</TT> a read-only attribute of <TT>Vector</TT>
5014  instead of a method. To do this, you might write some code like this:</P>
5015 <DIV class="code">
5016 <PRE>
5017 // Add a new attribute to Vector
5018 %extend Vector {
5019     const double magnitude;
5020 }
5021 // Now supply the implementation of the Vector_magnitude_get function
5022 %{
5023 const double Vector_magnitude_get(Vector *v) {
5024   return (const double) return sqrt(v-&gt;x*v-&gt;x+v-&gt;y*v-&gt;y+v-&gt;z*v-&gt;z);
5025 }
5026 %}
5027
5028 </PRE>
5029 </DIV>
5030 <P> Now, for all practical purposes, <TT>magnitude</TT> will appear like
5031  an attribute of the object.</P>
5032 <P> A similar technique can also be used to work with problematic data
5033  members. For example, consider this interface:</P>
5034 <DIV class="code">
5035 <PRE>
5036 struct Person {
5037    char name[50];
5038    ...
5039 }
5040 </PRE>
5041 </DIV>
5042 <P> By default, the <TT>name</TT> attribute is read-only because SWIG
5043  does not normally know how to modify arrays. However, you can rewrite
5044  the interface as follows to change this:</P>
5045 <DIV class="code">
5046 <PRE>
5047 struct Person {
5048     %extend {
5049        char *name;
5050     }
5051 ...
5052 }
5053
5054 // Specific implementation of set/get functions
5055 %{
5056 char *Person_name_get(Person *p) {
5057    return p-&gt;name;
5058 }
5059 void Person_name_set(Person *p, char *val) {
5060    strncpy(p-&gt;name,val,50);
5061 }
5062 %}
5063 </PRE>
5064 </DIV>
5065 <P> Finally, it should be stressed that even though <TT>%extend</TT> can
5066  be used to add new data members, these new members can not require the
5067  allocation of additional storage in the object (e.g., their values must
5068  be entirely synthesized from existing attributes of the structure).</P>
5069 <P><B> Compatibility note:</B> The <TT>%extend</TT> directive is a new
5070  name for the <TT>%addmethods</TT> directive. Since <TT>%addmethods</TT>
5071  could be used to extend a structure with more than just methods, a more
5072  suitable directive name has been chosen.</P>
5073 <H3><A name="SWIG_nested_structs"></A>5.5.7 Nested structures</H3>
5074 <P> Occasionally, a C program will involve structures like this :</P>
5075 <DIV class="code">
5076 <PRE>
5077 typedef struct Object {
5078         int objtype;
5079         union {
5080                 int     ivalue;
5081                 double  dvalue;
5082                 char    *strvalue;
5083                 void    *ptrvalue;
5084         } intRep;
5085 } Object;
5086
5087 </PRE>
5088 </DIV>
5089 <P> When SWIG encounters this, it performs a structure splitting
5090  operation that transforms the declaration into the equivalent of the
5091  following:</P>
5092 <DIV class="code">
5093 <PRE>
5094 typedef union {
5095         int             ivalue;
5096         double          dvalue;
5097         char            *strvalue;
5098         void            *ptrvalue;
5099 } Object_intRep;
5100
5101 typedef struct Object {
5102         int objType;
5103         Object_intRep intRep;
5104 } Object;
5105
5106 </PRE>
5107 </DIV>
5108 <P> SWIG will then create an <TT>Object_intRep</TT> structure for use
5109  inside the interface file. Accessor functions will be created for both
5110  structures. In this case, functions like this would be created :</P>
5111 <DIV class="code">
5112 <PRE>
5113 Object_intRep *Object_intRep_get(Object *o) {
5114         return (Object_intRep *) &amp;o-&gt;intRep;
5115 }
5116 int Object_intRep_ivalue_get(Object_intRep *o) {
5117         return o-&gt;ivalue;
5118 }
5119 int Object_intRep_ivalue_set(Object_intRep *o, int value) {
5120         return (o-&gt;ivalue = value);
5121 }
5122 double Object_intRep_dvalue_get(Object_intRep *o) {
5123         return o-&gt;dvalue;
5124 }
5125 ... etc ...
5126
5127 </PRE>
5128 </DIV>
5129 <P> Although this process is a little hairy, it works like you would
5130  expect in the target scripting language--especially when proxy classes
5131  are used. For instance, in Perl:</P>
5132 <DIV class="targetlang">
5133 <PRE>
5134 # Perl5 script for accessing nested member
5135 $o = CreateObject();                    # Create an object somehow
5136 $o-&gt;{intRep}-&gt;{ivalue} = 7              # Change value of o.intRep.ivalue
5137 </PRE>
5138 </DIV>
5139 <P> If you have a lot nested structure declarations, it is advisable to
5140  double-check them after running SWIG. Although, there is a good chance
5141  that they will work, you may have to modify the interface file in
5142  certain cases.</P>
5143 <H3><A name="SWIG_nn39"></A>5.5.8 Other things to note about structure
5144  wrapping</H3>
5145 <P> SWIG doesn't care if the declaration of a structure in a <TT>.i</TT>
5146  file exactly matches that used in the underlying C code (except in the
5147  case of nested structures). For this reason, there are no problems
5148  omitting problematic members or simply omitting the structure
5149  definition altogether. If you are happy passing pointers around, this
5150  can be done without ever giving SWIG a structure definition.</P>
5151 <P> Starting with SWIG1.3, a number of improvements have been made to
5152  SWIG's code generator. Specifically, even though structure access has
5153  been described in terms of high-level accessor functions such as this,</P>
5154 <DIV class="code">
5155 <PRE>
5156 double Vector_x_get(Vector *v) {
5157    return v-&gt;x;
5158 }
5159 </PRE>
5160 </DIV>
5161 <P> most of the generated code is actually inlined directly into wrapper
5162  functions. Therefore, no function <TT>Vector_x_get()</TT> actually
5163  exists in the generated wrapper file. For example, when creating a Tcl
5164  module, the following function is generated instead:</P>
5165 <DIV class="code">
5166 <PRE>
5167 static int
5168 _wrap_Vector_x_get(ClientData clientData, Tcl_Interp *interp, 
5169                    int objc, Tcl_Obj *CONST objv[]) {
5170     struct Vector *arg1 ;
5171     double result ;
5172     
5173     if (SWIG_GetArgs(interp, objc, objv,&quot;p:Vector_x_get self &quot;,&amp;arg0,
5174                      SWIGTYPE_p_Vector) == TCL_ERROR)
5175          return TCL_ERROR;
5176     result = (double ) (arg1-&gt;x);
5177     Tcl_SetObjResult(interp,Tcl_NewDoubleObj((double) result));
5178     return TCL_OK;
5179 }
5180 </PRE>
5181 </DIV>
5182 <P> The only exception to this rule are methods defined with <TT>%extend</TT>
5183 . In this case, the added code is contained in a separate function.</P>
5184 <P> Finally, it is important to note that most language modules may
5185  choose to build a more advanced interface. Although you may never use
5186  the low-level interface described here, most of SWIG's language modules
5187  use it in some way or another.</P>
5188 <H2><A name="SWIG_nn40"></A>5.6 Code Insertion</H2>
5189 <P> Sometimes it is necessary to insert special code into the resulting
5190  wrapper file generated by SWIG. For example, you may want to include
5191  additional C code to perform initialization or other operations. There
5192  are four common ways to insert code, but it's useful to know how the
5193  output of SWIG is structured first.</P>
5194 <H3><A name="SWIG_nn41"></A>5.6.1 The output of SWIG</H3>
5195 <P> When SWIG creates its output file, it is broken up into four
5196  sections corresponding to runtime code, headers, wrapper functions, and
5197  module initialization code (in that order).</P>
5198 <UL>
5199 <LI><B>Begin section</B>.
5200 <BR> A placeholder to put code at the beginning of the C/C++ wrapper
5201  file.</LI>
5202 <LI><B>Runtime code</B>.
5203 <BR> This code is internal to SWIG and is used to include type-checking
5204  and other support functions that are used by the rest of the module.</LI>
5205 <LI><B>Header section</B>.
5206 <BR> This is user-defined support code that has been included by the <TT>
5207 %{ ... %}</TT> directive. Usually this consists of header files and
5208  other helper functions.</LI>
5209 <LI><B>Wrapper code</B>.
5210 <BR> These are the wrappers generated automatically by SWIG.</LI>
5211 <LI><B>Module initialization</B>.
5212 <BR> The function generated by SWIG to initialize the module upon
5213  loading.</LI>
5214 </UL>
5215 <H3><A name="SWIG_nn42"></A>5.6.2 Code insertion blocks</H3>
5216 <P> Code is inserted into the appropriate code section by using one of
5217  the code insertion directives listed below. The order of the sections
5218  in the wrapper file is as shown:</P>
5219 <DIV class="code">
5220 <PRE>
5221 %begin %{
5222    ... code in begin section ...
5223 %}
5224
5225 %runtime %{
5226    ... code in runtime section ...
5227 %}
5228
5229 %header %{
5230    ... code in header section ...
5231 %}
5232
5233 %wrapper %{
5234    ... code in wrapper section ...
5235 %}
5236
5237 %init %{
5238    ... code in init section ...
5239 %}
5240 </PRE>
5241 </DIV>
5242 <P> The bare <TT>%{ ... %}</TT> directive is a shortcut that is the same
5243  as <TT>%header %{ ... %}</TT>.</P>
5244 <P> The <TT>%begin</TT> section is effectively empty as it just contains
5245  the SWIG banner by default. This section is provided as a way for users
5246  to insert code at the top of the wrapper file before any other code is
5247  generated. Everything in a code insertion block is copied verbatim into
5248  the output file and is not parsed by SWIG. Most SWIG input files have
5249  at least one such block to include header files and support C code.
5250  Additional code blocks may be placed anywhere in a SWIG file as needed.</P>
5251 <DIV class="code">
5252 <PRE>
5253 %module mymodule
5254 %{
5255 #include &quot;my_header.h&quot;
5256 %}
5257 ... Declare functions here
5258 %{
5259
5260 void some_extra_function() {
5261   ...
5262 }
5263 %}
5264 </PRE>
5265 </DIV>
5266 <P> A common use for code blocks is to write &quot;helper&quot; functions. These
5267  are functions that are used specifically for the purpose of building an
5268  interface, but which are generally not visible to the normal C program.
5269  For example :</P>
5270 <DIV class="code">
5271 <PRE>
5272 %{
5273 /* Create a new vector */
5274 static Vector *new_Vector() {
5275         return (Vector *) malloc(sizeof(Vector));
5276 }
5277
5278 %}
5279 // Now wrap it 
5280 Vector *new_Vector();
5281 </PRE>
5282 </DIV>
5283 <H3><A name="SWIG_nn43"></A>5.6.3 Inlined code blocks</H3>
5284 <P> Since the process of writing helper functions is fairly common,
5285  there is a special inlined form of code block that is used as follows :</P>
5286 <DIV class="code">
5287 <PRE>
5288 %inline %{
5289 /* Create a new vector */
5290 Vector *new_Vector() {
5291         return (Vector *) malloc(sizeof(Vector));
5292 }
5293 %}
5294
5295 </PRE>
5296 </DIV>
5297 <P> The <TT>%inline</TT> directive inserts all of the code that follows
5298  verbatim into the header portion of an interface file. The code is then
5299  parsed by both the SWIG preprocessor and parser. Thus, the above
5300  example creates a new command <TT>new_Vector</TT> using only one
5301  declaration. Since the code inside an <TT>%inline %{ ... %}</TT> block
5302  is given to both the C compiler and SWIG, it is illegal to include any
5303  SWIG directives inside a <TT>%{ ... %}</TT> block.</P>
5304 <H3><A name="SWIG_nn44"></A>5.6.4 Initialization blocks</H3>
5305 <P> When code is included in the <TT>%init</TT> section, it is copied
5306  directly into the module initialization function. For example, if you
5307  needed to perform some extra initialization on module loading, you
5308  could write this:</P>
5309 <DIV class="code">
5310 <PRE>
5311 %init %{
5312         init_variables();
5313 %}
5314 </PRE>
5315 </DIV>
5316 <H2><A name="SWIG_nn45"></A>5.7 An Interface Building Strategy</H2>
5317 <P> This section describes the general approach for building interface
5318  with SWIG. The specifics related to a particular scripting language are
5319  found in later chapters.</P>
5320 <H3><A name="SWIG_nn46"></A>5.7.1 Preparing a C program for SWIG</H3>
5321 <P> SWIG doesn't require modifications to your C code, but if you feed
5322  it a collection of raw C header files or source code, the results might
5323  not be what you expect---in fact, they might be awful. Here's a series
5324  of steps you can follow to make an interface for a C program :</P>
5325 <UL>
5326 <LI>Identify the functions that you want to wrap. It's probably not
5327  necessary to access every single function in a C program--thus, a
5328  little forethought can dramatically simplify the resulting scripting
5329  language interface. C header files are particularly good source for
5330  finding things to wrap.</LI>
5331 <LI>Create a new interface file to describe the scripting language
5332  interface to your program.</LI>
5333 <LI>Copy the appropriate declarations into the interface file or use
5334  SWIG's <TT>%include</TT> directive to process an entire C source/header
5335  file.</LI>
5336 <LI>Make sure everything in the interface file uses ANSI C/C++ syntax.</LI>
5337 <LI>Make sure all necessary `<TT>typedef</TT>' declarations and
5338  type-information is available in the interface file. In particular,
5339  ensure that the type information is specified in the correct order as
5340  required by a C/C++ compiler. Most importantly, define a type before it
5341  is used! A C compiler will tell you if the full type information is not
5342  available if it is needed, whereas SWIG will usually not warn or error
5343  out as it is designed to work without full type information. However,
5344  if type information is not specified correctly, the wrappers can be
5345  sub-optimal and even result in uncompileable C/C++ code.</LI>
5346 <LI>If your program has a main() function, you may need to rename it
5347  (read on).</LI>
5348 <LI>Run SWIG and compile.</LI>
5349 </UL>
5350 <P> Although this may sound complicated, the process turns out to be
5351  fairly easy once you get the hang of it.</P>
5352 <P> In the process of building an interface, SWIG may encounter syntax
5353  errors or other problems. The best way to deal with this is to simply
5354  copy the offending code into a separate interface file and edit it.
5355  However, the SWIG developers have worked very hard to improve the SWIG
5356  parser--you should report parsing errors to the <A href="http://www.swig.org/mail.html">
5357 swig-devel mailing list</A> or to the <A href="http://www.swig.org/bugs.html">
5358 SWIG bug tracker</A>.</P>
5359 <H3><A name="SWIG_nn47"></A>5.7.2 The SWIG interface file</H3>
5360 <P> The preferred method of using SWIG is to generate separate interface
5361  file. Suppose you have the following C header file :</P>
5362 <DIV class="code">
5363 <PRE>
5364 /* File : header.h */
5365
5366 #include &lt;stdio.h&gt;
5367 #include &lt;math.h&gt;
5368
5369 extern int foo(double);
5370 extern double bar(int, int);
5371 extern void dump(FILE *f);
5372
5373 </PRE>
5374 </DIV>
5375 <P> A typical SWIG interface file for this header file would look like
5376  the following :</P>
5377 <DIV class="code">
5378 <PRE>
5379 /* File : interface.i */
5380 %module mymodule
5381 %{
5382 #include &quot;header.h&quot;
5383 %}
5384 extern int foo(double);
5385 extern double bar(int, int);
5386 extern void dump(FILE *f);
5387
5388 </PRE>
5389 </DIV>
5390 <P> Of course, in this case, our header file is pretty simple so we
5391  could use a simpler approach and use an interface file like this:</P>
5392 <DIV class="code">
5393 <PRE>
5394 /* File : interface.i */
5395 %module mymodule
5396 %{
5397 #include &quot;header.h&quot;
5398 %}
5399 %include &quot;header.h&quot;
5400 </PRE>
5401 </DIV>
5402 <P> The main advantage of this approach is minimal maintenance of an
5403  interface file for when the header file changes in the future. In more
5404  complex projects, an interface file containing numerous <TT>%include</TT>
5405  and <TT>#include</TT> statements like this is one of the most common
5406  approaches to interface file design due to lower maintenance overhead.</P>
5407 <H3><A name="SWIG_nn48"></A>5.7.3 Why use separate interface files?</H3>
5408 <P> Although SWIG can parse many header files, it is more common to
5409  write a special <TT>.i</TT> file defining the interface to a package.
5410  There are several reasons why you might want to do this:</P>
5411 <UL>
5412 <LI>It is rarely necessary to access every single function in a large
5413  package. Many C functions might have little or no use in a scripted
5414  environment. Therefore, why wrap them?</LI>
5415 <LI>Separate interface files provide an opportunity to provide more
5416  precise rules about how an interface is to be constructed.</LI>
5417 <LI>Interface files can provide more structure and organization.</LI>
5418 <LI>SWIG can't parse certain definitions that appear in header files.
5419  Having a separate file allows you to eliminate or work around these
5420  problems.</LI>
5421 <LI>Interface files provide a more precise definition of what the
5422  interface is. Users wanting to extend the system can go to the
5423  interface file and immediately see what is available without having to
5424  dig it out of header files.</LI>
5425 </UL>
5426 <H3><A name="SWIG_nn49"></A>5.7.4 Getting the right header files</H3>
5427 <P> Sometimes, it is necessary to use certain header files in order for
5428  the code generated by SWIG to compile properly. Make sure you include
5429  certain header files by using a <TT>%{,%}</TT> block like this:</P>
5430 <DIV class="code">
5431 <PRE>
5432 %module graphics
5433 %{
5434 #include &lt;GL/gl.h&gt;
5435 #include &lt;GL/glu.h&gt;
5436 %}
5437
5438 // Put rest of declarations here
5439 ...
5440 </PRE>
5441 </DIV>
5442 <H3><A name="SWIG_nn50"></A>5.7.5 What to do with main()</H3>
5443 <P> If your program defines a <TT>main()</TT> function, you may need to
5444  get rid of it or rename it in order to use a scripting language. Most
5445  scripting languages define their own <TT>main()</TT> procedure that is
5446  called instead. <TT>main()</TT> also makes no sense when working with
5447  dynamic loading. There are a few approaches to solving the <TT>main()</TT>
5448  conflict :</P>
5449 <UL>
5450 <LI>Get rid of <TT>main()</TT> entirely.</LI>
5451 <LI>Rename <TT>main()</TT> to something else. You can do this by
5452  compiling your C program with an option like <TT>-Dmain=oldmain</TT>.</LI>
5453 <LI>Use conditional compilation to only include <TT>main()</TT> when not
5454  using a scripting language.</LI>
5455 </UL>
5456 <P> Getting rid of <TT>main()</TT> may cause potential initialization
5457  problems of a program. To handle this problem, you may consider writing
5458  a special function called <TT>program_init()</TT> that initializes your
5459  program upon startup. This function could then be called either from
5460  the scripting language as the first operation, or when the SWIG
5461  generated module is loaded.</P>
5462 <P> As a general note, many C programs only use the <TT>main()</TT>
5463  function to parse command line options and to set parameters. However,
5464  by using a scripting language, you are probably trying to create a
5465  program that is more interactive. In many cases, the old <TT>main()</TT>
5466  program can be completely replaced by a Perl, Python, or Tcl script.</P>
5467 <P><B> Note:</B> If some cases, you might be inclined to create a
5468  scripting language wrapper for <TT>main()</TT>. If you do this, the
5469  compilation will probably work and your module might even load
5470  correctly. The only trouble is that when you call your <TT>main()</TT>
5471  wrapper, you will find that it actually invokes the <TT>main()</TT> of
5472  the scripting language interpreter itself! This behavior is a side
5473  effect of the symbol binding mechanism used in the dynamic linker. The
5474  bottom line: don't do this.</P>
5475 <HR NOSHADE>
5476 <H1><A name="SWIGPlus"></A>6 SWIG and C++</H1>
5477
5478 <!-- INDEX -->
5479 <DIV class="sectiontoc">
5480 <UL>
5481 <LI><A href="#SWIGPlus_nn2">Comments on C++ Wrapping</A></LI>
5482 <LI><A href="#SWIGPlus_nn3">Approach</A></LI>
5483 <LI><A href="#SWIGPlus_nn4">Supported C++ features</A></LI>
5484 <LI><A href="#SWIGPlus_nn5">Command line options and compilation</A></LI>
5485 <LI><A href="#SWIGPlus_nn38">Proxy classes</A>
5486 <UL>
5487 <LI><A href="#SWIGPlus_nn39">Construction of proxy classes</A></LI>
5488 <LI><A href="#SWIGPlus_nn40">Resource management in proxies</A></LI>
5489 <LI><A href="#SWIGPlus_nn41">Language specific details</A></LI>
5490 </UL>
5491 </LI>
5492 <LI><A href="#SWIGPlus_nn6">Simple C++ wrapping</A>
5493 <UL>
5494 <LI><A href="#SWIGPlus_nn7">Constructors and destructors</A></LI>
5495 <LI><A href="#SWIGPlus_nn8">Default constructors, copy constructors and
5496  implicit destructors</A></LI>
5497 <LI><A href="#SWIGPlus_nn9">When constructor wrappers aren't created</A></LI>
5498 <LI><A href="#SWIGPlus_nn10">Copy constructors</A></LI>
5499 <LI><A href="#SWIGPlus_nn11">Member functions</A></LI>
5500 <LI><A href="#SWIGPlus_nn12">Static members</A></LI>
5501 <LI><A href="#SWIGPlus_member_data">Member data</A></LI>
5502 </UL>
5503 </LI>
5504 <LI><A href="#SWIGPlus_default_args">Default arguments</A></LI>
5505 <LI><A href="#SWIGPlus_nn15">Protection</A></LI>
5506 <LI><A href="#SWIGPlus_nn16">Enums and constants</A></LI>
5507 <LI><A href="#SWIGPlus_nn17">Friends</A></LI>
5508 <LI><A href="#SWIGPlus_nn18">References and pointers</A></LI>
5509 <LI><A href="#SWIGPlus_nn19">Pass and return by value</A></LI>
5510 <LI><A href="#SWIGPlus_nn20">Inheritance</A></LI>
5511 <LI><A href="#SWIGPlus_nn21">A brief discussion of multiple inheritance,
5512  pointers, and type checking</A></LI>
5513 <LI><A href="#SWIGPlus_overloaded_methods">Wrapping Overloaded Functions
5514  and Methods</A>
5515 <UL>
5516 <LI><A href="#SWIGPlus_nn24">Dispatch function generation</A></LI>
5517 <LI><A href="#SWIGPlus_nn25">Ambiguity in Overloading</A></LI>
5518 <LI><A href="#ambiguity_resolution_renaming">Ambiguity resolution and
5519  renaming</A></LI>
5520 <LI><A href="#SWIGPlus_nn27">Comments on overloading</A></LI>
5521 </UL>
5522 </LI>
5523 <LI><A href="#SWIGPlus_nn28">Wrapping overloaded operators</A></LI>
5524 <LI><A href="#SWIGPlus_class_extension">Class extension</A></LI>
5525 <LI><A href="#SWIGPlus_nn30">Templates</A></LI>
5526 <LI><A href="#SWIGPlus_nn31">Namespaces</A></LI>
5527 <LI><A href="#SWIGPlus_renaming_templated_types_namespaces">Renaming
5528  templated types in namespaces</A></LI>
5529 <LI><A href="#SWIGPlus_exception_specifications">Exception
5530  specifications</A></LI>
5531 <LI><A href="#SWIGPlus_catches">Exception handling with %catches</A></LI>
5532 <LI><A href="#SWIGPlus_nn33">Pointers to Members</A></LI>
5533 <LI><A href="#SWIGPlus_nn34">Smart pointers and operator-&gt;()</A></LI>
5534 <LI><A href="#SWIGPlus_nn35">Using declarations and inheritance</A></LI>
5535 <LI><A href="#SWIGPlus_nested_classes">Nested classes</A></LI>
5536 <LI><A href="#SWIGPlus_nn37">A brief rant about const-correctness</A></LI>
5537 <LI><A href="#SWIGPlus_nn42">Where to go for more information</A></LI>
5538 </UL>
5539 </DIV>
5540 <!-- INDEX -->
5541 <P> This chapter describes SWIG's support for wrapping C++. As a
5542  prerequisite, you should first read the chapter <A href="#SWIG">SWIG
5543  Basics</A> to see how SWIG wraps ANSI C. Support for C++ builds upon
5544  ANSI C wrapping and that material will be useful in understanding this
5545  chapter.</P>
5546 <H2><A name="SWIGPlus_nn2"></A>6.1 Comments on C++ Wrapping</H2>
5547 <P> Because of its complexity and the fact that C++ can be difficult to
5548  integrate with itself let alone other languages, SWIG only provides
5549  support for a subset of C++ features. Fortunately, this is now a rather
5550  large subset.</P>
5551 <P> In part, the problem with C++ wrapping is that there is no
5552  semantically obvious (or automatic ) way to map many of its advanced
5553  features into other languages. As a simple example, consider the
5554  problem of wrapping C++ multiple inheritance to a target language with
5555  no such support. Similarly, the use of overloaded operators and
5556  overloaded functions can be problematic when no such capability exists
5557  in a target language.</P>
5558 <P> A more subtle issue with C++ has to do with the way that some C++
5559  programmers think about programming libraries. In the world of SWIG,
5560  you are really trying to create binary-level software components for
5561  use in other languages. In order for this to work, a &quot;component&quot; has to
5562  contain real executable instructions and there has to be some kind of
5563  binary linking mechanism for accessing its functionality. In contrast,
5564  C++ has increasingly relied upon generic programming and templates for
5565  much of its functionality. Although templates are a powerful feature,
5566  they are largely orthogonal to the whole notion of binary components
5567  and libraries. For example, an STL <TT>vector</TT> does not define any
5568  kind of binary object for which SWIG can just create a wrapper. To
5569  further complicate matters, these libraries often utilize a lot of
5570  behind the scenes magic in which the semantics of seemingly basic
5571  operations (e.g., pointer dereferencing, procedure call, etc.) can be
5572  changed in dramatic and sometimes non-obvious ways. Although this
5573  &quot;magic&quot; may present few problems in a C++-only universe, it greatly
5574  complicates the problem of crossing language boundaries and provides
5575  many opportunities to shoot yourself in the foot. You will just have to
5576  be careful.</P>
5577 <H2><A name="SWIGPlus_nn3"></A>6.2 Approach</H2>
5578 <P> To wrap C++, SWIG uses a layered approach to code generation. At the
5579  lowest level, SWIG generates a collection of procedural ANSI-C style
5580  wrappers. These wrappers take care of basic type conversion, type
5581  checking, error handling, and other low-level details of the C++
5582  binding. These wrappers are also sufficient to bind C++ into any target
5583  language that supports built-in procedures. In some sense, you might
5584  view this layer of wrapping as providing a C library interface to C++.
5585  On top of the low-level procedural (flattened) interface, SWIG
5586  generates proxy classes that provide a natural object-oriented (OO)
5587  interface to the underlying code. The proxy classes are typically
5588  written in the target language itself. For instance, in Python, a real
5589  Python class is used to provide a wrapper around the underlying C++
5590  object.</P>
5591 <P> It is important to emphasize that SWIG takes a deliberately
5592  conservative and non-intrusive approach to C++ wrapping. SWIG does not
5593  encapsulate C++ classes inside a special C++ adaptor, it does not rely
5594  upon templates, nor does it add in additional C++ inheritance when
5595  generating wrappers. The last thing that most C++ programs need is even
5596  more compiler magic. Therefore, SWIG tries to maintain a very strict
5597  and clean separation between the implementation of your C++ application
5598  and the resulting wrapper code. You might say that SWIG has been
5599  written to follow the principle of least surprise--it does not play
5600  sneaky tricks with the C++ type system, it doesn't mess with your class
5601  hierarchies, and it doesn't introduce new semantics. Although this
5602  approach might not provide the most seamless integration with C++, it
5603  is safe, simple, portable, and debuggable.</P>
5604 <P> Some of this chapter focuses on the low-level procedural interface
5605  to C++ that is used as the foundation for all language modules. Keep in
5606  mind that the target languages also provide the high-level OO interface
5607  via proxy classes. More detailed coverage can be found in the
5608  documentation for each target language.</P>
5609 <H2><A name="SWIGPlus_nn4"></A>6.3 Supported C++ features</H2>
5610 <P> SWIG currently supports most C++ features including the following:</P>
5611 <UL>
5612 <LI>Classes</LI>
5613 <LI>Constructors and destructors</LI>
5614 <LI>Virtual functions</LI>
5615 <LI>Public inheritance (including multiple inheritance)</LI>
5616 <LI>Static functions</LI>
5617 <LI>Function and method overloading</LI>
5618 <LI>Operator overloading for many standard operators</LI>
5619 <LI>References</LI>
5620 <LI>Templates (including specialization and member templates)</LI>
5621 <LI>Pointers to members</LI>
5622 <LI>Namespaces</LI>
5623 <LI>Default parameters</LI>
5624 <LI>Smart pointers</LI>
5625 </UL>
5626 <P> The following C++ features are not currently supported:</P>
5627 <UL>
5628 <LI>Overloaded versions of certain operators (new, delete, etc.)</LI>
5629 <LI>Nested classes, see <A href="#SWIGPlus_nested_classes">Nested
5630  classes</A> for workarounds.</LI>
5631 </UL>
5632 <P> As a rule of thumb, SWIG should not be used on raw C++ source files,
5633  use header files only.</P>
5634 <P> SWIG's C++ support is an ongoing project so some of these
5635  limitations may be lifted in future releases. However, we make no
5636  promises. Also, submitting a bug report is a very good way to get
5637  problems fixed (wink).</P>
5638 <H2><A name="SWIGPlus_nn5"></A>6.4 Command line options and compilation</H2>
5639 <P> When wrapping C++ code, it is critical that SWIG be called with the
5640  `<TT>-c++</TT>' option. This changes the way a number of critical
5641  features such as memory management are handled. It also enables the
5642  recognition of C++ keywords. Without the <TT>-c++</TT> flag, SWIG will
5643  either issue a warning or a large number of syntax errors if it
5644  encounters C++ code in an interface file.</P>
5645 <P> When compiling and linking the resulting wrapper file, it is normal
5646  to use the C++ compiler. For example:</P>
5647 <DIV class="shell">
5648 <PRE>
5649 $ swig -c++ -tcl example.i
5650 $ c++ -c example_wrap.cxx 
5651 $ c++ example_wrap.o $(OBJS) -o example.so
5652 </PRE>
5653 </DIV>
5654 <P> Unfortunately, the process varies slightly on each platform. Make
5655  sure you refer to the documentation on each target language for further
5656  details. The SWIG Wiki also has further details.</P>
5657 <B> Compatibility Note:</B> Early versions of SWIG generated just a
5658  flattened low-level C style API to C++ classes by default. The <TT>
5659 -noproxy</TT> commandline option is recognised by many target languages
5660  and will generate just this interface as in earlier versions.
5661 <H2><A name="SWIGPlus_nn38"></A>6.5 Proxy classes</H2>
5662 <P> In order to provide a natural mapping from C++ classes to the target
5663  language classes, SWIG's target languages mostly wrap C++ classes with
5664  special proxy classes. These proxy classes are typically implemented in
5665  the target language itself. For example, if you're building a Python
5666  module, each C++ class is wrapped by a Python proxy class. Or if you're
5667  building a Java module, each C++ class is wrapped by a Java proxy
5668  class.</P>
5669 <H3><A name="SWIGPlus_nn39"></A>6.5.1 Construction of proxy classes</H3>
5670 <P> Proxy classes are always constructed as an extra layer of wrapping
5671  that uses low-level accessor functions. To illustrate, suppose you had
5672  a C++ class like this:</P>
5673 <DIV class="code">
5674 <PRE>
5675 class Foo {
5676 public:
5677       Foo();
5678      ~Foo();
5679       int  bar(int x);
5680       int  x;
5681 };
5682 </PRE>
5683 </DIV>
5684 <P> Using C++ as pseudocode, a proxy class looks something like this:</P>
5685 <DIV class="code">
5686 <PRE>
5687 class FooProxy {
5688 private:
5689       Foo    *self;
5690 public:
5691       FooProxy() {
5692             self = new_Foo();
5693       }
5694      ~FooProxy() {
5695             delete_Foo(self);
5696       }
5697       int bar(int x) {
5698             return Foo_bar(self,x);
5699       }
5700       int x_get() {
5701             return Foo_x_get(self);
5702       }
5703       void x_set(int x) {
5704             Foo_x_set(self,x);
5705       }
5706 };
5707 </PRE>
5708 </DIV>
5709 <P> Of course, always keep in mind that the real proxy class is written
5710  in the target language. For example, in Python, the proxy might look
5711  roughly like this:</P>
5712 <DIV class="targetlang">
5713 <PRE>
5714 class Foo:
5715     def __init__(self):
5716          self.this = new_Foo()
5717     def __del__(self):
5718          delete_Foo(self.this)
5719     def bar(self,x):
5720          return Foo_bar(self.this,x)
5721     def __getattr__(self,name):
5722          if name == 'x':
5723               return Foo_x_get(self.this)
5724          ...
5725     def __setattr__(self,name,value):
5726          if name == 'x':
5727               Foo_x_set(self.this,value)
5728          ...
5729 </PRE>
5730 </DIV>
5731 <P> Again, it's important to emphasize that the low-level accessor
5732  functions are always used by the proxy classes. Whenever possible,
5733  proxies try to take advantage of language features that are similar to
5734  C++. This might include operator overloading, exception handling, and
5735  other features.</P>
5736 <H3><A name="SWIGPlus_nn40"></A>6.5.2 Resource management in proxies</H3>
5737 <P> A major issue with proxies concerns the memory management of wrapped
5738  objects. Consider the following C++ code:</P>
5739 <DIV class="code">
5740 <PRE>
5741 class Foo {
5742 public:
5743       Foo();
5744      ~Foo();
5745       int bar(int x);
5746       int x;
5747 };
5748
5749 class Spam {
5750 public:
5751       Foo *value;
5752       ...
5753 };
5754 </PRE>
5755 </DIV>
5756 <P> Consider some script code that uses these classes:</P>
5757 <DIV class="targetlang">
5758 <PRE>
5759 f = Foo()               # Creates a new Foo
5760 s = Spam()              # Creates a new Spam
5761 s.value = f             # Stores a reference to f inside s
5762 g = s.value             # Returns stored reference
5763 g = 4                   # Reassign g to some other value
5764 del f                   # Destroy f 
5765 </PRE>
5766 </DIV>
5767 <P> Now, ponder the resulting memory management issues. When objects are
5768  created in the script, the objects are wrapped by newly created proxy
5769  classes. That is, there is both a new proxy class instance and a new
5770  instance of the underlying C++ class. In this example, both <TT>f</TT>
5771  and <TT>s</TT> are created in this way. However, the statement <TT>
5772 s.value</TT> is rather curious---when executed, a pointer to <TT>f</TT>
5773  is stored inside another object. This means that the scripting proxy
5774  class<EM> AND</EM> another C++ class share a reference to the same
5775  object. To make matters even more interesting, consider the statement <TT>
5776 g = s.value</TT>. When executed, this creates a new proxy class <TT>g</TT>
5777  that provides a wrapper around the C++ object stored in <TT>s.value</TT>
5778 . In general, there is no way to know where this object came from---it
5779  could have been created by the script, but it could also have been
5780  generated internally. In this particular example, the assignment of <TT>
5781 g</TT> results in a second proxy class for <TT>f</TT>. In other words, a
5782  reference to <TT>f</TT> is now shared by two proxy classes<EM> and</EM>
5783  a C++ class.</P>
5784 <P> Finally, consider what happens when objects are destroyed. In the
5785  statement, <TT>g=4</TT>, the variable <TT>g</TT> is reassigned. In many
5786  languages, this makes the old value of <TT>g</TT> available for garbage
5787  collection. Therefore, this causes one of the proxy classes to be
5788  destroyed. Later on, the statement <TT>del f</TT> destroys the other
5789  proxy class. Of course, there is still a reference to the original
5790  object stored inside another C++ object. What happens to it? Is the
5791  object still valid?</P>
5792 <P> To deal with memory management problems, proxy classes provide an
5793  API for controlling ownership. In C++ pseudocode, ownership control
5794  might look roughly like this:</P>
5795 <DIV class="code">
5796 <PRE>
5797 class FooProxy {
5798 public:
5799       Foo    *self;
5800       int     thisown;
5801
5802       FooProxy() {
5803             self = new_Foo();
5804             thisown = 1;       // Newly created object
5805       }
5806      ~FooProxy() {
5807             if (thisown) delete_Foo(self);
5808       }
5809       ...
5810       // Ownership control API
5811       void disown() {
5812            thisown = 0;
5813       }
5814       void acquire() {
5815            thisown = 1;
5816       }
5817 };
5818
5819 class FooPtrProxy: public FooProxy {
5820 public:
5821       FooPtrProxy(Foo *s) {
5822           self = s;
5823           thisown = 0;
5824       }
5825 };
5826
5827 class SpamProxy {
5828      ...
5829      FooProxy *value_get() {
5830           return FooPtrProxy(Spam_value_get(self));
5831      }
5832      void value_set(FooProxy *v) {
5833           Spam_value_set(self,v-&gt;self);
5834           v-&gt;disown();
5835      }
5836      ...
5837 };
5838 </PRE>
5839 </DIV>
5840 <P> Looking at this code, there are a few central features:</P>
5841 <UL>
5842 <LI>Each proxy class keeps an extra flag to indicate ownership. C++
5843  objects are only destroyed if the ownership flag is set.</LI>
5844 <LI>When new objects are created in the target language, the ownership
5845  flag is set.</LI>
5846 <LI>When a reference to an internal C++ object is returned, it is
5847  wrapped by a proxy class, but the proxy class does not have ownership.</LI>
5848 <LI>In certain cases, ownership is adjusted. For instance, when a value
5849  is assigned to the member of a class, ownership is lost.</LI>
5850 <LI>Manual ownership control is provided by special <TT>disown()</TT>
5851  and <TT>acquire()</TT> methods.</LI>
5852 </UL>
5853 <P> Given the tricky nature of C++ memory management, it is impossible
5854  for proxy classes to automatically handle every possible memory
5855  management problem. However, proxies do provide a mechanism for manual
5856  control that can be used (if necessary) to address some of the more
5857  tricky memory management problems.</P>
5858 <H3><A name="SWIGPlus_nn41"></A>6.5.3 Language specific details</H3>
5859 <P> Language specific details on proxy classes are contained in the
5860  chapters describing each target language. This chapter has merely
5861  introduced the topic in a very general way.</P>
5862 <H2><A name="SWIGPlus_nn6"></A>6.6 Simple C++ wrapping</H2>
5863 <P> The following code shows a SWIG interface file for a simple C++
5864  class.</P>
5865 <DIV class="code">
5866 <PRE>
5867 %module list
5868 %{
5869 #include &quot;list.h&quot;
5870 %}
5871
5872 // Very simple C++ example for linked list
5873
5874 class List {
5875 public:
5876   List();
5877   ~List();
5878   int  search(char *value);
5879   void insert(char *);
5880   void remove(char *);
5881   char *get(int n);
5882   int  length;
5883 static void print(List *l);
5884 };
5885 </PRE>
5886 </DIV>
5887 <P> To generate wrappers for this class, SWIG first reduces the class to
5888  a collection of low-level C-style accessor functions which are then
5889  used by the proxy classes.</P>
5890 <H3><A name="SWIGPlus_nn7"></A>6.6.1 Constructors and destructors</H3>
5891 <P> C++ constructors and destructors are translated into accessor
5892  functions such as the following :</P>
5893 <DIV class="code">
5894 <PRE>
5895 List * new_List(void) {
5896         return new List;
5897 }
5898 void delete_List(List *l) {
5899         delete l;
5900 }
5901
5902 </PRE>
5903 </DIV>
5904 <H3><A name="SWIGPlus_nn8"></A>6.6.2 Default constructors, copy
5905  constructors and implicit destructors</H3>
5906 <P> Following the C++ rules for implicit constructor and destructors,
5907  SWIG will automatically assume there is one even when they are not
5908  explicitly declared in the class interface.</P>
5909 <P> In general then:</P>
5910 <UL>
5911 <LI> If a C++ class does not declare any explicit constructor, SWIG will
5912  automatically generate a wrapper for one.</LI>
5913 <LI> If a C++ class does not declare an explicit copy constructor, SWIG
5914  will automatically generate a wrapper for one if the <TT>%copyctor</TT>
5915  is used.</LI>
5916 <LI> If a C++ class does not declare an explicit destructor, SWIG will
5917  automatically generate a wrapper for one.</LI>
5918 </UL>
5919 <P> And as in C++, a few rules that alters the previous behavior:</P>
5920 <UL>
5921 <LI>A default constructor is not created if a class already defines a
5922  constructor with arguments.</LI>
5923 <LI>Default constructors are not generated for classes with pure virtual
5924  methods or for classes that inherit from an abstract class, but don't
5925  provide definitions for all of the pure methods.</LI>
5926 <LI>A default constructor is not created unless all base classes support
5927  a default constructor.</LI>
5928 <LI>Default constructors and implicit destructors are not created if a
5929  class defines them in a <TT>private</TT> or <TT>protected</TT> section.</LI>
5930 <LI>Default constructors and implicit destructors are not created if any
5931  base class defines a non-public default constructor or destructor.</LI>
5932 </UL>
5933 <P> SWIG should never generate a default constructor, copy constructor
5934  or default destructor wrapper for a class in which it is illegal to do
5935  so. In some cases, however, it could be necessary (if the complete
5936  class declaration is not visible from SWIG, and one of the above rules
5937  is violated) or desired (to reduce the size of the final interface) by
5938  manually disabling the implicit constructor/destructor generation.</P>
5939 <P> To manually disable these, the <TT>%nodefaultctor</TT> and <TT>
5940 %nodefaultdtor</TT> <A href="#Customization_feature_flags">feature flag</A>
5941  directives can be used. Note that these directives only affects the
5942  implicit generation, and they have no effect if the default/copy
5943  constructors or destructor are explicitly declared in the class
5944  interface.</P>
5945 <P> For example:</P>
5946 <DIV class="code">
5947 <PRE>
5948 %nodefaultctor Foo;  // Disable the default constructor for class Foo.
5949 class Foo {          // No default constructor is generated, unless one is declared
5950 ...
5951 };
5952 class Bar {          // A default constructor is generated, if possible
5953 ...
5954 };
5955 </PRE>
5956 </DIV>
5957 <P> The directive <TT>%nodefaultctor</TT> can also be applied
5958  &quot;globally&quot;, as in:</P>
5959 <DIV class="code">
5960 <PRE>
5961 %nodefaultctor; // Disable creation of default constructors
5962 class Foo {     // No default constructor is generated, unless one is declared
5963 ...
5964 };
5965 class Bar {   
5966 public:
5967   Bar();        // The default constructor is generated, since one is declared
5968 };
5969 %clearnodefaultctor; // Enable the creation of default constructors again
5970 </PRE>
5971 </DIV>
5972 <P> The corresponding <TT>%nodefaultdtor</TT> directive can be used to
5973  disable the generation of the default or implicit destructor, if
5974  needed. Be aware, however, that this could lead to memory leaks in the
5975  target language. Hence, it is recommended to use this directive only in
5976  well known cases. For example:</P>
5977 <DIV class="code">
5978 <PRE>
5979 %nodefaultdtor Foo;   // Disable the implicit/default destructor for class Foo.
5980 class Foo {           // No destructor is generated, unless one is declared
5981 ...
5982 };
5983 </PRE>
5984 </DIV>
5985 <P><B> Compatibility Note:</B> The generation of default
5986  constructors/implicit destructors was made the default behavior in SWIG
5987  1.3.7. This may break certain older modules, but the old behavior can
5988  be easily restored using <TT>%nodefault</TT> or the <TT>-nodefault</TT>
5989  command line option. Furthermore, in order for SWIG to properly
5990  generate (or not generate) default constructors, it must be able to
5991  gather information from both the <TT>private</TT> and <TT>protected</TT>
5992  sections (specifically, it needs to know if a private or protected
5993  constructor/destructor is defined). In older versions of SWIG, it was
5994  fairly common to simply remove or comment out the private and protected
5995  sections of a class due to parser limitations. However, this removal
5996  may now cause SWIG to erroneously generate constructors for classes
5997  that define a constructor in those sections. Consider restoring those
5998  sections in the interface or using <TT>%nodefault</TT> to fix the
5999  problem.</P>
6000 <P><B> Note:</B> The <TT>%nodefault</TT> directive/<TT>-nodefault</TT>
6001  options described above, which disable both the default constructor and
6002  the implicit destructors, could lead to memory leaks, and so it is
6003  strongly recommended to not use them.</P>
6004 <H3><A name="SWIGPlus_nn9"></A>6.6.3 When constructor wrappers aren't
6005  created</H3>
6006 <P> If a class defines a constructor, SWIG normally tries to generate a
6007  wrapper for it. However, SWIG will not generate a constructor wrapper
6008  if it thinks that it will result in illegal wrapper code. There are
6009  really two cases where this might show up.</P>
6010 <P> First, SWIG won't generate wrappers for protected or private
6011  constructors. For example:</P>
6012 <DIV class="code">
6013 <PRE>
6014 class Foo {
6015 protected:
6016      Foo();         // Not wrapped.
6017 public:
6018       ...
6019 };
6020 </PRE>
6021 </DIV>
6022 <P> Next, SWIG won't generate wrappers for a class if it appears to be
6023  abstract--that is, it has undefined pure virtual methods. Here are some
6024  examples:</P>
6025 <DIV class="code">
6026 <PRE>
6027 class Bar {
6028 public:
6029      Bar();               // Not wrapped.  Bar is abstract.
6030      virtual void spam(void) = 0; 
6031 };
6032
6033 class Grok : public Bar {
6034 public:
6035       Grok();            // Not wrapped. No implementation of abstract spam().
6036 };
6037 </PRE>
6038 </DIV>
6039 <P> Some users are surprised (or confused) to find missing constructor
6040  wrappers in their interfaces. In almost all cases, this is caused when
6041  classes are determined to be abstract. To see if this is the case, run
6042  SWIG with all of its warnings turned on:</P>
6043 <DIV class="shell">
6044 <PRE>
6045 % swig -Wall -python module.i
6046 </PRE>
6047 </DIV>
6048 <P> In this mode, SWIG will issue a warning for all abstract classes. It
6049  is possible to force a class to be non-abstract using this:</P>
6050 <DIV class="code">
6051 <PRE>
6052 %feature(&quot;notabstract&quot;) Foo;
6053
6054 class Foo : public Bar {
6055 public:
6056      Foo();    // Generated no matter what---not abstract. 
6057      ...
6058 };
6059 </PRE>
6060 </DIV>
6061 <P> More information about <TT>%feature</TT> can be found in the <A href="#Customization">
6062 Customization features</A> chapter.</P>
6063 <H3><A name="SWIGPlus_nn10"></A>6.6.4 Copy constructors</H3>
6064 <P> If a class defines more than one constructor, its behavior depends
6065  on the capabilities of the target language. If overloading is
6066  supported, the copy constructor is accessible using the normal
6067  constructor function. For example, if you have this:</P>
6068 <DIV class="code">
6069 <PRE>
6070 class List {
6071 public:
6072     List();    
6073     List(const List &amp;);      // Copy constructor
6074     ...
6075 };
6076 </PRE>
6077 </DIV>
6078 <P> then the copy constructor can be used as follows:</P>
6079 <DIV class="targetlang">
6080 <PRE>
6081 x = List()               # Create a list
6082 y = List(x)              # Copy list x
6083 </PRE>
6084 </DIV>
6085 <P> If the target language does not support overloading, then the copy
6086  constructor is available through a special function like this:</P>
6087 <DIV class="code">
6088 <PRE>
6089 List *copy_List(List *f) {
6090     return new List(*f);
6091 }
6092 </PRE>
6093 </DIV>
6094 <P><B> Note:</B> For a class <TT>X</TT>, SWIG only treats a constructor
6095  as a copy constructor if it can be applied to an object of type <TT>X</TT>
6096  or <TT>X *</TT>. If more than one copy constructor is defined, only the
6097  first definition that appears is used as the copy constructor--other
6098  definitions will result in a name-clash. Constructors such as <TT>
6099 X(const X &amp;)</TT>, <TT>X(X &amp;)</TT>, and <TT>X(X *)</TT> are handled as
6100  copy constructors in SWIG.</P>
6101 <P><B> Note:</B> SWIG does<EM> not</EM> generate a copy constructor
6102  wrapper unless one is explicitly declared in the class. This differs
6103  from the treatment of default constructors and destructors. However,
6104  copy constructor wrappers can be generated if using the <TT>copyctor</TT>
6105  <A href="#Customization_feature_flags">feature flag</A>. For example:</P>
6106 <DIV class="code">
6107 <PRE>
6108 %copyctor List;
6109
6110 class List {
6111 public:
6112     List();    
6113 };
6114 </PRE>
6115 </DIV>
6116 <P> Will generate a copy constructor wrapper for <TT>List</TT>.</P>
6117 <P><B> Compatibility note:</B> Special support for copy constructors was
6118  not added until SWIG-1.3.12. In previous versions, copy constructors
6119  could be wrapped, but they had to be renamed. For example:</P>
6120 <DIV class="code">
6121 <PRE>
6122 class Foo {
6123 public:
6124     Foo();
6125   %name(CopyFoo) Foo(const Foo &amp;);
6126     ...
6127 };
6128 </PRE>
6129 </DIV>
6130 <P> For backwards compatibility, SWIG does not perform any special
6131  copy-constructor handling if the constructor has been manually renamed.
6132  For instance, in the above example, the name of the constructor is set
6133  to <TT>new_CopyFoo()</TT>. This is the same as in older versions.</P>
6134 <H3><A name="SWIGPlus_nn11"></A>6.6.5 Member functions</H3>
6135 <P> All member functions are roughly translated into accessor functions
6136  like this :</P>
6137 <DIV class="code">
6138 <PRE>
6139 int List_search(List *obj, char *value) {
6140         return obj-&gt;search(value);
6141 }
6142
6143 </PRE>
6144 </DIV>
6145 <P> This translation is the same even if the member function has been
6146  declared as <TT>virtual</TT>.</P>
6147 <P> It should be noted that SWIG does not<EM> actually</EM> create a C
6148  accessor function in the code it generates. Instead, member access such
6149  as <TT>obj-&gt;search(value)</TT> is directly inlined into the generated
6150  wrapper functions. However, the name and calling convention of the
6151  low-level procedural wrappers match the accessor function prototype
6152  described above.</P>
6153 <H3><A name="SWIGPlus_nn12"></A>6.6.6 Static members</H3>
6154 <P> Static member functions are called directly without making any
6155  special transformations. For example, the static member function <TT>
6156 print(List *l)</TT> directly invokes <TT>List::print(List *l)</TT> in
6157  the generated wrapper code.</P>
6158 <H3><A name="SWIGPlus_member_data"></A>6.6.7 Member data</H3>
6159 <P> Member data is handled in exactly the same manner as for C
6160  structures. A pair of accessor functions are effectively created. For
6161  example :</P>
6162 <DIV class="code">
6163 <PRE>
6164 int List_length_get(List *obj) {
6165         return obj-&gt;length;
6166 }
6167 int List_length_set(List *obj, int value) {
6168         obj-&gt;length = value;
6169         return value;
6170 }
6171
6172 </PRE>
6173 </DIV>
6174 <P> A read-only member can be created using the <TT>%immutable</TT> and <TT>
6175 %mutable</TT> <A href="#Customization_feature_flags">feature flag</A>
6176  directive. For example, we probably wouldn't want the user to change
6177  the length of a list so we could do the following to make the value
6178  available, but read-only.</P>
6179 <DIV class="code">
6180 <PRE>
6181 class List {
6182 public:
6183 ...
6184 %immutable;
6185         int length;
6186 %mutable;
6187 ...
6188 };
6189 </PRE>
6190 </DIV>
6191 <P> Alternatively, you can specify an immutable member in advance like
6192  this:</P>
6193 <DIV class="code">
6194 <PRE>
6195 %immutable List::length;
6196 ...
6197 class List {
6198    ...
6199    int length;         // Immutable by above directive
6200    ...
6201 };
6202 </PRE>
6203 </DIV>
6204 <P> Similarly, all data attributes declared as <TT>const</TT> are
6205  wrapped as read-only members.</P>
6206 <P> There are some subtle issues when wrapping data members that are
6207  themselves classes. For instance, if you had another class like this,</P>
6208 <DIV class="code">
6209 <PRE>
6210 class Foo {
6211 public:
6212     List items;
6213     ...
6214 </PRE>
6215 </DIV>
6216 <P> then the low-level accessor to the <TT>items</TT> member actually
6217  uses pointers. For example:</P>
6218 <DIV class="code">
6219 <PRE>
6220 List *Foo_items_get(Foo *self) {
6221     return &amp;self-&gt;items;
6222 }
6223 void Foo_items_set(Foo *self, List *value) {
6224     self-&gt;items = *value;
6225 }
6226 </PRE>
6227 </DIV>
6228 <P> More information about this can be found in the SWIG Basics chapter,
6229  <A href="#SWIG_structure_data_members">Structure data members</A>
6230  section.</P>
6231 <P> The wrapper code to generate the accessors for classes comes from
6232  the pointer typemaps. This can be somewhat unnatural for some types.
6233  For example, a user would expect the STL std::string class member
6234  variables to be wrapped as a string in the target language, rather than
6235  a pointer to this class. The const reference typemaps offer this type
6236  of marshalling, so there is a feature to tell SWIG to use the const
6237  reference typemaps rather than the pointer typemaps. It is the <TT>
6238 %naturalvar</TT> directive and is used as follows:</P>
6239 <DIV class="code">
6240 <PRE>
6241 // All List variables will use const List&amp; typemaps
6242 %naturalvar List;
6243
6244 // Only Foo::myList will use const List&amp; typemaps
6245 %naturalvar Foo::myList;
6246 struct Foo {
6247   List myList;
6248 };
6249
6250 // All variables will use const reference typemaps
6251 %naturalvar;
6252 </PRE>
6253 </DIV>
6254 <P> The observant reader will notice that <TT>%naturalvar</TT> works
6255  like any other <A href="#Customization_feature_flags">feature flag</A>
6256  directive, except it can also be attached to class types. The first of
6257  the example usages above show <TT>%naturalvar</TT> attaching to the <TT>
6258 List</TT> class. Effectively this feature changes the way accessors are
6259  generated to the following:</P>
6260 <DIV class="code">
6261 <PRE>
6262 const List &amp;Foo_items_get(Foo *self) {
6263     return self-&gt;items;
6264 }
6265 void Foo_items_set(Foo *self, const List &amp;value) {
6266     self-&gt;items = value;
6267 }
6268 </PRE>
6269 </DIV>
6270 <P> In fact it is generally a good idea to use this feature globally as
6271  the reference typemaps have extra NULL checking compared to the pointer
6272  typemaps. A pointer can be NULL, whereas a reference cannot, so the
6273  extra checking ensures that the target language user does not pass in a
6274  value that translates to a NULL pointer and thereby preventing any
6275  potential NULL pointer dereferences. The <TT>%naturalvar</TT> feature
6276  will apply to global variables in addition to member variables in some
6277  language modules, eg C# and Java.</P>
6278 <P> Other alternatives for turning this feature on globally are to use
6279  the <TT>swig -naturalvar</TT> commandline option or the module mode
6280  option, <TT>%module(naturalvar=1)</TT></P>
6281 <P><B> Compatibility note:</B> The <TT>%naturalvar</TT> feature was
6282  introduced in SWIG-1.3.28, prior to which it was necessary to manually
6283  apply the const reference typemaps, eg <TT>%apply const std::string &amp; {
6284  std::string * }</TT>, but this example would also apply the typemaps to
6285  methods taking a <TT>std::string</TT> pointer.</P>
6286 <P><B> Compatibility note:</B> Read-only access used to be controlled by
6287  a pair of directives <TT>%readonly</TT> and <TT>%readwrite</TT>.
6288  Although these directives still work, they generate a warning message.
6289  Simply change the directives to <TT>%immutable;</TT> and <TT>%mutable;</TT>
6290  to silence the warning. Don't forget the extra semicolon!</P>
6291 <P><B> Compatibility note:</B> Prior to SWIG-1.3.12, all members of
6292  unknown type were wrapped into accessor functions using pointers. For
6293  example, if you had a structure like this</P>
6294 <DIV class="code">
6295 <PRE>
6296 struct Foo {
6297    size_t  len;
6298 };
6299 </PRE>
6300 </DIV>
6301 <P> and nothing was known about <TT>size_t</TT>, then accessors would be
6302  written to work with <TT>size_t *</TT>. Starting in SWIG-1.3.12, this
6303  behavior has been modified. Specifically, pointers will<EM> only</EM>
6304  be used if SWIG knows that a datatype corresponds to a structure or
6305  class. Therefore, the above code would be wrapped into accessors
6306  involving <TT>size_t</TT>. This change is subtle, but it smooths over a
6307  few problems related to structure wrapping and some of SWIG's
6308  customization features.</P>
6309 <H2><A name="SWIGPlus_default_args"></A>6.7 Default arguments</H2>
6310 <P> SWIG will wrap all types of functions that have default arguments.
6311  For example member functions:</P>
6312 <DIV class="code">
6313 <PRE>
6314 class Foo {
6315 public:
6316     void bar(int x, int y = 3, int z = 4);
6317 };
6318 </PRE>
6319 </DIV>
6320 <P> SWIG handles default arguments by generating an extra overloaded
6321  method for each defaulted argument. SWIG is effectively handling
6322  methods with default arguments as if it was wrapping the equivalent
6323  overloaded methods. Thus for the example above, it is as if we had
6324  instead given the following to SWIG:</P>
6325 <DIV class="code">
6326 <PRE>
6327 class Foo {
6328 public:
6329     void bar(int x, int y, int z);
6330     void bar(int x, int y);
6331     void bar(int x);
6332 };
6333 </PRE>
6334 </DIV>
6335 <P> The wrappers produced are exactly the same as if the above code was
6336  instead fed into SWIG. Details of this are covered later in the <A href="#SWIGPlus_overloaded_methods">
6337 Wrapping Overloaded Functions and Methods</A> section. This approach
6338  allows SWIG to wrap all possible default arguments, but can be verbose.
6339  For example if a method has ten default arguments, then eleven wrapper
6340  methods are generated.</P>
6341 <P> Please see the <A href="#Customization_features_default_args">
6342 Features and default arguments</A> section for more information on using
6343  <TT>%feature</TT> with functions with default arguments. The <A href="#ambiguity_resolution_renaming">
6344 Ambiguity resolution and renaming</A> section also deals with using <TT>
6345 %rename</TT> and <TT>%ignore</TT> on methods with default arguments. If
6346  you are writing your own typemaps for types used in methods with
6347  default arguments, you may also need to write a <TT>typecheck</TT>
6348  typemap. See the <A href="#Typemaps_overloading">Typemaps and
6349  overloading</A> section for details or otherwise use the <TT>
6350 compactdefaultargs</TT> feature flag as mentioned below.</P>
6351 <P><B> Compatibility note:</B> Versions of SWIG prior to SWIG-1.3.23
6352  wrapped default arguments slightly differently. Instead a single
6353  wrapper method was generated and the default values were copied into
6354  the C++ wrappers so that the method being wrapped was then called with
6355  all the arguments specified. If the size of the wrappers are a concern
6356  then this approach to wrapping methods with default arguments can be
6357  re-activated by using the <TT>compactdefaultargs</TT> <A href="#Customization_feature_flags">
6358 feature flag</A>.</P>
6359 <DIV class="code">
6360 <PRE>
6361 %feature(&quot;compactdefaultargs&quot;) Foo::bar;
6362 class Foo {
6363 public:
6364     void bar(int x, int y = 3, int z = 4);
6365 };
6366 </PRE>
6367 </DIV>
6368 <P> This is great for reducing the size of the wrappers, but the caveat
6369  is it does not work for the statically typed languages, such as C# and
6370  Java, which don't have optional arguments in the language, Another
6371  restriction of this feature is that it cannot handle default arguments
6372  that are not public. The following example illustrates this:</P>
6373 <DIV class="code">
6374 <PRE>
6375 class Foo {
6376 private:
6377    static const int spam;
6378 public:
6379    void bar(int x, int y = spam);   // Won't work with %feature(&quot;compactdefaultargs&quot;) -
6380                                     // private default value
6381 };
6382 </PRE>
6383 </DIV>
6384 <P> This produces uncompileable wrapper code because default values in
6385  C++ are evaluated in the same scope as the member function whereas SWIG
6386  evaluates them in the scope of a wrapper function (meaning that the
6387  values have to be public).</P>
6388 <P> This feature is automatically turned on when wrapping <A href="#SWIG_default_args">
6389 C code with default arguments</A> and whenever keyword arguments
6390  (kwargs) are specified for either C or C++ code. Keyword arguments are
6391  a language feature of some scripting languages, for example Ruby and
6392  Python. SWIG is unable to support kwargs when wrapping overloaded
6393  methods, so the default approach cannot be used.</P>
6394 <H2><A name="SWIGPlus_nn15"></A>6.8 Protection</H2>
6395 <P> SWIG wraps class members that are public following the C++
6396  conventions, i.e., by explicit public declaration or by the use of the <TT>
6397 using</TT> directive. In general, anything specified in a private or
6398  protected section will be ignored, although the internal code generator
6399  sometimes looks at the contents of the private and protected sections
6400  so that it can properly generate code for default constructors and
6401  destructors. Directors could also modify the way non-public virtual
6402  protected members are treated.</P>
6403 <P> By default, members of a class definition are assumed to be private
6404  until you explicitly give a `<TT>public:</TT>' declaration (This is the
6405  same convention used by C++).</P>
6406 <H2><A name="SWIGPlus_nn16"></A>6.9 Enums and constants</H2>
6407 <P> Enumerations and constants are handled differently by the different
6408  language modules and are described in detail in the appropriate
6409  language chapter. However, many languages map enums and constants in a
6410  class definition into constants with the classname as a prefix. For
6411  example :</P>
6412 <DIV class="code">
6413 <PRE>
6414 class Swig {
6415 public:
6416         enum {ALE, LAGER, PORTER, STOUT};
6417 };
6418
6419 </PRE>
6420 </DIV>
6421 <P> Generates the following set of constants in the target scripting
6422  language :</P>
6423 <DIV class="targetlang">
6424 <PRE>
6425 Swig_ALE = Swig::ALE
6426 Swig_LAGER = Swig::LAGER
6427 Swig_PORTER = Swig::PORTER
6428 Swig_STOUT = Swig::STOUT
6429
6430 </PRE>
6431 </DIV>
6432 <P> Members declared as <TT>const</TT> are wrapped as read-only members
6433  and do not create constants.</P>
6434 <H2><A name="SWIGPlus_nn17"></A>6.10 Friends</H2>
6435 <P> Friend declarations are recognised by SWIG. For example, if you have
6436  this code:</P>
6437 <DIV class="code">
6438 <PRE>
6439 class Foo {
6440 public:
6441      ...
6442      friend void blah(Foo *f);
6443      ...
6444 };
6445 </PRE>
6446 </DIV>
6447 <P> then the <TT>friend</TT> declaration does result in a wrapper code
6448  equivalent to one generated for the following declaration</P>
6449 <DIV class="code">
6450 <PRE>
6451 class Foo {
6452 public:
6453     ...
6454 };
6455
6456 void blah(Foo *f);    
6457 </PRE>
6458 </DIV>
6459 <P> A friend declaration, as in C++, is understood to be in the same
6460  scope where the class is declared, hence, you can have</P>
6461 <DIV class="code">
6462 <PRE>
6463
6464 %ignore bar::blah(Foo *f);
6465
6466 namespace bar {
6467
6468   class Foo {
6469   public:
6470      ...
6471      friend void blah(Foo *f);
6472      ...
6473   };
6474 }
6475 </PRE>
6476 </DIV>
6477 <P> and a wrapper for the method 'blah' will not be generated.</P>
6478 <H2><A name="SWIGPlus_nn18"></A>6.11 References and pointers</H2>
6479 <P> C++ references are supported, but SWIG transforms them back into
6480  pointers. For example, a declaration like this :</P>
6481 <DIV class="code">
6482 <PRE>
6483 class Foo {
6484 public:
6485         double bar(double &amp;a);
6486 }
6487 </PRE>
6488 </DIV>
6489 <P> has a low-level accessor</P>
6490 <DIV class="code">
6491 <PRE>
6492 double Foo_bar(Foo *obj, double *a) {
6493         obj-&gt;bar(*a);
6494 }
6495 </PRE>
6496 </DIV>
6497 <P> As a special case, most language modules pass <TT>const</TT>
6498  references to primitive datatypes (<TT>int</TT>, <TT>short</TT>, <TT>
6499 float</TT>, etc.) by value instead of pointers. For example, if you have
6500  a function like this,</P>
6501 <DIV class="code">
6502 <PRE>
6503 void foo(const int &amp;x);
6504 </PRE>
6505 </DIV>
6506 <P> it is called from a script as follows:</P>
6507 <DIV class="targetlang">
6508 <PRE>
6509 foo(3)              # Notice pass by value
6510 </PRE>
6511 </DIV>
6512 <P> Functions that return a reference are remapped to return a pointer
6513  instead. For example:</P>
6514 <DIV class="code">
6515 <PRE>
6516 class Bar {
6517 public:
6518      Foo &amp;spam();
6519 };
6520 </PRE>
6521 </DIV>
6522 <P> Generates an accessor like this:</P>
6523 <DIV class="code">
6524 <PRE>
6525 Foo *Bar_spam(Bar *obj) {
6526    Foo &amp;result = obj-&gt;spam();
6527    return &amp;result;
6528 }
6529 </PRE>
6530 </DIV>
6531 <P> However, functions that return <TT>const</TT> references to
6532  primitive datatypes (<TT>int</TT>, <TT>short</TT>, etc.) normally
6533  return the result as a value rather than a pointer. For example, a
6534  function like this,</P>
6535 <DIV class="code">
6536 <PRE>
6537 const int &amp;bar();
6538 </PRE>
6539 </DIV>
6540 <P> will return integers such as 37 or 42 in the target scripting
6541  language rather than a pointer to an integer.</P>
6542 <P> Don't return references to objects allocated as local variables on
6543  the stack. SWIG doesn't make a copy of the objects so this will
6544  probably cause your program to crash.</P>
6545 <P><B> Note:</B> The special treatment for references to primitive
6546  datatypes is necessary to provide more seamless integration with more
6547  advanced C++ wrapping applications---especially related to templates
6548  and the STL. This was first added in SWIG-1.3.12.</P>
6549 <H2><A name="SWIGPlus_nn19"></A>6.12 Pass and return by value</H2>
6550 <P> Occasionally, a C++ program will pass and return class objects by
6551  value. For example, a function like this might appear:</P>
6552 <DIV class="code">
6553 <PRE>
6554 Vector cross_product(Vector a, Vector b);
6555 </PRE>
6556 </DIV>
6557 <P> If no information is supplied about <TT>Vector</TT>, SWIG creates a
6558  wrapper function similar to the following:</P>
6559 <DIV class="code">
6560 <PRE>
6561 Vector *wrap_cross_product(Vector *a, Vector *b) {
6562    Vector x = *a;
6563    Vector y = *b;
6564    Vector r = cross_product(x,y);
6565    return new Vector(r);
6566 }</PRE>
6567 </DIV>
6568 <P> In order for the wrapper code to compile, <TT>Vector</TT> must
6569  define a copy constructor and a default constructor.</P>
6570 <P> If <TT>Vector</TT> is defined as a class in the interface, but it
6571  does not support a default constructor, SWIG changes the wrapper code
6572  by encapsulating the arguments inside a special C++ template wrapper
6573  class, through a process called the &quot;Fulton Transform&quot;. This produces a
6574  wrapper that looks like this:</P>
6575 <DIV class="code">
6576 <PRE>
6577 Vector cross_product(Vector *a, Vector *b) {
6578    SwigValueWrapper&lt;Vector&gt; x = *a;
6579    SwigValueWrapper&lt;Vector&gt; y = *b;
6580    SwigValueWrapper&lt;Vector&gt; r = cross_product(x,y);
6581    return new Vector(r);
6582 }
6583 </PRE>
6584 </DIV>
6585 <P> This transformation is a little sneaky, but it provides support for
6586  pass-by-value even when a class does not provide a default constructor
6587  and it makes it possible to properly support a number of SWIG's
6588  customization options. The definition of <TT>SwigValueWrapper</TT> can
6589  be found by reading the SWIG wrapper code. This class is really nothing
6590  more than a thin wrapper around a pointer.</P>
6591 <P> Although SWIG usually detects the classes to which the Fulton
6592  Transform should be applied, in some situations it's necessary to
6593  override it. That's done with <TT>%feature(&quot;valuewrapper&quot;)</TT> to
6594  ensure it is used and <TT>%feature(&quot;novaluewrapper&quot;)</TT> to ensure it
6595  is not used:</P>
6596 <DIV class="code">
6597 <PRE>
6598 %feature(&quot;novaluewrapper&quot;) A;    
6599 class A;
6600
6601 %feature(&quot;valuewrapper&quot;) B;
6602 struct B { 
6603     B();
6604     // ....
6605 };   
6606 </PRE>
6607 </DIV>
6608 <P> It is well worth considering turning this feature on for classes
6609  that do have a default constructor. It will remove a redundant
6610  constructor call at the point of the variable declaration in the
6611  wrapper, so will generate notably better performance for large objects
6612  or for classes with expensive construction. Alternatively consider
6613  returning a reference or a pointer.</P>
6614 <P><B> Note:</B> this transformation has no effect on typemaps or any
6615  other part of SWIG---it should be transparent except that you may see
6616  this code when reading the SWIG output file.</P>
6617 <P><B> Note:</B> This template transformation is new in SWIG-1.3.11 and
6618  may be refined in future SWIG releases. In practice, it is only
6619  absolutely necessary to do this for classes that don't define a default
6620  constructor.</P>
6621 <P><B> Note:</B> The use of this template only occurs when objects are
6622  passed or returned by value. It is not used for C++ pointers or
6623  references.</P>
6624 <H2><A name="SWIGPlus_nn20"></A>6.13 Inheritance</H2>
6625 <P> SWIG supports C++ inheritance of classes and allows both single and
6626  multiple inheritance, as limited or allowed by the target language. The
6627  SWIG type-checker knows about the relationship between base and derived
6628  classes and allows pointers to any object of a derived class to be used
6629  in functions of a base class. The type-checker properly casts pointer
6630  values and is safe to use with multiple inheritance.</P>
6631 <P> SWIG treats private or protected inheritance as close to the C++
6632  spirit, and target language capabilities, as possible. In most cases,
6633  this means that SWIG will parse the non-public inheritance
6634  declarations, but that will have no effect in the generated code,
6635  besides the implicit policies derived for constructor and destructors.</P>
6636 <P> The following example shows how SWIG handles inheritance. For
6637  clarity, the full C++ code has been omitted.</P>
6638 <DIV class="code">
6639 <PRE>
6640 // shapes.i
6641 %module shapes
6642 %{
6643 #include &quot;shapes.h&quot;
6644 %}
6645
6646 class Shape {
6647 public:
6648         double x,y;
6649         virtual double area() = 0;
6650         virtual double perimeter() = 0;
6651         void    set_location(double x, double y);
6652 };
6653 class Circle : public Shape {
6654 public:
6655         Circle(double radius);
6656         ~Circle();
6657         double area();
6658         double perimeter();
6659 };
6660 class Square : public Shape {
6661 public:
6662         Square(double size);
6663         ~Square();
6664         double area();
6665         double perimeter();
6666 }
6667 </PRE>
6668 </DIV>
6669 <P> When wrapped into Python, we can perform the following operations
6670  (shown using the low level Python accessors):</P>
6671 <DIV class="targetlang">
6672 <PRE>
6673 $ python
6674 &gt;&gt;&gt; import shapes
6675 &gt;&gt;&gt; circle = shapes.new_Circle(7)
6676 &gt;&gt;&gt; square = shapes.new_Square(10)
6677 &gt;&gt;&gt; print shapes.Circle_area(circle)
6678 153.93804004599999757
6679 &gt;&gt;&gt; print shapes.Shape_area(circle)
6680 153.93804004599999757
6681 &gt;&gt;&gt; print shapes.Shape_area(square)
6682 100.00000000000000000
6683 &gt;&gt;&gt; shapes.Shape_set_location(square,2,-3)
6684 &gt;&gt;&gt; print shapes.Shape_perimeter(square)
6685 40.00000000000000000
6686 &gt;&gt;&gt;
6687 </PRE>
6688 </DIV>
6689 <P> In this example, Circle and Square objects have been created. Member
6690  functions can be invoked on each object by making calls to <TT>
6691 Circle_area</TT>, <TT>Square_area</TT>, and so on. However, the same
6692  results can be accomplished by simply using the <TT>Shape_area</TT>
6693  function on either object.</P>
6694 <P> One important point concerning inheritance is that the low-level
6695  accessor functions are only generated for classes in which they are
6696  actually declared. For instance, in the above example, the method <TT>
6697 set_location()</TT> is only accessible as <TT>Shape_set_location()</TT>
6698  and not as <TT>Circle_set_location()</TT> or <TT>Square_set_location()</TT>
6699 . Of course, the <TT>Shape_set_location()</TT> function will accept any
6700  kind of object derived from Shape. Similarly, accessor functions for
6701  the attributes <TT>x</TT> and <TT>y</TT> are generated as <TT>
6702 Shape_x_get()</TT>, <TT>Shape_x_set()</TT>, <TT>Shape_y_get()</TT>, and <TT>
6703 Shape_y_set()</TT>. Functions such as <TT>Circle_x_get()</TT> are not
6704  available--instead you should use <TT>Shape_x_get()</TT>.</P>
6705 <P> Note that there is a one to one correlation between the low-level
6706  accessor functions and the proxy methods and therefore there is also a
6707  one to one correlation between the C++ class methods and the generated
6708  proxy class methods.</P>
6709 <P><B> Note:</B> For the best results, SWIG requires all base classes to
6710  be defined in an interface. Otherwise, you may get a warning message
6711  like this:</P>
6712 <DIV class="shell">
6713 <PRE>
6714 example.i:18: Warning(401): Nothing known about base class 'Foo'. Ignored.
6715 </PRE>
6716 </DIV>
6717 <P> If any base class is undefined, SWIG still generates correct type
6718  relationships. For instance, a function accepting a <TT>Foo *</TT> will
6719  accept any object derived from <TT>Foo</TT> regardless of whether or
6720  not SWIG actually wrapped the <TT>Foo</TT> class. If you really don't
6721  want to generate wrappers for the base class, but you want to silence
6722  the warning, you might consider using the <TT>%import</TT> directive to
6723  include the file that defines <TT>Foo</TT>. <TT>%import</TT> simply
6724  gathers type information, but doesn't generate wrappers. Alternatively,
6725  you could just define <TT>Foo</TT> as an empty class in the SWIG
6726  interface or use <A href="#Warnings_suppression">warning suppression</A>
6727 .</P>
6728 <P><B> Note:</B> <TT>typedef</TT>-names<EM> can</EM> be used as base
6729  classes. For example:</P>
6730 <DIV class="code">
6731 <PRE>
6732 class Foo {
6733 ...
6734 };
6735
6736 typedef Foo FooObj;
6737 class Bar : public FooObj {     // Ok.  Base class is Foo
6738 ...
6739 };
6740 </PRE>
6741 </DIV>
6742 <P> Similarly, <TT>typedef</TT> allows unnamed structures to be used as
6743  base classes. For example:</P>
6744 <DIV class="code">
6745 <PRE>
6746 typedef struct {
6747    ...
6748 } Foo;
6749
6750 class Bar : public Foo {    // Ok. 
6751 ...
6752 };
6753 </PRE>
6754 </DIV>
6755 <P><B> Compatibility Note:</B> Starting in version 1.3.7, SWIG only
6756  generates low-level accessor wrappers for the declarations that are
6757  actually defined in each class. This differs from SWIG1.1 which used to
6758  inherit all of the declarations defined in base classes and regenerate
6759  specialized accessor functions such as <TT>Circle_x_get()</TT>, <TT>
6760 Square_x_get()</TT>, <TT>Circle_set_location()</TT>, and <TT>
6761 Square_set_location()</TT>. This behavior resulted in huge amounts of
6762  replicated code for large class hierarchies and made it awkward to
6763  build applications spread across multiple modules (since accessor
6764  functions are duplicated in every single module). It is also
6765  unnecessary to have such wrappers when advanced features like proxy
6766  classes are used.<B> Note:</B> Further optimizations are enabled when
6767  using the <TT>-fvirtual</TT> option, which avoids the regenerating of
6768  wrapper functions for virtual members that are already defined in a
6769  base class.</P>
6770 <H2><A name="SWIGPlus_nn21"></A>6.14 A brief discussion of multiple
6771  inheritance, pointers, and type checking</H2>
6772 <P> When a target scripting language refers to a C++ object, it normally
6773  uses a tagged pointer object that contains both the value of the
6774  pointer and a type string. For example, in Tcl, a C++ pointer might be
6775  encoded as a string like this:</P>
6776 <DIV class="diagram">
6777 <PRE>
6778 _808fea88_p_Circle
6779 </PRE>
6780 </DIV>
6781 <P> A somewhat common question is whether or not the type-tag could be
6782  safely removed from the pointer. For instance, to get better
6783  performance, could you strip all type tags and just use simple integers
6784  instead?</P>
6785 <P> In general, the answer to this question is no. In the wrappers, all
6786  pointers are converted into a common data representation in the target
6787  language. Typically this is the equivalent of casting a pointer to <TT>
6788 void *</TT>. This means that any C++ type information associated with
6789  the pointer is lost in the conversion.</P>
6790 <P> The problem with losing type information is that it is needed to
6791  properly support many advanced C++ features--especially multiple
6792  inheritance. For example, suppose you had code like this:</P>
6793 <DIV class="code">
6794 <PRE>
6795 class A {
6796 public:
6797    int x;
6798 };
6799
6800 class B {
6801 public:
6802    int y;
6803 };
6804
6805 class C : public A, public B {
6806 };
6807
6808 int A_function(A *a) {
6809    return a-&gt;x;
6810 }
6811
6812 int B_function(B *b) {
6813    return b-&gt;y;
6814 }
6815 </PRE>
6816 </DIV>
6817 <P> Now, consider the following code that uses <TT>void *</TT>.</P>
6818 <DIV class="code">
6819 <PRE>
6820 C *c = new C();
6821 void *p = (void *) c;
6822 ...
6823 int x = A_function((A *) p);
6824 int y = B_function((B *) p);
6825 </PRE>
6826 </DIV>
6827 <P> In this code, both <TT>A_function()</TT> and <TT>B_function()</TT>
6828  may legally accept an object of type <TT>C *</TT> (via inheritance).
6829  However, one of the functions will always return the wrong result when
6830  used as shown. The reason for this is that even though <TT>p</TT>
6831  points to an object of type <TT>C</TT>, the casting operation doesn't
6832  work like you would expect. Internally, this has to do with the data
6833  representation of <TT>C</TT>. With multiple inheritance, the data from
6834  each base class is stacked together. For example:</P>
6835 <DIV class="diagram">
6836 <PRE>
6837              ------------    &lt;--- (C *),  (A *)
6838             |     A      |
6839             |------------|   &lt;--- (B *)
6840             |     B      |
6841              ------------   
6842 </PRE>
6843 </DIV>
6844 <P> Because of this stacking, a pointer of type <TT>C *</TT> may change
6845  value when it is converted to a <TT>A *</TT> or <TT>B *</TT>. However,
6846  this adjustment does<EM> not</EM> occur if you are converting from a <TT>
6847 void *</TT>.</P>
6848 <P> The use of type tags marks all pointers with the real type of the
6849  underlying object. This extra information is then used by SWIG
6850  generated wrappers to correctly cast pointer values under inheritance
6851  (avoiding the above problem).</P>
6852 <P> Some of the language modules are able to solve the problem by
6853  storing multiple instances of the pointer, for example, <TT>A *</TT>,
6854  in the A proxy class as well as <TT>C *</TT> in the C proxy class. The
6855  correct cast can then be made by choosing the correct <TT>void *</TT>
6856  pointer to use and is guaranteed to work as the cast to a void pointer
6857  and back to the same type does not lose any type information:</P>
6858 <DIV class="code">
6859 <PRE>
6860 C *c = new C();
6861 void *p = (void *) c;
6862 void *pA = (void *) c;
6863 void *pB = (void *) c;
6864 ...
6865 int x = A_function((A *) pA);
6866 int y = B_function((B *) pB);
6867 </PRE>
6868 </DIV>
6869 <P> In practice, the pointer is held as an integral number in the target
6870  language proxy class.</P>
6871 <H2><A name="SWIGPlus_overloaded_methods"></A>6.15 Wrapping Overloaded
6872  Functions and Methods</H2>
6873 <P> In many language modules, SWIG provides partial support for
6874  overloaded functions, methods, and constructors. For example, if you
6875  supply SWIG with overloaded functions like this:</P>
6876 <DIV class="code">
6877 <PRE>
6878 void foo(int x) {
6879    printf(&quot;x is %d\n&quot;, x);
6880 }
6881 void foo(char *x) {
6882    printf(&quot;x is '%s'\n&quot;, x);
6883 }
6884 </PRE>
6885 </DIV>
6886 <P> The function is used in a completely natural way. For example:</P>
6887 <DIV class="targetlang">
6888 <PRE>
6889 &gt;&gt;&gt; foo(3)
6890 x is 3
6891 &gt;&gt;&gt; foo(&quot;hello&quot;)
6892 x is 'hello'
6893 &gt;&gt;&gt;
6894 </PRE>
6895 </DIV>
6896 <P> Overloading works in a similar manner for methods and constructors.
6897  For example if you have this code,</P>
6898 <DIV class="code">
6899 <PRE>
6900 class Foo {
6901 public:
6902      Foo();
6903      Foo(const Foo &amp;);   // Copy constructor
6904      void bar(int x);
6905      void bar(char *s, int y);
6906 };
6907 </PRE>
6908 </DIV>
6909 <P> it might be used like this</P>
6910 <DIV class="targetlang">
6911 <PRE>
6912 &gt;&gt;&gt; f = Foo()          # Create a Foo
6913 &gt;&gt;&gt; f.bar(3)
6914 &gt;&gt;&gt; g = Foo(f)         # Copy Foo
6915 &gt;&gt;&gt; f.bar(&quot;hello&quot;,2)
6916 </PRE>
6917 </DIV>
6918 <H3><A name="SWIGPlus_nn24"></A>6.15.1 Dispatch function generation</H3>
6919 <P> The implementation of overloaded functions and methods is somewhat
6920  complicated due to the dynamic nature of scripting languages. Unlike
6921  C++, which binds overloaded methods at compile time, SWIG must
6922  determine the proper function as a runtime check for scripting language
6923  targets. This check is further complicated by the typeless nature of
6924  certain scripting languages. For instance, in Tcl, all types are simply
6925  strings. Therefore, if you have two overloaded functions like this,</P>
6926 <DIV class="code">
6927 <PRE>
6928 void foo(char *x);
6929 void foo(int x);
6930 </PRE>
6931 </DIV>
6932 <P> the order in which the arguments are checked plays a rather critical
6933  role.</P>
6934 <P> For statically typed languages, SWIG uses the language's method
6935  overloading mechanism. To implement overloading for the scripting
6936  languages, SWIG generates a dispatch function that checks the number of
6937  passed arguments and their types. To create this function, SWIG first
6938  examines all of the overloaded methods and ranks them according to the
6939  following rules:</P>
6940 <OL>
6941 <LI><B>Number of required arguments.</B> Methods are sorted by
6942  increasing number of required arguments.</LI>
6943 <LI>
6944 <P><B>Argument type precedence.</B> All C++ datatypes are assigned a
6945  numeric type precedence value (which is determined by the language
6946  module).</P>
6947 <DIV class="diagram">
6948 <PRE>
6949 Type              Precedence
6950 ----------------  ----------
6951 TYPE *            0     (High)
6952 void *            20
6953 Integers          40
6954 Floating point    60
6955 char              80
6956 Strings           100   (Low)
6957 </PRE>
6958 </DIV>
6959 <P> Using these precedence values, overloaded methods with the same
6960  number of required arguments are sorted in increased order of
6961  precedence values.</P>
6962 </LI>
6963 </OL>
6964 <P> This may sound very confusing, but an example will help. Consider
6965  the following collection of overloaded methods:</P>
6966 <DIV class="code">
6967 <PRE>
6968 void foo(double);
6969 void foo(int);
6970 void foo(Bar *);
6971 void foo();
6972 void foo(int x, int y, int z, int w);
6973 void foo(int x, int y, int z = 3);
6974 void foo(double x, double y);
6975 void foo(double x, Bar *z);
6976 </PRE>
6977 </DIV>
6978 <P> The first rule simply ranks the functions by required argument
6979  count. This would produce the following list:</P>
6980 <DIV class="diagram">
6981 <PRE>
6982 rank
6983 -----
6984 [0]   foo()
6985 [1]   foo(double);
6986 [2]   foo(int);
6987 [3]   foo(Bar *);
6988 [4]   foo(int x, int y, int z = 3);
6989 [5]   foo(double x, double y)
6990 [6]   foo(double x, Bar *z)
6991 [7]   foo(int x, int y, int z, int w);
6992 </PRE>
6993 </DIV>
6994 <P> The second rule, simply refines the ranking by looking at argument
6995  type precedence values.</P>
6996 <DIV class="diagram">
6997 <PRE>
6998 rank
6999 -----
7000 [0]   foo()
7001 [1]   foo(Bar *);
7002 [2]   foo(int);
7003 [3]   foo(double);
7004 [4]   foo(int x, int y, int z = 3);
7005 [5]   foo(double x, Bar *z)
7006 [6]   foo(double x, double y)
7007 [7]   foo(int x, int y, int z, int w);
7008 </PRE>
7009 </DIV>
7010 <P> Finally, to generate the dispatch function, the arguments passed to
7011  an overloaded method are simply checked in the same order as they
7012  appear in this ranking.</P>
7013 <P> If you're still confused, don't worry about it---SWIG is probably
7014  doing the right thing.</P>
7015 <H3><A name="SWIGPlus_nn25"></A>6.15.2 Ambiguity in Overloading</H3>
7016 <P> Regrettably, SWIG is not able to support every possible use of valid
7017  C++ overloading. Consider the following example:</P>
7018 <DIV class="code">
7019 <PRE>
7020 void foo(int x);
7021 void foo(long x);
7022 </PRE>
7023 </DIV>
7024 <P> In C++, this is perfectly legal. However, in a scripting language,
7025  there is generally only one kind of integer object. Therefore, which
7026  one of these functions do you pick? Clearly, there is no way to truly
7027  make a distinction just by looking at the value of the integer itself (<TT>
7028 int</TT> and <TT>long</TT> may even be the same precision). Therefore,
7029  when SWIG encounters this situation, it may generate a warning message
7030  like this for scripting languages:</P>
7031 <DIV class="shell">
7032 <PRE>
7033 example.i:4: Warning(509): Overloaded foo(long) is shadowed by foo(int) at example.i:3.
7034 </PRE>
7035 </DIV>
7036 <P> or for statically typed languages like Java:</P>
7037 <DIV class="shell">
7038 <PRE>
7039 example.i:4: Warning(516): Overloaded method foo(long) ignored. Method foo(int)
7040 at example.i:3 used.
7041 </PRE>
7042 </DIV>
7043 <P> This means that the second overloaded function will be inaccessible
7044  from a scripting interface or the method won't be wrapped at all. This
7045  is done as SWIG does not know how to disambiguate it from an earlier
7046  method.</P>
7047 <P> Ambiguity problems are known to arise in the following situations:</P>
7048 <UL>
7049 <LI>Integer conversions. Datatypes such as <TT>int</TT>, <TT>long</TT>,
7050  and <TT>short</TT> cannot be disambiguated in some languages. Shown
7051  above.</LI>
7052 <LI>Floating point conversion. <TT>float</TT> and <TT>double</TT> can
7053  not be disambiguated in some languages.</LI>
7054 <LI>Pointers and references. For example, <TT>Foo *</TT> and <TT>Foo &amp;</TT>
7055 .</LI>
7056 <LI>Pointers and arrays. For example, <TT>Foo *</TT> and <TT>Foo [4]</TT>
7057 .</LI>
7058 <LI>Pointers and instances. For example, <TT>Foo</TT> and <TT>Foo *</TT>
7059 . Note: SWIG converts all instances to pointers.</LI>
7060 <LI>Qualifiers. For example, <TT>const Foo *</TT> and <TT>Foo *</TT>.</LI>
7061 <LI>Default vs. non default arguments. For example, <TT>foo(int a, int
7062  b)</TT> and <TT>foo(int a, int b = 3)</TT>.</LI>
7063 </UL>
7064 <P> When an ambiguity arises, methods are checked in the same order as
7065  they appear in the interface file. Therefore, earlier methods will
7066  shadow methods that appear later.</P>
7067 <P> When wrapping an overloaded function, there is a chance that you
7068  will get an error message like this:</P>
7069 <DIV class="shell">
7070 <PRE>
7071 example.i:3: Warning(467): Overloaded foo(int) not supported (no type checking
7072 rule for 'int').
7073 </PRE>
7074 </DIV>
7075 <P> This error means that the target language module supports
7076  overloading, but for some reason there is no type-checking rule that
7077  can be used to generate a working dispatch function. The resulting
7078  behavior is then undefined. You should report this as a bug to the <A href="http://www.swig.org/bugs.html">
7079 SWIG bug tracking database</A>.</P>
7080 <P> If you get an error message such as the following,</P>
7081 <DIV class="shell">
7082 <PRE>
7083 foo.i:6. Overloaded declaration ignored.  Spam::foo(double )
7084 foo.i:5. Previous declaration is Spam::foo(int )
7085 foo.i:7. Overloaded declaration ignored.  Spam::foo(Bar *,Spam *,int )
7086 foo.i:5. Previous declaration is Spam::foo(int )
7087 </PRE>
7088 </DIV>
7089 <P> it means that the target language module has not yet implemented
7090  support for overloaded functions and methods. The only way to fix the
7091  problem is to read the next section.</P>
7092 <H3><A name="ambiguity_resolution_renaming"></A>6.15.3 Ambiguity
7093  resolution and renaming</H3>
7094 <P> If an ambiguity in overload resolution occurs or if a module doesn't
7095  allow overloading, there are a few strategies for dealing with the
7096  problem. First, you can tell SWIG to ignore one of the methods. This is
7097  easy---simply use the <TT>%ignore</TT> directive. For example:</P>
7098 <DIV class="code">
7099 <PRE>
7100 %ignore foo(long);
7101
7102 void foo(int);
7103 void foo(long);       // Ignored.  Oh well.
7104 </PRE>
7105 </DIV>
7106 <P> The other alternative is to rename one of the methods. This can be
7107  done using <TT>%rename</TT>. For example:</P>
7108 <DIV class="code">
7109 <PRE>
7110 %rename(&quot;foo_short&quot;) foo(short);
7111 %rename(foo_long) foo(long);
7112
7113 void foo(int);
7114 void foo(short);      // Accessed as foo_short()
7115 void foo(long);       // Accessed as foo_long()
7116 </PRE>
7117 </DIV>
7118 <P> Note that the quotes around the new name are optional, however,
7119  should the new name be a C/C++ keyword they would be essential in order
7120  to avoid a parsing error. The <TT>%ignore</TT> and <TT>%rename</TT>
7121  directives are both rather powerful in their ability to match
7122  declarations. When used in their simple form, they apply to both global
7123  functions and methods. For example:</P>
7124 <DIV class="code">
7125 <PRE>
7126 /* Forward renaming declarations */
7127 %rename(foo_i) foo(int); 
7128 %rename(foo_d) foo(double);
7129 ...
7130 void foo(int);           // Becomes 'foo_i'
7131 void foo(char *c);       // Stays 'foo' (not renamed)
7132
7133 class Spam {
7134 public:
7135    void foo(int);      // Becomes 'foo_i'
7136    void foo(double);   // Becomes 'foo_d'
7137    ...
7138 };
7139 </PRE>
7140 </DIV>
7141 <P> If you only want the renaming to apply to a certain scope, the C++
7142  scope resolution operator (::) can be used. For example:</P>
7143 <DIV class="code">
7144 <PRE>
7145 %rename(foo_i) ::foo(int);      // Only rename foo(int) in the global scope.
7146                                 // (will not rename class members)
7147
7148 %rename(foo_i) Spam::foo(int);  // Only rename foo(int) in class Spam
7149 </PRE>
7150 </DIV>
7151 <P> When a renaming operator is applied to a class as in <TT>
7152 Spam::foo(int)</TT>, it is applied to that class and all derived
7153  classes. This can be used to apply a consistent renaming across an
7154  entire class hierarchy with only a few declarations. For example:</P>
7155 <DIV class="code">
7156 <PRE>
7157 %rename(foo_i) Spam::foo(int);
7158 %rename(foo_d) Spam::foo(double);
7159
7160 class Spam {
7161 public:
7162    virtual void foo(int);      // Renamed to foo_i
7163    virtual void foo(double);   // Renamed to foo_d
7164    ...
7165 };
7166
7167 class Bar : public Spam {
7168 public:
7169    virtual void foo(int);      // Renamed to foo_i
7170    virtual void foo(double);   // Renamed to foo_d
7171 ...
7172 };
7173
7174 class Grok : public Bar {
7175 public:
7176    virtual void foo(int);      // Renamed to foo_i
7177    virtual void foo(double);   // Renamed to foo_d
7178 ...
7179 };
7180 </PRE>
7181 </DIV>
7182 <P> It is also possible to include <TT>%rename</TT> specifications in
7183  the class definition itself. For example:</P>
7184 <DIV class="code">
7185 <PRE>
7186 class Spam {
7187    %rename(foo_i) foo(int);
7188    %rename(foo_d) foo(double);
7189 public:
7190    virtual void foo(int);      // Renamed to foo_i
7191    virtual void foo(double);   // Renamed to foo_d
7192    ...
7193 };
7194
7195 class Bar : public Spam {
7196 public:
7197    virtual void foo(int);      // Renamed to foo_i
7198    virtual void foo(double);   // Renamed to foo_d
7199 ...
7200 };
7201 </PRE>
7202 </DIV>
7203 <P> In this case, the <TT>%rename</TT> directives still get applied
7204  across the entire inheritance hierarchy, but it's no longer necessary
7205  to explicitly specify the class prefix <TT>Spam::</TT>.</P>
7206 <P> A special form of <TT>%rename</TT> can be used to apply a renaming
7207  just to class members (of all classes):</P>
7208 <DIV class="code">
7209 <PRE>
7210 %rename(foo_i) *::foo(int);   // Only rename foo(int) if it appears in a class.
7211 </PRE>
7212 </DIV>
7213 <P> Note: the <TT>*::</TT> syntax is non-standard C++, but the '*' is
7214  meant to be a wildcard that matches any class name (we couldn't think
7215  of a better alternative so if you have a better idea, send email to the
7216  <A href="http://www.swig.org/mail.html">swig-devel mailing list</A>.</P>
7217 <P> Although this discussion has primarily focused on <TT>%rename</TT>
7218  all of the same rules also apply to <TT>%ignore</TT>. For example:</P>
7219 <DIV class="code">
7220 <PRE>
7221 %ignore foo(double);          // Ignore all foo(double)
7222 %ignore Spam::foo;            // Ignore foo in class Spam
7223 %ignore Spam::foo(double);    // Ignore foo(double) in class Spam
7224 %ignore *::foo(double);       // Ignore foo(double) in all classes
7225 </PRE>
7226 </DIV>
7227 <P> When applied to a base class, <TT>%ignore</TT> forces all
7228  definitions in derived classes to disappear. For example, <TT>%ignore
7229  Spam::foo(double)</TT> will eliminate <TT>foo(double)</TT> in <TT>Spam</TT>
7230  and all classes derived from <TT>Spam</TT>.</P>
7231 <P><B> Notes on %rename and %ignore:</B></P>
7232 <UL>
7233 <LI>
7234 <P>Since, the <TT>%rename</TT> declaration is used to declare a renaming
7235  in advance, it can be placed at the start of an interface file. This
7236  makes it possible to apply a consistent name resolution without having
7237  to modify header files. For example:</P>
7238 <DIV class="code">
7239 <PRE>
7240 %module foo
7241
7242 /* Rename these overloaded functions */
7243 %rename(foo_i) foo(int); 
7244 %rename(foo_d) foo(double);
7245
7246 %include &quot;header.h&quot;
7247 </PRE>
7248 </DIV></LI>
7249 <LI>
7250 <P>The scope qualifier (::) can also be used on simple names. For
7251  example:</P>
7252 <DIV class="code">
7253 <PRE>
7254 %rename(bar) ::foo;       // Rename foo to bar in global scope only
7255 %rename(bar) Spam::foo;   // Rename foo to bar in class Spam only
7256 %rename(bar) *::foo;      // Rename foo in classes only
7257 </PRE>
7258 </DIV></LI>
7259 <LI>
7260 <P>Name matching tries to find the most specific match that is defined.
7261  A qualified name such as <TT>Spam::foo</TT> always has higher
7262  precedence than an unqualified name <TT>foo</TT>. <TT>Spam::foo</TT>
7263  has higher precedence than <TT>*::foo</TT> and <TT>*::foo</TT> has
7264  higher precedence than <TT>foo</TT>. A parameterized name has higher
7265  precedence than an unparameterized name within the same scope level.
7266  However, an unparameterized name with a scope qualifier has higher
7267  precedence than a parameterized name in global scope (e.g., a renaming
7268  of <TT>Spam::foo</TT> takes precedence over a renaming of <TT>foo(int)</TT>
7269 ).</P>
7270 </LI>
7271 <LI>
7272 <P> The order in which <TT>%rename</TT> directives are defined does not
7273  matter as long as they appear before the declarations to be renamed.
7274  Thus, there is no difference between saying:</P>
7275 <DIV class="code">
7276 <PRE>
7277 %rename(bar) foo;
7278 %rename(foo_i) Spam::foo(int);
7279 %rename(Foo) Spam::foo;
7280 </PRE>
7281 </DIV>
7282 <P> and this</P>
7283 <DIV class="code">
7284 <PRE>
7285 %rename(Foo) Spam::foo;
7286 %rename(bar) foo;
7287 %rename(foo_i) Spam::foo(int);
7288 </PRE>
7289 </DIV>
7290 <P> (the declarations are not stored in a linked list and order has no
7291  importance). Of course, a repeated <TT>%rename</TT> directive will
7292  change the setting for a previous <TT>%rename</TT> directive if exactly
7293  the same name, scope, and parameters are supplied.</P>
7294 </LI>
7295 <LI>For multiple inheritance where renaming rules are defined for
7296  multiple base classes, the first renaming rule found on a depth-first
7297  traversal of the class hierarchy is used.</LI>
7298 <LI>
7299 <P>The name matching rules strictly follow member qualification rules.
7300  For example, if you have a class like this:</P>
7301 <DIV class="code">
7302 <PRE>
7303 class Spam {
7304 public:
7305    ...
7306    void bar() const;
7307    ...
7308 };
7309 </PRE>
7310 </DIV>
7311 <P> the declaration</P>
7312 <DIV class="code">
7313 <PRE>
7314 %rename(name) Spam::bar();
7315 </PRE>
7316 </DIV>
7317 <P> will not apply as there is no unqualified member <TT>bar()</TT>. The
7318  following will apply as the qualifier matches correctly:</P>
7319 <DIV class="code">
7320 <PRE>
7321 %rename(name) Spam::bar() const;
7322 </PRE>
7323 </DIV>
7324 <P> An often overlooked C++ feature is that classes can define two
7325  different overloaded members that differ only in their qualifiers, like
7326  this:</P>
7327 <DIV class="code">
7328 <PRE>
7329 class Spam {
7330 public:
7331    ...
7332    void bar();         // Unqualified member
7333    void bar() const;   // Qualified member
7334    ...
7335 };
7336 </PRE>
7337 </DIV>
7338 <P> %rename can then be used to target each of the overloaded methods
7339  individually. For example we can give them separate names in the target
7340  language:</P>
7341 <DIV class="code">
7342 <PRE>
7343 %rename(name1) Spam::bar();
7344 %rename(name2) Spam::bar() const;
7345 </PRE>
7346 </DIV>
7347 <P> Similarly, if you merely wanted to ignore one of the declarations,
7348  use <TT>%ignore</TT> with the full qualification. For example, the
7349  following directive would tell SWIG to ignore the <TT>const</TT>
7350  version of <TT>bar()</TT> above:</P>
7351 <DIV class="code">
7352 <PRE>
7353 %ignore Spam::bar() const;   // Ignore bar() const, but leave other bar() alone
7354 </PRE>
7355 </DIV></LI>
7356 <LI>
7357 <P> Currently no resolution is performed in order to match function
7358  parameters. This means function parameter types must match exactly. For
7359  example, namespace qualifiers and typedefs will not work. The following
7360  usage of typedefs demonstrates this:<DIV class="code">
7361 <PRE>
7362 typedef int Integer;
7363
7364 %rename(foo_i) foo(int);
7365
7366 class Spam {
7367 public:
7368    void foo(Integer);  // Stays 'foo' (not renamed)
7369 };
7370 class Ham {
7371 public:
7372    void foo(int);      // Renamed to foo_i
7373 };
7374 </PRE>
7375 </DIV></P>
7376 </LI>
7377 <LI>
7378 <P> The name matching rules also use default arguments for finer control
7379  when wrapping methods that have default arguments. Recall that methods
7380  with default arguments are wrapped as if the equivalent overloaded
7381  methods had been parsed (<A href="#SWIGPlus_default_args">Default
7382  arguments</A> section). Let's consider the following example class:</P>
7383 <DIV class="code">
7384 <PRE>
7385 class Spam {
7386 public:
7387    ...
7388    void bar(int i=-1, double d=0.0);
7389    ...
7390 };
7391 </PRE>
7392 </DIV>
7393 <P> The following <TT>%rename</TT> will match exactly and apply to all
7394  the target language overloaded methods because the declaration with the
7395  default arguments exactly matches the wrapped method:</P>
7396 <DIV class="code">
7397 <PRE>
7398 %rename(newbar) Spam::bar(int i=-1, double d=0.0);
7399 </PRE>
7400 </DIV>
7401 <P> The C++ method can then be called from the target language with the
7402  new name no matter how many arguments are specified, for example: <TT>
7403 newbar(2, 2.0)</TT>, <TT>newbar(2)</TT> or <TT>newbar()</TT>. However,
7404  if the <TT>%rename</TT> does not contain the default arguments, it will
7405  only apply to the single equivalent target language overloaded method.
7406  So if instead we have:</P>
7407 <DIV class="code">
7408 <PRE>
7409 %rename(newbar) Spam::bar(int i, double d);
7410 </PRE>
7411 </DIV>
7412 <P> The C++ method must then be called from the target language with the
7413  new name <TT>newbar(2, 2.0)</TT> when both arguments are supplied or
7414  with the original name as <TT>bar(2)</TT> (one argument) or <TT>bar()</TT>
7415  (no arguments). In fact it is possible to use <TT>%rename</TT> on the
7416  equivalent overloaded methods, to rename all the equivalent overloaded
7417  methods:</P>
7418 <DIV class="code">
7419 <PRE>
7420 %rename(bar_2args)   Spam::bar(int i, double d);
7421 %rename(bar_1arg)    Spam::bar(int i);
7422 %rename(bar_default) Spam::bar();
7423 </PRE>
7424 </DIV>
7425 <P> Similarly, the extra overloaded methods can be selectively ignored
7426  using <TT>%ignore</TT>.</P>
7427 <P><B> Compatibility note:</B> The <TT>%rename</TT> directive introduced
7428  the default argument matching rules in SWIG-1.3.23 at the same time as
7429  the changes to wrapping methods with default arguments was introduced.</P>
7430 </LI>
7431 </UL>
7432 <H3><A name="SWIGPlus_nn27"></A>6.15.4 Comments on overloading</H3>
7433 <P> Support for overloaded methods was first added in SWIG-1.3.14. The
7434  implementation is somewhat unusual when compared to similar tools. For
7435  instance, the order in which declarations appear is largely irrelevant
7436  in SWIG. Furthermore, SWIG does not rely upon trial execution or
7437  exception handling to figure out which method to invoke.</P>
7438 <P> Internally, the overloading mechanism is completely configurable by
7439  the target language module. Therefore, the degree of overloading
7440  support may vary from language to language. As a general rule,
7441  statically typed languages like Java are able to provide more support
7442  than dynamically typed languages like Perl, Python, Ruby, and Tcl.</P>
7443 <H2><A name="SWIGPlus_nn28"></A>6.16 Wrapping overloaded operators</H2>
7444 <P> C++ overloaded operator declarations can be wrapped. For example,
7445  consider a class like this:</P>
7446 <DIV class="code">
7447 <PRE>
7448 class Complex {
7449 private:
7450   double rpart, ipart;
7451 public:
7452   Complex(double r = 0, double i = 0) : rpart(r), ipart(i) { }
7453   Complex(const Complex &amp;c) : rpart(c.rpart), ipart(c.ipart) { }
7454   Complex &amp;operator=(const Complex &amp;c) {
7455     rpart = c.rpart;
7456     ipart = c.ipart;
7457     return *this;
7458   }
7459   Complex operator+(const Complex &amp;c) const {
7460     return Complex(rpart+c.rpart, ipart+c.ipart);
7461   }
7462   Complex operator-(const Complex &amp;c) const {
7463     return Complex(rpart-c.rpart, ipart-c.ipart);
7464   }
7465   Complex operator*(const Complex &amp;c) const {
7466     return Complex(rpart*c.rpart - ipart*c.ipart,
7467                    rpart*c.ipart + c.rpart*ipart);
7468   }
7469   Complex operator-() const {
7470     return Complex(-rpart, -ipart);
7471   }
7472   double re() const { return rpart; }
7473   double im() const { return ipart; }
7474 };
7475 </PRE>
7476 </DIV>
7477 <P> When operator declarations appear, they are handled in<EM> exactly</EM>
7478  the same manner as regular methods. However, the names of these methods
7479  are set to strings like &quot;<TT>operator +</TT>&quot; or &quot;<TT>operator -</TT>&quot;.
7480  The problem with these names is that they are illegal identifiers in
7481  most scripting languages. For instance, you can't just create a method
7482  called &quot;<TT>operator +</TT>&quot; in Python--there won't be any way to call
7483  it.</P>
7484 <P> Some language modules already know how to automatically handle
7485  certain operators (mapping them into operators in the target language).
7486  However, the underlying implementation of this is really managed in a
7487  very general way using the <TT>%rename</TT> directive. For example, in
7488  Python a declaration similar to this is used:</P>
7489 <DIV class="code">
7490 <PRE>
7491 %rename(__add__) Complex::operator+;
7492 </PRE>
7493 </DIV>
7494 <P> This binds the + operator to a method called <TT>__add__</TT> (which
7495  is conveniently the same name used to implement the Python + operator).
7496  Internally, the generated wrapper code for a wrapped operator will look
7497  something like this pseudocode:</P>
7498 <DIV class="code">
7499 <PRE>
7500 _wrap_Complex___add__(args) {
7501    ... get args ...
7502    obj-&gt;operator+(args);
7503    ...
7504 }
7505 </PRE>
7506 </DIV>
7507 <P> When used in the target language, it may now be possible to use the
7508  overloaded operator normally. For example:</P>
7509 <DIV class="targetlang">
7510 <PRE>
7511 &gt;&gt;&gt; a = Complex(3,4)
7512 &gt;&gt;&gt; b = Complex(5,2)
7513 &gt;&gt;&gt; c = a + b           # Invokes __add__ method
7514 </PRE>
7515 </DIV>
7516 <P> It is important to realize that there is nothing magical happening
7517  here. The <TT>%rename</TT> directive really only picks a valid method
7518  name. If you wrote this:</P>
7519 <DIV class="code">
7520 <PRE>
7521 %rename(add) operator+;
7522 </PRE>
7523 </DIV>
7524 <P> The resulting scripting interface might work like this:</P>
7525 <DIV class="targetlang">
7526 <PRE>
7527 a = Complex(3,4)
7528 b = Complex(5,2)
7529 c = a.add(b)      # Call a.operator+(b)
7530 </PRE>
7531 </DIV>
7532 <P> All of the techniques described to deal with overloaded functions
7533  also apply to operators. For example:</P>
7534 <DIV class="code">
7535 <PRE>
7536 %ignore Complex::operator=;             // Ignore = in class Complex
7537 %ignore *::operator=;                   // Ignore = in all classes
7538 %ignore operator=;                      // Ignore = everywhere.
7539
7540 %rename(__sub__) Complex::operator-; 
7541 %rename(__neg__) Complex::operator-();  // Unary - 
7542 </PRE>
7543 </DIV>
7544 <P> The last part of this example illustrates how multiple definitions
7545  of the <TT>operator-</TT> method might be handled.</P>
7546 <P> Handling operators in this manner is mostly straightforward.
7547  However, there are a few subtle issues to keep in mind:</P>
7548 <UL>
7549 <LI>
7550 <P>In C++, it is fairly common to define different versions of the
7551  operators to account for different types. For example, a class might
7552  also include a friend function like this:</P>
7553 <DIV class="code">
7554 <PRE>
7555 class Complex {
7556 public:
7557   friend Complex operator+(Complex &amp;, double);
7558 };
7559 Complex operator+(Complex &amp;, double);
7560 </PRE>
7561 </DIV>
7562 <P> SWIG simply ignores all <TT>friend</TT> declarations. Furthermore,
7563  it doesn't know how to associate the associated <TT>operator+</TT> with
7564  the class (because it's not a member of the class).</P>
7565 <P> It's still possible to make a wrapper for this operator, but you'll
7566  have to handle it like a normal function. For example:</P>
7567 <DIV class="code">
7568 <PRE>
7569 %rename(add_complex_double) operator+(Complex &amp;, double);
7570 </PRE>
7571 </DIV></LI>
7572 <LI>
7573 <P>Certain operators are ignored by default. For instance, <TT>new</TT>
7574  and <TT>delete</TT> operators are ignored as well as conversion
7575  operators.</P>
7576 </LI>
7577 <LI>The semantics of certain C++ operators may not match those in the
7578  target language.</LI>
7579 </UL>
7580 <H2><A name="SWIGPlus_class_extension"></A>6.17 Class extension</H2>
7581 <P> New methods can be added to a class using the <TT>%extend</TT>
7582  directive. This directive is primarily used in conjunction with proxy
7583  classes to add additional functionality to an existing class. For
7584  example :</P>
7585 <DIV class="code">
7586 <PRE>
7587 %module vector
7588 %{
7589 #include &quot;vector.h&quot;
7590 %}
7591
7592 class Vector {
7593 public:
7594         double x,y,z;
7595         Vector();
7596         ~Vector();
7597         ... bunch of C++ methods ...
7598         %extend {
7599                 char *__str__() {
7600                         static char temp[256];
7601                         sprintf(temp,&quot;[ %g, %g, %g ]&quot;, $self-&gt;x,$self-&gt;y,$self-&gt;z);
7602                         return &amp;temp[0];
7603                 }
7604         }
7605 };
7606 </PRE>
7607 </DIV>
7608 <P> This code adds a <TT>__str__</TT> method to our class for producing
7609  a string representation of the object. In Python, such a method would
7610  allow us to print the value of an object using the <TT>print</TT>
7611  command.</P>
7612 <DIV class="targetlang">
7613 <PRE>
7614 &gt;&gt;&gt;
7615 &gt;&gt;&gt; v = Vector();
7616 &gt;&gt;&gt; v.x = 3
7617 &gt;&gt;&gt; v.y = 4
7618 &gt;&gt;&gt; v.z = 0
7619 &gt;&gt;&gt; print(v)
7620 [ 3.0, 4.0, 0.0 ]
7621 &gt;&gt;&gt;
7622
7623 </PRE>
7624 </DIV>
7625 <P> The C++ 'this' pointer is often needed to access member variables,
7626  methods etc. The <TT>$self</TT> special variable should be used
7627  wherever you could use 'this'. The example above demonstrates this for
7628  accessing member variables. Note that the members dereferenced by <TT>
7629 $self</TT> must be public members as the code is ultimately generated
7630  into a global function and so will not have any access to non-public
7631  members. The implicit 'this' pointer that is present in C++ methods is
7632  not present in <TT>%extend</TT> methods. In order to access anything in
7633  the extended class or its base class, an explicit 'this' is required.
7634  The following example shows how one could access base class members:</P>
7635 <DIV class="code">
7636 <PRE>
7637 struct Base {
7638   virtual void method(int v) {
7639     ...
7640   }
7641   int value;
7642 };
7643 struct Derived : Base {
7644 };
7645 %extend Derived {
7646   virtual void method(int v) {
7647     $self-&gt;Base::method(v); // akin to this-&gt;Base::method(v);
7648     $self-&gt;value = v;       // akin to this-&gt;value = v;
7649     ...
7650   }
7651 }
7652 </PRE>
7653 </DIV>
7654 <P> The <TT>%extend</TT> directive follows all of the same conventions
7655  as its use with C structures. Please refer to the <A href="#SWIG_adding_member_functions">
7656 Adding member functions to C structures</A> section for further details.</P>
7657 <P><B> Compatibility note:</B> The <TT>%extend</TT> directive is a new
7658  name for the <TT>%addmethods</TT> directive in SWIG1.1. Since <TT>
7659 %addmethods</TT> could be used to extend a structure with more than just
7660  methods, a more suitable directive name has been chosen.</P>
7661 <H2><A name="SWIGPlus_nn30"></A>6.18 Templates</H2>
7662 <P> Template type names may appear anywhere a type is expected in an
7663  interface file. For example:</P>
7664 <DIV class="code">
7665 <PRE>
7666 void foo(vector&lt;int&gt; *a, int n);
7667 void bar(list&lt;int,100&gt; *x);
7668 </PRE>
7669 </DIV>
7670 <P> There are some restrictions on the use of non-type arguments. Simple
7671  literals are supported, and so are some constant expressions. However,
7672  use of '&lt;' and '&gt;' within a constant expressions currently is not
7673  supported by SWIG ('&lt;=' and '&gt;=' are though). For example:</P>
7674 <DIV class="code">
7675 <PRE>
7676 void bar(list&lt;int,100&gt; *x);                // OK
7677 void bar(list&lt;int,2*50&gt; *x);               // OK
7678 void bar(list&lt;int,(2&gt;1 ? 100 : 50)&gt; *x)    // Not supported
7679 </PRE>
7680 </DIV>
7681 <P> The type system is smart enough to figure out clever games you might
7682  try to play with <TT>typedef</TT>. For instance, consider this code:</P>
7683 <DIV class="code">
7684 <PRE>
7685 typedef int Integer;
7686 void foo(vector&lt;int&gt; *x, vector&lt;Integer&gt; *y);
7687 </PRE>
7688 </DIV>
7689 <P> In this case, <TT>vector&lt;Integer&gt;</TT> is exactly the same type as <TT>
7690 vector&lt;int&gt;</TT>. The wrapper for <TT>foo()</TT> will accept either
7691  variant.</P>
7692 <P> Starting with SWIG-1.3.7, simple C++ template declarations can also
7693  be wrapped. SWIG-1.3.12 greatly expands upon the earlier
7694  implementation. Before discussing this any further, there are a few
7695  things you need to know about template wrapping. First, a bare C++
7696  template does not define any sort of runnable object-code for which
7697  SWIG can normally create a wrapper. Therefore, in order to wrap a
7698  template, you need to give SWIG information about a particular template
7699  instantiation (e.g., <TT>vector&lt;int&gt;</TT>, <TT>array&lt;double&gt;</TT>,
7700  etc.). Second, an instantiation name such as <TT>vector&lt;int&gt;</TT> is
7701  generally not a valid identifier name in most target languages. Thus,
7702  you will need to give the template instantiation a more suitable name
7703  such as <TT>intvector</TT> when creating a wrapper.</P>
7704 <P> To illustrate, consider the following template definition:</P>
7705 <DIV class="code">
7706 <PRE>
7707 template&lt;class T&gt; class List {
7708 private:
7709     T *data;
7710     int nitems;
7711     int maxitems;
7712 public:
7713     List(int max) {
7714       data = new T [max];
7715       nitems = 0;
7716       maxitems = max;
7717     }
7718     ~List() {
7719       delete [] data;
7720     };
7721     void append(T obj) {
7722       if (nitems &lt; maxitems) {
7723         data[nitems++] = obj;
7724       }
7725     }
7726     int length() {
7727       return nitems;
7728     }
7729     T get(int n) {
7730       return data[n];
7731     }
7732 };
7733 </PRE>
7734 </DIV>
7735 <P> By itself, this template declaration is useless--SWIG simply ignores
7736  it because it doesn't know how to generate any code until unless a
7737  definition of <TT>T</TT> is provided.</P>
7738 <P> One way to create wrappers for a specific template instantiation is
7739  to simply provide an expanded version of the class directly like this:</P>
7740 <DIV class="code">
7741 <PRE>
7742 %rename(intList) List&lt;int&gt;;       // Rename to a suitable identifier
7743 class List&lt;int&gt; {
7744 private:
7745     int *data;
7746     int nitems;
7747     int maxitems;
7748 public:
7749     List(int max);
7750     ~List();
7751     void append(int obj);
7752     int length();
7753     int get(int n);
7754 };
7755 </PRE>
7756 </DIV>
7757 <P> The <TT>%rename</TT> directive is needed to give the template class
7758  an appropriate identifier name in the target language (most languages
7759  would not recognize C++ template syntax as a valid class name). The
7760  rest of the code is the same as what would appear in a normal class
7761  definition.</P>
7762 <P> Since manual expansion of templates gets old in a hurry, the <TT>
7763 %template</TT> directive can be used to create instantiations of a
7764  template class. Semantically, <TT>%template</TT> is simply a
7765  shortcut---it expands template code in exactly the same way as shown
7766  above. Here are some examples:</P>
7767 <DIV class="code">
7768 <PRE>
7769 /* Instantiate a few different versions of the template */
7770 %template(intList) List&lt;int&gt;;
7771 %template(doubleList) List&lt;double&gt;;
7772 </PRE>
7773 </DIV>
7774 <P> The argument to <TT>%template()</TT> is the name of the
7775  instantiation in the target language. The name you choose should not
7776  conflict with any other declarations in the interface file with one
7777  exception---it is okay for the template name to match that of a typedef
7778  declaration. For example:</P>
7779 <DIV class="code">
7780 <PRE>
7781 %template(intList) List&lt;int&gt;;
7782 ...
7783 typedef List&lt;int&gt; intList;    // OK
7784 </PRE>
7785 </DIV>
7786 <P> SWIG can also generate wrappers for function templates using a
7787  similar technique. For example:</P>
7788 <DIV class="code">
7789 <PRE>
7790 // Function template
7791 template&lt;class T&gt; T max(T a, T b) { return a &gt; b ? a : b; }
7792
7793 // Make some different versions of this function
7794 %template(maxint) max&lt;int&gt;;
7795 %template(maxdouble) max&lt;double&gt;;
7796 </PRE>
7797 </DIV>
7798 <P> In this case, <TT>maxint</TT> and <TT>maxdouble</TT> become unique
7799  names for specific instantiations of the function.</P>
7800 <P> The number of arguments supplied to <TT>%template</TT> should match
7801  that in the original template definition. Template default arguments
7802  are supported. For example:</P>
7803 <DIV class="code">
7804 <PRE>
7805 template vector&lt;typename T, int max=100&gt; class vector {
7806 ...
7807 };
7808
7809 %template(intvec) vector&lt;int&gt;;           // OK
7810 %template(vec1000) vector&lt;int,1000&gt;;     // OK
7811 </PRE>
7812 </DIV>
7813 <P> The <TT>%template</TT> directive should not be used to wrap the same
7814  template instantiation more than once in the same scope. This will
7815  generate an error. For example:</P>
7816 <DIV class="code">
7817 <PRE>
7818 %template(intList) List&lt;int&gt;;
7819 %template(Listint) List&lt;int&gt;;    // Error.   Template already wrapped.
7820 </PRE>
7821 </DIV>
7822 <P> This error is caused because the template expansion results in two
7823  identical classes with the same name. This generates a symbol table
7824  conflict. Besides, it probably more efficient to only wrap a specific
7825  instantiation only once in order to reduce the potential for code
7826  bloat.</P>
7827 <P> Since the type system knows how to handle <TT>typedef</TT>, it is
7828  generally not necessary to instantiate different versions of a template
7829  for typenames that are equivalent. For instance, consider this code:</P>
7830 <DIV class="code">
7831 <PRE>
7832 %template(intList) vector&lt;int&gt;;
7833 typedef int Integer;
7834 ...
7835 void foo(vector&lt;Integer&gt; *x);
7836 </PRE>
7837 </DIV>
7838 <P> In this case, <TT>vector&lt;Integer&gt;</TT> is exactly the same type as <TT>
7839 vector&lt;int&gt;</TT>. Any use of <TT>Vector&lt;Integer&gt;</TT> is mapped back to
7840  the instantiation of <TT>vector&lt;int&gt;</TT> created earlier. Therefore,
7841  it is not necessary to instantiate a new class for the type <TT>Integer</TT>
7842  (doing so is redundant and will simply result in code bloat).</P>
7843 <P> When a template is instantiated using <TT>%template</TT>,
7844  information about that class is saved by SWIG and used elsewhere in the
7845  program. For example, if you wrote code like this,</P>
7846 <DIV class="code">
7847 <PRE>
7848 ...
7849 %template(intList) List&lt;int&gt;;
7850 ...
7851 class UltraList : public List&lt;int&gt; {
7852    ...
7853 };
7854 </PRE>
7855 </DIV>
7856 <P> then SWIG knows that <TT>List&lt;int&gt;</TT> was already wrapped as a
7857  class called <TT>intList</TT> and arranges to handle the inheritance
7858  correctly. If, on the other hand, nothing is known about <TT>List&lt;int&gt;</TT>
7859 , you will get a warning message similar to this:</P>
7860 <DIV class="shell">
7861 <PRE>
7862 example.h:42. Nothing known about class 'List&lt;int &gt;' (ignored). 
7863 example.h:42. Maybe you forgot to instantiate 'List&lt;int &gt;' using %template. 
7864 </PRE>
7865 </DIV>
7866 <P> If a template class inherits from another template class, you need
7867  to make sure that base classes are instantiated before derived classes.
7868  For example:</P>
7869 <DIV class="code">
7870 <PRE>
7871 template&lt;class T&gt; class Foo {
7872 ...
7873 };
7874
7875 template&lt;class T&gt; class Bar : public Foo&lt;T&gt; {
7876 ...
7877 };
7878
7879 // Instantiate base classes first 
7880 %template(intFoo) Foo&lt;int&gt;;
7881 %template(doubleFoo) Foo&lt;double&gt;;
7882
7883 // Now instantiate derived classes
7884 %template(intBar) Bar&lt;int&gt;;
7885 %template(doubleBar) Bar&lt;double&gt;;
7886 </PRE>
7887 </DIV>
7888 <P> The order is important since SWIG uses the instantiation names to
7889  properly set up the inheritance hierarchy in the resulting wrapper code
7890  (and base classes need to be wrapped before derived classes). Don't
7891  worry--if you get the order wrong, SWIG should generate a warning
7892  message.</P>
7893 <P> Occasionally, you may need to tell SWIG about base classes that are
7894  defined by templates, but which aren't supposed to be wrapped. Since
7895  SWIG is not able to automatically instantiate templates for this
7896  purpose, you must do it manually. To do this, simply use <TT>%template</TT>
7897  with no name. For example:</P>
7898 <DIV class="code">
7899 <PRE>
7900 // Instantiate traits&lt;double,double&gt;, but don't wrap it.
7901 %template() traits&lt;double,double&gt;;
7902 </PRE>
7903 </DIV>
7904 <P> If you have to instantiate a lot of different classes for many
7905  different types, you might consider writing a SWIG macro. For example:</P>
7906 <DIV class="code">
7907 <PRE>
7908 %define TEMPLATE_WRAP(prefix, T...) 
7909 %template(prefix ## Foo) Foo&lt;T &gt;;
7910 %template(prefix ## Bar) Bar&lt;T &gt;;
7911 ...
7912 %enddef
7913
7914 TEMPLATE_WRAP(int, int)
7915 TEMPLATE_WRAP(double, double)
7916 TEMPLATE_WRAP(String, char *)
7917 TEMPLATE_WRAP(PairStringInt, std::pair&lt;string, int&gt;)
7918 ...
7919 </PRE>
7920 </DIV>
7921 <P> Note the use of a vararg macro for the type T. If this wasn't used,
7922  the comma in the templated type in the last example would not be
7923  possible.</P>
7924 <P> The SWIG template mechanism<EM> does</EM> support specialization.
7925  For instance, if you define a class like this,</P>
7926 <DIV class="code">
7927 <PRE>
7928 template&lt;&gt; class List&lt;int&gt; {
7929 private:
7930     int *data;
7931     int nitems;
7932     int maxitems;
7933 public:
7934     List(int max);
7935     ~List();
7936     void append(int obj);
7937     int length();
7938     int get(int n);
7939 };
7940 </PRE>
7941 </DIV>
7942 <P> then SWIG will use this code whenever the user expands <TT>List&lt;int&gt;</TT>
7943 . In practice, this may have very little effect on the underlying
7944  wrapper code since specialization is often used to provide slightly
7945  modified method bodies (which are ignored by SWIG). However, special
7946  SWIG directives such as <TT>%typemap</TT>, <TT>%extend</TT>, and so
7947  forth can be attached to a specialization to provide customization for
7948  specific types.</P>
7949 <P> Partial template specialization is partially supported by SWIG. For
7950  example, this code defines a template that is applied when the template
7951  argument is a pointer.</P>
7952 <DIV class="code">
7953 <PRE>
7954 template&lt;class T&gt; class List&lt;T*&gt; {
7955 private:
7956     T *data;
7957     int nitems;
7958     int maxitems;
7959 public:
7960     List(int max);
7961     ~List();
7962     void append(int obj);
7963     int length();
7964     T get(int n);
7965 };
7966 </PRE>
7967 </DIV>
7968 <P> SWIG should be able to handle most simple uses of partial
7969  specialization. However, it may fail to match templates properly in
7970  more complicated cases. For example, if you have this code,</P>
7971 <DIV class="code">
7972 <PRE>
7973 template&lt;class T1, class T2&gt; class Foo&lt;T1, T2 *&gt; { };
7974 </PRE>
7975 </DIV>
7976 <P> SWIG isn't able to match it properly for instantiations like <TT>
7977 Foo&lt;int *, int *&gt;</TT>. This problem is not due to parsing, but due to
7978  the fact that SWIG does not currently implement all of the C++ argument
7979  deduction rules.</P>
7980 <P> Member function templates are supported. The underlying principle is
7981  the same as for normal templates--SWIG can't create a wrapper unless
7982  you provide more information about types. For example, a class with a
7983  member template might look like this:</P>
7984 <DIV class="code">
7985 <PRE>
7986 class Foo {
7987 public:
7988      template&lt;class T&gt; void bar(T x, T y) { ... };
7989      ...
7990 };
7991 </PRE>
7992 </DIV>
7993 <P> To expand the template, simply use <TT>%template</TT> inside the
7994  class.</P>
7995 <DIV class="code">
7996 <PRE>
7997 class Foo {
7998 public:
7999      template&lt;class T&gt; void bar(T x, T y) { ... };
8000      ...
8001      %template(barint)    bar&lt;int&gt;;
8002      %template(bardouble) bar&lt;double&gt;;
8003 };
8004 </PRE>
8005 </DIV>
8006 <P> Or, if you want to leave the original class definition alone, just
8007  do this:</P>
8008 <DIV class="code">
8009 <PRE>
8010 class Foo {
8011 public:
8012      template&lt;class T&gt; void bar(T x, T y) { ... };
8013      ...
8014 };
8015 ...
8016 %extend Foo {
8017      %template(barint)    bar&lt;int&gt;;
8018      %template(bardouble) bar&lt;double&gt;;
8019 };
8020 </PRE>
8021 </DIV>
8022 <P> or simply</P>
8023 <DIV class="code">
8024 <PRE>
8025 class Foo {
8026 public:
8027      template&lt;class T&gt; void bar(T x, T y) { ... };
8028      ...
8029 };
8030 ...
8031
8032 %template(bari) Foo::bar&lt;int&gt;;
8033 %template(bard) Foo::bar&lt;double&gt;;
8034 </PRE>
8035 </DIV>
8036 <P> In this case, the <TT>%extend</TT> directive is not needed, and <TT>
8037 %template</TT> does the exactly same job, i.e., it adds two new methods
8038  to the Foo class.</P>
8039 <P> Note: because of the way that templates are handled, the <TT>
8040 %template</TT> directive must always appear<EM> after</EM> the
8041  definition of the template to be expanded.</P>
8042 <P> Now, if your target language supports overloading, you can even try</P>
8043 <DIV class="code">
8044 <PRE>
8045 %template(bar) Foo::bar&lt;int&gt;;
8046 %template(bar) Foo::bar&lt;double&gt;;
8047 </PRE>
8048 </DIV>
8049 <P> and since the two new wrapped methods have the same name 'bar', they
8050  will be overloaded, and when called, the correct method will be
8051  dispatched depending on the argument type.</P>
8052 <P> When used with members, the <TT>%template</TT> directive may be
8053  placed in another template class. Here is a slightly perverse example:</P>
8054 <DIV class="code">
8055 <PRE>
8056 // A template
8057 template&lt;class T&gt; class Foo {
8058 public:
8059      // A member template
8060      template&lt;class S&gt; T bar(S x, S y) { ... };
8061      ...
8062 };
8063
8064 // Expand a few member templates
8065 %extend Foo {
8066   %template(bari) bar&lt;int&gt;;
8067   %template(bard) bar&lt;double&gt;;
8068 }
8069
8070 // Create some wrappers for the template
8071 %template(Fooi) Foo&lt;int&gt;;
8072 %template(Food) Foo&lt;double&gt;;
8073 </PRE>
8074 </DIV>
8075 <P> Miraculously, you will find that each expansion of <TT>Foo</TT> has
8076  member functions <TT>bari()</TT> and <TT>bard()</TT> added.</P>
8077 <P> A common use of member templates is to define constructors for
8078  copies and conversions. For example:</P>
8079 <DIV class="code">
8080 <PRE>
8081 template&lt;class T1, class T2&gt; struct pair {
8082    T1 first;
8083    T2 second;
8084    pair() : first(T1()), second(T2()) { }
8085    pair(const T1 &amp;x, const T2 &amp;y) : first(x), second(y) { }
8086    template&lt;class U1, class U2&gt; pair(const pair&lt;U1,U2&gt; &amp;x) 
8087                                         : first(x.first),second(x.second) { }
8088 };
8089 </PRE>
8090 </DIV>
8091 <P> This declaration is perfectly acceptable to SWIG, but the
8092  constructor template will be ignored unless you explicitly expand it.
8093  To do that, you could expand a few versions of the constructor in the
8094  template class itself. For example:</P>
8095 <DIV class="code">
8096 <PRE>
8097 %extend pair {
8098    %template(pair) pair&lt;T1,T2&gt;;        // Generate default copy constructor
8099 };
8100 </PRE>
8101 </DIV>
8102 <P> When using <TT>%extend</TT> in this manner, notice how you can still
8103  use the template parameters in the original template definition.</P>
8104 <P> Alternatively, you could expand the constructor template in selected
8105  instantiations. For example:</P>
8106 <DIV class="code">
8107 <PRE>
8108 // Instantiate a few versions
8109 %template(pairii) pair&lt;int,int&gt;;
8110 %template(pairdd) pair&lt;double,double&gt;;
8111
8112 // Create a default constructor only 
8113 %extend pair&lt;int,int&gt; {
8114    %template(paird) pair&lt;int,int&gt;;         // Default constructor
8115 };
8116
8117 // Create default and conversion constructors 
8118 %extend pair&lt;double,double&gt; {
8119    %template(paird) pair&lt;double,dobule&gt;;   // Default constructor
8120    %template(pairc) pair&lt;int,int&gt;;         // Conversion constructor
8121 };
8122 </PRE>
8123 </DIV>
8124 <P>And if your target language supports overloading, then you can try
8125  instead:</P>
8126 <DIV class="code">
8127 <PRE>
8128 // Create default and conversion constructors 
8129 %extend pair&lt;double,double&gt; {
8130    %template(pair) pair&lt;double,dobule&gt;;   // Default constructor
8131    %template(pair) pair&lt;int,int&gt;;         // Conversion constructor
8132 };
8133 </PRE>
8134 </DIV>
8135 <P> In this case, the default and conversion constructors have the same
8136  name. Hence, Swig will overload them and define an unique visible
8137  constructor, that will dispatch the proper call depending on the
8138  argument type.</P>
8139 <P> If all of this isn't quite enough and you really want to make
8140  someone's head explode, SWIG directives such as <TT>%rename</TT>, <TT>
8141 %extend</TT>, and <TT>%typemap</TT> can be included directly in template
8142  definitions. For example:</P>
8143 <DIV class="code">
8144 <PRE>
8145 // File : list.h
8146 template&lt;class T&gt; class List {
8147    ...
8148 public:
8149     %rename(__getitem__) get(int);
8150     List(int max);
8151     ~List();
8152     ...
8153     T get(int index);
8154     %extend {
8155         char *__str__() {
8156             /* Make a string representation */
8157             ...
8158         }
8159     }
8160 };
8161 </PRE>
8162 </DIV>
8163 <P> In this example, the extra SWIG directives are propagated to<EM>
8164  every</EM> template instantiation.</P>
8165 <P> It is also possible to separate these declarations from the template
8166  class. For example:</P>
8167 <DIV class="code">
8168 <PRE>
8169 %rename(__getitem__) List::get;
8170 %extend List {
8171     char *__str__() {
8172         /* Make a string representation */
8173         ...
8174     }
8175     /* Make a copy */
8176     T *__copy__() {
8177        return new List&lt;T&gt;(*$self);
8178     }
8179 };
8180
8181 ...
8182 template&lt;class T&gt; class List {
8183     ...
8184     public:
8185     List() { };
8186     T get(int index);
8187     ...
8188 };
8189 </PRE>
8190 </DIV>
8191 <P> When <TT>%extend</TT> is decoupled from the class definition, it is
8192  legal to use the same template parameters as provided in the class
8193  definition. These are replaced when the template is expanded. In
8194  addition, the <TT>%extend</TT> directive can be used to add additional
8195  methods to a specific instantiation. For example:</P>
8196 <DIV class="code">
8197 <PRE>
8198 %template(intList) List&lt;int&gt;;
8199
8200 %extend List&lt;int&gt; {
8201     void blah() {
8202           printf(&quot;Hey, I'm an List&lt;int&gt;!\n&quot;);
8203     }
8204 };
8205 </PRE>
8206 </DIV>
8207 <P> SWIG even supports overloaded templated functions. As usual the <TT>
8208 %template</TT> directive is used to wrap templated functions. For
8209  example:</P>
8210 <DIV class="code">
8211 <PRE>
8212 template&lt;class T&gt; void foo(T x) { };
8213 template&lt;class T&gt; void foo(T x, T y) { };
8214
8215 %template(foo) foo&lt;int&gt;;
8216 </PRE>
8217 </DIV>
8218 <P> This will generate two overloaded wrapper methods, the first will
8219  take a single integer as an argument and the second will take two
8220  integer arguments.</P>
8221 <P> Needless to say, SWIG's template support provides plenty of
8222  opportunities to break the universe. That said, an important final
8223  point is that<B> SWIG does not perform extensive error checking of
8224  templates!</B> Specifically, SWIG does not perform type checking nor
8225  does it check to see if the actual contents of the template declaration
8226  make any sense. Since the C++ compiler will hopefully check this when
8227  it compiles the resulting wrapper file, there is no practical reason
8228  for SWIG to duplicate this functionality (besides, none of the SWIG
8229  developers are masochistic enough to want to implement this right now).</P>
8230 <P><B> Compatibility Note</B>: The first implementation of template
8231  support relied heavily on macro expansion in the preprocessor.
8232  Templates have been more tightly integrated into the parser and type
8233  system in SWIG-1.3.12 and the preprocessor is no longer used. Code that
8234  relied on preprocessing features in template expansion will no longer
8235  work. However, SWIG still allows the # operator to be used to generate
8236  a string from a template argument.</P>
8237 <P><B> Compatibility Note</B>: In earlier versions of SWIG, the <TT>
8238 %template</TT> directive introduced a new class name. This name could
8239  then be used with other directives. For example:</P>
8240 <DIV class="code">
8241 <PRE>
8242 %template(vectori) vector&lt;int&gt;;
8243 %extend vectori {
8244     void somemethod() { }
8245 };
8246 </PRE>
8247 </DIV>
8248 <P> This behavior is no longer supported. Instead, you should use the
8249  original template name as the class name. For example:</P>
8250 <DIV class="code">
8251 <PRE>
8252 %template(vectori) vector&lt;int&gt;;
8253 %extend vector&lt;int&gt; {
8254     void somemethod() { }
8255 };
8256 </PRE>
8257 </DIV>
8258 <P> Similar changes apply to typemaps and other customization features.</P>
8259 <H2><A name="SWIGPlus_nn31"></A>6.19 Namespaces</H2>
8260 <P> Support for C++ namespaces is a relatively late addition to SWIG,
8261  first appearing in SWIG-1.3.12. Before describing the implementation,
8262  it is worth noting that the semantics of C++ namespaces is extremely
8263  non-trivial--especially with regard to the C++ type system and class
8264  machinery. At a most basic level, namespaces are sometimes used to
8265  encapsulate common functionality. For example:</P>
8266 <DIV class="code">
8267 <PRE>
8268 namespace math {
8269    double sin(double);
8270    double cos(double);
8271
8272    class Complex {
8273       double im,re;
8274    public:
8275       ...
8276    };
8277    ...
8278 };
8279 </PRE>
8280 </DIV>
8281 <P> Members of the namespace are accessed in C++ by prepending the
8282  namespace prefix to names. For example:</P>
8283 <DIV class="code">
8284 <PRE>
8285 double x = math::sin(1.0);
8286 double magnitude(math::Complex *c);
8287 math::Complex c;
8288 ...
8289 </PRE>
8290 </DIV>
8291 <P> At this level, namespaces are relatively easy to manage. However,
8292  things start to get very ugly when you throw in the other ways a
8293  namespace can be used. For example, selective symbols can be exported
8294  from a namespace with <TT>using</TT>.</P>
8295 <DIV class="code">
8296 <PRE>
8297 using math::Complex;
8298 double magnitude(Complex *c);       // Namespace prefix stripped
8299 </PRE>
8300 </DIV>
8301 <P> Similarly, the contents of an entire namespace can be made available
8302  like this:</P>
8303 <DIV class="code">
8304 <PRE>
8305 using namespace math;
8306 double x = sin(1.0);
8307 double magnitude(Complex *c);
8308 </PRE>
8309 </DIV>
8310 <P> Alternatively, a namespace can be aliased:</P>
8311 <DIV class="code">
8312 <PRE>
8313 namespace M = math;
8314 double x = M::sin(1.0);
8315 double magnitude(M::Complex *c);
8316 </PRE>
8317 </DIV>
8318 <P> Using combinations of these features, it is possible to write
8319  head-exploding code like this:</P>
8320 <DIV class="code">
8321 <PRE>
8322 namespace A {
8323   class Foo {
8324   };
8325 }
8326
8327 namespace B {
8328    namespace C {
8329       using namespace A;
8330    }
8331    typedef C::Foo FooClass;
8332 }
8333
8334 namespace BIGB = B;
8335
8336 namespace D {
8337    using BIGB::FooClass;
8338    class Bar : public FooClass {
8339    }
8340 };
8341
8342 class Spam : public D::Bar {
8343 };
8344
8345 void evil(A::Foo *a, B::FooClass *b, B::C::Foo *c, BIGB::FooClass *d,
8346           BIGB::C::Foo *e, D::FooClass *f);
8347
8348 </PRE>
8349 </DIV>
8350 <P> Given the possibility for such perversion, it's hard to imagine how
8351  every C++ programmer might want such code wrapped into the target
8352  language. Clearly this code defines three different classes. However,
8353  one of those classes is accessible under at least six different names!</P>
8354 <P> SWIG fully supports C++ namespaces in its internal type system and
8355  class handling code. If you feed SWIG the above code, it will be parsed
8356  correctly, it will generate compilable wrapper code, and it will
8357  produce a working scripting language module. However, the default
8358  wrapping behavior is to flatten namespaces in the target language. This
8359  means that the contents of all namespaces are merged together in the
8360  resulting scripting language module. For example, if you have code like
8361  this,</P>
8362 <DIV class="code">
8363 <PRE>
8364 %module foo
8365 namespace foo {
8366    void bar(int);
8367    void spam();
8368 }
8369
8370 namespace bar {
8371    void blah();
8372 }
8373
8374 </PRE>
8375 </DIV>
8376 <P> then SWIG simply creates three wrapper functions <TT>bar()</TT>, <TT>
8377 spam()</TT>, and <TT>blah()</TT> in the target language. SWIG does not
8378  prepend the names with a namespace prefix nor are the functions
8379  packaged in any kind of nested scope.</P>
8380 <P> There is some rationale for taking this approach. Since C++
8381  namespaces are often used to define modules in C++, there is a natural
8382  correlation between the likely contents of a SWIG module and the
8383  contents of a namespace. For instance, it would not be unreasonable to
8384  assume that a programmer might make a separate extension module for
8385  each C++ namespace. In this case, it would be redundant to prepend
8386  everything with an additional namespace prefix when the module itself
8387  already serves as a namespace in the target language. Or put another
8388  way, if you want SWIG to keep namespaces separate, simply wrap each
8389  namespace with its own SWIG interface.</P>
8390 <P> Because namespaces are flattened, it is possible for symbols defined
8391  in different namespaces to generate a name conflict in the target
8392  language. For example:</P>
8393 <DIV class="code">
8394 <PRE>
8395 namespace A {
8396    void foo(int);
8397 }
8398 namespace B {
8399    void foo(double);
8400 }
8401 </PRE>
8402 </DIV>
8403 <P> When this conflict occurs, you will get an error message that
8404  resembles this:</P>
8405 <DIV class="shell">
8406 <PRE>
8407 example.i:26. Error. 'foo' is multiply defined in the generated module.
8408 example.i:23. Previous declaration of 'foo'
8409 </PRE>
8410 </DIV>
8411 <P> To resolve this error, simply use <TT>%rename</TT> to disambiguate
8412  the declarations. For example:</P>
8413 <DIV class="code">
8414 <PRE>
8415 %rename(B_foo) B::foo;
8416 ...
8417 namespace A {
8418    void foo(int);
8419 }
8420 namespace B {
8421    void foo(double);     // Gets renamed to B_foo
8422 }
8423 </PRE>
8424 </DIV>
8425 <P> Similarly, <TT>%ignore</TT> can be used to ignore declarations.</P>
8426 <P> <TT>using</TT> declarations do not have any effect on the generated
8427  wrapper code. They are ignored by SWIG language modules and they do not
8428  result in any code. However, these declarations<EM> are</EM> used by
8429  the internal type system to track type-names. Therefore, if you have
8430  code like this:</P>
8431 <DIV class="code">
8432 <PRE>
8433 namespace A {
8434    typedef int Integer;
8435 }
8436 using namespace A;
8437 void foo(Integer x);
8438 </PRE>
8439 </DIV>
8440 <P> SWIG knows that <TT>Integer</TT> is the same as <TT>A::Integer</TT>
8441  which is the same as <TT>int</TT>.</P>
8442 <P> Namespaces may be combined with templates. If necessary, the <TT>
8443 %template</TT> directive can be used to expand a template defined in a
8444  different namespace. For example:</P>
8445 <DIV class="code">
8446 <PRE>
8447 namespace foo {
8448     template&lt;typename T&gt; T max(T a, T b) { return a &gt; b ? a : b; }
8449 }
8450
8451 using foo::max;
8452
8453 %template(maxint)   max&lt;int&gt;;           // Okay.
8454 %template(maxfloat) foo::max&lt;float&gt;;    // Okay (qualified name).
8455
8456 namespace bar {
8457     using namespace foo;
8458     %template(maxdouble)  max&lt;double&gt;;    // Okay.
8459 }
8460 </PRE>
8461 </DIV>
8462 <P> The combination of namespaces and other SWIG directives may
8463  introduce subtle scope-related problems. The key thing to keep in mind
8464  is that all SWIG generated wrappers are produced in the<EM> global</EM>
8465  namespace. Symbols from other namespaces are always accessed using
8466  fully qualified names---names are never imported into the global space
8467  unless the interface happens to do so with a <TT>using</TT>
8468  declaration. In almost all cases, SWIG adjusts typenames and symbols to
8469  be fully qualified. However, this is not done in code fragments such as
8470  function bodies, typemaps, exception handlers, and so forth. For
8471  example, consider the following:</P>
8472 <DIV class="code">
8473 <PRE>
8474 namespace foo {
8475     typedef int Integer;
8476     class bar {
8477     public:
8478        ...
8479     };
8480 }
8481
8482 %extend foo::bar {
8483    Integer add(Integer x, Integer y) {
8484        Integer r = x + y;        // Error. Integer not defined in this scope
8485        return r;
8486    }
8487 };
8488 </PRE>
8489 </DIV>
8490 <P> In this case, SWIG correctly resolves the added method parameters
8491  and return type to <TT>foo::Integer</TT>. However, since function
8492  bodies aren't parsed and such code is emitted in the global namespace,
8493  this code produces a compiler error about <TT>Integer</TT>. To fix the
8494  problem, make sure you use fully qualified names. For example:</P>
8495 <DIV class="code">
8496 <PRE>
8497 %extend foo::bar {
8498    Integer add(Integer x, Integer y) {
8499        foo::Integer r = x + y;        // Ok.
8500        return r;
8501    }
8502 };
8503 </PRE>
8504 </DIV>
8505 <P><B> Note:</B> SWIG does<EM> not</EM> propagate <TT>using</TT>
8506  declarations to the resulting wrapper code. If these declarations
8507  appear in an interface, they should<EM> also</EM> appear in any header
8508  files that might have been included in a <TT>%{ ... %}</TT> section. In
8509  other words, don't insert extra <TT>using</TT> declarations into a SWIG
8510  interface unless they also appear in the underlying C++ code.</P>
8511 <P><B> Note:</B> Code inclusion directives such as <TT>%{ ... %}</TT> or
8512  <TT>%inline %{ ... %}</TT> should not be placed inside a namespace
8513  declaration. The code emitted by these directives will not be enclosed
8514  in a namespace and you may get very strange results. If you need to use
8515  namespaces with these directives, consider the following:</P>
8516 <DIV class="code">
8517 <PRE>
8518 // Good version
8519 %inline %{
8520 namespace foo {
8521      void bar(int) { ... }
8522      ...
8523 }
8524 %}
8525
8526 // Bad version.  Emitted code not placed in namespace.
8527 namespace foo {
8528 %inline %{
8529      void bar(int) { ... }   /* I'm bad */
8530      ...
8531 %}
8532 }
8533 </PRE>
8534 </DIV>
8535 <P><B> Note:</B> When the <TT>%extend</TT> directive is used inside a
8536  namespace, the namespace name is included in the generated functions.
8537  For example, if you have code like this,</P>
8538 <DIV class="code">
8539 <PRE>
8540 namespace foo {
8541    class bar {
8542    public:
8543         %extend {
8544            int blah(int x);
8545         };
8546    };
8547 }
8548 </PRE>
8549 </DIV>
8550 <P> the added method <TT>blah()</TT> is mapped to a function <TT>int
8551  foo_bar_blah(foo::bar *self, int x)</TT>. This function resides in the
8552  global namespace.</P>
8553 <P><B> Note:</B> Although namespaces are flattened in the target
8554  language, the SWIG generated wrapper code observes the same namespace
8555  conventions as used in the input file. Thus, if there are no symbol
8556  conflicts in the input, there will be no conflicts in the generated
8557  code.</P>
8558 <P><B> Note:</B> In the same way that no resolution is performed on
8559  parameters, a conversion operator name must match exactly to how it is
8560  defined. Do not change the qualification of the operator. For example,
8561  suppose you had an interface like this:</P>
8562 <DIV class="code">
8563 <PRE>
8564 namespace foo {
8565    class bar;
8566    class spam {
8567    public:
8568         ...
8569         operator bar();      // Conversion of spam -&gt; bar
8570         ...
8571    };
8572 }
8573 </PRE>
8574 </DIV>
8575 <P> The following is how the feature is expected to be written for a
8576  successful match:</P>
8577 <DIV class="code">
8578 <PRE>
8579 %rename(tofoo) foo::spam::operator bar();
8580 </PRE>
8581 </DIV>
8582 <P> The following does not work as no namespace resolution is performed
8583  in the matching of conversion operator names:</P>
8584 <DIV class="code">
8585 <PRE>
8586 %rename(tofoo) foo::spam::operator <B>foo::</B>bar();
8587 </PRE>
8588 </DIV>
8589 <P> Note, however, that if the operator is defined using a qualifier in
8590  its name, then the feature must use it too...</P>
8591 <DIV class="code">
8592 <PRE>
8593 %rename(tofoo) foo::spam::operator bar();      // will not match
8594 %rename(tofoo) foo::spam::operator foo::bar(); // will match
8595 namespace foo {
8596    class bar;
8597    class spam {
8598    public:
8599         ...
8600         operator foo::bar();
8601         ...
8602    };
8603 }
8604 </PRE>
8605 </DIV>
8606 <P><B> Compatibility Note:</B> Versions of SWIG prior to 1.3.32 were
8607  inconsistent in this approach. A fully qualified name was usually
8608  required, but would not work in some situations.</P>
8609 <P><B> Note:</B> The flattening of namespaces is only intended to serve
8610  as a basic namespace implementation. None of the target language
8611  modules are currently programmed with any namespace awareness. In the
8612  future, language modules may or may not provide more advanced namespace
8613  support.</P>
8614 <H2><A name="SWIGPlus_renaming_templated_types_namespaces"></A>6.20
8615  Renaming templated types in namespaces</H2>
8616 <P> As has been mentioned, when %rename includes parameters, the
8617  parameter types must match exactly (no typedef or namespace resolution
8618  is performed). SWIG treats templated types slightly differently and has
8619  an additional matching rule so unlike non-templated types, an exact
8620  match is not always required. If the fully qualified templated type is
8621  specified, it will have a higher precedence over the generic template
8622  type. In the example below, the generic template type is used to rename
8623  to <TT>bbb</TT> and the fully qualified type is used to rename to <TT>
8624 ccc</TT>.</P>
8625 <DIV class="code">
8626 <PRE>
8627 %rename(bbb) Space::ABC::aaa(T t);                       // will match but with lower precedence than ccc
8628 %rename(ccc) Space::ABC&lt;Space::XYZ&gt;::aaa(Space::XYZ t);  // will match but with higher precedence than bbb
8629
8630 namespace Space {
8631   class XYZ {};
8632   template&lt;typename T&gt; struct ABC {
8633     void aaa(T t) {}
8634   };
8635 }
8636 %template(ABCXYZ) Space::ABC&lt;Space::XYZ&gt;;
8637 </PRE>
8638 </DIV>
8639 <P> It should now be apparent that there are many ways to achieve a
8640  renaming with %rename. This is demonstrated by the following two
8641  examples, which are effectively the same as the above example. Below
8642  shows how %rename can be placed inside a namespace.</P>
8643 <DIV class="code">
8644 <PRE>
8645 namespace Space {
8646   %rename(bbb) ABC::aaa(T t);                       // will match but with lower precedence than ccc
8647   %rename(ccc) ABC&lt;Space::XYZ&gt;::aaa(Space::XYZ t);  // will match but with higher precedence than bbb
8648   %rename(ddd) ABC&lt;Space::XYZ&gt;::aaa(XYZ t);         // will not match
8649 }
8650
8651 namespace Space {
8652   class XYZ {};
8653   template&lt;typename T&gt; struct ABC {
8654     void aaa(T t) {}
8655   };
8656 }
8657 %template(ABCXYZ) Space::ABC&lt;Space::XYZ&gt;;
8658 </PRE>
8659 </DIV>
8660 <P> Note that <TT>ddd</TT> does not match as there is no namespace
8661  resolution for parameter types and the fully qualified type must be
8662  specified for template type expansion. The following example shows how
8663  %rename can be placed within %extend.</P>
8664 <DIV class="code">
8665 <PRE>
8666 namespace Space {
8667   %extend ABC {
8668     %rename(bbb) aaa(T t);           // will match but with lower precedence than ccc
8669   }
8670   %extend ABC&lt;Space::XYZ&gt; {
8671     %rename(ccc) aaa(Space::XYZ t);  // will match but with higher precedence than bbb
8672     %rename(ddd) aaa(XYZ t);         // will not match
8673   }
8674 }
8675
8676 namespace Space {
8677   class XYZ {};
8678   template&lt;typename T&gt; struct ABC {
8679     void aaa(T t) {}
8680   };
8681 }
8682 %template(ABCXYZ) Space::ABC&lt;Space::XYZ&gt;;
8683 </PRE>
8684 </DIV>
8685 <H2><A name="SWIGPlus_exception_specifications"></A>6.21 Exception
8686  specifications</H2>
8687 <P> When C++ programs utilize exceptions, exceptional behavior is
8688  sometimes specified as part of a function or method declaration. For
8689  example:</P>
8690 <DIV class="code">
8691 <PRE>
8692 class Error { };
8693
8694 class Foo {
8695 public:
8696     ...
8697     void blah() throw(Error);
8698     ...
8699 };
8700 </PRE>
8701 </DIV>
8702 <P> If an exception specification is used, SWIG automatically generates
8703  wrapper code for catching the indicated exception and, when possible,
8704  rethrowing it into the target language, or converting it into an error
8705  in the target language otherwise. For example, in Python, you can write
8706  code like this:</P>
8707 <DIV class="targetlang">
8708 <PRE>
8709 f = Foo()
8710 try:
8711     f.blah()
8712 except Error,e:
8713      # e is a wrapped instance of &quot;Error&quot;
8714 </PRE>
8715 </DIV>
8716 <P> Details of how to tailor code for handling the caught C++ exception
8717  and converting it into the target language's exception/error handling
8718  mechanism is outlined in the <A href="#throws_typemap">&quot;throws&quot; typemap</A>
8719  section.</P>
8720 <P> Since exception specifications are sometimes only used sparingly,
8721  this alone may not be enough to properly handle C++ exceptions. To do
8722  that, a different set of special SWIG directives are used. Consult the
8723  &quot;<A href="#exception">Exception handling with %exception</A>&quot; section
8724  for details. The next section details a way of simulating an exception
8725  specification or replacing an existing one.</P>
8726 <H2><A name="SWIGPlus_catches"></A>6.22 Exception handling with %catches</H2>
8727 <P> Exceptions are automatically handled for methods with an exception
8728  specification. Similar handling can be achieved for methods without
8729  exception specifications through the <TT>%catches</TT> feature. It is
8730  also possible to replace any declared exception specification using the
8731  <TT>%catches</TT> feature. In fact, <TT>%catches</TT> uses the same <A href="#throws_typemap">
8732 &quot;throws&quot; typemaps</A> that SWIG uses for exception specifications in
8733  handling exceptions. The <TT>%catches</TT> feature must contain a list
8734  of possible types that can be thrown. For each type that is in the
8735  list, SWIG will generate a catch handler, in the same way that it would
8736  for types declared in the exception specification. Note that the list
8737  can also include the catch all specification &quot;...&quot;. For example,</P>
8738 <DIV class="code">
8739 <PRE>
8740 struct EBase { virtual ~EBase(); };
8741 struct Error1 : EBase { };
8742 struct Error2 : EBase { };
8743 struct Error3 : EBase { };
8744 struct Error4 : EBase { };
8745
8746 %catches(Error1,Error2,...) Foo::bar();
8747 %catches(EBase) Foo::blah();
8748
8749 class Foo {
8750 public:
8751     ...
8752     void bar();
8753     void blah() throw(Error1,Error2,Error3,Error4);
8754     ...
8755 };
8756 </PRE>
8757 </DIV>
8758 <P> For the <TT>Foo::bar()</TT> method, which can throw anything, SWIG
8759  will generate catch handlers for <TT>Error1</TT>, <TT>Error2</TT> as
8760  well as a catch all handler (...). Each catch handler will convert the
8761  caught exception and convert it into a target language error/exception.
8762  The catch all handler will convert the caught exception into an unknown
8763  error/exception.</P>
8764 <P> Without the <TT>%catches</TT> feature being attached to <TT>
8765 Foo::blah()</TT>, SWIG will generate catch handlers for all of the types
8766  in the exception specification, that is, <TT>Error1, Error2, Error3,
8767  Error4</TT>. However, with the <TT>%catches</TT> feature above, just a
8768  single catch handler for the base class, <TT>EBase</TT> will be
8769  generated to convert the C++ exception into a target language
8770  error/exception.</P>
8771 <H2><A name="SWIGPlus_nn33"></A>6.23 Pointers to Members</H2>
8772 <P> Starting with SWIG-1.3.7, there is limited parsing support for
8773  pointers to C++ class members. For example:</P>
8774 <DIV class="code">
8775 <PRE>
8776 double do_op(Object *o, double (Object::*callback)(double,double));
8777 extern double (Object::*fooptr)(double,double);
8778 %constant double (Object::*FOO)(double,double) = &amp;Object::foo;
8779 </PRE>
8780 </DIV>
8781 <P> Although these kinds of pointers can be parsed and represented by
8782  the SWIG type system, few language modules know how to handle them due
8783  to implementation differences from standard C pointers. Readers are<EM>
8784  strongly</EM> advised to consult an advanced text such as the &quot;The
8785  Annotated C++ Manual&quot; for specific details.</P>
8786 <P> When pointers to members are supported, the pointer value might
8787  appear as a special string like this:</P>
8788 <DIV class="targetlang">
8789 <PRE>
8790 &gt;&gt;&gt; print example.FOO
8791 _ff0d54a800000000_m_Object__f_double_double__double
8792 &gt;&gt;&gt;
8793 </PRE>
8794 </DIV>
8795 <P> In this case, the hexadecimal digits represent the entire value of
8796  the pointer which is usually the contents of a small C++ structure on
8797  most machines.</P>
8798 <P> SWIG's type-checking mechanism is also more limited when working
8799  with member pointers. Normally SWIG tries to keep track of inheritance
8800  when checking types. However, no such support is currently provided for
8801  member pointers.</P>
8802 <H2><A name="SWIGPlus_nn34"></A>6.24 Smart pointers and operator-&gt;()</H2>
8803 <P> In some C++ programs, objects are often encapsulated by
8804  smart-pointers or proxy classes. This is sometimes done to implement
8805  automatic memory management (reference counting) or persistence.
8806  Typically a smart-pointer is defined by a template class where the <TT>
8807 -&gt;</TT> operator has been overloaded. This class is then wrapped around
8808  some other class. For example:</P>
8809 <DIV class="code">
8810 <PRE>
8811 // Smart-pointer class
8812 template&lt;class T&gt; class SmartPtr {
8813     T *pointee;
8814 public:
8815     ...
8816     T *operator-&gt;() {
8817         return pointee;
8818     }
8819     ...
8820 };
8821
8822 // Ordinary class
8823 class Foo_Impl {
8824 public:
8825     int x;
8826     virtual void bar();
8827     ...
8828 };
8829
8830 // Smart-pointer wrapper
8831 typedef SmartPtr&lt;Foo_Impl&gt; Foo;
8832
8833 // Create smart pointer Foo
8834 Foo make_Foo() {
8835     return SmartPtr(new Foo_Impl());
8836 }
8837
8838 // Do something with smart pointer Foo
8839 void do_something(Foo f) {
8840     printf(&quot;x = %d\n&quot;, f-&gt;x);
8841     f-&gt;bar();
8842 }
8843 </PRE>
8844 </DIV>
8845 <P> A key feature of this approach is that by defining <TT>operator-&gt;</TT>
8846  the methods and attributes of the object wrapped by a smart pointer are
8847  transparently accessible. For example, expressions such as these (from
8848  the previous example),</P>
8849 <DIV class="code">
8850 <PRE>
8851 f-&gt;x
8852 f-&gt;bar()
8853 </PRE>
8854 </DIV>
8855 <P> are transparently mapped to the following</P>
8856 <DIV class="code">
8857 <PRE>
8858 (f.operator-&gt;())-&gt;x;
8859 (f.operator-&gt;())-&gt;bar();
8860 </PRE>
8861 </DIV>
8862 <P> When generating wrappers, SWIG tries to emulate this functionality
8863  to the extent that it is possible. To do this, whenever <TT>
8864 operator-&gt;()</TT> is encountered in a class, SWIG looks at its returned
8865  type and uses it to generate wrappers for accessing attributes of the
8866  underlying object. For example, wrapping the above code produces
8867  wrappers like this:</P>
8868 <DIV class="code">
8869 <PRE>
8870 int Foo_x_get(Foo *f) {
8871    return (*f)-&gt;x;
8872 }
8873 void Foo_x_set(Foo *f, int value) {
8874    (*f)-&gt;x = value;
8875 }
8876 void Foo_bar(Foo *f) {
8877    (*f)-&gt;bar();
8878 }
8879 </PRE>
8880 </DIV>
8881 <P> These wrappers take a smart-pointer instance as an argument, but
8882  dereference it in a way to gain access to the object returned by <TT>
8883 operator-&gt;()</TT>. You should carefully compare these wrappers to those
8884  in the first part of this chapter (they are slightly different).</P>
8885 <P> The end result is that access looks very similar to C++. For
8886  example, you could do this in Python:</P>
8887 <DIV class="targetlang">
8888 <PRE>
8889 &gt;&gt;&gt; f = make_Foo()
8890 &gt;&gt;&gt; print f.x
8891 0
8892 &gt;&gt;&gt; f.bar()
8893 &gt;&gt;&gt;
8894 </PRE>
8895 </DIV>
8896 <P> When generating wrappers through a smart-pointer, SWIG tries to
8897  generate wrappers for all methods and attributes that might be
8898  accessible through <TT>operator-&gt;()</TT>. This includes any methods
8899  that might be accessible through inheritance. However, there are a
8900  number of restrictions:</P>
8901 <UL>
8902 <LI>Member variables and methods are wrapped through a smart pointer.
8903  Enumerations, constructors, and destructors are not wrapped.</LI>
8904 <LI>
8905 <P>If the smart-pointer class and the underlying object both define a
8906  method or variable of the same name, then the smart-pointer version has
8907  precedence. For example, if you have this code</P>
8908 <DIV class="code">
8909 <PRE>
8910 class Foo {
8911 public:
8912     int x;
8913 };
8914
8915 class Bar {
8916 public:
8917     int x;       
8918     Foo *operator-&gt;();
8919 };
8920 </PRE>
8921 </DIV>
8922 <P> then the wrapper for <TT>Bar::x</TT> accesses the <TT>x</TT> defined
8923  in <TT>Bar</TT>, and not the <TT>x</TT> defined in <TT>Foo</TT>.</P>
8924 </LI>
8925 </UL>
8926 <P> If your intent is to only expose the smart-pointer class in the
8927  interface, it is not necessary to wrap both the smart-pointer class and
8928  the class for the underlying object. However, you must still tell SWIG
8929  about both classes if you want the technique described in this section
8930  to work. To only generate wrappers for the smart-pointer class, you can
8931  use the %ignore directive. For example:</P>
8932 <DIV class="code">
8933 <PRE>
8934 %ignore Foo;
8935 class Foo {       // Ignored
8936 };
8937
8938 class Bar {
8939 public:
8940    Foo *operator-&gt;();
8941    ...
8942 };
8943 </PRE>
8944 </DIV>
8945 <P> Alternatively, you can import the definition of <TT>Foo</TT> from a
8946  separate file using <TT>%import</TT>.</P>
8947 <P><B> Note:</B> When a class defines <TT>operator-&gt;()</TT>, the
8948  operator itself is wrapped as a method <TT>__deref__()</TT>. For
8949  example:</P>
8950 <DIV class="targetlang">
8951 <PRE>
8952 f = Foo()               # Smart-pointer
8953 p = f.__deref__()       # Raw pointer from operator-&gt;
8954 </PRE>
8955 </DIV>
8956 <P><B> Note:</B> To disable the smart-pointer behavior, use <TT>%ignore</TT>
8957  to ignore <TT>operator-&gt;()</TT>. For example:</P>
8958 <DIV class="code">
8959 <PRE>
8960 %ignore Bar::operator-&gt;;
8961 </PRE>
8962 </DIV>
8963 <P><B> Note:</B> Smart pointer support was first added in SWIG-1.3.14.</P>
8964 <H2><A name="SWIGPlus_nn35"></A>6.25 Using declarations and inheritance</H2>
8965 <P> <TT>using</TT> declarations are sometimes used to adjust access to
8966  members of base classes. For example:</P>
8967 <DIV class="code">
8968 <PRE>
8969 class Foo {
8970 public:
8971       int  blah(int x);
8972 };
8973
8974 class Bar {
8975 public:
8976       double blah(double x);
8977 };
8978
8979 class FooBar : public Foo, public Bar {
8980 public:
8981       using Foo::blah;  
8982       using Bar::blah;
8983       char *blah(const char *x);
8984 };
8985 </PRE>
8986 </DIV>
8987 <P> In this example, the <TT>using</TT> declarations make different
8988  versions of the overloaded <TT>blah()</TT> method accessible from the
8989  derived class. For example:</P>
8990 <DIV class="code">
8991 <PRE>
8992 FooBar *f;
8993 f-&gt;blah(3);         // Ok. Invokes Foo::blah(int)
8994 f-&gt;blah(3.5);       // Ok. Invokes Bar::blah(double)
8995 f-&gt;blah(&quot;hello&quot;);   // Ok. Invokes FooBar::blah(const char *);
8996 </PRE>
8997 </DIV>
8998 <P> SWIG emulates the same functionality when creating wrappers. For
8999  example, if you wrap this code in Python, the module works just like
9000  you would expect:</P>
9001 <DIV class="targetlang">
9002 <PRE>
9003 &gt;&gt;&gt; import example
9004 &gt;&gt;&gt; f = example.FooBar()
9005 &gt;&gt;&gt; f.blah(3)
9006 &gt;&gt;&gt; f.blah(3.5)
9007 &gt;&gt;&gt; f.blah(&quot;hello&quot;)
9008 </PRE>
9009 </DIV>
9010 <P> <TT>using</TT> declarations can also be used to change access when
9011  applicable. For example:</P>
9012 <DIV class="code">
9013 <PRE>
9014 class Foo {
9015 protected:
9016     int x;
9017     int blah(int x);
9018 };
9019
9020 class Bar : public Foo {
9021 public:
9022     using Foo::x;       // Make x public
9023     using Foo::blah;    // Make blah public
9024 };
9025 </PRE>
9026 </DIV>
9027 <P> This also works in SWIG---the exposed declarations will be wrapped
9028  normally.</P>
9029 <P> When <TT>using</TT> declarations are used as shown in these
9030  examples, declarations from the base classes are copied into the
9031  derived class and wrapped normally. When copied, the declarations
9032  retain any properties that might have been attached using <TT>%rename</TT>
9033 , <TT>%ignore</TT>, or <TT>%feature</TT>. Thus, if a method is ignored
9034  in a base class, it will also be ignored by a <TT>using</TT>
9035  declaration.</P>
9036 <P> Because a <TT>using</TT> declaration does not provide fine-grained
9037  control over the declarations that get imported, it may be difficult to
9038  manage such declarations in applications that make heavy use of SWIG
9039  customization features. If you can't get <TT>using</TT> to work
9040  correctly, you can always change the interface to the following:</P>
9041 <DIV class="code">
9042 <PRE>
9043
9044 class FooBar : public Foo, public Bar {
9045 public:
9046 #ifndef SWIG
9047       using Foo::blah;  
9048       using Bar::blah;
9049 #else
9050       int blah(int x);         // explicitly tell SWIG about other declarations
9051       double blah(double x);
9052 #endif
9053
9054       char *blah(const char *x);
9055 };
9056 </PRE>
9057 </DIV>
9058 <P><B> Notes:</B></P>
9059 <UL>
9060 <LI>
9061 <P>If a derived class redefines a method defined in a base class, then a
9062  <TT>using</TT> declaration won't cause a conflict. For example:</P>
9063 <DIV class="code">
9064 <PRE>
9065 class Foo {
9066 public:
9067        int blah(int );
9068        double blah(double);
9069 };
9070
9071 class Bar : public Foo {
9072 public:
9073        using Foo::blah;    // Only imports blah(double);
9074        int blah(int);
9075 };
9076 </PRE>
9077 </DIV></LI>
9078 <LI>
9079 <P>Resolving ambiguity in overloading may prevent declarations from
9080  being imported by <TT>using</TT>. For example:</P>
9081 <DIV class="code">
9082 <PRE>
9083 %rename(blah_long) Foo::blah(long);
9084 class Foo {
9085 public:
9086      int blah(int);
9087      long blah(long);  // Renamed to blah_long
9088 };
9089
9090 class Bar : public Foo {
9091 public:
9092      using Foo::blah;     // Only imports blah(int)
9093      double blah(double x);
9094 };
9095 </PRE>
9096 </DIV></LI>
9097 </UL>
9098 <H2><A name="SWIGPlus_nested_classes"></A>6.26 Nested classes</H2>
9099 <P> There is limited support for nested structs and unions when wrapping
9100  C code, see <A href="#SWIG_nested_structs">Nested structures</A> for
9101  further details. However, there is no nested class/struct/union support
9102  when wrapping C++ code (using the -c++ commandline option). This may be
9103  added at a future date, however, until then some of the following
9104  workarounds can be applied.</P>
9105 <P> It might be possible to use partial class information. Since SWIG
9106  does not need the entire class specification to work, conditional
9107  compilation can be used to comment out the problematic nested class
9108  definition, you might do this:</P>
9109 <DIV class="code">
9110 <PRE>
9111 class Foo {
9112 public:
9113 #ifndef SWIG
9114    class Bar {
9115    public:
9116      ...
9117    };
9118 #endif
9119    Foo();
9120   ~Foo();
9121    ...
9122 };
9123 </PRE>
9124 </DIV>
9125 <P> The next workaround assumes you cannot modify the source code as was
9126  done above and it provides a solution for methods that use nested class
9127  types. Imagine we are wrapping the <TT>Outer</TT> class which contains
9128  a nested class <TT>Inner</TT>:</P>
9129 <DIV class="code">
9130 <PRE>
9131 // File outer.h
9132 class Outer {
9133 public:
9134   class Inner {
9135     public:
9136       int var;
9137       Inner(int v = 0) : var(v) {}
9138   };
9139   void method(Inner inner);
9140 };
9141 </PRE>
9142 </DIV>
9143 <P> The following interface file works around SWIG nested class
9144  limitations by redefining the nested class as a global class. A typedef
9145  for the compiler is also required in order for the generated wrappers
9146  to compile.</P>
9147 <DIV class="code">
9148 <PRE>
9149 // File : example.i
9150 %module example
9151
9152 // Suppress SWIG warning
9153 #pragma SWIG nowarn=SWIGWARN_PARSE_NESTED_CLASS
9154
9155 // Redefine nested class in global scope in order for SWIG to generate
9156 // a proxy class. Only SWIG parses this definition.
9157 class Inner {
9158   public:
9159     int var;
9160     Inner(int v = 0) : var(v) {}
9161 };
9162
9163 %{
9164 #include &quot;outer.h&quot;
9165 %}
9166 %include &quot;outer.h&quot;
9167
9168 %{
9169 // SWIG thinks that Inner is a global class, so we need to trick the C++
9170 // compiler into understanding this so called global type.
9171 typedef Outer::Inner Inner;
9172 %}
9173
9174 </PRE>
9175 </DIV>
9176 <P> The downside to this approach is having to maintain two definitions
9177  of <TT>Inner</TT>, the real one and the one in the interface file that
9178  SWIG parses.</P>
9179 <H2><A name="SWIGPlus_nn37"></A>6.27 A brief rant about
9180  const-correctness</H2>
9181 <P> A common issue when working with C++ programs is dealing with all
9182  possible ways in which the <TT>const</TT> qualifier (or lack thereof)
9183  will break your program, all programs linked against your program, and
9184  all programs linked against those programs.</P>
9185 <P> Although SWIG knows how to correctly deal with <TT>const</TT> in its
9186  internal type system and it knows how to generate wrappers that are
9187  free of const-related warnings, SWIG does not make any attempt to
9188  preserve const-correctness in the target language. Thus, it is possible
9189  to pass <TT>const</TT> qualified objects to non-const methods and
9190  functions. For example, consider the following code in C++:</P>
9191 <DIV class="code">
9192 <PRE>
9193 const Object * foo();
9194 void bar(Object *);
9195
9196 ...
9197 // C++ code
9198 void blah() {
9199    bar(foo());         // Error: bar discards const
9200 };
9201 </PRE>
9202 </DIV>
9203 <P> Now, consider the behavior when wrapped into a Python module:</P>
9204 <DIV class="targetlang">
9205 <PRE>
9206 &gt;&gt;&gt; bar(foo())         # Okay
9207 &gt;&gt;&gt; 
9208 </PRE>
9209 </DIV>
9210 <P> Although this is clearly a violation of the C++ type-system, fixing
9211  the problem doesn't seem to be worth the added implementation
9212  complexity that would be required to support it in the SWIG run-time
9213  type system. There are no plans to change this in future releases
9214  (although we'll never rule anything out entirely).</P>
9215 <P> The bottom line is that this particular issue does not appear to be
9216  a problem for most SWIG projects. Of course, you might want to consider
9217  using another tool if maintaining constness is the most important part
9218  of your project.</P>
9219 <H2><A name="SWIGPlus_nn42"></A>6.28 Where to go for more information</H2>
9220 <P> If you're wrapping serious C++ code, you might want to pick up a
9221  copy of &quot;The Annotated C++ Reference Manual&quot; by Ellis and Stroustrup.
9222  This is the reference document we use to guide a lot of SWIG's C++
9223  support.</P>
9224
9225 <!--  LocalWords:  destructors Enums Namespaces const SWIG's STL OO adaptor tcl
9226  -->
9227
9228 <!--  LocalWords:  debuggable cxx OBJS Wiki accessor nodefault makedefault
9229  -->
9230
9231 <!--  LocalWords:  notabstract CopyFoo
9232  -->
9233 <HR NOSHADE>
9234 <H1><A name="Preprocessor"></A>7 Preprocessing</H1>
9235
9236 <!-- INDEX -->
9237 <DIV class="sectiontoc">
9238 <UL>
9239 <LI><A href="#Preprocessor_nn2">File inclusion</A></LI>
9240 <LI><A href="#Preprocessor_nn3">File imports</A></LI>
9241 <LI><A href="#Preprocessor_condition_compilation">Conditional
9242  Compilation</A></LI>
9243 <LI><A href="#Preprocessor_nn5">Macro Expansion</A></LI>
9244 <LI><A href="#Preprocessor_nn6">SWIG Macros</A></LI>
9245 <LI><A href="#Preprocessor_nn7">C99 and GNU Extensions</A></LI>
9246 <LI><A href="#Preprocessor_nn8">Preprocessing and %{ ... %} &amp; &quot; ... &quot;
9247  delimiters</A></LI>
9248 <LI><A href="#Preprocessor_nn9">Preprocessing and { ... } delimiters</A></LI>
9249 <LI><A href="#Preprocessor_typemap_delimiters">Preprocessor and Typemaps</A>
9250 </LI>
9251 <LI><A href="#Preprocessor_nn10">Viewing preprocessor output</A></LI>
9252 <LI><A href="#Preprocessor_warning_error">The #error and #warning
9253  directives</A></LI>
9254 </UL>
9255 </DIV>
9256 <!-- INDEX -->
9257 <P> SWIG includes its own enhanced version of the C preprocessor. The
9258  preprocessor supports the standard preprocessor directives and macro
9259  expansion rules. However, a number of modifications and enhancements
9260  have been made. This chapter describes some of these modifications.</P>
9261 <H2><A name="Preprocessor_nn2"></A>7.1 File inclusion</H2>
9262 <P> To include another file into a SWIG interface, use the <TT>%include</TT>
9263  directive like this:</P>
9264 <DIV class="code">
9265 <PRE>
9266 %include &quot;pointer.i&quot;
9267 </PRE>
9268 </DIV>
9269 <P> Unlike, <TT>#include</TT>, <TT>%include</TT> includes each file once
9270  (and will not reload the file on subsequent <TT>%include</TT>
9271  declarations). Therefore, it is not necessary to use include-guards in
9272  SWIG interfaces.</P>
9273 <P> By default, the <TT>#include</TT> is ignored unless you run SWIG
9274  with the <TT>-includeall</TT> option. The reason for ignoring
9275  traditional includes is that you often don't want SWIG to try and wrap
9276  everything included in standard header system headers and auxiliary
9277  files.</P>
9278 <H2><A name="Preprocessor_nn3"></A>7.2 File imports</H2>
9279 <P> SWIG provides another file inclusion directive with the <TT>%import</TT>
9280  directive. For example:</P>
9281 <DIV class="code">
9282 <PRE>
9283 %import &quot;foo.i&quot;
9284 </PRE>
9285 </DIV>
9286 <P> The purpose of <TT>%import</TT> is to collect certain information
9287  from another SWIG interface file or a header file without actually
9288  generating any wrapper code. Such information generally includes type
9289  declarations (e.g., <TT>typedef</TT>) as well as C++ classes that might
9290  be used as base-classes for class declarations in the interface. The
9291  use of <TT>%import</TT> is also important when SWIG is used to generate
9292  extensions as a collection of related modules. This is an advanced
9293  topic and is described in later in the <A href="Modules.html">Working
9294  with Modules</A> chapter.</P>
9295 <P> The <TT>-importall</TT> directive tells SWIG to follow all <TT>
9296 #include</TT> statements as imports. This might be useful if you want to
9297  extract type definitions from system header files without generating
9298  any wrappers.</P>
9299 <H2><A name="Preprocessor_condition_compilation"></A>7.3 Conditional
9300  Compilation</H2>
9301 <P> SWIG fully supports the use of <TT>#if</TT>, <TT>#ifdef</TT>, <TT>
9302 #ifndef</TT>, <TT>#else</TT>, <TT>#endif</TT> to conditionally include
9303  parts of an interface. The following symbols are predefined by SWIG
9304  when it is parsing the interface:</P>
9305 <DIV class="code">
9306 <PRE>
9307 SWIG                            Always defined when SWIG is processing a file
9308 SWIGIMPORTED                    Defined when SWIG is importing a file with <TT>%import</TT>
9309 SWIGMAC                         Defined when running SWIG on the Macintosh
9310 SWIGWIN                         Defined when running SWIG under Windows
9311 SWIG_VERSION                    Hexadecimal number containing SWIG version,
9312                                 such as 0x010311 (corresponding to SWIG-1.3.11).
9313
9314 SWIGALLEGROCL                   Defined when using Allegro CL
9315 SWIGCFFI                        Defined when using CFFI
9316 SWIGCHICKEN                     Defined when using CHICKEN
9317 SWIGCLISP                       Defined when using CLISP
9318 SWIGCSHARP                      Defined when using C#
9319 SWIGGUILE                       Defined when using Guile
9320 SWIGJAVA                        Defined when using Java
9321 SWIGLUA                         Defined when using Lua
9322 SWIGMODULA3                     Defined when using Modula-3
9323 SWIGMZSCHEME                    Defined when using Mzscheme        
9324 SWIGOCAML                       Defined when using Ocaml
9325 SWIGOCTAVE                      Defined when using Octave
9326 SWIGPERL                        Defined when using Perl
9327 SWIGPHP                         Defined when using PHP
9328 SWIGPIKE                        Defined when using Pike
9329 SWIGPYTHON                      Defined when using Python
9330 SWIGR                           Defined when using R
9331 SWIGRUBY                        Defined when using Ruby
9332 SWIGSEXP                        Defined when using S-expressions
9333 SWIGTCL                         Defined when using Tcl
9334 SWIGXML                         Defined when using XML
9335 </PRE>
9336 </DIV>
9337 <P> In addition, SWIG defines the following set of standard C/C++
9338  macros:</P>
9339 <DIV class="code">
9340 <PRE>
9341 __LINE__                        Current line number
9342 __FILE__                        Current file name
9343 __STDC__                        Defined to indicate ANSI C
9344 __cplusplus                     Defined when -c++ option used
9345 </PRE>
9346 </DIV>
9347 <P> Interface files can look at these symbols as necessary to change the
9348  way in which an interface is generated or to mix SWIG directives with C
9349  code. These symbols are also defined within the C code generated by
9350  SWIG (except for the symbol `<TT>SWIG</TT>' which is only defined
9351  within the SWIG compiler).</P>
9352 <H2><A name="Preprocessor_nn5"></A>7.4 Macro Expansion</H2>
9353 <P> Traditional preprocessor macros can be used in SWIG interfaces. Be
9354  aware that the <TT>#define</TT> statement is also used to try and
9355  detect constants. Therefore, if you have something like this in your
9356  file,</P>
9357 <DIV class="code">
9358 <PRE>
9359 #ifndef _FOO_H 1
9360 #define _FOO_H 1
9361 ...
9362 #endif
9363 </PRE>
9364 </DIV>
9365 <P> you may get some extra constants such as <TT>_FOO_H</TT> showing up
9366  in the scripting interface.</P>
9367 <P> More complex macros can be defined in the standard way. For example:</P>
9368 <DIV class="code">
9369 <PRE>
9370 #define EXTERN extern
9371 #ifdef __STDC__
9372 #define _ANSI(args)   (args)
9373 #else
9374 #define _ANSI(args) ()
9375 #endif
9376 </PRE>
9377 </DIV>
9378 <P> The following operators can appear in macro definitions:</P>
9379 <UL>
9380 <LI><TT>#x</TT>
9381 <BR> Converts macro argument <TT>x</TT> to a string surrounded by double
9382  quotes (&quot;x&quot;).</LI>
9383 <LI><TT>x ## y</TT>
9384 <BR> Concatenates x and y together to form <TT>xy</TT>.</LI>
9385 <LI><TT>`x`</TT>
9386 <BR> If <TT>x</TT> is a string surrounded by double quotes, do nothing.
9387  Otherwise, turn into a string like <TT>#x</TT>. This is a non-standard
9388  SWIG extension.</LI>
9389 </UL>
9390 <H2><A name="Preprocessor_nn6"></A>7.5 SWIG Macros</H2>
9391 <P> SWIG provides an enhanced macro capability with the <TT>%define</TT>
9392  and <TT>%enddef</TT> directives. For example:</P>
9393 <DIV class="code">
9394 <PRE>
9395 %define ARRAYHELPER(type,name)
9396 %inline %{
9397 type *new_ ## name (int nitems) {
9398    return (type *) malloc(sizeof(type)*nitems);
9399 }
9400 void delete_ ## name(type *t) {
9401    free(t);
9402 }
9403 type name ## _get(type *t, int index) {
9404    return t[index];
9405 }
9406 void name ## _set(type *t, int index, type val) {
9407    t[index] = val;
9408 }
9409 %}
9410 %enddef
9411
9412 ARRAYHELPER(int, IntArray)
9413 ARRAYHELPER(double, DoubleArray)
9414 </PRE>
9415 </DIV>
9416 <P> The primary purpose of <TT>%define</TT> is to define large macros of
9417  code. Unlike normal C preprocessor macros, it is not necessary to
9418  terminate each line with a continuation character (\)--the macro
9419  definition extends to the first occurrence of <TT>%enddef</TT>.
9420  Furthermore, when such macros are expanded, they are reparsed through
9421  the C preprocessor. Thus, SWIG macros can contain all other
9422  preprocessor directives except for nested <TT>%define</TT> statements.</P>
9423 <P> The SWIG macro capability is a very quick and easy way to generate
9424  large amounts of code. In fact, many of SWIG's advanced features and
9425  libraries are built using this mechanism (such as C++ template
9426  support).</P>
9427 <H2><A name="Preprocessor_nn7"></A>7.6 C99 and GNU Extensions</H2>
9428 <P> SWIG-1.3.12 and newer releases support variadic preprocessor macros.
9429  For example:</P>
9430 <DIV class="code">
9431 <PRE>
9432 #define DEBUGF(fmt,...)   fprintf(stderr,fmt,__VA_ARGS__)
9433 </PRE>
9434 </DIV>
9435 <P> When used, any extra arguments to <TT>...</TT> are placed into the
9436  special variable <TT>__VA_ARGS__</TT>. This also works with special
9437  SWIG macros defined using <TT>%define</TT>.</P>
9438 <P> SWIG allows a variable number of arguments to be empty. However,
9439  this often results in an extra comma (,) and syntax error in the
9440  resulting expansion. For example:</P>
9441 <DIV class="code">
9442 <PRE>
9443 DEBUGF(&quot;hello&quot;);   --&gt; fprintf(stderr,&quot;hello&quot;,);
9444 </PRE>
9445 </DIV>
9446 <P> To get rid of the extra comma, use <TT>##</TT> like this:</P>
9447 <DIV class="code">
9448 <PRE>
9449 #define DEBUGF(fmt,...)   fprintf(stderr,fmt, ##__VA_ARGS__)
9450 </PRE>
9451 </DIV>
9452 <P> SWIG also supports GNU-style variadic macros. For example:</P>
9453 <DIV class="code">
9454 <PRE>
9455 #define DEBUGF(fmt, args...)  fprintf(stdout,fmt,args)
9456 </PRE>
9457 </DIV>
9458 <P><B> Comment:</B> It's not entirely clear how variadic macros might be
9459  useful to interface building. However, they are used internally to
9460  implement a number of SWIG directives and are provided to make SWIG
9461  more compatible with C99 code.</P>
9462 <H2><A name="Preprocessor_nn8"></A>7.7 Preprocessing and %{ ... %} &amp; &quot;
9463  ... &quot; delimiters</H2>
9464 <P> The SWIG preprocessor does not process any text enclosed in a code
9465  block %{ ... %}. Therefore, if you write code like this,</P>
9466 <DIV class="code">
9467 <PRE>
9468 %{
9469 #ifdef NEED_BLAH
9470 int blah() {
9471    ...
9472 }
9473 #endif
9474 %}
9475 </PRE>
9476 </DIV>
9477 <P> the contents of the <TT>%{ ... %}</TT> block are copied without
9478  modification to the output (including all preprocessor directives).</P>
9479 <H2><A name="Preprocessor_nn9"></A>7.8 Preprocessing and { ... }
9480  delimiters</H2>
9481 <P> SWIG always runs the preprocessor on text appearing inside <TT>{ ...
9482  }</TT>. However, sometimes it is desirable to make a preprocessor
9483  directive pass through to the output file. For example:</P>
9484 <DIV class="code">
9485 <PRE>
9486 %extend Foo {
9487    void bar() {
9488       #ifdef DEBUG
9489        printf(&quot;I'm in bar\n&quot;);
9490       #endif
9491    }
9492 }
9493 </PRE>
9494 </DIV>
9495 <P> By default, SWIG will interpret the <TT>#ifdef DEBUG</TT> statement.
9496  However, if you really wanted that code to actually go into the wrapper
9497  file, prefix the preprocessor directives with <TT>%</TT> like this:</P>
9498 <DIV class="code">
9499 <PRE>
9500 %extend Foo {
9501    void bar() {
9502       %#ifdef DEBUG
9503        printf(&quot;I'm in bar\n&quot;);
9504       %#endif
9505    }
9506 }
9507 </PRE>
9508 </DIV>
9509 <P> SWIG will strip the extra <TT>%</TT> and leave the preprocessor
9510  directive in the code.</P>
9511 <H2><A name="Preprocessor_typemap_delimiters"></A>7.9 Preprocessor and
9512  Typemaps</H2>
9513 <P> <A href="Typemaps.html">Typemaps</A> support a special attribute
9514  called <TT>noblock</TT> where the { ... } delimiters can be used, but
9515  the delimiters are not actually generated into the code. The effect is
9516  then similar to using &quot;&quot; or %{ %} delimiters but the code<B> is</B> run
9517  through the preprocessor. For example:</P>
9518 <DIV class="code">
9519 <PRE>
9520 #define SWIG_macro(CAST) (CAST)$input
9521 %typemap(in) Int {$1= SWIG_macro(int);}
9522 </PRE>
9523 </DIV>
9524 <P> might generate</P>
9525 <DIV class="code">
9526 <PRE>
9527   {
9528     arg1=(int)jarg1;
9529   }
9530 </PRE>
9531 </DIV>
9532 <P> whereas</P>
9533 <DIV class="code">
9534 <PRE>
9535 #define SWIG_macro(CAST) (CAST)$input
9536 %typemap(in,noblock=1) Int {$1= SWIG_macro(int);}
9537 </PRE>
9538 </DIV>
9539 <P> might generate</P>
9540 <DIV class="code">
9541 <PRE>
9542   arg1=(int)jarg1;
9543 </PRE>
9544 </DIV>
9545 <P> and</P>
9546 <DIV class="code">
9547 <PRE>
9548 #define SWIG_macro(CAST) (CAST)$input
9549 %typemap(in) Int %{$1=SWIG_macro(int);%}
9550 </PRE>
9551 </DIV>
9552 <P> would generate</P>
9553 <DIV class="code">
9554 <PRE>
9555   arg1=SWIG_macro(int);
9556 </PRE>
9557 </DIV>
9558 <H2><A name="Preprocessor_nn10"></A>7.10 Viewing preprocessor output</H2>
9559 <P> Like many compilers, SWIG supports a <TT>-E</TT> command line option
9560  to display the output from the preprocessor. When the <TT>-E</TT>
9561  switch is used, SWIG will not generate any wrappers. Instead the
9562  results after the preprocessor has run are displayed. This might be
9563  useful as an aid to debugging and viewing the results of macro
9564  expansions.</P>
9565 <H2><A name="Preprocessor_warning_error"></A>7.11 The #error and
9566  #warning directives</H2>
9567 <P> SWIG supports the commonly used <TT>#warning</TT> and <TT>#error</TT>
9568  preprocessor directives. The <TT>#warning</TT> directive will cause
9569  SWIG to issue a warning then continue processing. The <TT>#error</TT>
9570  directive will cause SWIG to exit with a fatal error. Example usage:</P>
9571 <DIV class="code">
9572 <PRE>
9573 #error &quot;This is a fatal error message&quot;
9574 #warning &quot;This is a warning message&quot;
9575 </PRE>
9576 </DIV>
9577 <P> The <TT>#error</TT> behaviour can be made to work like <TT>#warning</TT>
9578  if the <TT>-cpperraswarn</TT> commandline option is used.
9579  Alternatively, the <TT>#pragma</TT> directive can be used to the same
9580  effect, for example:</P>
9581 <DIV class="code">
9582 <PRE>
9583   /* Modified behaviour: #error does not cause SWIG to exit with error */
9584   #pragma SWIG cpperraswarn=1
9585   /* Normal behaviour: #error does cause SWIG to exit with error */
9586   #pragma SWIG cpperraswarn=0
9587 </PRE>
9588 </DIV><HR NOSHADE>
9589 <H1><A name="Library"></A>8 SWIG library</H1>
9590
9591 <!-- INDEX -->
9592 <DIV class="sectiontoc">
9593 <UL>
9594 <LI><A href="#Library_nn2">The %include directive and library search
9595  path</A></LI>
9596 <LI><A href="#Library_nn3">C Arrays and Pointers</A>
9597 <UL>
9598 <LI><A href="#Library_nn4">cpointer.i</A></LI>
9599 <LI><A href="#Library_carrays">carrays.i</A></LI>
9600 <LI><A href="#Library_nn6">cmalloc.i</A></LI>
9601 <LI><A href="#Library_nn7">cdata.i</A></LI>
9602 </UL>
9603 </LI>
9604 <LI><A href="#Library_nn8">C String Handling</A>
9605 <UL>
9606 <LI><A href="#Library_nn9">Default string handling</A></LI>
9607 <LI><A href="#Library_nn10">Passing binary data</A></LI>
9608 <LI><A href="#Library_nn11">Using %newobject to release memory</A></LI>
9609 <LI><A href="#Library_nn12">cstring.i</A></LI>
9610 </UL>
9611 </LI>
9612 <LI><A href="#Library_stl_cpp_library">STL/C++ Library</A>
9613 <UL>
9614 <LI><A href="#Library_nn14">std_string.i</A></LI>
9615 <LI><A href="#Library_nn15">std_vector.i</A></LI>
9616 <LI><A href="#Library_stl_exceptions">STL exceptions</A></LI>
9617 </UL>
9618 </LI>
9619 <LI><A href="#Library_nn16">Utility Libraries</A>
9620 <UL>
9621 <LI><A href="#Library_nn17">exception.i</A></LI>
9622 </UL>
9623 </LI>
9624 </UL>
9625 </DIV>
9626 <!-- INDEX -->
9627 <P> To help build extension modules, SWIG is packaged with a library of
9628  support files that you can include in your own interfaces. These files
9629  often define new SWIG directives or provide utility functions that can
9630  be used to access parts of the standard C and C++ libraries. This
9631  chapter provides a reference to the current set of supported library
9632  files.</P>
9633 <P><B> Compatibility note:</B> Older versions of SWIG included a number
9634  of library files for manipulating pointers, arrays, and other
9635  structures. Most these files are now deprecated and have been removed
9636  from the distribution. Alternative libraries provide similar
9637  functionality. Please read this chapter carefully if you used the old
9638  libraries.</P>
9639 <H2><A name="Library_nn2"></A>8.1 The %include directive and library
9640  search path</H2>
9641 <P> Library files are included using the <TT>%include</TT> directive.
9642  When searching for files, directories are searched in the following
9643  order:</P>
9644 <UL>
9645 <LI>The current directory</LI>
9646 <LI>Directories specified with the <TT>-I</TT> command line option</LI>
9647 <LI>.<TT>/swig_lib</TT></LI>
9648 <LI>SWIG library install location as reported by <TT>swig -swiglib</TT>,
9649  for example <TT>/usr/local/share/swig/1.3.30</TT></LI>
9650 <LI>On Windows, a directory <TT>Lib</TT> relative to the location of <TT>
9651 swig.exe</TT> is also searched.</LI>
9652 </UL>
9653 <P> Within each directory, SWIG first looks for a subdirectory
9654  corresponding to a target language (e.g., <TT>python</TT>, <TT>tcl</TT>
9655 , etc.). If found, SWIG will search the language specific directory
9656  first. This allows for language-specific implementations of library
9657  files.</P>
9658 <P> You can ignore the installed SWIG library by setting the <TT>
9659 SWIG_LIB</TT> environment variable. Set the environment variable to hold
9660  an alternative library directory.</P>
9661 <P> The directories that are searched are displayed when using <TT>
9662 -verbose</TT> commandline option.</P>
9663 <H2><A name="Library_nn3"></A>8.2 C Arrays and Pointers</H2>
9664 <P> This section describes library modules for manipulating low-level C
9665  arrays and pointers. The primary use of these modules is in supporting
9666  C declarations that manipulate bare pointers such as <TT>int *</TT>, <TT>
9667 double *</TT>, or <TT>void *</TT>. The modules can be used to allocate
9668  memory, manufacture pointers, dereference memory, and wrap pointers as
9669  class-like objects. Since these functions provide direct access to
9670  memory, their use is potentially unsafe and you should exercise
9671  caution.</P>
9672 <H3><A name="Library_nn4"></A>8.2.1 cpointer.i</H3>
9673 <P> The <TT>cpointer.i</TT> module defines macros that can be used to
9674  used to generate wrappers around simple C pointers. The primary use of
9675  this module is in generating pointers to primitive datatypes such as <TT>
9676 int</TT> and <TT>double</TT>.</P>
9677 <P><B> <TT>%pointer_functions(type,name)</TT></B></P>
9678 <DIV class="indent">
9679 <P>Generates a collection of four functions for manipulating a pointer <TT>
9680 type *</TT>:</P>
9681 <P> <TT>type *new_name()</TT></P>
9682 <DIV class="indent">
9683 <P> Creates a new object of type <TT>type</TT> and returns a pointer to
9684  it. In C, the object is created using <TT>calloc()</TT>. In C++, <TT>
9685 new</TT> is used.</P>
9686 </DIV>
9687 <P> <TT>type *copy_name(type value)</TT></P>
9688 <DIV class="indent">
9689 <P> Creates a new object of type <TT>type</TT> and returns a pointer to
9690  it. An initial value is set by copying it from <TT>value</TT>. In C,
9691  the object is created using <TT>calloc()</TT>. In C++, <TT>new</TT> is
9692  used.</P>
9693 </DIV>
9694 <P> <TT>type *delete_name(type *obj)</TT></P>
9695 <DIV class="indent">
9696 <P> Deletes an object type <TT>type</TT>.</P>
9697 </DIV>
9698 <P> <TT>void name_assign(type *obj, type value)</TT></P>
9699 <DIV class="indent">
9700 <P> Assigns <TT>*obj = value</TT>.</P>
9701 </DIV>
9702 <P> <TT>type name_value(type *obj)</TT></P>
9703 <DIV class="indent">
9704 <P> Returns the value of <TT>*obj</TT>.</P>
9705 </DIV>
9706 <P> When using this macro, <TT>type</TT> may be any type and <TT>name</TT>
9707  must be a legal identifier in the target language. <TT>name</TT> should
9708  not correspond to any other name used in the interface file.</P>
9709 <P> Here is a simple example of using <TT>%pointer_functions()</TT>:</P>
9710 <DIV class="code">
9711 <PRE>
9712 %module example
9713 %include &quot;cpointer.i&quot;
9714
9715 /* Create some functions for working with &quot;int *&quot; */
9716 %pointer_functions(int, intp);
9717
9718 /* A function that uses an &quot;int *&quot; */
9719 void add(int x, int y, int *result);
9720 </PRE>
9721 </DIV>
9722 <P> Now, in Python:</P>
9723 <DIV class="targetlang">
9724 <PRE>
9725 &gt;&gt;&gt; import example
9726 &gt;&gt;&gt; c = example.new_intp()     # Create an &quot;int&quot; for storing result
9727 &gt;&gt;&gt; example.add(3,4,c)         # Call function
9728 &gt;&gt;&gt; example.intp_value(c)      # Dereference
9729 7
9730 &gt;&gt;&gt; example.delete_intp(c)     # Delete
9731 </PRE>
9732 </DIV></DIV>
9733 <P><B> <TT>%pointer_class(type,name)</TT></B></P>
9734 <DIV class="indent">
9735 <P> Wraps a pointer of <TT>type *</TT> inside a class-based interface.
9736  This interface is as follows:</P>
9737 <DIV class="code">
9738 <PRE>
9739 struct name {
9740    name();                            // Create pointer object
9741   ~name();                            // Delete pointer object
9742    void assign(type value);           // Assign value
9743    type value();                      // Get value
9744    type *cast();                      // Cast the pointer to original type
9745    static name *frompointer(type *);  // Create class wrapper from existing
9746                                       // pointer
9747 };
9748 </PRE>
9749 </DIV>
9750 <P> When using this macro, <TT>type</TT> is restricted to a simple type
9751  name like <TT>int</TT>, <TT>float</TT>, or <TT>Foo</TT>. Pointers and
9752  other complicated types are not allowed. <TT>name</TT> must be a valid
9753  identifier not already in use. When a pointer is wrapped as a class,
9754  the &quot;class&quot; may be transparently passed to any function that expects
9755  the pointer.</P>
9756 <P> If the target language does not support proxy classes, the use of
9757  this macro will produce the example same functions as <TT>
9758 %pointer_functions()</TT> macro.</P>
9759 <P> It should be noted that the class interface does introduce a new
9760  object or wrap a pointer inside a special structure. Instead, the raw
9761  pointer is used directly.</P>
9762 <P> Here is the same example using a class instead:</P>
9763 <DIV class="code">
9764 <PRE>
9765 %module example
9766 %include &quot;cpointer.i&quot;
9767
9768 /* Wrap a class interface around an &quot;int *&quot; */
9769 %pointer_class(int, intp);
9770
9771 /* A function that uses an &quot;int *&quot; */
9772 void add(int x, int y, int *result);
9773 </PRE>
9774 </DIV>
9775 <P> Now, in Python (using proxy classes)</P>
9776 <DIV class="targetlang">
9777 <PRE>
9778 &gt;&gt;&gt; import example
9779 &gt;&gt;&gt; c = example.intp()         # Create an &quot;int&quot; for storing result
9780 &gt;&gt;&gt; example.add(3,4,c)         # Call function
9781 &gt;&gt;&gt; c.value()                  # Dereference
9782 7
9783 </PRE>
9784 </DIV>
9785 <P> Of the two macros, <TT>%pointer_class</TT> is probably the most
9786  convenient when working with simple pointers. This is because the
9787  pointers are access like objects and they can be easily garbage
9788  collected (destruction of the pointer object destroys the underlying
9789  object).</P>
9790 </DIV>
9791 <P><B> <TT>%pointer_cast(type1, type2, name)</TT></B></P>
9792 <DIV class="indent">
9793 <P> Creates a casting function that converts <TT>type1</TT> to <TT>type2</TT>
9794 . The name of the function is <TT>name</TT>. For example:</P>
9795 <DIV class="code">
9796 <PRE>
9797 %pointer_cast(int *, unsigned int *, int_to_uint);
9798 </PRE>
9799 </DIV>
9800 <P> In this example, the function <TT>int_to_uint()</TT> would be used
9801  to cast types in the target language.</P>
9802 </DIV>
9803 <P><B> Note:</B> None of these macros can be used to safely work with
9804  strings (<TT>char *</TT> or <TT>char **</TT>).</P>
9805 <P><B> Note:</B> When working with simple pointers, typemaps can often
9806  be used to provide more seamless operation.</P>
9807 <H3><A name="Library_carrays"></A>8.2.2 carrays.i</H3>
9808 <P> This module defines macros that assist in wrapping ordinary C
9809  pointers as arrays. The module does not provide any safety or an extra
9810  layer of wrapping--it merely provides functionality for creating,
9811  destroying, and modifying the contents of raw C array data.</P>
9812 <P><B> <TT>%array_functions(type,name)</TT></B></P>
9813 <DIV class="indent">
9814 <P>Creates four functions.</P>
9815 <P> <TT>type *new_name(int nelements)</TT></P>
9816 <DIV class="indent">
9817 <P> Creates a new array of objects of type <TT>type</TT>. In C, the
9818  array is allocated using <TT>calloc()</TT>. In C++, <TT>new []</TT> is
9819  used.</P>
9820 </DIV>
9821 <P> <TT>type *delete_name(type *ary)</TT></P>
9822 <DIV class="indent">
9823 <P> Deletes an array. In C, <TT>free()</TT> is used. In C++, <TT>delete
9824  []</TT> is used.</P>
9825 </DIV>
9826 <P> <TT>type name_getitem(type *ary, int index)</TT></P>
9827 <DIV class="indent">
9828 <P> Returns the value <TT>ary[index]</TT>.</P>
9829 </DIV>
9830 <P> <TT>void name_setitem(type *ary, int index, type value)</TT></P>
9831 <DIV class="indent">
9832 <P> Assigns <TT>ary[index] = value</TT>.</P>
9833 </DIV>
9834 <P> When using this macro, <TT>type</TT> may be any type and <TT>name</TT>
9835  must be a legal identifier in the target language. <TT>name</TT> should
9836  not correspond to any other name used in the interface file.</P>
9837 <P> Here is an example of <TT>%array_functions()</TT>. Suppose you had a
9838  function like this:</P>
9839 <DIV class="code">
9840 <PRE>
9841 void print_array(double x[10]) {
9842    int i;
9843    for (i = 0; i &lt; 10; i++) {
9844       printf(&quot;[%d] = %g\n&quot;, i, x[i]);
9845    }
9846 }
9847 </PRE>
9848 </DIV>
9849 <P> To wrap it, you might write this:</P>
9850 <DIV class="code">
9851 <PRE>
9852 %module example
9853
9854 %include &quot;carrays.i&quot;
9855 %array_functions(double, doubleArray);
9856
9857 void print_array(double x[10]);
9858 </PRE>
9859 </DIV>
9860 <P> Now, in a scripting language, you might write this:</P>
9861 <DIV class="code">
9862 <PRE>
9863 a = new_doubleArray(10)           # Create an array
9864 for i in range(0,10):
9865     doubleArray_setitem(a,i,2*i)  # Set a value
9866 print_array(a)                    # Pass to C
9867 delete_doubleArray(a)             # Destroy array
9868 </PRE>
9869 </DIV></DIV>
9870 <P><B> <TT>%array_class(type,name)</TT></B></P>
9871 <DIV class="indent">
9872 <P> Wraps a pointer of <TT>type *</TT> inside a class-based interface.
9873  This interface is as follows:</P>
9874 <DIV class="code">
9875 <PRE>
9876 struct name {
9877    name(int nelements);                  // Create an array
9878   ~name();                               // Delete array
9879    type getitem(int index);              // Return item
9880    void setitem(int index, type value);  // Set item
9881    type *cast();                         // Cast to original type
9882    static name *frompointer(type *);     // Create class wrapper from
9883                                          // existing pointer
9884 };
9885 </PRE>
9886 </DIV>
9887 <P> When using this macro, <TT>type</TT> is restricted to a simple type
9888  name like <TT>int</TT> or <TT>float</TT>. Pointers and other
9889  complicated types are not allowed. <TT>name</TT> must be a valid
9890  identifier not already in use. When a pointer is wrapped as a class, it
9891  can be transparently passed to any function that expects the pointer.</P>
9892 <P> When combined with proxy classes, the <TT>%array_class()</TT> macro
9893  can be especially useful. For example:</P>
9894 <DIV class="code">
9895 <PRE>
9896 %module example
9897 %include &quot;carrays.i&quot;
9898 %array_class(double, doubleArray);
9899
9900 void print_array(double x[10]);
9901 </PRE>
9902 </DIV>
9903 <P> Allows you to do this:</P>
9904 <DIV class="code">
9905 <PRE>
9906 import example
9907 c = example.doubleArray(10)  # Create double[10]
9908 for i in range(0,10):
9909     c[i] = 2*i               # Assign values
9910 example.print_array(c)       # Pass to C
9911 </PRE>
9912 </DIV></DIV>
9913 <P><B> Note:</B> These macros do not encapsulate C arrays inside a
9914  special data structure or proxy. There is no bounds checking or safety
9915  of any kind. If you want this, you should consider using a special
9916  array object rather than a bare pointer.</P>
9917 <P><B> Note:</B> <TT>%array_functions()</TT> and <TT>%array_class()</TT>
9918  should not be used with types of <TT>char</TT> or <TT>char *</TT>.</P>
9919 <H3><A name="Library_nn6"></A>8.2.3 cmalloc.i</H3>
9920 <P> This module defines macros for wrapping the low-level C memory
9921  allocation functions <TT>malloc()</TT>, <TT>calloc()</TT>, <TT>
9922 realloc()</TT>, and <TT>free()</TT>.</P>
9923 <P><B> <TT>%malloc(type [,name=type])</TT></B></P>
9924 <DIV class="indent">
9925 <P> Creates a wrapper around <TT>malloc()</TT> with the following
9926  prototype:</P>
9927 <DIV class="code">
9928 <PRE>
9929 <EM>type</EM> *malloc_<EM>name</EM>(int nbytes = sizeof(<EM>type</EM>));
9930 </PRE>
9931 </DIV>
9932 <P> If <TT>type</TT> is <TT>void</TT>, then the size parameter <TT>
9933 nbytes</TT> is required. The <TT>name</TT> parameter only needs to be
9934  specified when wrapping a type that is not a valid identifier (e.g., &quot;<TT>
9935 int *</TT>&quot;, &quot;<TT>double **</TT>&quot;, etc.).</P>
9936 </DIV>
9937 <P><B> <TT>%calloc(type [,name=type])</TT></B></P>
9938 <DIV class="indent">
9939 <P> Creates a wrapper around <TT>calloc()</TT> with the following
9940  prototype:</P>
9941 <DIV class="code">
9942 <PRE>
9943 <EM>type</EM> *calloc_<EM>name</EM>(int nobj =1, int sz = sizeof(<EM>type</EM>));
9944 </PRE>
9945 </DIV>
9946 <P> If <TT>type</TT> is <TT>void</TT>, then the size parameter <TT>sz</TT>
9947  is required.</P>
9948 </DIV>
9949 <P><B> <TT>%realloc(type [,name=type])</TT></B></P>
9950 <DIV class="indent">
9951 <P> Creates a wrapper around <TT>realloc()</TT> with the following
9952  prototype:</P>
9953 <DIV class="code">
9954 <PRE>
9955 <EM>type</EM> *realloc_<EM>name</EM>(<EM>type</EM> *ptr, int nitems);
9956 </PRE>
9957 </DIV>
9958 <P> Note: unlike the C <TT>realloc()</TT>, the wrapper generated by this
9959  macro implicitly includes the size of the corresponding type. For
9960  example, <TT>realloc_int(p, 100)</TT> reallocates <TT>p</TT> so that it
9961  holds 100 integers.</P>
9962 </DIV>
9963 <P><B> <TT>%free(type [,name=type])</TT></B></P>
9964 <DIV class="indent">
9965 <P> Creates a wrapper around <TT>free()</TT> with the following
9966  prototype:</P>
9967 <DIV class="code">
9968 <PRE>
9969 void free_<EM>name</EM>(<EM>type</EM> *ptr);
9970 </PRE>
9971 </DIV></DIV>
9972 <P><B> <TT>%sizeof(type [,name=type])</TT></B></P>
9973 <DIV class="indent">
9974 <P> Creates the constant:</P>
9975 <DIV class="code">
9976 <PRE>
9977 %constant int sizeof_<EM>name</EM> = sizeof(<EM>type</EM>);
9978 </PRE>
9979 </DIV></DIV>
9980 <P><B> <TT>%allocators(type [,name=type])</TT></B></P>
9981 <DIV class="indent">
9982 <P> Generates wrappers for all five of the above operations.</P>
9983 </DIV>
9984 <P> Here is a simple example that illustrates the use of these macros:</P>
9985 <DIV class="code">
9986 <PRE>
9987 // SWIG interface
9988 %module example
9989 %include &quot;cmalloc.i&quot;
9990
9991 %malloc(int);
9992 %free(int);
9993
9994 %malloc(int *, intp);
9995 %free(int *, intp);
9996
9997 %allocators(double);
9998 </PRE>
9999 </DIV>
10000 <P> Now, in a script:</P>
10001 <DIV class="targetlang">
10002 <PRE>
10003 &gt;&gt;&gt; from example import *
10004 &gt;&gt;&gt; a = malloc_int()
10005 &gt;&gt;&gt; a
10006 '_000efa70_p_int'
10007 &gt;&gt;&gt; free_int(a)
10008 &gt;&gt;&gt; b = malloc_intp()
10009 &gt;&gt;&gt; b
10010 '_000efb20_p_p_int'
10011 &gt;&gt;&gt; free_intp(b)
10012 &gt;&gt;&gt; c = calloc_double(50)
10013 &gt;&gt;&gt; c
10014 '_000fab98_p_double'
10015 &gt;&gt;&gt; c = realloc_double(100000)
10016 &gt;&gt;&gt; free_double(c)
10017 &gt;&gt;&gt; print sizeof_double
10018 8
10019 &gt;&gt;&gt;
10020 </PRE>
10021 </DIV>
10022 <H3><A name="Library_nn7"></A>8.2.4 cdata.i</H3>
10023 <P> The <TT>cdata.i</TT> module defines functions for converting raw C
10024  data to and from strings in the target language. The primary
10025  applications of this module would be packing/unpacking of binary data
10026  structures---for instance, if you needed to extract data from a buffer.
10027  The target language must support strings with embedded binary data in
10028  order for this to work.</P>
10029 <P><B> <TT>char *cdata(void *ptr, int nbytes)</TT></B></P>
10030 <DIV class="indent">
10031 <P> Converts <TT>nbytes</TT> of data at <TT>ptr</TT> into a string. <TT>
10032 ptr</TT> can be any pointer.</P>
10033 </DIV>
10034 <P><B> <TT>void memmove(void *ptr, char *s)</TT></B></P>
10035 <DIV class="indent">
10036 <P> Copies all of the string data in <TT>s</TT> into the memory pointed
10037  to by <TT>ptr</TT>. The string may contain embedded NULL bytes. The
10038  length of the string is implicitly determined in the underlying wrapper
10039  code.</P>
10040 </DIV>
10041 <P> One use of these functions is packing and unpacking data from
10042  memory. Here is a short example:</P>
10043 <DIV class="code">
10044 <PRE>
10045 // SWIG interface
10046 %module example
10047 %include &quot;carrays.i&quot;
10048 %include &quot;cdata.i&quot;
10049
10050 %array_class(int, intArray);
10051 </PRE>
10052 </DIV>
10053 <P> Python example:</P>
10054 <DIV class="targetlang">
10055 <PRE>
10056 &gt;&gt;&gt; a = intArray(10)
10057 &gt;&gt;&gt; for i in range(0,10):
10058 ...    a[i] = i
10059 &gt;&gt;&gt; b = cdata(a,40)
10060 &gt;&gt;&gt; b
10061 '\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04
10062 \x00\x00\x00\x05\x00\x00\x00\x06\x00\x00\x00\x07\x00\x00\x00\x08\x00\x00\x00\t'
10063 &gt;&gt;&gt; c = intArray(10)
10064 &gt;&gt;&gt; memmove(c,b)
10065 &gt;&gt;&gt; print c[4]
10066 4
10067 &gt;&gt;&gt;
10068 </PRE>
10069 </DIV>
10070 <P> Since the size of data is not always known, the following macro is
10071  also defined:</P>
10072 <P><B> <TT>%cdata(type [,name=type])</TT></B></P>
10073 <DIV class="indent">
10074 <P> Generates the following function for extracting C data for a given
10075  type.</P>
10076 <DIV class="code">
10077 <PRE>
10078 char *cdata_<EM>name</EM>(type* ptr, int nitems)
10079 </PRE>
10080 </DIV>
10081 <P> <TT>nitems</TT> is the number of items of the given type to extract.</P>
10082 </DIV>
10083 <P><B> Note:</B> These functions provide direct access to memory and can
10084  be used to overwrite data. Clearly they are unsafe.</P>
10085 <H2><A name="Library_nn8"></A>8.3 C String Handling</H2>
10086 <P> A common problem when working with C programs is dealing with
10087  functions that manipulate raw character data using <TT>char *</TT>. In
10088  part, problems arise because there are different interpretations of <TT>
10089 char *</TT>---it could be a NULL-terminated string or it could point to
10090  binary data. Moreover, functions that manipulate raw strings may mutate
10091  data, perform implicit memory allocations, or utilize fixed-sized
10092  buffers.</P>
10093 <P> The problems (and perils) of using <TT>char *</TT> are well-known.
10094  However, SWIG is not in the business of enforcing morality. The modules
10095  in this section provide basic functionality for manipulating raw C
10096  strings.</P>
10097 <H3><A name="Library_nn9"></A>8.3.1 Default string handling</H3>
10098 <P> Suppose you have a C function with this prototype:</P>
10099 <DIV class="code">
10100 <PRE>
10101 char *foo(char *s);
10102 </PRE>
10103 </DIV>
10104 <P> The default wrapping behavior for this function is to set <TT>s</TT>
10105  to a raw <TT>char *</TT> that refers to the internal string data in the
10106  target language. In other words, if you were using a language like Tcl,
10107  and you wrote this,</P>
10108 <DIV class="code">
10109 <PRE>
10110 % foo Hello
10111 </PRE>
10112 </DIV>
10113 <P> then <TT>s</TT> would point to the representation of &quot;Hello&quot; inside
10114  the Tcl interpreter. When returning a <TT>char *</TT>, SWIG assumes
10115  that it is a NULL-terminated string and makes a copy of it. This gives
10116  the target language its own copy of the result.</P>
10117 <P> There are obvious problems with the default behavior. First, since a
10118  <TT>char *</TT> argument points to data inside the target language, it
10119  is<B> NOT</B> safe for a function to modify this data (doing so may
10120  corrupt the interpreter and lead to a crash). Furthermore, the default
10121  behavior does not work well with binary data. Instead, strings are
10122  assumed to be NULL-terminated.</P>
10123 <H3><A name="Library_nn10"></A>8.3.2 Passing binary data</H3>
10124 <P> If you have a function that expects binary data,</P>
10125 <DIV class="code">
10126 <PRE>
10127 int parity(char *str, int len, int initial);
10128 </PRE>
10129 </DIV>
10130 <P> you can wrap the parameters <TT>(char *str, int len)</TT> as a
10131  single argument using a typemap. Just do this:</P>
10132 <DIV class="code">
10133 <PRE>
10134 %apply (char *STRING, int LENGTH) { (char *str, int len) };
10135 ...
10136 int parity(char *str, int len, int initial);
10137 </PRE>
10138 </DIV>
10139 <P> Now, in the target language, you can use binary string data like
10140  this:</P>
10141 <DIV class="code">
10142 <PRE>
10143 &gt;&gt;&gt; s = &quot;H\x00\x15eg\x09\x20&quot;
10144 &gt;&gt;&gt; parity(s,0)
10145 </PRE>
10146 </DIV>
10147 <P> In the wrapper function, the passed string will be expanded to a
10148  pointer and length parameter.</P>
10149 <H3><A name="Library_nn11"></A>8.3.3 Using %newobject to release memory</H3>
10150 <P> If you have a function that allocates memory like this,</P>
10151 <DIV class="code">
10152 <PRE>
10153 char *foo() {
10154    char *result = (char *) malloc(...);
10155    ...
10156    return result;
10157 }
10158 </PRE>
10159 </DIV>
10160 <P> then the SWIG generated wrappers will have a memory leak--the
10161  returned data will be copied into a string object and the old contents
10162  ignored.</P>
10163 <P> To fix the memory leak, use the <TT>%newobject</TT> directive.</P>
10164 <DIV class="code">
10165 <PRE>
10166 %newobject foo;
10167 ...
10168 char *foo();
10169 </PRE>
10170 </DIV>
10171 <P> This will release the result.</P>
10172 <H3><A name="Library_nn12"></A>8.3.4 cstring.i</H3>
10173 <P> The <TT>cstring.i</TT> library file provides a collection of macros
10174  for dealing with functions that either mutate string arguments or which
10175  try to output string data through their arguments. An example of such a
10176  function might be this rather questionable implementation:</P>
10177 <DIV class="code">
10178 <PRE>
10179 void get_path(char *s) {
10180     // Potential buffer overflow---uh, oh.
10181     sprintf(s,&quot;%s/%s&quot;, base_directory, sub_directory);
10182 }
10183 ...
10184 // Somewhere else in the C program
10185 {
10186     char path[1024];
10187     ...
10188     get_path(path);
10189     ...
10190 }
10191 </PRE>
10192 </DIV>
10193 <P> (Off topic rant: If your program really has functions like this, you
10194  would be well-advised to replace them with safer alternatives involving
10195  bounds checking).</P>
10196 <P> The macros defined in this module all expand to various combinations
10197  of typemaps. Therefore, the same pattern matching rules and ideas
10198  apply.</P>
10199 <P><B> %cstring_bounded_output(parm, maxsize)</B></P>
10200 <DIV class="indent">
10201 <P> Turns parameter <TT><EM>parm</EM></TT> into an output value. The
10202  output string is assumed to be NULL-terminated and smaller than <TT><EM>
10203 maxsize</EM></TT> characters. Here is an example:</P>
10204 <DIV class="code">
10205 <PRE>
10206 %cstring_bounded_output(char *path, 1024);
10207 ...
10208 void get_path(char *path);
10209 </PRE>
10210 </DIV>
10211 <P> In the target language:</P>
10212 <DIV class="targetlang">
10213 <PRE>
10214 &gt;&gt;&gt; get_path()
10215 /home/beazley/packages/Foo/Bar
10216 &gt;&gt;&gt;
10217 </PRE>
10218 </DIV>
10219 <P> Internally, the wrapper function allocates a small buffer (on the
10220  stack) of the requested size and passes it as the pointer value. Data
10221  stored in the buffer is then returned as a function return value. If
10222  the function already returns a value, then the return value and the
10223  output string are returned together (multiple return values).<B> If
10224  more than <TT><EM>maxsize</EM></TT> bytes are written, your program
10225  will crash with a buffer overflow!</B></P>
10226 </DIV>
10227 <P><B> %cstring_chunk_output(parm, chunksize)</B></P>
10228 <DIV class="indent">
10229 <P> Turns parameter <TT><EM>parm</EM></TT> into an output value. The
10230  output string is always <TT><EM>chunksize</EM></TT> and may contain
10231  binary data. Here is an example:</P>
10232 <DIV class="code">
10233 <PRE>
10234 %cstring_chunk_output(char *packet, PACKETSIZE);
10235 ...
10236 void get_packet(char *packet);
10237 </PRE>
10238 </DIV>
10239 <P> In the target language:</P>
10240 <DIV class="targetlang">
10241 <PRE>
10242 &gt;&gt;&gt; get_packet()
10243 '\xa9Y:\xf6\xd7\xe1\x87\xdbH;y\x97\x7f\xd3\x99\x14V\xec\x06\xea\xa2\x88'
10244 &gt;&gt;&gt;
10245 </PRE>
10246 </DIV>
10247 <P> This macro is essentially identical to <TT>%cstring_bounded_output</TT>
10248 . The only difference is that the result is always <TT><EM>chunksize</EM>
10249 </TT> characters. Furthermore, the result can contain binary data.<B> If
10250  more than <TT><EM>maxsize</EM></TT> bytes are written, your program
10251  will crash with a buffer overflow!</B></P>
10252 </DIV>
10253 <P><B> %cstring_bounded_mutable(parm, maxsize)</B></P>
10254 <DIV class="indent">
10255 <P> Turns parameter <TT><EM>parm</EM></TT> into a mutable string
10256  argument. The input string is assumed to be NULL-terminated and smaller
10257  than <TT><EM>maxsize</EM></TT> characters. The output string is also
10258  assumed to be NULL-terminated and less than <TT><EM>maxsize</EM></TT>
10259  characters.</P>
10260 <DIV class="code">
10261 <PRE>
10262 %cstring_bounded_mutable(char *ustr, 1024);
10263 ...
10264 void make_upper(char *ustr);
10265 </PRE>
10266 </DIV>
10267 <P> In the target language:</P>
10268 <DIV class="targetlang">
10269 <PRE>
10270 &gt;&gt;&gt; make_upper(&quot;hello world&quot;)
10271 'HELLO WORLD'
10272 &gt;&gt;&gt;
10273 </PRE>
10274 </DIV>
10275 <P> Internally, this macro is almost exactly the same as <TT>
10276 %cstring_bounded_output</TT>. The only difference is that the parameter
10277  accepts an input value that is used to initialize the internal buffer.
10278  It is important to emphasize that this function does not mutate the
10279  string value passed---instead it makes a copy of the input value,
10280  mutates it, and returns it as a result.<B> If more than <TT><EM>maxsize</EM>
10281 </TT> bytes are written, your program will crash with a buffer overflow!</B>
10282 </P>
10283 </DIV>
10284 <P><B> %cstring_mutable(parm [, expansion])</B></P>
10285 <DIV class="indent">
10286 <P> Turns parameter <TT><EM>parm</EM></TT> into a mutable string
10287  argument. The input string is assumed to be NULL-terminated. An
10288  optional parameter <TT><EM>expansion</EM></TT> specifies the number of
10289  extra characters by which the string might grow when it is modified.
10290  The output string is assumed to be NULL-terminated and less than the
10291  size of the input string plus any expansion characters.</P>
10292 <DIV class="code">
10293 <PRE>
10294 %cstring_mutable(char *ustr);
10295 ...
10296 void make_upper(char *ustr);
10297
10298 %cstring_mutable(char *hstr, HEADER_SIZE);
10299 ...
10300 void attach_header(char *hstr);
10301 </PRE>
10302 </DIV>
10303 <P> In the target language:</P>
10304 <DIV class="targetlang">
10305 <PRE>
10306 &gt;&gt;&gt; make_upper(&quot;hello world&quot;)
10307 'HELLO WORLD'
10308 &gt;&gt;&gt; attach_header(&quot;Hello world&quot;)
10309 'header: Hello world'
10310 &gt;&gt;&gt;
10311 </PRE>
10312 </DIV>
10313 <P> This macro differs from <TT>%cstring_bounded_mutable()</TT> in that
10314  a buffer is dynamically allocated (on the heap using <TT>malloc/new</TT>
10315 ). This buffer is always large enough to store a copy of the input value
10316  plus any expansion bytes that might have been requested. It is
10317  important to emphasize that this function does not directly mutate the
10318  string value passed---instead it makes a copy of the input value,
10319  mutates it, and returns it as a result.<B> If the function expands the
10320  result by more than <TT><EM>expansion</EM></TT> extra bytes, then the
10321  program will crash with a buffer overflow!</B></P>
10322 </DIV>
10323 <P><B> %cstring_output_maxsize(parm, maxparm)</B></P>
10324 <DIV class="indent">
10325 <P> This macro is used to handle bounded character output functions
10326  where both a <TT>char *</TT> and a maximum length parameter are
10327  provided. As input, a user simply supplies the maximum length. The
10328  return value is assumed to be a NULL-terminated string.</P>
10329 <DIV class="code">
10330 <PRE>
10331 %cstring_output_maxsize(char *path, int maxpath);
10332 ...
10333 void get_path(char *path, int maxpath);
10334 </PRE>
10335 </DIV>
10336 <P> In the target language:</P>
10337 <DIV class="targetlang">
10338 <PRE>
10339 &gt;&gt;&gt; get_path(1024)
10340 '/home/beazley/Packages/Foo/Bar'
10341 &gt;&gt;&gt;
10342 </PRE>
10343 </DIV>
10344 <P> This macro provides a safer alternative for functions that need to
10345  write string data into a buffer. User supplied buffer size is used to
10346  dynamically allocate memory on heap. Results are placed into that
10347  buffer and returned as a string object.</P>
10348 </DIV>
10349 <P><B> %cstring_output_withsize(parm, maxparm)</B></P>
10350 <DIV class="indent">
10351 <P> This macro is used to handle bounded character output functions
10352  where both a <TT>char *</TT> and a pointer <TT>int *</TT> are passed.
10353  Initially, the <TT>int *</TT> parameter points to a value containing
10354  the maximum size. On return, this value is assumed to contain the
10355  actual number of bytes. As input, a user simply supplies the maximum
10356  length. The output value is a string that may contain binary data.</P>
10357 <DIV class="code">
10358 <PRE>
10359 %cstring_output_withsize(char *data, int *maxdata);
10360 ...
10361 void get_data(char *data, int *maxdata);
10362 </PRE>
10363 </DIV>
10364 <P> In the target language:</P>
10365 <DIV class="targetlang">
10366 <PRE>
10367 &gt;&gt;&gt; get_data(1024)
10368 'x627388912'
10369 &gt;&gt;&gt; get_data(1024)
10370 'xyzzy'
10371 &gt;&gt;&gt;
10372 </PRE>
10373 </DIV>
10374 <P> This macro is a somewhat more powerful version of <TT>
10375 %cstring_output_chunk()</TT>. Memory is dynamically allocated and can be
10376  arbitrary large. Furthermore, a function can control how much data is
10377  actually returned by changing the value of the <TT>maxparm</TT>
10378  argument.</P>
10379 </DIV>
10380 <P><B> %cstring_output_allocate(parm, release)</B></P>
10381 <DIV class="indent">
10382 <P> This macro is used to return strings that are allocated within the
10383  program and returned in a parameter of type <TT>char **</TT>. For
10384  example:</P>
10385 <DIV class="code">
10386 <PRE>
10387 void foo(char **s) {
10388     *s = (char *) malloc(64);
10389     sprintf(*s, &quot;Hello world\n&quot;);
10390 }
10391 </PRE>
10392 </DIV>
10393 <P> The returned string is assumed to be NULL-terminated. <TT><EM>
10394 release</EM></TT> specifies how the allocated memory is to be released
10395  (if applicable). Here is an example:</P>
10396 <DIV class="code">
10397 <PRE>
10398 %cstring_output_allocate(char **s, free(*$1));
10399 ...
10400 void foo(char **s);
10401 </PRE>
10402 </DIV>
10403 <P> In the target language:</P>
10404 <DIV class="targetlang">
10405 <PRE>
10406 &gt;&gt;&gt; foo()
10407 'Hello world\n'
10408 &gt;&gt;&gt;
10409 </PRE>
10410 </DIV></DIV>
10411 <P><B> %cstring_output_allocate_size(parm, szparm, release)</B></P>
10412 <DIV class="indent">
10413 <P> This macro is used to return strings that are allocated within the
10414  program and returned in two parameters of type <TT>char **</TT> and <TT>
10415 int *</TT>. For example:</P>
10416 <DIV class="code">
10417 <PRE>
10418 void foo(char **s, int *sz) {
10419     *s = (char *) malloc(64);
10420     *sz = 64;
10421     // Write some binary data
10422     ...
10423 }
10424 </PRE>
10425 </DIV>
10426 <P> The returned string may contain binary data. <TT><EM>release</EM></TT>
10427  specifies how the allocated memory is to be released (if applicable).
10428  Here is an example:</P>
10429 <DIV class="code">
10430 <PRE>
10431 %cstring_output_allocate_size(char **s, int *slen, free(*$1));
10432 ...
10433 void foo(char **s, int *slen);
10434 </PRE>
10435 </DIV>
10436 <P> In the target language:</P>
10437 <DIV class="targetlang">
10438 <PRE>
10439 &gt;&gt;&gt; foo()
10440 '\xa9Y:\xf6\xd7\xe1\x87\xdbH;y\x97\x7f\xd3\x99\x14V\xec\x06\xea\xa2\x88'
10441 &gt;&gt;&gt;
10442 </PRE>
10443 </DIV>
10444 <P> This is the safest and most reliable way to return binary string
10445  data in SWIG. If you have functions that conform to another prototype,
10446  you might consider wrapping them with a helper function. For example,
10447  if you had this:</P>
10448 <DIV class="code">
10449 <PRE>
10450 char  *get_data(int *len);
10451 </PRE>
10452 </DIV>
10453 <P> You could wrap it with a function like this:</P>
10454 <DIV class="code">
10455 <PRE>
10456 void my_get_data(char **result, int *len) {
10457    *result = get_data(len);
10458 }
10459 </PRE>
10460 </DIV></DIV>
10461 <P><B> Comments:</B></P>
10462 <UL>
10463 <LI>Support for the <TT>cstring.i</TT> module depends on the target
10464  language. Not all SWIG modules currently support this library.</LI>
10465 <LI>Reliable handling of raw C strings is a delicate topic. There are
10466  many ways to accomplish this in SWIG. This library provides support for
10467  a few common techniques.</LI>
10468 <LI>If used in C++, this library uses <TT>new</TT> and <TT>delete []</TT>
10469  for memory allocation. If using ANSI C, the library uses <TT>malloc()</TT>
10470  and <TT>free()</TT>.</LI>
10471 <LI>Rather than manipulating <TT>char *</TT> directly, you might
10472  consider using a special string structure or class instead.</LI>
10473 </UL>
10474 <H2><A name="Library_stl_cpp_library"></A>8.4 STL/C++ Library</H2>
10475 <P> The library modules in this section provide access to parts of the
10476  standard C++ library including the STL. SWIG support for the STL is an
10477  ongoing effort. Support is quite comprehensive for some language
10478  modules but some of the lesser used modules do not have quite as much
10479  library code written.</P>
10480 <P> The following table shows which C++ classes are supported and the
10481  equivalent SWIG interface library file for the C++ library.</P>
10482 <TABLE BORDER summary="SWIG C++ library files">
10483 <TR VALIGN="TOP"><TD><B>C++ class</B></TD><TD><B>C++ Library file</B></TD><TD>
10484 <B>SWIG Interface library file</B></TD></TR>
10485 <TR><TD>std::deque</TD><TD>deque</TD><TD>std_deque.i</TD></TR>
10486 <TR><TD>std::list</TD><TD>list</TD><TD>std_list.i</TD></TR>
10487 <TR><TD>std::map</TD><TD>map</TD><TD>std_map.i</TD></TR>
10488 <TR><TD>std::pair</TD><TD>utility</TD><TD>std_pair.i</TD></TR>
10489 <TR><TD>std::set</TD><TD>set</TD><TD>std_set.i</TD></TR>
10490 <TR><TD>std::string</TD><TD>string</TD><TD>std_string.i</TD></TR>
10491 <TR><TD>std::vector</TD><TD>vector</TD><TD>std_vector.i</TD></TR>
10492 </TABLE>
10493 <P> The list is by no means complete; some language modules support a
10494  subset of the above and some support additional STL classes. Please
10495  look for the library files in the appropriate language library
10496  directory.</P>
10497 <H3><A name="Library_nn14"></A>8.4.1 std_string.i</H3>
10498 <P> The <TT>std_string.i</TT> library provides typemaps for converting
10499  C++ <TT>std::string</TT> objects to and from strings in the target
10500  scripting language. For example:</P>
10501 <DIV class="code">
10502 <PRE>
10503 %module example
10504 %include &quot;std_string.i&quot;
10505
10506 std::string foo();
10507 void        bar(const std::string &amp;x);
10508 </PRE>
10509 </DIV>
10510 <P> In the target language:</P>
10511 <DIV class="targetlang">
10512 <PRE>
10513 x = foo();                # Returns a string object
10514 bar(&quot;Hello World&quot;);       # Pass string as std::string
10515 </PRE>
10516 </DIV>
10517 <P> A common problem that people encounter is that of classes/structures
10518  containing a <TT>std::string</TT>. This can be overcome by defining a
10519  typemap. For example:</P>
10520 <DIV class="code">
10521 <PRE>
10522 %module example
10523 %include &quot;std_string.i&quot;
10524
10525 %apply const std::string&amp; {std::string* foo};
10526
10527 struct my_struct
10528 {
10529   std::string foo;
10530 };
10531 </PRE>
10532 </DIV>
10533 <P> In the target language:</P>
10534 <DIV class="targetlang">
10535 <PRE>
10536 x = my_struct();
10537 x.foo=&quot;Hello World&quot;;      # assign with string
10538 print x.foo;              # print as string
10539 </PRE>
10540 </DIV>
10541 <P> This module only supports types <TT>std::string</TT> and <TT>const
10542  std::string &amp;</TT>. Pointers and non-const references are left
10543  unmodified and returned as SWIG pointers.</P>
10544 <P> This library file is fully aware of C++ namespaces. If you export <TT>
10545 std::string</TT> or rename it with a typedef, make sure you include
10546  those declarations in your interface. For example:</P>
10547 <DIV class="code">
10548 <PRE>
10549 %module example
10550 %include &quot;std_string.i&quot;
10551
10552 using namespace std;
10553 typedef std::string String;
10554 ...
10555 void foo(string s, const String &amp;t);     // std_string typemaps still applied
10556 </PRE>
10557 </DIV>
10558 <P><B> Note:</B> The <TT>std_string</TT> library is incompatible with
10559  Perl on some platforms. We're looking into it.</P>
10560 <H3><A name="Library_nn15"></A>8.4.2 std_vector.i</H3>
10561 <P> The <TT>std_vector.i</TT> library provides support for the C++ <TT>
10562 vector</TT> class in the STL. Using this library involves the use of the
10563  <TT>%template</TT> directive. All you need to do is to instantiate
10564  different versions of <TT>vector</TT> for the types that you want to
10565  use. For example:</P>
10566 <DIV class="code">
10567 <PRE>
10568 %module example
10569 %include &quot;std_vector.i&quot;
10570
10571 namespace std {
10572    %template(vectori) vector&lt;int&gt;;
10573    %template(vectord) vector&lt;double&gt;;
10574 };
10575 </PRE>
10576 </DIV>
10577 <P> When a template <TT>vector&lt;X&gt;</TT> is instantiated a number of
10578  things happen:</P>
10579 <UL>
10580 <LI>A class that exposes the C++ API is created in the target language .
10581  This can be used to create objects, invoke methods, etc. This class is
10582  currently a subset of the real STL vector class.</LI>
10583 <LI>Input typemaps are defined for <TT>vector&lt;X&gt;</TT>, <TT>const
10584  vector&lt;X&gt; &amp;</TT>, and <TT>const vector&lt;X&gt; *</TT>. For each of these, a
10585  pointer <TT>vector&lt;X&gt; *</TT> may be passed or a native list object in
10586  the target language.</LI>
10587 <LI>An output typemap is defined for <TT>vector&lt;X&gt;</TT>. In this case,
10588  the values in the vector are expanded into a list object in the target
10589  language.</LI>
10590 <LI>For all other variations of the type, the wrappers expect to receive
10591  a <TT>vector&lt;X&gt; *</TT> object in the usual manner.</LI>
10592 <LI>An exception handler for <TT>std::out_of_range</TT> is defined.</LI>
10593 <LI>Optionally, special methods for indexing, item retrieval, slicing,
10594  and element assignment may be defined. This depends on the target
10595  language.</LI>
10596 </UL>
10597 <P> To illustrate the use of this library, consider the following
10598  functions:</P>
10599 <DIV class="code">
10600 <PRE>
10601 /* File : example.h */
10602
10603 #include &lt;vector&gt;
10604 #include &lt;algorithm&gt;
10605 #include &lt;functional&gt;
10606 #include &lt;numeric&gt;
10607
10608 double average(std::vector&lt;int&gt; v) {
10609     return std::accumulate(v.begin(),v.end(),0.0)/v.size();
10610 }
10611
10612 std::vector&lt;double&gt; half(const std::vector&lt;double&gt;&amp; v) {
10613     std::vector&lt;double&gt; w(v);
10614     for (unsigned int i=0; i&lt;w.size(); i++)
10615         w[i] /= 2.0;
10616     return w;
10617 }
10618
10619 void halve_in_place(std::vector&lt;double&gt;&amp; v) {
10620     std::transform(v.begin(),v.end(),v.begin(),
10621                    std::bind2nd(std::divides&lt;double&gt;(),2.0));
10622 }
10623 </PRE>
10624 </DIV>
10625 <P> To wrap with SWIG, you might write the following:</P>
10626 <DIV class="code">
10627 <PRE>
10628 %module example
10629 %{
10630 #include &quot;example.h&quot;
10631 %}
10632
10633 %include &quot;std_vector.i&quot;
10634 // Instantiate templates used by example
10635 namespace std {
10636    %template(IntVector) vector&lt;int&gt;;
10637    %template(DoubleVector) vector&lt;double&gt;;
10638 }
10639
10640 // Include the header file with above prototypes
10641 %include &quot;example.h&quot;
10642 </PRE>
10643 </DIV>
10644 <P> Now, to illustrate the behavior in the scripting interpreter,
10645  consider this Python example:</P>
10646 <DIV class="targetlang">
10647 <PRE>
10648 &gt;&gt;&gt; from example import *
10649 &gt;&gt;&gt; iv = IntVector(4)         # Create an vector&lt;int&gt;
10650 &gt;&gt;&gt; for i in range(0,4):
10651 ...      iv[i] = i
10652 &gt;&gt;&gt; average(iv)               # Call method
10653 1.5
10654 &gt;&gt;&gt; average([0,1,2,3])        # Call with list
10655 1.5
10656 &gt;&gt;&gt; half([1,2,3])             # Half a list
10657 (0.5,1.0,1.5)
10658 &gt;&gt;&gt; halve_in_place([1,2,3])   # Oops
10659 Traceback (most recent call last):
10660   File &quot;&lt;stdin&gt;&quot;, line 1, in ?
10661 TypeError: Type error. Expected _p_std__vectorTdouble_t
10662 &gt;&gt;&gt; dv = DoubleVector(4)
10663 &gt;&gt;&gt; for i in range(0,4):
10664 ...       dv[i] = i
10665 &gt;&gt;&gt; halve_in_place(dv)       # Ok
10666 &gt;&gt;&gt; for i in dv:
10667 ...       print i
10668 ...
10669 0.0
10670 0.5
10671 1.0
10672 1.5
10673 &gt;&gt;&gt; dv[20] = 4.5
10674 Traceback (most recent call last):
10675   File &quot;&lt;stdin&gt;&quot;, line 1, in ?
10676   File &quot;example.py&quot;, line 81, in __setitem__
10677     def __setitem__(*args): return apply(examplec.DoubleVector___setitem__,args)
10678 IndexError: vector index out of range
10679 &gt;&gt;&gt;
10680 </PRE>
10681 </DIV>
10682 <P> This library module is fully aware of C++ namespaces. If you use
10683  vectors with other names, make sure you include the appropriate <TT>
10684 using</TT> or typedef directives. For example:</P>
10685 <DIV class="code">
10686 <PRE>
10687 %include &quot;std_vector.i&quot;
10688
10689 namespace std {
10690     %template(IntVector) vector&lt;int&gt;;
10691 }
10692
10693 using namespace std;
10694 typedef std::vector Vector;
10695
10696 void foo(vector&lt;int&gt; *x, const Vector &amp;x);
10697 </PRE>
10698 </DIV>
10699 <P><B> Note:</B> This module makes use of several advanced SWIG features
10700  including templatized typemaps and template partial specialization. If
10701  you are trying to wrap other C++ code with templates, you might look at
10702  the code contained in <TT>std_vector.i</TT>. Alternatively, you can
10703  show them the code if you want to make their head explode.</P>
10704 <P><B> Note:</B> This module is defined for all SWIG target languages.
10705  However argument conversion details and the public API exposed to the
10706  interpreter vary.</P>
10707 <P><B> Note:</B> <TT>std_vector.i</TT> was written by Luigi &quot;The
10708  Amazing&quot; Ballabio.</P>
10709 <H3><A name="Library_stl_exceptions"></A>8.4.3 STL exceptions</H3>
10710 <P> Many of the STL wrapper functions add parameter checking and will
10711  throw a language dependent error/exception should the values not be
10712  valid. The classic example is array bounds checking. The library
10713  wrappers are written to throw a C++ exception in the case of error. The
10714  C++ exception in turn gets converted into an appropriate
10715  error/exception for the target language. By and large this handling
10716  should not need customising, however, customisation can easily be
10717  achieved by supplying appropriate &quot;throws&quot; typemaps. For example:</P>
10718 <DIV class="code">
10719 <PRE>
10720 %module example
10721 %include &quot;std_vector.i&quot;
10722 %typemap(throws) std::out_of_range {
10723   // custom exception handler
10724 }
10725 %template(VectInt) std::vector&lt;int&gt;;
10726 </PRE>
10727 </DIV>
10728 <P> The custom exception handler might, for example, log the exception
10729  then convert it into a specific error/exception for the target
10730  language.</P>
10731 <P> When using the STL it is advisable to add in an exception handler to
10732  catch all STL exceptions. The <TT>%exception</TT> directive can be used
10733  by placing the following code before any other methods or libraries to
10734  be wrapped:</P>
10735 <DIV class="code">
10736 <PRE>
10737 %include &quot;exception.i&quot;
10738
10739 %exception {
10740   try {
10741     $action
10742   } catch (const std::exception&amp; e) {
10743     SWIG_exception(SWIG_RuntimeError, e.what());
10744   }
10745 }
10746 </PRE>
10747 </DIV>
10748 <P> Any thrown STL exceptions will then be gracefully handled instead of
10749  causing a crash.</P>
10750 <H2><A name="Library_nn16"></A>8.5 Utility Libraries</H2>
10751 <H3><A name="Library_nn17"></A>8.5.1 exception.i</H3>
10752 <P> The <TT>exception.i</TT> library provides a language-independent
10753  function for raising a run-time exception in the target language. This
10754  library is largely used by the SWIG library writers. If possible, use
10755  the error handling scheme available to your target language as there is
10756  greater flexibility in what errors/exceptions can be thrown.</P>
10757 <P><B> <TT>SWIG_exception(int code, const char *message)</TT></B></P>
10758 <DIV class="indent">
10759 <P> Raises an exception in the target language. <TT>code</TT> is one of
10760  the following symbolic constants:</P>
10761 <DIV class="code">
10762 <PRE>
10763 SWIG_MemoryError
10764 SWIG_IOError
10765 SWIG_RuntimeError
10766 SWIG_IndexError
10767 SWIG_TypeError
10768 SWIG_DivisionByZero
10769 SWIG_OverflowError
10770 SWIG_SyntaxError
10771 SWIG_ValueError
10772 SWIG_SystemError
10773 </PRE>
10774 </DIV>
10775 <P> <TT>message</TT> is a string indicating more information about the
10776  problem.</P>
10777 </DIV>
10778 <P> The primary use of this module is in writing language-independent
10779  exception handlers. For example:</P>
10780 <DIV class="code">
10781 <PRE>
10782 %include &quot;exception.i&quot;
10783 %exception std::vector::getitem {
10784     try {
10785         $action
10786     } catch (std::out_of_range&amp; e) {
10787         SWIG_exception(SWIG_IndexError,const_cast&lt;char*&gt;(e.what()));
10788     }
10789 }
10790 </PRE>
10791 </DIV><HR NOSHADE>
10792 <H1><A name="Arguments"></A>9 Argument Handling</H1>
10793
10794 <!-- INDEX -->
10795 <DIV class="sectiontoc">
10796 <UL>
10797 <LI><A href="#Arguments_nn2">The typemaps.i library</A>
10798 <UL>
10799 <LI><A href="#Arguments_nn3">Introduction</A></LI>
10800 <LI><A href="#Arguments_nn4">Input parameters</A></LI>
10801 <LI><A href="#Arguments_nn5">Output parameters</A></LI>
10802 <LI><A href="#Arguments_nn6">Input/Output parameters</A></LI>
10803 <LI><A href="#Arguments_nn7">Using different names</A></LI>
10804 </UL>
10805 </LI>
10806 <LI><A href="#Arguments_nn8">Applying constraints to input values</A>
10807 <UL>
10808 <LI><A href="#Arguments_nn9">Simple constraint example</A></LI>
10809 <LI><A href="#Arguments_nn10">Constraint methods</A></LI>
10810 <LI><A href="#Arguments_nn11">Applying constraints to new datatypes</A></LI>
10811 </UL>
10812 </LI>
10813 </UL>
10814 </DIV>
10815 <!-- INDEX -->
10816 <P> In Chapter 3, SWIG's treatment of basic datatypes and pointers was
10817  described. In particular, primitive types such as <TT>int</TT> and <TT>
10818 double</TT> are mapped to corresponding types in the target language.
10819  For everything else, pointers are used to refer to structures, classes,
10820  arrays, and other user-defined datatypes. However, in certain
10821  applications it is desirable to change SWIG's handling of a specific
10822  datatype. For example, you might want to return multiple values through
10823  the arguments of a function. This chapter describes some of the
10824  techniques for doing this.</P>
10825 <H2><A name="Arguments_nn2"></A>9.1 The typemaps.i library</H2>
10826 <P> This section describes the <TT>typemaps.i</TT> library
10827  file--commonly used to change certain properties of argument
10828  conversion.</P>
10829 <H3><A name="Arguments_nn3"></A>9.1.1 Introduction</H3>
10830 <P> Suppose you had a C function like this:</P>
10831 <DIV class="code">
10832 <PRE>
10833 void add(double a, double b, double *result) {
10834         *result = a + b;
10835 }
10836 </PRE>
10837 </DIV>
10838 <P> From reading the source code, it is clear that the function is
10839  storing a value in the <TT>double *result</TT> parameter. However,
10840  since SWIG does not examine function bodies, it has no way to know that
10841  this is the underlying behavior.</P>
10842 <P> One way to deal with this is to use the <TT>typemaps.i</TT> library
10843  file and write interface code like this:</P>
10844 <DIV class="code">
10845 <PRE>
10846 // Simple example using typemaps
10847 %module example
10848 %include &quot;typemaps.i&quot;
10849
10850 %apply double *OUTPUT { double *result };
10851 %inlne %{
10852 extern void add(double a, double b, double *result);
10853 %}
10854 </PRE>
10855 </DIV>
10856 <P> The <TT>%apply</TT> directive tells SWIG that you are going to apply
10857  a special type handling rule to a type. The &quot;<TT>double *OUTPUT</TT>&quot;
10858  specification is the name of a rule that defines how to return an
10859  output value from an argument of type <TT>double *</TT>. This rule gets
10860  applied to all of the datatypes listed in curly braces-- in this case &quot;<TT>
10861 double *result</TT>&quot;.</P>
10862 <P> When the resulting module is created, you can now use the function
10863  like this (shown for Python):</P>
10864 <DIV class="targetlang">
10865 <PRE>
10866 &gt;&gt;&gt; a = add(3,4)
10867 &gt;&gt;&gt; print a
10868 7
10869 &gt;&gt;&gt;
10870 </PRE>
10871 </DIV>
10872 <P> In this case, you can see how the output value normally returned in
10873  the third argument has magically been transformed into a function
10874  return value. Clearly this makes the function much easier to use since
10875  it is no longer necessary to manufacture a special <TT>double *</TT>
10876  object and pass it to the function somehow.</P>
10877 <P> Once a typemap has been applied to a type, it stays in effect for
10878  all future occurrences of the type and name. For example, you could
10879  write the following:</P>
10880 <DIV class="code">
10881 <PRE>
10882 %module example
10883 %include &quot;typemaps.i&quot;
10884
10885 %apply double *OUTPUT { double *result };
10886
10887 %inline %{
10888 extern void add(double a, double b, double *result);
10889 extern void sub(double a, double b, double *result);
10890 extern void mul(double a, double b, double *result);
10891 extern void div(double a, double b, double *result);
10892 %}
10893 ...
10894 </PRE>
10895 </DIV>
10896 <P> In this case, the <TT>double *OUTPUT</TT> rule is applied to all of
10897  the functions that follow.</P>
10898 <P> Typemap transformations can even be extended to multiple return
10899  values. For example, consider this code:</P>
10900 <DIV class="code">
10901 <PRE>
10902 %include &quot;typemaps.i&quot;
10903 %apply int *OUTPUT { int *width, int *height };
10904
10905 // Returns a pair (width,height)
10906 void getwinsize(int winid, int *width, int *height);
10907 </PRE>
10908 </DIV>
10909 <P> In this case, the function returns multiple values, allowing it to
10910  be used like this:</P>
10911 <DIV class="targetlang">
10912 <PRE>
10913 &gt;&gt;&gt; w,h = genwinsize(wid)
10914 &gt;&gt;&gt; print w
10915 400
10916 &gt;&gt;&gt; print h
10917 300
10918 &gt;&gt;&gt;
10919 </PRE>
10920 </DIV>
10921 <P> It should also be noted that although the <TT>%apply</TT> directive
10922  is used to associate typemap rules to datatypes, you can also use the
10923  rule names directly in arguments. For example, you could write this:</P>
10924 <DIV class="code">
10925 <PRE>
10926 // Simple example using typemaps
10927 %module example
10928 %include &quot;typemaps.i&quot;
10929
10930 %{
10931 extern void add(double a, double b, double *OUTPUT);
10932 %}
10933 extern void add(double a, double b, double *OUTPUT);
10934 </PRE>
10935 </DIV>
10936 <P> Typemaps stay in effect until they are explicitly deleted or
10937  redefined to something else. To clear a typemap, the <TT>%clear</TT>
10938  directive should be used. For example:</P>
10939 <DIV class="code">
10940 <PRE>
10941 %clear double *result;      // Remove all typemaps for double *result
10942 </PRE>
10943 </DIV>
10944 <H3><A name="Arguments_nn4"></A>9.1.2 Input parameters</H3>
10945 <P> The following typemaps instruct SWIG that a pointer really only
10946  holds a single input value:</P>
10947 <DIV class="code">
10948 <PRE>
10949 int *INPUT              
10950 short *INPUT
10951 long *INPUT
10952 unsigned int *INPUT
10953 unsigned short *INPUT
10954 unsigned long *INPUT
10955 double *INPUT
10956 float *INPUT
10957 </PRE>
10958 </DIV>
10959 <P> When used, it allows values to be passed instead of pointers. For
10960  example, consider this function:</P>
10961 <DIV class="code">
10962 <PRE>
10963 double add(double *a, double *b) {
10964         return *a+*b;
10965 }
10966 </PRE>
10967 </DIV>
10968 <P> Now, consider this SWIG interface:</P>
10969 <DIV class="code">
10970 <PRE>
10971 %module example
10972 %include &quot;typemaps.i&quot;
10973 ...
10974 %{
10975 extern double add(double *, double *);
10976 %}
10977 extern double add(double *INPUT, double *INPUT);
10978
10979 </PRE>
10980 </DIV>
10981 <P> When the function is used in the scripting language interpreter, it
10982  will work like this:</P>
10983 <DIV class="targetlang">
10984 <PRE>
10985 result = add(3,4)
10986 </PRE>
10987 </DIV>
10988 <H3><A name="Arguments_nn5"></A>9.1.3 Output parameters</H3>
10989 <P> The following typemap rules tell SWIG that pointer is the output
10990  value of a function. When used, you do not need to supply the argument
10991  when calling the function. Instead, one or more output values are
10992  returned.</P>
10993 <DIV class="code">
10994 <PRE>
10995 int *OUTPUT
10996 short *OUTPUT
10997 long *OUTPUT
10998 unsigned int *OUTPUT
10999 unsigned short *OUTPUT
11000 unsigned long *OUTPUT
11001 double *OUTPUT
11002 float *OUTPUT
11003
11004 </PRE>
11005 </DIV>
11006 <P> These methods can be used as shown in an earlier example. For
11007  example, if you have this C function :</P>
11008 <DIV class="code">
11009 <PRE>
11010 void add(double a, double b, double *c) {
11011         *c = a+b;
11012 }
11013 </PRE>
11014 </DIV>
11015 <P> A SWIG interface file might look like this :</P>
11016 <DIV class="code">
11017 <PRE>
11018 %module example
11019 %include &quot;typemaps.i&quot;
11020 ...
11021 %inline %{
11022 extern void add(double a, double b, double *OUTPUT);
11023 %}
11024
11025 </PRE>
11026 </DIV>
11027 <P> In this case, only a single output value is returned, but this is
11028  not a restriction. An arbitrary number of output values can be returned
11029  by applying the output rules to more than one argument (as shown
11030  previously).</P>
11031 <P> If the function also returns a value, it is returned along with the
11032  argument. For example, if you had this:</P>
11033 <DIV class="code">
11034 <PRE>
11035 extern int foo(double a, double b, double *OUTPUT);
11036 </PRE>
11037 </DIV>
11038 <P> The function will return two values like this:</P>
11039 <DIV class="targetlang">
11040 <PRE>
11041 iresult, dresult = foo(3.5, 2)
11042 </PRE>
11043 </DIV>
11044 <H3><A name="Arguments_nn6"></A>9.1.4 Input/Output parameters</H3>
11045 <P> When a pointer serves as both an input and output value you can use
11046  the following typemaps :</P>
11047 <DIV class="code">
11048 <PRE>
11049 int *INOUT
11050 short *INOUT
11051 long *INOUT
11052 unsigned int *INOUT
11053 unsigned short *INOUT
11054 unsigned long *INOUT
11055 double *INOUT
11056 float *INOUT
11057
11058 </PRE>
11059 </DIV>
11060 <P> A C function that uses this might be something like this:</P>
11061 <DIV class="code">
11062 <PRE>
11063 void negate(double *x) {
11064         *x = -(*x);
11065 }
11066
11067 </PRE>
11068 </DIV>
11069 <P> To make x function as both and input and output value, declare the
11070  function like this in an interface file :</P>
11071 <DIV class="code">
11072 <PRE>
11073 %module example
11074 %include &quot;typemaps.i&quot;
11075 ...
11076 %{
11077 extern void negate(double *);
11078 %}
11079 extern void negate(double *INOUT);
11080
11081 </PRE>
11082 </DIV>
11083 <P> Now within a script, you can simply call the function normally :</P>
11084 <DIV class="targetlang">
11085 <PRE>
11086 a = negate(3);         # a = -3 after calling this
11087 </PRE>
11088 </DIV>
11089 <P> One subtle point of the <TT>INOUT</TT> rule is that many scripting
11090  languages enforce mutability constraints on primitive objects (meaning
11091  that simple objects like integers and strings aren't supposed to
11092  change). Because of this, you can't just modify the object's value in
11093  place as the underlying C function does in this example. Therefore, the
11094  <TT>INOUT</TT> rule returns the modified value as a new object rather
11095  than directly overwriting the value of the original input object.</P>
11096 <P><B> Compatibility note :</B> The <TT>INOUT</TT> rule used to be known
11097  as <TT>BOTH</TT> in earlier versions of SWIG. Backwards compatibility
11098  is preserved, but deprecated.</P>
11099 <H3><A name="Arguments_nn7"></A>9.1.5 Using different names</H3>
11100 <P> As previously shown, the <TT>%apply</TT> directive can be used to
11101  apply the <TT>INPUT</TT>, <TT>OUTPUT</TT>, and <TT>INOUT</TT> typemaps
11102  to different argument names. For example:</P>
11103 <DIV class="code">
11104 <PRE>
11105 // Make double *result an output value
11106 %apply double *OUTPUT { double *result };
11107
11108 // Make Int32 *in an input value
11109 %apply int *INPUT { Int32 *in };
11110
11111 // Make long *x inout
11112 %apply long *INOUT {long *x};
11113
11114 </PRE>
11115 </DIV>
11116 <P> To clear a rule, the <TT>%clear</TT> directive is used:</P>
11117 <DIV class="code">
11118 <PRE>
11119 %clear double *result;
11120 %clear Int32 *in, long *x;
11121 </PRE>
11122 </DIV>
11123 <P> Typemap declarations are lexically scoped so a typemap takes effect
11124  from the point of definition to the end of the file or a matching <TT>
11125 %clear</TT> declaration.</P>
11126 <H2><A name="Arguments_nn8"></A>9.2 Applying constraints to input values</H2>
11127 <P> In addition to changing the handling of various input values, it is
11128  also possible to use typemaps to apply constraints. For example, maybe
11129  you want to insure that a value is positive, or that a pointer is
11130  non-NULL. This can be accomplished including the <TT>constraints.i</TT>
11131  library file.</P>
11132 <H3><A name="Arguments_nn9"></A>9.2.1 Simple constraint example</H3>
11133 <P> The constraints library is best illustrated by the following
11134  interface file :</P>
11135 <DIV class="code">
11136 <PRE>
11137 // Interface file with constraints
11138 %module example
11139 %include &quot;constraints.i&quot;
11140
11141 double exp(double x);
11142 double log(double POSITIVE);         // Allow only positive values
11143 double sqrt(double NONNEGATIVE);     // Non-negative values only
11144 double inv(double NONZERO);          // Non-zero values
11145 void   free(void *NONNULL);          // Non-NULL pointers only
11146
11147 </PRE>
11148 </DIV>
11149 <P> The behavior of this file is exactly as you would expect. If any of
11150  the arguments violate the constraint condition, a scripting language
11151  exception will be raised. As a result, it is possible to catch bad
11152  values, prevent mysterious program crashes and so on.</P>
11153 <H3><A name="Arguments_nn10"></A>9.2.2 Constraint methods</H3>
11154 <P> The following constraints are currently available</P>
11155 <DIV class="code">
11156 <PRE>
11157 POSITIVE                     Any number &gt; 0 (not zero)
11158 NEGATIVE                     Any number &lt; 0 (not zero)
11159 NONNEGATIVE                  Any number &gt;= 0
11160 NONPOSITIVE                  Any number &lt;= 0
11161 NONZERO                      Nonzero number
11162 NONNULL                      Non-NULL pointer (pointers only).
11163
11164 </PRE>
11165 </DIV>
11166 <H3><A name="Arguments_nn11"></A>9.2.3 Applying constraints to new
11167  datatypes</H3>
11168 <P> The constraints library only supports the primitive C datatypes, but
11169  it is easy to apply it to new datatypes using <TT>%apply</TT>. For
11170  example :</P>
11171 <DIV class="code">
11172 <PRE>
11173 // Apply a constraint to a Real variable
11174 %apply Number POSITIVE { Real in };
11175
11176 // Apply a constraint to a pointer type
11177 %apply Pointer NONNULL { Vector * };
11178
11179 </PRE>
11180 </DIV>
11181 <P> The special types of &quot;Number&quot; and &quot;Pointer&quot; can be applied to any
11182  numeric and pointer variable type respectively. To later remove a
11183  constraint, the <TT>%clear</TT> directive can be used :</P>
11184 <DIV class="code">
11185 <PRE>
11186 %clear Real in;
11187 %clear Vector *;
11188 </PRE>
11189 </DIV><HR NOSHADE>
11190 <H1><A name="Typemaps"></A>10 Typemaps</H1>
11191
11192 <!-- INDEX -->
11193 <DIV class="sectiontoc">
11194 <UL>
11195 <LI><A href="#Typemaps_nn2">Introduction</A>
11196 <UL>
11197 <LI><A href="#Typemaps_nn3">Type conversion</A></LI>
11198 <LI><A href="#Typemaps_nn4">Typemaps</A></LI>
11199 <LI><A href="#Typemaps_nn5">Pattern matching</A></LI>
11200 <LI><A href="#Typemaps_nn6">Reusing typemaps</A></LI>
11201 <LI><A href="#Typemaps_nn7">What can be done with typemaps?</A></LI>
11202 <LI><A href="#Typemaps_nn8">What can't be done with typemaps?</A></LI>
11203 <LI><A href="#Typemaps_nn9">The rest of this chapter</A></LI>
11204 </UL>
11205 </LI>
11206 <LI><A href="#Typemaps_nn10">Typemap specifications</A>
11207 <UL>
11208 <LI><A href="#Typemaps_defining">Defining a typemap</A></LI>
11209 <LI><A href="#Typemaps_nn12">Typemap scope</A></LI>
11210 <LI><A href="#Typemaps_nn13">Copying a typemap</A></LI>
11211 <LI><A href="#Typemaps_nn14">Deleting a typemap</A></LI>
11212 <LI><A href="#Typemaps_nn15">Placement of typemaps</A></LI>
11213 </UL>
11214 </LI>
11215 <LI><A href="#Typemaps_pattern_matching">Pattern matching rules</A>
11216 <UL>
11217 <LI><A href="#Typemaps_nn17">Basic matching rules</A></LI>
11218 <LI><A href="#Typemaps_nn18">Typedef reductions</A></LI>
11219 <LI><A href="#Typemaps_nn19">Default typemaps</A></LI>
11220 <LI><A href="#Typemaps_mixed_default">Mixed default typemaps</A></LI>
11221 <LI><A href="#Typemaps_nn20">Multi-arguments typemaps</A></LI>
11222 </UL>
11223 </LI>
11224 <LI><A href="#Typemaps_nn21">Code generation rules</A>
11225 <UL>
11226 <LI><A href="#Typemaps_nn22">Scope</A></LI>
11227 <LI><A href="#Typemaps_nn23">Declaring new local variables</A></LI>
11228 <LI><A href="#Typemaps_special_variables">Special variables</A></LI>
11229 <LI><A href="#Typemaps_special_variable_macros">Special variable macros</A>
11230 <UL>
11231 <LI><A href="#Typemaps_special_macro_descriptor">$descriptor(type)</A></LI>
11232 <LI><A href="#Typemaps_special_macro_typemap">$typemap(method,
11233  typepattern)</A></LI>
11234 </UL>
11235 </LI>
11236 </UL>
11237 </LI>
11238 <LI><A href="#Typemaps_nn25">Common typemap methods</A>
11239 <UL>
11240 <LI><A href="#Typemaps_nn26">&quot;in&quot; typemap</A></LI>
11241 <LI><A href="#Typemaps_nn27">&quot;typecheck&quot; typemap</A></LI>
11242 <LI><A href="#Typemaps_nn28">&quot;out&quot; typemap</A></LI>
11243 <LI><A href="#Typemaps_nn29">&quot;arginit&quot; typemap</A></LI>
11244 <LI><A href="#Typemaps_nn30">&quot;default&quot; typemap</A></LI>
11245 <LI><A href="#Typemaps_nn31">&quot;check&quot; typemap</A></LI>
11246 <LI><A href="#Typemaps_nn32">&quot;argout&quot; typemap</A></LI>
11247 <LI><A href="#Typemaps_nn33">&quot;freearg&quot; typemap</A></LI>
11248 <LI><A href="#Typemaps_nn34">&quot;newfree&quot; typemap</A></LI>
11249 <LI><A href="#Typemaps_nn35">&quot;memberin&quot; typemap</A></LI>
11250 <LI><A href="#Typemaps_nn36">&quot;varin&quot; typemap</A></LI>
11251 <LI><A href="#Typemaps_nn37">&quot;varout&quot; typemap</A></LI>
11252 <LI><A href="#throws_typemap">&quot;throws&quot; typemap</A></LI>
11253 </UL>
11254 </LI>
11255 <LI><A href="#Typemaps_nn39">Some typemap examples</A>
11256 <UL>
11257 <LI><A href="#Typemaps_nn40">Typemaps for arrays</A></LI>
11258 <LI><A href="#Typemaps_nn41">Implementing constraints with typemaps</A></LI>
11259 </UL>
11260 </LI>
11261 <LI><A href="#Typemaps_nn43">Typemaps for multiple languages</A></LI>
11262 <LI><A href="#Typemaps_optimal">Optimal code generation when returning
11263  by value</A></LI>
11264 <LI><A href="#Typemaps_multi_argument_typemaps">Multi-argument typemaps</A>
11265 </LI>
11266 <LI><A href="#runtime_type_checker">The run-time type checker</A>
11267 <UL>
11268 <LI><A href="#Typemaps_nn45">Implementation</A></LI>
11269 <LI><A href="#Typemaps_runtime_type_checker_usage">Usage</A></LI>
11270 </UL>
11271 </LI>
11272 <LI><A href="#Typemaps_overloading">Typemaps and overloading</A></LI>
11273 <LI><A href="#Typemaps_nn48">More about <TT>%apply</TT> and <TT>%clear</TT>
11274 </A></LI>
11275 <LI><A href="#Typemaps_nn49">Reducing wrapper code size</A></LI>
11276 <LI><A href="#Typemaps_nn47">Passing data between typemaps</A></LI>
11277 <LI><A href="#Typemaps_nn52">C++ &quot;this&quot; pointer</A></LI>
11278 <LI><A href="#Typemaps_nn51">Where to go for more information?</A></LI>
11279 </UL>
11280 </DIV>
11281 <!-- INDEX -->
11282 <H2><A name="Typemaps_nn2"></A>10.1 Introduction</H2>
11283 <P> Chances are, you are reading this chapter for one of two reasons;
11284  you either want to customize SWIG's behavior or you overheard someone
11285  mumbling some incomprehensible drivel about &quot;typemaps&quot; and you asked
11286  yourself &quot;typemaps, what are those?&quot; That said, let's start with a
11287  short disclaimer that &quot;typemaps&quot; are an advanced customization feature
11288  that provide direct access to SWIG's low-level code generator. Not only
11289  that, they are an integral part of the SWIG C++ type system (a
11290  non-trivial topic of its own). Typemaps are generally<EM> not</EM> a
11291  required part of using SWIG. Therefore, you might want to re-read the
11292  earlier chapters if you have found your way to this chapter with only a
11293  vague idea of what SWIG already does by default.</P>
11294 <H3><A name="Typemaps_nn3"></A>10.1.1 Type conversion</H3>
11295 <P> One of the most important problems in wrapper code generation is the
11296  conversion of datatypes between programming languages. Specifically,
11297  for every C/C++ declaration, SWIG must somehow generate wrapper code
11298  that allows values to be passed back and forth between languages. Since
11299  every programming language represents data differently, this is not a
11300  simple of matter of simply linking code together with the C linker.
11301  Instead, SWIG has to know something about how data is represented in
11302  each language and how it can be manipulated.</P>
11303 <P> To illustrate, suppose you had a simple C function like this:</P>
11304 <DIV class="code">
11305 <PRE>
11306 int factorial(int n);
11307 </PRE>
11308 </DIV>
11309 <P> To access this function from Python, a pair of Python API functions
11310  are used to convert integer values. For example:</P>
11311 <DIV class="code">
11312 <PRE>
11313 long PyInt_AsLong(PyObject *obj);      /* Python --&gt; C */
11314 PyObject *PyInt_FromLong(long x);      /* C --&gt; Python */
11315 </PRE>
11316 </DIV>
11317 <P> The first function is used to convert the input argument from a
11318  Python integer object to C <TT>long</TT>. The second function is used
11319  to convert a value from C back into a Python integer object.</P>
11320 <P> Inside the wrapper function, you might see these functions used like
11321  this:</P>
11322 <DIV class="code">
11323 <PRE>
11324 PyObject *wrap_factorial(PyObject *self, PyObject *args) {
11325     int       arg1;
11326     int       result;
11327     PyObject *obj1;
11328     PyObject *resultobj;
11329
11330     if (!PyArg_ParseTuple(&quot;O:factorial&quot;, &amp;obj1)) return NULL;
11331     <B>arg1 = PyInt_AsLong(obj1);</B>
11332     result = factorial(arg1);
11333     <B>resultobj = PyInt_FromLong(result);</B>
11334     return resultobj;
11335 }
11336 </PRE>
11337 </DIV>
11338 <P> Every target language supported by SWIG has functions that work in a
11339  similar manner. For example, in Perl, the following functions are used:</P>
11340 <DIV class="code">
11341 <PRE>
11342 IV SvIV(SV *sv);                     /* Perl --&gt; C */
11343 void sv_setiv(SV *sv, IV val);       /* C --&gt; Perl */
11344 </PRE>
11345 </DIV>
11346 <P> In Tcl:</P>
11347 <DIV class="code">
11348 <PRE>
11349 int Tcl_GetLongFromObj(Tcl_Interp *interp, Tcl_Obj *obj, long *value);
11350 Tcl_Obj *Tcl_NewIntObj(long value);
11351 </PRE>
11352 </DIV>
11353 <P> The precise details are not so important. What is important is that
11354  all of the underlying type conversion is handled by collections of
11355  utility functions and short bits of C code like this---you simply have
11356  to read the extension documentation for your favorite language to know
11357  how it works (an exercise left to the reader).</P>
11358 <H3><A name="Typemaps_nn4"></A>10.1.2 Typemaps</H3>
11359 <P> Since type handling is so central to wrapper code generation, SWIG
11360  allows it to be completely defined (or redefined) by the user. To do
11361  this, a special <TT>%typemap</TT> directive is used. For example:</P>
11362 <DIV class="code">
11363 <PRE>
11364 /* Convert from Python --&gt; C */
11365 %typemap(in) int {
11366     $1 = PyInt_AsLong($input);
11367 }
11368
11369 /* Convert from C --&gt; Python */
11370 %typemap(out) int {
11371     $result = PyInt_FromLong($1);
11372 }
11373 </PRE>
11374 </DIV>
11375 <P> At first glance, this code will look a little confusing. However,
11376  there is really not much to it. The first typemap (the &quot;in&quot; typemap) is
11377  used to convert a value from the target language to C. The second
11378  typemap (the &quot;out&quot; typemap) is used to convert in the other direction.
11379  The content of each typemap is a small fragment of code that is
11380  inserted directly into the SWIG generated wrapper functions. The code
11381  is usually C or C++ code which will be generated into the C/C++ wrapper
11382  functions. Note that this isn't always the case as some target language
11383  modules allow target language code within the typemaps which gets
11384  generated into target language specific files. Within this code, a
11385  number of special variables prefixed with a $ are expanded. These are
11386  really just placeholders for C/C++ variables that are generated in the
11387  course of creating the wrapper function. In this case, <TT>$input</TT>
11388  refers to an input object that needs to be converted to C/C++ and <TT>
11389 $result</TT> refers to an object that is going to be returned by a
11390  wrapper function. <TT>$1</TT> refers to a C/C++ variable that has the
11391  same type as specified in the typemap declaration (an <TT>int</TT> in
11392  this example).</P>
11393 <P> A short example might make this a little more clear. If you were
11394  wrapping a function like this:</P>
11395 <DIV class="code">
11396 <PRE>
11397 int gcd(int x, int y);
11398 </PRE>
11399 </DIV>
11400 <P> A wrapper function would look approximately like this:</P>
11401 <DIV class="code">
11402 <PRE>
11403 PyObject *wrap_gcd(PyObject *self, PyObject *args) {
11404    int arg1;
11405    int arg2;
11406    int result;
11407    PyObject *obj1;
11408    PyObject *obj2;
11409    PyObject *resultobj;
11410
11411    if (!PyArg_ParseTuple(&quot;OO:gcd&quot;, &amp;obj1, &amp;obj2)) return NULL;
11412
11413    /* &quot;in&quot; typemap, argument 1 */<B>   
11414    {
11415       arg1 = PyInt_AsLong(obj1);
11416    }
11417 </B>
11418    /* &quot;in&quot; typemap, argument 2 */<B>
11419    {
11420       arg2 = PyInt_AsLong(obj2);
11421    }
11422 </B>
11423    result = gcd(arg1,arg2);
11424
11425    /* &quot;out&quot; typemap, return value */<B>
11426    {
11427       resultobj = PyInt_FromLong(result);
11428    }
11429 </B>
11430    return resultobj;
11431 }
11432 </PRE>
11433 </DIV>
11434 <P> In this code, you can see how the typemap code has been inserted
11435  into the function. You can also see how the special $ variables have
11436  been expanded to match certain variable names inside the wrapper
11437  function. This is really the whole idea behind typemaps--they simply
11438  let you insert arbitrary code into different parts of the generated
11439  wrapper functions. Because arbitrary code can be inserted, it possible
11440  to completely change the way in which values are converted.</P>
11441 <H3><A name="Typemaps_nn5"></A>10.1.3 Pattern matching</H3>
11442 <P> As the name implies, the purpose of a typemap is to &quot;map&quot; C
11443  datatypes to types in the target language. Once a typemap is defined
11444  for a C datatype, it is applied to all future occurrences of that type
11445  in the input file. For example:</P>
11446 <DIV class="code">
11447 <PRE>
11448 /* Convert from Perl --&gt; C */
11449 %typemap(in) <B>int</B> {
11450    $1 = SvIV($input);
11451 }
11452
11453 ...
11454 int factorial(<B>int</B> n);
11455 int gcd(<B>int</B> x, <B>int</B> y);
11456 int count(char *s, char *t, <B>int</B> max);
11457 </PRE>
11458 </DIV>
11459 <P> The matching of typemaps to C datatypes is more than a simple
11460  textual match. In fact, typemaps are fully built into the underlying
11461  type system. Therefore, typemaps are unaffected by <TT>typedef</TT>,
11462  namespaces, and other declarations that might hide the underlying type.
11463  For example, you could have code like this:</P>
11464 <DIV class="code">
11465 <PRE>
11466 /* Convert from Ruby--&gt; C */
11467 %typemap(in) <B>int</B> {
11468    $1 = NUM2INT($input);
11469 }
11470 ...
11471 typedef int Integer;
11472 namespace foo {
11473     typedef Integer Number;
11474 };
11475
11476 int foo(<B>int</B> x);
11477 int bar(<B>Integer</B> y);
11478 int spam(<B>foo::Number</B> a, <B>foo::Number</B> b);
11479 </PRE>
11480 </DIV>
11481 <P> In this case, the typemap is still applied to the proper arguments
11482  even though typenames don't always match the text &quot;int&quot;. This ability
11483  to track types is a critical part of SWIG--in fact, all of the target
11484  language modules work merely define a set of typemaps for the basic
11485  types. Yet, it is never necessary to write new typemaps for typenames
11486  introduced by <TT>typedef</TT>.</P>
11487 <P> In addition to tracking typenames, typemaps may also be specialized
11488  to match against a specific argument name. For example, you could write
11489  a typemap like this:</P>
11490 <DIV class="code">
11491 <PRE>
11492 %typemap(in) <B>double nonnegative</B> {
11493    $1 = PyFloat_AsDouble($input);
11494    if ($1 &lt; 0) {
11495         PyErr_SetString(PyExc_ValueError,&quot;argument must be nonnegative.&quot;);
11496         return NULL;
11497    }
11498 }
11499
11500 ...
11501 double sin(double x);
11502 double cos(double x);
11503 double sqrt(<B>double nonnegative</B>);
11504
11505 typedef double Real;
11506 double log(<B>Real nonnegative</B>);
11507 ...
11508 </PRE>
11509 </DIV>
11510 <P> For certain tasks such as input argument conversion, typemaps can be
11511  defined for sequences of consecutive arguments. For example:</P>
11512 <DIV class="code">
11513 <PRE>
11514 %typemap(in) (<B>char *str, int len</B>) {
11515     $1 = PyString_AsString($input);   /* char *str */
11516     $2 = PyString_Size($input);       /* int len   */
11517 }
11518 ...
11519 int count(<B>char *str, int len</B>, char c);
11520 </PRE>
11521 </DIV>
11522 <P> In this case, a single input object is expanded into a pair of C
11523  arguments. This example also provides a hint to the unusual variable
11524  naming scheme involving <TT>$1</TT>, <TT>$2</TT>, and so forth.</P>
11525 <H3><A name="Typemaps_nn6"></A>10.1.4 Reusing typemaps</H3>
11526 <P> Typemaps are normally defined for specific type and argument name
11527  patterns. However, typemaps can also be copied and reused. One way to
11528  do this is to use assignment like this:</P>
11529 <DIV class="code">
11530 <PRE>
11531 %typemap(in) Integer = int;   
11532 %typemap(in) (char *buffer, int size) = (char *str, int len);
11533 </PRE>
11534 </DIV>
11535 <P> A more general form of copying is found in the <TT>%apply</TT>
11536  directive like this:</P>
11537 <DIV class="code">
11538 <PRE>
11539 %typemap(in) int {
11540    /* Convert an integer argument */
11541    ...
11542 }
11543 %typemap(out) int {
11544    /* Return an integer value */
11545    ...
11546 }
11547
11548 /* Apply all of the integer typemaps to size_t */
11549 %apply int { size_t };    
11550 </PRE>
11551 </DIV>
11552 <P> <TT>%apply</TT> merely takes<EM> all</EM> of the typemaps that are
11553  defined for one type and applies them to other types. Note: you can
11554  include a comma separated set of types in the <TT>{ ... }</TT> part of <TT>
11555 %apply</TT>.</P>
11556 <P> It should be noted that it is not necessary to copy typemaps for
11557  types that are related by <TT>typedef</TT>. For example, if you have
11558  this,</P>
11559 <DIV class="code">
11560 <PRE>
11561 typedef int size_t;
11562 </PRE>
11563 </DIV>
11564 <P> then SWIG already knows that the <TT>int</TT> typemaps apply. You
11565  don't have to do anything.</P>
11566 <H3><A name="Typemaps_nn7"></A>10.1.5 What can be done with typemaps?</H3>
11567 <P> The primary use of typemaps is for defining wrapper generation
11568  behavior at the level of individual C/C++ datatypes. There are
11569  currently six general categories of problems that typemaps address:</P>
11570 <P><B> Argument handling</B></P>
11571 <DIV class="code">
11572 <PRE>
11573 int foo(<B>int x, double y, char *s</B>);
11574 </PRE>
11575 </DIV>
11576 <UL>
11577 <LI>Input argument conversion (&quot;in&quot; typemap).</LI>
11578 <LI>Input argument type checking (&quot;typecheck&quot; typemap).</LI>
11579 <LI>Output argument handling (&quot;argout&quot; typemap).</LI>
11580 <LI>Input argument value checking (&quot;check&quot; typemap).</LI>
11581 <LI>Input argument initialization (&quot;arginit&quot; typemap).</LI>
11582 <LI>Default arguments (&quot;default&quot; typemap).</LI>
11583 <LI>Input argument resource management (&quot;freearg&quot; typemap).</LI>
11584 </UL>
11585 <P><B> Return value handling</B></P>
11586 <DIV class="code">
11587 <PRE>
11588 <B>int</B> foo(int x, double y, char *s);
11589 </PRE>
11590 </DIV>
11591 <UL>
11592 <LI>Function return value conversion (&quot;out&quot; typemap).</LI>
11593 <LI>Return value resource management (&quot;ret&quot; typemap).</LI>
11594 <LI>Resource management for newly allocated objects (&quot;newfree&quot; typemap).</LI>
11595 </UL>
11596 <P><B> Exception handling</B></P>
11597 <DIV class="code">
11598 <PRE>
11599 <B>int</B> foo(int x, double y, char *s) throw(<B>MemoryError, IndexError</B>);
11600 </PRE>
11601 </DIV>
11602 <UL>
11603 <LI>Handling of C++ exception specifications. (&quot;throw&quot; typemap).</LI>
11604 </UL>
11605 <P><B> Global variables</B></P>
11606 <DIV class="code">
11607 <PRE>
11608 <B>int foo;</B>
11609 </PRE>
11610 </DIV>
11611 <UL>
11612 <LI>Assignment of a global variable. (&quot;varin&quot; typemap).</LI>
11613 <LI>Reading a global variable. (&quot;varout&quot; typemap).</LI>
11614 </UL>
11615 <P><B> Member variables</B></P>
11616 <DIV class="code">
11617 <PRE>
11618 struct Foo {
11619     <B>int x[20]</B>;
11620 };
11621 </PRE>
11622 </DIV>
11623 <UL>
11624 <LI>Assignment of data to a class/structure member. (&quot;memberin&quot;
11625  typemap).</LI>
11626 </UL>
11627 <P><B> Constant creation</B></P>
11628 <DIV class="code">
11629 <PRE>
11630 #define FOO 3
11631 %constant int BAR = 42;
11632 enum { ALE, LAGER, STOUT };
11633 </PRE>
11634 </DIV>
11635 <UL>
11636 <LI>Creation of constant values. (&quot;consttab&quot; or &quot;constcode&quot; typemap).</LI>
11637 </UL>
11638 <P> Details of each of these typemaps will be covered shortly. Also,
11639  certain language modules may define additional typemaps that expand
11640  upon this list. For example, the Java module defines a variety of
11641  typemaps for controlling additional aspects of the Java bindings.
11642  Consult language specific documentation for further details.</P>
11643 <H3><A name="Typemaps_nn8"></A>10.1.6 What can't be done with typemaps?</H3>
11644 <P> Typemaps can't be used to define properties that apply to C/C++
11645  declarations as a whole. For example, suppose you had a declaration
11646  like this,</P>
11647 <DIV class="code">
11648 <PRE>
11649 Foo *make_Foo();
11650 </PRE>
11651 </DIV>
11652 <P> and you wanted to tell SWIG that <TT>make_Foo()</TT> returned a
11653  newly allocated object (for the purposes of providing better memory
11654  management). Clearly, this property of <TT>make_Foo()</TT> is<EM> not</EM>
11655  a property that would be associated with the datatype <TT>Foo *</TT> by
11656  itself. Therefore, a completely different SWIG customization mechanism
11657  (<TT>%feature</TT>) is used for this purpose. Consult the <A href="#Customization">
11658 Customization Features</A> chapter for more information about that.</P>
11659 <P> Typemaps also can't be used to rearrange or transform the order of
11660  arguments. For example, if you had a function like this:</P>
11661 <DIV class="code">
11662 <PRE>
11663 void foo(int, char *);
11664 </PRE>
11665 </DIV>
11666 <P> you can't use typemaps to interchange the arguments, allowing you to
11667  call the function like this:</P>
11668 <DIV class="targetlang">
11669 <PRE>
11670 foo(&quot;hello&quot;,3)          # Reversed arguments
11671 </PRE>
11672 </DIV>
11673 <P> If you want to change the calling conventions of a function, write a
11674  helper function instead. For example:</P>
11675 <DIV class="code">
11676 <PRE>
11677 %rename(foo) wrap_foo;
11678 %inline %{
11679 void wrap_foo(char *s, int x) {
11680    foo(x,s);
11681 }
11682 %}
11683 </PRE>
11684 </DIV>
11685 <H3><A name="Typemaps_nn9"></A>10.1.7 The rest of this chapter</H3>
11686 <P> The rest of this chapter provides detailed information for people
11687  who want to write new typemaps. This information is of particular
11688  importance to anyone who intends to write a new SWIG target language
11689  module. Power users can also use this information to write application
11690  specific type conversion rules.</P>
11691 <P> Since typemaps are strongly tied to the underlying C++ type system,
11692  subsequent sections assume that you are reasonably familiar with the
11693  basic details of values, pointers, references, arrays, type qualifiers
11694  (e.g., <TT>const</TT>), structures, namespaces, templates, and memory
11695  management in C/C++. If not, you would be well-advised to consult a
11696  copy of &quot;The C Programming Language&quot; by Kernighan and Ritchie or &quot;The
11697  C++ Programming Language&quot; by Stroustrup before going any further.</P>
11698 <H2><A name="Typemaps_nn10"></A>10.2 Typemap specifications</H2>
11699 <P> This section describes the behavior of the <TT>%typemap</TT>
11700  directive itself.</P>
11701 <H3><A name="Typemaps_defining"></A>10.2.1 Defining a typemap</H3>
11702 <P> New typemaps are defined using the <TT>%typemap</TT> declaration.
11703  The general form of this declaration is as follows (parts enclosed in [
11704  ... ] are optional):</P>
11705 <DIV class="code">
11706 <PRE>
11707 %typemap(<EM>method</EM> [, <EM>modifiers</EM>]) <EM>typelist</EM> <EM>code</EM> ;
11708 </PRE>
11709 </DIV>
11710 <P><EM> method</EM> is a simply a name that specifies what kind of
11711  typemap is being defined. It is usually a name like <TT>&quot;in&quot;</TT>, <TT>
11712 &quot;out&quot;</TT>, or <TT>&quot;argout&quot;</TT>. The purpose of these methods is
11713  described later.</P>
11714 <P><EM> modifiers</EM> is an optional comma separated list of <TT>
11715 name=&quot;value&quot;</TT> values. These are sometimes to attach extra
11716  information to a typemap and is often target-language dependent.</P>
11717 <P><EM> typelist</EM> is a list of the C++ type patterns that the
11718  typemap will match. The general form of this list is as follows:</P>
11719 <DIV class="diagram">
11720 <PRE>
11721 typelist    :  typepattern [, typepattern, typepattern, ... ] ;
11722
11723 typepattern :  type [ (parms) ]
11724             |  type name [ (parms) ]
11725             |  ( typelist ) [ (parms) ]
11726
11727 </PRE>
11728 </DIV>
11729 <P> Each type pattern is either a simple type, a simple type and
11730  argument name, or a list of types in the case of multi-argument
11731  typemaps. In addition, each type pattern can be parameterized with a
11732  list of temporary variables (parms). The purpose of these variables
11733  will be explained shortly.</P>
11734 <P><EM>code</EM> specifies the code used in the typemap. Usually this is
11735  C/C++ code, but in the statically typed target languages, such as Java
11736  and C#, this can contain target language code for certain typemaps. It
11737  can take any one of the following forms:</P>
11738 <DIV class="diagram">
11739 <PRE>
11740 code       : { ... }
11741            | &quot; ... &quot;
11742            | %{ ... %}
11743 </PRE>
11744 </DIV>
11745 <P> Note that the preprocessor will expand code within the {}
11746  delimiters, but not in the last two styles of delimiters, see <A href="#Preprocessor_typemap_delimiters">
11747 Preprocessor and Typemaps</A>. Here are some examples of valid typemap
11748  specifications:</P>
11749 <DIV class="code">
11750 <PRE>
11751 /* Simple typemap declarations */
11752 %typemap(in) int {
11753    $1 = PyInt_AsLong($input);
11754 }
11755 %typemap(in) int &quot;$1 = PyInt_AsLong($input);&quot;;
11756 %typemap(in) int %{ 
11757    $1 = PyInt_AsLong($input);
11758 %}
11759
11760 /* Typemap with extra argument name */
11761 %typemap(in) int nonnegative {
11762    ...
11763 }
11764
11765 /* Multiple types in one typemap */
11766 %typemap(in) int, short, long { 
11767    $1 = SvIV($input);
11768 }
11769
11770 /* Typemap with modifiers */
11771 %typemap(in,doc=&quot;integer&quot;) int &quot;$1 = gh_scm2int($input);&quot;;
11772
11773 /* Typemap applied to patterns of multiple arguments */
11774 %typemap(in) (char *str, int len),
11775              (char *buffer, int size)
11776 {
11777    $1 = PyString_AsString($input);
11778    $2 = PyString_Size($input);
11779 }
11780
11781 /* Typemap with extra pattern parameters */
11782 %typemap(in, numinputs=0) int *output (int temp),
11783                           long *output (long temp)
11784 {
11785    $1 = &amp;temp;
11786 }
11787 </PRE>
11788 </DIV>
11789 <P> Admittedly, it's not the most readable syntax at first glance.
11790  However, the purpose of the individual pieces will become clear.</P>
11791 <H3><A name="Typemaps_nn12"></A>10.2.2 Typemap scope</H3>
11792 <P> Once defined, a typemap remains in effect for all of the
11793  declarations that follow. A typemap may be redefined for different
11794  sections of an input file. For example:</P>
11795 <DIV class="code">
11796 <PRE>
11797 // typemap1
11798 %typemap(in) int {
11799 ...
11800 }
11801
11802 int fact(int);                    // typemap1
11803 int gcd(int x, int y);            // typemap1
11804
11805 // typemap2
11806 %typemap(in) int {
11807 ...
11808 }
11809
11810 int isprime(int);                 // typemap2
11811 </PRE>
11812 </DIV>
11813 <P> One exception to the typemap scoping rules pertains to the <TT>
11814 %extend</TT> declaration. <TT>%extend</TT> is used to attach new
11815  declarations to a class or structure definition. Because of this, all
11816  of the declarations in an <TT>%extend</TT> block are subject to the
11817  typemap rules that are in effect at the point where the class itself is
11818  defined. For example:</P>
11819 <DIV class="code">
11820 <PRE>
11821 class Foo {
11822    ...
11823 };
11824
11825 %typemap(in) int {
11826  ...
11827 }
11828
11829 %extend Foo {
11830    int blah(int x);    // typemap has no effect.  Declaration is attached to Foo which 
11831                        // appears before the %typemap declaration.
11832 };
11833 </PRE>
11834 </DIV>
11835 <H3><A name="Typemaps_nn13"></A>10.2.3 Copying a typemap</H3>
11836 <P> A typemap is copied by using assignment. For example:</P>
11837 <DIV class="code">
11838 <PRE>
11839 %typemap(in) Integer = int;
11840 </PRE>
11841 </DIV>
11842 <P> or this:</P>
11843 <DIV class="code">
11844 <PRE>
11845 %typemap(in) Integer, Number, int32_t = int;
11846 </PRE>
11847 </DIV>
11848 <P> Types are often managed by a collection of different typemaps. For
11849  example:</P>
11850 <DIV class="code">
11851 <PRE>
11852 %typemap(in)     int { ... }
11853 %typemap(out)    int { ... }
11854 %typemap(varin)  int { ... }
11855 %typemap(varout) int { ... }
11856 </PRE>
11857 </DIV>
11858 <P> To copy all of these typemaps to a new type, use <TT>%apply</TT>.
11859  For example:</P>
11860 <DIV class="code">
11861 <PRE>
11862 %apply int { Integer };            // Copy all int typemaps to Integer
11863 %apply int { Integer, Number };    // Copy all int typemaps to both Integer and Number
11864 </PRE>
11865 </DIV>
11866 <P> The patterns for <TT>%apply</TT> follow the same rules as for <TT>
11867 %typemap</TT>. For example:</P>
11868 <DIV class="code">
11869 <PRE>
11870 %apply int *output { Integer *output };                    // Typemap with name
11871 %apply (char *buf, int len) { (char *buffer, int size) };  // Multiple arguments
11872 </PRE>
11873 </DIV>
11874 <H3><A name="Typemaps_nn14"></A>10.2.4 Deleting a typemap</H3>
11875 <P> A typemap can be deleted by simply defining no code. For example:</P>
11876 <DIV class="code">
11877 <PRE>
11878 %typemap(in) int;               // Clears typemap for int
11879 %typemap(in) int, long, short;  // Clears typemap for int, long, short
11880 %typemap(in) int *output;       
11881 </PRE>
11882 </DIV>
11883 <P> The <TT>%clear</TT> directive clears all typemaps for a given type.
11884  For example:</P>
11885 <DIV class="code">
11886 <PRE>
11887 %clear int;                     // Removes all types for int
11888 %clear int *output, long *output;
11889 </PRE>
11890 </DIV>
11891 <P><B> Note:</B> Since SWIG's default behavior is defined by typemaps,
11892  clearing a fundamental type like <TT>int</TT> will make that type
11893  unusable unless you also define a new set of typemaps immediately after
11894  the clear operation.</P>
11895 <H3><A name="Typemaps_nn15"></A>10.2.5 Placement of typemaps</H3>
11896 <P> Typemap declarations can be declared in the global scope, within a
11897  C++ namespace, and within a C++ class. For example:</P>
11898 <DIV class="code">
11899 <PRE>
11900 %typemap(in) int {
11901    ...
11902 }
11903
11904 namespace std {
11905     class string;
11906     %typemap(in) string {
11907         ...
11908     }
11909 }
11910
11911 class Bar {
11912 public:
11913     typedef const int &amp; const_reference;
11914     %typemap(out) const_reference {
11915          ...
11916     }
11917 };
11918 </PRE>
11919 </DIV>
11920 <P> When a typemap appears inside a namespace or class, it stays in
11921  effect until the end of the SWIG input (just like before). However, the
11922  typemap takes the local scope into account. Therefore, this code</P>
11923 <DIV class="code">
11924 <PRE>
11925 namespace std {
11926     class string;
11927     %typemap(in) string {
11928        ...
11929     }
11930 }
11931 </PRE>
11932 </DIV>
11933 <P> is really defining a typemap for the type <TT>std::string</TT>. You
11934  could have code like this:</P>
11935 <DIV class="code">
11936 <PRE>
11937 namespace std {
11938     class string;
11939     %typemap(in) string {          /* std::string */
11940        ...
11941     }
11942 }
11943
11944 namespace Foo {
11945     class string;
11946     %typemap(in) string {          /* Foo::string */
11947        ...
11948     }
11949 }
11950 </PRE>
11951 </DIV>
11952 <P> In this case, there are two completely distinct typemaps that apply
11953  to two completely different types (<TT>std::string</TT> and <TT>
11954 Foo::string</TT>).</P>
11955 <P> It should be noted that for scoping to work, SWIG has to know that <TT>
11956 string</TT> is a typename defined within a particular namespace. In this
11957  example, this is done using the class declaration <TT>class string</TT>
11958 .</P>
11959 <H2><A name="Typemaps_pattern_matching"></A>10.3 Pattern matching rules</H2>
11960 <P> The section describes the pattern matching rules by which C
11961  datatypes are associated with typemaps.</P>
11962 <H3><A name="Typemaps_nn17"></A>10.3.1 Basic matching rules</H3>
11963 <P> Typemaps are matched using both a type and a name (typically the
11964  name of a argument). For a given <TT>TYPE NAME</TT> pair, the following
11965  rules are applied, in order, to find a match. The first typemap found
11966  is used.</P>
11967 <UL>
11968 <LI>Typemaps that exactly match <TT>TYPE</TT> and <TT>NAME</TT>.</LI>
11969 <LI>Typemaps that exactly match <TT>TYPE</TT> only.</LI>
11970 </UL>
11971 <P> If <TT>TYPE</TT> includes qualifiers (const, volatile, etc.), they
11972  are stripped and the following checks are made:</P>
11973 <UL>
11974 <LI>Typemaps that match the stripped <TT>TYPE</TT> and <TT>NAME</TT>.</LI>
11975 <LI>Typemaps that match the stripped <TT>TYPE</TT> only.</LI>
11976 </UL>
11977 <P> If <TT>TYPE</TT> is an array. The following transformation is made:</P>
11978 <UL>
11979 <LI>Replace all dimensions to <TT>[ANY]</TT> and look for a generic
11980  array typemap.</LI>
11981 </UL>
11982 <P> To illustrate, suppose that you had a function like this:</P>
11983 <DIV class="code">
11984 <PRE>
11985 int foo(const char *s);
11986 </PRE>
11987 </DIV>
11988 <P> To find a typemap for the argument <TT>const char *s</TT>, SWIG will
11989  search for the following typemaps:</P>
11990 <DIV class="diagram">
11991 <PRE>
11992 const char *s           Exact type and name match
11993 const char *            Exact type match
11994 char *s                 Type and name match (stripped qualifiers)
11995 char *                  Type match (stripped qualifiers)
11996 </PRE>
11997 </DIV>
11998 <P> When more than one typemap rule might be defined, only the first
11999  match found is actually used. Here is an example that shows how some of
12000  the basic rules are applied:</P>
12001 <DIV class="code">
12002 <PRE>
12003 %typemap(in) int *x {
12004    ... typemap 1
12005 }
12006
12007 %typemap(in) int * {
12008    ... typemap 2
12009 }
12010
12011 %typemap(in) const int *z {
12012    ... typemap 3
12013 }
12014
12015 %typemap(in) int [4] {
12016    ... typemap 4
12017 }
12018
12019 %typemap(in) int [ANY] {
12020    ... typemap 5
12021 }
12022
12023 void A(int *x);        // int *x rule    (typemap 1)
12024 void B(int *y);        // int * rule     (typemap 2)
12025 void C(const int *x);  // int *x rule    (typemap 1)
12026 void D(const int *z);  // int * rule     (typemap 3)
12027 void E(int x[4]);      // int [4] rule   (typemap 4)
12028 void F(int x[1000]);   // int [ANY] rule (typemap 5)
12029 </PRE>
12030 </DIV>
12031 <H3><A name="Typemaps_nn18"></A>10.3.2 Typedef reductions</H3>
12032 <P> If no match is found using the rules in the previous section, SWIG
12033  applies a typedef reduction to the type and repeats the typemap search
12034  for the reduced type. To illustrate, suppose you had code like this:</P>
12035 <DIV class="code">
12036 <PRE>
12037 %typemap(in) int {
12038    ... typemap 1
12039 }
12040
12041 typedef int Integer;
12042 void blah(Integer x);
12043 </PRE>
12044 </DIV>
12045 <P> To find the typemap for <TT>Integer x</TT>, SWIG will first search
12046  for the following typemaps:</P>
12047 <DIV class="diagram">
12048 <PRE>
12049 Integer x
12050 Integer
12051 </PRE>
12052 </DIV>
12053 <P> Finding no match, it then applies a reduction <TT>Integer -&gt; int</TT>
12054  to the type and repeats the search.</P>
12055 <DIV class="diagram">
12056 <PRE>
12057 int x
12058 int      --&gt; match: typemap 1
12059 </PRE>
12060 </DIV>
12061 <P> Even though two types might be the same via typedef, SWIG allows
12062  typemaps to be defined for each typename independently. This allows for
12063  interesting customization possibilities based solely on the typename
12064  itself. For example, you could write code like this:</P>
12065 <DIV class="code">
12066 <PRE>
12067 typedef double  pdouble;     // Positive double
12068
12069 // typemap 1
12070 %typemap(in) double {
12071    ... get a double ...
12072 }
12073 // typemap 2
12074 %typemap(in) pdouble {
12075    ... get a positive double ...
12076 }
12077 double sin(double x);           // typemap 1
12078 pdouble sqrt(pdouble x);        // typemap 2
12079 </PRE>
12080 </DIV>
12081 <P> When reducing the type, only one typedef reduction is applied at a
12082  time. The search process continues to apply reductions until a match is
12083  found or until no more reductions can be made.</P>
12084 <P> For complicated types, the reduction process can generate a long
12085  list of patterns. Consider the following:</P>
12086 <DIV class="code">
12087 <PRE>
12088 typedef int Integer;
12089 typedef Integer Row4[4];
12090 void foo(Row4 rows[10]);
12091 </PRE>
12092 </DIV>
12093 <P> To find a match for the <TT>Row4 rows[10]</TT> argument, SWIG would
12094  check the following patterns, stopping only when it found a match:</P>
12095 <DIV class="code">
12096 <PRE>
12097 Row4 rows[10]
12098 Row4 [10]
12099 Row4 rows[ANY]
12100 Row4 [ANY]
12101
12102 # Reduce Row4 --&gt; Integer[4]
12103 Integer rows[10][4]
12104 Integer [10][4]
12105 Integer rows[ANY][ANY]
12106 Integer [ANY][ANY]
12107
12108 # Reduce Integer --&gt; int
12109 int rows[10][4]
12110 int [10][4]
12111 int rows[ANY][ANY]
12112 int [ANY][ANY]
12113 </PRE>
12114 </DIV>
12115 <P> For parameterized types like templates, the situation is even more
12116  complicated. Suppose you had some declarations like this:</P>
12117 <DIV class="code">
12118 <PRE>
12119 typedef int Integer;
12120 typedef foo&lt;Integer,Integer&gt; fooii;
12121 void blah(fooii *x);
12122 </PRE>
12123 </DIV>
12124 <P> In this case, the following typemap patterns are searched for the
12125  argument <TT>fooii *x</TT>:</P>
12126 <DIV class="code">
12127 <PRE>
12128 fooii *x
12129 fooii *
12130
12131 # Reduce fooii --&gt; foo&lt;Integer,Integer&gt;
12132 foo&lt;Integer,Integer&gt; *x
12133 foo&lt;Integer,Integer&gt; *
12134
12135 # Reduce Integer -&gt; int
12136 foo&lt;int, Integer&gt; *x
12137 foo&lt;int, Integer&gt; *
12138
12139 # Reduce Integer -&gt; int
12140 foo&lt;int, int&gt; *x
12141 foo&lt;int, int&gt; *
12142 </PRE>
12143 </DIV>
12144 <P> Typemap reductions are always applied to the left-most type that
12145  appears. Only when no reductions can be made to the left-most type are
12146  reductions made to other parts of the type. This behavior means that
12147  you could define a typemap for <TT>foo&lt;int,Integer&gt;</TT>, but a typemap
12148  for <TT>foo&lt;Integer,int&gt;</TT> would never be matched. Admittedly, this
12149  is rather esoteric--there's little practical reason to write a typemap
12150  quite like that. Of course, you could rely on this to confuse your
12151  coworkers even more.</P>
12152 <H3><A name="Typemaps_nn19"></A>10.3.3 Default typemaps</H3>
12153 <P> Most SWIG language modules use typemaps to define the default
12154  behavior of the C primitive types. This is entirely straightforward.
12155  For example, a set of typemaps are written like this:</P>
12156 <DIV class="code">
12157 <PRE>
12158 %typemap(in) int   &quot;convert an int&quot;;
12159 %typemap(in) short &quot;convert a short&quot;;
12160 %typemap(in) float &quot;convert a float&quot;;
12161 ...
12162 </PRE>
12163 </DIV>
12164 <P> Since typemap matching follows all <TT>typedef</TT> declarations,
12165  any sort of type that is mapped to a primitive type through <TT>typedef</TT>
12166  will be picked up by one of these primitive typemaps.</P>
12167 <P> The default behavior for pointers, arrays, references, and other
12168  kinds of types are handled by specifying rules for variations of the
12169  reserved <TT>SWIGTYPE</TT> type. For example:</P>
12170 <DIV class="code">
12171 <PRE>
12172 %typemap(in) SWIGTYPE *            { ... default pointer handling ...         }
12173 %typemap(in) SWIGTYPE &amp;            { ... default reference handling ...       }
12174 %typemap(in) SWIGTYPE []           { ... default array handling ...           }
12175 %typemap(in) enum SWIGTYPE         { ... default handling for enum values ... }
12176 %typemap(in) SWIGTYPE (CLASS::*)   { ... default pointer member handling ...  } 
12177 </PRE>
12178 </DIV>
12179 <P> These rules match any kind of pointer, reference, or array--even
12180  when multiple levels of indirection or multiple array dimensions are
12181  used. Therefore, if you wanted to change SWIG's default handling for
12182  all types of pointers, you would simply redefine the rule for <TT>
12183 SWIGTYPE *</TT>.</P>
12184 <P> Finally, the following typemap rule is used to match against simple
12185  types that don't match any other rules:</P>
12186 <DIV class="code">
12187 <PRE>
12188 %typemap(in) SWIGTYPE   { ... handle an unknown type ... }
12189 </PRE>
12190 </DIV>
12191 <P> This typemap is important because it is the rule that gets triggered
12192  when call or return by value is used. For instance, if you have a
12193  declaration like this:</P>
12194 <DIV class="code">
12195 <PRE>
12196 double dot_product(Vector a, Vector b);
12197 </PRE>
12198 </DIV>
12199 <P> The <TT>Vector</TT> type will usually just get matched against <TT>
12200 SWIGTYPE</TT>. The default implementation of <TT>SWIGTYPE</TT> is to
12201  convert the value into pointers (as described in chapter 3).</P>
12202 <P> By redefining <TT>SWIGTYPE</TT> it may be possible to implement
12203  other behavior. For example, if you cleared all typemaps for <TT>
12204 SWIGTYPE</TT>, SWIG simply won't wrap any unknown datatype (which might
12205  be useful for debugging). Alternatively, you might modify SWIGTYPE to
12206  marshal objects into strings instead of converting them to pointers.</P>
12207 <P> The best way to explore the default typemaps is to look at the ones
12208  already defined for a particular language module. Typemaps definitions
12209  are usually found in the SWIG library in a file such as <TT>python.swg</TT>
12210 , <TT>tcl8.swg</TT>, etc.</P>
12211 <H3><A name="Typemaps_mixed_default"></A>10.3.4 Mixed default typemaps</H3>
12212 <P> The default typemaps described above can be mixed with <TT>const</TT>
12213  and with each other. For example the <TT>SWIGTYPE *</TT> typemap is for
12214  default pointer handling, but if a <TT>const SWIGTYPE *</TT> typemap is
12215  defined it will be used instead for constant pointers. Some further
12216  examples follow:</P>
12217 <DIV class="code">
12218 <PRE>
12219 %typemap(in) enum SWIGTYPE &amp;        { ... enum references ...                       }
12220 %typemap(in) const enum SWIGTYPE &amp;  { ... const enum references ...                 }
12221 %typemap(in) SWIGTYPE *&amp;            { ... pointers passed by reference ...          }
12222 %typemap(in) SWIGTYPE * const &amp;     { ... constant pointers passed by reference ... }
12223 %typemap(in) SWIGTYPE[ANY][ANY]     { ... 2D arrays ...                             }
12224 </PRE>
12225 </DIV>
12226 <P> Note that the the typedef reduction described earlier is also used
12227  with these mixed default typemaps. For example, say the following
12228  typemaps are defined and SWIG is looking for the best match for the
12229  enum shown below:</P>
12230 <DIV class="code">
12231 <PRE>
12232 %typemap(in) const Hello &amp;          { ... }
12233 %typemap(in) const enum SWIGTYPE &amp;  { ... }
12234 %typemap(in) enum SWIGTYPE &amp;        { ... }
12235 %typemap(in) SWIGTYPE &amp;             { ... }
12236 %typemap(in) SWIGTYPE               { ... }
12237
12238 enum Hello {};
12239 const Hello &amp;hi;
12240 </PRE>
12241 </DIV>
12242 <P> The typemap at the top of the list will be chosen, not because it is
12243  defined first, but because it is the closest match for the type being
12244  wrapped. If any of the typemaps in the above list were not defined,
12245  then the next one on the list would have precedence. In other words the
12246  typemap chosen is the closest explicit match.</P>
12247 <P><B> Compatibility note:</B> The mixed default typemaps were
12248  introduced in SWIG-1.3.23, but were not used much in this version.
12249  Expect to see them being used more and more within the various
12250  libraries in later versions of SWIG.</P>
12251 <H3><A name="Typemaps_nn20"></A>10.3.5 Multi-arguments typemaps</H3>
12252 <P> When multi-argument typemaps are specified, they take precedence
12253  over any typemaps specified for a single type. For example:</P>
12254 <DIV class="code">
12255 <PRE>
12256 %typemap(in) (char *buffer, int len) {
12257    // typemap 1
12258 }
12259
12260 %typemap(in) char *buffer {
12261    // typemap 2
12262 }
12263
12264 void foo(char *buffer, int len, int count); // (char *buffer, int len)
12265 void bar(char *buffer, int blah);           // char *buffer
12266 </PRE>
12267 </DIV>
12268 <P> Multi-argument typemaps are also more restrictive in the way that
12269  they are matched. Currently, the first argument follows the matching
12270  rules described in the previous section, but all subsequent arguments
12271  must match exactly.</P>
12272 <H2><A name="Typemaps_nn21"></A>10.4 Code generation rules</H2>
12273 <P> This section describes rules by which typemap code is inserted into
12274  the generated wrapper code.</P>
12275 <H3><A name="Typemaps_nn22"></A>10.4.1 Scope</H3>
12276 <P> When a typemap is defined like this:</P>
12277 <DIV class="code">
12278 <PRE>
12279 %typemap(in) int {
12280    $1 = PyInt_AsLong($input);
12281 }
12282 </PRE>
12283 </DIV>
12284 <P> the typemap code is inserted into the wrapper function using a new
12285  block scope. In other words, the wrapper code will look like this:</P>
12286 <DIV class="code">
12287 <PRE>
12288 wrap_whatever() {
12289     ...
12290     // Typemap code
12291     {                    
12292        arg1 = PyInt_AsLong(obj1);
12293     }
12294     ...
12295 }
12296 </PRE>
12297 </DIV>
12298 <P> Because the typemap code is enclosed in its own block, it is legal
12299  to declare temporary variables for use during typemap execution. For
12300  example:</P>
12301 <DIV class="code">
12302 <PRE>
12303 %typemap(in) short {
12304    long temp;          /* Temporary value */
12305    if (Tcl_GetLongFromObj(interp, $input, &amp;temp) != TCL_OK) {
12306       return TCL_ERROR;
12307    }
12308    $1 = (short) temp;
12309 }
12310 </PRE>
12311 </DIV>
12312 <P> Of course, any variables that you declare inside a typemap are
12313  destroyed as soon as the typemap code has executed (they are not
12314  visible to other parts of the wrapper function or other typemaps that
12315  might use the same variable names).</P>
12316 <P> Occasionally, typemap code will be specified using a few alternative
12317  forms. For example:</P>
12318 <DIV class="code">
12319 <PRE>
12320 %typemap(in) int &quot;$1 = PyInt_AsLong($input);&quot;;
12321 %typemap(in) int %{
12322 $1 = PyInt_AsLong($input);
12323 %}
12324 </PRE>
12325 </DIV>
12326 <P> These two forms are mainly used for cosmetics--the specified code is
12327  not enclosed inside a block scope when it is emitted. This sometimes
12328  results in a less complicated looking wrapper function.</P>
12329 <H3><A name="Typemaps_nn23"></A>10.4.2 Declaring new local variables</H3>
12330 <P> Sometimes it is useful to declare a new local variable that exists
12331  within the scope of the entire wrapper function. A good example of this
12332  might be an application in which you wanted to marshal strings. Suppose
12333  you had a C++ function like this</P>
12334 <DIV class="code">
12335 <PRE>
12336 int foo(std::string *s);
12337 </PRE>
12338 </DIV>
12339 <P> and you wanted to pass a native string in the target language as an
12340  argument. For instance, in Perl, you wanted the function to work like
12341  this:</P>
12342 <DIV class="targetlang">
12343 <PRE>
12344 $x = foo(&quot;Hello World&quot;);
12345 </PRE>
12346 </DIV>
12347 <P> To do this, you can't just pass a raw Perl string as the <TT>
12348 std::string *</TT> argument. Instead, you have to create a temporary <TT>
12349 std::string</TT> object, copy the Perl string data into it, and then
12350  pass a pointer to the object. To do this, simply specify the typemap
12351  with an extra parameter like this:</P>
12352 <DIV class="code">
12353 <PRE>
12354 %typemap(in) std::string * <B>(std::string temp)</B> {
12355     unsigned int len;
12356     char        *s;
12357     s = SvPV($input,len);         /* Extract string data */
12358     temp.assign(s,len);           /* Assign to temp */
12359     $1 = &amp;temp;                   /* Set argument to point to temp */
12360 }
12361 </PRE>
12362 </DIV>
12363 <P> In this case, <TT>temp</TT> becomes a local variable in the scope of
12364  the entire wrapper function. For example:</P>
12365 <DIV class="code">
12366 <PRE>
12367 wrap_foo() {
12368    std::string temp;    &lt;--- Declaration of temp goes here
12369    ...
12370
12371    /* Typemap code */
12372    {
12373       ...
12374       temp.assign(s,len);
12375       ...
12376    } 
12377    ...
12378 }
12379 </PRE>
12380 </DIV>
12381 <P> When you set <TT>temp</TT> to a value, it persists for the duration
12382  of the wrapper function and gets cleaned up automatically on exit.</P>
12383 <P> It is perfectly safe to use more than one typemap involving local
12384  variables in the same declaration. For example, you could declare a
12385  function as :</P>
12386 <DIV class="code">
12387 <PRE>
12388 void foo(std::string *x, std::string *y, std::string *z);
12389 </PRE>
12390 </DIV>
12391 <P> This is safely handled because SWIG actually renames all local
12392  variable references by appending an argument number suffix. Therefore,
12393  the generated code would actually look like this:</P>
12394 <DIV class="code">
12395 <PRE>
12396 wrap_foo() {
12397    int *arg1;    /* Actual arguments */
12398    int *arg2;
12399    int *arg3;
12400    std::string temp1;    /* Locals declared in the typemap */
12401    std::string temp2;
12402    std::string temp3;
12403    ...
12404    {
12405        char *s;
12406        unsigned int len;
12407        ...
12408        temp1.assign(s,len);
12409        arg1 = *temp1;
12410    }
12411    {
12412        char *s;
12413        unsigned int len;
12414        ...
12415        temp2.assign(s,len);
12416        arg2 = &amp;temp2;
12417    }
12418    {
12419        char *s;
12420        unsigned int len;
12421        ...
12422        temp3.assign(s,len);
12423        arg3 = &amp;temp3;
12424    }
12425    ...
12426 }
12427 </PRE>
12428 </DIV>
12429 <P> Some typemaps do not recognize local variables (or they may simply
12430  not apply). At this time, only typemaps that apply to argument
12431  conversion support this.</P>
12432 <P><B> Note:</B></P>
12433 <P> When declaring a typemap for multiple types, each type must have its
12434  own local variable declaration.</P>
12435 <DIV class="code">
12436 <PRE>
12437 %typemap(in) const std::string *, std::string * (std::string temp) // NO!
12438 // only std::string * has a local variable
12439 // const std::string * does not (oops)
12440 ....
12441
12442 %typemap(in) const std::string * (std::string temp), std::string * (std::string temp) // Correct
12443 ....
12444 </PRE>
12445 </DIV>
12446 <H3><A name="Typemaps_special_variables"></A>10.4.3 Special variables</H3>
12447 <P> Within all typemaps, the following special variables are expanded.
12448  This is by no means a complete list as some target languages have
12449  additional special variables which are documented in the language
12450  specific chapters.</P>
12451 <CENTER>
12452 <TABLE border="1" summary="Typemap special variables">
12453 <TR><TH>Variable</TH><TH>Meaning</TH></TR>
12454 <TR><TD>$<EM>n</EM></TD><TD> A C local variable corresponding to type<EM>
12455  n</EM> in the typemap pattern.</TD></TR>
12456 <TR><TD>$argnum</TD><TD>Argument number. Only available in typemaps
12457  related to argument conversion</TD></TR>
12458 <TR><TD>$<EM>n</EM>_name</TD><TD>Argument name</TD></TR>
12459 <TR><TD>$<EM>n</EM>_type</TD><TD>Real C datatype of type<EM> n</EM>.</TD>
12460 </TR>
12461 <TR><TD>$<EM>n</EM>_ltype</TD><TD>ltype of type<EM> n</EM></TD></TR>
12462 <TR><TD>$<EM>n</EM>_mangle</TD><TD>Mangled form of type<EM> n</EM>. For
12463  example <TT>_p_Foo</TT></TD></TR>
12464 <TR><TD>$<EM>n</EM>_descriptor</TD><TD>Type descriptor structure for
12465  type<EM> n</EM>. For example <TT>SWIGTYPE_p_Foo</TT>. This is primarily
12466  used when interacting with the run-time type checker (described later).</TD>
12467 </TR>
12468 <TR><TD>$*<EM>n</EM>_type</TD><TD>Real C datatype of type<EM> n</EM>
12469  with one pointer removed.</TD></TR>
12470 <TR><TD>$*<EM>n</EM>_ltype</TD><TD>ltype of type<EM> n</EM> with one
12471  pointer removed.</TD></TR>
12472 <TR><TD>$*<EM>n</EM>_mangle</TD><TD>Mangled form of type<EM> n</EM> with
12473  one pointer removed.</TD></TR>
12474 <TR><TD>$*<EM>n</EM>_descriptor</TD><TD>Type descriptor structure for
12475  type<EM> n</EM> with one pointer removed.</TD></TR>
12476 <TR><TD>$&amp;<EM>n</EM>_type</TD><TD>Real C datatype of type<EM> n</EM>
12477  with one pointer added.</TD></TR>
12478 <TR><TD>$&amp;<EM>n</EM>_ltype</TD><TD>ltype of type<EM> n</EM> with one
12479  pointer added.</TD></TR>
12480 <TR><TD>$&amp;<EM>n</EM>_mangle</TD><TD>Mangled form of type<EM> n</EM> with
12481  one pointer added.</TD></TR>
12482 <TR><TD>$&amp;<EM>n</EM>_descriptor</TD><TD>Type descriptor structure for
12483  type<EM> n</EM> with one pointer added.</TD></TR>
12484 <TR><TD>$<EM>n</EM>_basetype</TD><TD>Base typename with all pointers and
12485  qualifiers stripped.</TD></TR>
12486 </TABLE>
12487 </CENTER>
12488 <P> Within the table, $<EM>n</EM> refers to a specific type within the
12489  typemap specification. For example, if you write this</P>
12490 <DIV class="code">
12491 <PRE>
12492 %typemap(in) int *INPUT {
12493
12494 }
12495 </PRE>
12496 </DIV>
12497 <P> then $1 refers to <TT>int *INPUT</TT>. If you have a typemap like
12498  this,</P>
12499 <DIV class="code">
12500 <PRE>
12501 %typemap(in) (int argc, char *argv[]) {
12502   ...
12503 }
12504 </PRE>
12505 </DIV>
12506 <P> then $1 refers to <TT>int argc</TT> and $2 refers to <TT>char
12507  *argv[]</TT>.</P>
12508 <P> Substitutions related to types and names always fill in values from
12509  the actual code that was matched. This is useful when a typemap might
12510  match multiple C datatype. For example:</P>
12511 <DIV class="code">
12512 <PRE>
12513 %typemap(in)  int, short, long {
12514    $1 = ($1_ltype) PyInt_AsLong($input);
12515 }
12516 </PRE>
12517 </DIV>
12518 <P> In this case, <TT>$1_ltype</TT> is replaced with the datatype that
12519  is actually matched.</P>
12520 <P> When typemap code is emitted, the C/C++ datatype of the special
12521  variables <TT>$1</TT> and <TT>$2</TT> is always an &quot;ltype.&quot; An &quot;ltype&quot;
12522  is simply a type that can legally appear on the left-hand side of a C
12523  assignment operation. Here are a few examples of types and ltypes:</P>
12524 <DIV class="diagram">
12525 <PRE>
12526 type              ltype
12527 ------            ----------------
12528 int               int
12529 const int         int
12530 const int *       int *
12531 int [4]           int *
12532 int [4][5]        int (*)[5]
12533 </PRE>
12534 </DIV>
12535 <P> In most cases a ltype is simply the C datatype with qualifiers
12536  stripped off. In addition, arrays are converted into pointers.</P>
12537 <P> Variables such as <TT>$&amp;1_type</TT> and <TT>$*1_type</TT> are used
12538  to safely modify the type by removing or adding pointers. Although not
12539  needed in most typemaps, these substitutions are sometimes needed to
12540  properly work with typemaps that convert values between pointers and
12541  values.</P>
12542 <P> If necessary, type related substitutions can also be used when
12543  declaring locals. For example:</P>
12544 <DIV class="code">
12545 <PRE>
12546 %typemap(in) int * ($*1_type temp) {
12547     temp = PyInt_AsLong($input);
12548     $1 = &amp;temp;
12549 }
12550 </PRE>
12551 </DIV>
12552 <P> There is one word of caution about declaring local variables in this
12553  manner. If you declare a local variable using a type substitution such
12554  as <TT>$1_ltype temp</TT>, it won't work like you expect for arrays and
12555  certain kinds of pointers. For example, if you wrote this,</P>
12556 <DIV class="code">
12557 <PRE>
12558 %typemap(in) int [10][20] {
12559    $1_ltype temp;
12560 }
12561 </PRE>
12562 </DIV>
12563 <P> then the declaration of <TT>temp</TT> will be expanded as</P>
12564 <DIV class="code">
12565 <PRE>
12566 int (*)[20] temp;
12567 </PRE>
12568 </DIV>
12569 <P> This is illegal C syntax and won't compile. There is currently no
12570  straightforward way to work around this problem in SWIG due to the way
12571  that typemap code is expanded and processed. However, one possible
12572  workaround is to simply pick an alternative type such as <TT>void *</TT>
12573  and use casts to get the correct type when needed. For example:</P>
12574 <DIV class="code">
12575 <PRE>
12576 %typemap(in) int [10][20] {
12577    void *temp;
12578    ...
12579    (($1_ltype) temp)[i][j] = x;    /* set a value */
12580    ...
12581 }
12582 </PRE>
12583 </DIV>
12584 <P> Another approach, which only works for arrays is to use the <TT>
12585 $1_basetype</TT> substitution. For example:</P>
12586 <DIV class="code">
12587 <PRE>
12588 %typemap(in) int [10][20] {
12589    $1_basetype temp[10][20];
12590    ...
12591    temp[i][j] = x;    /* set a value */
12592    ...
12593 }
12594 </PRE>
12595 </DIV>
12596 <H3><A name="Typemaps_special_variable_macros"></A>10.4.4 Special
12597  variable macros</H3>
12598 <P> Special variable macros are like macro functions in that they take
12599  one or more input arguments which are used for the macro expansion.
12600  They look like macro/function calls but use the special variable <TT>$</TT>
12601  prefix to the macro name. Note that unlike normal macros, the expansion
12602  is not done by the preprocessor, it is done during the SWIG
12603  parsing/compilation stages. The following special variable macros are
12604  available across all language modules.</P>
12605 <H4><A name="Typemaps_special_macro_descriptor"></A>10.4.4.1
12606  $descriptor(type)</H4>
12607 <P> This macro expands into the type descriptor structure for any C/C++
12608  type specified in <TT>type</TT>. It behaves like the <TT>$1_descriptor</TT>
12609  special variable described above except that the type to expand is
12610  taken from the macro argument rather than inferred from the typemap
12611  type. For example, <TT>$descriptor(std::vector&lt;int&gt; *)</TT> will expand
12612  into <TT>SWIGTYPE_p_std__vectorT_int_t</TT>. This macro is mostly used
12613  in the scripting target languages and is demonstrated later in the <A href="#Typemaps_runtime_type_checker_usage">
12614 Run-time type checker usage</A> section.</P>
12615 <H4><A name="Typemaps_special_macro_typemap"></A>10.4.4.2
12616  $typemap(method, typepattern)</H4>
12617 <P> This macro uses the <A href="#Typemaps_pattern_matching">pattern
12618  matching rules</A> described earlier to lookup and then substitute the
12619  special variable macro with the code in the matched typemap. The
12620  typemap to search for is specified by the arguments, where <TT>method</TT>
12621  is the typemap method name and <TT>typepattern</TT> is a type pattern
12622  as per the <TT>%typemap</TT> specification in the <A href="#Typemaps_defining">
12623 Defining a typemap</A> section.</P>
12624 <P> The special variables within the matched typemap are expanded into
12625  those for the matched typemap type, not the typemap within which the
12626  macro is called. In practice, there is little use for this macro in the
12627  scripting target languages. It is mostly used in the target languages
12628  that are statically typed as a way to obtain the target language type
12629  given the C/C++ type and more commonly only when the C++ type is a
12630  template parameter.</P>
12631 <P> The example below is for C# only and uses some typemap method names
12632  documented in the C# chapter, but it shows some of the possible syntax
12633  variations.</P>
12634 <DIV class="code">
12635 <PRE>
12636 %typemap(cstype) unsigned long    &quot;uint&quot;
12637 %typemap(cstype) unsigned long bb &quot;bool&quot;
12638 %typemap(cscode) BarClass %{
12639   void foo($typemap(cstype, unsigned long aa) var1,
12640            $typemap(cstype, unsigned long bb) var2,
12641            $typemap(cstype, (unsigned long bb)) var3,
12642            $typemap(cstype, unsigned long) var4)
12643   {
12644     // do something
12645   }
12646 %}
12647 </PRE>
12648 </DIV>
12649 <P> The result is the following expansion</P>
12650 <DIV class="code">
12651 <PRE>
12652 %typemap(cstype) unsigned long    &quot;uint&quot;
12653 %typemap(cstype) unsigned long bb &quot;bool&quot;
12654 %typemap(cscode) BarClass %{
12655   void foo(uint var1,
12656            bool var2,
12657            bool var3,
12658            uint var4)
12659   {
12660     // do something
12661   }
12662 %}
12663 </PRE>
12664 </DIV>
12665 <H2><A name="Typemaps_nn25"></A>10.5 Common typemap methods</H2>
12666 <P> The set of typemaps recognized by a language module may vary.
12667  However, the following typemap methods are nearly universal:</P>
12668 <H3><A name="Typemaps_nn26"></A>10.5.1 &quot;in&quot; typemap</H3>
12669 <P> The &quot;in&quot; typemap is used to convert function arguments from the
12670  target language to C. For example:</P>
12671 <DIV class="code">
12672 <PRE>
12673 %typemap(in) int {
12674    $1 = PyInt_AsLong($input);
12675 }
12676 </PRE>
12677 </DIV>
12678 <P> The following special variables are available:</P>
12679 <DIV class="code">
12680 <PRE>
12681 $input            - Input object holding value to be converted.
12682 $symname          - Name of function/method being wrapped
12683 </PRE>
12684 </DIV>
12685 <P> This is probably the most commonly redefined typemap because it can
12686  be used to implement customized conversions.</P>
12687 <P> In addition, the &quot;in&quot; typemap allows the number of converted
12688  arguments to be specified. The <TT>numinputs</TT> attributes
12689  facilitates this. For example:</P>
12690 <DIV class="code">
12691 <PRE>
12692 // Ignored argument.
12693 %typemap(in, numinputs=0) int *out (int temp) {
12694     $1 = &amp;temp;
12695 }
12696 </PRE>
12697 </DIV>
12698 <P> At this time, only zero or one arguments may be converted. When <TT>
12699 numinputs</TT> is set to 0, the argument is effectively ignored and
12700  cannot be supplied from the target language. The argument is still
12701  required when making the C/C++ call and the above typemap shows the
12702  value used is instead obtained from a locally declared variable called <TT>
12703 temp</TT>. Usually <TT>numinputs</TT> is not specified, whereupon the
12704  default value is 1, that is, there is a one to one mapping of the
12705  number of arguments when used from the target language to the C/C++
12706  call. <A href="#Typemaps_multi_argument_typemaps">Multi-argument
12707  typemaps</A> provide a similar concept where the number of arguments
12708  mapped from the target language to C/C++ can be changed for more tha
12709  multiple adjacent C/C++ arguments.</P>
12710 <P><B> Compatibility note:</B> Specifying <TT>numinputs=0</TT> is the
12711  same as the old &quot;ignore&quot; typemap.</P>
12712 <H3><A name="Typemaps_nn27"></A>10.5.2 &quot;typecheck&quot; typemap</H3>
12713 <P> The &quot;typecheck&quot; typemap is used to support overloaded functions and
12714  methods. It merely checks an argument to see whether or not it matches
12715  a specific type. For example:</P>
12716 <DIV class="code">
12717 <PRE>
12718 %typemap(typecheck,precedence=SWIG_TYPECHECK_INTEGER) int {
12719    $1 = PyInt_Check($input) ? 1 : 0;
12720 }
12721 </PRE>
12722 </DIV>
12723 <P> For typechecking, the $1 variable is always a simple integer that is
12724  set to 1 or 0 depending on whether or not the input argument is the
12725  correct type.</P>
12726 <P> If you define new &quot;in&quot; typemaps<EM> and</EM> your program uses
12727  overloaded methods, you should also define a collection of &quot;typecheck&quot;
12728  typemaps. More details about this follow in a later section on
12729  &quot;Typemaps and Overloading.&quot;</P>
12730 <H3><A name="Typemaps_nn28"></A>10.5.3 &quot;out&quot; typemap</H3>
12731 <P> The &quot;out&quot; typemap is used to convert function/method return values
12732  from C into the target language. For example:</P>
12733 <DIV class="code">
12734 <PRE>
12735 %typemap(out) int {
12736    $result = PyInt_FromLong($1);
12737 }
12738 </PRE>
12739 </DIV>
12740 <P> The following special variables are available.</P>
12741 <DIV class="code">
12742 <PRE>
12743 $result           - Result object returned to target language.
12744 $symname          - Name of function/method being wrapped
12745 </PRE>
12746 </DIV>
12747 <P> The &quot;out&quot; typemap supports an optional attribute flag called
12748  &quot;optimal&quot;. This is for code optimisation and is detailed in the <A href="#Typemaps_optimal">
12749 Optimal code generation when returning by value</A> section.</P>
12750 <H3><A name="Typemaps_nn29"></A>10.5.4 &quot;arginit&quot; typemap</H3>
12751 <P> The &quot;arginit&quot; typemap is used to set the initial value of a function
12752  argument--before any conversion has occurred. This is not normally
12753  necessary, but might be useful in highly specialized applications. For
12754  example:</P>
12755 <DIV class="code">
12756 <PRE>
12757 // Set argument to NULL before any conversion occurs
12758 %typemap(arginit) int *data {
12759    $1 = NULL;
12760 }
12761 </PRE>
12762 </DIV>
12763 <H3><A name="Typemaps_nn30"></A>10.5.5 &quot;default&quot; typemap</H3>
12764 <P> The &quot;default&quot; typemap is used to turn an argument into a default
12765  argument. For example:</P>
12766 <DIV class="code">
12767 <PRE>
12768 %typemap(default) int flags {
12769    $1 = DEFAULT_FLAGS;
12770 }
12771 ...
12772 int foo(int x, int y, int flags);
12773 </PRE>
12774 </DIV>
12775 <P> The primary use of this typemap is to either change the wrapping of
12776  default arguments or specify a default argument in a language where
12777  they aren't supported (like C). Target languages that do not support
12778  optional arguments, such as Java and C#, effectively ignore the value
12779  specified by this typemap as all arguments must be given.</P>
12780 <P> Once a default typemap has been applied to an argument, all
12781  arguments that follow must have default values. See the <A href="#SWIG_default_args">
12782 Default/optional arguments</A> section for further information on
12783  default argument wrapping.</P>
12784 <H3><A name="Typemaps_nn31"></A>10.5.6 &quot;check&quot; typemap</H3>
12785 <P> The &quot;check&quot; typemap is used to supply value checking code during
12786  argument conversion. The typemap is applied<EM> after</EM> arguments
12787  have been converted. For example:</P>
12788 <DIV class="code">
12789 <PRE>
12790 %typemap(check) int positive {
12791    if ($1 &lt;= 0) {
12792        SWIG_exception(SWIG_ValueError,&quot;Expected positive value.&quot;);
12793    }
12794 }
12795 </PRE>
12796 </DIV>
12797 <H3><A name="Typemaps_nn32"></A>10.5.7 &quot;argout&quot; typemap</H3>
12798 <P> The &quot;argout&quot; typemap is used to return values from arguments. This
12799  is most commonly used to write wrappers for C/C++ functions that need
12800  to return multiple values. The &quot;argout&quot; typemap is almost always
12801  combined with an &quot;in&quot; typemap---possibly to ignore the input value. For
12802  example:</P>
12803 <DIV class="code">
12804 <PRE>
12805 /* Set the input argument to point to a temporary variable */
12806 %typemap(in, numinputs=0) int *out (int temp) {
12807    $1 = &amp;temp;
12808 }
12809
12810 %typemap(argout) int *out {
12811    // Append output value $1 to $result
12812    ...
12813 }
12814 </PRE>
12815 </DIV>
12816 <P> The following special variables are available.</P>
12817 <DIV class="diagram">
12818 <PRE>
12819 $result           - Result object returned to target language.
12820 $input            - The original input object passed.
12821 $symname          - Name of function/method being wrapped
12822 </PRE>
12823 </DIV>
12824 <P> The code supplied to the &quot;argout&quot; typemap is always placed after the
12825  &quot;out&quot; typemap. If multiple return values are used, the extra return
12826  values are often appended to return value of the function.</P>
12827 <P> See the <TT>typemaps.i</TT> library for examples.</P>
12828 <H3><A name="Typemaps_nn33"></A>10.5.8 &quot;freearg&quot; typemap</H3>
12829 <P> The &quot;freearg&quot; typemap is used to cleanup argument data. It is only
12830  used when an argument might have allocated resources that need to be
12831  cleaned up when the wrapper function exits. The &quot;freearg&quot; typemap
12832  usually cleans up argument resources allocated by the &quot;in&quot; typemap. For
12833  example:</P>
12834 <DIV class="code">
12835 <PRE>
12836 // Get a list of integers
12837 %typemap(in) int *items {
12838    int nitems = Length($input);    
12839    $1 = (int *) malloc(sizeof(int)*nitems);
12840 }
12841 // Free the list 
12842 %typemap(freearg) int *items {
12843    free($1);
12844 }
12845 </PRE>
12846 </DIV>
12847 <P> The &quot;freearg&quot; typemap inserted at the end of the wrapper function,
12848  just before control is returned back to the target language. This code
12849  is also placed into a special variable <TT>$cleanup</TT> that may be
12850  used in other typemaps whenever a wrapper function needs to abort
12851  prematurely.</P>
12852 <H3><A name="Typemaps_nn34"></A>10.5.9 &quot;newfree&quot; typemap</H3>
12853 <P> The &quot;newfree&quot; typemap is used in conjunction with the <TT>%newobject</TT>
12854  directive and is used to deallocate memory used by the return result of
12855  a function. For example:</P>
12856 <DIV class="code">
12857 <PRE>
12858 %typemap(newfree) string * {
12859    delete $1;
12860 }
12861 %typemap(out) string * {
12862    $result = PyString_FromString($1-&gt;c_str());
12863 }
12864 ...
12865
12866 %newobject foo;
12867 ...
12868 string *foo();
12869 </PRE>
12870 </DIV>
12871 <P> See <A href="#ownership">Object ownership and %newobject</A> for
12872  further details.</P>
12873 <H3><A name="Typemaps_nn35"></A>10.5.10 &quot;memberin&quot; typemap</H3>
12874 <P> The &quot;memberin&quot; typemap is used to copy data from<EM> an already
12875  converted input value</EM> into a structure member. It is typically
12876  used to handle array members and other special cases. For example:</P>
12877 <DIV class="code">
12878 <PRE>
12879 %typemap(memberin) int [4] {
12880    memmove($1, $input, 4*sizeof(int));
12881 }
12882 </PRE>
12883 </DIV>
12884 <P> It is rarely necessary to write &quot;memberin&quot; typemaps---SWIG already
12885  provides a default implementation for arrays, strings, and other
12886  objects.</P>
12887 <H3><A name="Typemaps_nn36"></A>10.5.11 &quot;varin&quot; typemap</H3>
12888 <P> The &quot;varin&quot; typemap is used to convert objects in the target
12889  language to C for the purposes of assigning to a C/C++ global variable.
12890  This is implementation specific.</P>
12891 <H3><A name="Typemaps_nn37"></A>10.5.12 &quot;varout&quot; typemap</H3>
12892 <P> The &quot;varout&quot; typemap is used to convert a C/C++ object to an object
12893  in the target language when reading a C/C++ global variable. This is
12894  implementation specific.</P>
12895 <H3><A name="throws_typemap"></A>10.5.13 &quot;throws&quot; typemap</H3>
12896 <P> The &quot;throws&quot; typemap is only used when SWIG parses a C++ method with
12897  an exception specification or has the <TT>%catches</TT> feature
12898  attached to the method. It provides a default mechanism for handling
12899  C++ methods that have declared the exceptions they will throw. The
12900  purpose of this typemap is to convert a C++ exception into an error or
12901  exception in the target language. It is slightly different to the other
12902  typemaps as it is based around the exception type rather than the type
12903  of a parameter or variable. For example:</P>
12904 <DIV class="code">
12905 <PRE>
12906 %typemap(throws) const char * %{
12907   PyErr_SetString(PyExc_RuntimeError, $1);
12908   SWIG_fail;
12909 %}
12910 void bar() throw (const char *);
12911 </PRE>
12912 </DIV>
12913 <P> As can be seen from the generated code below, SWIG generates an
12914  exception handler with the catch block comprising the &quot;throws&quot; typemap
12915  content.</P>
12916 <DIV class="code">
12917 <PRE>
12918 ...
12919 try {
12920     bar();
12921 }
12922 catch(char const *_e) {
12923     PyErr_SetString(PyExc_RuntimeError, _e);
12924     SWIG_fail;
12925     
12926 }
12927 ...
12928 </PRE>
12929 </DIV>
12930 <P> Note that if your methods do not have an exception specification yet
12931  they do throw exceptions, SWIG cannot know how to deal with them. For a
12932  neat way to handle these, see the <A href="#exception">Exception
12933  handling with %exception</A> section.</P>
12934 <H2><A name="Typemaps_nn39"></A>10.6 Some typemap examples</H2>
12935 <P> This section contains a few examples. Consult language module
12936  documentation for more examples.</P>
12937 <H3><A name="Typemaps_nn40"></A>10.6.1 Typemaps for arrays</H3>
12938 <P> A common use of typemaps is to provide support for C arrays
12939  appearing both as arguments to functions and as structure members.</P>
12940 <P> For example, suppose you had a function like this:</P>
12941 <DIV class="code">
12942 <PRE>
12943 void set_vector(int type, float value[4]);
12944 </PRE>
12945 </DIV>
12946 <P> If you wanted to handle <TT>float value[4]</TT> as a list of floats,
12947  you might write a typemap similar to this:</P>
12948 <DIV class="code">
12949 <PRE>
12950
12951 %typemap(in) float value[4] (float temp[4]) {
12952   int i;
12953   if (!PySequence_Check($input)) {
12954     PyErr_SetString(PyExc_ValueError,&quot;Expected a sequence&quot;);
12955     return NULL;
12956   }
12957   if (PySequence_Length($input) != 4) {
12958     PyErr_SetString(PyExc_ValueError,&quot;Size mismatch. Expected 4 elements&quot;);
12959     return NULL;
12960   }
12961   for (i = 0; i &lt; 4; i++) {
12962     PyObject *o = PySequence_GetItem($input,i);
12963     if (PyNumber_Check(o)) {
12964       temp[i] = (float) PyFloat_AsDouble(o);
12965     } else {
12966       PyErr_SetString(PyExc_ValueError,&quot;Sequence elements must be numbers&quot;);      
12967       return NULL;
12968     }
12969   }
12970   $1 = temp;
12971 }
12972 </PRE>
12973 </DIV>
12974 <P> In this example, the variable <TT>temp</TT> allocates a small array
12975  on the C stack. The typemap then populates this array and passes it to
12976  the underlying C function.</P>
12977 <P> When used from Python, the typemap allows the following type of
12978  function call:</P>
12979 <DIV class="targetlang">
12980 <PRE>
12981 &gt;&gt;&gt; set_vector(type, [ 1, 2.5, 5, 20 ])
12982 </PRE>
12983 </DIV>
12984 <P> If you wanted to generalize the typemap to apply to arrays of all
12985  dimensions you might write this:</P>
12986 <DIV class="code">
12987 <PRE>
12988 %typemap(in) float value[ANY] (float temp[$1_dim0]) {
12989   int i;
12990   if (!PySequence_Check($input)) {
12991     PyErr_SetString(PyExc_ValueError,&quot;Expected a sequence&quot;);
12992     return NULL;
12993   }
12994   if (PySequence_Length($input) != $1_dim0) {
12995     PyErr_SetString(PyExc_ValueError,&quot;Size mismatch. Expected $1_dim0 elements&quot;);
12996     return NULL;
12997   }
12998   for (i = 0; i &lt; $1_dim0; i++) {
12999     PyObject *o = PySequence_GetItem($input,i);
13000     if (PyNumber_Check(o)) {
13001       temp[i] = (float) PyFloat_AsDouble(o);
13002     } else {
13003       PyErr_SetString(PyExc_ValueError,&quot;Sequence elements must be numbers&quot;);      
13004       return NULL;
13005     }
13006   }
13007   $1 = temp;
13008 }
13009 </PRE>
13010 </DIV>
13011 <P> In this example, the special variable <TT>$1_dim0</TT> is expanded
13012  with the actual array dimensions. Multidimensional arrays can be
13013  matched in a similar manner. For example:</P>
13014 <DIV class="code">
13015 <PRE>
13016 %typemap(in) float matrix[ANY][ANY] (float temp[$1_dim0][$1_dim1]) {
13017    ... convert a 2d array ...
13018 }
13019 </PRE>
13020 </DIV>
13021 <P> For large arrays, it may be impractical to allocate storage on the
13022  stack using a temporary variable as shown. To work with heap allocated
13023  data, the following technique can be used.</P>
13024 <DIV class="code">
13025 <PRE>
13026 %typemap(in) float value[ANY] {
13027   int i;
13028   if (!PySequence_Check($input)) {
13029     PyErr_SetString(PyExc_ValueError,&quot;Expected a sequence&quot;);
13030     return NULL;
13031   }
13032   if (PySequence_Length($input) != $1_dim0) {
13033     PyErr_SetString(PyExc_ValueError,&quot;Size mismatch. Expected $1_dim0 elements&quot;);
13034     return NULL;
13035   }
13036   $1 = (float *) malloc($1_dim0*sizeof(float));
13037   for (i = 0; i &lt; $1_dim0; i++) {
13038     PyObject *o = PySequence_GetItem($input,i);
13039     if (PyNumber_Check(o)) {
13040       $1[i] = (float) PyFloat_AsDouble(o);
13041     } else {
13042       PyErr_SetString(PyExc_ValueError,&quot;Sequence elements must be numbers&quot;);      
13043       free($1);
13044       return NULL;
13045     }
13046   }
13047 }
13048 %typemap(freearg) float value[ANY] {
13049    if ($1) free($1);
13050 }
13051 </PRE>
13052 </DIV>
13053 <P> In this case, an array is allocated using <TT>malloc</TT>. The <TT>
13054 freearg</TT> typemap is then used to release the argument after the
13055  function has been called.</P>
13056 <P> Another common use of array typemaps is to provide support for array
13057  structure members. Due to subtle differences between pointers and
13058  arrays in C, you can't just &quot;assign&quot; to a array structure member.
13059  Instead, you have to explicitly copy elements into the array. For
13060  example, suppose you had a structure like this:</P>
13061 <DIV class="code">
13062 <PRE>
13063 struct SomeObject {
13064         float  value[4];
13065         ...
13066 };
13067 </PRE>
13068 </DIV>
13069 <P> When SWIG runs, it won't produce any code to set the <TT>vec</TT>
13070  member. You may even get a warning message like this:</P>
13071 <DIV class="shell">
13072 <PRE>
13073 swig -python  example.i
13074 Generating wrappers for Python
13075 example.i:10.  Warning. Array member value will be read-only.
13076 </PRE>
13077 </DIV>
13078 <P> These warning messages indicate that SWIG does not know how you want
13079  to set the <TT>vec</TT> field.</P>
13080 <P> To fix this, you can supply a special &quot;memberin&quot; typemap like this:</P>
13081 <DIV class="code">
13082 <PRE>
13083 %typemap(memberin) float [ANY] {
13084   int i;
13085   for (i = 0; i &lt; $1_dim0; i++) {
13086       $1[i] = $input[i];
13087   }
13088 }
13089 </PRE>
13090 </DIV>
13091 <P> The memberin typemap is used to set a structure member from data
13092  that has already been converted from the target language to C. In this
13093  case, <TT>$input</TT> is the local variable in which converted input
13094  data is stored. This typemap then copies this data into the structure.</P>
13095 <P> When combined with the earlier typemaps for arrays, the combination
13096  of the &quot;in&quot; and &quot;memberin&quot; typemap allows the following usage:</P>
13097 <DIV class="targetlang">
13098 <PRE>
13099 &gt;&gt;&gt; s = SomeObject()
13100 &gt;&gt;&gt; s.x = [1, 2.5, 5, 10]
13101 </PRE>
13102 </DIV>
13103 <P> Related to structure member input, it may be desirable to return
13104  structure members as a new kind of object. For example, in this
13105  example, you will get very odd program behavior where the structure
13106  member can be set nicely, but reading the member simply returns a
13107  pointer:</P>
13108 <DIV class="targetlang">
13109 <PRE>
13110 &gt;&gt;&gt; s = SomeObject()
13111 &gt;&gt;&gt; s.x = [1, 2.5, 5, 10]
13112 &gt;&gt;&gt; print s.x
13113 _1008fea8_p_float
13114 &gt;&gt;&gt; 
13115 </PRE>
13116 </DIV>
13117 <P> To fix this, you can write an &quot;out&quot; typemap. For example:</P>
13118 <DIV class="code">
13119 <PRE>
13120 %typemap(out) float [ANY] {
13121   int i;
13122   $result = PyList_New($1_dim0);
13123   for (i = 0; i &lt; $1_dim0; i++) {
13124     PyObject *o = PyFloat_FromDouble((double) $1[i]);
13125     PyList_SetItem($result,i,o);
13126   }
13127 }
13128 </PRE>
13129 </DIV>
13130 <P> Now, you will find that member access is quite nice:</P>
13131 <DIV class="targetlang">
13132 <PRE>
13133 &gt;&gt;&gt; s = SomeObject()
13134 &gt;&gt;&gt; s.x = [1, 2.5, 5, 10]
13135 &gt;&gt;&gt; print s.x
13136 [ 1, 2.5, 5, 10]
13137 </PRE>
13138 </DIV>
13139 <P><B> Compatibility Note:</B> SWIG1.1 used to provide a special
13140  &quot;memberout&quot; typemap. However, it was mostly useless and has since been
13141  eliminated. To return structure members, simply use the &quot;out&quot; typemap.</P>
13142 <H3><A name="Typemaps_nn41"></A>10.6.2 Implementing constraints with
13143  typemaps</H3>
13144 <P> One particularly interesting application of typemaps is the
13145  implementation of argument constraints. This can be done with the
13146  &quot;check&quot; typemap. When used, this allows you to provide code for
13147  checking the values of function arguments. For example :</P>
13148 <DIV class="code">
13149 <PRE>
13150 %module math
13151
13152 %typemap(check) double posdouble {
13153         if ($1 &lt; 0) {
13154                 croak(&quot;Expecting a positive number&quot;);
13155         }
13156 }
13157
13158 ...
13159 double sqrt(double posdouble);
13160
13161 </PRE>
13162 </DIV>
13163 <P> This provides a sanity check to your wrapper function. If a negative
13164  number is passed to this function, a Perl exception will be raised and
13165  your program terminated with an error message.</P>
13166 <P> This kind of checking can be particularly useful when working with
13167  pointers. For example :</P>
13168 <DIV class="code">
13169 <PRE>
13170 %typemap(check) Vector * {
13171     if ($1 == 0) {
13172         PyErr_SetString(PyExc_TypeError,&quot;NULL Pointer not allowed&quot;);
13173         return NULL;
13174    }
13175 }
13176
13177 </PRE>
13178 </DIV>
13179 <P> will prevent any function involving a <TT>Vector *</TT> from
13180  accepting a NULL pointer. As a result, SWIG can often prevent a
13181  potential segmentation faults or other run-time problems by raising an
13182  exception rather than blindly passing values to the underlying C/C++
13183  program.</P>
13184 <P> Note: A more advanced constraint checking system is in development.
13185  Stay tuned.</P>
13186 <H2><A name="Typemaps_nn43"></A>10.7 Typemaps for multiple languages</H2>
13187 <P> The code within typemaps is usually language dependent, however,
13188  many languages support the same typemaps. In order to distinguish
13189  typemaps across different languages, the preprocessor should be used.
13190  For example, the &quot;in&quot; typemap for Perl and Ruby could be written as:</P>
13191 <DIV class="code">
13192 <PRE>
13193 #if defined(SWIGPERL)
13194   %typemap(in) int &quot;$1 = ($1_ltype) SvIV($input);&quot;
13195 #elif defined(SWIGRUBY)
13196   %typemap(in) int &quot;$1 = NUM2INT($input);&quot;
13197 #else
13198   #warning no &quot;in&quot; typemap defined
13199 #endif
13200 </PRE>
13201 </DIV>
13202 <P> The full set of language specific macros is defined in the <A href="#Preprocessor_condition_compilation">
13203 Conditional Compilation</A> section. The example above also shows a
13204  common approach of issuing a warning for an as yet unsupported
13205  language.</P>
13206 <P><B> Compatibility note:</B> In SWIG-1.1 different languages could be
13207  distinguished with the language name being put within the <TT>%typemap</TT>
13208  directive, for example,
13209 <BR> <TT>%typemap(ruby,in) int &quot;$1 = NUM2INT($input);&quot;</TT>.</P>
13210 <H2><A name="Typemaps_optimal"></A>10.8 Optimal code generation when
13211  returning by value</H2>
13212 <P> The &quot;out&quot; typemap is the main typemap for return types. This typemap
13213  supports an optional attribute flag called &quot;optimal&quot;, which is for
13214  reducing temporary variables and the amount of generated code, thereby
13215  giving the compiler the opportunity to use<I> return value optimization</I>
13216  for generating faster executing code. It only really makes a difference
13217  when returning objects by value and has some limitations on usage, as
13218  explained later on.</P>
13219 <P> When a function returns an object by value, SWIG generates code that
13220  instantiates the default type on the stack then assigns the value
13221  returned by the function call to it. A copy of this object is then made
13222  on the heap and this is what is ultimately stored and used from the
13223  target language. This will be clearer considering an example. Consider
13224  running the following code through SWIG:</P>
13225 <DIV class="code">
13226 <PRE>
13227 %typemap(out) SWIGTYPE %{
13228   $result = new $1_ltype((const $1_ltype &amp;)$1);
13229 %}
13230
13231 %inline %{
13232 #include &lt;iostream&gt;
13233 using namespace std;
13234
13235 struct XX {
13236   XX() { cout &lt;&lt; &quot;XX()&quot; &lt;&lt; endl; }
13237   XX(int i) { cout &lt;&lt; &quot;XX(&quot; &lt;&lt; i &lt;&lt; &quot;)&quot; &lt;&lt; endl; }
13238   XX(const XX &amp;other) { cout &lt;&lt; &quot;XX(const XX &amp;)&quot; &lt;&lt; endl; }
13239   XX &amp; operator =(const XX &amp;other) { cout &lt;&lt; &quot;operator=(const XX &amp;)&quot; &lt;&lt; endl; return *this; }
13240   ~XX() { cout &lt;&lt; &quot;~XX()&quot; &lt;&lt; endl; }
13241   static XX create() { 
13242     return XX(0);
13243   }
13244 };
13245 %}
13246 </PRE>
13247 </DIV>
13248 <P> The &quot;out&quot; typemap shown is the default typemap for C# when returning
13249  by objects by value. When making a call to <TT>XX::create()</TT> from
13250  C#, the output is as follows:</P>
13251 <DIV class="targetlang">
13252 <PRE>
13253 XX()
13254 XX(0)
13255 operator=(const XX &amp;)
13256 ~XX()
13257 XX(const XX &amp;)
13258 ~XX()
13259 ~XX()
13260 </PRE>
13261 </DIV>
13262 <P> Note that three objects are being created as well as an assignment.
13263  Wouldn't it be great if the <TT>XX::create()</TT> method was the only
13264  time a constructor was called? As the method returns by value, this is
13265  asking a lot and the code that SWIG generates by default makes it
13266  impossible for the compiler to use<I> return value optimisation (RVO)</I>
13267 . However, this is where the &quot;optimal&quot; attribute in the &quot;out&quot; typemap
13268  can help out. If the typemap code is kept the same and just the
13269  &quot;optimal&quot; attribute specified like this:</P>
13270 <DIV class="code">
13271 <PRE>
13272 %typemap(out, optimal=&quot;1&quot;) SWIGTYPE %{
13273   $result = new $1_ltype((const $1_ltype &amp;)$1);
13274 %}
13275 </PRE>
13276 </DIV>
13277 <P> then when the code is run again, the output is simply:</P>
13278 <DIV class="targetlang">
13279 <PRE>
13280 XX(0)
13281 ~XX()
13282 </PRE>
13283 </DIV>
13284 <P> How the &quot;optimal&quot; attribute works is best explained using the
13285  generated code. Without &quot;optimal&quot;, the generated code is:</P>
13286 <DIV class="code">
13287 <PRE>
13288 SWIGEXPORT void * SWIGSTDCALL CSharp_XX_create() {
13289   void * jresult ;
13290   XX result;
13291   result = XX::create();
13292   jresult = new XX((const XX &amp;)result);
13293   return jresult;
13294 }
13295
13296 </PRE>
13297 </DIV>
13298 <P> With the &quot;optimal&quot; attribute, the code is:</P>
13299 <DIV class="code">
13300 <PRE>
13301 SWIGEXPORT void * SWIGSTDCALL CSharp_XX_create() {
13302   void * jresult ;
13303   jresult = new XX((const XX &amp;)XX::create());
13304   return jresult;
13305 }
13306 </PRE>
13307 </DIV>
13308 <P> The major difference is the <TT>result</TT> temporary variable
13309  holding the value returned from <TT>XX::create()</TT> is no longer
13310  generated and instead the copy constructor call is made directly from
13311  the value returned by <TT>XX::create()</TT>. With modern compilers
13312  implementing RVO, the copy is not actually done, in fact the object is
13313  never created on the stack in <TT>XX::create()</TT> at all, it is
13314  simply created directly on the heap. In the first instance, the <TT>$1</TT>
13315  special variable in the typemap is expanded into <TT>result</TT>. In
13316  the second instance, <TT>$1</TT> is expanded into <TT>XX::create()</TT>
13317  and this is essentially what the &quot;optimal&quot; attribute is telling SWIG to
13318  do.</P>
13319 <P> The &quot;optimal&quot; attribute optimisation is not turned on by default as
13320  it has a number of restrictions. Firstly, some code cannot be condensed
13321  into a simple call for passing into the copy constructor. One common
13322  occurrence is when <A href="#exception">%exception</A> is used.
13323  Consider adding the following <TT>%exception</TT> to the example:</P>
13324 <DIV class="code">
13325 <PRE>
13326 %exception XX::create() %{
13327 try {
13328   $action
13329 } catch(const std::exception &amp;e) {
13330   cout &lt;&lt; e.what() &lt;&lt; endl;
13331 }
13332 %}
13333 </PRE>
13334 </DIV>
13335 <P> SWIG can detect when the &quot;optimal&quot; attribute cannot be used and will
13336  ignore it and in this case will issue the following warning:</P>
13337 <DIV class="targetlang">
13338 <PRE>
13339 example.i:28: Warning(474): Method XX::create() usage of the optimal attribute in the out 
13340 typemap at example.i:14 ignored as the following cannot be used to generate optimal code: 
13341 try {
13342   result = XX::create();
13343 } catch(const std::exception &amp;e) {
13344   cout &lt;&lt; e.what() &lt;&lt; endl;
13345 }
13346 </PRE>
13347 </DIV>
13348 <P> It should be clear that the above code cannot be used as the
13349  argument to the copy constructor call, ie for the <TT>$1</TT>
13350  substitution.</P>
13351 <P> Secondly, if the typemaps uses <TT>$1</TT> more than once, then
13352  multiple calls to the wrapped function will be made. Obviously that is
13353  not very optimal. In fact SWIG attempts to detect this and will issue a
13354  warning something like:</P>
13355 <DIV class="targetlang">
13356 <PRE>
13357 example.i:21: Warning(475): Multiple calls to XX::create() might be generated due to 
13358 optimal attribute usage in the out typemap at example.i:7.
13359 </PRE>
13360 </DIV>
13361 <P> However, it doesn't always get it right, for example when <TT>$1</TT>
13362  is within some commented out code.</P>
13363 <H2><A name="Typemaps_multi_argument_typemaps"></A>10.9 Multi-argument
13364  typemaps</H2>
13365 <P> So far, the typemaps presented have focused on the problem of
13366  dealing with single values. For example, converting a single input
13367  object to a single argument in a function call. However, certain
13368  conversion problems are difficult to handle in this manner. As an
13369  example, consider the example at the very beginning of this chapter:</P>
13370 <DIV class="code">
13371 <PRE>
13372 int foo(int argc, char *argv[]);
13373 </PRE>
13374 </DIV>
13375 <P> Suppose that you wanted to wrap this function so that it accepted a
13376  single list of strings like this:</P>
13377 <DIV class="targetlang">
13378 <PRE>
13379 &gt;&gt;&gt; foo([&quot;ale&quot;,&quot;lager&quot;,&quot;stout&quot;])
13380 </PRE>
13381 </DIV>
13382 <P> To do this, you not only need to map a list of strings to <TT>char
13383  *argv[]</TT>, but the value of <TT>int argc</TT> is implicitly
13384  determined by the length of the list. Using only simple typemaps, this
13385  type of conversion is possible, but extremely painful. Therefore,
13386  SWIG1.3 introduces the notion of multi-argument typemaps.</P>
13387 <P> A multi-argument typemap is a conversion rule that specifies how to
13388  convert a<EM> single</EM> object in the target language to set of
13389  consecutive function arguments in C/C++. For example, the following
13390  multi-argument maps perform the conversion described for the above
13391  example:</P>
13392 <DIV class="code">
13393 <PRE>
13394 %typemap(in) (int argc, char *argv[]) {
13395   int i;
13396   if (!PyList_Check($input)) {
13397     PyErr_SetString(PyExc_ValueError, &quot;Expecting a list&quot;);
13398     return NULL;
13399   }
13400   $1 = PyList_Size($input);
13401   $2 = (char **) malloc(($1+1)*sizeof(char *));
13402   for (i = 0; i &lt; $1; i++) {
13403     PyObject *s = PyList_GetItem($input,i);
13404     if (!PyString_Check(s)) {
13405         free($2);
13406         PyErr_SetString(PyExc_ValueError, &quot;List items must be strings&quot;);
13407         return NULL;
13408     }
13409     $2[i] = PyString_AsString(s);
13410   }
13411   $2[i] = 0;
13412 }
13413
13414 %typemap(freearg) (int argc, char *argv[]) {
13415    if ($2) free($2);
13416 }
13417 </PRE>
13418 </DIV>
13419 <P> A multi-argument map is always specified by surrounding the
13420  arguments with parentheses as shown. For example:</P>
13421 <DIV class="code">
13422 <PRE>
13423 %typemap(in) (int argc, char *argv[]) { ... }
13424 </PRE>
13425 </DIV>
13426 <P> Within the typemap code, the variables <TT>$1</TT>, <TT>$2</TT>, and
13427  so forth refer to each type in the map. All of the usual substitutions
13428  apply--just use the appropriate <TT>$1</TT> or <TT>$2</TT> prefix on
13429  the variable name (e.g., <TT>$2_type</TT>, <TT>$1_ltype</TT>, etc.)</P>
13430 <P> Multi-argument typemaps always have precedence over simple typemaps
13431  and SWIG always performs longest-match searching. Therefore, you will
13432  get the following behavior:</P>
13433 <DIV class="code">
13434 <PRE>
13435 %typemap(in) int argc                              { ... typemap 1 ... }
13436 %typemap(in) (int argc, char *argv[])              { ... typemap 2 ... }
13437 %typemap(in) (int argc, char *argv[], char *env[]) { ... typemap 3 ... }
13438
13439 int foo(int argc, char *argv[]);                   // Uses typemap 2
13440 int bar(int argc, int x);                          // Uses typemap 1
13441 int spam(int argc, char *argv[], char *env[]);     // Uses typemap 3
13442 </PRE>
13443 </DIV>
13444 <P> It should be stressed that multi-argument typemaps can appear
13445  anywhere in a function declaration and can appear more than once. For
13446  example, you could write this:</P>
13447 <DIV class="code">
13448 <PRE>
13449 %typemap(in) (int scount, char *swords[]) { ... }
13450 %typemap(in) (int wcount, char *words[]) { ... }
13451
13452 void search_words(int scount, char *swords[], int wcount, char *words[], int maxcount);
13453 </PRE>
13454 </DIV>
13455 <P> Other directives such as <TT>%apply</TT> and <TT>%clear</TT> also
13456  work with multi-argument maps. For example:</P>
13457 <DIV class="code">
13458 <PRE>
13459 %apply (int argc, char *argv[]) {
13460     (int scount, char *swords[]),
13461     (int wcount, char *words[])
13462 };
13463 ...
13464 %clear (int scount, char *swords[]), (int wcount, char *words[]);
13465 ...
13466 </PRE>
13467 </DIV>
13468 <P> Although multi-argument typemaps may seem like an exotic, little
13469  used feature, there are several situations where they make sense.
13470  First, suppose you wanted to wrap functions similar to the low-level <TT>
13471 read()</TT> and <TT>write()</TT> system calls. For example:</P>
13472 <DIV class="code">
13473 <PRE>
13474 typedef unsigned int size_t;
13475
13476 int read(int fd, void *rbuffer, size_t len);
13477 int write(int fd, void *wbuffer, size_t len);
13478 </PRE>
13479 </DIV>
13480 <P> As is, the only way to use the functions would be to allocate memory
13481  and pass some kind of pointer as the second argument---a process that
13482  might require the use of a helper function. However, using
13483  multi-argument maps, the functions can be transformed into something
13484  more natural. For example, you might write typemaps like this:</P>
13485 <DIV class="code">
13486 <PRE>
13487 // typemap for an outgoing buffer
13488 %typemap(in) (void *wbuffer, size_t len) {
13489    if (!PyString_Check($input)) {
13490        PyErr_SetString(PyExc_ValueError, &quot;Expecting a string&quot;);
13491        return NULL;
13492    }
13493    $1 = (void *) PyString_AsString($input);
13494    $2 = PyString_Size($input);
13495 }
13496
13497 // typemap for an incoming buffer
13498 %typemap(in) (void *rbuffer, size_t len) {
13499    if (!PyInt_Check($input)) {
13500        PyErr_SetString(PyExc_ValueError, &quot;Expecting an integer&quot;);
13501        return NULL;
13502    }
13503    $2 = PyInt_AsLong($input);
13504    if ($2 &lt; 0) {
13505        PyErr_SetString(PyExc_ValueError, &quot;Positive integer expected&quot;);
13506        return NULL;
13507    }
13508    $1 = (void *) malloc($2);
13509 }
13510
13511 // Return the buffer.  Discarding any previous return result
13512 %typemap(argout) (void *rbuffer, size_t len) {
13513    Py_XDECREF($result);   /* Blow away any previous result */
13514    if (result &lt; 0) {      /* Check for I/O error */
13515        free($1);
13516        PyErr_SetFromErrno(PyExc_IOError);
13517        return NULL;
13518    }
13519    $result = PyString_FromStringAndSize($1,result);
13520    free($1);
13521 }
13522 </PRE>
13523 </DIV>
13524 <P> (note: In the above example, <TT>$result</TT> and <TT>result</TT>
13525  are two different variables. <TT>result</TT> is the real C datatype
13526  that was returned by the function. <TT>$result</TT> is the scripting
13527  language object being returned to the interpreter.).</P>
13528 <P> Now, in a script, you can write code that simply passes buffers as
13529  strings like this:</P>
13530 <DIV class="targetlang">
13531 <PRE>
13532 &gt;&gt;&gt; f = example.open(&quot;Makefile&quot;)
13533 &gt;&gt;&gt; example.read(f,40)
13534 'TOP        = ../..\nSWIG       = $(TOP)/.'
13535 &gt;&gt;&gt; example.read(f,40)
13536 './swig\nSRCS       = example.c\nTARGET    '
13537 &gt;&gt;&gt; example.close(f)
13538 0
13539 &gt;&gt;&gt; g = example.open(&quot;foo&quot;, example.O_WRONLY | example.O_CREAT, 0644)
13540 &gt;&gt;&gt; example.write(g,&quot;Hello world\n&quot;)
13541 12
13542 &gt;&gt;&gt; example.write(g,&quot;This is a test\n&quot;)
13543 15
13544 &gt;&gt;&gt; example.close(g)
13545 0
13546 &gt;&gt;&gt;
13547 </PRE>
13548 </DIV>
13549 <P> A number of multi-argument typemap problems also arise in libraries
13550  that perform matrix-calculations--especially if they are mapped onto
13551  low-level Fortran or C code. For example, you might have a function
13552  like this:</P>
13553 <DIV class="code">
13554 <PRE>
13555 int is_symmetric(double *mat, int rows, int columns);
13556 </PRE>
13557 </DIV>
13558 <P> In this case, you might want to pass some kind of higher-level
13559  object as an matrix. To do this, you could write a multi-argument
13560  typemap like this:</P>
13561 <DIV class="code">
13562 <PRE>
13563 %typemap(in) (double *mat, int rows, int columns) {
13564     MatrixObject *a;
13565     a = GetMatrixFromObject($input);     /* Get matrix somehow */
13566
13567     /* Get matrix properties */
13568     $1 = GetPointer(a);
13569     $2 = GetRows(a);
13570     $3 = GetColumns(a);
13571 }
13572 </PRE>
13573 </DIV>
13574 <P> This kind of technique can be used to hook into scripting-language
13575  matrix packages such as Numeric Python. However, it should also be
13576  stressed that some care is in order. For example, when crossing
13577  languages you may need to worry about issues such as row-major vs.
13578  column-major ordering (and perform conversions if needed).</P>
13579 <H2><A name="runtime_type_checker"></A>10.10 The run-time type checker</H2>
13580 <P> Most scripting languages need type information at run-time. This
13581  type information can include how to construct types, how to garbage
13582  collect types, and the inheritance relationships between types. If the
13583  language interface does not provide its own type information storage,
13584  the generated SWIG code needs to provide it.</P>
13585 <P> Requirements for the type system:</P>
13586 <UL>
13587 <LI>Store inheritance and type equivalence information and be able to
13588  correctly re-create the type pointer.</LI>
13589 <LI>Share type information between modules.</LI>
13590 <LI>Modules can be loaded in any order, irregardless of actual type
13591  dependency.</LI>
13592 <LI>Avoid the use of dynamically allocated memory, and library/system
13593  calls in general.</LI>
13594 <LI>Provide a reasonably fast implementation, minimizing the lookup time
13595  for all language modules.</LI>
13596 <LI>Custom, language specific information can be attached to types.</LI>
13597 <LI>Modules can be unloaded from the type system.</LI>
13598 </UL>
13599 <H3><A name="Typemaps_nn45"></A>10.10.1 Implementation</H3>
13600 <P> The run-time type checker is used by many, but not all, of SWIG's
13601  supported target languages. The run-time type checker features are not
13602  required and are thus not used for strongly typed languages such as
13603  Java and C#. The scripting and scheme based languages rely on it and it
13604  forms a critical part of SWIG's operation for these languages.</P>
13605 <P> When pointers, arrays, and objects are wrapped by SWIG, they are
13606  normally converted into typed pointer objects. For example, an instance
13607  of <TT>Foo *</TT> might be a string encoded like this:</P>
13608 <DIV class="diagram">
13609 <PRE>
13610 _108e688_p_Foo
13611 </PRE>
13612 </DIV>
13613 <P> At a basic level, the type checker simply restores some type-safety
13614  to extension modules. However, the type checker is also responsible for
13615  making sure that wrapped C++ classes are handled correctly---especially
13616  when inheritance is used. This is especially important when an
13617  extension module makes use of multiple inheritance. For example:</P>
13618 <DIV class="code">
13619 <PRE>
13620 class Foo {
13621    int x;
13622 };
13623
13624 class Bar {
13625    int y;
13626 };
13627
13628 class FooBar : public Foo, public Bar {
13629    int z;
13630 };
13631 </PRE>
13632 </DIV>
13633 <P> When the class <TT>FooBar</TT> is organized in memory, it contains
13634  the contents of the classes <TT>Foo</TT> and <TT>Bar</TT> as well as
13635  its own data members. For example:</P>
13636 <DIV class="diagram">
13637 <PRE>
13638 FooBar --&gt; | -----------|  &lt;-- Foo
13639            |   int x    |
13640            |------------|  &lt;-- Bar
13641            |   int y    |
13642            |------------|
13643            |   int z    |
13644            |------------|
13645 </PRE>
13646 </DIV>
13647 <P> Because of the way that base class data is stacked together, the
13648  casting of a <TT>Foobar *</TT> to either of the base classes may change
13649  the actual value of the pointer. This means that it is generally not
13650  safe to represent pointers using a simple integer or a bare <TT>void *</TT>
13651 ---type tags are needed to implement correct handling of pointer values
13652  (and to make adjustments when needed).</P>
13653 <P> In the wrapper code generated for each language, pointers are
13654  handled through the use of special type descriptors and conversion
13655  functions. For example, if you look at the wrapper code for Python, you
13656  will see code like this:</P>
13657 <DIV class="code">
13658 <PRE>
13659 if ((SWIG_ConvertPtr(obj0,(void **) &amp;arg1, SWIGTYPE_p_Foo,1)) == -1) return NULL;
13660 </PRE>
13661 </DIV>
13662 <P> In this code, <TT>SWIGTYPE_p_Foo</TT> is the type descriptor that
13663  describes <TT>Foo *</TT>. The type descriptor is actually a pointer to
13664  a structure that contains information about the type name to use in the
13665  target language, a list of equivalent typenames (via typedef or
13666  inheritance), and pointer value handling information (if applicable).
13667  The <TT>SWIG_ConvertPtr()</TT> function is simply a utility function
13668  that takes a pointer object in the target language and a
13669  type-descriptor objects and uses this information to generate a C++
13670  pointer. However, the exact name and calling conventions of the
13671  conversion function depends on the target language (see language
13672  specific chapters for details).</P>
13673 <P> The actual type code is in swigrun.swg, and gets inserted near the
13674  top of the generated swig wrapper file. The phrase &quot;a type X that can
13675  cast into a type Y&quot; means that given a type X, it can be converted into
13676  a type Y. In other words, X is a derived class of Y or X is a typedef
13677  of Y. The structure to store type information looks like this:</P>
13678 <DIV class="code">
13679 <PRE>
13680 /* Structure to store information on one type */
13681 typedef struct swig_type_info {
13682   const char *name;             /* mangled name of this type */
13683   const char *str;              /* human readable name for this type */
13684   swig_dycast_func dcast;       /* dynamic cast function down a hierarchy */
13685   struct swig_cast_info *cast;  /* Linked list of types that can cast into this type */
13686   void *clientdata;             /* Language specific type data */
13687 } swig_type_info;
13688
13689 /* Structure to store a type and conversion function used for casting */
13690 typedef struct swig_cast_info {
13691   swig_type_info *type;          /* pointer to type that is equivalent to this type */
13692   swig_converter_func converter; /* function to cast the void pointers */
13693   struct swig_cast_info *next;   /* pointer to next cast in linked list */
13694   struct swig_cast_info *prev;   /* pointer to the previous cast */
13695 } swig_cast_info;
13696 </PRE>
13697 </DIV>
13698 <P> Each <TT>swig_type_info</TT> stores a linked list of types that it
13699  is equivalent to. Each entry in this doubly linked list stores a
13700  pointer back to another swig_type_info structure, along with a pointer
13701  to a conversion function. This conversion function is used to solve the
13702  above problem of the FooBar class, correctly returning a pointer to the
13703  type we want.</P>
13704 <P> The basic problem we need to solve is verifying and building
13705  arguments passed to functions. So going back to the <TT>
13706 SWIG_ConvertPtr()</TT> function example from above, we are expecting a <TT>
13707 Foo *</TT> and need to check if <TT>obj0</TT> is in fact a <TT>Foo *</TT>
13708 . From before, <TT>SWIGTYPE_p_Foo</TT> is just a pointer to the <TT>
13709 swig_type_info</TT> structure describing <TT>Foo *</TT>. So we loop
13710  through the linked list of <TT>swig_cast_info</TT> structures attached
13711  to <TT>SWIGTYPE_p_Foo</TT>. If we see that the type of <TT>obj0</TT> is
13712  in the linked list, we pass the object through the associated
13713  conversion function and then return a positive. If we reach the end of
13714  the linked list without a match, then <TT>obj0</TT> can not be
13715  converted to a <TT>Foo *</TT> and an error is generated.</P>
13716 <P> Another issue needing to be addressed is sharing type information
13717  between multiple modules. More explicitly, we need to have ONE <TT>
13718 swig_type_info</TT> for each type. If two modules both use the type, the
13719  second module loaded must lookup and use the swig_type_info structure
13720  from the module already loaded. Because no dynamic memory is used and
13721  the circular dependencies of the casting information, loading the type
13722  information is somewhat tricky, and not explained here. A complete
13723  description is in the <TT>Lib/swiginit.swg</TT> file (and near the top
13724  of any generated file).</P>
13725 <P> Each module has one swig_module_info structure which looks like
13726  this:</P>
13727 <DIV class="code">
13728 <PRE>
13729 /* Structure used to store module information
13730  * Each module generates one structure like this, and the runtime collects
13731  * all of these structures and stores them in a circularly linked list.*/
13732 typedef struct swig_module_info {
13733   swig_type_info **types;         /* Array of pointers to swig_type_info structs in this module */
13734   int size;                       /* Number of types in this module */
13735   struct swig_module_info *next;  /* Pointer to next element in circularly linked list */
13736   swig_type_info **type_initial;  /* Array of initially generated type structures */
13737   swig_cast_info **cast_initial;  /* Array of initially generated casting structures */
13738   void *clientdata;               /* Language specific module data */
13739 } swig_module_info;
13740 </PRE>
13741 </DIV>
13742 <P> Each module stores an array of pointers to <TT>swig_type_info</TT>
13743  structures and the number of types in this module. So when a second
13744  module is loaded, it finds the <TT>swig_module_info</TT> structure for
13745  the first module and searches the array of types. If any of its own
13746  types are in the first module and have already been loaded, it uses
13747  those <TT>swig_type_info</TT> structures rather than creating new ones.
13748  These <TT>swig_module_info</TT> structures are chained together in a
13749  circularly linked list.</P>
13750 <H3><A name="Typemaps_runtime_type_checker_usage"></A>10.10.2 Usage</H3>
13751 <P>This section covers how to use these functions from typemaps. To
13752  learn how to call these functions from external files (not the
13753  generated _wrap.c file), see the <A href="#external_run_time">External
13754  access to the run-time system</A> section.</P>
13755 <P>When pointers are converted in a typemap, the typemap code often
13756  looks similar to this:</P>
13757 <DIV class="code">
13758 <PRE>
13759 %typemap(in) Foo * {
13760   if ((SWIG_ConvertPtr($input, (void **) &amp;$1, $1_descriptor)) == -1) return NULL;
13761 }
13762 </PRE>
13763 </DIV>
13764 <P> The most critical part is the typemap is the use of the <TT>
13765 $1_descriptor</TT> special variable. When placed in a typemap, this is
13766  expanded into the <TT>SWIGTYPE_*</TT> type descriptor object above. As
13767  a general rule, you should always use <TT>$1_descriptor</TT> instead of
13768  trying to hard-code the type descriptor name directly.</P>
13769 <P> There is another reason why you should always use the <TT>
13770 $1_descriptor</TT> variable. When this special variable is expanded,
13771  SWIG marks the corresponding type as &quot;in use.&quot; When type-tables and
13772  type information is emitted in the wrapper file, descriptor information
13773  is only generated for those datatypes that were actually used in the
13774  interface. This greatly reduces the size of the type tables and
13775  improves efficiency.</P>
13776 <P> Occasionally, you might need to write a typemap that needs to
13777  convert pointers of other types. To handle this, the special variable
13778  macro <TT>$descriptor(type)</TT> covered earlier can be used to
13779  generate the SWIG type descriptor name for any C datatype. For example:</P>
13780 <DIV class="code">
13781 <PRE>
13782 %typemap(in) Foo * {
13783   if ((SWIG_ConvertPtr($input, (void **) &amp;$1, $1_descriptor)) == -1) {
13784      Bar *temp;
13785      if ((SWIG_ConvertPtr($input, (void **) &amp;temp, <B>$descriptor(Bar *)</B>) == -1) {
13786          return NULL;
13787      }
13788      $1 = (Foo *) temp;
13789   }
13790 }
13791 </PRE>
13792 </DIV>
13793 <P> The primary use of <TT>$descriptor(type)</TT> is when writing
13794  typemaps for container objects and other complex data structures. There
13795  are some restrictions on the argument---namely it must be a fully
13796  defined C datatype. It can not be any of the special typemap variables.</P>
13797 <P> In certain cases, SWIG may not generate type-descriptors like you
13798  expect. For example, if you are converting pointers in some
13799  non-standard way or working with an unusual combination of interface
13800  files and modules, you may find that SWIG omits information for a
13801  specific type descriptor. To fix this, you may need to use the <TT>
13802 %types</TT> directive. For example:</P>
13803 <DIV class="code">
13804 <PRE>
13805 %types(int *, short *, long *, float *, double *);
13806 </PRE>
13807 </DIV>
13808 <P> When <TT>%types</TT> is used, SWIG generates type-descriptor
13809  information even if those datatypes never appear elsewhere in the
13810  interface file.</P>
13811 <P> Further details about the run-time type checking can be found in the
13812  documentation for individual language modules. Reading the source code
13813  may also help. The file <TT>Lib/swigrun.swg</TT> in the SWIG library
13814  contains all of the source code for type-checking. This code is also
13815  included in every generated wrapped file so you probably just look at
13816  the output of SWIG to get a better sense for how types are managed.</P>
13817 <H2><A name="Typemaps_overloading"></A>10.11 Typemaps and overloading</H2>
13818 <P> In many target languages, SWIG fully supports C++ overloaded methods
13819  and functions. For example, if you have a collection of functions like
13820  this:</P>
13821 <DIV class="code">
13822 <PRE>
13823 int foo(int x);
13824 int foo(double x);
13825 int foo(char *s, int y);
13826 </PRE>
13827 </DIV>
13828 <P> You can access the functions in a normal way from the scripting
13829  interpreter:</P>
13830 <DIV class="targetlang">
13831 <PRE>
13832 # Python
13833 foo(3)           # foo(int)
13834 foo(3.5)         # foo(double)
13835 foo(&quot;hello&quot;,5)   # foo(char *, int)
13836
13837 # Tcl
13838 foo 3            # foo(int)
13839 foo 3.5          # foo(double)
13840 foo hello 5      # foo(char *, int)
13841 </PRE>
13842 </DIV>
13843 <P> To implement overloading, SWIG generates a separate wrapper function
13844  for each overloaded method. For example, the above functions would
13845  produce something roughly like this:</P>
13846 <DIV class="code">
13847 <PRE>
13848 // wrapper pseudocode
13849 _wrap_foo_0(argc, args[]) {       // foo(int)
13850    int arg1;
13851    int result;
13852    ...
13853    arg1 = FromInteger(args[0]);
13854    result = foo(arg1);
13855    return ToInteger(result);
13856 }
13857
13858 _wrap_foo_1(argc, args[]) {       // foo(double)
13859    double arg1;
13860    int result;
13861    ...
13862    arg1 = FromDouble(args[0]);
13863    result = foo(arg1);
13864    return ToInteger(result);
13865 }
13866
13867 _wrap_foo_2(argc, args[]) {       // foo(char *, int)
13868    char *arg1;
13869    int   arg2;
13870    int result;
13871    ...
13872    arg1 = FromString(args[0]);
13873    arg2 = FromInteger(args[1]);
13874    result = foo(arg1,arg2);
13875    return ToInteger(result);
13876 }
13877
13878 </PRE>
13879 </DIV>
13880 <P> Next, a dynamic dispatch function is generated:</P>
13881 <DIV class="code">
13882 <PRE>
13883 _wrap_foo(argc, args[]) {
13884    if (argc == 1) {
13885        if (IsInteger(args[0])) {
13886            return _wrap_foo_0(argc,args);
13887        } 
13888        if (IsDouble(args[0])) {
13889            return _wrap_foo_1(argc,args);
13890        }
13891    }
13892    if (argc == 2) {
13893        if (IsString(args[0]) &amp;&amp; IsInteger(args[1])) {
13894           return _wrap_foo_2(argc,args);
13895        }
13896    }
13897    error(&quot;No matching function!\n&quot;);
13898 }
13899 </PRE>
13900 </DIV>
13901 <P> The purpose of the dynamic dispatch function is to select the
13902  appropriate C++ function based on argument types---a task that must be
13903  performed at runtime in most of SWIG's target languages.</P>
13904 <P> The generation of the dynamic dispatch function is a relatively
13905  tricky affair. Not only must input typemaps be taken into account
13906  (these typemaps can radically change the types of arguments accepted),
13907  but overloaded methods must also be sorted and checked in a very
13908  specific order to resolve potential ambiguity. A high-level overview of
13909  this ranking process is found in the &quot;<A href="#SWIGPlus">SWIG and C++</A>
13910 &quot; chapter. What isn't mentioned in that chapter is the mechanism by
13911  which it is implemented---as a collection of typemaps.</P>
13912 <P> To support dynamic dispatch, SWIG first defines a general purpose
13913  type hierarchy as follows:</P>
13914 <DIV class="diagram">
13915 <PRE>
13916 Symbolic Name                   Precedence Value
13917 ------------------------------  ------------------
13918 SWIG_TYPECHECK_POINTER           0  
13919 SWIG_TYPECHECK_VOIDPTR           10 
13920 SWIG_TYPECHECK_BOOL              15 
13921 SWIG_TYPECHECK_UINT8             20 
13922 SWIG_TYPECHECK_INT8              25 
13923 SWIG_TYPECHECK_UINT16            30 
13924 SWIG_TYPECHECK_INT16             35 
13925 SWIG_TYPECHECK_UINT32            40 
13926 SWIG_TYPECHECK_INT32             45 
13927 SWIG_TYPECHECK_UINT64            50 
13928 SWIG_TYPECHECK_INT64             55 
13929 SWIG_TYPECHECK_UINT128           60 
13930 SWIG_TYPECHECK_INT128            65 
13931 SWIG_TYPECHECK_INTEGER           70 
13932 SWIG_TYPECHECK_FLOAT             80 
13933 SWIG_TYPECHECK_DOUBLE            90 
13934 SWIG_TYPECHECK_COMPLEX           100 
13935 SWIG_TYPECHECK_UNICHAR           110 
13936 SWIG_TYPECHECK_UNISTRING         120 
13937 SWIG_TYPECHECK_CHAR              130 
13938 SWIG_TYPECHECK_STRING            140 
13939 SWIG_TYPECHECK_BOOL_ARRAY        1015 
13940 SWIG_TYPECHECK_INT8_ARRAY        1025 
13941 SWIG_TYPECHECK_INT16_ARRAY       1035 
13942 SWIG_TYPECHECK_INT32_ARRAY       1045 
13943 SWIG_TYPECHECK_INT64_ARRAY       1055 
13944 SWIG_TYPECHECK_INT128_ARRAY      1065 
13945 SWIG_TYPECHECK_FLOAT_ARRAY       1080 
13946 SWIG_TYPECHECK_DOUBLE_ARRAY      1090 
13947 SWIG_TYPECHECK_CHAR_ARRAY        1130 
13948 SWIG_TYPECHECK_STRING_ARRAY      1140 
13949 </PRE>
13950 </DIV>
13951 <P> (These precedence levels are defined in <TT>swig.swg</TT>, a library
13952  file that's included by all target language modules.)</P>
13953 <P> In this table, the precedence-level determines the order in which
13954  types are going to be checked. Low values are always checked before
13955  higher values. For example, integers are checked before floats, single
13956  values are checked before arrays, and so forth.</P>
13957 <P> Using the above table as a guide, each target language defines a
13958  collection of &quot;typecheck&quot; typemaps. The follow excerpt from the Python
13959  module illustrates this:</P>
13960 <DIV class="code">
13961 <PRE>
13962 /* Python type checking rules */
13963 /* Note:  %typecheck(X) is a macro for %typemap(typecheck,precedence=X) */
13964
13965 %typecheck(SWIG_TYPECHECK_INTEGER)
13966          int, short, long,
13967          unsigned int, unsigned short, unsigned long,
13968          signed char, unsigned char,
13969          long long, unsigned long long,
13970          const int &amp;, const short &amp;, const long &amp;,
13971          const unsigned int &amp;, const unsigned short &amp;, const unsigned long &amp;,
13972          const long long &amp;, const unsigned long long &amp;,
13973          enum SWIGTYPE,
13974          bool, const bool &amp; 
13975 {
13976   $1 = (PyInt_Check($input) || PyLong_Check($input)) ? 1 : 0;
13977 }
13978
13979 %typecheck(SWIG_TYPECHECK_DOUBLE)
13980         float, double,
13981         const float &amp;, const double &amp;
13982 {
13983   $1 = (PyFloat_Check($input) || PyInt_Check($input) || PyLong_Check($input)) ? 1 : 0;
13984 }
13985
13986 %typecheck(SWIG_TYPECHECK_CHAR) char {
13987   $1 = (PyString_Check($input) &amp;&amp; (PyString_Size($input) == 1)) ? 1 : 0;
13988 }
13989
13990 %typecheck(SWIG_TYPECHECK_STRING) char * {
13991   $1 = PyString_Check($input) ? 1 : 0;
13992 }
13993
13994 %typecheck(SWIG_TYPECHECK_POINTER) SWIGTYPE *, SWIGTYPE &amp;, SWIGTYPE [] {
13995   void *ptr;
13996   if (SWIG_ConvertPtr($input, (void **) &amp;ptr, $1_descriptor, 0) == -1) {
13997     $1 = 0;
13998     PyErr_Clear();
13999   } else {
14000     $1 = 1;
14001   }
14002 }
14003
14004 %typecheck(SWIG_TYPECHECK_POINTER) SWIGTYPE {
14005   void *ptr;
14006   if (SWIG_ConvertPtr($input, (void **) &amp;ptr, $&amp;1_descriptor, 0) == -1) {
14007     $1 = 0;
14008     PyErr_Clear();
14009   } else {
14010     $1 = 1;
14011   }
14012 }
14013
14014 %typecheck(SWIG_TYPECHECK_VOIDPTR) void * {
14015   void *ptr;
14016   if (SWIG_ConvertPtr($input, (void **) &amp;ptr, 0, 0) == -1) {
14017     $1 = 0;
14018     PyErr_Clear();
14019   } else {
14020     $1 = 1;
14021   }
14022 }
14023
14024 %typecheck(SWIG_TYPECHECK_POINTER) PyObject *
14025 {
14026   $1 = ($input != 0);
14027 }
14028 </PRE>
14029 </DIV>
14030 <P> It might take a bit of contemplation, but this code has merely
14031  organized all of the basic C++ types, provided some simple
14032  type-checking code, and assigned each type a precedence value.</P>
14033 <P> Finally, to generate the dynamic dispatch function, SWIG uses the
14034  following algorithm:</P>
14035 <UL>
14036 <LI>Overloaded methods are first sorted by the number of required
14037  arguments.</LI>
14038 <LI>Methods with the same number of arguments are then sorted by
14039  precedence values of argument types.</LI>
14040 <LI>Typecheck typemaps are then emitted to produce a dispatch function
14041  that checks arguments in the correct order.</LI>
14042 </UL>
14043 <P> If you haven't written any typemaps of your own, it is unnecessary
14044  to worry about the typechecking rules. However, if you have written new
14045  input typemaps, you might have to supply a typechecking rule as well.
14046  An easy way to do this is to simply copy one of the existing
14047  typechecking rules. Here is an example,</P>
14048 <DIV class="code">
14049 <PRE>
14050 // Typemap for a C++ string
14051 %typemap(in) std::string {
14052     if (PyString_Check($input)) {
14053          $1 = std::string(PyString_AsString($input));
14054      } else {
14055          SWIG_exception(SWIG_TypeError, &quot;string expected&quot;);
14056      }
14057 }
14058 // Copy the typecheck code for &quot;char *&quot;.  
14059 %typemap(typecheck) std::string = char *;
14060 </PRE>
14061 </DIV>
14062 <P> The bottom line: If you are writing new typemaps and you are using
14063  overloaded methods, you will probably have to write typecheck code or
14064  copy existing code. Since this is a relatively new SWIG feature, there
14065  are few examples to work with. However, you might look at some of the
14066  existing library files likes 'typemaps.i' for a guide.</P>
14067 <P><B> Notes:</B></P>
14068 <UL>
14069 <LI>Typecheck typemaps are not used for non-overloaded methods. Because
14070  of this, it is still always necessary to check types in any &quot;in&quot;
14071  typemaps.</LI>
14072 <LI>The dynamic dispatch process is only meant to be a heuristic. There
14073  are many corner cases where SWIG simply can't disambiguate types to the
14074  same degree as C++. The only way to resolve this ambiguity is to use
14075  the %rename directive to rename one of the overloaded methods
14076  (effectively eliminating overloading).</LI>
14077 <LI> Typechecking may be partial. For example, if working with arrays,
14078  the typecheck code might simply check the type of the first array
14079  element and use that to dispatch to the correct function. Subsequent
14080  &quot;in&quot; typemaps would then perform more extensive type-checking.</LI>
14081 <LI>Make sure you read the section on overloading in the &quot;<A href="#SWIGPlus">
14082 SWIG and C++</A>&quot; chapter.</LI>
14083 </UL>
14084 <H2><A name="Typemaps_nn48"></A>10.12 More about <TT>%apply</TT> and <TT>
14085 %clear</TT></H2>
14086 <P> In order to implement certain kinds of program behavior, it is
14087  sometimes necessary to write sets of typemaps. For example, to support
14088  output arguments, one often writes a set of typemaps like this:</P>
14089 <DIV class="code">
14090 <PRE>
14091 %typemap(in,numinputs=0) int *OUTPUT (int temp) {
14092    $1 = &amp;temp;
14093 }
14094 %typemap(argout) int *OUTPUT {
14095    // return value somehow
14096 }
14097 </PRE>
14098 </DIV>
14099 <P> To make it easier to apply the typemap to different argument types
14100  and names, the <TT>%apply</TT> directive performs a copy of all
14101  typemaps from one type to another. For example, if you specify this,</P>
14102 <DIV class="code">
14103 <PRE>
14104 %apply int *OUTPUT { int *retvalue, int32 *output };
14105 </PRE>
14106 </DIV>
14107 <P> then all of the <TT>int *OUTPUT</TT> typemaps are copied to <TT>int
14108  *retvalue</TT> and <TT>int32 *output</TT>.</P>
14109 <P> However, there is a subtle aspect of <TT>%apply</TT> that needs more
14110  description. Namely, <TT>%apply</TT> does not overwrite a typemap rule
14111  if it is already defined for the target datatype. This behavior allows
14112  you to do two things:</P>
14113 <UL>
14114 <LI>You can specialize parts of a complex typemap rule by first defining
14115  a few typemaps and then using <TT>%apply</TT> to incorporate the
14116  remaining pieces.</LI>
14117 <LI>Sets of different typemaps can be applied to the same datatype using
14118  repeated <TT>%apply</TT> directives.</LI>
14119 </UL>
14120 <P> For example:</P>
14121 <DIV class="code">
14122 <PRE>
14123 %typemap(in) int *INPUT (int temp) {
14124    temp = ... get value from $input ...;
14125    $1 = &amp;temp;
14126 }
14127
14128 %typemap(check) int *POSITIVE {
14129    if (*$1 &lt;= 0) {
14130       SWIG_exception(SWIG_ValueError,&quot;Expected a positive number!\n&quot;);
14131       return NULL;
14132    }
14133 }
14134
14135 ...
14136 %apply int *INPUT     { int *invalue };
14137 %apply int *POSITIVE  { int *invalue };
14138 </PRE>
14139 </DIV>
14140 <P> Since <TT>%apply</TT> does not overwrite or replace any existing
14141  rules, the only way to reset behavior is to use the <TT>%clear</TT>
14142  directive. <TT>%clear</TT> removes all typemap rules defined for a
14143  specific datatype. For example:</P>
14144 <DIV class="code">
14145 <PRE>
14146 %clear int *invalue;
14147 </PRE>
14148 </DIV>
14149 <H2><A name="Typemaps_nn49"></A>10.13 Reducing wrapper code size</H2>
14150 <P> Since the code supplied to a typemap is inlined directly into
14151  wrapper functions, typemaps can result in a tremendous amount of code
14152  bloat. For example, consider this typemap for an array:</P>
14153 <DIV class="code">
14154 <PRE>
14155 %typemap(in) float [ANY] {
14156   int i;
14157   if (!PySequence_Check($input)) {
14158     PyErr_SetString(PyExc_ValueError,&quot;Expected a sequence&quot;);
14159     return NULL;
14160   }
14161   if (PySequence_Length($input) != $1_dim0) {
14162     PyErr_SetString(PyExc_ValueError,&quot;Size mismatch. Expected $1_dim0 elements&quot;);
14163     return NULL;
14164   }
14165   $1 = (float) malloc($1_dim0*sizeof(float));
14166   for (i = 0; i &lt; $1_dim0; i++) {
14167     PyObject *o = PySequence_GetItem($input,i);
14168     if (PyNumber_Check(o)) {
14169       $1[i] = (float) PyFloat_AsDouble(o);
14170     } else {
14171       PyErr_SetString(PyExc_ValueError,&quot;Sequence elements must be numbers&quot;);      
14172       free(result);
14173       return NULL;
14174     }
14175   }
14176 }
14177 </PRE>
14178 </DIV>
14179 <P> If you had a large interface with hundreds of functions all
14180  accepting array parameters, this typemap would be replicated
14181  repeatedly--generating a huge amount of code. A better approach might
14182  be to consolidate some of the typemap into a function. For example:</P>
14183 <DIV class="code">
14184 <PRE>
14185 %{
14186 /* Define a helper function */
14187 static float *
14188 convert_float_array(PyObject *input, int size) {
14189   int i;
14190   float *result;
14191   if (!PySequence_Check(input)) {
14192     PyErr_SetString(PyExc_ValueError,&quot;Expected a sequence&quot;);
14193     return NULL;
14194   }
14195   if (PySequence_Length(input) != size) {
14196     PyErr_SetString(PyExc_ValueError,&quot;Size mismatch. &quot;);
14197     return NULL;
14198   }
14199   result = (float) malloc(size*sizeof(float));
14200   for (i = 0; i &lt; size; i++) {
14201     PyObject *o = PySequence_GetItem(input,i);
14202     if (PyNumber_Check(o)) {
14203       result[i] = (float) PyFloat_AsDouble(o);
14204     } else {
14205       PyErr_SetString(PyExc_ValueError,&quot;Sequence elements must be numbers&quot;);
14206       free(result);       
14207       return NULL;
14208     }
14209   }
14210   return result;
14211 }
14212 %}
14213
14214 %typemap(in) float [ANY] {
14215     $1 = convert_float_array($input, $1_dim0);
14216     if (!$1) return NULL;
14217 }
14218 %}
14219 </PRE>
14220 </DIV>
14221 <H2><A name="Typemaps_nn47"></A>10.14 Passing data between typemaps</H2>
14222 <P> It is also important to note that the primary use of local variables
14223  is to create stack-allocated objects for temporary use inside a wrapper
14224  function (this is faster and less-prone to error than allocating data
14225  on the heap). In general, the variables are not intended to pass
14226  information between different types of typemaps. However, this can be
14227  done if you realize that local names have the argument number appended
14228  to them. For example, you could do this:</P>
14229 <DIV class="code">
14230 <PRE>
14231 %typemap(in) int *(int temp) {
14232    temp = (int) PyInt_AsLong($input);
14233    $1 = &amp;temp;
14234 }
14235
14236 %typemap(argout) int * {
14237    PyObject *o = PyInt_FromLong(temp$argnum);
14238    ...
14239 }
14240 </PRE>
14241 </DIV>
14242 <P> In this case, the <TT>$argnum</TT> variable is expanded into the
14243  argument number. Therefore, the code will reference the appropriate
14244  local such as <TT>temp1</TT> and <TT>temp2</TT>. It should be noted
14245  that there are plenty of opportunities to break the universe here and
14246  that accessing locals in this manner should probably be avoided. At the
14247  very least, you should make sure that the typemaps sharing information
14248  have exactly the same types and names.</P>
14249 <H2><A name="Typemaps_nn52"></A>10.15 C++ &quot;this&quot; pointer</H2>
14250 <P> All the rules discussed for Typemaps apply to C++ as well as C.
14251  However in addition C++ passes an extra parameter into every non-static
14252  class method -- the <TT>this</TT> pointer. Occasionally it can be
14253  useful to apply a typemap to this pointer (for example to check and
14254  make sure <TT>this</TT> is non-null before deferencing). Actually, C
14255  also has an the equivalent of the <TT>this</TT> pointer which is used
14256  when accessing variables in a C struct.</P>
14257 <P> In order to customise the <TT>this</TT> pointer handling, target a
14258  variable named <TT>self</TT> in your typemaps. <TT>self</TT> is the
14259  name SWIG uses to refer to the extra parameter in wrapped functions.</P>
14260 <P> For example, if wrapping for Java generation:</P>
14261 <DIV class="code">
14262 <PRE>
14263 %typemap(check) SWIGTYPE *self %{
14264 if (!$1) {
14265   SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, &quot;swigCPtr null&quot;);
14266   return $null;
14267 }
14268 %}
14269 </PRE>
14270 </DIV>
14271 <P> In the above case, the <TT>$1</TT> variable is expanded into the
14272  argument name that SWIG is using as the <TT>this</TT> pointer. SWIG
14273  will then insert the check code before the actual C++ class method is
14274  called, and will raise an exception rather than crash the Java virtual
14275  machine. The generated code will look something like:</P>
14276 <DIV class="code">
14277 <PRE>
14278   if (!arg1) {
14279     SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException,
14280       &quot;invalid native object; delete() likely already called&quot;);
14281     return ;
14282   }
14283   (arg1)-&gt;wrappedFunction(...);
14284 </PRE>
14285 </DIV>
14286 <P> Note that if you have a parameter named <TT>self</TT> then it will
14287  also match the typemap. One work around is to create an interface file
14288  that wraps the method, but give the argument a name other than <TT>self</TT>
14289 .</P>
14290 <H2><A name="Typemaps_nn51"></A>10.16 Where to go for more information?</H2>
14291 <P> The best place to find out more information about writing typemaps
14292  is to look in the SWIG library. Most language modules define all of
14293  their default behavior using typemaps. These are found in files such as
14294  <TT>python.swg</TT>, <TT>perl5.swg</TT>, <TT>tcl8.swg</TT> and so
14295  forth. The <TT>typemaps.i</TT> file in the library also contains
14296  numerous examples. You should look at these files to get a feel for how
14297  to define typemaps of your own. Some of the language modules support
14298  additional typemaps and further information is available in the
14299  individual chapters for each target language. There you may also find
14300  more hands-on practical examples.</P>
14301 <HR NOSHADE>
14302 <H1><A name="Customization"></A>11 Customization Features</H1>
14303
14304 <!-- INDEX -->
14305 <DIV class="sectiontoc">
14306 <UL>
14307 <LI><A href="#exception">Exception handling with %exception</A>
14308 <UL>
14309 <LI><A href="#Customization_nn3">Handling exceptions in C code</A></LI>
14310 <LI><A href="#Customization_nn4">Exception handling with longjmp()</A></LI>
14311 <LI><A href="#Customization_nn5">Handling C++ exceptions</A></LI>
14312 <LI><A href="#Customization_allowexcept">Exception handlers for
14313  variables</A></LI>
14314 <LI><A href="#Customization_nn6">Defining different exception handlers</A>
14315 </LI>
14316 <LI><A href="#Customization_exception_special_variables">Special
14317  variables for %exception</A></LI>
14318 <LI><A href="#Customization_nn7">Using The SWIG exception library</A></LI>
14319 </UL>
14320 </LI>
14321 <LI><A href="#ownership">Object ownership and %newobject</A></LI>
14322 <LI><A href="#features">Features and the %feature directive</A>
14323 <UL>
14324 <LI><A href="#Customization_feature_attributes">Feature attributes</A></LI>
14325 <LI><A href="#Customization_feature_flags">Feature flags</A></LI>
14326 <LI><A href="#Customization_clearing_features">Clearing features</A></LI>
14327 <LI><A href="#Customization_features_default_args">Features and default
14328  arguments</A></LI>
14329 <LI><A href="#features_example">Feature example</A></LI>
14330 </UL>
14331 </LI>
14332 </UL>
14333 </DIV>
14334 <!-- INDEX -->
14335 <P> In many cases, it is desirable to change the default wrapping of
14336  particular declarations in an interface. For example, you might want to
14337  provide hooks for catching C++ exceptions, add assertions, or provide
14338  hints to the underlying code generator. This chapter describes some of
14339  these customization techniques. First, a discussion of exception
14340  handling is presented. Then, a more general-purpose customization
14341  mechanism known as &quot;features&quot; is described.</P>
14342 <H2><A name="exception"></A>11.1 Exception handling with %exception</H2>
14343 <P> The <TT>%exception</TT> directive allows you to define a general
14344  purpose exception handler. For example, you can specify the following:</P>
14345 <DIV class="code">
14346 <PRE>
14347 %exception {
14348     try {
14349         $action
14350     }
14351     catch (RangeError) {
14352         PyErr_SetString(PyExc_IndexError,&quot;index out-of-bounds&quot;);
14353         return NULL;
14354     }
14355 }
14356 </PRE>
14357 </DIV>
14358 <P> When defined, the code enclosed in braces is inserted directly into
14359  the low-level wrapper functions. The special variable <TT>$action</TT>
14360  is one of a few <A href="#Customization_exception_special_variables">
14361 %exception special variable</A> supported and gets replaced with the
14362  actual operation to be performed (a function call, method invocation,
14363  attribute access, etc.). An exception handler remains in effect until
14364  it is explicitly deleted. This is done by using either <TT>%exception</TT>
14365  or <TT>%noexception</TT> with no code. For example:</P>
14366 <DIV class="code">
14367 <PRE>
14368 %exception;   // Deletes any previously defined handler
14369 </PRE>
14370 </DIV>
14371 <P><B> Compatibility note:</B> Previous versions of SWIG used a special
14372  directive <TT>%except</TT> for exception handling. That directive is
14373  deprecated--<TT>%exception</TT> provides the same functionality, but is
14374  substantially more flexible.</P>
14375 <H3><A name="Customization_nn3"></A>11.1.1 Handling exceptions in C code</H3>
14376 <P> C has no formal exception handling mechanism so there are several
14377  approaches that might be used. A somewhat common technique is to simply
14378  set a special error code. For example:</P>
14379 <DIV class="code">
14380 <PRE>
14381 /* File : except.c */
14382
14383 static char error_message[256];
14384 static int error_status = 0;
14385
14386 void throw_exception(char *msg) {
14387         strncpy(error_message,msg,256);
14388         error_status = 1;
14389 }
14390
14391 void clear_exception() {
14392         error_status = 0;
14393 }
14394 char *check_exception() {
14395         if (error_status) return error_message;
14396         else return NULL;
14397 }
14398
14399 </PRE>
14400 </DIV>
14401 <P> To use these functions, functions simply call <TT>throw_exception()</TT>
14402  to indicate an error occurred. For example :</P>
14403 <DIV class="code">
14404 <PRE>
14405 double inv(double x) {
14406         if (x != 0) return 1.0/x;
14407         else {
14408                 throw_exception(&quot;Division by zero&quot;);
14409                 return 0;
14410         }
14411 }
14412
14413 </PRE>
14414 </DIV>
14415 <P> To catch the exception, you can write a simple exception handler
14416  such as the following (shown for Perl5) :</P>
14417 <DIV class="code">
14418 <PRE>
14419 %exception {
14420     char *err;
14421     clear_exception();
14422     $action
14423     if ((err = check_exception())) {
14424        croak(err);
14425     }
14426 }
14427 </PRE>
14428 </DIV>
14429 <P> In this case, when an error occurs, it is translated into a Perl
14430  error. Each target language has its own approach to creating a runtime
14431  error/exception in and for Perl it is the <TT>croak</TT> method shown
14432  above.</P>
14433 <H3><A name="Customization_nn4"></A>11.1.2 Exception handling with
14434  longjmp()</H3>
14435 <P> Exception handling can also be added to C code using the <TT>
14436 &lt;setjmp.h&gt;</TT> library. Here is a minimalistic implementation that
14437  relies on the C preprocessor :</P>
14438 <DIV class="code">
14439 <PRE>
14440 /* File : except.c
14441    Just the declaration of a few global variables we're going to use */
14442
14443 #include &lt;setjmp.h&gt;
14444 jmp_buf exception_buffer;
14445 int exception_status;
14446
14447 /* File : except.h */
14448 #include &lt;setjmp.h&gt;
14449 extern jmp_buf exception_buffer;
14450 extern int exception_status;
14451
14452 #define try if ((exception_status = setjmp(exception_buffer)) == 0)
14453 #define catch(val) else if (exception_status == val)
14454 #define throw(val) longjmp(exception_buffer,val)
14455 #define finally else
14456
14457 /* Exception codes */
14458
14459 #define RangeError     1
14460 #define DivisionByZero 2
14461 #define OutOfMemory    3
14462
14463 </PRE>
14464 </DIV>
14465 <P> Now, within a C program, you can do the following :</P>
14466 <DIV class="code">
14467 <PRE>
14468 double inv(double x) {
14469         if (x) return 1.0/x;
14470         else throw(DivisionByZero);
14471 }
14472
14473 </PRE>
14474 </DIV>
14475 <P> Finally, to create a SWIG exception handler, write the following :</P>
14476 <DIV class="code">
14477 <PRE>
14478 %{
14479 #include &quot;except.h&quot;
14480 %}
14481
14482 %exception {
14483         try {
14484                 $action
14485         } catch(RangeError) {
14486                 croak(&quot;Range Error&quot;);
14487         } catch(DivisionByZero) {
14488                 croak(&quot;Division by zero&quot;);
14489         } catch(OutOfMemory) {
14490                 croak(&quot;Out of memory&quot;);
14491         } finally {
14492                 croak(&quot;Unknown exception&quot;);
14493         }
14494 }
14495 </PRE>
14496 </DIV>
14497 <P> Note: This implementation is only intended to illustrate the general
14498  idea. To make it work better, you'll need to modify it to handle nested
14499  <TT>try</TT> declarations.</P>
14500 <H3><A name="Customization_nn5"></A>11.1.3 Handling C++ exceptions</H3>
14501 <P> Handling C++ exceptions is also straightforward. For example:</P>
14502 <DIV class="code">
14503 <PRE>
14504 %exception {
14505         try {
14506                 $action
14507         } catch(RangeError) {
14508                 croak(&quot;Range Error&quot;);
14509         } catch(DivisionByZero) {
14510                 croak(&quot;Division by zero&quot;);
14511         } catch(OutOfMemory) {
14512                 croak(&quot;Out of memory&quot;);
14513         } catch(...) {
14514                 croak(&quot;Unknown exception&quot;);
14515         }
14516 }
14517
14518 </PRE>
14519 </DIV>
14520 <P> The exception types need to be declared as classes elsewhere,
14521  possibly in a header file :</P>
14522 <DIV class="code">
14523 <PRE>
14524 class RangeError {};
14525 class DivisionByZero {};
14526 class OutOfMemory {};
14527 </PRE>
14528 </DIV>
14529 <H3><A name="Customization_allowexcept"></A>11.1.4 Exception handlers
14530  for variables</H3>
14531 <P> By default all variables will ignore <TT>%exception</TT>, so it is
14532  effectively turned off for all variables wrappers. This applies to
14533  global variables, member variables and static member variables. The
14534  approach is certainly a logical one when wrapping variables in C.
14535  However, in C++, it is quite possible for an exception to be thrown
14536  while the variable is being assigned. To ensure <TT>%exception</TT> is
14537  used when wrapping variables, it needs to be 'turned on' using the <TT>
14538 %allowexception</TT> feature. Note that <TT>%allowexception</TT> is just
14539  a macro for <TT>%feature(&quot;allowexcept&quot;)</TT>, that is, it is a feature
14540  called &quot;allowexcept&quot;. Any variable which has this feature attached to
14541  it, will then use the <TT>%exception</TT> feature, but of course, only
14542  if there is a <TT>%exception</TT> attached to the variable in the first
14543  place. The <TT>%allowexception</TT> feature works like any other
14544  feature and so can be used globally or for selective variables.</P>
14545 <DIV class="code">
14546 <PRE>
14547 %allowexception;                // turn on globally
14548 %allowexception Klass::MyVar;   // turn on for a specific variable
14549
14550 %noallowexception Klass::MyVar; // turn off for a specific variable
14551 %noallowexception;              // turn off globally
14552 </PRE>
14553 </DIV>
14554 <H3><A name="Customization_nn6"></A>11.1.5 Defining different exception
14555  handlers</H3>
14556 <P> By default, the <TT>%exception</TT> directive creates an exception
14557  handler that is used for all wrapper functions that follow it. Unless
14558  there is a well-defined (and simple) error handling mechanism in place,
14559  defining one universal exception handler may be unwieldy and result in
14560  excessive code bloat since the handler is inlined into each wrapper
14561  function.</P>
14562 <P> To fix this, you can be more selective about how you use the <TT>
14563 %exception</TT> directive. One approach is to only place it around
14564  critical pieces of code. For example:</P>
14565 <DIV class="code">
14566 <PRE>
14567 %exception {
14568         ... your exception handler ...
14569 }
14570 /* Define critical operations that can throw exceptions here */
14571
14572 %exception;
14573
14574 /* Define non-critical operations that don't throw exceptions */
14575 </PRE>
14576 </DIV>
14577 <P> More precise control over exception handling can be obtained by
14578  attaching an exception handler to specific declaration name. For
14579  example:</P>
14580 <DIV class="code">
14581 <PRE>
14582 %exception allocate {
14583     try {
14584         $action
14585     } 
14586     catch (MemoryError) {
14587         croak(&quot;Out of memory&quot;);
14588     }
14589 }
14590 </PRE>
14591 </DIV>
14592 <P> In this case, the exception handler is only attached to declarations
14593  named &quot;allocate&quot;. This would include both global and member functions.
14594  The names supplied to <TT>%exception</TT> follow the same rules as for <TT>
14595 %rename</TT> described in the section on <A href="#ambiguity_resolution_renaming">
14596 Ambiguity resolution and renaming</A>. For example, if you wanted to
14597  define an exception handler for a specific class, you might write this:</P>
14598 <DIV class="code">
14599 <PRE>
14600 %exception Object::allocate {
14601     try {
14602         $action
14603     } 
14604     catch (MemoryError) {
14605         croak(&quot;Out of memory&quot;);
14606     }
14607 }
14608 </PRE>
14609 </DIV>
14610 <P> When a class prefix is supplied, the exception handler is applied to
14611  the corresponding declaration in the specified class as well as for
14612  identically named functions appearing in derived classes.</P>
14613 <P> <TT>%exception</TT> can even be used to pinpoint a precise
14614  declaration when overloading is used. For example:</P>
14615 <DIV class="code">
14616 <PRE>
14617 %exception Object::allocate(int) {
14618     try {
14619         $action
14620     } 
14621     catch (MemoryError) {
14622         croak(&quot;Out of memory&quot;);
14623     }
14624 }
14625 </PRE>
14626 </DIV>
14627 <P> Attaching exceptions to specific declarations is a good way to
14628  reduce code bloat. It can also be a useful way to attach exceptions to
14629  specific parts of a header file. For example:</P>
14630 <DIV class="code">
14631 <PRE>
14632 %module example
14633 %{
14634 #include &quot;someheader.h&quot;
14635 %}
14636
14637 // Define a few exception handlers for specific declarations
14638 %exception Object::allocate(int) {
14639     try {
14640         $action
14641     } 
14642     catch (MemoryError) {
14643         croak(&quot;Out of memory&quot;);
14644     }
14645 }
14646
14647 %exception Object::getitem {
14648     try {
14649        $action
14650     }
14651     catch (RangeError) {
14652        croak(&quot;Index out of range&quot;);
14653     }
14654 }
14655 ...
14656 // Read a raw header file
14657 %include &quot;someheader.h&quot;
14658 </PRE>
14659 </DIV>
14660 <P><B> Compatibility note:</B> The <TT>%exception</TT> directive
14661  replaces the functionality provided by the deprecated &quot;except&quot; typemap.
14662  The typemap would allow exceptions to be thrown in the target language
14663  based on the return type of a function and was intended to be a
14664  mechanism for pinpointing specific declarations. However, it never
14665  really worked that well and the new %exception directive is much
14666  better.</P>
14667 <H3><A name="Customization_exception_special_variables"></A>11.1.6
14668  Special variables for %exception</H3>
14669 <P> The %exception directive supports a few special variables which are
14670  placeholders for code substitution. The following table shows the
14671  available special variables and details what the special variables are
14672  replaced with.</P>
14673 <TABLE summary="Special variables for %exception">
14674 <TR><TD>$action</TD><TD>The actual operation to be performed (a function
14675  call, method invocation, variable access, etc.)</TD></TR>
14676 <TR><TD>$symname</TD><TD>The symbol name used internally by SWIG</TD></TR>
14677 <TR><TD>$overname</TD><TD>The extra mangling used in the symbol name for
14678  overloaded method. Expands to nothing if the wrapped method is not
14679  overloaded.</TD></TR>
14680 <TR><TD>$wrapname</TD><TD>The language specific wrapper name (usually a
14681  C function name exported from the shared object/dll)</TD></TR>
14682 <TR><TD>$decl</TD><TD>The fully qualified C/C++ declaration of the
14683  method being wrapped without the return type</TD></TR>
14684 <TR><TD>$fulldecl</TD><TD>The fully qualified C/C++ declaration of the
14685  method being wrapped including the return type</TD></TR>
14686 </TABLE>
14687 <P> The special variables are often used in situations where method
14688  calls are logged. Exactly which form of the method call needs logging
14689  is up to individual requirements, but the example code below shows all
14690  the possible expansions, plus how an exception message could be
14691  tailored to show the C++ method declaration:</P>
14692 <DIV class="code">
14693 <PRE>
14694 %exception Special::something {
14695   log(&quot;symname: $symname&quot;);
14696   log(&quot;overname: $overname&quot;);
14697   log(&quot;wrapname: $wrapname&quot;);
14698   log(&quot;decl: $decl&quot;);
14699   log(&quot;fulldecl: $fulldecl&quot;);
14700   try {
14701     $action
14702   } 
14703   catch (MemoryError) {
14704       croak(&quot;Out of memory in $decl&quot;);
14705   }
14706 }
14707 void log(const char *message);
14708 struct Special {
14709   void something(const char *c);
14710   void something(int i);
14711 };
14712 </PRE>
14713 </DIV>
14714 <P> Below shows the expansions for the 1st of the overloaded <TT>
14715 something</TT> wrapper methods for Perl:</P>
14716 <DIV class="code">
14717 <PRE>
14718   log(&quot;symname: Special_something&quot;);
14719   log(&quot;overname: __SWIG_0&quot;);
14720   log(&quot;wrapname: _wrap_Special_something__SWIG_0&quot;);
14721   log(&quot;decl: Special::something(char const *)&quot;);
14722   log(&quot;fulldecl: void Special::something(char const *)&quot;);
14723   try {
14724     (arg1)-&gt;something((char const *)arg2);
14725   } 
14726   catch (MemoryError) {
14727     croak(&quot;Out of memory in Special::something(char const *)&quot;);
14728   }
14729 </PRE>
14730 </DIV>
14731 <H3><A name="Customization_nn7"></A>11.1.7 Using The SWIG exception
14732  library</H3>
14733 <P> The <TT>exception.i</TT> library file provides support for creating
14734  language independent exceptions in your interfaces. To use it, simply
14735  put an &quot;<TT>%include exception.i</TT>&quot; in your interface file. This
14736  creates a function <TT>SWIG_exception()</TT> that can be used to raise
14737  common scripting language exceptions in a portable manner. For example
14738  :</P>
14739 <DIV class="code">
14740 <PRE>
14741 // Language independent exception handler
14742 %include exception.i       
14743
14744 %exception {
14745     try {
14746         $action
14747     } catch(RangeError) {
14748         SWIG_exception(SWIG_ValueError, &quot;Range Error&quot;);
14749     } catch(DivisionByZero) {
14750         SWIG_exception(SWIG_DivisionByZero, &quot;Division by zero&quot;);
14751     } catch(OutOfMemory) {
14752         SWIG_exception(SWIG_MemoryError, &quot;Out of memory&quot;);
14753     } catch(...) {
14754         SWIG_exception(SWIG_RuntimeError,&quot;Unknown exception&quot;);
14755     }
14756 }
14757
14758 </PRE>
14759 </DIV>
14760 <P> As arguments, <TT>SWIG_exception()</TT> takes an error type code (an
14761  integer) and an error message string. The currently supported error
14762  types are :</P>
14763 <DIV class="diagram">
14764 <PRE>
14765 SWIG_UnknownError
14766 SWIG_IOError
14767 SWIG_RuntimeError
14768 SWIG_IndexError
14769 SWIG_TypeError
14770 SWIG_DivisionByZero
14771 SWIG_OverflowError
14772 SWIG_SyntaxError
14773 SWIG_ValueError
14774 SWIG_SystemError
14775 SWIG_AttributeError
14776 SWIG_MemoryError
14777 SWIG_NullReferenceError
14778 </PRE>
14779 </DIV>
14780 <P> Since the <TT>SWIG_exception()</TT> function is defined at the
14781  C-level it can be used elsewhere in SWIG. This includes typemaps and
14782  helper functions.</P>
14783 <H2><A name="ownership"></A>11.2 Object ownership and %newobject</H2>
14784 <P> A common problem in some applications is managing proper ownership
14785  of objects. For example, consider a function like this:</P>
14786 <DIV class="code">
14787 <PRE>
14788 Foo *blah() {
14789    Foo *f = new Foo();
14790    return f;
14791 }
14792 </PRE>
14793 </DIV>
14794 <P> If you wrap the function <TT>blah()</TT>, SWIG has no idea that the
14795  return value is a newly allocated object. As a result, the resulting
14796  extension module may produce a memory leak (SWIG is conservative and
14797  will never delete objects unless it knows for certain that the returned
14798  object was newly created).</P>
14799 <P> To fix this, you can provide an extra hint to the code generator
14800  using the <TT>%newobject</TT> directive. For example:</P>
14801 <DIV class="code">
14802 <PRE>
14803 %newobject blah;
14804 Foo *blah();
14805 </PRE>
14806 </DIV>
14807 <P> <TT>%newobject</TT> works exactly like <TT>%rename</TT> and <TT>
14808 %exception</TT>. In other words, you can attach it to class members and
14809  parameterized declarations as before. For example:</P>
14810 <DIV class="code">
14811 <PRE>
14812 %newobject ::blah();                   // Only applies to global blah
14813 %newobject Object::blah(int,double);   // Only blah(int,double) in Object
14814 %newobject *::copy;                    // Copy method in all classes
14815 ...
14816 </PRE>
14817 </DIV>
14818 <P> When <TT>%newobject</TT> is supplied, many language modules will
14819  arrange to take ownership of the return value. This allows the value to
14820  be automatically garbage-collected when it is no longer in use.
14821  However, this depends entirely on the target language (a language
14822  module may also choose to ignore the <TT>%newobject</TT> directive).</P>
14823 <P> Closely related to <TT>%newobject</TT> is a special typemap. The
14824  &quot;newfree&quot; typemap can be used to deallocate a newly allocated return
14825  value. It is only available on methods for which <TT>%newobject</TT>
14826  has been applied and is commonly used to clean-up string results. For
14827  example:</P>
14828 <DIV class="code">
14829 <PRE>
14830 %typemap(newfree) char * &quot;free($1);&quot;;
14831 ...
14832 %newobject strdup;
14833 ...
14834 char *strdup(const char *s);
14835 </PRE>
14836 </DIV>
14837 <P> In this case, the result of the function is a string in the target
14838  language. Since this string is a copy of the original result, the data
14839  returned by <TT>strdup()</TT> is no longer needed. The &quot;newfree&quot;
14840  typemap in the example simply releases this memory.</P>
14841 <P> As a complement to the <TT>%newobject</TT>, from SWIG 1.3.28, you
14842  can use the <TT>%delobject</TT> directive. For example, if you have two
14843  methods, one to create objects and one to destroy them, you can use:</P>
14844 <DIV class="code">
14845 <PRE>
14846 %newobject create_foo;
14847 %delobject destroy_foo;
14848 ...
14849 Foo *create_foo();
14850 void destroy_foo(Foo *foo);
14851 </PRE>
14852 </DIV>
14853 <P> or in a member method as:</P>
14854 <DIV class="code">
14855 <PRE>
14856 %delobject Foo::destroy;
14857
14858 class Foo {
14859 public:
14860   void destroy() { delete this;}
14861
14862 private:
14863   ~Foo();
14864 };
14865 </PRE>
14866 </DIV>
14867 <P> <TT>%delobject</TT> instructs SWIG that the first argument passed to
14868  the method will be destroyed, and therefore, the target language should
14869  not attempt to deallocate it twice. This is similar to use the DISOWN
14870  typemap in the first method argument, and in fact, it also depends on
14871  the target language on implementing the 'disown' mechanism properly.</P>
14872 <P><B> Compatibility note:</B> Previous versions of SWIG had a special <TT>
14873 %new</TT> directive. However, unlike <TT>%newobject</TT>, it only
14874  applied to the next declaration. For example:</P>
14875 <DIV class="code">
14876 <PRE>
14877 %new char *strdup(const char *s);
14878 </PRE>
14879 </DIV>
14880 <P> For now this is still supported but is deprecated.</P>
14881 <P><B> How to shoot yourself in the foot:</B> The <TT>%newobject</TT>
14882  directive is not a declaration modifier like the old <TT>%new</TT>
14883  directive. Don't write code like this:</P>
14884 <DIV class="code">
14885 <PRE>
14886 %newobject
14887 char *strdup(const char *s);
14888 </PRE>
14889 </DIV>
14890 <P> The results might not be what you expect.</P>
14891 <H2><A name="features"></A>11.3 Features and the %feature directive</H2>
14892 <P> Both <TT>%exception</TT> and <TT>%newobject</TT> are examples of a
14893  more general purpose customization mechanism known as &quot;features.&quot; A
14894  feature is simply a user-definable property that is attached to
14895  specific declarations. Features are attached using the <TT>%feature</TT>
14896  directive. For example:</P>
14897 <DIV class="code">
14898 <PRE>
14899 %feature(&quot;except&quot;) Object::allocate {
14900     try {
14901         $action
14902     } 
14903     catch (MemoryError) {
14904         croak(&quot;Out of memory&quot;);
14905     }
14906 }
14907
14908 %feature(&quot;new&quot;,&quot;1&quot;) *::copy;
14909 </PRE>
14910 </DIV>
14911 <P> In fact, the <TT>%exception</TT> and <TT>%newobject</TT> directives
14912  are really nothing more than macros involving <TT>%feature</TT>:</P>
14913 <DIV class="code">
14914 <PRE>
14915 #define %exception %feature(&quot;except&quot;)
14916 #define %newobject %feature(&quot;new&quot;,&quot;1&quot;)
14917 </PRE>
14918 </DIV>
14919 <P> The name matching rules outlined in the <A href="#ambiguity_resolution_renaming">
14920 Ambiguity resolution and renaming</A> section applies to all <TT>
14921 %feature</TT> directives. In fact the the <TT>%rename</TT> directive is
14922  just a special form of <TT>%feature</TT>. The matching rules mean that
14923  features are very flexible and can be applied with pinpoint accuracy to
14924  specific declarations if needed. Additionally, if no declaration name
14925  is given, a global feature is said to be defined. This feature is then
14926  attached to<EM> every</EM> declaration that follows. This is how global
14927  exception handlers are defined. For example:</P>
14928 <DIV class="code">
14929 <PRE>
14930 /* Define a global exception handler */
14931 %feature(&quot;except&quot;) {
14932    try {
14933      $action
14934    }
14935    ...
14936 }
14937
14938 ... bunch of declarations ...
14939 </PRE>
14940 </DIV>
14941 <P> The <TT>%feature</TT> directive can be used with different syntax.
14942  The following are all equivalent:</P>
14943 <DIV class="code">
14944 <PRE>
14945 %feature(&quot;except&quot;) Object::method { $action };
14946 %feature(&quot;except&quot;) Object::method %{ $action %};
14947 %feature(&quot;except&quot;) Object::method &quot; $action &quot;;
14948 %feature(&quot;except&quot;,&quot;$action&quot;) Object::method;
14949 </PRE>
14950 </DIV>
14951 <P> The syntax in the first variation will generate the <TT>{ }</TT>
14952  delimiters used whereas the other variations will not.</P>
14953 <H3><A name="Customization_feature_attributes"></A>11.3.1 Feature
14954  attributes</H3>
14955 <P> The <TT>%feature</TT> directive also accepts XML style attributes in
14956  the same way that typemaps do. Any number of attributes can be
14957  specified. The following is the generic syntax for features:</P>
14958 <DIV class="code">
14959 <PRE>
14960 %feature(&quot;name&quot;,&quot;value&quot;, attribute1=&quot;AttributeValue1&quot;) symbol;
14961 %feature(&quot;name&quot;, attribute1=&quot;AttributeValue1&quot;) symbol {value};
14962 %feature(&quot;name&quot;, attribute1=&quot;AttributeValue1&quot;) symbol %{value%};
14963 %feature(&quot;name&quot;, attribute1=&quot;AttributeValue1&quot;) symbol &quot;value&quot;;
14964 </PRE>
14965 </DIV>
14966 <P> More than one attribute can be specified using a comma separated
14967  list. The Java module is an example that uses attributes in <TT>
14968 %feature(&quot;except&quot;)</TT>. The <TT>throws</TT> attribute specifies the
14969  name of a Java class to add to a proxy method's throws clause. In the
14970  following example, <TT>MyExceptionClass</TT> is the name of the Java
14971  class for adding to the throws clause.</P>
14972 <DIV class="code">
14973 <PRE>
14974 %feature(&quot;except&quot;, throws=&quot;MyExceptionClass&quot;) Object::method { 
14975    try {
14976      $action
14977    } catch (...) {
14978      ... code to throw a MyExceptionClass Java exception ...
14979    }
14980 };
14981 </PRE>
14982 </DIV>
14983 <P> Further details can be obtained from the <A href="#exception_handling">
14984 Java exception handling</A> section.</P>
14985 <H3><A name="Customization_feature_flags"></A>11.3.2 Feature flags</H3>
14986 <P> Feature flags are used to enable or disable a particular feature.
14987  Feature flags are a common but simple usage of <TT>%feature</TT> and
14988  the feature value should be either <TT>1</TT> to enable or <TT>0</TT>
14989  to disable the feature.</P>
14990 <DIV class="code">
14991 <PRE>
14992 %feature(&quot;featurename&quot;)          // enables feature
14993 %feature(&quot;featurename&quot;, &quot;1&quot;)     // enables feature
14994 %feature(&quot;featurename&quot;, &quot;x&quot;)     // enables feature
14995 %feature(&quot;featurename&quot;, &quot;0&quot;)     // disables feature
14996 %feature(&quot;featurename&quot;, &quot;&quot;)      // clears feature
14997 </PRE>
14998 </DIV>
14999 <P> Actually any value other than zero will enable the feature. Note
15000  that if the value is omitted completely, the default value becomes <TT>
15001 1</TT>, thereby enabling the feature. A feature is cleared by specifying
15002  no value, see <A href="#Customization_clearing_features">Clearing
15003  features</A>. The <TT>%immutable</TT> directive described in the <A href="#SWIG_readonly_variables">
15004 Creating read-only variables</A> section, is just a macro for <TT>
15005 %feature(&quot;immutable&quot;)</TT>, and can be used to demonstrates feature
15006  flags:</P>
15007 <DIV class="code">
15008 <PRE>
15009                                 // features are disabled by default
15010 int red;                        // mutable
15011
15012 %feature(&quot;immutable&quot;);          // global enable
15013 int orange;                     // immutable
15014
15015 %feature(&quot;immutable&quot;,&quot;0&quot;);      // global disable
15016 int yellow;                     // mutable
15017
15018 %feature(&quot;immutable&quot;,&quot;1&quot;);      // another form of global enable
15019 int green;                      // immutable
15020
15021 %feature(&quot;immutable&quot;,&quot;&quot;);       // clears the global feature
15022 int blue;                       // mutable
15023 </PRE>
15024 </DIV>
15025 <P> Note that features are disabled by default and must be explicitly
15026  enabled either globally or by specifying a targeted declaration. The
15027  above intersperses SWIG directives with C code. Of course you can
15028  target features explicitly, so the above could also be rewritten as:</P>
15029 <DIV class="code">
15030 <PRE>
15031 %feature(&quot;immutable&quot;,&quot;1&quot;) orange;
15032 %feature(&quot;immutable&quot;,&quot;1&quot;) green;
15033 int red;                        // mutable
15034 int orange;                     // immutable
15035 int yellow;                     // mutable
15036 int green;                      // immutable
15037 int blue;                       // mutable
15038 </PRE>
15039 </DIV>
15040 <P> The above approach allows for the C declarations to be separated
15041  from the SWIG directives for when the C declarations are parsed from a
15042  C header file. The logic above can of course be inverted and rewritten
15043  as:</P>
15044 <DIV class="code">
15045 <PRE>
15046 %feature(&quot;immutable&quot;,&quot;1&quot;);
15047 %feature(&quot;immutable&quot;,&quot;0&quot;) red;
15048 %feature(&quot;immutable&quot;,&quot;0&quot;) yellow;
15049 %feature(&quot;immutable&quot;,&quot;0&quot;) blue;
15050 int red;                        // mutable
15051 int orange;                     // immutable
15052 int yellow;                     // mutable
15053 int green;                      // immutable
15054 int blue;                       // mutable
15055 </PRE>
15056 </DIV>
15057 <P> As hinted above for <TT>%immutable</TT>, most feature flags can also
15058  be specified via alternative syntax. The alternative syntax is just a
15059  macro in the <TT>swig.swg</TT> Library file. The following shows the
15060  alternative syntax for the imaginary <TT>featurename</TT> feature:</P>
15061 <DIV class="code">
15062 <PRE>
15063 %featurename       // equivalent to %feature(&quot;featurename&quot;, &quot;1&quot;) ie enables feature
15064 %nofeaturename     // equivalent to %feature(&quot;featurename&quot;, &quot;0&quot;) ie disables feature
15065 %clearfeaturename  // equivalent to %feature(&quot;featurename&quot;, &quot;&quot;)  ie clears feature
15066 </PRE>
15067 </DIV>
15068 <P> The concept of clearing features is discussed next.</P>
15069 <H3><A name="Customization_clearing_features"></A>11.3.3 Clearing
15070  features</H3>
15071 <P> A feature stays in effect until it is explicitly cleared. A feature
15072  is cleared by supplying a <TT>%feature</TT> directive with no value.
15073  For example <TT>%feature(&quot;name&quot;,&quot;&quot;)</TT>. A cleared feature means that
15074  any feature exactly matching any previously defined feature is no
15075  longer used in the name matching rules. So if a feature is cleared, it
15076  might mean that another name matching rule will apply. To clarify,
15077  let's consider the <TT>except</TT> feature again (<TT>%exception</TT>):</P>
15078 <DIV class="code">
15079 <PRE>
15080 // Define global exception handler
15081 %feature(&quot;except&quot;) {
15082     try {
15083         $action
15084     } catch (...) {
15085         croak(&quot;Unknown C++ exception&quot;);
15086     }
15087 }
15088
15089 // Define exception handler for all clone methods to log the method calls
15090 %feature(&quot;except&quot;) *::clone() {
15091     try {
15092         logger.info(&quot;$action&quot;);
15093         $action
15094     } catch (...) {
15095         croak(&quot;Unknown C++ exception&quot;);
15096     }
15097 }
15098
15099 ... initial set of class declarations with clone methods ...
15100
15101 // clear the previously defined feature
15102 %feature(&quot;except&quot;,&quot;&quot;) *::clone();
15103
15104 ... final set of class declarations with clone methods ...
15105 </PRE>
15106 </DIV>
15107 <P> In the above scenario, the initial set of clone methods will log all
15108  method invocations from the target language. This specific feature is
15109  cleared for the final set of clone methods. However, these clone
15110  methods will still have an exception handler (without logging) as the
15111  next best feature match for them is the global exception handler.</P>
15112 <P> Note that clearing a feature is not always the same as disabling it.
15113  Clearing the feature above with <TT>%feature(&quot;except&quot;,&quot;&quot;) *::clone()</TT>
15114  is not the same as specifying <TT>%feature(&quot;except&quot;,&quot;0&quot;) *::clone()</TT>
15115 . The former will disable the feature for clone methods - the feature is
15116  still a better match than the global feature. If on the other hand, no
15117  global exception handler had been defined at all, then clearing the
15118  feature would be the same as disabling it as no other feature would
15119  have matched.</P>
15120 <P> Note that the feature must match exactly for it to be cleared by any
15121  previously defined feature. For example the following attempt to clear
15122  the initial feature will not work:</P>
15123 <DIV class="code">
15124 <PRE>
15125 %feature(&quot;except&quot;) clone() { logger.info(&quot;$action&quot;); $action }
15126 %feature(&quot;except&quot;,&quot;&quot;) *::clone();
15127 </PRE>
15128 </DIV>
15129 <P> but this will:</P>
15130 <DIV class="code">
15131 <PRE>
15132 %feature(&quot;except&quot;) clone() { logger.info(&quot;$action&quot;); $action }
15133 %feature(&quot;except&quot;,&quot;&quot;) clone();
15134 </PRE>
15135 </DIV>
15136 <P> SWIG provides macros for disabling and clearing features. Many of
15137  these can be found in the <TT>swig.swg</TT> library file. The typical
15138  pattern is to define three macros; one to define the feature itself,
15139  one to disable the feature and one to clear the feature. The three
15140  macros below show this for the &quot;except&quot; feature:</P>
15141 <DIV class="code">
15142 <PRE>
15143 #define %exception      %feature(&quot;except&quot;)
15144 #define %noexception    %feature(&quot;except&quot;,&quot;0&quot;)
15145 #define %clearexception %feature(&quot;except&quot;,&quot;&quot;)
15146 </PRE>
15147 </DIV>
15148 <H3><A name="Customization_features_default_args"></A>11.3.4 Features
15149  and default arguments</H3>
15150 <P> SWIG treats methods with default arguments as separate overloaded
15151  methods as detailed in the <A href="#SWIGPlus_default_args">default
15152  arguments</A> section. Any <TT>%feature</TT> targeting a method with
15153  default arguments will apply to all the extra overloaded methods that
15154  SWIG generates if the default arguments are specified in the feature.
15155  If the default arguments are not specified in the feature, then the
15156  feature will match that exact wrapper method only and not the extra
15157  overloaded methods that SWIG generates. For example:</P>
15158 <DIV class="code">
15159 <PRE>
15160 %feature(&quot;except&quot;) void hello(int i=0, double d=0.0) { ... }
15161 void hello(int i=0, double d=0.0);
15162 </PRE>
15163 </DIV>
15164 <P> will apply the feature to all three wrapper methods, that is:</P>
15165 <DIV class="code">
15166 <PRE>
15167 void hello(int i, double d);
15168 void hello(int i);
15169 void hello();
15170 </PRE>
15171 </DIV>
15172 <P> If the default arguments are not specified in the feature:</P>
15173 <DIV class="code">
15174 <PRE>
15175 %feature(&quot;except&quot;) void hello(int i, double d) { ... }
15176 void hello(int i=0, double d=0.0);
15177 </PRE>
15178 </DIV>
15179 <P> then the feature will only apply to this wrapper method:</P>
15180 <DIV class="code">
15181 <PRE>
15182 void hello(int i, double d);
15183 </PRE>
15184 </DIV>
15185 <P> and not these wrapper methods:</P>
15186 <DIV class="code">
15187 <PRE>
15188 void hello(int i);
15189 void hello();
15190 </PRE>
15191 </DIV>
15192 <P> If <A href="#SWIGPlus_default_args">compactdefaultargs</A> are being
15193  used, then the difference between specifying or not specifying default
15194  arguments in a feature is not applicable as just one wrapper is
15195  generated.</P>
15196 <P><B> Compatibility note:</B> The different behaviour of features
15197  specified with or without default arguments was introduced in
15198  SWIG-1.3.23 when the approach to wrapping methods with default
15199  arguments was changed.</P>
15200 <H3><A name="features_example"></A>11.3.5 Feature example</H3>
15201 <P> As has been shown earlier, the intended use for the <TT>%feature</TT>
15202  directive is as a highly flexible customization mechanism that can be
15203  used to annotate declarations with additional information for use by
15204  specific target language modules. Another example is in the Python
15205  module. You might use <TT>%feature</TT> to rewrite proxy/shadow class
15206  code as follows:</P>
15207 <DIV class="code">
15208 <PRE>
15209 %module example
15210 %rename(bar_id) bar(int,double);
15211
15212 // Rewrite bar() to allow some nice overloading
15213
15214 %feature(&quot;shadow&quot;) Foo::bar(int) %{
15215 def bar(*args):
15216     if len(args) == 3:
15217          return apply(examplec.Foo_bar_id,args)
15218     return apply(examplec.Foo_bar,args)
15219 %}
15220     
15221 class Foo {
15222 public:
15223     int bar(int x);
15224     int bar(int x, double y);
15225 }
15226 </PRE>
15227 </DIV>
15228 <P> Further details of <TT>%feature</TT> usage is described in the
15229  documentation for specific language modules.</P>
15230 <HR NOSHADE>
15231 <H1><A name="Contract"></A>12 Contracts</H1>
15232
15233 <!-- INDEX -->
15234 <DIV class="sectiontoc">
15235 <UL>
15236 <LI><A href="#Contract_nn2">The %contract directive</A></LI>
15237 <LI><A href="#Contract_nn3">%contract and classes</A></LI>
15238 <LI><A href="#Contract_nn4">Constant aggregation and %aggregate_check</A>
15239 </LI>
15240 <LI><A href="#Contract_nn5">Notes</A></LI>
15241 </UL>
15242 </DIV>
15243 <!-- INDEX -->
15244 <P> A common problem that arises when wrapping C libraries is that of
15245  maintaining reliability and checking for errors. The fact of the matter
15246  is that many C programs are notorious for not providing error checks.
15247  Not only that, when you expose the internals of an application as a
15248  library, it often becomes possible to crash it simply by providing bad
15249  inputs or using it in a way that wasn't intended.</P>
15250 <P> This chapter describes SWIG's support for software contracts. In the
15251  context of SWIG, a contract can be viewed as a runtime constraint that
15252  is attached to a declaration. For example, you can easily attach
15253  argument checking rules, check the output values of a function and
15254  more. When one of the rules is violated by a script, a runtime
15255  exception is generated rather than having the program continue to
15256  execute.</P>
15257 <H2><A name="Contract_nn2"></A>12.1 The %contract directive</H2>
15258 <P> Contracts are added to a declaration using the %contract directive.
15259  Here is a simple example:</P>
15260 <DIV class="code">
15261 <PRE>
15262 %contract sqrt(double x) {
15263 require:
15264     x &gt;= 0;
15265 ensure:
15266     sqrt &gt;= 0;
15267 }
15268
15269 ...
15270 double sqrt(double);
15271 </PRE>
15272 </DIV>
15273 <P> In this case, a contract is being added to the <TT>sqrt()</TT>
15274  function. The <TT>%contract</TT> directive must always appear before
15275  the declaration in question. Within the contract there are two
15276  sections, both of which are optional. The <TT>require:</TT> section
15277  specifies conditions that must hold before the function is called.
15278  Typically, this is used to check argument values. The <TT>ensure:</TT>
15279  section specifies conditions that must hold after the function is
15280  called. This is often used to check return values or the state of the
15281  program. In both cases, the conditions that must hold must be specified
15282  as boolean expressions.</P>
15283 <P> In the above example, we're simply making sure that sqrt() returns a
15284  non-negative number (if it didn't, then it would be broken in some
15285  way).</P>
15286 <P> Once a contract has been specified, it modifies the behavior of the
15287  resulting module. For example:</P>
15288 <DIV class="shell">
15289 <PRE>
15290 &gt;&gt;&gt; example.sqrt(2)
15291 1.4142135623730951
15292 &gt;&gt;&gt; example.sqrt(-2)
15293 Traceback (most recent call last):
15294   File &quot;&lt;stdin&gt;&quot;, line 1, in ?
15295 RuntimeError: Contract violation: require: (arg1&gt;=0)
15296 &gt;&gt;&gt;
15297 </PRE>
15298 </DIV>
15299 <H2><A name="Contract_nn3"></A>12.2 %contract and classes</H2>
15300 <P> The <TT>%contract</TT> directive can also be applied to class
15301  methods and constructors. For example:</P>
15302 <DIV class="code">
15303 <PRE>
15304 %contract Foo::bar(int x, int y) {
15305 require:
15306    x &gt; 0;
15307 ensure:
15308    bar &gt; 0;
15309 }
15310
15311 %contract Foo::Foo(int a) {
15312 require:
15313    a &gt; 0;
15314 }
15315
15316 class Foo {
15317 public:
15318     Foo(int);
15319     int bar(int, int);
15320 };
15321 </PRE>
15322 </DIV>
15323 <P> The way in which <TT>%contract</TT> is applied is exactly the same
15324  as the <TT>%feature</TT> directive. Thus, any contract that you
15325  specified for a base class will also be attached to inherited methods.
15326  For example:</P>
15327 <DIV class="code">
15328 <PRE>
15329 class Spam : public Foo {
15330 public:
15331    int bar(int,int);    // Gets contract defined for Foo::bar(int,int)
15332 };
15333 </PRE>
15334 </DIV>
15335 <P> In addition to this, separate contracts can be applied to both the
15336  base class and a derived class. For example:</P>
15337 <DIV class="code">
15338 <PRE>
15339 %contract Foo::bar(int x, int) {
15340 require:
15341     x &gt; 0;
15342 }
15343
15344 %contract Spam::bar(int, int y) {
15345 require:
15346     y &gt; 0;
15347 }
15348
15349 class Foo {
15350 public:
15351     int bar(int,int);   // Gets Foo::bar contract.
15352 };
15353
15354 class Spam : public Foo {
15355 public:
15356      int bar(int,int);   // Gets Foo::bar and Spam::bar contract
15357 };
15358 </PRE>
15359 </DIV>
15360 <P> When more than one contract is applied, the conditions specified in
15361  a &quot;require:&quot; section are combined together using a logical-AND
15362  operation. In other words conditions specified for the base class and
15363  conditions specified for the derived class all must hold. In the above
15364  example, this means that both the arguments to <TT>Spam::bar</TT> must
15365  be positive.</P>
15366 <H2><A name="Contract_nn4"></A>12.3 Constant aggregation and
15367  %aggregate_check</H2>
15368 <P> Consider an interface file that contains the following code:</P>
15369 <DIV class="code">
15370 <PRE>
15371 #define  UP     1
15372 #define  DOWN   2
15373 #define  RIGHT  3
15374 #define  LEFT   4
15375
15376 void move(SomeObject *, int direction, int distance);
15377 </PRE>
15378 </DIV>
15379 <P> One thing you might want to do is impose a constraint on the
15380  direction parameter to make sure it's one of a few accepted values. To
15381  do that, SWIG provides an easy to use macro %aggregate_check() that
15382  works like this:</P>
15383 <DIV class="code">
15384 <PRE>
15385 %aggregate_check(int, check_direction, UP, DOWN, LEFT, RIGHT);
15386 </PRE>
15387 </DIV>
15388 <P> This merely defines a utility function of the form</P>
15389 <DIV class="code">
15390 <PRE>
15391 int check_direction(int x);
15392 </PRE>
15393 </DIV>
15394 <P> That checks the argument x to see if it is one of the values listed.
15395  This utility function can be used in contracts. For example:</P>
15396 <DIV class="code">
15397 <PRE>
15398 %aggregate_check(int, check_direction, UP, DOWN, RIGHT, LEFT);
15399
15400 %contract move(SomeObject *, int direction, in) {
15401 require:
15402      check_direction(direction);
15403 }
15404
15405 #define  UP     1
15406 #define  DOWN   2
15407 #define  RIGHT  3
15408 #define  LEFT   4
15409
15410 void move(SomeObject *, int direction, int distance);
15411 </PRE>
15412 </DIV>
15413 <P> Alternatively, it can be used in typemaps and other directives. For
15414  example:</P>
15415 <DIV class="code">
15416 <PRE>
15417 %aggregate_check(int, check_direction, UP, DOWN, RIGHT, LEFT);
15418
15419 %typemap(check) int direction {
15420     if (!check_direction($1)) SWIG_exception(SWIG_ValueError, &quot;Bad direction&quot;);
15421 }
15422
15423 #define  UP     1
15424 #define  DOWN   2
15425 #define  RIGHT  3
15426 #define  LEFT   4
15427
15428 void move(SomeObject *, int direction, int distance);
15429 </PRE>
15430 </DIV>
15431 <P> Regrettably, there is no automatic way to perform similar checks
15432  with enums values. Maybe in a future release.</P>
15433 <H2><A name="Contract_nn5"></A>12.4 Notes</H2>
15434 <P> Contract support was implemented by Songyan (Tiger) Feng and first
15435  appeared in SWIG-1.3.20.</P>
15436 <HR NOSHADE>
15437 <H1><A name="Varargs"></A>13 Variable Length Arguments</H1>
15438
15439 <!-- INDEX -->
15440 <DIV class="sectiontoc">
15441 <UL>
15442 <LI><A href="#Varargs_nn2">Introduction</A></LI>
15443 <LI><A href="#Varargs_nn3">The Problem</A></LI>
15444 <LI><A href="#Varargs_nn4">Default varargs support</A></LI>
15445 <LI><A href="#Varargs_nn5">Argument replacement using %varargs</A></LI>
15446 <LI><A href="#Varargs_nn6">Varargs and typemaps</A></LI>
15447 <LI><A href="#Varargs_nn7">Varargs wrapping with libffi</A></LI>
15448 <LI><A href="#Varargs_nn8">Wrapping of va_list</A></LI>
15449 <LI><A href="#Varargs_nn9">C++ Issues</A></LI>
15450 <LI><A href="#Varargs_nn10">Discussion</A></LI>
15451 </UL>
15452 </DIV>
15453 <!-- INDEX -->
15454 <P><B> (a.k.a, &quot;The horror. The horror.&quot;)</B></P>
15455 <P> This chapter describes the problem of wrapping functions that take a
15456  variable number of arguments. For instance, generating wrappers for the
15457  C <TT>printf()</TT> family of functions.</P>
15458 <P> This topic is sufficiently advanced to merit its own chapter. In
15459  fact, support for varargs is an often requested feature that was first
15460  added in SWIG-1.3.12. Most other wrapper generation tools have wisely
15461  chosen to avoid this issue.</P>
15462 <H2><A name="Varargs_nn2"></A>13.1 Introduction</H2>
15463 <P> Some C and C++ programs may include functions that accept a variable
15464  number of arguments. For example, most programmers are familiar with
15465  functions from the C library such as the following:</P>
15466 <DIV class="code">
15467 <PRE>
15468 int printf(const char *fmt, ...)
15469 int fprintf(FILE *, const char *fmt, ...);
15470 int sprintf(char *s, const char *fmt, ...);
15471 </PRE>
15472 </DIV>
15473 <P> Although there is probably little practical purpose in wrapping
15474  these specific C library functions in a scripting language (what would
15475  be the point?), a library may include its own set of special functions
15476  based on a similar API. For example:</P>
15477 <DIV class="code">
15478 <PRE>
15479 int  traceprintf(const char *fmt, ...);
15480 </PRE>
15481 </DIV>
15482 <P> In this case, you may want to have some kind of access from the
15483  target language.</P>
15484 <P> Before describing the SWIG implementation, it is important to
15485  discuss the common uses of varargs that you are likely to encounter in
15486  real programs. Obviously, there are the <TT>printf()</TT> style output
15487  functions as shown. Closely related to this would be <TT>scanf()</TT>
15488  style input functions that accept a format string and a list of
15489  pointers into which return values are placed. However, variable length
15490  arguments are also sometimes used to write functions that accept a
15491  NULL-terminated list of pointers. A good example of this would be a
15492  function like this:</P>
15493 <DIV class="code">
15494 <PRE>
15495 int execlp(const char *path, const char *arg1, ...);
15496 ...
15497
15498 /* Example */
15499 execlp(&quot;ls&quot;,&quot;ls&quot;,&quot;-l&quot;,NULL);
15500 </PRE>
15501 </DIV>
15502 <P> In addition, varargs is sometimes used to fake default arguments in
15503  older C libraries. For instance, the low level <TT>open()</TT> system
15504  call is often declared as a varargs function so that it will accept two
15505  or three arguments:</P>
15506 <DIV class="code">
15507 <PRE>
15508 int open(const char *path, int oflag, ...);
15509 ...
15510
15511 /* Examples */
15512 f = open(&quot;foo&quot;, O_RDONLY);
15513 g = open(&quot;bar&quot;, O_WRONLY | O_CREAT, 0644);
15514 </PRE>
15515 </DIV>
15516 <P> Finally, to implement a varargs function, recall that you have to
15517  use the C library functions defined in <TT>&lt;stdarg.h&gt;</TT>. For
15518  example:</P>
15519 <DIV class="code">
15520 <PRE>
15521 List make_list(const char *s, ...) {
15522     va_list ap;
15523     List    x;
15524     ...
15525     va_start(ap, s);
15526     while (s) {
15527        x.append(s);
15528        s = va_arg(ap, const char *);
15529     }
15530     va_end(ap);
15531     return x;
15532 }
15533 </PRE>
15534 </DIV>
15535 <H2><A name="Varargs_nn3"></A>13.2 The Problem</H2>
15536 <P> Generating wrappers for a variable length argument function presents
15537  a number of special challenges. Although C provides support for
15538  implementing functions that receive variable length arguments, there
15539  are no functions that can go in the other direction. Specifically, you
15540  can't write a function that dynamically creates a list of arguments and
15541  which invokes a varargs function on your behalf.</P>
15542 <P> Although it is possible to write functions that accept the special
15543  type <TT>va_list</TT>, this is something entirely different. You can't
15544  take a <TT>va_list</TT> structure and pass it in place of the variable
15545  length arguments to another varargs function. It just doesn't work.</P>
15546 <P> The reason this doesn't work has to do with the way that function
15547  calls get compiled. For example, suppose that your program has a
15548  function call like this:</P>
15549 <DIV class="code">
15550 <PRE>
15551 printf(&quot;Hello %s. Your number is %d\n&quot;, name, num);
15552 </PRE>
15553 </DIV>
15554 <P> When the compiler looks at this, it knows that you are calling <TT>
15555 printf()</TT> with exactly three arguments. Furthermore, it knows that
15556  the number of arguments as well are their types and sizes is<EM> never</EM>
15557  going to change during program execution. Therefore, this gets turned
15558  to machine code that sets up a three-argument stack frame followed by a
15559  call to <TT>printf()</TT>.</P>
15560 <P> In contrast, suppose you attempted to make some kind of wrapper
15561  around <TT>printf()</TT> using code like this:</P>
15562 <DIV class="code">
15563 <PRE>
15564 int wrap_printf(const char *fmt, ...) {
15565    va_list ap;
15566    va_start(ap,fmt);
15567    ...
15568    printf(fmt,ap);
15569    ...
15570    va_end(ap);
15571 };
15572 </PRE>
15573 </DIV>
15574 <P> Although this code might compile, it won't do what you expect. This
15575  is because the call to <TT>printf()</TT> is compiled as a procedure
15576  call involving only two arguments. However, clearly a two-argument
15577  configuration of the call stack is completely wrong if your intent is
15578  to pass an arbitrary number of arguments to the real <TT>printf()</TT>.
15579  Needless to say, it won't work.</P>
15580 <P> Unfortunately, the situation just described is exactly the problem
15581  faced by wrapper generation tools. In general, the number of passed
15582  arguments will not be known until run-time. To make matters even worse,
15583  you won't know the types and sizes of arguments until run-time as well.
15584  Needless to say, there is no obvious way to make the C compiler
15585  generate code for a function call involving an unknown number of
15586  arguments of unknown types.</P>
15587 <P> In theory, it<EM> is</EM> possible to write a wrapper that does the
15588  right thing. However, this involves knowing the underlying ABI for the
15589  target platform and language as well as writing special purpose code
15590  that manually constructed the call stack before making a procedure
15591  call. Unfortunately, both of these tasks require the use of inline
15592  assembly code. Clearly, that's the kind of solution you would much
15593  rather avoid.</P>
15594 <P> With this nastiness in mind, SWIG provides a number of solutions to
15595  the varargs wrapping problem. Most of these solutions are compromises
15596  that provide limited varargs support without having to resort to
15597  assembly language. However, SWIG can also support real varargs wrapping
15598  (with stack-frame manipulation) if you are willing to get hands dirty.
15599  Keep reading.</P>
15600 <H2><A name="Varargs_nn4"></A>13.3 Default varargs support</H2>
15601 <P> When variable length arguments appear in an interface, the default
15602  behavior is to drop the variable argument list entirely, replacing them
15603  with a single NULL pointer. For example, if you had this function,</P>
15604 <DIV class="code">
15605 <PRE>
15606 void traceprintf(const char *fmt, ...);
15607 </PRE>
15608 </DIV>
15609 <P> it would be wrapped as if it had been declared as follows:</P>
15610 <DIV class="code">
15611 <PRE>
15612 void traceprintf(const char *fmt);
15613 </PRE>
15614 </DIV>
15615 <P> When the function is called inside the wrappers, it is called as
15616  follows:</P>
15617 <DIV class="code">
15618 <PRE>
15619 traceprintf(arg1, NULL);
15620 </PRE>
15621 </DIV>
15622 <P> Arguably, this approach seems to defeat the whole point of variable
15623  length arguments. However, this actually provides enough support for
15624  many simple kinds of varargs functions to still be useful. For
15625  instance, you could make function calls like this (in Python):</P>
15626 <DIV class="targetlang">
15627 <PRE>
15628 &gt;&gt;&gt; traceprintf(&quot;Hello World&quot;)
15629 &gt;&gt;&gt; traceprintf(&quot;Hello %s. Your number is %d\n&quot; % (name, num))
15630 </PRE>
15631 </DIV>
15632 <P> Notice how string formatting is being done in Python instead of C.</P>
15633 <H2><A name="Varargs_nn5"></A>13.4 Argument replacement using %varargs</H2>
15634 <P> Instead of dropping the variable length arguments, an alternative
15635  approach is to replace <TT>(...)</TT> with a set of suitable arguments.
15636  SWIG provides a special <TT>%varargs</TT> directive that can be used to
15637  do this. For example,</P>
15638 <DIV class="code">
15639 <PRE>
15640 %varargs(int mode = 0) open;
15641 ...
15642 int open(const char *path, int oflags, ...);
15643 </PRE>
15644 </DIV>
15645 <P> is equivalent to this:</P>
15646 <DIV class="code">
15647 <PRE>
15648 int open(const char *path, int oflags, int mode = 0);
15649 </PRE>
15650 </DIV>
15651 <P> In this case, <TT>%varargs</TT> is simply providing more specific
15652  information about the extra arguments that might be passed to a
15653  function. If the parameters to a varargs function are of uniform type, <TT>
15654 %varargs</TT> can also accept a numerical argument count as follows:</P>
15655 <DIV class="code">
15656 <PRE>
15657 %varargs(10,char *arg = NULL) execlp;
15658 ...
15659 int execlp(const char *path, const char *arg1, ...);
15660 </PRE>
15661 </DIV>
15662 <P> This would wrap <TT>execlp()</TT> as a function that accepted up to
15663  10 optional arguments. Depending on the application, this may be more
15664  than enough for practical purposes.</P>
15665 <P> Argument replacement is most appropriate in cases where the types of
15666  the extra arguments is uniform and the maximum number of arguments is
15667  known. When replicated argument replacement is used, at least one extra
15668  argument is added to the end of the arguments when making the function
15669  call. This argument serves as a sentinel to make sure the list is
15670  properly terminated. It has the same value as that supplied to the <TT>
15671 %varargs</TT> directive.</P>
15672 <P> Argument replacement is not as useful when working with functions
15673  that accept mixed argument types such as <TT>printf()</TT>. Providing
15674  general purpose wrappers to such functions presents special problems
15675  (covered shortly).</P>
15676 <H2><A name="Varargs_nn6"></A>13.5 Varargs and typemaps</H2>
15677 <P> Variable length arguments may be used in typemap specifications. For
15678  example:</P>
15679 <DIV class="code">
15680 <PRE>
15681 %typemap(in) (...) {
15682     // Get variable length arguments (somehow)
15683     ...
15684 }
15685
15686 %typemap(in) (const char *fmt, ...) {
15687     // Multi-argument typemap
15688 }
15689 </PRE>
15690 </DIV>
15691 <P> However, this immediately raises the question of what &quot;type&quot; is
15692  actually used to represent <TT>(...)</TT>. For lack of a better
15693  alternative, the type of <TT>(...)</TT> is set to <TT>void *</TT>.
15694  Since there is no way to dynamically pass arguments to a varargs
15695  function (as previously described), the <TT>void *</TT> argument value
15696  is intended to serve as a place holder for storing some kind of
15697  information about the extra arguments (if any). In addition, the
15698  default behavior of SWIG is to pass the <TT>void *</TT> value as an
15699  argument to the function. Therefore, you could use the pointer to hold
15700  a valid argument value if you wanted.</P>
15701 <P> To illustrate, here is a safer version of wrapping <TT>printf()</TT>
15702  in Python:</P>
15703 <DIV class="code">
15704 <PRE>
15705 %typemap(in) (const char *fmt, ...) {
15706     $1 = &quot;%s&quot;;                                /* Fix format string to %s */
15707     $2 = (void *) PyString_AsString($input);  /* Get string argument */
15708 };
15709 ...
15710 int printf(const char *fmt, ...);
15711 </PRE>
15712 </DIV>
15713 <P> In this example, the format string is implicitly set to <TT>&quot;%s&quot;</TT>
15714 . This prevents a program from passing a bogus format string to the
15715  extension. Then, the passed input object is decoded and placed in the <TT>
15716 void *</TT> argument defined for the <TT>(...)</TT> argument. When the
15717  actual function call is made, the underlying wrapper code will look
15718  roughly like this:</P>
15719 <DIV class="code">
15720 <PRE>
15721 wrap_printf() {
15722    char *arg1;
15723    void *arg2;
15724    int   result;
15725
15726    arg1 = &quot;%s&quot;;
15727    arg2 = (void *) PyString_AsString(arg2obj);
15728    ...
15729    result = printf(arg1,arg2);
15730    ...
15731 }
15732 </PRE>
15733 </DIV>
15734 <P> Notice how both arguments are passed to the function and it does
15735  what you would expect.</P>
15736 <P> The next example illustrates a more advanced kind of varargs
15737  typemap. Disclaimer: this requires special support in the target
15738  language module and is not guaranteed to work with all SWIG modules at
15739  this time. It also starts to illustrate some of the more fundamental
15740  problems with supporting varargs in more generality.</P>
15741 <P> If a typemap is defined for any form of <TT>(...)</TT>, many SWIG
15742  modules will generate wrappers that accept a variable number of
15743  arguments as input and will make these arguments available in some
15744  form. The precise details of this depends on the language module being
15745  used (consult the appropriate chapter for more details). However,
15746  suppose that you wanted to create a Python wrapper for the <TT>execlp()</TT>
15747  function shown earlier. To do this using a typemap instead of using <TT>
15748 %varargs</TT>, you might first write a typemap like this:</P>
15749 <DIV class="code">
15750 <PRE>
15751 %typemap(in) (...)(char *args[10]) {
15752     int i;
15753     int argc;
15754     for (i = 0; i &lt; 10; i++) args[i] = 0;
15755     argc = PyTuple_Size(varargs);
15756     if (argc &gt; 10) {
15757        PyErr_SetString(PyExc_ValueError,&quot;Too many arguments&quot;);
15758        return NULL;
15759     }
15760     for (i = 0; i &lt; argc; i++) {
15761        PyObject *o = PyTuple_GetItem(varargs,i);
15762        if (!PyString_Check(o)) {
15763            PyErr_SetString(PyExc_ValueError,&quot;Expected a string&quot;);
15764            return NULL;
15765        }
15766        args[i] = PyString_AsString(o);
15767     }
15768     $1 = (void *) args;
15769 }
15770 </PRE>
15771 </DIV>
15772 <P> In this typemap, the special variable <TT>varargs</TT> is a tuple
15773  holding all of the extra arguments passed (this is specific to the
15774  Python module). The typemap then pulls this apart and sticks the values
15775  into the array of strings <TT>args</TT>. Then, the array is assigned to
15776  <TT>$1</TT> (recall that this is the <TT>void *</TT> variable
15777  corresponding to <TT>(...)</TT>). However, this assignment is only half
15778  of the picture----clearly this alone is not enough to make the function
15779  work. To patch everything up, you have to rewrite the underlying action
15780  code using the <TT>%feature</TT> directive like this:</P>
15781 <DIV class="code">
15782 <PRE>
15783 %feature(&quot;action&quot;) execlp {
15784    char *args = (char **) arg3;
15785    result = execlp(arg1, arg2, args[0], args[1], args[2], args[3], args[4],
15786                    args[5],args[6],args[7],args[8],args[9], NULL);
15787 }
15788
15789 int execlp(const char *path, const char *arg, ...);
15790 </PRE>
15791 </DIV>
15792 <P> This patches everything up and creates a function that more or less
15793  works. However, don't try explaining this to your coworkers unless you
15794  know for certain that they've had several cups of coffee. If you really
15795  want to elevate your guru status and increase your job security,
15796  continue to the next section.</P>
15797 <H2><A name="Varargs_nn7"></A>13.6 Varargs wrapping with libffi</H2>
15798 <P> All of the previous examples have relied on features of SWIG that
15799  are portable and which don't rely upon any low-level machine-level
15800  details. In many ways, they have all dodged the real issue of variable
15801  length arguments by recasting a varargs function into some weaker
15802  variation with a fixed number of arguments of known types. In many
15803  cases, this works perfectly fine. However, if you want more generality
15804  than this, you need to bring out some bigger guns.</P>
15805 <P> One way to do this is to use a special purpose library such as
15806  libffi (<A href="http://sources.redhat.com/libffi/">
15807 http://sources.redhat.com/libffi</A>). libffi is a library that allows
15808  you to dynamically construct call-stacks and invoke procedures in a
15809  relatively platform independent manner. Details about the library can
15810  be found in the libffi distribution and are not repeated here.</P>
15811 <P> To illustrate the use of libffi, suppose that you<EM> really</EM>
15812  wanted to create a wrapper for <TT>execlp()</TT> that accepted<EM> any</EM>
15813  number of arguments. To do this, you might make a few adjustments to
15814  the previous example. For example:</P>
15815 <DIV class="code">
15816 <PRE>
15817 /* Take an arbitrary number of extra arguments and place into an array
15818    of strings */
15819
15820 %typemap(in) (...) {
15821    char **argv;
15822    int    argc;
15823    int    i;
15824
15825    argc = PyTuple_Size(varargs);
15826    argv = (char **) malloc(sizeof(char *)*(argc+1));
15827    for (i = 0; i &lt; argc; i++) {
15828       PyObject *o = PyTuple_GetItem(varargs,i);
15829       if (!PyString_Check(o)) {
15830           PyErr_SetString(PyExc_ValueError,&quot;Expected a string&quot;);
15831           free(argv);
15832           return NULL;
15833       }
15834       argv[i] = PyString_AsString(o);
15835    }
15836    argv[i] = NULL;
15837    $1 = (void *) argv;
15838 }
15839
15840 /* Rewrite the function call, using libffi */    
15841
15842 %feature(&quot;action&quot;) execlp {
15843   int       i, vc;
15844   ffi_cif   cif;
15845   ffi_type  **types;
15846   void      **values;
15847   char      **args;
15848
15849   vc = PyTuple_Size(varargs);
15850   types  = (ffi_type **) malloc((vc+3)*sizeof(ffi_type *));
15851   values = (void **) malloc((vc+3)*sizeof(void *));
15852   args   = (char **) arg3;
15853
15854   /* Set up path parameter */
15855   types[0] = &amp;ffi_type_pointer;
15856   values[0] = &amp;arg1;
15857   
15858   /* Set up first argument */
15859   types[1] = &amp;ffi_type_pointer;
15860   values[1] = &amp;arg2;
15861
15862   /* Set up rest of parameters */
15863   for (i = 0; i &lt;= vc; i++) {
15864     types[2+i] = &amp;ffi_type_pointer;
15865     values[2+i] = &amp;args[i];
15866   }
15867   if (ffi_prep_cif(&amp;cif, FFI_DEFAULT_ABI, vc+3,
15868                    &amp;ffi_type_uint, types) == FFI_OK) {
15869     ffi_call(&amp;cif, (void (*)()) execlp, &amp;result, values);
15870   } else {
15871     PyErr_SetString(PyExc_RuntimeError, &quot;Whoa!!!!!&quot;);
15872     free(types);
15873     free(values);
15874     free(arg3);
15875     return NULL;
15876   }
15877   free(types);
15878   free(values);
15879   free(arg3);
15880 }
15881
15882 /* Declare the function. Whew! */
15883 int execlp(const char *path, const char *arg1, ...);
15884 </PRE>
15885 </DIV>
15886 <P> Looking at this example, you may start to wonder if SWIG is making
15887  life any easier. Given the amount of code involved, you might also
15888  wonder why you didn't just write a hand-crafted wrapper! Either that or
15889  you're wondering &quot;why in the hell am I trying to wrap this varargs
15890  function in the first place?!?&quot; Obviously, those are questions you'll
15891  have to answer for yourself.</P>
15892 <P> As a more extreme example of libffi, here is some code that attempts
15893  to wrap <TT>printf()</TT>,</P>
15894 <DIV class="code">
15895 <PRE>
15896 /* A wrapper for printf() using libffi */
15897
15898 %{
15899 /* Structure for holding passed arguments after conversion */
15900   typedef struct {
15901     int type;
15902     union {
15903       int    ivalue;
15904       double dvalue;
15905       void   *pvalue;
15906     } val;
15907   } vtype;
15908   enum { VT_INT, VT_DOUBLE, VT_POINTER };
15909 %}
15910
15911 %typemap(in) (const char *fmt, ...) {
15912   vtype *argv;
15913   int    argc;
15914   int    i;
15915
15916   /* Format string */
15917   $1 = PyString_AsString($input);
15918
15919   /* Variable length arguments */
15920   argc = PyTuple_Size(varargs);
15921   argv = (vtype *) malloc(argc*sizeof(vtype));
15922   for (i = 0; i &lt; argc; i++) {
15923     PyObject *o = PyTuple_GetItem(varargs,i);
15924     if (PyInt_Check(o)) {
15925       argv[i].type = VT_INT;
15926       argv[i].val.ivalue = PyInt_AsLong(o);
15927     } else if (PyFloat_Check(o)) {
15928       argv[i].type = VT_DOUBLE;
15929       argv[i].val.dvalue = PyFloat_AsDouble(o);
15930     } else if (PyString_Check(o)) {
15931       argv[i].type = VT_POINTER;
15932       argv[i].val.pvalue = (void *) PyString_AsString(o);
15933     } else {
15934       PyErr_SetString(PyExc_ValueError,&quot;Unsupported argument type&quot;);
15935       free(argv);
15936       return NULL;
15937     }
15938   }
15939   $2 = (void *) argv;
15940 }
15941
15942 /* Rewrite the function call using libffi */    
15943 %feature(&quot;action&quot;) printf {
15944   int       i, vc;
15945   ffi_cif   cif;
15946   ffi_type  **types;
15947   void      **values;
15948   vtype     *args;
15949
15950   vc = PyTuple_Size(varargs);
15951   types  = (ffi_type **) malloc((vc+1)*sizeof(ffi_type *));
15952   values = (void **) malloc((vc+1)*sizeof(void *));
15953   args   = (vtype *) arg2;
15954
15955   /* Set up fmt parameter */
15956   types[0] = &amp;ffi_type_pointer;
15957   values[0] = &amp;arg1;
15958
15959   /* Set up rest of parameters */
15960   for (i = 0; i &lt; vc; i++) {
15961     switch(args[i].type) {
15962     case VT_INT:
15963       types[1+i] = &amp;ffi_type_uint;
15964       values[1+i] = &amp;args[i].val.ivalue;
15965       break;
15966     case VT_DOUBLE:
15967       types[1+i] = &amp;ffi_type_double;
15968       values[1+i] = &amp;args[i].val.dvalue;
15969       break;
15970     case VT_POINTER:
15971       types[1+i] = &amp;ffi_type_pointer;
15972       values[1+i] = &amp;args[i].val.pvalue;
15973       break;
15974     default:
15975       abort();    /* Whoa! We're seriously hosed */
15976       break;   
15977     }
15978   }
15979   if (ffi_prep_cif(&amp;cif, FFI_DEFAULT_ABI, vc+1,
15980                    &amp;ffi_type_uint, types) == FFI_OK) {
15981     ffi_call(&amp;cif, (void (*)()) printf, &amp;result, values);
15982   } else {
15983     PyErr_SetString(PyExc_RuntimeError, &quot;Whoa!!!!!&quot;);
15984     free(types);
15985     free(values);
15986     free(args);
15987     return NULL;
15988   }
15989   free(types);
15990   free(values);
15991   free(args);
15992 }
15993
15994 /* The function */
15995 int printf(const char *fmt, ...);
15996 </PRE>
15997 </DIV>
15998 <P> Much to your amazement, it even seems to work if you try it:</P>
15999 <DIV class="targetlang">
16000 <PRE>
16001 &gt;&gt;&gt; import example
16002 &gt;&gt;&gt; example.printf(&quot;Grade: %s   %d/60 = %0.2f%%\n&quot;, &quot;Dave&quot;, 47, 47.0*100/60)
16003 Grade: Dave   47/60 = 78.33%
16004 &gt;&gt;&gt;
16005 </PRE>
16006 </DIV>
16007 <P> Of course, there are still some limitations to consider:</P>
16008 <DIV class="targetlang">
16009 <PRE>
16010 &gt;&gt;&gt; example.printf(&quot;la de da de da %s&quot;, 42)
16011 Segmentation fault (core dumped)
16012 </PRE>
16013 </DIV>
16014 <P> And, on this note, we leave further exploration of libffi to the
16015  reader as an exercise. Although Python has been used as an example,
16016  most of the techniques in this section can be extrapolated to other
16017  language modules with a bit of work. The only details you need to know
16018  is how the extra arguments are accessed in each target language. For
16019  example, in the Python module, we used the special <TT>varargs</TT>
16020  variable to get these arguments. Modules such as Tcl8 and Perl5 simply
16021  provide an argument number for the first extra argument. This can be
16022  used to index into an array of passed arguments to get values. Please
16023  consult the chapter on each language module for more details.</P>
16024 <H2><A name="Varargs_nn8"></A>13.7 Wrapping of va_list</H2>
16025 <P> Closely related to variable length argument wrapping, you may
16026  encounter functions that accept a parameter of type <TT>va_list</TT>.
16027  For example:</P>
16028 <DIV class="code">
16029 <PRE>
16030 int vfprintf(FILE *f, const char *fmt, va_list ap);
16031 </PRE>
16032 </DIV>
16033 <P> As far as we know, there is no obvious way to wrap these functions
16034  with SWIG. This is because there is no documented way to assemble the
16035  proper va_list structure (there are no C library functions to do it and
16036  the contents of va_list are opaque). Not only that, the contents of a <TT>
16037 va_list</TT> structure are closely tied to the underlying call-stack.
16038  It's not clear that exporting a <TT>va_list</TT> would have any use or
16039  that it would work at all.</P>
16040 <H2><A name="Varargs_nn9"></A>13.8 C++ Issues</H2>
16041 <P> Wrapping of C++ member functions that accept a variable number of
16042  arguments presents a number of challenges. By far, the easiest way to
16043  handle this is to use the <TT>%varargs</TT> directive. This is portable
16044  and it fully supports classes much like the <TT>%rename</TT> directive.
16045  For example:</P>
16046 <DIV class="code">
16047 <PRE>
16048 %varargs (10, char * = NULL) Foo::bar;
16049
16050 class Foo {
16051 public:
16052      virtual void bar(char *arg, ...);   // gets varargs above
16053 };
16054
16055 class Spam: public Foo {
16056 public:
16057      virtual void bar(char *arg, ...);   // gets varargs above
16058 };
16059 </PRE>
16060 </DIV>
16061 <P> <TT>%varargs</TT> also works with constructors, operators, and any
16062  other C++ programming construct that accepts variable arguments.</P>
16063 <P> Doing anything more advanced than this is likely to involve a
16064  serious world of pain. In order to use a library like libffi, you will
16065  need to know the underlying calling conventions and details of the C++
16066  ABI. For instance, the details of how <TT>this</TT> is passed to member
16067  functions as well as any hidden arguments that might be used to pass
16068  additional information. These details are implementation specific and
16069  may differ between compilers and even different versions of the same
16070  compiler. Also, be aware that invoking a member function is further
16071  complicated if it is a virtual method. In this case, invocation might
16072  require a table lookup to obtain the proper function address (although
16073  you might be able to obtain an address by casting a bound pointer to a
16074  pointer to function as described in the C++ ARM section 18.3.4).</P>
16075 <P> If you do decide to change the underlying action code, be aware that
16076  SWIG always places the <TT>this</TT> pointer in <TT>arg1</TT>. Other
16077  arguments are placed in <TT>arg2</TT>, <TT>arg3</TT>, and so forth. For
16078  example:</P>
16079 <DIV class="code">
16080 <PRE>
16081 %feature(&quot;action&quot;) Foo::bar {
16082    ...
16083    result = arg1-&gt;bar(arg2, arg3, etc.);
16084    ...
16085 }
16086 </PRE>
16087 </DIV>
16088 <P> Given the potential to shoot yourself in the foot, it is probably
16089  easier to reconsider your design or to provide an alternative interface
16090  using a helper function than it is to create a fully general wrapper to
16091  a varargs C++ member function.</P>
16092 <H2><A name="Varargs_nn10"></A>13.9 Discussion</H2>
16093 <P> This chapter has provided a number of techniques that can be used to
16094  address the problem of variable length argument wrapping. If you care
16095  about portability and ease of use, the <TT>%varargs</TT> directive is
16096  probably the easiest way to tackle the problem. However, using
16097  typemaps, it is possible to do some very advanced kinds of wrapping.</P>
16098 <P> One point of discussion concerns the structure of the libffi
16099  examples in the previous section. Looking at that code, it is not at
16100  all clear that this is the easiest way to solve the problem. However,
16101  there are a number of subtle aspects of the solution to
16102  consider--mostly concerning the way in which the problem has been
16103  decomposed. First, the example is structured in a way that tries to
16104  maintain separation between wrapper-specific information and the
16105  declaration of the function itself. The idea here is that you might
16106  structure your interface like this:</P>
16107 <DIV class="code">
16108 <PRE>
16109 %typemap(const char *fmt, ...) {
16110    ...
16111 }
16112 %feature(&quot;action&quot;) traceprintf {
16113    ...
16114 }
16115
16116 /* Include some header file with traceprintf in it */
16117 %include &quot;someheader.h&quot;
16118 </PRE>
16119 </DIV>
16120 <P> Second, careful scrutiny will reveal that the typemaps involving <TT>
16121 (...)</TT> have nothing whatsoever to do with the libffi library. In
16122  fact, they are generic with respect to the way in which the function is
16123  actually called. This decoupling means that it will be much easier to
16124  consider other library alternatives for making the function call. For
16125  instance, if libffi wasn't supported on a certain platform, you might
16126  be able to use something else instead. You could use conditional
16127  compilation to control this:</P>
16128 <DIV class="code">
16129 <PRE>
16130 #ifdef USE_LIBFFI
16131 %feature(&quot;action&quot;) printf {
16132    ...
16133 }
16134 #endif
16135 #ifdef USE_OTHERFFI
16136 %feature(&quot;action&quot;) printf {
16137 ...
16138 }
16139 #endif
16140 </PRE>
16141 </DIV>
16142 <P> Finally, even though you might be inclined to just write a
16143  hand-written wrapper for varargs functions, the techniques used in the
16144  previous section have the advantage of being compatible with all other
16145  features of SWIG such as exception handling.</P>
16146 <P> As a final word, some C programmers seem to have the assumption that
16147  the wrapping of variable length argument functions is an easily solved
16148  problem. However, this section has hopefully dispelled some of these
16149  myths. All things being equal, you are better off avoiding variable
16150  length arguments if you can. If you can't avoid them, please consider
16151  some of the simple solutions first. If you can't live with a simple
16152  solution, proceed with caution. At the very least, make sure you
16153  carefully read the section &quot;A7.3.2 Function Calls&quot; in Kernighan and
16154  Ritchie and make sure you fully understand the parameter passing
16155  conventions used for varargs. Also, be aware of the platform
16156  dependencies and reliability issues that this will introduce. Good
16157  luck.</P>
16158 <HR NOSHADE>
16159 <H1><A name="Warnings"></A>14 Warning Messages</H1>
16160
16161 <!-- INDEX -->
16162 <DIV class="sectiontoc">
16163 <UL>
16164 <LI><A href="#Warnings_nn2">Introduction</A></LI>
16165 <LI><A href="#Warnings_suppression">Warning message suppression</A></LI>
16166 <LI><A href="#Warnings_nn4">Enabling extra warnings</A></LI>
16167 <LI><A href="#Warnings_nn5">Issuing a warning message</A></LI>
16168 <LI><A href="#Warnings_symbolic_symbols">Symbolic symbols</A></LI>
16169 <LI><A href="#Warnings_nn6">Commentary</A></LI>
16170 <LI><A href="#Warnings_nn7">Warnings as errors</A></LI>
16171 <LI><A href="#Warnings_nn8">Message output format</A></LI>
16172 <LI><A href="#Warnings_nn9">Warning number reference</A>
16173 <UL>
16174 <LI><A href="#Warnings_nn10">Deprecated features (100-199)</A></LI>
16175 <LI><A href="#Warnings_nn11">Preprocessor (200-299)</A></LI>
16176 <LI><A href="#Warnings_nn12">C/C++ Parser (300-399)</A></LI>
16177 <LI><A href="#Warnings_nn13">Types and typemaps (400-499)</A></LI>
16178 <LI><A href="#Warnings_nn14">Code generation (500-599)</A></LI>
16179 <LI><A href="#Warnings_nn15">Language module specific (800-899)</A></LI>
16180 <LI><A href="#Warnings_nn16">User defined (900-999)</A></LI>
16181 </UL>
16182 </LI>
16183 <LI><A href="#Warnings_nn17">History</A></LI>
16184 </UL>
16185 </DIV>
16186 <!-- INDEX -->
16187 <H2><A name="Warnings_nn2"></A>14.1 Introduction</H2>
16188 <P> During compilation, SWIG may generate a variety of warning messages.
16189  For example:</P>
16190 <DIV class="shell">
16191 <PRE>
16192 example.i:16: Warning(501): Overloaded declaration ignored.  bar(double)
16193 example.i:15: Warning(501): Previous declaration is bar(int)
16194 </PRE>
16195 </DIV>
16196 <P> Typically, warning messages indicate non-fatal problems with the
16197  input where the generated wrapper code will probably compile, but it
16198  may not work like you expect.</P>
16199 <H2><A name="Warnings_suppression"></A>14.2 Warning message suppression</H2>
16200 <P> All warning messages have a numeric code that is shown in the
16201  warning message itself. To suppress the printing of a warning message,
16202  a number of techniques can be used. First, you can run SWIG with the <TT>
16203 -w</TT> command line option. For example:</P>
16204 <DIV class="shell">
16205 <PRE>
16206 % swig -python -w501 example.i
16207 % swig -python -w501,505,401 example.i
16208 </PRE>
16209 </DIV>
16210 <P> Alternatively, warnings can be suppressed by inserting a special
16211  preprocessor pragma into the input file:</P>
16212 <DIV class="code">
16213 <PRE>
16214 %module example
16215 #pragma SWIG nowarn=501
16216 #pragma SWIG nowarn=501,505,401
16217 </PRE>
16218 </DIV>
16219 <P> Finally, code-generation warnings can be disabled on a declaration
16220  by declaration basis using the <TT>%warnfilter</TT> directive. For
16221  example:</P>
16222 <DIV class="code">
16223 <PRE>
16224 %module example
16225 %warnfilter(501) foo;
16226 ...
16227 int foo(int);
16228 int foo(double);              // Silently ignored.
16229 </PRE>
16230 </DIV>
16231 <P> The <TT>%warnfilter</TT> directive has the same semantics as other
16232  declaration modifiers like <TT>%rename</TT>, <TT>%ignore</TT> and <TT>
16233 %feature</TT>, see the <A href="#features">%feature directive</A>
16234  section. For example, if you wanted to suppress a warning for a method
16235  in a class hierarchy, you could do this:</P>
16236 <DIV class="code">
16237 <PRE>
16238 %warnfilter(501) Object::foo;
16239 class Object {
16240 public:
16241    int foo(int);
16242    int foo(double);      // Silently ignored
16243    ...
16244 };
16245
16246 class Derived : public Object {
16247 public:
16248    int foo(int);
16249    int foo(double);      // Silently ignored
16250    ...
16251 };
16252 </PRE>
16253 </DIV>
16254 <P> Warnings can be suppressed for an entire class by supplying a class
16255  name. For example:</P>
16256 <DIV class="code">
16257 <PRE>
16258 %warnfilter(501) Object;
16259
16260 class Object {
16261 public:
16262    ...                      // All 501 warnings ignored in class
16263 };
16264 </PRE>
16265 </DIV>
16266 <P> There is no option to suppress all SWIG warning messages. The
16267  warning messages are there for a reason---to tell you that something
16268  may be<EM> broken</EM> in your interface. Ignore the warning messages
16269  at your own peril.</P>
16270 <H2><A name="Warnings_nn4"></A>14.3 Enabling extra warnings</H2>
16271 <P> Some warning messages are disabled by default and are generated only
16272  to provide additional diagnostics. These warnings can be turned on
16273  using the <TT>-Wextra</TT> option. For example:</P>
16274 <DIV class="shell">
16275 <PRE>
16276 % swig -Wextra -python example.i
16277 </PRE>
16278 </DIV>
16279 <P> To selectively turn on extra warning messages, you can use the
16280  directives and options in the previous section--simply add a &quot;+&quot; to all
16281  warning numbers. For example:</P>
16282 <DIV class="shell">
16283 <PRE>
16284 % swig -w+309,+452 example.i
16285 </PRE>
16286 </DIV>
16287 <P> or in your interface file use either</P>
16288 <DIV class="code">
16289 <PRE>
16290 #pragma SWIG nowarn=+309,+452
16291 </PRE>
16292 </DIV>
16293 <P> or</P>
16294 <DIV class="code">
16295 <PRE>
16296 %warnfilter(+309,+452) foo;
16297 </PRE>
16298 </DIV>
16299 <P> Note: selective enabling of warnings with <TT>%warnfilter</TT>
16300  overrides any global settings you might have made using <TT>-w</TT> or <TT>
16301 #pragma</TT>.</P>
16302 <P> You can of course also enable all warnings and suppress a select
16303  few, for example:</P>
16304 <DIV class="shell">
16305 <PRE>
16306 % swig -Wextra -w309,452 example.i
16307 </PRE>
16308 </DIV>
16309 <P> The warnings on the right take precedence over the warnings on the
16310  left, so in the above example <TT>-Wextra</TT> adds numerous warnings
16311  including 452, but then <TT>-w309,452</TT> overrides this and so 452 is
16312  suppressesed.</P>
16313 <P> If you would like all warnings to appear, regardless of the warning
16314  filters used, then use the <TT>-Wall</TT> option. The <TT>-Wall</TT>
16315  option also turns on the extra warnings that <TT>-Wextra</TT> adds,
16316  however, it is subtely different. When <TT>-Wall</TT> is used, it also
16317  disables all other warning filters, that is, any warnings suppressed or
16318  added in <TT>%warnfilter</TT>, <TT>#pragma SWIG nowarn</TT> or the <TT>
16319 -w</TT> option.</P>
16320 <H2><A name="Warnings_nn5"></A>14.4 Issuing a warning message</H2>
16321 <P> Warning messages can be issued from an interface file using a number
16322  of directives. The <TT>%warn</TT> directive is the most simple:</P>
16323 <DIV class="code">
16324 <PRE>
16325 %warn &quot;900:This is your last warning!&quot;
16326 </PRE>
16327 </DIV>
16328 <P> All warning messages are optionally prefixed by the warning number
16329  to use. If you are generating your own warnings, make sure you don't
16330  use numbers defined in the table at the end of this section.</P>
16331 <P> The <TT>%ignorewarn</TT> directive is the same as <TT>%ignore</TT>
16332  except that it issues a warning message whenever a matching declaration
16333  is found. For example:</P>
16334 <DIV class="code">
16335 <PRE>
16336 %ignorewarn(&quot;362:operator= ignored&quot;) operator=;
16337 </PRE>
16338 </DIV>
16339 <P> Warning messages can be associated with typemaps using the <TT>
16340 warning</TT> attribute of a typemap declaration. For example:</P>
16341 <DIV class="code">
16342 <PRE>
16343 %typemap(in, warning=&quot;901:You are really going to regret this&quot;) blah * {
16344    ...
16345 }
16346 </PRE>
16347 </DIV>
16348 <P> In this case, the warning message will be printed whenever the
16349  typemap is actually used.</P>
16350 <H2><A name="Warnings_symbolic_symbols"></A>14.5 Symbolic symbols</H2>
16351 <P> The <TT>swigwarn.swg</TT> file that is installed with SWIG contains
16352  symbol constants that could also be used in <TT>%warnfilter</TT> and <TT>
16353 #pragma SWIG nowarn</TT>. For example this file contains the following
16354  line:</P>
16355 <DIV class="code">
16356 <PRE>
16357 %define SWIGWARN_TYPE_UNDEFINED_CLASS 401 %enddef
16358 </PRE>
16359 </DIV>
16360 <P> so <TT>SWIGWARN_TYPE_UNDEFINED_CLASS</TT> could be used instead of
16361  401, for example:</P>
16362 <DIV class="code">
16363 <PRE>
16364 #pragma SWIG nowarn=SWIGWARN_TYPE_UNDEFINED_CLASS
16365 </PRE>
16366 </DIV>
16367 <P> or</P>
16368 <DIV class="code">
16369 <PRE>
16370 %warnfilter(SWIGWARN_TYPE_UNDEFINED_CLASS) Foo;
16371 </PRE>
16372 </DIV>
16373 <H2><A name="Warnings_nn6"></A>14.6 Commentary</H2>
16374 <P> The ability to suppress warning messages is really only provided for
16375  advanced users and is not recommended in normal use. You are advised to
16376  modify your interface to fix the problems highlighted by the warnings
16377  wherever possible instead of suppressing warnings.</P>
16378 <P> Certain types of SWIG problems are errors. These usually arise due
16379  to parsing errors (bad syntax) or semantic problems for which there is
16380  no obvious recovery. There is no mechanism for suppressing error
16381  messages.</P>
16382 <H2><A name="Warnings_nn7"></A>14.7 Warnings as errors</H2>
16383 <P> Warnings can be handled as errors by using the <TT>-Werror</TT>
16384  command line option. This will cause SWIG to exit with a non successful
16385  exit code if a warning is encountered.</P>
16386 <H2><A name="Warnings_nn8"></A>14.8 Message output format</H2>
16387 <P> The output format for both warnings and errors can be selected for
16388  integration with your favourite IDE/editor. Editors and IDEs can
16389  usually parse error messages and if in the appropriate format will
16390  easily take you directly to the source of the error. The standard
16391  format is used by default except on Windows where the Microsoft format
16392  is used by default. These can be overridden using command line options,
16393  for example:</P>
16394 <DIV class="shell">
16395 <PRE>
16396 $ swig -python -Fstandard example.i
16397 example.i:4: Syntax error in input.
16398 $ swig -python -Fmicrosoft example.i
16399 example.i(4): Syntax error in input.
16400 </PRE>
16401 </DIV>
16402 <H2><A name="Warnings_nn9"></A>14.9 Warning number reference</H2>
16403 <H3><A name="Warnings_nn10"></A>14.9.1 Deprecated features (100-199)</H3>
16404 <UL>
16405 <LI>101. Deprecated <TT>%extern</TT> directive.</LI>
16406 <LI>102. Deprecated <TT>%val</TT> directive.</LI>
16407 <LI>103. Deprecated <TT>%out</TT> directive.</LI>
16408 <LI>104. Deprecated <TT>%disabledoc</TT> directive.</LI>
16409 <LI>105. Deprecated <TT>%enabledoc</TT> directive.</LI>
16410 <LI>106. Deprecated <TT>%doconly</TT> directive.</LI>
16411 <LI>107. Deprecated <TT>%style</TT> directive.</LI>
16412 <LI>108. Deprecated <TT>%localstyle</TT> directive.</LI>
16413 <LI>109. Deprecated <TT>%title</TT> directive.</LI>
16414 <LI>110. Deprecated <TT>%section</TT> directive.</LI>
16415 <LI>111. Deprecated <TT>%subsection</TT> directive.</LI>
16416 <LI>112. Deprecated <TT>%subsubsection</TT> directive.</LI>
16417 <LI>113. Deprecated <TT>%addmethods</TT> directive.</LI>
16418 <LI>114. Deprecated <TT>%readonly</TT> directive.</LI>
16419 <LI>115. Deprecated <TT>%readwrite</TT> directive.</LI>
16420 <LI>116. Deprecated <TT>%except</TT> directive.</LI>
16421 <LI>117. Deprecated <TT>%new</TT> directive.</LI>
16422 <LI>118. Deprecated <TT>%typemap(except)</TT>.</LI>
16423 <LI>119. Deprecated <TT>%typemap(ignore)</TT>.</LI>
16424 <LI>120. Deprecated command line option (-runtime, -noruntime).</LI>
16425 <LI>121. Deprecated <TT>%name</TT> directive.</LI>
16426 </UL>
16427 <H3><A name="Warnings_nn11"></A>14.9.2 Preprocessor (200-299)</H3>
16428 <UL>
16429 <LI>201. Unable to find 'filename'.</LI>
16430 <LI>202. Could not evaluate 'expr'.</LI>
16431 </UL>
16432 <H3><A name="Warnings_nn12"></A>14.9.3 C/C++ Parser (300-399)</H3>
16433 <UL>
16434 <LI>301. <TT>class</TT> keyword used, but not in C++ mode.</LI>
16435 <LI>302. Identifier '<EM>name</EM>' redefined (ignored).</LI>
16436 <LI>303. <TT>%extend</TT> defined for an undeclared class '<EM>name</EM>
16437 '.</LI>
16438 <LI>304. Unsupported constant value (ignored).</LI>
16439 <LI>305. Bad constant value (ignored).</LI>
16440 <LI>306. '<EM>identifier</EM>' is private in this context.</LI>
16441 <LI>307. Can't set default argument value (ignored)</LI>
16442 <LI>308. Namespace alias '<EM>name</EM>' not allowed here. Assuming '<EM>
16443 name</EM>'</LI>
16444 <LI>309. [private | protected] inheritance ignored.</LI>
16445 <LI>310. Template '<EM>name</EM>' was already wrapped as '<EM>name</EM>'
16446  (ignored)</LI>
16447 <LI>311. Template partial specialization not supported.</LI>
16448 <LI>312. Nested classes not currently supported (ignored).</LI>
16449 <LI>313. Unrecognized extern type &quot;<EM>name</EM>&quot; (ignored).</LI>
16450 <LI>314. '<EM>identifier</EM>' is a<EM> lang</EM> keyword.</LI>
16451 <LI>315. Nothing known about '<EM>identifier</EM>'.</LI>
16452 <LI>316. Repeated %module directive.</LI>
16453 <LI>317. Specialization of non-template '<EM>name</EM>'.</LI>
16454 <LI>318. Instantiation of template<EM> name</EM> is ambiguous. Using<EM>
16455  templ</EM> at<EM> file</EM>:<EM>line</EM></LI>
16456 <LI>319. No access specifier given for base class<EM> name</EM>
16457  (ignored).</LI>
16458 <LI>320. Explicit template instantiation ignored.</LI>
16459 <LI>321.<EM> identifier</EM> conflicts with a built-in name.</LI>
16460 <LI>322. Redundant redeclaration of '<EM>name</EM>'.</LI>
16461 <LI>350. operator new ignored.</LI>
16462 <LI>351. operator delete ignored.</LI>
16463 <LI>352. operator+ ignored.</LI>
16464 <LI>353. operator- ignored.</LI>
16465 <LI>354. operator* ignored.</LI>
16466 <LI>355. operator/ ignored.</LI>
16467 <LI>356. operator% ignored.</LI>
16468 <LI>357. operator^ ignored.</LI>
16469 <LI>358. operator&amp; ignored.</LI>
16470 <LI>359. operator| ignored.</LI>
16471 <LI>360. operator~ ignored.</LI>
16472 <LI>361. operator! ignored.</LI>
16473 <LI>362. operator= ignored.</LI>
16474 <LI>363. operator&lt; ignored.</LI>
16475 <LI>364. operator&gt; ignored.</LI>
16476 <LI>365. operator+= ignored.</LI>
16477 <LI>366. operator-= ignored.</LI>
16478 <LI>367. operator*= ignored.</LI>
16479 <LI>368. operator/= ignored.</LI>
16480 <LI>369. operator%= ignored.</LI>
16481 <LI>370. operator^= ignored.</LI>
16482 <LI>371. operator&amp;= ignored.</LI>
16483 <LI>372. operator|= ignored.</LI>
16484 <LI>373. operator&lt;&lt; ignored.</LI>
16485 <LI>374. operator&gt;&gt;ignored.</LI>
16486 <LI>375. operator&lt;&lt;= ignored.</LI>
16487 <LI>376. operator&gt;&gt;= ignored.</LI>
16488 <LI>377. operator== ignored.</LI>
16489 <LI>378. operator!= ignored.</LI>
16490 <LI>379. operator&lt;= ignored.</LI>
16491 <LI>380. operator&gt;= ignored.</LI>
16492 <LI>381. operator&amp;&amp; ignored.</LI>
16493 <LI>382. operator|| ignored.</LI>
16494 <LI>383. operator++ ignored.</LI>
16495 <LI>384. operator-- ignored.</LI>
16496 <LI>385. operator, ignored.</LI>
16497 <LI>386. operator-&lt;* ignored.</LI>
16498 <LI>387. operator-&lt; ignored.</LI>
16499 <LI>388. operator() ignored.</LI>
16500 <LI>389. operator[] ignored.</LI>
16501 <LI>390. operator+ ignored (unary).</LI>
16502 <LI>391. operator- ignored (unary).</LI>
16503 <LI>392. operator* ignored (unary).</LI>
16504 <LI>393. operator&amp; ignored (unary).</LI>
16505 <LI>394. operator new[] ignored.</LI>
16506 <LI>395. operator delete[] ignored.</LI>
16507 </UL>
16508 <H3><A name="Warnings_nn13"></A>14.9.4 Types and typemaps (400-499)</H3>
16509 <UL>
16510 <LI>401. Nothing known about class 'name'. Ignored.</LI>
16511 <LI>402. Base class 'name' is incomplete.</LI>
16512 <LI>403. Class 'name' might be abstract.</LI>
16513 <LI>450. Deprecated typemap feature ($source/$target).</LI>
16514 <LI>451. Setting const char * variable may leak memory.</LI>
16515 <LI>452. Reserved</LI>
16516 <LI>453. Can't apply (pattern). No typemaps are defined.</LI>
16517 <LI>460. Unable to use type<EM> type</EM> as a function argument.</LI>
16518 <LI>461. Unable to use return type<EM> type</EM> in function<EM> name</EM>
16519 .</LI>
16520 <LI>462. Unable to set variable of type<EM> type</EM>.</LI>
16521 <LI>463. Unable to read variable of type<EM> type</EM>.</LI>
16522 <LI>464. Unsupported constant value.</LI>
16523 <LI>465. Unable to handle type<EM> type</EM>.</LI>
16524 <LI>466. Unsupported variable type<EM> type</EM>.</LI>
16525 <LI>467. Overloaded<EM> declaration</EM> not supported (no type checking
16526  rule for '<EM>type</EM>')</LI>
16527 <LI>468. No 'throw' typemap defined for exception type<EM> type</EM></LI>
16528 <LI>469. No or improper directorin typemap defined for<EM> type</EM></LI>
16529 <LI>470. Thread/reentrant unsafe wrapping, consider returning by value
16530  instead.</LI>
16531 <LI>471. Unable to use return type<EM> type</EM> in director method</LI>
16532 <LI>474. Method<EM> method</EM> usage of the optimal attribute in the
16533  out typemap at<EM> file</EM>:<EM>line</EM> ignored as the following
16534  cannot be used to generate optimal code:<EM> code</EM></LI>
16535 <LI>475. Multiple calls to<EM> method</EM> might be generated due to
16536  optimal attribute usage in the out typemap at<EM> file</EM>:<EM>line</EM>
16537 .</LI>
16538 </UL>
16539 <H3><A name="Warnings_nn14"></A>14.9.5 Code generation (500-599)</H3>
16540 <UL>
16541 <LI>501. Overloaded declaration ignored.<EM> decl</EM></LI>
16542 <LI>502. Overloaded constructor ignored.<EM> decl</EM></LI>
16543 <LI>503. Can't wrap '<EM>identifier</EM>' unless renamed to a valid
16544  identifier.</LI>
16545 <LI>504. Function<EM> name</EM> must have a return type.</LI>
16546 <LI>505. Variable length arguments discarded.</LI>
16547 <LI>506. Can't wrap varargs with keyword arguments enabled.</LI>
16548 <LI>507. Adding native function<EM> name</EM> not supported (ignored).</LI>
16549 <LI>508. Declaration of '<EM>name</EM>' shadows declaration accessible
16550  via operator-&gt;() at<EM> file:line</EM>.</LI>
16551 <LI>509. Overloaded<EM> declaration</EM> is shadowed by<EM> declaration</EM>
16552  at<EM> file</EM>:<EM>line</EM>.</LI>
16553 <LI>510. Friend function '<EM>name</EM>' ignored.</LI>
16554 <LI>511. Can't use keyword arguments with overloaded functions.</LI>
16555 <LI>512. Overloaded<EM> declaration</EM> const ignored. Non-const method
16556  at<EM> file</EM>:<EM>line</EM> used.</LI>
16557 <LI>513. Can't generate wrappers for unnamed struct/class.</LI>
16558 <LI>514.</LI>
16559 <LI>515.</LI>
16560 <LI>516. Overloaded method<EM> declaration</EM> ignored. Method<EM>
16561  declaration</EM> at<EM> file</EM>:<EM>line</EM> used.</LI>
16562 <LI>517.</LI>
16563 <LI>518. Portability warning: File<EM> file1</EM> will be overwritten by<EM>
16564  file2</EM> on case insensitive filesystems such as Windows' FAT32 and
16565  NTFS unless the class/module name is renamed.</LI>
16566 <LI>519. %template() contains no name. Template method ignored:<EM>
16567  declaration</EM></LI>
16568 </UL>
16569 <H3><A name="Warnings_nn15"></A>14.9.6 Language module specific
16570  (800-899)</H3>
16571 <UL>
16572 <LI>801. Wrong name (corrected to '<EM>name</EM>'). (Ruby).</LI>
16573 </UL>
16574 <UL>
16575 <LI>810. No jni typemap defined for<EM> type</EM> (Java).</LI>
16576 <LI>811. No jtype typemap defined for<EM> type</EM> (Java).</LI>
16577 <LI>812. No jstype typemap defined for<EM> type</EM> (Java).</LI>
16578 <LI>813. Warning for<EM> classname</EM>: Base<EM> baseclass</EM>
16579  ignored. Multiple inheritance is not supported in Java. (Java).</LI>
16580 <LI>814.</LI>
16581 <LI>815. No javafinalize typemap defined for<EM> type</EM> (Java).</LI>
16582 <LI>816. No javabody typemap defined for<EM> type</EM> (Java).</LI>
16583 <LI>817. No javaout typemap defined for<EM> type</EM> (Java).</LI>
16584 <LI>818. No javain typemap defined for<EM> type</EM> (Java).</LI>
16585 <LI>819. No javadirectorin typemap defined for<EM> type</EM> (Java).</LI>
16586 <LI>820. No javadirectorout typemap defined for<EM> type</EM> (Java).</LI>
16587 <LI>821.</LI>
16588 <LI>822. Covariant return types not supported in Java. Proxy method will
16589  return<EM> basetype</EM> (Java).</LI>
16590 <LI>823. No javaconstruct typemap defined for<EM> type</EM> (Java).</LI>
16591 <LI>824. Missing JNI descriptor in directorin typemap defined for<EM>
16592  type</EM> (Java).</LI>
16593 </UL>
16594 <UL>
16595 <LI>830. No ctype typemap defined for<EM> type</EM> (C#).</LI>
16596 <LI>831. No cstype typemap defined for<EM> type</EM> (C#).</LI>
16597 <LI>832. No cswtype typemap defined for<EM> type</EM> (C#).</LI>
16598 <LI>833. Warning for<EM> classname</EM>: Base<EM> baseclass</EM>
16599  ignored. Multiple inheritance is not supported in C#. (C#).</LI>
16600 <LI>834.</LI>
16601 <LI>835. No csfinalize typemap defined for<EM> type</EM> (C#).</LI>
16602 <LI>836. No csbody typemap defined for<EM> type</EM> (C#).</LI>
16603 <LI>837. No csout typemap defined for<EM> type</EM> (C#).</LI>
16604 <LI>838. No csin typemap defined for<EM> type</EM> (C#).</LI>
16605 <LI>839.</LI>
16606 <LI>840.</LI>
16607 <LI>841.</LI>
16608 <LI>842. Covariant return types not supported in C#. Proxy method will
16609  return<EM> basetype</EM> (C#).</LI>
16610 <LI>843. No csconstruct typemap defined for<EM> type</EM> (C#).</LI>
16611 <LI>844. C# exception may not be thrown - no $excode or excode attribute
16612  in<EM> typemap</EM> typemap. (C#).</LI>
16613 <LI>845. Unmanaged code contains a call to a
16614  SWIG_CSharpSetPendingException method and C# code does not handle
16615  pending exceptions via the canthrow attribute. (C#).</LI>
16616 </UL>
16617 <UL>
16618 <LI>870. Warning for<EM> classname</EM>: Base<EM> baseclass</EM>
16619  ignored. Multiple inheritance is not supported in PHP.</LI>
16620 <LI>871. Unrecognized pragma<EM> pragma</EM>. (Php).</LI>
16621 </UL>
16622 <H3><A name="Warnings_nn16"></A>14.9.7 User defined (900-999)</H3>
16623 <P> These numbers can be used by your own application.</P>
16624 <H2><A name="Warnings_nn17"></A>14.10 History</H2>
16625 <P> The ability to control warning messages was first added to
16626  SWIG-1.3.12.</P>
16627 <HR NOSHADE>
16628 <H1><A name="Modules"></A>15 Working with Modules</H1>
16629
16630 <!-- INDEX -->
16631 <DIV class="sectiontoc">
16632 <UL>
16633 <LI><A href="#Modules_introduction">Modules Introduction</A></LI>
16634 <LI><A href="#Modules_nn1">Basics</A></LI>
16635 <LI><A href="#Modules_nn2">The SWIG runtime code</A></LI>
16636 <LI><A href="#external_run_time">External access to the runtime</A></LI>
16637 <LI><A href="#Modules_nn4">A word of caution about static libraries</A></LI>
16638 <LI><A href="#Modules_nn5">References</A></LI>
16639 <LI><A href="#Modules_nn6">Reducing the wrapper file size</A></LI>
16640 </UL>
16641 </DIV>
16642 <!-- INDEX -->
16643 <H2><A name="Modules_introduction"></A>15.1 Modules Introduction</H2>
16644 <P> Each invocation of SWIG requires a module name to be specified. The
16645  module name is used to name the resulting target language extension
16646  module. Exactly what this means and and what the name is used for
16647  depends on the target language, for example the name can define a
16648  target language namespace or merely be a useful name for naming files
16649  or helper classes. Essentially, a module comprises target language
16650  wrappers for a chosen collection of global variables/functions,
16651  structs/classes and other C/C++ types.</P>
16652 <P> The module name can be supplied in one of two ways. The first is to
16653  specify it with the special <TT>%module</TT> directive. This directive
16654  must appear at the beginning of the interface file. The general form of
16655  this directive is:</P>
16656 <DIV class="code">
16657 <PRE>
16658 <TT>%module(option1=&quot;value1&quot;,option2=&quot;value2&quot;,...) modulename</TT>
16659 </PRE>
16660 </DIV>
16661 <P> where the modulename is mandatory and the options add one or more
16662  optional additional features. Typically no options are specified, for
16663  example:</P>
16664 <DIV class="code">
16665 <PRE>
16666 <TT>%module mymodule</TT>
16667 </PRE>
16668 </DIV>
16669 <P> The second way to specify the module name is with the <TT>-module</TT>
16670  command line option, for example <TT>-module mymodule</TT>. If the
16671  module name is supplied on the command line, it overrides the name
16672  specified by the <TT>%module</TT> directive.</P>
16673 <P> When first working with SWIG, users commonly start by creating a
16674  single module. That is, you might define a single SWIG interface that
16675  wraps some set of C/C++ code. You then compile all of the generated
16676  wrapper code together and use it. For large applications, however, this
16677  approach is problematic---the size of the generated wrapper code can be
16678  rather large. Moreover, it is probably easier to manage the target
16679  language interface when it is broken up into smaller pieces.</P>
16680 <P> This chapter describes the problem of using SWIG in programs where
16681  you want to create a collection of modules. Each module in the
16682  collection is created via separate invocations of SWIG.</P>
16683 <H2><A name="Modules_nn1"></A>15.2 Basics</H2>
16684 <P> The basic usage case with multiple modules is when modules do not
16685  have cross-references (ie. when wrapping multiple independent C APIs).
16686  In that case, swig input files should just work out of the box - you
16687  simply create multiple wrapper .cxx files, link them into your
16688  application, and insert/load each in the scripting language runtime as
16689  you would do for the single module case.</P>
16690 <P> A bit more complex is the case in which modules need to share
16691  information. For example, when one module extends the class of another
16692  by deriving from it:</P>
16693 <DIV class="code">
16694 <PRE>
16695 // File: base.h
16696 class base {
16697 public:
16698   int foo();
16699 };
16700 </PRE>
16701 </DIV> &nbsp;<DIV class="code">
16702 <PRE>
16703 // File: base_module.i
16704 %module base_module
16705
16706 %{
16707 #include &quot;base.h&quot;
16708 %}
16709 %include &quot;base.h&quot;
16710 </PRE>
16711 </DIV> &nbsp;<DIV class="code">
16712 <PRE>
16713 // File: derived_module.i
16714 %module derived_module
16715
16716 %import &quot;base_module.i&quot;
16717
16718 %inline %{
16719 class derived : public base {
16720 public:
16721   int bar();
16722 };
16723 %}
16724 </PRE>
16725 </DIV>
16726 <P>To create the wrapper properly, module <TT>derived_module</TT> needs
16727  to know about the <TT>base</TT> class and that its interface is covered
16728  in another module. The line <TT>%import &quot;base_module.i&quot;</TT> lets SWIG
16729  know exactly that. Oftentimes the <TT>.h</TT> file is passed to <TT>
16730 %import</TT> instead of the <TT>.i</TT>, which unfortunately doesn't
16731  work for all language modules. For example, Python requires the name of
16732  module that the base class exists in so that the proxy classes can
16733  fully inherit the base class's methods. Typically you will get a
16734  warning when the module name is missing, eg:</P>
16735 <DIV class="shell">
16736 <PRE>
16737 derived_module.i:8: Warning(401): Base class 'base' ignored - unknown module name for base. Either import 
16738 the appropriate module interface file or specify the name of the module in the %import directive.
16739 </PRE>
16740 </DIV>
16741 <P> It is sometimes desirable to import the header file rather than the
16742  interface file and overcome the above warning. For example in the case
16743  of the imported interface being quite large, it may be desirable to
16744  simplify matters and just import a small header file of dependent
16745  types. This can be done by specifying the optional <TT>module</TT>
16746  attribute in the <TT>%import</TT> directive. The <TT>derived_module.i</TT>
16747  file shown above could be replaced with the following:<DIV class="code">
16748 <PRE>
16749 // File: derived_module.i
16750 %module derived_module
16751
16752 %import(module=&quot;base_module&quot;) &quot;base.h&quot;
16753
16754 %inline %{
16755 class derived : public base {
16756 public:
16757   int bar();
16758 };
16759 </PRE>
16760 </DIV></P>
16761 <P> Note that &quot;base_module&quot; is the module name and is the same as that
16762  specified in <TT>%module</TT> in <TT>base_module.i</TT> as well as the <TT>
16763 %import</TT> in <TT>derived_module.i</TT>.</P>
16764 <P> Another issue to beware of is that multiple dependent wrappers
16765  should not be linked/loaded in parallel from multiple threads as SWIG
16766  provides no locking - for more on that issue, read on.</P>
16767 <H2><A name="Modules_nn2"></A>15.3 The SWIG runtime code</H2>
16768 <P> Many of SWIG's target languages generate a set of functions commonly
16769  known as the &quot;SWIG runtime.&quot; These functions are primarily related to
16770  the runtime type system which checks pointer types and performs other
16771  tasks such as proper casting of pointer values in C++. As a general
16772  rule, the statically typed target languages, such as Java, use the
16773  language's built in static type checking and have no need for a SWIG
16774  runtime. All the dynamically typed / interpreted languages rely on the
16775  SWIG runtime.</P>
16776 <P> The runtime functions are private to each SWIG-generated module.
16777  That is, the runtime functions are declared with &quot;static&quot; linkage and
16778  are visible only to the wrapper functions defined in that module. The
16779  only problem with this approach is that when more than one SWIG module
16780  is used in the same application, those modules often need to share type
16781  information. This is especially true for C++ programs where SWIG must
16782  collect and share information about inheritance relationships that
16783  cross module boundaries.</P>
16784 <P> To solve the problem of sharing information across modules, a
16785  pointer to the type information is stored in a global variable in the
16786  target language namespace. During module initialization, type
16787  information is loaded into the global data structure of type
16788  information from all modules.</P>
16789 <P> There are a few trade offs with this approach. This type information
16790  is global across all SWIG modules loaded, and can cause type conflicts
16791  between modules that were not designed to work together. To solve this
16792  approach, the SWIG runtime code uses a define SWIG_TYPE_TABLE to
16793  provide a unique type table. This behavior can be enabled when
16794  compiling the generated _wrap.cxx or _wrap.c file by adding
16795  -DSWIG_TYPE_TABLE=myprojectname to the command line argument.</P>
16796 <P> Then, only modules compiled with SWIG_TYPE_TABLE set to
16797  myprojectname will share type information. So if your project has three
16798  modules, all three should be compiled with
16799  -DSWIG_TYPE_TABLE=myprojectname, and then these three modules will
16800  share type information. But any other project's types will not
16801  interfere or clash with the types in your module.</P>
16802 <P> Another issue relating to the global type table is thread safety. If
16803  two modules try and load at the same time, the type information can
16804  become corrupt. SWIG currently does not provide any locking, and if you
16805  use threads, you must make sure that modules are loaded serially. Be
16806  careful if you use threads and the automatic module loading that some
16807  scripting languages provide. One solution is to load all modules before
16808  spawning any threads, or use SWIG_TYPE_TABLE to separate type tables so
16809  they do not clash with each other.</P>
16810 <P> Lastly, SWIG uses a #define SWIG_RUNTIME_VERSION, located in
16811  Lib/swigrun.swg and near the top of every generated module. This number
16812  gets incremented when the data structures change, so that SWIG modules
16813  generated with different versions can peacefully coexist. So the type
16814  structures are separated by the (SWIG_TYPE_TABLE, SWIG_RUNTIME_VERSION)
16815  pair, where by default SWIG_TYPE_TABLE is empty. Only modules compiled
16816  with the same pair will share type information.</P>
16817 <H2><A name="external_run_time"></A>15.4 External access to the runtime</H2>
16818 <P>As described in <A href="#runtime_type_checker">The run-time type
16819  checker</A>, the functions <TT>SWIG_TypeQuery</TT>, <TT>
16820 SWIG_NewPointerObj</TT>, and others sometimes need to be called. Calling
16821  these functions from a typemap is supported, since the typemap code is
16822  embedded into the <TT>_wrap.c</TT> file, which has those declarations
16823  available. If you need to call the SWIG run-time functions from another
16824  C file, there is one header you need to include. To generate the header
16825  that needs to be included, run the following command:<DIV class="shell">
16826 <PRE>
16827 $ swig -python -external-runtime &lt;filename&gt;
16828 </PRE>
16829 </DIV></P>
16830 <P>The filename argument is optional and if it is not passed, then the
16831  default filename will be something like <TT>swigpyrun.h</TT>, depending
16832  on the language. This header file should be treated like any of the
16833  other _wrap.c output files, and should be regenerated when the _wrap
16834  files are. After including this header, your code will be able to call <TT>
16835 SWIG_TypeQuery</TT>, <TT>SWIG_NewPointerObj</TT>, <TT>SWIG_ConvertPtr</TT>
16836  and others. The exact argument parameters for these functions might
16837  differ between language modules; please check the language module
16838  chapters for more information.</P>
16839 <P>Inside this header the functions are declared static and are included
16840  inline into the file, and thus the file does not need to be linked
16841  against any SWIG libraries or code (you might still need to link
16842  against the language libraries like libpython-2.3). Data is shared
16843  between this file and the _wrap.c files through a global variable in
16844  the scripting language. It is also possible to copy this header file
16845  along with the generated wrapper files into your own package, so that
16846  you can distribute a package that can be compiled without SWIG
16847  installed (this works because the header file is self-contained, and
16848  does not need to link with anything).</P>
16849 <P> This header will also use the -DSWIG_TYPE_TABLE described above, so
16850  when compiling any code which includes the generated header file should
16851  define the SWIG_TYPE_TABLE to be the same as the module whose types you
16852  are trying to access.</P>
16853 <H2><A name="Modules_nn4"></A>15.5 A word of caution about static
16854  libraries</H2>
16855 <P> When working with multiple SWIG modules, you should take care not to
16856  use static libraries. For example, if you have a static library <TT>
16857 libfoo.a</TT> and you link a collection of SWIG modules with that
16858  library, each module will get its own private copy of the library code
16859  inserted into it. This is very often<B> NOT</B> what you want and it
16860  can lead to unexpected or bizarre program behavior. When working with
16861  dynamically loadable modules, you should try to work exclusively with
16862  shared libraries.</P>
16863 <H2><A name="Modules_nn5"></A>15.6 References</H2>
16864 <P> Due to the complexity of working with shared libraries and multiple
16865  modules, it might be a good idea to consult an outside reference. John
16866  Levine's &quot;Linkers and Loaders&quot; is highly recommended.</P>
16867 <H2><A name="Modules_nn6"></A>15.7 Reducing the wrapper file size</H2>
16868 <P> Using multiple modules with the <TT>%import</TT> directive is the
16869  most common approach to modularising large projects. In this way a
16870  number of different wrapper files can be generated, thereby avoiding
16871  the generation of a single large wrapper file. There are a couple of
16872  alternative solutions for reducing the size of a wrapper file through
16873  the use of command line options and features.</P>
16874 <P><B> -fcompact</B>
16875 <BR> This command line option will compact the size of the wrapper file
16876  without changing the code generated into the wrapper file. It simply
16877  removes blank lines and joins lines of code together. This is useful
16878  for compilers that have a maximum file size that can be handled.</P>
16879 <P><B> -fvirtual</B>
16880 <BR> This command line option will remove the generation of superfluous
16881  virtual method wrappers. Consider the following inheritance hierarchy:</P>
16882 <DIV class="code">
16883 <PRE>
16884 struct Base {
16885   virtual void method();
16886   ...
16887 };
16888
16889 struct Derived : Base {
16890   virtual void method();
16891   ...
16892 };
16893 </PRE>
16894 </DIV>
16895 <P> Normally wrappers are generated for both methods, whereas this
16896  command line option will suppress the generation of a wrapper for <TT>
16897 Derived::method</TT>. Normal polymorphic behaviour remains as <TT>
16898 Derived::method</TT> will still be called should you have a <TT>Derived</TT>
16899  instance and call the wrapper for <TT>Base::method</TT>.</P>
16900 <P><B> %feature(&quot;compactdefaultargs&quot;)</B>
16901 <BR> This feature can reduce the number of wrapper methods when wrapping
16902  methods with default arguments. The section on <A href="#SWIGPlus_default_args">
16903 default arguments</A> discusses the feature and its limitations.</P>
16904 <HR NOSHADE>
16905 <H1><A name="CCache"></A>16 Using SWIG with ccache - ccache-swig(1)
16906  manpage</H1>
16907
16908 <!-- INDEX -->
16909 <DIV class="sectiontoc">
16910 <UL>
16911 <LI><A href="#CCache_nn2">NAME</A></LI>
16912 <LI><A href="#CCache_nn3">SYNOPSIS</A></LI>
16913 <LI><A href="#CCache_nn4">DESCRIPTION</A></LI>
16914 <LI><A href="#CCache_nn5">OPTIONS SUMMARY</A></LI>
16915 <LI><A href="#CCache_nn6">OPTIONS</A></LI>
16916 <LI><A href="#CCache_nn7">INSTALLATION</A></LI>
16917 <LI><A href="#CCache_nn8">EXTRA OPTIONS</A></LI>
16918 <LI><A href="#CCache_nn9">ENVIRONMENT VARIABLES</A></LI>
16919 <LI><A href="#CCache_nn10">CACHE SIZE MANAGEMENT</A></LI>
16920 <LI><A href="#CCache_nn11">CACHE COMPRESSION</A></LI>
16921 <LI><A href="#CCache_nn12">HOW IT WORKS</A></LI>
16922 <LI><A href="#CCache_nn13">USING CCACHE WITH DISTCC</A></LI>
16923 <LI><A href="#CCache_nn14">SHARING A CACHE</A></LI>
16924 <LI><A href="#CCache_nn15">HISTORY</A></LI>
16925 <LI><A href="#CCache_nn16">DIFFERENCES FROM COMPILERCACHE</A></LI>
16926 <LI><A href="#CCache_nn17">CREDITS</A></LI>
16927 <LI><A href="#CCache_nn18">AUTHOR</A></LI>
16928 </UL>
16929 </DIV>
16930 <!-- INDEX -->
16931 <P></P>
16932 <H2><A name="CCache_nn2"></A>16.1 NAME</H2>
16933 <P> ccache-swig - a fast compiler cache</P>
16934 <P></P>
16935 <H2><A name="CCache_nn3"></A>16.2 SYNOPSIS</H2>
16936 <P> ccache-swig [OPTION]</P>
16937 <P> ccache-swig &lt;compiler&gt; [COMPILER OPTIONS]</P>
16938 <P> &lt;compiler&gt; [COMPILER OPTIONS]</P>
16939 <P></P>
16940 <H2><A name="CCache_nn4"></A>16.3 DESCRIPTION</H2>
16941 <P> ccache-swig is a compiler cache. It speeds up re-compilation of
16942  C/C++/SWIG code by caching previous compiles and detecting when the
16943  same compile is being done again. ccache-swig is ccache plus support
16944  for SWIG. ccache and ccache-swig are used interchangeably in this
16945  document.</P>
16946 <P></P>
16947 <H2><A name="CCache_nn5"></A>16.4 OPTIONS SUMMARY</H2>
16948 <P> Here is a summary of the options to ccache-swig.</P>
16949 <P></P>
16950 <PRE>
16951
16952 -s                      show statistics summary
16953 -z                      zero statistics
16954 -c                      run a cache cleanup
16955 -C                      clear the cache completely
16956 -F &lt;n&gt;                  set maximum files in cache
16957 -M &lt;n&gt;                  set maximum size of cache (use G, M or K)
16958 -h                      this help page
16959 -V                      print version number
16960
16961 </PRE>
16962 <P></P>
16963 <H2><A name="CCache_nn6"></A>16.5 OPTIONS</H2>
16964 <P> These options only apply when you invoke ccache as &quot;ccache-swig&quot;.
16965  When invoked as a compiler none of these options apply. In that case
16966  your normal compiler options apply and you should refer to your
16967  compilers documentation.</P>
16968 <P></P>
16969 <DL>
16970 <P>
16971 <DT><STRONG><STRONG>-h</STRONG></STRONG></DT>
16972 <DD> Print a options summary page
16973 <P></P>
16974 <P></P>
16975 </DD>
16976 <DT><STRONG><STRONG>-s</STRONG></STRONG></DT>
16977 <DD> Print the current statistics summary for the cache. The statistics
16978  are stored spread across the subdirectories of the cache. Using
16979  &quot;ccache-swig -s&quot; adds up the statistics across all subdirectories and
16980  prints the totals.
16981 <P></P>
16982 <P></P>
16983 </DD>
16984 <DT><STRONG><STRONG>-z</STRONG></STRONG></DT>
16985 <DD> Zero the cache statistics.
16986 <P></P>
16987 <P></P>
16988 </DD>
16989 <DT><STRONG><STRONG>-V</STRONG></STRONG></DT>
16990 <DD> Print the ccache version number
16991 <P></P>
16992 <P></P>
16993 </DD>
16994 <DT><STRONG><STRONG>-c</STRONG></STRONG></DT>
16995 <DD> Clean the cache and re-calculate the cache file count and size
16996  totals. Normally the -c option should not be necessary as ccache keeps
16997  the cache below the specified limits at runtime and keeps statistics up
16998  to date on each compile. This option is mostly useful if you manually
16999  modify the cache contents or believe that the cache size statistics may
17000  be inaccurate.
17001 <P></P>
17002 <P></P>
17003 </DD>
17004 <DT><STRONG><STRONG>-C</STRONG></STRONG></DT>
17005 <DD> Clear the entire cache, removing all cached files.
17006 <P></P>
17007 <P></P>
17008 </DD>
17009 <DT><STRONG><STRONG>-F &lt;maxfiles&gt;</STRONG></STRONG></DT>
17010 <DD> This sets the maximum number of files allowed in the cache. The
17011  value is stored inside the cache directory and applies to all future
17012  compiles. Due to the way the value is stored the actual value used is
17013  always rounded down to the nearest multiple of 16.
17014 <P></P>
17015 <P></P>
17016 </DD>
17017 <DT><STRONG><STRONG>-M &lt;maxsize&gt;</STRONG></STRONG></DT>
17018 <DD> This sets the maximum cache size. You can specify a value in
17019  gigabytes, megabytes or kilobytes by appending a G, M or K to the
17020  value. The default is gigabytes. The actual value stored is rounded
17021  down to the nearest multiple of 16 kilobytes.
17022 <P></P>
17023 </DD>
17024 </P>
17025 </DL>
17026 <P></P>
17027 <H2><A name="CCache_nn7"></A>16.6 INSTALLATION</H2>
17028 <P> There are two ways to use ccache. You can either prefix your compile
17029  commands with &quot;ccache-swig&quot; or you can create a symbolic link between
17030  ccache-swig and the names of your compilers. The first method is most
17031  convenient if you just want to try out ccache or wish to use it for
17032  some specific projects. The second method is most useful for when you
17033  wish to use ccache for all your compiles.</P>
17034 <P> To install for usage by the first method just copy ccache-swig to
17035  somewhere in your path.</P>
17036 <P> To install for the second method do something like this:</P>
17037 <PRE>
17038
17039   cp ccache-swig /usr/local/bin/
17040   ln -s /usr/local/bin/ccache-swig /usr/local/bin/gcc
17041   ln -s /usr/local/bin/ccache-swig /usr/local/bin/g++
17042   ln -s /usr/local/bin/ccache-swig /usr/local/bin/cc
17043   ln -s /usr/local/bin/ccache-swig /usr/local/bin/swig
17044
17045 </PRE>
17046  This will work as long as /usr/local/bin comes before the path to gcc
17047  (which is usually in /usr/bin). After installing you may wish to run
17048  &quot;which gcc&quot; to make sure that the correct link is being used.
17049 <P> Note! Do not use a hard link, use a symbolic link. A hardlink will
17050  cause &quot;interesting&quot; problems.</P>
17051 <P></P>
17052 <H2><A name="CCache_nn8"></A>16.7 EXTRA OPTIONS</H2>
17053 <P> When run as a compiler front end ccache usually just takes the same
17054  command line options as the compiler you are using. The only exception
17055  to this is the option '--ccache-skip'. That option can be used to tell
17056  ccache that the next option is definitely not a input filename, and
17057  should be passed along to the compiler as-is.</P>
17058 <P> The reason this can be important is that ccache does need to parse
17059  the command line and determine what is an input filename and what is a
17060  compiler option, as it needs the input filename to determine the name
17061  of the resulting object file (among other things). The heuristic ccache
17062  uses in this parse is that any string on the command line that exists
17063  as a file is treated as an input file name (usually a C file). By using
17064  --ccache-skip you can force an option to not be treated as an input
17065  file name and instead be passed along to the compiler as a command line
17066  option.</P>
17067 <P></P>
17068 <H2><A name="CCache_nn9"></A>16.8 ENVIRONMENT VARIABLES</H2>
17069 <P> ccache uses a number of environment variables to control operation.
17070  In most cases you won't need any of these as the defaults will be fine.</P>
17071 <P></P>
17072 <DL>
17073 <P></P>
17074 <P>
17075 <DT><STRONG><STRONG>CCACHE_DIR</STRONG></STRONG></DT>
17076 <DD> the CCACHE_DIR environment variable specifies where ccache will
17077  keep its cached compiler output. The default is &quot;$HOME/.ccache&quot;.
17078 <P></P>
17079 <P></P>
17080 </DD>
17081 <DT><STRONG><STRONG>CCACHE_TEMPDIR</STRONG></STRONG></DT>
17082 <DD> the CCACHE_TEMPDIR environment variable specifies where ccache will
17083  put temporary files. The default is the same as CCACHE_DIR. Note that
17084  the CCACHE_TEMPDIR path must be on the same filesystem as the
17085  CCACHE_DIR path, so that renames of files between the two directories
17086  can work.
17087 <P></P>
17088 <P></P>
17089 </DD>
17090 <DT><STRONG><STRONG>CCACHE_LOGFILE</STRONG></STRONG></DT>
17091 <DD> If you set the CCACHE_LOGFILE environment variable then ccache will
17092  write some log information on cache hits and misses in that file. This
17093  is useful for tracking down problems.
17094 <P></P>
17095 <P></P>
17096 </DD>
17097 <DT><STRONG><STRONG>CCACHE_VERBOSE</STRONG></STRONG></DT>
17098 <DD> If you set the CCACHE_VERBOSE environment variable then ccache will
17099  display on stdout all the compiler invocations that it makes. This can
17100  useful for debugging unexpected problems.
17101 <P></P>
17102 <P></P>
17103 </DD>
17104 <DT><STRONG><STRONG>CCACHE_PATH</STRONG></STRONG></DT>
17105 <DD> You can optionally set CCACHE_PATH to a colon separated path where
17106  ccache will look for the real compilers. If you don't do this then
17107  ccache will look for the first executable matching the compiler name in
17108  the normal PATH that isn't a symbolic link to ccache itself.
17109 <P></P>
17110 <P></P>
17111 </DD>
17112 <DT><STRONG><STRONG>CCACHE_CC</STRONG></STRONG></DT>
17113 <DD> You can optionally set CCACHE_CC to force the name of the compiler
17114  to use. If you don't do this then ccache works it out from the command
17115  line.
17116 <P></P>
17117 <P></P>
17118 </DD>
17119 <DT><STRONG><STRONG>CCACHE_PREFIX</STRONG></STRONG></DT>
17120 <DD> This option adds a prefix to the command line that ccache runs when
17121  invoking the compiler. Also see the section below on using ccache with
17122  distcc.
17123 <P></P>
17124 <P></P>
17125 </DD>
17126 <DT><STRONG><STRONG>CCACHE_DISABLE</STRONG></STRONG></DT>
17127 <DD> If you set the environment variable CCACHE_DISABLE then ccache will
17128  just call the real compiler, bypassing the cache completely.
17129 <P></P>
17130 <P></P>
17131 </DD>
17132 <DT><STRONG><STRONG>CCACHE_READONLY</STRONG></STRONG></DT>
17133 <DD> the CCACHE_READONLY environment variable tells ccache to attempt to
17134  use existing cached object files, but not to try to add anything new to
17135  the cache. If you are using this because your CCACHE_DIR is read-only,
17136  then you may find that you also need to set CCACHE_TEMPDIR as otherwise
17137  ccache will fail to create the temporary files.
17138 <P></P>
17139 <P></P>
17140 </DD>
17141 <DT><STRONG><STRONG>CCACHE_CPP2</STRONG></STRONG></DT>
17142 <DD> If you set the environment variable CCACHE_CPP2 then ccache will
17143  not use the optimisation of avoiding the 2nd call to the pre-processor
17144  by compiling the pre-processed output that was used for finding the
17145  hash in the case of a cache miss. This is primarily a debugging option,
17146  although it is possible that some unusual compilers will have problems
17147  with the intermediate filename extensions used in this optimisation, in
17148  which case this option could allow ccache to be used.
17149 <P></P>
17150 <P></P>
17151 </DD>
17152 <DT><STRONG><STRONG>CCACHE_NOCOMPRESS</STRONG></STRONG></DT>
17153 <DD> If you set the environment variable CCACHE_NOCOMPRESS then there is
17154  no compression used on files that go into the cache. However, this
17155  setting has no effect on how files are retrieved from the cache,
17156  compressed results will still be usable.
17157 <P></P>
17158 <P></P>
17159 </DD>
17160 <DT><STRONG><STRONG>CCACHE_NOSTATS</STRONG></STRONG></DT>
17161 <DD> If you set the environment variable CCACHE_NOSTATS then ccache will
17162  not update the statistics files on each compile.
17163 <P></P>
17164 <P></P>
17165 </DD>
17166 <DT><STRONG><STRONG>CCACHE_NLEVELS</STRONG></STRONG></DT>
17167 <DD> The environment variable CCACHE_NLEVELS allows you to choose the
17168  number of levels of hash in the cache directory. The default is 2. The
17169  minimum is 1 and the maximum is 8.
17170 <P></P>
17171 <P></P>
17172 </DD>
17173 <DT><STRONG><STRONG>CCACHE_HARDLINK</STRONG></STRONG></DT>
17174 <DD> If you set the environment variable CCACHE_HARDLINK then ccache
17175  will attempt to use hard links from the cache directory when creating
17176  the compiler output rather than using a file copy. Using hard links is
17177  faster, but can confuse programs like 'make' that rely on modification
17178  times. Hard links are never made for compressed cache files.
17179 <P></P>
17180 <P></P>
17181 </DD>
17182 <DT><STRONG><STRONG>CCACHE_RECACHE</STRONG></STRONG></DT>
17183 <DD> This forces ccache to not use any cached results, even if it finds
17184  them. New results are still cached, but existing cache entries are
17185  ignored.
17186 <P></P>
17187 <P></P>
17188 </DD>
17189 <DT><STRONG><STRONG>CCACHE_UMASK</STRONG></STRONG></DT>
17190 <DD> This sets the umask for ccache and all child processes (such as the
17191  compiler). This is mostly useful when you wish to share your cache with
17192  other users. Note that this also affects the file permissions set on
17193  the object files created from your compilations.
17194 <P></P>
17195 <P></P>
17196 </DD>
17197 <DT><STRONG><STRONG>CCACHE_HASHDIR</STRONG></STRONG></DT>
17198 <DD> This tells ccache to hash the current working directory when
17199  calculating the hash that is used to distinguish two compiles. This
17200  prevents a problem with the storage of the current working directory in
17201  the debug info of a object file, which can lead ccache to give a cached
17202  object file that has the working directory in the debug info set
17203  incorrectly. This option is off by default as the incorrect setting of
17204  this debug info rarely causes problems. If you strike problems with gdb
17205  not using the correct directory then enable this option.
17206 <P></P>
17207 <P></P>
17208 </DD>
17209 <DT><STRONG><STRONG>CCACHE_UNIFY</STRONG></STRONG></DT>
17210 <DD> If you set the environment variable CCACHE_UNIFY then ccache will
17211  use the C/C++ unifier when hashing the pre-processor output if -g is
17212  not used in the compile. The unifier is slower than a normal hash, so
17213  setting this environment variable loses a little bit of speed, but it
17214  means that ccache can take advantage of not recompiling when the
17215  changes to the source code consist of reformatting only. Note that
17216  using CCACHE_UNIFY changes the hash, so cached compiles with
17217  CCACHE_UNIFY set cannot be used when CCACHE_UNIFY is not set and vice
17218  versa. The reason the unifier is off by default is that it can give
17219  incorrect line number information in compiler warning messages.
17220 <P></P>
17221 <P></P>
17222 </DD>
17223 <DT><STRONG><STRONG>CCACHE_EXTENSION</STRONG></STRONG></DT>
17224 <DD> Normally ccache tries to automatically determine the extension to
17225  use for intermediate C pre-processor files based on the type of file
17226  being compiled. Unfortunately this sometimes doesn't work, for example
17227  when using the aCC compiler on HP-UX. On systems like this you can use
17228  the CCACHE_EXTENSION option to override the default. On HP-UX set this
17229  environment variable to &quot;i&quot; if you use the aCC compiler.
17230 <P></P>
17231 <P></P>
17232 </DD>
17233 <DT><STRONG><STRONG>CCACHE_STRIPC</STRONG></STRONG></DT>
17234 <DD> If you set the environment variable CCACHE_STRIPC then ccache will
17235  strip the -c option when invoking the preprocessor. This option is
17236  primarily for the Sun Workshop C++ compiler as without this option an
17237  unwarranted warning is displayed: CC: Warning: &quot;-E&quot; redefines product
17238  from &quot;object&quot; to &quot;source (stdout)&quot; when -E and -c is used together.
17239 <P></P>
17240 <P></P>
17241 </DD>
17242 <DT><STRONG><STRONG>CCACHE_SWIG</STRONG></STRONG></DT>
17243 <DD> When using SWIG as the compiler and it does not have 'swig' in the
17244  executable name, then the CCACHE_SWIG environment variable needs to be
17245  set in order for ccache to work correctly with SWIG. The use of
17246  CCACHE_CPP2 is also recommended for SWIG due to some preprocessor
17247  quirks, however, use of CCACHE_CPP2 can often be skipped -- check your
17248  generated code with and without this option set. Known problems are
17249  using preprocessor directives within %inline blocks and the use of
17250  '#pragma SWIG'.
17251 <P></P>
17252 </DD>
17253 </P>
17254 </DL>
17255 <P></P>
17256 <H2><A name="CCache_nn10"></A>16.9 CACHE SIZE MANAGEMENT</H2>
17257 <P> By default ccache has a one gigabyte limit on the cache size and no
17258  maximum number of files. You can set a different limit using the
17259  &quot;ccache -M&quot; and &quot;ccache -F&quot; options, which set the size and number of
17260  files limits.</P>
17261 <P> When these limits are reached ccache will reduce the cache to 20%
17262  below the numbers you specified in order to avoid doing the cache clean
17263  operation too often.</P>
17264 <P></P>
17265 <H2><A name="CCache_nn11"></A>16.10 CACHE COMPRESSION</H2>
17266 <P> By default on most platforms ccache will compress all files it puts
17267  into the cache using the zlib compression. While this involves a
17268  negligible performance slowdown, it significantly increases the number
17269  of files that fit in the cache. You can turn off compression setting
17270  the CCACHE_NOCOMPRESS environment variable.</P>
17271 <P></P>
17272 <H2><A name="CCache_nn12"></A>16.11 HOW IT WORKS</H2>
17273 <P> The basic idea is to detect when you are compiling exactly the same
17274  code a 2nd time and use the previously compiled output. You detect that
17275  it is the same code by forming a hash of:</P>
17276 <P></P>
17277 <UL>
17278 <LI> the pre-processor output from running the compiler with -E</LI>
17279 <LI> the command line options</LI>
17280 <LI> the real compilers size and modification time</LI>
17281 <LI> any stderr output generated by the compiler</LI>
17282 </UL>
17283 <P> These are hashed using md4 (a strong hash) and a cache file is
17284  formed based on that hash result. When the same compilation is done a
17285  second time ccache is able to supply the correct compiler output
17286  (including all warnings etc) from the cache.</P>
17287 <P> ccache has been carefully written to always produce exactly the same
17288  compiler output that you would get without the cache. If you ever
17289  discover a case where ccache changes the output of your compiler then
17290  please let me know.</P>
17291 <P></P>
17292 <H2><A name="CCache_nn13"></A>16.12 USING CCACHE WITH DISTCC</H2>
17293 <P> distcc is a very useful program for distributing compilation across
17294  a range of compiler servers. It is often useful to combine distcc with
17295  ccache, so that compiles that are done are sped up by distcc, but that
17296  ccache avoids the compile completely where possible.</P>
17297 <P> To use distcc with ccache I recommend using the CCACHE_PREFIX
17298  option. You just need to set the environment variable CCACHE_PREFIX to
17299  'distcc' and ccache will prefix the command line used with the compiler
17300  with the command 'distcc'.</P>
17301 <P></P>
17302 <H2><A name="CCache_nn14"></A>16.13 SHARING A CACHE</H2>
17303 <P> A group of developers can increase the cache hit rate by sharing a
17304  cache directory. The hard links however cause unwanted side effects, as
17305  all links to a cached file share the file's modification timestamp.
17306  This results in false dependencies to be triggered by timestamp-based
17307  build systems whenever another user links to an existing file.
17308  Typically, users will see that their libraries and binaries are
17309  relinked without reason. To share a cache without side effects, the
17310  following conditions need to be met:</P>
17311 <P></P>
17312 <UL>
17313 <LI> Use the same<STRONG> CCACHE_DIR</STRONG> environment variable
17314  setting</LI>
17315 <LI> Unset the<STRONG> CCACHE_HARDLINK</STRONG> environment variable</LI>
17316 <LI> Make sure everyone sets the CCACHE_UMASK environment variable to
17317  002, this ensures that cached files are accessible to everyone in the
17318  group.</LI>
17319 <LI> Make sure that all users have write permission in the entire cache
17320  directory (and that you trust all users of the shared cache).</LI>
17321 <LI> Make sure that the setgid bit is set on all directories in the
17322  cache. This tells the filesystem to inherit group ownership for new
17323  directories. The command &quot;chmod g+s `find $CCACHE_DIR -type d`&quot; might
17324  be useful for this.</LI>
17325 <LI> Set<STRONG> CCACHE_NOCOMPRESS</STRONG> for all users, if there are
17326  users with versions of ccache that do not support compression.</LI>
17327 </UL>
17328 <P></P>
17329 <H2><A name="CCache_nn15"></A>16.14 HISTORY</H2>
17330 <P> ccache was inspired by the compilercache shell script script written
17331  by Erik Thiele and I would like to thank him for an excellent piece of
17332  work. See <A href="http://www.erikyyy.de/compilercache/">
17333 http://www.erikyyy.de/compilercache/</A> for the Erik's scripts.
17334  ccache-swig is a port of the original ccache with support added for use
17335  with SWIG.</P>
17336 <P> I wrote ccache because I wanted to get a bit more speed out of a
17337  compiler cache and I wanted to remove some of the limitations of the
17338  shell-script version.</P>
17339 <P></P>
17340 <H2><A name="CCache_nn16"></A>16.15 DIFFERENCES FROM COMPILERCACHE</H2>
17341 <P> The biggest differences between Erik's compilercache script and
17342  ccache are:</P>
17343 <UL>
17344 <LI> ccache is written in C, which makes it a bit faster (calling out to
17345  external programs is mostly what slowed down the scripts).</LI>
17346 <LI> ccache can automatically find the real compiler</LI>
17347 <LI> ccache keeps statistics on hits/misses</LI>
17348 <LI> ccache can do automatic cache management</LI>
17349 <LI> ccache can cache compiler output that includes warnings. In many
17350  cases this gives ccache a much higher cache hit rate.</LI>
17351 <LI> ccache can handle a much wider ranger of compiler options</LI>
17352 <LI> ccache avoids a double call to cpp on a cache miss</LI>
17353 </UL>
17354 <P></P>
17355 <H2><A name="CCache_nn17"></A>16.16 CREDITS</H2>
17356 <P> Thanks to the following people for their contributions to ccache</P>
17357 <UL>
17358 <LI> Erik Thiele for the original compilercache script</LI>
17359 <LI> Luciano Rocha for the idea of compiling the pre-processor output to
17360  avoid a 2nd cpp pass</LI>
17361 <LI> Paul Russell for many suggestions and the debian packaging</LI>
17362 </UL>
17363 <P></P>
17364 <H2><A name="CCache_nn18"></A>16.17 AUTHOR</H2>
17365 <P> ccache was written by Andrew Tridgell <A href="http://samba.org/~tridge/">
17366 http://samba.org/~tridge/</A>. ccache was adapted to create ccache-swig
17367  for use with SWIG by William Fulton.</P>
17368 <P> If you wish to report a problem or make a suggestion then please
17369  email the SWIG developers on the swig-devel mailing list, see <A href="http://www.swig.org/mail.html">
17370 http://www.swig.org/mail.html</A></P>
17371 <P> ccache is released under the GNU General Public License version 2 or
17372  later. Please see the file COPYING for license details.</P>
17373 <P></P>
17374 <HR NOSHADE>
17375
17376 <!-- Hand-written HTML -->
17377 <H1><A name="Allegrocl_nn1"></A>17 SWIG and Allegro Common Lisp</H1>
17378
17379 <!-- INDEX -->
17380 <DIV class="sectiontoc">
17381 <UL>
17382 <LI><A href="#Allegrocl_nn2">Basics</A>
17383 <UL>
17384 <LI><A href="#Allegrocl_nn3">Running Swig</A></LI>
17385 <LI><A href="#Allegrocl_nn4">Command Line Options</A></LI>
17386 <LI><A href="#Allegrocl_nn5">Inserting user code into generated files</A>
17387 </LI>
17388 </UL>
17389 </LI>
17390 <LI><A href="#Allegrocl_nn6">Wrapping Overview</A>
17391 <UL>
17392 <LI><A href="#Allegrocl_nn7">Function Wrapping</A></LI>
17393 <LI><A href="#Allegrocl_nn8">Foreign Wrappers</A></LI>
17394 <LI><A href="#Allegrocl_nn9">FFI Wrappers</A></LI>
17395 <LI><A href="#Allegrocl_nn10">Non-overloaded Defuns</A></LI>
17396 <LI><A href="#Allegrocl_nn11">Overloaded Defuns</A></LI>
17397 <LI><A href="#Allegrocl_nn12">What about constant and variable access?</A>
17398 </LI>
17399 <LI><A href="#Allegrocl_nn13">Object Wrapping</A></LI>
17400 </UL>
17401 </LI>
17402 <LI><A href="#Allegrocl_nn14">Wrapping Details</A>
17403 <UL>
17404 <LI><A href="#Allegrocl_nn15">Namespaces</A></LI>
17405 <LI><A href="#Allegrocl_nn16">Constants</A></LI>
17406 <LI><A href="#Allegrocl_nn17">Variables</A></LI>
17407 <LI><A href="#Allegrocl_nn18">Enumerations</A></LI>
17408 <LI><A href="#Allegrocl_nn19">Arrays</A></LI>
17409 <LI><A href="#Allegrocl_nn20">Classes and Structs and Unions (oh my!)</A>
17410 <UL>
17411 <LI><A href="#Allegrocl_nn21">CLOS wrapping of</A></LI>
17412 <LI><A href="#Allegrocl_nn22">CLOS Inheritance</A></LI>
17413 <LI><A href="#Allegrocl_nn23">Member fields and functions</A></LI>
17414 <LI><A href="#Allegrocl_nn24">Why not directly access C++ classes using
17415  foreign types?</A></LI>
17416 </UL>
17417 </LI>
17418 <LI><A href="#Allegrocl_nn25">Templates</A>
17419 <UL>
17420 <LI><A href="#Allegrocl_nn26">Generating wrapper code for templates</A></LI>
17421 <LI><A href="#Allegrocl_nn27">Implicit Template instantiation</A></LI>
17422 </UL>
17423 </LI>
17424 <LI><A href="#Allegrocl_nn28">Typedef, Templates, and Synonym Types</A>
17425 <UL>
17426 <LI><A href="#Allegrocl_nn29">Choosing a primary type</A></LI>
17427 </UL>
17428 </LI>
17429 <LI><A href="#Allegrocl_nn30">Function overloading/Parameter defaulting</A>
17430 </LI>
17431 <LI><A href="#Allegrocl_nn31">Operator wrapping and Operator overloading</A>
17432 </LI>
17433 <LI><A href="#Allegrocl_nn32">Varargs</A></LI>
17434 <LI><A href="#Allegrocl_nn33">C++ Exceptions</A></LI>
17435 <LI><A href="#Allegrocl_nn34">Pass by value, pass by reference</A></LI>
17436 </UL>
17437 </LI>
17438 <LI><A href="#Allegrocl_nn35">Typemaps</A>
17439 <UL>
17440 <LI><A href="#Allegrocl_nn36">Code Generation in the C++ Wrapper</A>
17441 <UL>
17442 <LI><A href="#Allegrocl_nn37">IN Typemap</A></LI>
17443 <LI><A href="#Allegrocl_nn38">OUT Typemap</A></LI>
17444 <LI><A href="#Allegrocl_nn39">CTYPE Typemap</A></LI>
17445 </UL>
17446 </LI>
17447 <LI><A href="#Allegrocl_nn40">Code generation in Lisp wrappers</A>
17448 <UL>
17449 <LI><A href="#Allegrocl_nn41">LIN Typemap</A></LI>
17450 <LI><A href="#Allegrocl_nn42">LOUT Typemap</A></LI>
17451 <LI><A href="#Allegrocl_nn43">FFITYPE Typemap</A></LI>
17452 <LI><A href="#Allegrocl_nn44">LISPTYPE Typemap</A></LI>
17453 <LI><A href="#Allegrocl_nn45">LISPCLASS Typemap</A></LI>
17454 </UL>
17455 </LI>
17456 <LI><A href="#Allegrocl_nn46">Modifying SWIG behavior using typemaps</A></LI>
17457 </UL>
17458 </LI>
17459 <LI><A href="#Allegrocl_nn47">Identifier Converter functions</A>
17460 <UL>
17461 <LI><A href="#Allegrocl_nn48">Creating symbols in the lisp environment</A>
17462 </LI>
17463 <LI><A href="#Allegrocl_nn49">Existing identifier-converter functions</A>
17464 <UL>
17465 <LI><A href="#Allegrocl_nn50">identifier-convert-null</A></LI>
17466 <LI><A href="#Allegrocl_nn51">identifier-convert-lispify</A></LI>
17467 <LI><A href="#Allegrocl_nn52">Default identifier to symbol conversions</A>
17468 </LI>
17469 </UL>
17470 </LI>
17471 <LI><A href="#Allegrocl_nn53">Defining your own identifier-converter</A></LI>
17472 <LI><A href="#Allegrocl_nn54">Instructing SWIG to use a particular
17473  identifier-converter</A></LI>
17474 </UL>
17475 </LI>
17476 </UL>
17477 </DIV>
17478 <!-- INDEX -->
17479 <P> This chapter describes SWIG's support of Allegro Common Lisp.
17480  Allegro CL is a full-featured implementation of the Common Lisp
17481  language standard that includes many vendor-specific enhancements and
17482  add-on modules for increased usability.</P>
17483 <P> One such module included in Allegro CL is the Foreign Functions
17484  Interface (FFI). This module, tailored primarily toward interfacing
17485  with C/C++ and, historically, Fortran, provides a means by which
17486  compiled foreign code can be loaded into a running lisp environment and
17487  executed. The interface supports the calling of foreign functions and
17488  methods, allows for executing lisp routines from foreign code
17489  (callbacks), and the passing of data between foreign and lisp code.</P>
17490 <P> The goal of this module is to make it possible to quickly generate
17491  the necessary foreign function definitions so one can make use of C/C++
17492  foreign libraries directly from lisp without the tedium of having to
17493  code them by hand. When necessary, it will also generate further C/C++
17494  code that will need to be linked with the intended library for proper
17495  interfacing from lisp. It has been designed with an eye toward
17496  flexibility. Some foreign function calls may release the heap, while
17497  other should not. Some foreign functions should automatically convert
17498  lisp strings into native strings, while others should not. These
17499  adjustments and many more are possible with the current module.</P>
17500 <P> It is significant to note that, while this is a vendor-specific
17501  module, we would like to acknowledge the current and ongoing work by
17502  developers in the open source lisp community that are working on
17503  similar interfaces to implementation-independent foreign function
17504  interfaces (UFFI or CFFI, for example). Such work can only benefit the
17505  lisp community, and we would not be unhappy to see some enterprising
17506  folk use this work to add to it.</P>
17507 <H2><A name="Allegrocl_nn2"></A>17.1 Basics</H2>
17508 <H3><A name="Allegrocl_nn3"></A>17.1.1 Running Swig</H3>
17509 <P> If you're reading this, you must have some library you need to
17510  generate an interface for. In order for SWIG to do this work, however,
17511  it needs a bit of information about how it should go about creating
17512  your interface, and what you are interfacing to.</P>
17513 <P> SWIG expects a description of what in the foreign interface you wish
17514  to connect to. It must consisting of C/C++ declarations and special
17515  SWIG directives. SWIG can be furnished with a header file, but an
17516  interface can also be generated without library headers by supplying a
17517  simple text file--called the interface file, which is typically named
17518  with a <TT>.i</TT> extension--containing any foreign declarations of
17519  identifiers you wish to use. The most common approach is to use a an
17520  interface file with directives to parse the needed headers. A straight
17521  parse of library headers will result in usable code, but SWIG
17522  directives provides much freedom in how a user might tailor the
17523  generated code to their needs or style of coding.</P>
17524 <P> Note that SWIG does not require any function definitions; the
17525  declarations of those functions is all that is necessary. Be careful
17526  when tuning the interface as it is quite possible to generate code that
17527  will not load or compile.</P>
17528 <P> An example interface file is shown below. It makes use of two SWIG
17529  directives, one of which requests that the declarations in a header
17530  file be used to generate part of the interface, and also includes an
17531  additional declaration to be added.</P>
17532 <DIV class="code">example.i
17533 <PRE>
17534 %module example
17535
17536 %include &quot;header.h&quot;
17537
17538 int fact(int n);
17539 </PRE>
17540 </DIV>
17541 <P>The contents of header.h are very simple:</P>
17542 <DIV class="code">header.h
17543 <PRE>
17544 int fact(char *statement);   // pass it a fact, and it will rate it.
17545 </PRE>
17546 </DIV>
17547 <P>The contents of example.cl will look like this:</P>
17548 <DIV class="targetlang">example.cl
17549 <PRE>
17550 (defpackage :example
17551   (:use :common-lisp :swig :ff :excl))
17552
17553   ... helper routines for defining the interface ...
17554
17555 (swig-in-package ())
17556
17557 (swig-defun (&quot;fact&quot;)
17558   ((PARM0_statement cl:string (* :char) ))
17559   (:returning (:int )
17560    :strings-convert t)
17561   (let ((SWIG_arg0 PARM0_statement))
17562   (swig-ff-call SWIG_arg0)))
17563
17564 (swig-defun (&quot;fact&quot;)
17565   ((PARM0_n cl:integer :int ))
17566   (:returning (:int )
17567    :strings-convert t)
17568   (let ((SWIG_arg0 PARM0_n))
17569   (swig-ff-call SWIG_arg0)))
17570
17571 (swig-dispatcher (&quot;fact&quot; :type :function :arities (1)))
17572 </PRE>
17573 </DIV>
17574 <P> The generated file contains calls to internal swig helper functions.
17575  In this case there are two calls to swig-defun. These calls will expand
17576  into code that will make the appropriate definitions using the Allegro
17577  FFI. Note also, that this code is<B> erroneous</B>. Function
17578  overloading is not supported in C, and this code will not compile even
17579  though SWIG did not complain.</P>
17580 <P> In order to generate a C interface to Allegro CL using this code run
17581  swig using the <TT>-allegrocl</TT> option, as below:</P>
17582 <DIV class="shell">
17583 <PRE>
17584 % swig -allegrocl example.i
17585 </PRE>
17586 </DIV>
17587 <P> When building an interface to C++ code, include the <TT>-c++</TT>
17588  option:</P>
17589 <DIV class="shell">
17590 <PRE>
17591 % swig -allegrocl -c++ example.i
17592 </PRE>
17593 </DIV>
17594 <P> As a result of running one of the above commands, a file named <TT>
17595 example.cl</TT> will be generated containing the lisp side of the
17596  interface. As well, a file <TT>example_wrap.cxx</TT> is also generated,
17597  containing C/C++ wrapper code to facilitate access to C++ methods,
17598  enumeration values, and constant values. Wrapper functions are
17599  necessary in C++ due to the lack of a standard for mangling the names
17600  of symbols across all C++ compilers. These wrapper functions are
17601  exported from the shared library as appropriate, using the C name
17602  mangling convention. The lisp code that is generated will interface to
17603  your foreign library through these wrappers.</P>
17604 <P> It is possible to disable the creation of the .cxx file when
17605  generating a C interface by using the -nocwrap command-line argument.
17606  For interfaces that don't contain complex enum or constant expressions,
17607  contain nested struct/union declarations, or doesn't need to use many
17608  of the SWIG customization featuers, this will result in a more
17609  streamlined, direct interface to the intended module.</P>
17610 <P> The generated wrapper file is below. It contains very simple
17611  wrappers by default, that simply pass the arguments to the actual
17612  function.</P>
17613 <DIV class="code">example_wrap.i
17614 <PRE>
17615    ... lots of SWIG internals ...
17616
17617 EXPORT int ACL___fact__SWIG_0 (char *larg1) {
17618     int lresult = (int)0 ;
17619     char *arg1 = (char *) 0 ;
17620     int result;
17621     
17622     arg1 = larg1;
17623     try {
17624         result = (int)fact(arg1);
17625         
17626         lresult = result;
17627         return lresult;
17628     } catch (...) {
17629         return (int)0;
17630     }
17631 }
17632
17633
17634 EXPORT int ACL___fact__SWIG_1 (int larg1) {
17635     int lresult = (int)0 ;
17636     int arg1 ;
17637     int result;
17638     
17639     arg1 = larg1;
17640     try {
17641         result = (int)fact(arg1);
17642         
17643         lresult = result;
17644         return lresult;
17645     } catch (...) {
17646         return (int)0;
17647     }
17648 }
17649 </PRE>
17650 </DIV>
17651 <P> And again, the generated lisp code. Note that it differs from what
17652  is generated when parsing C code:</P>
17653 <DIV class="targetlang">
17654 <PRE>
17655    ...
17656
17657 (swig-in-package ())
17658
17659 (swig-defmethod (&quot;fact&quot; &quot;ACL___fact__SWIG_0&quot; :type :function :arity 1)
17660   ((PARM0_statement cl:string (* :char) ))
17661   (:returning (:int )
17662    :strings-convert t)
17663   (let ((SWIG_arg0 PARM0_statement))
17664   (swig-ff-call SWIG_arg0)))
17665
17666 (swig-defmethod (&quot;fact&quot; &quot;ACL___fact__SWIG_1&quot; :type :function :arity 1)
17667   ((PARM0_n cl:integer :int ))
17668   (:returning (:int )
17669    :strings-convert t)
17670   (let ((SWIG_arg0 PARM0_n))
17671   (swig-ff-call SWIG_arg0)))
17672
17673 (swig-dispatcher (&quot;fact&quot; :type :function :arities (1)))
17674 </PRE>
17675 </DIV>
17676 <P>In this case, the interface generates two swig-defmethod forms and a
17677  swig-dispatcher form. This provides a single functional interface for
17678  all overloaded routines. A more detailed description of this features
17679  is to be found in the section titled<B> Function overloading/Parameter
17680  defaulting</B>.</P>
17681 <P> In order to load a C++ interface, you will need to build a shared
17682  library from example_wrap.cxx. Be sure to link in the actual library
17683  you created the interface for, as well as any other dependent shared
17684  libraries. For example, if you intend to be able to call back into
17685  lisp, you will also need to link in the Allegro shared library. The
17686  library you create from the C++ wrapper will be what you then load into
17687  Allegro CL.</P>
17688 <H3><A name="Allegrocl_nn4"></A>17.1.2 Command Line Options</H3>
17689 <P> There are three Allegro CL specific command-line option:</P>
17690 <DIV class="shell">
17691 <PRE>
17692 swig -allegrocl [ options ] filename
17693
17694    -identifier-converter [name] - Binds the variable swig:*swig-identifier-convert* 
17695                                   in the generated .cl file to <TT>name</TT>.
17696                                   This function is used to generate symbols
17697                                   for the lisp side of the interface. 
17698
17699    -cwrap - [default] Generate a .cxx file containing C wrapper function when
17700             wrapping C code. The interface generated is similar to what is
17701             done for C++ code.
17702    -nocwrap - Explicitly turn off generation of .cxx wrappers for C code. Reasonable
17703               for modules with simple interfaces. Can not handle all legal enum
17704               and constant constructs, or take advantage of SWIG customization features.
17705
17706    -isolate - With this command-line argument, all lisp helper functions are defined
17707               in a unique package named <TT>swig.&lt;module-name&gt;</TT> rather than
17708               <TT>swig</TT>. This prevents conflicts when the module is
17709               intended to be used with other swig generated interfaces that may, 
17710               for instance, make use of different identifier converters.
17711 </PRE>
17712 </DIV>
17713 <P> See <A href="#Allegrocl_nn47">Section 17.5 Identifier converter
17714  functions</A> for more details.</P>
17715 <H3><A name="Allegrocl_nn5"></A>17.1.3 Inserting user code into
17716  generated files</H3>
17717 <P> It is often necessary to include user-defined code into the
17718  automatically generated interface files. For example, when building a
17719  C++ interface, example_wrap.cxx will likely not compile unless you add
17720  a <TT>#include &quot;header.h&quot;</TT> directive. This can be done using the
17721  SWIG <TT>%insert(section) %{ ...code... %}</TT> directive:</P>
17722 <DIV class="code">
17723 <PRE>
17724 %module example
17725
17726 %{
17727 #include &quot;header.h&quot;
17728 %}
17729
17730 %include &quot;header.h&quot;
17731
17732 int fact(int n);
17733 </PRE>
17734 </DIV>
17735 <P> Additional sections have been added for inserting into the generated
17736  lisp interface file</P>
17737 <UL>
17738 <LI><TT>lisphead</TT> - inserts before type declarations</LI>
17739 <LI><TT>lisp</TT> - inserts after type declarations according to where
17740  it appears in the .i file</LI>
17741 </UL>
17742 <P> Note that the block <TT>%{ ... %}</TT> is effectively a shortcut for
17743  <TT>%insert(&quot;header&quot;) %{ ... %}</TT>.</P>
17744 <H2><A name="Allegrocl_nn6"></A>17.2 Wrapping Overview</H2>
17745 <P> New users to SWIG are encouraged to read <A href="#SWIG">SWIG Basics</A>
17746 , and <A href="#SWIGPlus">SWIG and C++</A>, for those interested in
17747  generating an interface to C++.</P>
17748 <H3><A name="Allegrocl_nn7"></A>17.2.1 Function Wrapping</H3>
17749 <P> Writing lisp code that directly invokes functions at the foreign
17750  function interface level can be cumbersome. Data must often be
17751  translated between lisp and foreign types, data extracted from objects,
17752  foreign objects allocated and freed upon completion of the foreign
17753  call. Dealing with pointers can be unwieldy when it comes to keeping
17754  them distinct from other valid integer values.</P>
17755 <P> We make an attempt to ease some of these burdens by making the
17756  interface to foreign code much more lisp-like, rather than C like. How
17757  this is done is described in later chapters. The layers themselves,
17758  appear as follows:</P>
17759 <DIV class="diagram">
17760 <PRE>
17761         ______________
17762        |              |  (foreign side)
17763        | Foreign Code |  What we're generating an interface to.
17764        |______________|
17765                |
17766                |
17767         _______v______
17768        |              |  (foreign side)
17769        | Wrapper code |  extern &quot;C&quot; wrappers calling C++ 
17770        |______________|  functions and methods.
17771                |
17772     .  . . - - + - - . .  .
17773         _______v______
17774        |              |  (lisp side)
17775        |  FFI Layer   |  Low level lisp interface. ff:def-foreign-call,
17776        |______________|  ff:def-foreign-variable
17777                |
17778                +----------------------------
17779         _______v______              _______v______
17780        |              |            |              | (lisp side)    
17781        |    Defuns    |            |  Defmethods  | wrapper for overloaded
17782        |______________|            |______________| functions or those with
17783         (lisp side)                        |        defaulted arguments
17784         Wrapper for non-overloaded         |
17785         functions and methods       _______v______
17786                                    |              | (lisp side)
17787                                    |    Defuns    | dispatch function
17788                                    |______________| to overloads based
17789                                                     on arity
17790   </PRE>
17791 </DIV>
17792 <H3><A name="Allegrocl_nn8"></A>17.2.2 Foreign Wrappers</H3>
17793 <P> These wrappers are as generated by SWIG default. The types of
17794  function parameters can be transformed in place using the CTYPE
17795  typemap. This is use for converting pass-by-value parameters to
17796  pass-by-reference where necessary. All wrapper parameters are then
17797  bound to local variables for possible transformation of values (see LIN
17798  typemap). Return values can be transformed via the OUT typemap.</P>
17799 <H3><A name="Allegrocl_nn9"></A>17.2.3 FFI Wrappers</H3>
17800 <P> These are the generated ff:def-foreign-call forms. No typemaps are
17801  applicable to this layer, but the <TT>%ffargs</TT> directive is
17802  available for use in .i files, to specify which keyword arguments
17803  should be specified for a given function.</P>
17804 <DIV class="code">ffargs.i:
17805 <PRE>
17806 %module ffargs
17807
17808 %ffargs(strings_convert=&quot;nil&quot;,call_direct=&quot;t&quot;) foo;
17809 %ffargs(strings_convert=&quot;nil&quot;,release_heap=&quot;:never&quot;,optimize_for_space=&quot;t&quot;) bar;
17810
17811 int foo(float f1, float f2);
17812 int foo(float f1, char c2);
17813
17814 void bar(void *lisp_fn);
17815
17816 char *xxx();
17817   </PRE>
17818 </DIV>
17819 <P>Generates:</P>
17820 <DIV class="targetlang">ffargs.cl:
17821 <PRE>
17822 (swig-in-package ())
17823
17824 (swig-defmethod (&quot;foo&quot; &quot;ACL___foo__SWIG_0&quot; :type :function :arity 2)
17825   ((PARM0_f1 cl:single-float :float )
17826    (PARM1_f2 cl:single-float :float ))
17827   (:returning (:int )
17828    :call-direct t
17829    :strings-convert nil)
17830   (let ((SWIG_arg0 PARM0_f1))
17831   (let ((SWIG_arg1 PARM1_f2))
17832   (swig-ff-call SWIG_arg0 SWIG_arg1))))
17833
17834 (swig-defmethod (&quot;foo&quot; &quot;ACL___foo__SWIG_1&quot; :type :function :arity 2)
17835   ((PARM0_f1 cl:single-float :float )
17836    (PARM1_c2 cl:character :char character))
17837   (:returning (:int )
17838    :call-direct t
17839    :strings-convert nil)
17840   (let ((SWIG_arg0 PARM0_f1))
17841   (let ((SWIG_arg1 PARM1_c2))
17842   (swig-ff-call SWIG_arg0 SWIG_arg1))))
17843
17844 (swig-dispatcher (&quot;foo&quot; :type :function :arities (2)))
17845 (swig-defun (&quot;bar&quot; &quot;ACL___bar__SWIG_0&quot; :type :function)
17846   ((PARM0_lisp_fn  (* :void) ))
17847   (:returning (:void )
17848    :release-heap :never
17849    :optimize-for-space t
17850    :strings-convert nil)
17851   (let ((SWIG_arg0 PARM0_lisp_fn))
17852   (swig-ff-call SWIG_arg0)))
17853
17854
17855 (swig-defun (&quot;xxx&quot; &quot;ACL___xxx__SWIG_0&quot; :type :function)
17856   (:void)
17857   (:returning ((* :char) )
17858    :strings-convert t)
17859   (swig-ff-call))
17860   </PRE>
17861 </DIV><DIV class="code">
17862 <PRE>%ffargs(strings_convert=&quot;t&quot;);</PRE>
17863 </DIV>
17864 <P> Is the only default value specified in <TT>allegrocl.swg</TT> to
17865  force the muffling of warnings about automatic string conversion when
17866  defining ff:def-foreign-call's.</P>
17867 <H3><A name="Allegrocl_nn10"></A>17.2.4 Non-overloaded Defuns</H3>
17868 <P> These are simple defuns. There is no typechecking of arguments.
17869  Parameters are bound to local variables for possible transformation of
17870  values, such as pulling values out of instance slots or allocating
17871  temporary stack allocated structures, via the <TT>lin</TT> typemap.
17872  These arguments are then passed to the foreign-call (where typechecking
17873  may occur). The return value from this function can be manipulated via
17874  the <TT>lout</TT> typemap.</P>
17875 <H3><A name="Allegrocl_nn11"></A>17.2.5 Overloaded Defuns</H3>
17876 <P> In the case of overloaded functions, mulitple layers are generated.
17877  First, all the overloads for a given name are separated out into groups
17878  based on arity, and are wrapped in defmethods. Each method calls a
17879  distinct wrapper function, but are themselves distinguished by the
17880  types of their arguments (see <TT>lispclass</TT> typemap). These are
17881  further wrapped in a dispatching function (defun) which will invoke the
17882  appropriate generic-function based on arity. This provides a single
17883  functional interface to all overloads. The return value from this
17884  function can be manipulated via the <TT>lout</TT> typemap.</P>
17885 <H3><A name="Allegrocl_nn12"></A>17.2.6 What about constant and variable
17886  access?</H3>
17887 <P> Along with the described functional layering, when creating a .cxx
17888  wrapper, this module will generate getter and--if not
17889  immutable--setter, functions for variables and constants. If the
17890  -nocwrap option is used, <TT>defconstant</TT> and <TT>
17891 ff:def-foreign-variable</TT> forms will be generated for accessing
17892  constants and global variables. These, along with the <TT>defuns</TT>
17893  listed above are the intended API for calling into the foreign module.</P>
17894 <H3><A name="Allegrocl_nn13"></A>17.2.7 Object Wrapping</H3>
17895 <P> All non-primitive types (Classes, structs, unions, and typedefs
17896  involving same) have a corresponding foreign-type defined on the lisp
17897  side via ff:def-foreign-type.</P>
17898 <P> All non-primitive types are further represented by a CLOS class,
17899  created via defclass. An attempt is made to create the same class
17900  hierarchy, with all classes inheriting directly or indirectly from
17901  ff:foreign-pointer. Further, wherever it is apparent, all pointers
17902  returned from foreign code are wrapped in a CLOS instance of the
17903  appropriate class. For ff:def-foreign-calls that have been defined to
17904  expect a :foreign-address type as argument, these CLOS instances can
17905  legally be passed and the pointer to the C++ object automatically
17906  extracted. This is a natural feature of Allegro's foreign function
17907  interface.</P>
17908 <H2><A name="Allegrocl_nn14"></A>17.3 Wrapping Details</H2>
17909 <P> In this section is described how particular C/C++ constructs are
17910  translated into lisp.</P>
17911 <H3><A name="Allegrocl_nn15"></A>17.3.1 Namespaces</H3>
17912 <P> C++ namespaces are translated into Lisp packages by SWIG. The Global
17913  namespace is mapped to a package named by the <TT>%module</TT>
17914  directive or the <TT>-module</TT> command-line argument. Further
17915  namespaces are generated by the <TT>swig-defpackage</TT> utility
17916  function and given names based on Allegro CLs nested namespace
17917  convention. For example:</P>
17918 <DIV class="code">foo.i:
17919 <PRE>
17920 %module foo
17921
17922 %{
17923 #include &quot;foo.h&quot;
17924 %}
17925
17926 %include &quot;foo.h&quot;
17927
17928 namespace car {
17929    ...
17930    namespace tires {
17931       int do_something(int n);
17932    }
17933 }
17934     </PRE>
17935 </DIV>
17936 <P>Generates the following code.</P>
17937 <DIV class="targetlang">foo.cl
17938 <PRE>
17939 (defpackage :foo
17940   (:use :common-lisp :swig :ff :excl))
17941
17942 ...
17943
17944 (swig-defpackage (&quot;car&quot;))
17945 (swig-defpackage (&quot;car&quot; &quot;tires&quot;))
17946
17947 ...
17948
17949 (swig-in-package (&quot;car&quot; &quot;tires&quot;))
17950 (swig-defun (&quot;do_something&quot; &quot;ACL_car_tires__do_something__SWIG_0&quot; :type :function)
17951   ((PARM0_n  :int ))
17952   (:returning (:int )
17953    :strings-convert t)
17954   (let ((SWIG_arg0 PARM0_n))
17955   (swig-ff-call SWIG_arg0)))
17956     </PRE>
17957 </DIV>
17958 <P> The above interface file would cause packages foo, foo.car, and
17959  foo.car.tires to be created. One would find the function wrapper for
17960  do_something defined in the foo.car.tires package(*).</P>
17961 <P>(<B>*</B>) Except for the package named by the module, all namespace
17962  names are passed to the identifier-converter-function as strings with a
17963  <TT>:type</TT> of <TT>:namespace</TT>. It is the job of this function
17964  to generate the desired symbol, accounting for case preferences,
17965  additional naming cues, etc.</P>
17966 <P> Note that packages created by <TT>swig-defpackage</TT> do not use
17967  the COMMON-LISP or EXCL package. This reduces possible conflicts when
17968  defining foreign types via the SWIG interface in<B> all but the
17969  toplevel modules package</B>. This may lead to confusion if, for
17970  example, the current package is <TT>foo.car.tires</TT> and you attempt
17971  to use a common-lisp function such as <TT>(car '(1 2 3)</TT>.</P>
17972 <H3><A name="Allegrocl_nn16"></A>17.3.2 Constants</H3>
17973 <P> Constants, as declared by the preprocessor #define macro or SWIG <TT>
17974 %constant</TT> directive, are included in SWIGs parse tree when it can
17975  be determined that they are, or could be reduced to, a literal value.
17976  Such values are translated into defconstant forms in the generated lisp
17977  wrapper when the -nocwrap command-line options is used. Else, wrapper
17978  functions are generated as in the case of variable access (see section
17979  below).</P>
17980 <P> Here are examples of simple preprocessor constants when using
17981  -nocwrap.</P>
17982 <DIV class="code">
17983 <PRE>
17984 #define A 1                    =&gt; (swig-defconstant &quot;A&quot; 1)  
17985 #define B 'c'                  =&gt; (swig-defconstant &quot;B&quot; #\c)
17986 #define C B                    =&gt; (swig-defconstant &quot;C&quot; #\c)
17987 #define D 1.0e2                =&gt; (swig-defconstant &quot;D&quot; 1.0d2)
17988 #define E 2222                 =&gt; (swig-defconstant &quot;E&quot; 2222)
17989 #define F (unsigned int)2222   =&gt; no code generated
17990 #define G 1.02e2f              =&gt; (swig-defconstant &quot;G&quot; 1.02f2)
17991 #define H foo                  =&gt; no code generated
17992       </PRE>
17993 </DIV>
17994 <P> Note that where SWIG is unable to determine if a constant is a
17995  literal, no node is added to the SWIG parse tree, and so no values can
17996  be generated.</P>
17997 <P> For preprocessor constants containing expressions which can be
17998  reduced to literal values, nodes are created, but with no
17999  simplification of the constant value. A very very simple infix to
18000  prefix converter has been implemented that tries to do the right thing
18001  for simple cases, but does not for more complex expressions. If the
18002  literal parser determines that something is wrong, a warning will be
18003  generated and the literal expression will be included in the generated
18004  code, but commented out.</P>
18005 <DIV class="code">
18006 <PRE>
18007 #define I A + E                =&gt; (swig-defconstant &quot;I&quot; (+ 1 2222))
18008 #define J 1|2                  =&gt; (swig-defconstant &quot;J&quot; (logior 1 2))
18009 #define Y 1 + 2 * 3 + 4        =&gt; (swig-defconstant &quot;Y&quot; (* (+ 1 2) (+ 3 4)))
18010 #define Y1 (1 + 2) * (3 + 4)   =&gt; (swig-defconstant &quot;Y1&quot; (* (+ 1 2) (+ 3 4)))
18011 #define Y2 1 * 2 + 3 * 4       =&gt; (swig-defconstant &quot;Y2&quot; (* 1 (+ 2 3) 4))  ;; WRONG
18012 #define Y3 (1 * 2) + (3 * 4)   =&gt; (swig-defconstant &quot;Y3&quot; (* 1 (+ 2 3) 4))  ;; WRONG
18013 #define Z 1 + 2 - 3 + 4 * 5    =&gt; (swig-defconstant &quot;Z&quot; (* (+ 1 (- 2 3) 4) 5)) ;; WRONG
18014       </PRE>
18015 </DIV>
18016 <P> Users are cautioned to get to know their constants before use, or
18017  not use the <TT>-nocwrap</TT> command-line option.</P>
18018 <H3><A name="Allegrocl_nn17"></A>17.3.3 Variables</H3>
18019 <P> For C wrapping, a def-foreign-variable call is generated for access
18020  to global variables.</P>
18021 <P> When wrapping C++ code, both global and member variables, getter
18022  wrappers are generated for accessing their value, and if not immutable,
18023  setter wrappers as well. In the example below, note the lack of a
18024  setter wrapper for global_var, defined as const.</P>
18025 <DIV class="code">vars.h
18026 <PRE>
18027 namespace nnn {
18028   int const global_var = 2;
18029   float glob_float = 2.0;
18030 }
18031     </PRE>
18032 </DIV>
18033 <P> Generated code:</P>
18034 <DIV class="targetlang">vars.cl
18035 <PRE>
18036 (swig-in-package (&quot;nnn&quot;))
18037 (swig-defun (&quot;global_var&quot; &quot;ACL_nnn__global_var_get__SWIG_0&quot; :type :getter)
18038   (:void)
18039   (:returning (:int )
18040    :strings-convert t)
18041   (swig-ff-call))
18042
18043
18044 (swig-defun (&quot;glob_float&quot; &quot;ACL_nnn__glob_float_set__SWIG_0&quot; :type :setter)
18045   ((PARM0_glob_float  :float ))
18046   (:returning (:void )
18047    :strings-convert t)
18048   (let ((SWIG_arg0 PARM0_glob_float))
18049   (swig-ff-call SWIG_arg0)))
18050
18051
18052 (swig-defun (&quot;glob_float&quot; &quot;ACL_nnn__glob_float_get__SWIG_0&quot; :type :getter)
18053   (:void)
18054   (:returning (:float )
18055    :strings-convert t)
18056   (swig-ff-call))
18057     </PRE>
18058 </DIV>
18059 <P> Note also, that where applicable, setter wrappers are implemented as
18060  setf methods on the getter function, providing a lispy interface to the
18061  foreign code.</P>
18062 <DIV class="targetlang">
18063 <PRE>
18064 user&gt; (load &quot;globalvar.dll&quot;)
18065 ; Foreign loading globalvar.dll.
18066 t
18067 user&gt; (load &quot;globalvar.cl&quot;)
18068 ; Loading c:\mikel\src\swig\test\globalvar.cl
18069 t
18070 user&gt; 
18071 globalvar&gt; (globalvar.nnn::global_var)
18072 2
18073 globalvar&gt; (globalvar.nnn::glob_float)
18074 2.0
18075 globalvar&gt; (setf (globalvar.nnn::glob_float) 3.0)
18076 3.0
18077 globalvar&gt; (globalvar.nnn::glob_float)
18078 3.0
18079     </PRE>
18080 </DIV>
18081 <H3><A name="Allegrocl_nn18"></A>17.3.4 Enumerations</H3>
18082 <P> In C, an enumeration value is an integer value, while in C++ an
18083  enumeration value is implicitly convertible to an integer value, but
18084  can also be distinguished by it's enum type. For each enum declaration
18085  a def-foreign-type is generated, assigning the enum a default type of
18086  :int. Users may adjust the foreign type of enums via SWIG <TT>typemaps</TT>
18087 .</P>
18088 <P> Enum values are a bit trickier as they can be initialized using any
18089  valid C/C++ expression. In C with the -nocwrap command-line option, we
18090  handle the typical cases (simple integer initialization) and generate a
18091  defconstant form for each enum value. This has the advantage of it not
18092  being necessary to probe into foreign space to retrieve enum values.
18093  When generating a .cxx wrapper file, a more general solution is
18094  employed. A wrapper variable is created in the module_wrap.cxx file,
18095  and a ff:def-foreign-variable call is generated to retrieve it's value
18096  into lisp.</P>
18097 <P>For example, the following header file<DIV class="code">enum.h:
18098 <PRE>
18099 enum COL { RED, GREEN, BLUE };  
18100 enum FOO { FOO1 = 10, FOO2, FOO3 };
18101       </PRE>
18102 </DIV></P>
18103 <P> In -nocwrap mode, generates</P>
18104 <DIV class="targetlang">enum.cl:
18105 <PRE>
18106 (swig-def-foreign-type &quot;COL&quot; :int)
18107 (swig-defconstant &quot;RED&quot; 0)
18108 (swig-defconstant &quot;GREEN&quot; (+ #.(swig-insert-id &quot;RED&quot; () :type :constant) 1))
18109 (swig-defconstant &quot;BLUE&quot; (+ #.(swig-insert-id &quot;GREEN&quot; () :type :constant) 1))
18110
18111 (swig-def-foreign-type &quot;FOO&quot; :int)
18112 (swig-defconstant &quot;FOO1&quot; 10)
18113 (swig-defconstant &quot;FOO2&quot; (+ #.(swig-insert-id &quot;FOO1&quot; () :type :constant) 1))
18114 (swig-defconstant &quot;FOO3&quot; (+ #.(swig-insert-id &quot;FOO2&quot; () :type :constant) 1))
18115       </PRE>
18116 </DIV>
18117 <P>And when generating a .cxx wrapper<DIV class="code">enum_wrap.cxx:
18118 <PRE>
18119 EXPORT const int ACL_ENUM___RED__SWIG_0 = RED;
18120 EXPORT const int ACL_ENUM___GREEN__SWIG_0 = GREEN;
18121 EXPORT const int ACL_ENUM___BLUE__SWIG_0 = BLUE;
18122 EXPORT const int ACL_ENUM___FOO1__SWIG_0 = FOO1;
18123 EXPORT const int ACL_ENUM___FOO2__SWIG_0 = FOO2;
18124 EXPORT const int ACL_ENUM___FOO3__SWIG_0 = FOO3;
18125       </PRE>
18126 </DIV></P>
18127 <P> and</P>
18128 <DIV class="targetlang">enum.cl:
18129 <PRE>
18130 (swig-def-foreign-type &quot;COL&quot; :int)
18131 (swig-defvar &quot;RED&quot; &quot;ACL_ENUM___RED__SWIG_0&quot; :type :constant)
18132 (swig-defvar &quot;GREEN&quot; &quot;ACL_ENUM___GREEN__SWIG_0&quot; :type :constant)
18133 (swig-defvar &quot;BLUE&quot; &quot;ACL_ENUM___BLUE__SWIG_0&quot; :type :constant)
18134
18135 (swig-def-foreign-type &quot;FOO&quot; :int)
18136 (swig-defvar &quot;FOO1&quot; &quot;ACL_ENUM___FOO1__SWIG_0&quot; :type :constant)
18137 (swig-defvar &quot;FOO2&quot; &quot;ACL_ENUM___FOO2__SWIG_0&quot; :type :constant)
18138 (swig-defvar &quot;FOO3&quot; &quot;ACL_ENUM___FOO3__SWIG_0&quot; :type :constant)
18139
18140       </PRE>
18141 </DIV>
18142 <H3><A name="Allegrocl_nn19"></A>17.3.5 Arrays</H3>
18143 <P> One limitation in the Allegro CL foreign-types module, is that,
18144  without macrology, expressions may not be used to specify the
18145  dimensions of an array declaration. This is not a horrible drawback
18146  unless it is necessary to allocate foreign structures based on the
18147  array declaration using ff:allocate-fobject. When it can be determined
18148  that an array bound is a valid numeric value, SWIG will include this in
18149  the generated array declaration on the lisp side, otherwise the value
18150  will be included, but commented out.</P>
18151 <P> Below is a comprehensive example, showing a number of legal C/C++
18152  array declarations and how they are translated into foreign-type
18153  specifications in the generated lisp code.</P>
18154 <DIV class="code">array.h
18155 <PRE>
18156 #define MAX_BUF_SIZE 1024
18157
18158 namespace FOO {
18159   int global_var1[13];
18160   float global_var2[MAX_BUF_SIZE];
18161
18162 }
18163
18164 enum COLOR { RED = 10, GREEN = 20, BLUE, PURPLE = 50, CYAN };
18165
18166 namespace BAR {
18167   char global_var3[MAX_BUF_SIZE + 1];
18168   float global_var4[MAX_BUF_SIZE][13];
18169   signed short global_var5[MAX_BUF_SIZE + MAX_BUF_SIZE];
18170
18171   int enum_var5[GREEN];
18172   int enum_var6[CYAN];
18173
18174   COLOR enum_var7[CYAN][MAX_BUF_SIZE];
18175 }
18176     </PRE>
18177 </DIV>
18178 <P> Generates:</P>
18179 <DIV class="targetlang">array.cl
18180 <PRE>
18181 (in-package #.*swig-module-name*)
18182
18183 (swig-defpackage (&quot;FOO&quot;))
18184 (swig-defpackage (&quot;BAR&quot;))
18185
18186 (swig-in-package ())
18187 (swig-def-foreign-type &quot;COLOR&quot; :int)
18188 (swig-defvar &quot;RED&quot; &quot;ACL_ENUM___RED__SWIG_0&quot; :type :constant)
18189 (swig-defvar &quot;GREEN&quot; &quot;ACL_ENUM___GREEN__SWIG_0&quot; :type :constant)
18190 (swig-defvar &quot;BLUE&quot; &quot;ACL_ENUM___BLUE__SWIG_0&quot; :type :constant)
18191 (swig-defvar &quot;PURPLE&quot; &quot;ACL_ENUM___PURPLE__SWIG_0&quot; :type :constant)
18192 (swig-defvar &quot;CYAN&quot; &quot;ACL_ENUM___CYAN__SWIG_0&quot; :type :constant)
18193
18194 (swig-in-package ())
18195
18196 (swig-defconstant &quot;MAX_BUF_SIZE&quot; 1024)
18197 (swig-in-package (&quot;FOO&quot;))
18198
18199 (swig-defun (&quot;global_var1&quot; &quot;ACL_FOO__global_var1_get__SWIG_0&quot; :type :getter)
18200   (:void)
18201   (:returning ((* :int) )
18202    :strings-convert t)
18203   (make-instance 'ff:foreign-pointer :foreign-address (swig-ff-call)))
18204
18205
18206 (swig-defun (&quot;global_var2&quot; &quot;ACL_FOO__global_var2_set__SWIG_0&quot; :type :setter)
18207   ((global_var2  (:array :float 1024) ))
18208   (:returning (:void )
18209    :strings-convert t)
18210   (let ((SWIG_arg0 global_var2))
18211   (swig-ff-call SWIG_arg0)))
18212
18213
18214 (swig-in-package ())
18215 (swig-in-package (&quot;BAR&quot;))
18216 (swig-defun (&quot;global_var3&quot; &quot;ACL_BAR__global_var3_set__SWIG_0&quot; :type :setter)
18217   ((global_var3  (:array :char #|1024+1|#) ))
18218   (:returning (:void )
18219    :strings-convert t)
18220   (let ((SWIG_arg0 global_var3))
18221   (swig-ff-call SWIG_arg0)))
18222
18223
18224 (swig-defun (&quot;global_var4&quot; &quot;ACL_BAR__global_var4_set__SWIG_0&quot; :type :setter)
18225   ((global_var4  (:array (:array :float 13) 1024) ))
18226   (:returning (:void )
18227    :strings-convert t)
18228   (let ((SWIG_arg0 global_var4))
18229   (swig-ff-call SWIG_arg0)))
18230
18231
18232 (swig-defun (&quot;global_var4&quot; &quot;ACL_BAR__global_var4_get__SWIG_0&quot; :type :getter)
18233   (:void)
18234   (:returning ((* (:array :float 13)) )
18235    :strings-convert t)
18236   (make-instance 'ff:foreign-pointer :foreign-address (swig-ff-call)))
18237
18238
18239 (swig-defun (&quot;global_var5&quot; &quot;ACL_BAR__global_var5_set__SWIG_0&quot; :type :setter)
18240   ((global_var5  (:array :short #|1024+1024|#) ))
18241   (:returning (:void )
18242    :strings-convert t)
18243   (let ((SWIG_arg0 global_var5))
18244   (swig-ff-call SWIG_arg0)))
18245
18246
18247 (swig-defun (&quot;enum_var5&quot; &quot;ACL_BAR__enum_var5_set__SWIG_0&quot; :type :setter)
18248   ((enum_var5  (:array :int #|GREEN|#) ))
18249   (:returning (:void )
18250    :strings-convert t)
18251   (let ((SWIG_arg0 enum_var5))
18252   (swig-ff-call SWIG_arg0)))
18253
18254
18255 (swig-defun (&quot;enum_var6&quot; &quot;ACL_BAR__enum_var6_set__SWIG_0&quot; :type :setter)
18256   ((enum_var6  (:array :int #|CYAN|#) ))
18257   (:returning (:void )
18258    :strings-convert t)
18259   (let ((SWIG_arg0 enum_var6))
18260   (swig-ff-call SWIG_arg0)))
18261
18262
18263 (swig-defun (&quot;enum_var7&quot; &quot;ACL_BAR__enum_var7_set__SWIG_0&quot; :type :setter)
18264   ((enum_var7  (:array (:array #.(swig-insert-id &quot;COLOR&quot; ()) 1024) #|CYAN|#) ))
18265   (:returning (:void )
18266    :strings-convert t)
18267   (let ((SWIG_arg0 enum_var7))
18268   (swig-ff-call SWIG_arg0)))
18269
18270
18271 (swig-defun (&quot;enum_var7&quot; &quot;ACL_BAR__enum_var7_get__SWIG_0&quot; :type :getter)
18272   (:void)
18273   (:returning ((* (:array #.(swig-insert-id &quot;COLOR&quot; ()) 1024)) )
18274    :strings-convert t)
18275   (make-instance 'ff:foreign-pointer :foreign-address (swig-ff-call)))
18276     </PRE>
18277 </DIV>
18278 <H3><A name="Allegrocl_nn20"></A>17.3.6 Classes and Structs and Unions
18279  (oh my!)</H3>
18280 <H4><A name="Allegrocl_nn21"></A>17.3.6.1 CLOS wrapping of</H4>
18281 <P> Classes, unions, and structs are all treated the same way by the
18282  interface generator. For any of these objects, a def-foreign-type and a
18283  defclass form are generated. For every function that returns an object
18284  (or pointer/reference) of C/C++ type <TT>X</TT>, the wrapping defun (or
18285  defmethod) on the Lisp side will automatically wrap the pointer
18286  returned in an instance of the apropriate class. This makes it much
18287  easier to write and debug code than if pointers were passed around as a
18288  jumble of integer values.</P>
18289 <H4><A name="Allegrocl_nn22"></A>17.3.6.2 CLOS Inheritance</H4>
18290 <P> The CLOS class schema generated by the interface mirrors the
18291  inheritance of the classes in foreign code, with the ff:foreign-pointer
18292  class at its root. ff:foreign-pointer is a thin wrapper for pointers
18293  that is made available by the foreign function interface. It's key
18294  benefit is that it may be passed as an argument to any
18295  ff:def-foreign-call that is expecting a pointer as the parameter.</P>
18296 <H4><A name="Allegrocl_nn23"></A>17.3.6.3 Member fields and functions</H4>
18297 <P> All public fields will have accessor getter/setter functions
18298  generated for them, as appropriate. All public member functions will
18299  have wrapper functions generated.</P>
18300 <P> We currently ignore anything that isn't <TT>public</TT> (i.e. <TT>
18301 private</TT> or <TT>protected</TT>), because the C++ compiler won't
18302  allow the wrapper functions to access such fields. Likewise, the
18303  interface does nothing for <TT>friend</TT> directives,</P>
18304 <H4><A name="Allegrocl_nn24"></A>17.3.6.4 Why not directly access C++
18305  classes using foreign types?</H4>
18306 <P> The def-foreign-type generated by the SWIG interface is currently
18307  incomplete. We can reliably generate the object layout of simple
18308  structs and unions; they can be allocated via ff:allocate-fobject, and
18309  their member variables accessed directly using the various
18310  ff:fslot-value-* functions. However, the layout of C++ classes is more
18311  complicated. Different compilers adjust class layout based on
18312  inheritance patterns, and the presence of virtual member functions. The
18313  size of member function pointers vary across compilers as well. As a
18314  result, it is recommended that users of any generated interface not
18315  attempt to access C++ instances via the foreign type system, but
18316  instead use the more robust wrapper functions.</P>
18317 <H3><A name="Allegrocl_nn25"></A>17.3.7 Templates</H3>
18318 <H4><A name="Allegrocl_nn26"></A>17.3.7.1 Generating wrapper code for
18319  templates</H4>
18320 <P> SWIG provides support for dealing with templates, but by default, it
18321  will not generate any member variable or function wrappers for
18322  templated classes. In order to create these wrappers, you need to
18323  explicitly tell SWIG to instantiate them. This is done via the <A href="#SWIGPlus_nn30">
18324 <TT>%template</TT></A> directive.</P>
18325 <H4><A name="Allegrocl_nn27"></A>17.3.7.2 Implicit Template
18326  instantiation</H4>
18327 <P> While no wrapper code is generated for accessing member variables,
18328  or calling member functions, type code is generated to include these
18329  templated classes in the foreign-type and CLOS class schema.</P>
18330 <H3><A name="Allegrocl_nn28"></A>17.3.8 Typedef, Templates, and Synonym
18331  Types</H3>
18332 <P> In C/C++ it is possible, via typedef, to have many names refer to
18333  the same <TT>type</TT>. In general, this is not a problem, though it
18334  can lead to confusion. Assume the below C++ header file:</P>
18335 <DIV class="code">synonyms.h
18336 <PRE>
18337 class A { 
18338    int x;
18339    int y;
18340 };
18341
18342 typedef A Foo;
18343
18344 A *xxx(int i);         /* sets A-&gt;x = A-&gt;y = i */
18345 Foo *yyy(int i);       /* sets Foo-&gt;x = Foo-&gt;y = i */
18346
18347 int zzz(A *inst = 0);  /* return inst-&gt;x + inst-&gt;y */
18348     </PRE>
18349 </DIV>
18350 <P> The function <TT>zzz</TT> is an overloaded functions; the foreign
18351  function call to it will be wrapped in a generic-function whose
18352  argument will be checked against a type of <TT>A</TT>. Assuming a
18353  simple implementation, a call to <TT>xxx(1)</TT> will return a pointer
18354  to an A object, which will be wrapped in a CLOS instance of class <TT>A</TT>
18355 , and a call to <TT>yyy(1)</TT> will result in a CLOS instance of type <TT>
18356 Foo</TT> being returned. Without establishing a clear type relationship
18357  between <TT>Foo</TT> and <TT>A</TT>, an attempt to call <TT>zzz(yyy(1))</TT>
18358  will result in an error.</P>
18359 <P> We resolve this issue, by noting synonym relationships between types
18360  while generating the interface. A Primary type is selected (more on
18361  this below) from the candidate list of synonyms. For all other
18362  synonyms, intead of generating a distinct CLOS class definition, we
18363  generate a form that expands to:</P>
18364 <DIV class="targetlang"> <TT>(setf (find-class &lt;synonym&gt;) &lt;primary&gt;)</TT>
18365 </DIV>
18366 <P> The result is that all references to synonym types in foreign code,
18367  are wrapped in the same CLOS wrapper, and, in particular, method
18368  specialization in wrapping generic functions works as expected.</P>
18369 <P> Given the above header file, synonym.h, a Lisp session would appear
18370  as follows:</P>
18371 <DIV class="targetlang">
18372 <PRE>
18373 CL-USER&gt; (load &quot;synonym.dll&quot;)
18374 ; Foreign loading synonym.dll.
18375 t
18376 CL-USER&gt; (load &quot;synonym.cl&quot;)
18377 ; Loading c:\mikel\src\swig\test\synonym.cl
18378 t
18379 CL-USER&gt; 
18380 synonym&gt; (setf a (xxx 3))
18381 #&lt;A nil #x3261a0 @ #x207299da&gt;
18382 synonym&gt; (setf foo (yyy 10))
18383 #&lt;A nil #x3291d0 @ #x2072e982&gt;
18384 synonym&gt; (zzz a)
18385 6
18386 synonym&gt; (zzz foo)
18387 20
18388 synonym&gt; 
18389     </PRE>
18390 </DIV>
18391 <H4><A name="Allegrocl_nn29"></A>17.3.8.1 Choosing a primary type</H4>
18392 <P> The choice of a primary type is selected by the following criteria
18393  from a set of synonym types.</P>
18394 <UL>
18395 <LI> If a synonym type has a class definition, it is the primary type.</LI>
18396 <LI> If a synonym type is a class template and has been explicitly
18397  instantiated via <TT>%template</TT>, it is the primary type.</LI>
18398 <LI> For all other sets of synonymous types, the synonym which is parsed
18399  first becomes the primary type.</LI>
18400 </UL>
18401 <H3><A name="Allegrocl_nn30"></A>17.3.9 Function overloading/Parameter
18402  defaulting</H3>
18403 <P> For each possible argument combination, a distinct wrapper function
18404  is created in the .cxx file. On the Lisp side, a generic functions is
18405  defined for each possible arity the overloaded/defaulted call may have.
18406  Each distinct wrapper is then called from within a defmethod on the
18407  appropriate generic function. These are further wrapped inside a
18408  dispatch function that checks the number of arguments it is called with
18409  and passes them via apply to the appropriate generic-function. This
18410  allows for a single entry point to overloaded functions on the lisp
18411  side.</P>
18412 <P>Example:</P>
18413 <DIV class="code">overload.h:
18414 <PRE>
18415
18416 class A {
18417  public:
18418   int x;
18419   int y;
18420 };
18421
18422 float xxx(int i, int x = 0);   /* return i * x */
18423 float xxx(A *inst, int x);     /* return x + A-&gt;x + A-&gt;y */
18424     </PRE>
18425 </DIV>
18426 <P>Creates the following three wrappers, for each of the possible
18427  argument combinations</P>
18428 <DIV class="code">overload_wrap.cxx
18429 <PRE>
18430 EXPORT void ACL___delete_A__SWIG_0 (A *larg1) {
18431     A *arg1 = (A *) 0 ;
18432     
18433     arg1 = larg1;
18434     try {
18435         delete arg1;
18436         
18437     } catch (...) {
18438         
18439     }
18440 }
18441
18442
18443 EXPORT float ACL___xxx__SWIG_0 (int larg1, int larg2) {
18444     float lresult = (float)0 ;
18445     int arg1 ;
18446     int arg2 ;
18447     float result;
18448     
18449     arg1 = larg1;
18450     arg2 = larg2;
18451     try {
18452         result = (float)xxx(arg1,arg2);
18453         
18454         lresult = result;
18455         return lresult;
18456     } catch (...) {
18457         return (float)0;
18458     }
18459 }
18460
18461
18462 EXPORT float ACL___xxx__SWIG_1 (int larg1) {
18463     float lresult = (float)0 ;
18464     int arg1 ;
18465     float result;
18466     
18467     arg1 = larg1;
18468     try {
18469         result = (float)xxx(arg1);
18470         
18471         lresult = result;
18472         return lresult;
18473     } catch (...) {
18474         return (float)0;
18475     }
18476 }
18477
18478
18479 EXPORT float ACL___xxx__SWIG_2 (A *larg1, int larg2) {
18480     float lresult = (float)0 ;
18481     A *arg1 = (A *) 0 ;
18482     int arg2 ;
18483     float result;
18484     
18485     arg1 = larg1;
18486     arg2 = larg2;
18487     try {
18488         result = (float)xxx(arg1,arg2);
18489         
18490         lresult = result;
18491         return lresult;
18492     } catch (...) {
18493         return (float)0;
18494     }
18495 }
18496     </PRE>
18497 </DIV>
18498 <P> And the following foreign-function-call and method definitions on
18499  the lisp side:</P>
18500 <DIV class="targetlang">overload.cl
18501 <PRE>
18502 (swig-defmethod (&quot;xxx&quot; &quot;ACL___xxx__SWIG_0&quot; :type :function :arity 2)
18503   ((PARM0_i cl:integer :int )
18504    (PARM1_x cl:integer :int ))
18505   (:returning (:float )
18506    :strings-convert t)
18507   (let ((SWIG_arg0 PARM0_i))
18508   (let ((SWIG_arg1 PARM1_x))
18509   (swig-ff-call SWIG_arg0 SWIG_arg1))))
18510
18511 (swig-defmethod (&quot;xxx&quot; &quot;ACL___xxx__SWIG_1&quot; :type :function :arity 1)
18512   ((PARM0_i cl:integer :int ))
18513   (:returning (:float )
18514    :strings-convert t)
18515   (let ((SWIG_arg0 PARM0_i))
18516   (swig-ff-call SWIG_arg0)))
18517
18518 (swig-defmethod (&quot;xxx&quot; &quot;ACL___xxx__SWIG_2&quot; :type :function :arity 2)
18519   ((PARM0_inst #.(swig-insert-id &quot;A&quot; () :type :class) (* #.(swig-insert-id &quot;A&quot; ())) )
18520    (PARM1_x cl:integer :int ))
18521   (:returning (:float )
18522    :strings-convert t)
18523   (let ((SWIG_arg0 PARM0_inst))
18524   (let ((SWIG_arg1 PARM1_x))
18525   (swig-ff-call SWIG_arg0 SWIG_arg1))))
18526
18527 (swig-dispatcher (&quot;xxx&quot; :type :function :arities (1 2)))
18528     </PRE>
18529 </DIV>
18530 <P>And their usage in a sample lisp session:</P>
18531 <DIV class="targetlang">
18532 <PRE>
18533 overload&gt; (setf a (new_A))
18534 #&lt;A nil #x329268 @ #x206cf612&gt;
18535 overload&gt; (setf (A_x a) 10)
18536 10
18537 overload&gt; (setf (A_y a) 20)
18538 20
18539 overload&gt; (xxx 1)
18540 0.0
18541 overload&gt; (xxx 3 10)
18542 30.0
18543 overload&gt; (xxx a 1)
18544 31.0
18545 overload&gt; (xxx a 2)
18546 32.0
18547 overload&gt; 
18548     </PRE>
18549 </DIV>
18550 <H3><A name="Allegrocl_nn31"></A>17.3.10 Operator wrapping and Operator
18551  overloading</H3>
18552 <P> Wrappers to defined C++ Operators are automatically renamed, using <TT>
18553 %rename</TT>, to the following defaults:</P>
18554 <DIV class="code">
18555 <PRE>
18556 /* name conversion for overloaded operators. */
18557 #ifdef __cplusplus
18558 %rename(__add__)             *::operator+;
18559 %rename(__pos__)             *::operator+();
18560 %rename(__pos__)             *::operator+() const;
18561
18562 %rename(__sub__)             *::operator-;
18563 %rename(__neg__)             *::operator-() const;
18564 %rename(__neg__)             *::operator-();
18565
18566 %rename(__mul__)             *::operator*;
18567 %rename(__deref__)           *::operator*();
18568 %rename(__deref__)           *::operator*() const;
18569
18570 %rename(__div__)             *::operator/;
18571 %rename(__mod__)             *::operator%;
18572 %rename(__logxor__)          *::operator^;
18573 %rename(__logand__)          *::operator&amp;;
18574 %rename(__logior__)          *::operator|;
18575 %rename(__lognot__)          *::operator~();
18576 %rename(__lognot__)          *::operator~() const;
18577
18578 %rename(__not__)             *::operator!();
18579 %rename(__not__)             *::operator!() const;
18580
18581 %rename(__assign__)          *::operator=;
18582
18583 %rename(__add_assign__)      *::operator+=;
18584 %rename(__sub_assign__)      *::operator-=;
18585 %rename(__mul_assign__)      *::operator*=;
18586 %rename(__div_assign__)      *::operator/=;
18587 %rename(__mod_assign__)      *::operator%=;
18588 %rename(__logxor_assign__)   *::operator^=;
18589 %rename(__logand_assign__)   *::operator&amp;=;
18590 %rename(__logior_assign__)   *::operator|=;
18591
18592 %rename(__lshift__)          *::operator&lt;&lt;;
18593 %rename(__lshift_assign__)   *::operator&lt;&lt;=;
18594 %rename(__rshift__)          *::operator&gt;&gt;;
18595 %rename(__rshift_assign__)   *::operator&gt;&gt;=;
18596
18597 %rename(__eq__)              *::operator==;
18598 %rename(__ne__)              *::operator!=;
18599 %rename(__lt__)              *::operator&lt;;
18600 %rename(__gt__)              *::operator&gt;;
18601 %rename(__lte__)             *::operator&lt;=;
18602 %rename(__gte__)             *::operator&gt;=;
18603
18604 %rename(__and__)             *::operator&amp;&amp;;
18605 %rename(__or__)              *::operator||;
18606
18607 %rename(__preincr__)         *::operator++();
18608 %rename(__postincr__)        *::operator++(int);
18609 %rename(__predecr__)         *::operator--();
18610 %rename(__postdecr__)        *::operator--(int);
18611
18612 %rename(__comma__)           *::operator,();
18613 %rename(__comma__)           *::operator,() const;
18614
18615 %rename(__member_ref__)      *::operator-&gt;;
18616 %rename(__member_func_ref__) *::operator-&gt;*;
18617
18618 %rename(__funcall__)         *::operator();
18619 %rename(__aref__)            *::operator[];
18620     </PRE>
18621 </DIV>
18622 <P> Name mangling occurs on all such renamed identifiers, so that
18623  wrapper name generated by <TT>B::operator=</TT> will be <TT>B___eq__</TT>
18624 , i.e. <TT>&lt;class-or-namespace&gt;_</TT> has been added. Users may modify
18625  these default names by adding <TT>%rename</TT> directives in their own
18626  .i files.</P>
18627 <P> Operator overloading can be achieved by adding functions based on
18628  the mangled names of the function. In the following example, a class B
18629  is defined with a Operator== method defined. The swig <TT>%extend</TT>
18630  directive is used to add an overload method on Operator==.</P>
18631 <DIV class="code">opoverload.h
18632 <PRE>
18633 class B {
18634  public:
18635   int x;
18636   int y;
18637   bool operator==(B const&amp; other) const;
18638 };
18639     </PRE>
18640 </DIV>
18641 <P> and</P>
18642 <DIV class="code">opoverload.i
18643 <PRE>
18644 %module opoverload
18645
18646 %{
18647 #include &lt;fstream&gt;
18648 #include &quot;opoverload.h&quot;
18649 %}
18650
18651 %{
18652 bool B___eq__(B const *inst, int const x)
18653 {
18654   // insert the function definition into the wrapper code before
18655   // the wrapper for it.
18656   // ... do stuff ...
18657 }
18658 %}
18659
18660 %include &quot;opoverload.h&quot;
18661
18662 %extend B {
18663  public:
18664   bool __eq__(int const x) const;
18665 };
18666     </PRE>
18667 </DIV>
18668 <P> Either operator can be called via a single call to the dispatch
18669  function:</P>
18670 <DIV class="targetlang">
18671 <PRE>
18672 opoverload&gt; (B___eq__ x1 x2)
18673 nil
18674 opoverload&gt; (B___eq__ x1 3)
18675 nil
18676 opoverload&gt; 
18677     </PRE>
18678 </DIV>
18679 <H3><A name="Allegrocl_nn32"></A>17.3.11 Varargs</H3>
18680 <P> Variable length argument lists are not supported, by default. If
18681  such a function is encountered, a warning will generated to stderr.
18682  Varargs are supported via the SWIG <TT>%vararg</TT> directive. This
18683  directive allows you to specify a (finite) argument list which will be
18684  inserted into the wrapper in place of the variable length argument
18685  indicator. As an example, consider the function <TT>printf()</TT>. It's
18686  declaration would appear as follows:</P>
18687 <P> See the following section on <A href="#Varargs">Variable Length
18688  arguments</A> provides examples on how <TT>%vararg</TT> can be used,
18689  along with other ways such functions can be wrapped.</P>
18690 <H3><A name="Allegrocl_nn33"></A>17.3.12 C++ Exceptions</H3>
18691 <P> Each C++ wrapper includes a handler to catch any exceptions that may
18692  be thrown while in foreign code. This helps prevent simple C++ errors
18693  from killing the entire lisp process. There is currently no mechanism
18694  to have these exceptions forwarded to the lisp condition system, nor
18695  has any explicit support of the exception related SWIG typemaps been
18696  implemented.</P>
18697 <H3><A name="Allegrocl_nn34"></A>17.3.13 Pass by value, pass by
18698  reference</H3>
18699 <P> Allegro CL does not support the passing of non-primitive foreign
18700  structures by value. As a result, SWIG must automatically detect and
18701  convert function parameters and return values to pointers whenever
18702  necessary. This is done via the use of <TT>typemaps</TT>, and should
18703  not require any fine tuning by the user, even for newly defined types.</P>
18704 <H2><A name="Allegrocl_nn35"></A>17.4 Typemaps</H2>
18705 <P> SWIG Typemaps provide a powerful tool for automatically generating
18706  code to handle various menial tasks required of writing an interface to
18707  foreign code. The purpose of this section is to describe each of the
18708  typemaps used by the Allegro CL module. Please read the chapter on <A href="#Typemaps">
18709 Typemaps</A> for more information.</P>
18710 <H3><A name="Allegrocl_nn36"></A>17.4.1 Code Generation in the C++
18711  Wrapper</H3>
18712 <P> Every C++ wrapper generated by SWIG takes the following form:</P>
18713 <DIV class="diagram">
18714 <PRE>
18715 return-val wrapper-name(parm0, parm1, ..., parmN)
18716 {
18717    return-val lresult;   /* return value from wrapper */
18718    &lt;local-declaration&gt;
18719    ... results;          /* return value from function call */
18720
18721    &lt;binding locals to parameters&gt;
18722
18723    try {
18724       result = function-name(local0, local1, ..., localN);
18725
18726       &lt;convert and bind result to lresult&gt;
18727
18728       return lresult;
18729    catch (...) {
18730       return (int)0;
18731    }
18732     </PRE>
18733 </DIV>
18734 <H4><A name="Allegrocl_nn37"></A>17.4.1.1 IN Typemap</H4>
18735 <P> the <TT>in</TT> typemap is used to generate code to convert
18736  parameters passed to C++ wrapper functions into the arguments desired
18737  for the call being wrapped. That is, it fills in the code for the <TT>
18738 &lt;binding locals to parameters&gt;</TT> section above. We use this map to
18739  automatically convert parameters passed by reference to the wrapper
18740  function into by-value arguments for the wrapped call, and also to
18741  convert boolean values, which are passed as integers from lisp (by
18742  default), into the appropriate type for the language of code being
18743  wrapped.</P>
18744 <P>These are the default specifications for the IN typemap. Here, <TT>
18745 $input</TT> refers to the parameter code is being generated for, and <TT>
18746 $1</TT> is the local variable to which it is being assigned. The default
18747  settings of this typemap are as follows:</P>
18748 <DIV class="code">
18749 <PRE>
18750 %typemap(in) bool                          &quot;$1 = (bool)$input;&quot;;
18751 %typemap(in) char, unsigned char, signed char,
18752              short, signed short, unsigned short,
18753              int, signed int, unsigned int,
18754              long, signed long, unsigned long,
18755              float, double, long double, char *, void *, void,
18756              enum SWIGTYPE, SWIGTYPE *,
18757              SWIGTYPE[ANY], SWIGTYPE &amp;     &quot;$1 = $input;&quot;;
18758 %typemap(in) SWIGTYPE                      &quot;$1 = *$input;&quot;;
18759     </PRE>
18760 </DIV>
18761 <H4><A name="Allegrocl_nn38"></A>17.4.1.2 OUT Typemap</H4>
18762 <P> The <TT>out</TT> typemap is used to generate code to form the return
18763  value of the wrapper from the return value of the wrapped function.
18764  This code is placed in the &lt;convert and bind result to lresult&gt; section
18765  of the above code diagram. It's default mapping is as follows:</P>
18766 <DIV class="code">
18767 <PRE>
18768 %typemap(out) bool                          &quot;$result = (int)$1;&quot;;
18769 %typemap(out) char, unsigned char, signed char,
18770               short, signed short, unsigned short,
18771               int, signed int, unsigned int,
18772               long, signed long, unsigned long,
18773               float, double, long double, char *, void *, void,
18774               enum SWIGTYPE, SWIGTYPE *,
18775               SWIGTYPE[ANY], SWIGTYPE &amp;    &quot;$result = $1;&quot;;
18776 %typemap(out) SWIGTYPE                     &quot;$result = new $1_type($1);&quot;;
18777     </PRE>
18778 </DIV>
18779 <H4><A name="Allegrocl_nn39"></A>17.4.1.3 CTYPE Typemap</H4>
18780 <P> This typemap is not used for code generation, but purely for the
18781  transformation of types in the parameter list of the wrapper function.
18782  It's primary use is to handle by-value to by-reference conversion in
18783  the wrappers parameter list. Its default settings are:</P>
18784 <DIV class="code">
18785 <PRE>
18786 %typemap(ctype) bool                       &quot;int&quot;;
18787 %typemap(ctype) char, unsigned char, signed char,
18788                 short, signed short, unsigned short,
18789                 int, signed int, unsigned int,
18790                 long, signed long, unsigned long,
18791                 float, double, long double, char *, void *, void,
18792                 enum SWIGTYPE, SWIGTYPE *,
18793                 SWIGTYPE[ANY], SWIGTYPE &amp;  &quot;$1_ltype&quot;;
18794 %typemap(ctype) SWIGTYPE                   &quot;$&amp;1_type&quot;;
18795     </PRE>
18796 </DIV>
18797 <P> These three typemaps are specifically employed by the the Allegro CL
18798  interface generator. SWIG also implements a number of other typemaps
18799  that can be used for generating code in the C/C++ wrappers. You can
18800  read about these <A href="#Typemaps_nn25">common typemaps</A> here.</P>
18801 <H3><A name="Allegrocl_nn40"></A>17.4.2 Code generation in Lisp wrappers</H3>
18802 <P> A number of custom typemaps have also been added to facilitate the
18803  generation of code in the lisp side of the interface. These are
18804  described below. The basic code generation structure is applied as a
18805  series of nested expressions, one for each parameter, then one for
18806  manipulating the return value, and last, the foreign function call
18807  itself.</P>
18808 <P> Note that the typemaps below use fully qualified symbols where
18809  necessary. Users writing their own typemaps should do likewise. See the
18810  explanation in the last paragraph of <A href="#Allegrocl_nn15">16.3.1
18811  Namespaces</A> for details.</P>
18812 <H4><A name="Allegrocl_nn41"></A>17.4.2.1 LIN Typemap</H4>
18813 <P> The LIN typemap allows for the manipulating the lisp objects passed
18814  as arguments to the wrapping defun before passing them to the foreign
18815  function call. For example, when passing lisp strings to foreign code,
18816  it is often necessary to copy the string into a foreign structure of
18817  type (:char *) of appropriate size, and pass this copy to the foreign
18818  call. Using the LIN typemap, one could arrange for the stack-allocation
18819  of a foreign char array, copy your string into it, and not have to
18820  worry about freeing the copy after the function returns.</P>
18821 <P>The LIN typemap accepts the following <TT>$variable</TT> references.</P>
18822 <UL>
18823 <LI><TT>$in</TT> - expands to the name of the parameter being applied to
18824  this typemap</LI>
18825 <LI><TT>$out</TT> - expands to the name of the local variable assigned
18826  to this typemap</LI>
18827 <LI><TT>$in_fftype</TT> - the foreign function type of the C type.</LI>
18828 <LI><TT>$*in_fftype</TT> - the foreign function type of the C type with
18829  one pointer removed. If there is no pointer, then $*in_fftype is the
18830  same as $in_fftype.</LI>
18831 <LI><TT>$body</TT> - very important. Instructs SWIG where subsequent
18832  code generation steps should be inserted into the current typemap.
18833  Leaving out a <TT>$body</TT> reference will result in lisp wrappers
18834  that do very little by way of calling into foreign code. Not
18835  recommended.</LI>
18836 </UL>
18837 <DIV class="code">
18838 <PRE>
18839 %typemap(lin)   SWIGTYPE        &quot;(cl:let (($out $in))\n  $body)&quot;;
18840     </PRE>
18841 </DIV>
18842 <H4><A name="Allegrocl_nn42"></A>17.4.2.2 LOUT Typemap</H4>
18843 <P> The LOUT typemap is the means by which we effect the wrapping of
18844  foreign pointers in CLOS instances. It is applied after all LIN
18845  typemaps, and immediately before the actual foreign-call.</P>
18846 <P>The LOUT typemap uses the following $variable</P>
18847 <UL>
18848 <LI><TT>$lclass</TT> - Expands to the CLOS class that represents
18849  foreign-objects of the return type matching this typemap.</LI>
18850 <LI><TT>$body</TT> - Same as for the LIN map. Place this variable where
18851  you want the foreign-function call to occur.</LI>
18852 <LI><TT>$ldestructor</TT> - Expands to the symbol naming the destructor
18853  for this class ($lclass) of object. Allows you to insert finalization
18854  or automatic garbage collection into the wrapper code (see default
18855  mappings below).</LI>
18856 </UL>
18857 <DIV class="code">
18858 <PRE>
18859 %typemap(lout) bool, char, unsigned char, signed char,
18860                short, signed short, unsigned short,
18861                int, signed int, unsigned int,
18862                long, signed long, unsigned long,
18863                float, double, long double, char *, void *, void,
18864                enum SWIGTYPE    &quot;$body&quot;;
18865 %typemap(lout) SWIGTYPE[ANY], SWIGTYPE *,
18866                SWIGTYPE &amp;       &quot;(cl:make-instance '$lclass :foreign-address $body)&quot;;
18867 %typemap(lout) SWIGTYPE    &quot;(cl:let* ((address $body)\n
18868                             (ACL_result (cl:make-instance '$lclass :foreign-address address)))\n
18869                             (cl:unless (cl::zerop address)\n
18870                             (excl:schedule-finalization ACL_result #'$ldestructor))\n
18871                              ACL_result)&quot;;
18872     </PRE>
18873 </DIV>
18874 <H4><A name="Allegrocl_nn43"></A>17.4.2.3 FFITYPE Typemap</H4>
18875 <P> The FFITYPE typemap works as a helper for a body of code that
18876  converts C/C++ type specifications into Allegro CL foreign-type
18877  specifications. These foreign-type specifications appear in
18878  ff:def-foreing-type declarations, and in the argument list and return
18879  values of ff:def-foreign-calls. You would modify this typemap if you
18880  want to change how the FFI passes through arguments of a given type.
18881  For example, if you know that a particular compiler represents booleans
18882  as a single byte, you might add an entry for:</P>
18883 <DIV class="code">
18884 <PRE>
18885 %typemap(ffitype) bool &quot;:unsigned-char&quot;;
18886     </PRE>
18887 </DIV>
18888 <P> Note that this typemap is pure type transformation, and is not used
18889  in any code generations step the way the LIN and LOUT typemaps are. The
18890  default mappings for this typemap are:</P>
18891 <DIV class="code">
18892 <PRE>
18893 %typemap(ffitype) bool &quot;:int&quot;;
18894 %typemap(ffitype) char &quot;:char&quot;;
18895 %typemap(ffitype) unsigned char &quot;:unsigned-char&quot;;
18896 %typemap(ffitype) signed char &quot;:char&quot;;
18897 %typemap(ffitype) short, signed short &quot;:short&quot;;
18898 %typemap(ffitype) unsigned short &quot;:unsigned-short&quot;;
18899 %typemap(ffitype) int, signed int &quot;:int&quot;;
18900 %typemap(ffitype) unsigned int &quot;:unsigned-int&quot;;
18901 %typemap(ffitype) long, signed long &quot;:long&quot;;
18902 %typemap(ffitype) unsigned long &quot;:unsigned-long&quot;;
18903 %typemap(ffitype) float &quot;:float&quot;;
18904 %typemap(ffitype) double &quot;:double&quot;;
18905 %typemap(ffitype) char * &quot;(* :char)&quot;;
18906 %typemap(ffitype) void * &quot;(* :void)&quot;;
18907 %typemap(ffitype) void &quot;:void&quot;;
18908 %typemap(ffitype) enum SWIGTYPE &quot;:int&quot;;
18909 %typemap(ffitype) SWIGTYPE &amp; &quot;(* :void)&quot;;
18910     </PRE>
18911 </DIV>
18912 <H4><A name="Allegrocl_nn44"></A>17.4.2.4 LISPTYPE Typemap</H4>
18913 <P> This is another type only transformation map, and is used to provide
18914  the lisp-type, which is the optional third argument in argument
18915  specifier in a ff:def-foreign-call form. Specifying a lisp-type allows
18916  the foreign call to perform type checking on the arguments passed in.
18917  The default entries in this typemap are:</P>
18918 <DIV class="code">
18919 <PRE>
18920 %typemap(lisptype) bool &quot;cl:boolean&quot;;
18921 %typemap(lisptype) char &quot;cl:character&quot;;
18922 %typemap(lisptype) unsigned char &quot;cl:integer&quot;;
18923 %typemap(lisptype) signed char &quot;cl:integer&quot;;
18924     </PRE>
18925 </DIV>
18926 <H4><A name="Allegrocl_nn45"></A>17.4.2.5 LISPCLASS Typemap</H4>
18927 <P> The LISPCLASS typemap is used to generate the method signatures for
18928  the generic-functions which wrap overloaded functions and functions
18929  with defaulted arguments. The default entries are:</P>
18930 <DIV class="code">
18931 <PRE>
18932 %typemap(lispclass) bool &quot;t&quot;;
18933 %typemap(lispclass) char &quot;cl:character&quot;;
18934 %typemap(lispclass) unsigned char, signed char,
18935                     short, signed short, unsigned short,
18936                     int, signed int, unsigned int,
18937                     long, signed long, unsigned long,
18938                     enum SWIGTYPE       &quot;cl:integer&quot;;
18939 %typemap(lispclass) float &quot;cl:single-float&quot;;
18940 %typemap(lispclass) double &quot;cl:double-float&quot;;
18941 %typemap(lispclass) char * &quot;cl:string&quot;;
18942     </PRE>
18943 </DIV>
18944 <H3><A name="Allegrocl_nn46"></A>17.4.3 Modifying SWIG behavior using
18945  typemaps</H3>
18946 <P> The following example shows how we made use of the above typemaps to
18947  add support for the wchar_t type.</P>
18948 <DIV class="code">
18949 <PRE>
18950 %typecheck(SWIG_TYPECHECK_UNICHAR) wchar_t { $1 = 1; };
18951
18952 %typemap(in)        wchar_t &quot;$1 = $input;&quot;;
18953 %typemap(lin)       wchar_t &quot;(cl:let (($out (cl:char-code $in)))\n  $body)&quot;;
18954 %typemap(lin)       wchar_t* &quot;(excl:with-native-string
18955                                          ($out $in
18956                                           :external-format #+little-endian :fat-le 
18957                                                            #-little-endian :fat)\n
18958                                  $body)&quot;
18959
18960 %typemap(out)       wchar_t &quot;$result = $1;&quot;;
18961 %typemap(lout)      wchar_t &quot;(cl:code-char $body)&quot;;
18962 %typemap(lout)      wchar_t* &quot;(excl:native-to-string $body
18963                                           :external-format #+little-endian :fat-le
18964                                                            #-little-endian :fat)&quot;;
18965
18966 %typemap(ffitype)   wchar_t &quot;:unsigned-short&quot;;
18967 %typemap(lisptype)  wchar_t &quot;&quot;;
18968 %typemap(ctype)     wchar_t &quot;wchar_t&quot;;
18969 %typemap(lispclass) wchar_t &quot;cl:character&quot;;
18970 %typemap(lispclass) wchar_t* &quot;cl:string&quot;;
18971     </PRE>
18972 </DIV>
18973 <H2><A name="Allegrocl_nn47"></A>17.5 Identifier Converter functions</H2>
18974 <H3><A name="Allegrocl_nn48"></A>17.5.1 Creating symbols in the lisp
18975  environment</H3>
18976 <P> Various symbols must be generated in the lisp environment to which
18977  class definitions, functions, constants, variables, etc. must be bound.
18978  Rather than force a particular convention for naming these symbols, an
18979  identifier (to symbol) conversion function is used. A user-defined
18980  identifier-converter can then implement any symbol naming,
18981  case-modifying, scheme desired.</P>
18982 <P> In generated SWIG code, whenever some interface object must be
18983  referenced by its lisp symbol, a macro is inserted that calls the
18984  identifier-converter function to generate the appropriate symbol
18985  reference. It is therefore expected that the identifier-converter
18986  function reliably return the same (eq) symbol given the same set of
18987  arguments.</P>
18988 <H3><A name="Allegrocl_nn49"></A>17.5.2 Existing identifier-converter
18989  functions</H3>
18990 <P>Two basic identifier routines have been defined.</P>
18991 <H4><A name="Allegrocl_nn50"></A>17.5.2.1 identifier-convert-null</H4>
18992 <P> No modification of the identifier string is performed. Based on
18993  other arguments, the identifier may be concatenated with other strings,
18994  from which a symbol will be created.</P>
18995 <H4><A name="Allegrocl_nn51"></A>17.5.2.2 identifier-convert-lispify</H4>
18996 <P> All underscores in the identifier string are converted to hyphens.
18997  Otherwise, identifier-convert-lispify performs the same symbol
18998  transformations.</P>
18999 <H4><A name="Allegrocl_nn52"></A>17.5.2.3 Default identifier to symbol
19000  conversions</H4>
19001 <P> Check the definitions of the above two default identifier-converters
19002  in <TT>Lib/allegrocl/allegrocl.swg</TT> for default naming conventions.</P>
19003 <H3><A name="Allegrocl_nn53"></A>17.5.3 Defining your own
19004  identifier-converter</H3>
19005 <P> A user-defined identifier-converter function should conform to the
19006  following specification:</P>
19007 <DIV class="targetlang">
19008 <PRE>
19009 (defun identifier-convert-fn (id &amp;key type class arity) ...body...)
19010 result ==&gt; symbol or (setf symbol)
19011 </PRE>
19012 </DIV>
19013 <P>The <TT>ID</TT> argument is a string representing an identifier in
19014  the foreign environment.</P>
19015 <P> The :type keyword argument provides more information on the type of
19016  identifier. It's value is a symbol. This allows the
19017  identifier-converter to apply different heuristics when mapping
19018  different types of identifiers to symbols. SWIG will generate calls to
19019  your identifier-converter using the following types.</P>
19020 <UL>
19021 <LI>:class - names a CLOS class.</LI>
19022 <LI>:constant - names a defconstant</LI>
19023 <LI>:constructor - names a function for creating a foreign object</LI>
19024 <LI>:destructor - names a function for freeing a foreign object</LI>
19025 <LI>:function - names a CLOS wrapping defmethod or defun.</LI>
19026 <LI>:ff-operator - names a foreign call defined via ff:def-foreign-call</LI>
19027 <LI>:getter - getter function</LI>
19028 <LI>:namespace - names a C++ namespace</LI>
19029 <LI>:setter - names a setter function. May return a (setf symbol)
19030  reference</LI>
19031 <LI>:operator - names a C++ operator, such as Operator=, Operator*.</LI>
19032 <LI>:slot - names a slot in a struct/class/union declaration.</LI>
19033 <LI>:type - names a foreign-type defined via ff:def-foreign-type.</LI>
19034 <LI>:variable - names a variable defined via ff:def-foreign-variable.</LI>
19035 </UL>
19036 <P> The :class keyword argument is a string naming a foreign class. When
19037  non-nil, it indicates that the current identifier has scope in the
19038  specified class.</P>
19039 <P> The :arity keyword argument only appears in swig:swig-defmethod
19040  forms generated for overloaded functions. It's value is an integer
19041  indicating the number of arguments passed to the routine indicated by
19042  this identifier.</P>
19043 <H3><A name="Allegrocl_nn54"></A>17.5.4 Instructing SWIG to use a
19044  particular identifier-converter</H3>
19045 <P> By default, SWIG will use identifier-converter-null. To specify
19046  another convert function, use the <TT>-identifier-converter</TT>
19047  command-line argument. The value should be a string naming the function
19048  you wish the interface to use instead, when generating symbols. ex:</P>
19049 <DIV class="code">
19050 <PRE>
19051 % swig -allegrocl -c++ -module mymodule -identifier-converter my-identifier-converter
19052 </PRE>
19053 </DIV><HR NOSHADE>
19054 <H1><A name="CSharp"></A>18 SWIG and C#</H1>
19055
19056 <!-- INDEX -->
19057 <DIV class="sectiontoc">
19058 <UL>
19059 <LI><A href="#csharp_introduction">Introduction</A></LI>
19060 <LI><A href="#csharp_differences_java">Differences to the Java module</A>
19061 </LI>
19062 <LI><A href="#CSharp_arrays">C# Arrays</A>
19063 <UL>
19064 <LI><A href="#CSharp_arrays_swig_library">The SWIG C arrays library</A></LI>
19065 <LI><A href="#CSharp_arrays_pinvoke_default_array_marshalling">Managed
19066  arrays using P/Invoke default array marshalling</A></LI>
19067 <LI><A href="#CSharp_arrays_pinning">Managed arrays using pinning</A></LI>
19068 </UL>
19069 </LI>
19070 <LI><A href="#csharp_exceptions">C# Exceptions</A>
19071 <UL>
19072 <LI><A href="#csharp_exception_example_check_typemap">C# exception
19073  example using &quot;check&quot; typemap</A></LI>
19074 <LI><A href="#csharp_exception_example_percent_exception">C# exception
19075  example using %exception</A></LI>
19076 <LI><A href="#csharp_exception_example_exception_specifications">C#
19077  exception example using exception specifications</A></LI>
19078 <LI><A href="#csharp_custom_application_exception">Custom C#
19079  ApplicationException example</A></LI>
19080 </UL>
19081 </LI>
19082 <LI><A href="#csharp_directors">C# Directors</A>
19083 <UL>
19084 <LI><A href="#csharp_directors_example">Directors example</A></LI>
19085 <LI><A href="#csharp_directors_implementation">Directors implementation</A>
19086 </LI>
19087 <LI><A href="#csharp_director_caveats">Director caveats</A></LI>
19088 </UL>
19089 </LI>
19090 <LI><A href="#csharp_typemap_examples">C# Typemap examples</A>
19091 <UL>
19092 <LI><A href="#csharp_memory_management_member_variables">Memory
19093  management when returning references to member variables</A></LI>
19094 <LI><A href="#csharp_memory_management_objects">Memory management for
19095  objects passed to the C++ layer</A></LI>
19096 <LI><A href="#csharp_date_marshalling">Date marshalling using the csin
19097  typemap and associated attributes</A></LI>
19098 <LI><A href="#csharp_date_properties">A date example demonstrating
19099  marshalling of C# properties</A></LI>
19100 <LI><A href="#csharp_partial_classes">Turning wrapped classes into
19101  partial classes</A></LI>
19102 <LI><A href="#csharp_extending_proxy_class">Extending proxy classes with
19103  additional C# code</A></LI>
19104 </UL>
19105 </LI>
19106 </UL>
19107 </DIV>
19108 <!-- INDEX -->
19109 <H2><A name="csharp_introduction"></A>18.1 Introduction</H2>
19110 <P> The purpose of the C# module is to offer an automated way of
19111  accessing existing C/C++ code from .NET languages. The wrapper code
19112  implementation uses C# and the Platform Invoke (PInvoke) interface to
19113  access natively compiled C/C++ code. The PInvoke interface has been
19114  chosen over Microsoft's Managed C++ interface as it is portable to both
19115  Microsoft Windows and non-Microsoft platforms. PInvoke is part of the
19116  ECMA/ISO C# specification. It is also better suited for robust
19117  production environments due to the Managed C++ flaw called the <A href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dv_vstechart/html/vcconMixedDLLLoadingProblem.asp">
19118 Mixed DLL Loading Problem</A>. Swig C# works equally well on
19119  non-Microsoft operating systems such as Linux, Solaris and Apple Mac
19120  using <A href="http://www.mono-project.com/">Mono</A> and <A href="http://www.dotgnu.org/pnet.html">
19121 Portable.NET</A>.</P>
19122 <P> To get the most out of this chapter an understanding of interop is
19123  required. The <A href="http://msdn.microsoft.com">Microsoft Developer
19124  Network (MSDN)</A> has a good reference guide in a section titled
19125  &quot;Interop Marshaling&quot;. Monodoc, available from the Mono project, has a
19126  very useful section titled <A href="http://www.mono-project.com/Interop_with_Native_Libraries">
19127 Interop with native libraries</A>.</P>
19128 <H2><A name="csharp_differences_java"></A>18.2 Differences to the Java
19129  module</H2>
19130 <P> The C# module is very similar to the Java module, so until some more
19131  complete documentation has been written, please use the <A href="#Java">
19132 Java documentation</A> as a guide to using SWIG with C#. The C# module
19133  has the same major SWIG features as the Java module. The rest of this
19134  section should be read in conjunction with the Java documentation as it
19135  lists the main differences. The most notable differences to Java are
19136  the following:</P>
19137 <UL>
19138 <LI> When invoking SWIG use the <TT>-csharp</TT> command line option
19139  instead of <TT>-java</TT>.</LI>
19140 <LI> The <TT>-nopgcpp</TT> command line option does not exist.</LI>
19141 <LI> The <TT>-package</TT> command line option does not exist.</LI>
19142 <LI> The <TT>-namespace &lt;name&gt;</TT> commandline option will generate all
19143  code into the namespace specified by <TT>&lt;name&gt;</TT>. C# supports
19144  nested namespaces that are not lexically nested, so nested namespaces
19145  will of course also work. For example: <TT>-namespace com.bloggs.widget</TT>
19146 , will generate code into C# namespaces:<DIV class="code">
19147 <PRE>
19148 namespace com.bloggs.widget {
19149   ...
19150 }
19151 </PRE>
19152 </DIV> Note that by default, the generated C# classes have no namespace
19153  and the module name is unrelated to namespaces. The module name is just
19154  like in Java and is merely used to name some of the generated classes.</LI>
19155 <LI> The <TT>-dllimport &lt;name&gt;</TT> commandline option specifies the
19156  name of the DLL for the <TT>DllImport</TT> attribute for every PInvoke
19157  method. If this commandline option is not given, the <TT>DllImport</TT>
19158  DLL name is the same as the module name. This option is useful for when
19159  one wants to invoke SWIG multiple times on different modules, yet
19160  compile all the resulting code into a single DLL.</LI>
19161 <LI> C/C++ variables are wrapped with C# properties and not JavaBean
19162  style getters and setters.</LI>
19163 <LI> Global constants are generated into the module class. There is no
19164  constants interface.</LI>
19165 <LI> There is no implementation for type unsafe enums - not deemed
19166  necessary.</LI>
19167 <LI> The default enum wrapping approach is proper C# enums, not typesafe
19168  enums.
19169 <BR> Note that %csconst(0) will be ignored when wrapping C/C++ enums
19170  with proper C# enums. This is because C# enum items must be initialised
19171  from a compile time constant. If an enum item has an initialiser and
19172  the initialiser doesn't compile as C# code, then the %csconstvalue
19173  directive must be used as %csconst(0) will have no effect. If it was
19174  used, it would generate an illegal runtime initialisation via a PInvoke
19175  call.</LI>
19176 <LI> C# doesn't support the notion of throws clauses. Therefore there is
19177  no 'throws' typemap attribute support for adding exception classes to a
19178  throws clause. Likewise there is no need for an equivalent to <TT>
19179 %javaexception</TT>. In fact, throwing C# exceptions works quite
19180  differently, see <A href="#csharp_exceptions">C# Exceptions</A> below.</LI>
19181 <LI> The majority of the typemaps are in csharp.swg, not java.swg.</LI>
19182 <LI>
19183 <P>Typemap equivalent names:</P>
19184 <DIV class="code">
19185 <PRE>
19186 jni                         -&gt; ctype
19187 jtype                       -&gt; imtype
19188 jstype                      -&gt; cstype
19189 javain                      -&gt; csin
19190 javaout                     -&gt; csout
19191 javadirectorin              -&gt; csdirectorin
19192 javadirectorout             -&gt; csdirectorout
19193 javainterfaces              -&gt; csinterfaces and csinterfaces_derived
19194 javabase                    -&gt; csbase
19195 javaclassmodifiers          -&gt; csclassmodifiers
19196 javacode                    -&gt; cscode
19197 javaimports                 -&gt; csimports
19198 javabody                    -&gt; csbody
19199 javafinalize                -&gt; csfinalize
19200 javadestruct                -&gt; csdestruct
19201 javadestruct_derived        -&gt; csdestruct_derived
19202 </PRE>
19203 </DIV></LI>
19204 <LI>
19205 <P>Additional typemaps:</P>
19206 <DIV class="code">
19207 <PRE>
19208 csvarin                     C# code property set typemap
19209 csvarout                    C# code property get typemap
19210 csattributes                C# attributes for attaching to proxy classes/enums
19211 </PRE>
19212 </DIV></LI>
19213 <LI>
19214 <P>Feature equivalent names:</P>
19215 <DIV class="code">
19216 <PRE>
19217 %javaconst                  -&gt; %csconst
19218 %javaconstvalue             -&gt; %csconstvalue
19219 %javamethodmodifiers        -&gt; %csmethodmodifiers
19220 </PRE>
19221 </DIV></LI>
19222 <LI>
19223 <P>Pragma equivalent names:</P>
19224 <DIV class="code">
19225 <PRE>
19226 %pragma(java)               -&gt; %pragma(csharp)
19227 jniclassbase                -&gt; imclassbase
19228 jniclassclassmodifiers      -&gt; imclassclassmodifiers
19229 jniclasscode                -&gt; imclasscode
19230 jniclassimports             -&gt; imclassimports
19231 jniclassinterfaces          -&gt; imclassinterfaces
19232 </PRE>
19233 </DIV></LI>
19234 <LI>
19235 <P>Special variable equivalent names:</P>
19236 <DIV class="code">
19237 <PRE>
19238 $javaclassname              -&gt; $csclassname
19239 $&amp;javaclassname             -&gt; $&amp;csclassname
19240 $*javaclassname             -&gt; $*csclassname
19241 $javainput                  -&gt; $csinput
19242 $jnicall                    -&gt; $imcall
19243 </PRE>
19244 </DIV></LI>
19245 <LI>
19246 <P> Unlike the &quot;javain&quot; typemap, the &quot;csin&quot; typemap does not support the
19247  'pgcpp' attribute as the C# module does not have a premature garbage
19248  collection prevention parameter. The &quot;csin&quot; typemap supports additional
19249  optional attributes called 'cshin' and 'terminator'. The 'cshin'
19250  attribute should contain the parameter type and name whenever a <A href="#java_constructor_helper_function">
19251 constructor helper function</A> is generated due to the 'pre' or 'post'
19252  attributes. The 'terminator' attribute normally just contains a closing
19253  brace for when the 'pre' attribute contains an opening brace, such as
19254  when a C# <TT>using</TT> or <TT>fixed</TT> block is started. Note that
19255  'pre', 'post', 'terminator' and 'cshin' attributes are not used for
19256  marshalling the property set. Please see the <A href="#csharp_date_marshalling">
19257 Date marshalling example</A> and <A href="#csharp_date_properties">Date
19258  marshalling of properties example</A> for further understanding of
19259  these &quot;csin&quot; applicable attributes.</P>
19260 </LI>
19261 <LI>
19262 <P> Support for asymmetric type marshalling. The 'ctype', 'imtype' and
19263  'cstype' typemaps support an optional <TT>out</TT> attribute which is
19264  used for output types. If this typemap attribute is specified, then the
19265  type specified in the attribute is used for output types and the type
19266  specified in the typemap itself is used for the input type. If this
19267  typemap attribute is not specified, then the type used for both input
19268  and output is the type specified in the typemap. An example shows that <TT>
19269 char *</TT> could be marshalled in different ways,</P>
19270 <DIV class="code">
19271 <PRE>
19272 %typemap(imtype, out=&quot;IntPtr&quot;) char * &quot;string&quot;
19273 char * function(char *);
19274 </PRE>
19275 </DIV>
19276 <P> The output type is thus IntPtr and the input type is string. The
19277  resulting intermediary C# code is:</P>
19278 <DIV class="code">
19279 <PRE>
19280 public static extern IntPtr function(string jarg1);
19281 </PRE>
19282 </DIV></LI>
19283 <LI>
19284 <P> Support for type attributes. The 'imtype' and 'cstype' typemaps can
19285  have an optional <TT>inattributes</TT> and <TT>outattributes</TT>
19286  typemap attribute. There are C# attributes and typemap attributes,
19287  don't get confused!! The C# attributes specified in these typemap
19288  attributes are generated wherever the type is used in the C# wrappers.
19289  These can be used to specify any C# attribute associated with a C/C++
19290  type, but are more typically used for the C# <TT>MarshalAs</TT>
19291  attribute. For example:</P>
19292 <DIV class="code">
19293 <PRE>
19294 %typemap(imtype,
19295          inattributes=&quot;[MarshalAs(UnmanagedType.LPStr)]&quot;,
19296          outattributes=&quot;[return: MarshalAs(UnmanagedType.LPStr)]&quot;) const char * &quot;String&quot;
19297
19298 const char * GetMsg() {}
19299 void SetMsg(const char *msg) {}
19300 </PRE>
19301 </DIV>
19302 <P> The intermediary class will then have the marshalling as specified
19303  by everything in the 'imtype' typemap:</P>
19304 <DIV class="code">
19305 <PRE>
19306 class examplePINVOKE {
19307   ...
19308   [DllImport(&quot;example&quot;, EntryPoint=&quot;CSharp_GetMsg&quot;)]
19309   [return: MarshalAs(UnmanagedType.LPStr)]
19310   public static extern String GetMsg();
19311
19312   [DllImport(&quot;example&quot;, EntryPoint=&quot;CSharp_SetMsg&quot;)]
19313   public static extern void SetMsg([MarshalAs(UnmanagedType.LPStr)]String jarg1);
19314 }
19315 </PRE>
19316 </DIV>
19317 <P> Note that the <TT>DllImport</TT> attribute is always generated,
19318  irrespective of any additional attributes specified.</P>
19319 <P> These attributes are associated with the C/C++ parameter type or
19320  return type, which is subtly different to the attribute features and
19321  typemaps covered next. Note that all these different C# attributes can
19322  be combined so that a method has more than one attribute.</P>
19323 </LI>
19324 <LI>
19325 <P> Support for attaching C# attributes to wrapped methods and
19326  variables. This is done using the <TT>%csattributes</TT> feature, see <A
19327 href="#features">%feature directives</A>. Note that C# attributes are
19328  attached to proxy classes and enums using the <TT>csattributes</TT>
19329  typemap. For example, imagine we have a custom attribute class, <TT>
19330 ThreadSafeAttribute</TT>, for labelling thread safety. The following
19331  SWIG code shows how to attach this C# attribute to some methods and the
19332  class declaration itself:</P>
19333 <DIV class="code">
19334 <PRE>
19335 %typemap(csattributes) AClass          &quot;[ThreadSafe]&quot;
19336 %csattributes AClass::AClass(double d) &quot;[ThreadSafe(false)]&quot;
19337 %csattributes AClass::AMethod()        &quot;[ThreadSafe(true)]&quot;
19338
19339 %inline %{
19340 class AClass {
19341 public:
19342   AClass(double a) {}
19343   void AMethod() {}
19344 };
19345 %}
19346 </PRE>
19347 </DIV>
19348 <P> will generate a C# proxy class:</P>
19349 <DIV class="code">
19350 <PRE>
19351 [ThreadSafe]
19352 public class AClass : IDisposable {
19353   ...
19354   [ThreadSafe(false)]
19355   public AClass(double a) ...
19356
19357   [ThreadSafe(true)]
19358   public void AMethod() ...
19359 }
19360 </PRE>
19361 </DIV>
19362 <P> If C# attributes need adding to the <TT>set</TT> or <TT>get</TT>
19363  part of C# properties, when wrapping C/C++ variables, they can be added
19364  using the 'csvarin' and 'csvarout' typemaps respectively. Note that the
19365  type used for the property is specified in the 'cstype' typemap. If the
19366  'out' attribute exists in this typemap, then the type used is from the
19367  'out' attribute.</P>
19368 </LI>
19369 <LI>
19370 <P> The intermediary classname has <TT>PINVOKE</TT> appended after the
19371  module name instead of <TT>JNI</TT>, for example <TT>modulenamePINVOKE</TT>
19372 .</P>
19373 </LI>
19374 <LI>
19375 <P> The <TT>%csmethodmodifiers</TT> feature can also be applied to
19376  variables as well as methods. In addition to the default <TT>public</TT>
19377  modifier that SWIG generates when <TT>%csmethodmodifiers</TT> is not
19378  specified, the feature will also replace the <TT>virtual</TT>/<TT>new</TT>
19379 /<TT>override</TT> modifiers that SWIG thinks is appropriate. This
19380  feature is useful for some obscure cases where SWIG might get the <TT>
19381 virtual</TT>/<TT>new</TT>/<TT>override</TT> modifiers incorrect, for
19382  example with multiple inheritance.</P>
19383 </LI>
19384 <LI> <A name="csharp_module_directive"></A>
19385 <P> The name of the intermediary class can be changed from its default,
19386  that is, the module name with PINVOKE appended after it. The module
19387  directive attribute <TT>imclassname</TT> is used to achieve this:</P>
19388 <DIV class="code">
19389 <PRE>
19390 %module (imclassname=&quot;name&quot;) modulename
19391 </PRE>
19392 </DIV>
19393 <P> If <TT>name</TT> is the same as <TT>modulename</TT> then the module
19394  class name gets changed from <TT>modulename</TT> to <TT>
19395 modulenameModule</TT>.</P>
19396 </LI>
19397 <LI> There is no additional 'premature garbage collection prevention
19398  parameter' as the marshalling of the <TT>HandleRef</TT> object takes
19399  care of ensuring a reference to the proxy class is held until the
19400  unmanaged call completed.</LI>
19401 </UL>
19402 <P><B> <TT>$dllimport</TT></B>
19403 <BR> This is a C# only special variable that can be used in typemaps,
19404  pragmas, features etc. The special variable will get translated into
19405  the value specified by the <TT>-dllimport</TT> commandline option if
19406  specified, otherwise it is equivalent to the<B> $module</B> special
19407  variable.</P>
19408 <P><B> <TT>$imclassname</TT></B>
19409 <BR> This special variable expands to the intermediary class name. For
19410  C# this is usually the same as '$modulePINVOKE' ('$moduleJNI' for
19411  Java), unless the imclassname attribute is specified in the <A href="#csharp_module_directive">
19412 %module directive</A>.</P>
19413 <P> The directory <TT>Examples/csharp</TT> has a number of simple
19414  examples. Visual Studio .NET 2003 solution and project files are
19415  available for compiling with the Microsoft .NET C# compiler on Windows.
19416  If your SWIG installation went well on a Unix environment and your C#
19417  compiler was detected, you should be able to type <TT>make</TT> in each
19418  example directory, then <TT>ilrun runme.exe</TT> (Portable.NET C#
19419  compiler) or <TT>mono runme.exe</TT> (Mono C# compiler) to run the
19420  examples. Windows users can also get the examples working using a <A href="http://www.cygwin.com">
19421 Cygwin</A> or <A href="http://www.mingw.org">MinGW</A> environment for
19422  automatic configuration of the example makefiles. Any one of the three
19423  C# compilers (Portable.NET, Mono or Microsoft) can be detected from
19424  within a Cygwin or Mingw environment if installed in your path.</P>
19425 <H2><A name="CSharp_arrays"></A>18.3 C# Arrays</H2>
19426 <P> There are various ways to pass arrays from C# to C/C++. The default
19427  wrapping treats arrays as pointers and as such simple type wrapper
19428  classes are generated, eg <TT>SWIGTYPE_p_int</TT> when wrapping the C
19429  type <TT>int []</TT> or <TT>int *</TT>. This gives a rather restricted
19430  use of the underlying unmanaged code and the most practical way to use
19431  arrays is to enhance or customise with one of the following three
19432  approaches; namely the SWIG C arrays library, P/Invoke default array
19433  marshalling or pinned arrays.</P>
19434 <H3><A name="CSharp_arrays_swig_library"></A>18.3.1 The SWIG C arrays
19435  library</H3>
19436 <P> The C arrays library keeps all the array memory in the unmanaged
19437  layer. The library is available to all language modules and is
19438  documented in the <A href="#Library_carrays">carrays.i library</A>
19439  section. Please refer to this section for details, but for convenience,
19440  the C# usage for the two examples outlined there is shown below.</P>
19441 <P> For the <TT>%array_functions</TT> example, the equivalent usage
19442  would be:</P>
19443 <DIV class="code">
19444 <PRE>
19445 SWIGTYPE_p_double a = example.new_doubleArray(10);  // Create an array
19446 for (int i=0; i&lt;10; i++)
19447   example.doubleArray_setitem(a,i,2*i);             // Set a value
19448 example.print_array(a);                             // Pass to C
19449 example.delete_doubleArray(a);                      // Destroy array
19450 </PRE>
19451 </DIV>
19452 <P> and for the <TT>%array_class</TT> example, the equivalent usage
19453  would be:</P>
19454 <DIV class="code">
19455 <PRE>
19456 doubleArray c = new doubleArray(10);    // Create double[10]
19457 for (int i=0; i&lt;10; i++)
19458   c.setitem(i, 2*i);                    // Assign values
19459 example.print_array(c.cast());          // Pass to C
19460 </PRE>
19461 </DIV>
19462 <H3><A name="CSharp_arrays_pinvoke_default_array_marshalling"></A>18.3.2
19463  Managed arrays using P/Invoke default array marshalling</H3>
19464 <P> In the P/Invoke default marshalling scheme, one needs to designate
19465  whether the invoked function will treat a managed array parameter as
19466  input, output, or both. When the function is invoked, the CLR allocates
19467  a separate chunk of memory as big as the given managed array, which is
19468  automatically released at the end of the function call. If the array
19469  parameter is marked as being input, the content of the managed array is
19470  copied into this buffer when the call is made. Correspondingly, if the
19471  array parameter is marked as being output, the contents of the reserved
19472  buffer are copied back into the managed array after the call returns. A
19473  pointer to to this buffer is passed to the native function.</P>
19474 <P> The reason for allocating a separate buffer is to leave the CLR free
19475  to relocate the managed array object during garbage collection. If the
19476  overhead caused by the copying is causing a significant performance
19477  penalty, consider pinning the managed array and passing a direct
19478  reference as described in the next section.</P>
19479 <P> For more information on the subject, see the <A href="http://msdn.microsoft.com/en-us/library/z6cfh6e6(VS.80).aspx">
19480 Default Marshaling for Arrays</A> article on MSDN.</P>
19481 <P> The P/Invoke default marshalling is supported by the <TT>
19482 arrays_csharp.i</TT> library via the INPUT, OUTPUT and INOUT typemaps.
19483  Let's look at some example usage. Consider the following C function:</P>
19484 <DIV class="code">
19485 <PRE>
19486 void myArrayCopy(int *sourceArray, int *targetArray, int nitems);
19487 </PRE>
19488 </DIV>
19489 <P> We can now instruct SWIG to use the default marshalling typemaps by</P>
19490 <DIV class="code">
19491 <PRE>
19492 %include &quot;arrays_csharp.i&quot;
19493
19494 %apply int INPUT[]  {int *sourceArray}
19495 %apply int OUTPUT[] {int *targetArray}
19496 </PRE>
19497 </DIV>
19498 <P> As a result, we get the following method in the module class:</P>
19499 <DIV class="code">
19500 <PRE>
19501 public static void myArrayCopy(int[] sourceArray, int[] targetArray, int nitems) {
19502     examplePINVOKE.myArrayCopy(sourceArray, targetArray, nitems);
19503 }
19504 </PRE>
19505 </DIV>
19506 <P> If we look beneath the surface at the corresponding intermediary
19507  class code, we see that SWIG has generated code that uses attributes
19508  (from the System.Runtime.InteropServices namespace) to tell the CLR to
19509  use default marshalling for the arrays:</P>
19510 <DIV class="code">
19511 <PRE>
19512 [DllImport(&quot;example&quot;, EntryPoint=&quot;CSharp_myArrayCopy&quot;)]
19513 public static extern void myArrayCopy([In, MarshalAs(UnmanagedType.LPArray)]int[] jarg1, 
19514                                       [Out, MarshalAs(UnmanagedType.LPArray)]int[] jarg2, int jarg3);
19515 </PRE>
19516 </DIV>
19517 <P> As an example of passing an inout array (i.e. the target function
19518  will both read from and write to the array), consider this C function
19519  that swaps a given number of elements in the given arrays:</P>
19520 <DIV class="code">
19521 <PRE>
19522 void myArraySwap(int *array1, int *array2, int nitems);
19523 </PRE>
19524 </DIV>
19525 <P> Now, we can instruct SWIG to wrap this by</P>
19526 <DIV class="code">
19527 <PRE>
19528 %include &quot;arrays_csharp.i&quot;
19529
19530 %apply int INOUT[] {int *array1}
19531 %apply int INOUT[] {int *array2}
19532 </PRE>
19533 </DIV>
19534 <P> This results in the module class method</P>
19535 <DIV class="code">
19536 <PRE>
19537   public static void myArraySwap(int[] array1, int[] array2, int nitems) {
19538     examplePINVOKE.myArraySwap(array1, array2, nitems);
19539   }
19540 </PRE>
19541 </DIV>
19542 <P> and intermediate class method</P>
19543 <DIV class="code">
19544 <PRE>
19545   [DllImport(&quot;example&quot;, EntryPoint=&quot;CSharp_myArraySwap&quot;)]
19546   public static extern void myArraySwap([In, Out, MarshalAs(UnmanagedType.LPArray)]int[] jarg1, 
19547                                         [In, Out, MarshalAs(UnmanagedType.LPArray)]int[] jarg2, int jarg3);
19548 </PRE>
19549 </DIV>
19550 <H3><A name="CSharp_arrays_pinning"></A>18.3.3 Managed arrays using
19551  pinning</H3>
19552 <P> It is also possible to pin a given array in memory (i.e. fix its
19553  location in memory), obtain a direct pointer to it, and then pass this
19554  pointer to the wrapped C/C++ function. This approach involves no
19555  copying, but it makes the work of the garbage collector harder as the
19556  managed array object can not be relocated before the fix on the array
19557  is released. You should avoid fixing arrays in memory in cases where
19558  the control may re-enter the managed side via a callback and/or another
19559  thread may produce enough garbage to trigger garbage collection.</P>
19560 <P> For more information, see the <A href="http://msdn.microsoft.com/en-us/library/f58wzh21(VS.80).aspx">
19561 fixed statement</A> in the C# language reference.</P>
19562 <P> Now let's look at an example using pinning, thus avoiding the CLR
19563  making copies of the arrays passed as parameters. The <TT>
19564 arrays_csharp.i</TT> library file again provides the required support
19565  via the <TT>FIXED</TT> typemaps. Let's use the same function from the
19566  previous section:</P>
19567 <DIV class="code">
19568 <PRE>
19569 void myArrayCopy(int *sourceArray, int *targetArray, int nitems);
19570 </PRE>
19571 </DIV>
19572 <P> We now need to declare the module class method unsafe, as we are
19573  using pointers:</P>
19574 <DIV class="code">
19575 <PRE>
19576 %csmethodmodifiers myArrayCopy &quot;public unsafe&quot;;
19577  </PRE>
19578 </DIV>
19579 <P> Apply the appropriate typemaps to the array parameters:</P>
19580 <DIV class="code">
19581 <PRE>
19582 %include &quot;arrays_csharp.i&quot;
19583
19584 %apply int FIXED[] {int *sourceArray}
19585 %apply int FIXED[] {int *targetArray}
19586 </PRE>
19587 </DIV>
19588 <P> Notice that there is no need for separate in, out or inout typemaps
19589  as is the case when using P/Invoke default marshalling.</P>
19590 <P> As a result, we get the following method in the module class:</P>
19591 <DIV class="code">
19592 <PRE>
19593   public unsafe static void myArrayCopy(int[] sourceArray, int[] targetArray, int nitems) {
19594     fixed ( int *swig_ptrTo_sourceArray = sourceArray ) {
19595     fixed ( int *swig_ptrTo_targetArray = targetArray ) {
19596     {
19597       examplePINVOKE.myArrayCopy((IntPtr)swig_ptrTo_sourceArray, (IntPtr)swig_ptrTo_targetArray, nitems);
19598     }
19599     }
19600     }
19601   }
19602 </PRE>
19603 </DIV>
19604 <P> On the method signature level the only difference to the version
19605  using P/Invoke default marshalling is the &quot;unsafe&quot; quantifier, which is
19606  required because we are handling pointers.</P>
19607 <P> Also the intermediate class method looks a little different from the
19608  default marshalling example - the method is expecting an IntPtr as the
19609  parameter type.</P>
19610 <DIV class="code">
19611 <PRE>
19612 [DllImport(&quot;example&quot;, EntryPoint=&quot;CSharp_myArrayCopy&quot;)]
19613 public static extern void myArrayCopy(IntPtr jarg1, IntPtr jarg2, int jarg3);
19614 </PRE>
19615 </DIV>
19616 <H2><A name="csharp_exceptions"></A>18.4 C# Exceptions</H2>
19617 <P> It is possible to throw a C# Exception from C/C++ code. SWIG already
19618  provides the framework for throwing C# exceptions if it is able to
19619  detect that a C++ exception could be thrown. Automatically detecting
19620  that a C++ exception could be thrown is only possible when a C++
19621  exception specification is used, see <A href="#SWIGPlus_exception_specifications">
19622 Exception specifications</A>. The <A href="#exception">Exception
19623  handling with %exception</A> section details the <TT>%exception</TT>
19624  feature. Customised code for handling exceptions with or without a C++
19625  exception specification is possible and the details follow. However
19626  anyone wishing to do this should be familiar with the contents of the
19627  sections referred to above.</P>
19628 <P> Unfortunately a C# exception cannot simply be thrown from unmanaged
19629  code for a variety of reasons. Most notably being that throwing a C#
19630  exception results in exceptions being thrown across the C PInvoke
19631  interface and C does not understand exceptions. The design revolves
19632  around a C# exception being constructed and stored as a pending
19633  exception, to be thrown only when the unmanaged code has completed.
19634  Implementing this is a tad involved and there are thus some unusual
19635  typemap constructs. Some practical examples follow and they should be
19636  read in conjunction with the rest of this section.</P>
19637 <P> First some details about the design that must be followed. Each
19638  typemap or feature that generates<B> unmanaged code</B> supports an
19639  attribute called <TT>canthrow</TT>. This is simply a flag which when
19640  set indicates that the code in the typemap/feature has code which might
19641  want to throw a C# exception. The code in the typemap/feature can then
19642  raise a C# exception by calling one of the C functions, <TT>
19643 SWIG_CSharpSetPendingException()</TT> or <TT>
19644 SWIG_CSharpSetPendingExceptionArgument()</TT>. When called, the function
19645  makes a callback into the managed world via a delegate. The callback
19646  creates and stores an exception ready for throwing when the unmanaged
19647  code has finished. The typemap/feature unmanaged code is then expected
19648  to force an immediate return from the unmanaged wrapper function, so
19649  that the pending managed exception can then be thrown. The support code
19650  has been carefully designed to be efficient as well as thread-safe.
19651  However to achieve the goal of efficiency requires some optional code
19652  generation in the<B> managed code</B> typemaps. Code to check for
19653  pending exceptions is generated if and only if the unmanaged code has
19654  code to set a pending exception, that is if the <TT>canthrow</TT>
19655  attribute is set. The optional managed code is generated using the <TT>
19656 excode</TT> typemap attribute and <TT>$excode</TT> special variable in
19657  the relevant managed code typemaps. Simply, if any relevant unmanaged
19658  code has the <TT>canthrow</TT> attribute set, then any occurrences of <TT>
19659 $excode</TT> is replaced with the code in the <TT>excode</TT> attribute.
19660  If the <TT>canthrow</TT> attribute is not set, then any occurrences of <TT>
19661 $excode</TT> are replaced with nothing.</P>
19662 <P> The prototypes for the <TT>SWIG_CSharpSetPendingException()</TT> and
19663  <TT>SWIG_CSharpSetPendingExceptionArgument()</TT> functions are</P>
19664 <DIV class="code">
19665 <PRE>
19666 static void SWIG_CSharpSetPendingException(SWIG_CSharpExceptionCodes code,
19667                                            const char *msg);
19668
19669 static void SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpExceptionArgumentCodes code,
19670                                                    const char *msg,
19671                                                    const char *param_name);
19672 </PRE>
19673 </DIV>
19674 <P> The first parameter defines which .NET exceptions can be thrown:</P>
19675 <DIV class="code">
19676 <PRE>
19677 typedef enum {
19678   SWIG_CSharpApplicationException,
19679   SWIG_CSharpArithmeticException,
19680   SWIG_CSharpDivideByZeroException,
19681   SWIG_CSharpIndexOutOfRangeException,
19682   SWIG_CSharpInvalidCastException,
19683   SWIG_CSharpInvalidOperationException,
19684   SWIG_CSharpIOException,
19685   SWIG_CSharpNullReferenceException,
19686   SWIG_CSharpOutOfMemoryException,
19687   SWIG_CSharpOverflowException,
19688   SWIG_CSharpSystemException
19689 } SWIG_CSharpExceptionCodes;
19690
19691 typedef enum {
19692   SWIG_CSharpArgumentException,
19693   SWIG_CSharpArgumentNullException,
19694   SWIG_CSharpArgumentOutOfRangeException,
19695 } SWIG_CSharpExceptionArgumentCodes;
19696 </PRE>
19697 </DIV>
19698 <P> where, for example, <TT>SWIG_CSharpApplicationException</TT>
19699  corresponds to the .NET exception, <TT>ApplicationException</TT>. The <TT>
19700 msg</TT> and <TT>param_name</TT> parameters contain the C# exception
19701  message and parameter name associated with the exception.</P>
19702 <P> The <TT>%exception</TT> feature in C# has the <TT>canthrow</TT>
19703  attribute set. The <TT>%csnothrowexception</TT> feature is like <TT>
19704 %exception</TT>, but it does not have the <TT>canthrow</TT> attribute
19705  set so should only be used when a C# exception is not created.</P>
19706 <H3><A name="csharp_exception_example_check_typemap"></A>18.4.1 C#
19707  exception example using &quot;check&quot; typemap</H3>
19708 <P> Lets say we have the following simple C++ method:</P>
19709 <DIV class="code">
19710 <PRE>
19711 void positivesonly(int number);
19712 </PRE>
19713 </DIV>
19714 <P> and we want to check that the input <TT>number</TT> is always
19715  positive and if not throw a C# <TT>ArgumentOutOfRangeException</TT>.
19716  The &quot;check&quot; typemap is designed for checking input parameters. Below
19717  you will see the <TT>canthrow</TT> attribute is set because the code
19718  contains a call to <TT>SWIG_CSharpSetPendingExceptionArgument()</TT>.
19719  The full example follows:</P>
19720 <DIV class="code">
19721 <PRE>
19722 %module example
19723
19724 %typemap(check, canthrow=1) int number %{
19725 if ($1 &lt; 0) {
19726   SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentOutOfRangeException,
19727                                          &quot;only positive numbers accepted&quot;, &quot;number&quot;);
19728   return $null;
19729 }
19730 // SWIGEXCODE is a macro used by many other csout typemaps
19731 %define SWIGEXCODE
19732  &quot;\n    if ($modulePINVOKE.SWIGPendingException.Pending)&quot;
19733  &quot;\n      throw $modulePINVOKE.SWIGPendingException.Retrieve();&quot;
19734 %enddef
19735 %typemap(csout, excode=SWIGEXCODE) void {
19736     $imcall;$excode
19737   }
19738 %}
19739
19740 %inline %{
19741
19742 void positivesonly(int number) {
19743 }
19744
19745 %}
19746 </PRE>
19747 </DIV>
19748 <P> When the following C# code is executed:</P>
19749 <DIV class="code">
19750 <PRE>
19751 public class runme {
19752     static void Main() {
19753       example.positivesonly(-1);
19754     }
19755 }
19756 </PRE>
19757 </DIV>
19758 <P> The exception is thrown:</P>
19759 <DIV class="code">
19760 <PRE>
19761 Unhandled Exception: System.ArgumentOutOfRangeException: only positive numbers accepted
19762 Parameter name: number
19763 in &lt;0x00034&gt; example:positivesonly (int)
19764 in &lt;0x0000c&gt; runme:Main ()
19765 </PRE>
19766 </DIV>
19767 <P> Now let's analyse the generated code to gain a fuller understanding
19768  of the typemaps. The generated unmanaged C++ code is:</P>
19769 <DIV class="code">
19770 <PRE>
19771 SWIGEXPORT void SWIGSTDCALL CSharp_positivesonly(int jarg1) {
19772     int arg1 ;
19773     
19774     arg1 = (int)jarg1; 
19775     
19776     if (arg1 &lt; 0) {
19777         SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentOutOfRangeException,
19778                                                &quot;only positive numbers accepted&quot;, &quot;number&quot;);
19779         return ;
19780     }
19781     
19782     positivesonly(arg1);
19783     
19784 }
19785 </PRE>
19786 </DIV>
19787 <P> This largely comes from the &quot;check&quot; typemap. The managed code in the
19788  module class is:</P>
19789 <DIV class="code">
19790 <PRE>
19791 public class example {
19792   public static void positivesonly(int number) {
19793     examplePINVOKE.positivesonly(number);
19794     if (examplePINVOKE.SWIGPendingException.Pending)
19795       throw examplePINVOKE.SWIGPendingException.Retrieve();
19796   }
19797
19798 }
19799 </PRE>
19800 </DIV>
19801 <P> This comes largely from the &quot;csout&quot; typemap.</P>
19802 <P> The &quot;csout&quot; typemap is the same as the default void &quot;csout&quot; typemap
19803  so is not strictly necessary for the example. However, it is shown to
19804  demonstrate what managed output code typemaps should contain, that is,
19805  a <TT>$excode</TT> special variable and an <TT>excode</TT> attribute.
19806  Also note that <TT>$excode</TT> is expanded into the code held in the <TT>
19807 excode</TT> attribute. The <TT>$imcall</TT> as always expands into <TT>
19808 examplePINVOKE.positivesonly(number)</TT>. The exception support code in
19809  the intermediary class, <TT>examplePINVOKE</TT>, is not shown, but is
19810  contained within the inner classes, <TT>SWIGPendingException</TT> and <TT>
19811 SWIGExceptionHelper</TT> and is always generated. These classes can be
19812  seen in any of the generated wrappers. However, all that is required of
19813  a user is as demonstrated in the &quot;csin&quot; typemap above. That is, is to
19814  check <TT>SWIGPendingException.Pending</TT> and to throw the exception
19815  returned by <TT>SWIGPendingException.Retrieve()</TT>.</P>
19816 <P> If the &quot;check&quot; typemap did not exist, then the following module
19817  class would instead be generated:</P>
19818 <DIV class="code">
19819 <PRE>
19820 public class example {
19821   public static void positivesonly(int number) {
19822     examplePINVOKE.positivesonly(number);
19823   }
19824
19825 }
19826 </PRE>
19827 </DIV>
19828 <P> Here we see the pending exception checking code is omitted. In fact,
19829  the code above would be generated if the <TT>canthrow</TT> attribute
19830  was not in the &quot;check&quot; typemap, such as:</P>
19831 <DIV class="code">
19832 <PRE>
19833 %typemap(check) int number %{
19834 if ($1 &lt; 0) {
19835   SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentOutOfRangeException,
19836                                          &quot;only positive numbers accepted&quot;, &quot;number&quot;);
19837   return $null;
19838 }
19839 %}
19840 </PRE>
19841 </DIV>
19842 <P> Note that if SWIG detects you have used <TT>
19843 SWIG_CSharpSetPendingException()</TT> or <TT>
19844 SWIG_CSharpSetPendingExceptionArgument()</TT> without setting the <TT>
19845 canthrow</TT> attribute you will get a warning message similar to</P>
19846 <DIV class="code">
19847 <PRE>
19848 example.i:21: Warning(845): Unmanaged code contains a call to a SWIG_CSharpSetPendingException
19849 method and C# code does not handle pending exceptions via the canthrow attribute.
19850 </PRE>
19851 </DIV>
19852 <P> Actually it will issue this warning for any function beginning with <TT>
19853 SWIG_CSharpSetPendingException</TT>.</P>
19854 <H3><A name="csharp_exception_example_percent_exception"></A>18.4.2 C#
19855  exception example using %exception</H3>
19856 <P> Let's consider a similar, but more common example that throws a C++
19857  exception from within a wrapped function. We can use <TT>%exception</TT>
19858  as mentioned in <A href="#exception">Exception handling with %exception</A>
19859 .</P>
19860 <DIV class="code">
19861 <PRE>
19862 %exception negativesonly(int value) %{
19863 try {
19864   $action
19865 } catch (std::out_of_range e) {
19866   SWIG_CSharpSetPendingException(SWIG_CSharpApplicationException, e.what());
19867 }
19868 %}
19869
19870 %inline %{
19871 #include &lt;stdexcept&gt;
19872 void negativesonly(int value) {
19873   if (value &gt;= 0)
19874     throw std::out_of_range(&quot;number should be negative&quot;);
19875 }
19876 %}
19877 </PRE>
19878 </DIV>
19879 <P> The generated unmanaged code this time catches the C++ exception and
19880  converts it into a C# <TT>ApplicationException</TT>.</P>
19881 <DIV class="code">
19882 <PRE>
19883 SWIGEXPORT void SWIGSTDCALL CSharp_negativesonly(int jarg1) {
19884     int arg1 ;
19885     
19886     arg1 = (int)jarg1; 
19887     
19888     try {
19889         negativesonly(arg1);
19890         
19891     } catch (std::out_of_range e) {
19892         SWIG_CSharpSetPendingException(SWIG_CSharpApplicationException, e.what());
19893         return ;
19894     }
19895     
19896 }
19897 </PRE>
19898 </DIV>
19899 <P> The managed code generated does check for the pending exception as
19900  mentioned earlier as the C# version of <TT>%exception</TT> has the <TT>
19901 canthrow</TT> attribute set by default:</P>
19902 <DIV class="code">
19903 <PRE>
19904   public static void negativesonly(int value) {
19905     examplePINVOKE.negativesonly(value);
19906     if (examplePINVOKE.SWIGPendingException.Pending)
19907       throw examplePINVOKE.SWIGPendingException.Retrieve();
19908   }
19909 </PRE>
19910 </DIV>
19911 <H3><A name="csharp_exception_example_exception_specifications"></A>
19912 18.4.3 C# exception example using exception specifications</H3>
19913 <P> When C++ exception specifications are used, SWIG is able to detect
19914  that the method might throw an exception. By default SWIG will
19915  automatically generate code to catch the exception and convert it into
19916  a managed <TT>ApplicationException</TT>, as defined by the default
19917  &quot;throws&quot; typemaps. The following example has a user supplied &quot;throws&quot;
19918  typemap which is used whenever an exception specification contains a <TT>
19919 std::out_of_range</TT>, such as the <TT>evensonly</TT> method below.</P>
19920 <DIV class="code">
19921 <PRE>
19922 %typemap(throws, canthrow=1) std::out_of_range {
19923   SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentException, $1.what(), NULL);
19924   return $null;
19925 }
19926
19927 %inline %{
19928 #include &lt;stdexcept&gt;
19929 void evensonly(int input) throw (std::out_of_range) {
19930   if (input%2 != 0)
19931     throw std::out_of_range(&quot;number is not even&quot;);
19932 }
19933 %}
19934 </PRE>
19935 </DIV>
19936 <P> Note that the type for the throws typemap is the type in the
19937  exception specification. SWIG generates a try catch block with the
19938  throws typemap code in the catch handler.</P>
19939 <DIV class="code">
19940 <PRE>
19941 SWIGEXPORT void SWIGSTDCALL CSharp_evensonly(int jarg1) {
19942     int arg1 ;
19943     
19944     arg1 = (int)jarg1; 
19945     try {
19946         evensonly(arg1);
19947     }
19948     catch(std::out_of_range &amp;_e) {
19949       {
19950           SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentException, (&amp;_e)-&gt;what(), NULL);
19951           return ;
19952       }
19953     }
19954     
19955 }
19956 </PRE>
19957 </DIV>
19958 <P> Multiple catch handlers are generated should there be more than one
19959  exception specifications declared.</P>
19960 <H3><A name="csharp_custom_application_exception"></A>18.4.4 Custom C#
19961  ApplicationException example</H3>
19962 <P> This example involves a user defined exception. The conventional
19963  .NET exception handling approach is to create a custom <TT>
19964 ApplicationException</TT> and throw it in your application. The goal in
19965  this example is to convert the STL <TT>std::out_of_range</TT> exception
19966  into one of these custom .NET exceptions.</P>
19967 <P> The default exception handling is quite easy to use as the <TT>
19968 SWIG_CSharpSetPendingException()</TT> and <TT>
19969 SWIG_CSharpSetPendingExceptionArgument()</TT> methods are provided by
19970  SWIG. However, for a custom C# exception, the boiler plate code that
19971  supports these functions needs replicating. In essence this consists of
19972  some C/C++ code and C# code. The C/C++ code can be generated into the
19973  wrapper file using the <TT>%insert(runtime)</TT> directive and the C#
19974  code can be generated into the intermediary class using the <TT>
19975 imclasscode</TT> pragma as follows:</P>
19976 <DIV class="code">
19977 <PRE>
19978 %insert(runtime) %{
19979   // Code to handle throwing of C# CustomApplicationException from C/C++ code.
19980   // The equivalent delegate to the callback, CSharpExceptionCallback_t, is CustomExceptionDelegate
19981   // and the equivalent customExceptionCallback instance is customDelegate
19982   typedef void (SWIGSTDCALL* CSharpExceptionCallback_t)(const char *);
19983   CSharpExceptionCallback_t customExceptionCallback = NULL;
19984
19985   extern &quot;C&quot; SWIGEXPORT
19986   void SWIGSTDCALL CustomExceptionRegisterCallback(CSharpExceptionCallback_t customCallback) {
19987     customExceptionCallback = customCallback;
19988   }
19989
19990   // Note that SWIG detects any method calls named starting with
19991   // SWIG_CSharpSetPendingException for warning 845
19992   static void SWIG_CSharpSetPendingExceptionCustom(const char *msg) {
19993     customExceptionCallback(msg);
19994   }
19995 %}
19996
19997 %pragma(csharp) imclasscode=%{
19998   class CustomExceptionHelper {
19999     // C# delegate for the C/C++ customExceptionCallback
20000     public delegate void CustomExceptionDelegate(string message);
20001     static CustomExceptionDelegate customDelegate =
20002                                    new CustomExceptionDelegate(SetPendingCustomException);
20003
20004     [DllImport(&quot;$dllimport&quot;, EntryPoint=&quot;CustomExceptionRegisterCallback&quot;)]
20005     public static extern
20006            void CustomExceptionRegisterCallback(CustomExceptionDelegate customCallback);
20007
20008     static void SetPendingCustomException(string message) {
20009       SWIGPendingException.Set(new CustomApplicationException(message));
20010     }
20011
20012     static CustomExceptionHelper() {
20013       CustomExceptionRegisterCallback(customDelegate);
20014     }
20015   }
20016   static CustomExceptionHelper exceptionHelper = new CustomExceptionHelper();
20017 %}
20018 </PRE>
20019 </DIV>
20020 <P> The method stored in the C# delegate instance, <TT>customDelegate</TT>
20021  is what gets called by the C/C++ callback. However, the equivalent to
20022  the C# delegate, that is the C/C++ callback, needs to be assigned
20023  before any unmanaged code is executed. This is achieved by putting the
20024  initialisation code in the intermediary class. Recall that the
20025  intermediary class contains all the PInvoke methods, so the static
20026  variables in the intermediary class will be initialised before any of
20027  the PInvoke methods in this class are called. The <TT>exceptionHelper</TT>
20028  static variable ensures the C/C++ callback is initialised with the
20029  value in <TT>customDelegate</TT> by calling the <TT>
20030 CustomExceptionRegisterCallback</TT> method in the <TT>
20031 CustomExceptionHelper</TT> static constructor. Once this has been done,
20032  unmanaged code can make callbacks into the managed world as <TT>
20033 customExceptionCallback</TT> will be initialised with a valid
20034  callback/delegate. Any calls to <TT>
20035 SWIG_CSharpSetPendingExceptionCustom()</TT> will make the callback to
20036  create the pending exception in the same way that <TT>
20037 SWIG_CSharpSetPendingException()</TT> and <TT>
20038 SWIG_CSharpSetPendingExceptionArgument()</TT> does. In fact the method
20039  has been similarly named so that SWIG can issue the warning about
20040  missing <TT>canthrow</TT> attributes as discussed earlier. It is an
20041  invaluable warning as it is easy to forget the <TT>canthrow</TT>
20042  attribute when writing typemaps/features.</P>
20043 <P> The <TT>SWIGPendingException</TT> helper class is not shown, but is
20044  generated as an inner class into the intermediary class. It stores the
20045  pending exception in Thread Local Storage so that the exception
20046  handling mechanism is thread safe.</P>
20047 <P> The boiler plate code above must be used in addition to a
20048  handcrafted <TT>CustomApplicationException</TT>:</P>
20049 <DIV class="code">
20050 <PRE>
20051 // Custom C# Exception
20052 class CustomApplicationException : System.ApplicationException {
20053   public CustomApplicationException(string message) 
20054     : base(message) {
20055   }
20056 }
20057 </PRE>
20058 </DIV>
20059 <P> and the SWIG interface code:</P>
20060 <DIV class="code">
20061 <PRE>
20062 %typemap(throws, canthrow=1) std::out_of_range {
20063   SWIG_CSharpSetPendingExceptionCustom($1.what());
20064   return $null;
20065 }
20066
20067 %inline %{
20068 void oddsonly(int input) throw (std::out_of_range) {
20069   if (input%2 != 1)
20070     throw std::out_of_range(&quot;number is not odd&quot;);
20071 }
20072 %}
20073 </PRE>
20074 </DIV>
20075 <P> The &quot;throws&quot; typemap now simply calls our new <TT>
20076 SWIG_CSharpSetPendingExceptionCustom()</TT> function so that the
20077  exception can be caught, as such:</P>
20078 <DIV class="code">
20079 <PRE>
20080 try {
20081   example.oddsonly(2);
20082 } catch (CustomApplicationException e) {
20083   ...
20084 }
20085 </PRE>
20086 </DIV>
20087 <H2><A name="csharp_directors"></A>18.5 C# Directors</H2>
20088 <P> The SWIG directors feature adds extra code to the generated C# proxy
20089  classes that enable these classes to be used in cross-language
20090  polymorphism. Essentially, it enables unmanaged C++ code to call back
20091  into managed code for virtual methods so that a C# class can derive
20092  from a wrapped C++ class.</P>
20093 <P> The following sections provide information on the C# director
20094  implementation and contain most of the information required to use the
20095  C# directors. However, the <A href="#java_directors">Java directors</A>
20096  section should also be read in order to gain more insight into
20097  directors.</P>
20098 <H3><A name="csharp_directors_example"></A>18.5.1 Directors example</H3>
20099 <P> Imagine we are wrapping a C++ base class, <TT>Base</TT>, from which
20100  we would like to inherit in C#. Such a class is shown below as well as
20101  another class, <TT>Caller</TT>, which calls the virtual method <TT>
20102 UIntMethod</TT> from pure unmanaged C++ code.</P>
20103 <DIV class="code">
20104 <PRE>
20105 // file: example.h
20106 class Base {
20107 public:
20108   virtual ~Base() {}
20109
20110   virtual unsigned int UIntMethod(unsigned int x) {
20111     std::cout &lt;&lt; &quot;Base - UIntMethod(&quot; &lt;&lt; x &lt;&lt; &quot;)&quot; &lt;&lt; std::endl;
20112     return x;
20113   }
20114   virtual void BaseBoolMethod(const Base &amp;b, bool flag) {}
20115 };
20116
20117 class Caller {
20118 public:
20119   Caller(): m_base(0) {}
20120   ~Caller() { delBase(); }
20121   void set(Base *b) { delBase(); m_base = b; }
20122   void reset() { m_base = 0; }
20123   unsigned int UIntMethodCall(unsigned int x) { return m_base-&gt;UIntMethod(x); }
20124
20125 private:
20126   Base *m_base;
20127   void delBase() { delete m_base; m_base = 0; }
20128 };
20129 </PRE>
20130 </DIV>
20131 <P> The director feature is turned off by default and the following
20132  simple interface file shows how directors are enabled for the class <TT>
20133 Base</TT>.</P>
20134 <DIV class="code">
20135 <PRE>
20136 /* File : example.i */
20137 %module(directors=&quot;1&quot;) example
20138 %{
20139 #include &quot;example.h&quot;
20140 %}
20141
20142 %feature(&quot;director&quot;) Base;
20143
20144 %include &quot;example.h&quot;
20145 </PRE>
20146 </DIV>
20147 <P> The following is a C# class inheriting from <TT>Base</TT>:</P>
20148 <DIV class="code">
20149 <PRE>
20150 public class CSharpDerived : Base
20151 {
20152   public override uint UIntMethod(uint x)
20153   {
20154     Console.WriteLine(&quot;CSharpDerived - UIntMethod({0})&quot;, x);
20155     return x;
20156   }
20157 }
20158 </PRE>
20159 </DIV>
20160 <P> The <TT>Caller</TT> class can demonstrate the <TT>UIntMethod</TT>
20161  method being called from unmanaged code using the following C# code:</P>
20162 <DIV class="targetlang">
20163 <PRE>
20164 public class runme
20165 {
20166   static void Main() 
20167   {
20168     Caller myCaller = new Caller();
20169
20170     // Test pure C++ class
20171     using (Base myBase = new Base())
20172     {
20173       makeCalls(myCaller, myBase);
20174     }
20175
20176     // Test director / C# derived class
20177     using (Base myBase = new CSharpDerived())
20178     {
20179       makeCalls(myCaller, myBase);
20180     }
20181   }
20182
20183   static void makeCalls(Caller myCaller, Base myBase)
20184   {
20185     myCaller.set(myBase);
20186     myCaller.UIntMethodCall(123);
20187     myCaller.reset();
20188   }
20189 }
20190 </PRE>
20191 </DIV>
20192 <P> If the above is run, the output is then:</P>
20193 <DIV class="shell">
20194 <PRE>
20195 Base - UIntMethod(123)
20196 CSharpDerived - UIntMethod(123)
20197 </PRE>
20198 </DIV>
20199 <H3><A name="csharp_directors_implementation"></A>18.5.2 Directors
20200  implementation</H3>
20201 <P> The previous section demonstrated a simple example where the virtual
20202  <TT>UIntMethod</TT> method was called from C++ code, even when the
20203  overridden method is implemented in C#. The intention of this section
20204  is to gain an insight into how the director feature works. It shows the
20205  generated code for the two virtual methods, <TT>UIntMethod</TT> and <TT>
20206 BaseBoolMethod</TT>, when the director feature is enabled for the <TT>
20207 Base</TT> class.</P>
20208 <P> Below is the generated C# <TT>Base</TT> director class.</P>
20209 <DIV class="code">
20210 <PRE>
20211 using System;
20212 using System.Runtime.InteropServices;
20213
20214 public class Base : IDisposable {
20215   private HandleRef swigCPtr;
20216   protected bool swigCMemOwn;
20217
20218   internal Base(IntPtr cPtr, bool cMemoryOwn) {
20219     swigCMemOwn = cMemoryOwn;
20220     swigCPtr = new HandleRef(this, cPtr);
20221   }
20222
20223   internal static HandleRef getCPtr(Base obj) {
20224     return (obj == null) ? new HandleRef(null, IntPtr.Zero) : obj.swigCPtr;
20225   }
20226
20227   ~Base() {
20228     Dispose();
20229   }
20230
20231   public virtual void Dispose() {
20232     lock(this) {
20233       if(swigCPtr.Handle != IntPtr.Zero &amp;&amp; swigCMemOwn) {
20234         swigCMemOwn = false;
20235         examplePINVOKE.delete_Base(swigCPtr);
20236       }
20237       swigCPtr = new HandleRef(null, IntPtr.Zero);
20238       GC.SuppressFinalize(this);
20239     }
20240   }
20241
20242   public virtual uint UIntMethod(uint x) {
20243     uint ret = examplePINVOKE.Base_UIntMethod(swigCPtr, x);
20244     return ret;
20245   }
20246
20247   public virtual void BaseBoolMethod(Base b, bool flag) {
20248     examplePINVOKE.Base_BaseBoolMethod(swigCPtr, Base.getCPtr(b), flag);
20249     if (examplePINVOKE.SWIGPendingException.Pending)
20250       throw examplePINVOKE.SWIGPendingException.Retrieve();
20251   }
20252
20253   public Base() : this(examplePINVOKE.new_Base(), true) {
20254     SwigDirectorConnect();
20255   }
20256
20257   private void SwigDirectorConnect() {
20258     if (SwigDerivedClassHasMethod(&quot;UIntMethod&quot;, swigMethodTypes0))
20259       swigDelegate0 = new SwigDelegateBase_0(SwigDirectorUIntMethod);
20260     if (SwigDerivedClassHasMethod(&quot;BaseBoolMethod&quot;, swigMethodTypes1))
20261       swigDelegate1 = new SwigDelegateBase_1(SwigDirectorBaseBoolMethod);
20262     examplePINVOKE.Base_director_connect(swigCPtr, swigDelegate0, swigDelegate1);
20263   }
20264
20265   private bool SwigDerivedClassHasMethod(string methodName, Type[] methodTypes) {
20266     System.Reflection.MethodInfo methodInfo = this.GetType().GetMethod(methodName, methodTypes);
20267     bool hasDerivedMethod = methodInfo.DeclaringType.IsSubclassOf(typeof(Base));
20268     return hasDerivedMethod;
20269   }
20270
20271   private uint SwigDirectorUIntMethod(uint x) {
20272     return UIntMethod(x);
20273   }
20274
20275   private void SwigDirectorBaseBoolMethod(IntPtr b, bool flag) {
20276     BaseBoolMethod(new Base(b, false), flag);
20277   }
20278
20279   internal delegate uint SwigDelegateBase_0(uint x);
20280   internal delegate void SwigDelegateBase_1(IntPtr b, bool flag);
20281
20282   private SwigDelegateBase_0 swigDelegate0;
20283   private SwigDelegateBase_1 swigDelegate1;
20284
20285   private static Type[] swigMethodTypes0 = new Type[] { typeof(uint) };
20286   private static Type[] swigMethodTypes1 = new Type[] { typeof(Base), typeof(bool) };
20287 }
20288 </PRE>
20289 </DIV>
20290 <P> Everything from the <TT>SwigDirectorConnect()</TT> method and below
20291  is code that is only generated when directors are enabled. The design
20292  comprises a C# delegate being initialised for each virtual method on
20293  construction of the class. Let's examine the <TT>BaseBoolMethod</TT>.</P>
20294 <P> In the <TT>Base</TT> constructor a call is made to <TT>
20295 SwigDirectorConnect()</TT> which contains the initialisation code for
20296  all the virtual methods. It uses a support method, <TT>
20297 SwigDerivedClassHasMethod()</TT>, which simply uses reflection to
20298  determine if the named method, BaseBoolMethod, with the list of
20299  required parameter types, exists in a subclass. If it does not exist,
20300  the delegate is not initialised as there is no need for unmanaged code
20301  to call back into managed C# code. However, if there is an overridden
20302  method in any subclass, the delegate is required. It is then
20303  initialised to the <TT>SwigDirectorBaseBoolMethod</TT> which in turn
20304  will call <TT>BaseBoolMethod</TT> if invoked. The delegate is not
20305  initialised to the <TT>BaseBoolMethod</TT> directly as quite often
20306  types will need marshalling from the unmanaged type to the managed type
20307  in which case an intermediary method (<TT>SwigDirectorBaseBoolMethod</TT>
20308 ) is required for the marshalling. In this case, the C# <TT>Base</TT>
20309  class needs to be created from the unmanaged <TT>IntPtr</TT> type.</P>
20310 <P> The last thing that <TT>SwigDirectorConnect()</TT> does is to pass
20311  the delegates to the unmanaged code. It calls the intermediary method <TT>
20312 Base_director_connect()</TT> which is really a call to the C function <TT>
20313 CSharp_Base_director_connect()</TT>. This method simply maps each C#
20314  delegate onto a C function pointer.</P>
20315 <DIV class="code">
20316 <PRE>
20317 SWIGEXPORT void SWIGSTDCALL CSharp_Base_director_connect(void *objarg, 
20318                                         SwigDirector_Base::SWIG_Callback0_t callback0,
20319                                         SwigDirector_Base::SWIG_Callback1_t callback1) {
20320   Base *obj = (Base *)objarg;
20321   SwigDirector_Base *director = dynamic_cast&lt;SwigDirector_Base *&gt;(obj);
20322   if (director) {
20323     director-&gt;swig_connect_director(callback0, callback1);
20324   }
20325 }
20326
20327 class SwigDirector_Base : public Base, public Swig::Director {
20328 public:
20329     SwigDirector_Base();
20330     virtual unsigned int UIntMethod(unsigned int x);
20331     virtual ~SwigDirector_Base();
20332     virtual void BaseBoolMethod(Base const &amp;b, bool flag);
20333
20334     typedef unsigned int (SWIGSTDCALL* SWIG_Callback0_t)(unsigned int);
20335     typedef void (SWIGSTDCALL* SWIG_Callback1_t)(void *, unsigned int);
20336     void swig_connect_director(SWIG_Callback0_t callbackUIntMethod, 
20337                                SWIG_Callback1_t callbackBaseBoolMethod);
20338
20339 private:
20340     SWIG_Callback0_t swig_callbackUIntMethod;
20341     SWIG_Callback1_t swig_callbackBaseBoolMethod;
20342     void swig_init_callbacks();
20343 };
20344
20345 void SwigDirector_Base::swig_connect_director(SWIG_Callback0_t callbackUIntMethod, 
20346                                               SWIG_Callback1_t callbackBaseBoolMethod) {
20347   swig_callbackUIntMethod = callbackUIntMethod;
20348   swig_callbackBaseBoolMethod = callbackBaseBoolMethod;
20349 }
20350 </PRE>
20351 </DIV>
20352 <P> Note that for each director class SWIG creates an unmanaged director
20353  class for making the callbacks. For example <TT>Base</TT> has <TT>
20354 SwigDirector_Base</TT> and <TT>SwigDirector_Base</TT> is derived from <TT>
20355 Base</TT>. Should a C# class be derived from <TT>Base</TT>, the
20356  underlying C++ <TT>SwigDirector_Base</TT> is created rather than <TT>
20357 Base</TT>. The <TT>SwigDirector_Base</TT> class then implements all the
20358  virtual methods, redirecting calls up to managed code if the
20359  callback/delegate is non-zero. The implementation of <TT>
20360 SwigDirector_Base::BaseBoolMethod</TT> shows this - the callback is made
20361  by invoking the <TT>swig_callbackBaseBoolMethod</TT> function pointer:</P>
20362 <DIV class="code">
20363 <PRE>
20364 void SwigDirector_Base::BaseBoolMethod(Base const &amp;b, bool flag) {
20365   void * jb = 0 ;
20366   unsigned int jflag  ;
20367   
20368   if (!swig_callbackBaseBoolMethod) {
20369     Base::BaseBoolMethod(b,flag);
20370     return;
20371   } else {
20372     jb = (Base *) &amp;b; 
20373     jflag = flag;
20374     swig_callbackBaseBoolMethod(jb, jflag);
20375   }
20376 }
20377 </PRE>
20378 </DIV>
20379 <H3><A name="csharp_director_caveats"></A>18.5.3 Director caveats</H3>
20380 <P> There is a subtle gotcha with directors. If default parameters are
20381  used, it is recommended to follow a pattern of always calling a single
20382  method in any C# derived class. An example will clarify this and the
20383  reasoning behind the recommendation. Consider the following C++ class
20384  wrapped as a director class:</P>
20385 <DIV class="code">
20386 <PRE>
20387 class Defaults {
20388 public:
20389   virtual ~Defaults();
20390   virtual void DefaultMethod(int a=-100);
20391 };
20392 </PRE>
20393 </DIV>
20394 <P> Recall that C++ methods with default parameters generate overloaded
20395  methods for each defaulted parameter, so a C# derived class can be
20396  created with two <TT>DefaultMethod</TT> override methods:</P>
20397 <DIV class="code">
20398 <PRE>
20399 public class CSharpDefaults : Defaults
20400 {
20401   public override void DefaultMethod()
20402   {
20403     DefaultMethod(-100); // note C++ default value used
20404   }
20405   public override void DefaultMethod(int x)
20406   {
20407   }
20408 }
20409 </PRE>
20410 </DIV>
20411 <P> It may not be clear at first, but should a user intend to call <TT>
20412 CSharpDefaults.DefaultMethod()</TT> from C++, a call is actually made to
20413  <TT>CSharpDefaults.DefaultMethod(int)</TT>. This is because the initial
20414  call is made in C++ and therefore the <TT>DefaultMethod(int)</TT>
20415  method will be called as is expected with C++ calls to methods with
20416  defaults, with the default being set to -100. The callback/delegate
20417  matching this method is of course the overloaded method <TT>
20418 DefaultMethod(int)</TT>. However, a call from C# to <TT>
20419 CSharpDefaults.DefaultMethod()</TT> will of course call this exact
20420  method and in order for behaviour to be consistent with calls from C++,
20421  the implementation should pass the call on to <TT>
20422 CSharpDefaults.DefaultMethod(int)</TT>using the C++ default value, as
20423  shown above.</P>
20424 <H2><A name="csharp_typemap_examples"></A>18.6 C# Typemap examples</H2>
20425  This section includes a few examples of typemaps. For more examples,
20426  you might look at the files &quot;<TT>csharp.swg</TT>&quot; and &quot;<TT>typemaps.i</TT>
20427 &quot; in the SWIG library.
20428 <H3><A name="csharp_memory_management_member_variables"></A>18.6.1
20429  Memory management when returning references to member variables</H3>
20430 <P> This example shows how to prevent premature garbage collection of
20431  objects when the underlying C++ class returns a pointer or reference to
20432  a member variable. The example is a direct equivalent to this <A href="#java_memory_management_objects">
20433 Java equivalent</A>.</P>
20434 <P> Consider the following C++ code:</P>
20435 <DIV class="code">
20436 <PRE>
20437 struct Wheel {
20438   int size;
20439   Wheel(int sz) : size(sz) {}
20440 };
20441
20442 class Bike {
20443   Wheel wheel;
20444 public:
20445   Bike(int val) : wheel(val) {}
20446   Wheel&amp; getWheel() { return wheel; }
20447 };
20448 </PRE>
20449 </DIV>
20450 <P> and the following usage from C# after running the code through SWIG:</P>
20451 <DIV class="code">
20452 <PRE>
20453       Wheel wheel = new Bike(10).getWheel();
20454       Console.WriteLine(&quot;wheel size: &quot; + wheel.size);
20455       // Simulate a garbage collection
20456       System.GC.Collect();
20457       System.GC.WaitForPendingFinalizers();
20458       Console.WriteLine(&quot;wheel size: &quot; + wheel.size);
20459 </PRE>
20460 </DIV>
20461 <P> Don't be surprised that if the resulting output gives strange
20462  results such as...</P>
20463 <DIV class="shell">
20464 <PRE>
20465 wheel size: 10
20466 wheel size: 135019664
20467 </PRE>
20468 </DIV>
20469 <P> What has happened here is the garbage collector has collected the <TT>
20470 Bike</TT> instance as it doesn't think it is needed any more. The proxy
20471  instance, <TT>wheel</TT>, contains a reference to memory that was
20472  deleted when the <TT>Bike</TT> instance was collected. In order to
20473  prevent the garbage collector from collecting the <TT>Bike</TT>
20474  instance a reference to the <TT>Bike</TT> must be added to the <TT>
20475 wheel</TT> instance. You can do this by adding the reference when the <TT>
20476 getWheel()</TT> method is called using the following typemaps.</P>
20477 <DIV class="code">
20478 <PRE>
20479 %typemap(cscode) Wheel %{
20480   // Ensure that the GC doesn't collect any Bike instance set from C#
20481   private Bike bikeReference;
20482   internal void addReference(Bike bike) {
20483     bikeReference = bike;
20484   }
20485 %}
20486
20487 // Add a C# reference to prevent premature garbage collection and resulting use
20488 // of dangling C++ pointer. Intended for methods that return pointers or
20489 // references to a member variable.
20490 %typemap(csout, excode=SWIGEXCODE) Wheel&amp; getWheel {
20491     IntPtr cPtr = $imcall;$excode
20492     $csclassname ret = null;
20493     if (cPtr != IntPtr.Zero) {
20494       ret = new $csclassname(cPtr, $owner);
20495       ret.addReference(this);
20496     }
20497     return ret;
20498   }
20499 </PRE>
20500 </DIV>
20501 <P> The code in the first typemap gets added to the <TT>Wheel</TT> proxy
20502  class. The code in the second typemap constitutes the bulk of the code
20503  in the generated <TT>getWheel()</TT> function:</P>
20504 <DIV class="code">
20505 <PRE>
20506 public class Wheel : IDisposable {
20507   ...
20508   // Ensure that the GC doesn't collect any Bike instance set from C#
20509   private Bike bikeReference;
20510   internal void addReference(Bike bike) {
20511     bikeReference = bike;
20512   }
20513 }
20514
20515 public class Bike : IDisposable {
20516   ...
20517   public Wheel getWheel() {
20518     IntPtr cPtr = examplePINVOKE.Bike_getWheel(swigCPtr);
20519     Wheel ret = null;
20520     if (cPtr != IntPtr.Zero) {
20521       ret = new Wheel(cPtr, false);
20522       ret.addReference(this);
20523     }
20524     return ret;
20525   }
20526 }
20527 </PRE>
20528 </DIV>
20529 <P> Note the <TT>addReference</TT> call.</P>
20530 <H3><A name="csharp_memory_management_objects"></A>18.6.2 Memory
20531  management for objects passed to the C++ layer</H3>
20532 <P> The example is a direct equivalent to this <A href="#java_memory_management_objects">
20533 Java equivalent</A>. Managing memory can be tricky when using C++ and C#
20534  proxy classes. The previous example shows one such case and this
20535  example looks at memory management for a class passed to a C++ method
20536  which expects the object to remain in scope after the function has
20537  returned. Consider the following two C++ classes:</P>
20538 <DIV class="code">
20539 <PRE>
20540 struct Element {
20541   int value;
20542   Element(int val) : value(val) {}
20543 };
20544 class Container {
20545   Element* element;
20546 public:
20547   Container() : element(0) {}
20548   void setElement(Element* e) { element = e; }
20549   Element* getElement() { return element; }
20550 };
20551 </PRE>
20552 </DIV>
20553 <P> and usage from C++</P>
20554 <DIV class="code">
20555 <PRE>
20556     Container container;
20557     Element element(20);
20558     container.setElement(&amp;element);
20559     cout &lt;&lt; &quot;element.value: &quot; &lt;&lt; container.getElement()-&gt;value &lt;&lt; endl;
20560 </PRE>
20561 </DIV>
20562 <P> and more or less equivalent usage from C#</P>
20563 <DIV class="code">
20564 <PRE>
20565       Container container = new Container();
20566       Element element = new Element(20);
20567       container.setElement(element);
20568 </PRE>
20569 </DIV>
20570 <P> The C++ code will always print out 20, but the value printed out may
20571  not be this in the C# equivalent code. In order to understand why,
20572  consider a garbage collection occuring...</P>
20573 <DIV class="code">
20574 <PRE>
20575       Container container = new Container();
20576       Element element = new Element(20);
20577       container.setElement(element);
20578       Console.WriteLine(&quot;element.value: &quot; + container.getElement().value);
20579       // Simulate a garbage collection
20580       System.GC.Collect();
20581       System.GC.WaitForPendingFinalizers();
20582       Console.WriteLine(&quot;element.value: &quot; + container.getElement().value);
20583 </PRE>
20584 </DIV>
20585 <P> The temporary element created with <TT>new Element(20)</TT> could
20586  get garbage collected which ultimately means the <TT>container</TT>
20587  variable is holding a dangling pointer, thereby printing out any old
20588  random value instead of the expected value of 20. One solution is to
20589  add in the appropriate references in the C# layer...</P>
20590 <DIV class="code">
20591 <PRE>
20592 public class Container : IDisposable {
20593
20594   ...
20595
20596   // Ensure that the GC doesn't collect any Element set from C#
20597   // as the underlying C++ class stores a shallow copy
20598   private Element elementReference;
20599   private HandleRef getCPtrAndAddReference(Element element) {
20600     elementReference = element;
20601     return Element.getCPtr(element);
20602   }
20603
20604   public void setElement(Element e) {
20605     examplePINVOKE.Container_setElement(swigCPtr, getCPtrAndAddReference(e));
20606   }
20607 }
20608 </PRE>
20609 </DIV>
20610 <P> The following typemaps will generate the desired code. The 'csin'
20611  typemap matches the input parameter type for the <TT>setElement</TT>
20612  method. The 'cscode' typemap simply adds in the specified code into the
20613  C# proxy class.</P>
20614 <DIV class="code">
20615 <PRE>
20616 %typemap(csin) Element *e &quot;getCPtrAndAddReference($csinput)&quot;
20617
20618 %typemap(cscode) Container %{
20619   // Ensure that the GC doesn't collect any Element set from C#
20620   // as the underlying C++ class stores a shallow copy
20621   private Element elementReference;
20622   private HandleRef getCPtrAndAddReference(Element element) {
20623     elementReference = element;
20624     return Element.getCPtr(element);
20625   }
20626 %}
20627 </PRE>
20628 </DIV>
20629 <H3><A name="csharp_date_marshalling"></A>18.6.3 Date marshalling using
20630  the csin typemap and associated attributes</H3>
20631 <P> The <A href="#nan_exception_typemap">NaN Exception example</A> is a
20632  simple example of the &quot;javain&quot; typemap and its 'pre' attribute. This
20633  example demonstrates how a C++ date class, say <TT>CDate</TT>, can be
20634  mapped onto the standard .NET date class, <TT>System.DateTime</TT> by
20635  using the 'pre', 'post' and 'pgcppname' attributes of the &quot;csin&quot;
20636  typemap (the C# equivalent to the &quot;javain&quot; typemap). The example is an
20637  equivalent to the <A href="#java_date_marshalling">Java Date
20638  marshalling example</A>. The idea is that the <TT>System.DateTime</TT>
20639  is used wherever the C++ API uses a <TT>CDate</TT>. Let's assume the
20640  code being wrapped is as follows:</P>
20641 <DIV class="code">
20642 <PRE>
20643 class CDate {
20644 public:
20645   CDate();
20646   CDate(int year, int month, int day);
20647   int getYear();
20648   int getMonth();
20649   int getDay();
20650   ...
20651 };
20652 struct Action {
20653   static int doSomething(const CDate &amp;dateIn, CDate &amp;dateOut);
20654   Action(const CDate &amp;date, CDate &amp;dateOut);
20655 };
20656 </PRE>
20657 </DIV>
20658 <P> Note that <TT>dateIn</TT> is const and therefore read only and <TT>
20659 dateOut</TT> is a non-const output type.</P>
20660 <P> First let's look at the code that is generated by default, where the
20661  C# proxy class <TT>CDate</TT> is used in the proxy interface:</P>
20662 <DIV class="code">
20663 <PRE>
20664 public class Action : IDisposable {
20665   ...
20666   public Action(CDate dateIn, CDate dateOut) 
20667       : this(examplePINVOKE.new_Action(CDate.getCPtr(dateIn), CDate.getCPtr(dateOut)), true) {
20668     if (examplePINVOKE.SWIGPendingException.Pending) 
20669       throw examplePINVOKE.SWIGPendingException.Retrieve();
20670   }
20671
20672   public int doSomething(CDate dateIn, CDate dateOut) {
20673     int ret = examplePINVOKE.Action_doSomething(swigCPtr, 
20674                                                 CDate.getCPtr(dateIn), 
20675                                                 CDate.getCPtr(dateOut));
20676     if (examplePINVOKE.SWIGPendingException.Pending) 
20677       throw examplePINVOKE.SWIGPendingException.Retrieve();
20678     return ret;
20679   }
20680 }
20681 </PRE>
20682 </DIV>
20683 <P> The <TT>CDate &amp;</TT> and <TT>const CDate &amp;</TT> C# code is generated
20684  from the following two default typemaps:</P>
20685 <DIV class="code">
20686 <PRE>
20687 %typemap(cstype) SWIGTYPE &amp; &quot;$csclassname&quot;
20688 %typemap(csin) SWIGTYPE &amp; &quot;$csclassname.getCPtr($csinput)&quot;
20689 </PRE>
20690 </DIV>
20691 <P> where '$csclassname' is translated into the proxy class name, <TT>
20692 CDate</TT> and '$csinput' is translated into the name of the parameter,
20693  eg <TT>dateIn</TT>. From C#, the intention is then to call into a
20694  modifed API with something like:</P>
20695 <DIV class="code">
20696 <PRE>
20697 System.DateTime dateIn = new System.DateTime(2011, 4, 13);
20698 System.DateTime dateOut = new System.DateTime();
20699
20700 // Note in calls below, dateIn remains unchanged and dateOut 
20701 // is set to a new value by the C++ call
20702 Action action = new Action(dateIn, out dateOut);
20703 dateIn = new System.DateTime(2012, 7, 14);
20704 </PRE>
20705 </DIV>
20706 <P> To achieve this mapping, we need to alter the default code
20707  generation slightly so that at the C# layer, a <TT>System.DateTime</TT>
20708  is converted into a <TT>CDate</TT>. The intermediary layer will still
20709  take a pointer to the underlying <TT>CDate</TT> class. The typemaps to
20710  achieve this are shown below.</P>
20711 <DIV class="code">
20712 <PRE>
20713 %typemap(cstype) const CDate&amp; &quot;System.DateTime&quot;
20714 %typemap(csin, 
20715          pre=&quot;    CDate temp$csinput = new CDate($csinput.Year, $csinput.Month, $csinput.Day);&quot;
20716         ) const CDate &amp;
20717          &quot;$csclassname.getCPtr(temp$csinput)&quot;
20718
20719 %typemap(cstype) CDate&amp; &quot;out System.DateTime&quot;
20720 %typemap(csin, 
20721          pre=&quot;    CDate temp$csinput = new CDate();&quot;, 
20722          post=&quot;      $csinput = new System.DateTime(temp$csinput.getYear(),&quot;
20723               &quot; temp$csinput.getMonth(), temp$csinput.getDay(), 0, 0, 0);&quot;, 
20724          cshin=&quot;out $csinput&quot;
20725         ) CDate &amp;
20726          &quot;$csclassname.getCPtr(temp$csinput)&quot;
20727
20728 </PRE>
20729 </DIV>
20730 <P> The resulting generated proxy code in the <TT>Action</TT> class
20731  follows:</P>
20732 <DIV class="code">
20733 <PRE>
20734 public class Action : IDisposable {
20735   ...
20736   public int doSomething(System.DateTime dateIn, out System.DateTime dateOut) {
20737     CDate tempdateIn = new CDate(dateIn.Year, dateIn.Month, dateIn.Day);
20738     CDate tempdateOut = new CDate();
20739     try {
20740       int ret = examplePINVOKE.Action_doSomething(swigCPtr, 
20741                                                   CDate.getCPtr(tempdateIn), 
20742                                                   CDate.getCPtr(tempdateOut));
20743       if (examplePINVOKE.SWIGPendingException.Pending) 
20744         throw examplePINVOKE.SWIGPendingException.Retrieve();
20745       return ret;
20746     } finally {
20747       dateOut = new System.DateTime(tempdateOut.getYear(), 
20748                                     tempdateOut.getMonth(), tempdateOut.getDay(), 0, 0, 0);
20749     }
20750   }
20751
20752   static private IntPtr SwigConstructAction(System.DateTime dateIn, out System.DateTime dateOut) {
20753     CDate tempdateIn = new CDate(dateIn.Year, dateIn.Month, dateIn.Day);
20754     CDate tempdateOut = new CDate();
20755     try {
20756       return examplePINVOKE.new_Action(CDate.getCPtr(tempdateIn), CDate.getCPtr(tempdateOut));
20757     } finally {
20758       dateOut = new System.DateTime(tempdateOut.getYear(), 
20759                                     tempdateOut.getMonth(), tempdateOut.getDay(), 0, 0, 0);
20760     }
20761   }
20762
20763   public Action(System.DateTime dateIn, out System.DateTime dateOut) 
20764       : this(Action.SwigConstructAction(dateIn, out dateOut), true) {
20765     if (examplePINVOKE.SWIGPendingException.Pending) 
20766       throw examplePINVOKE.SWIGPendingException.Retrieve();
20767   }
20768 }
20769 </PRE>
20770 </DIV>
20771 <P> A few things to note:</P>
20772 <UL>
20773 <LI> The &quot;cstype&quot; typemap has changed the parameter type to <TT>
20774 System.DateTime</TT> instead of the default generated <TT>CDate</TT>
20775  proxy.</LI>
20776 <LI> The non-const <TT>CDate &amp;</TT> type is marshalled as a reference
20777  parameter in C# as the date cannot be explicitly set once the object
20778  has been created, so a new object is created instead.</LI>
20779 <LI> The code in the 'pre' attribute appears before the intermediary
20780  call (<TT>examplePINVOKE.new_Action</TT> / <TT>
20781 examplePINVOKE.Action_doSomething</TT>).</LI>
20782 <LI> The code in the 'post' attribute appears after the intermediary
20783  call.</LI>
20784 <LI> A try .. finally block is generated with the intermediary call in
20785  the try block and 'post' code in the finally block. The alternative of
20786  just using a temporary variable for the return value from the
20787  intermediary call and the 'post' code being inserted before the return
20788  statement is not possible given that the intermediary call and method
20789  return comes from a single source (the &quot;csout&quot; typemap).</LI>
20790 <LI> The temporary variables in the &quot;csin&quot; typemaps are called <TT>
20791 temp$csin</TT>, where &quot;$csin&quot; is replaced with the parameter name.
20792  &quot;$csin&quot; is used to mangle the variable name so that more than one <TT>
20793 CDate &amp;</TT> type can be used as a parameter in a method, otherwise two
20794  or more local variables with the same name would be generated.</LI>
20795 <LI> The use of the &quot;csin&quot; typemap causes a constructor helper function
20796  (<TT>SwigConstructAction</TT>) to be generated. This allows C# code to
20797  be called before the intermediary call made in the constructor
20798  initialization list.</LI>
20799 <LI> The 'cshin' attribute is required for the <TT>SwigConstructAction</TT>
20800  constructor helper function so that the 2nd parameter is declared as <TT>
20801 out dateOut</TT> instead of just <TT>dateOut</TT>.</LI>
20802 </UL>
20803 <P> So far we have considered the date as an input only and an output
20804  only type. Now let's consider <TT>CDate *</TT> used as an input/output
20805  type. Consider the following C++ function which modifies the date
20806  passed in:</P>
20807 <DIV class="code">
20808 <PRE>
20809 void addYears(CDate *pDate, int years) {
20810   *pDate = CDate(pDate-&gt;getYear() + years, pDate-&gt;getMonth(), pDate-&gt;getDay());
20811 }
20812 </PRE>
20813 </DIV>
20814 <P> If usage of <TT>CDate *</TT> commonly follows this input/output
20815  pattern, usage from C# like the following</P>
20816 <DIV class="code">
20817 <PRE>
20818 System.DateTime christmasEve = new System.DateTime(2000, 12, 24);
20819 example.addYears(ref christmasEve, 10); // christmasEve now contains 2010-12-24
20820 </PRE>
20821 </DIV>
20822 <P> will be possible with the following <TT>CDate *</TT> typemaps</P>
20823 <DIV class="code">
20824 <PRE>
20825 %typemap(cstype, out=&quot;System.DateTime&quot;) CDate * &quot;ref System.DateTime&quot;
20826
20827 %typemap(csin,
20828          pre=&quot;    CDate temp$csinput = new CDate($csinput.Year, $csinput.Month, $csinput.Day);&quot;,
20829          post=&quot;      $csinput = new System.DateTime(temp$csinput.getYear(),&quot;
20830               &quot; temp$csinput.getMonth(), temp$csinput.getDay(), 0, 0, 0);&quot;, 
20831          cshin=&quot;ref $csinput&quot;
20832         ) CDate *
20833          &quot;$csclassname.getCPtr(temp$csinput)&quot;
20834 </PRE>
20835 </DIV>
20836 <P> Globals are wrapped by the module class and for a module called
20837  example, the typemaps result in the following code:</P>
20838 <DIV class="code">
20839 <PRE>
20840 public class example {
20841   public static void addYears(ref System.DateTime pDate, int years) {
20842     CDate temppDate = new CDate(pDate.Year, pDate.Month, pDate.Day);
20843     try {
20844       examplePINVOKE.addYears(CDate.getCPtr(temppDate), years);
20845     } finally {
20846       pDate = new System.DateTime(temppDate.getYear(), temppDate.getMonth(), temppDate.getDay(), 0, 0, 0);
20847     }
20848   }
20849   ...
20850 }
20851 </PRE>
20852 </DIV>
20853 <P> The following typemap is the same as the previous but demonstrates
20854  how a using block can be used for the temporary variable. The only
20855  change to the previous typemap is the introduction of the 'terminator'
20856  attribute to terminate the <TT>using</TT> block. The <TT>subtractYears</TT>
20857  method is nearly identical to the above <TT>addYears</TT> method.</P>
20858 <DIV class="code">
20859 <PRE>
20860 %typemap(csin,
20861          pre=&quot;    using (CDate temp$csinput = new CDate($csinput.Year, $csinput.Month, $csinput.Day)) {&quot;,
20862          post=&quot;      $csinput = new System.DateTime(temp$csinput.getYear(),&quot;
20863               &quot; temp$csinput.getMonth(), temp$csinput.getDay(), 0, 0, 0);&quot;, 
20864          terminator=&quot;    } // terminate temp$csinput using block&quot;,
20865          cshin=&quot;ref $csinput&quot;
20866         ) CDate *
20867          &quot;$csclassname.getCPtr(temp$csinput)&quot;
20868
20869 void subtractYears(CDate *pDate, int years) {
20870   *pDate = CDate(pDate-&gt;getYear() - years, pDate-&gt;getMonth(), pDate-&gt;getDay());
20871 }
20872 </PRE>
20873 </DIV>
20874 <P> The resulting generated code shows the termination of the <TT>using</TT>
20875  block:</P>
20876 <DIV class="code">
20877 <PRE>
20878 public class example {
20879   public static void subtractYears(ref System.DateTime pDate, int years) {
20880     using (CDate temppDate = new CDate(pDate.Year, pDate.Month, pDate.Day)) {
20881     try {
20882       examplePINVOKE.subtractYears(CDate.getCPtr(temppDate), years);
20883     } finally {
20884       pDate = new System.DateTime(temppDate.getYear(), temppDate.getMonth(), temppDate.getDay(), 0, 0, 0);
20885     }
20886     } // terminate temppDate using block
20887   }
20888   ...
20889 }
20890 </PRE>
20891 </DIV>
20892 <H3><A name="csharp_date_properties"></A>18.6.4 A date example
20893  demonstrating marshalling of C# properties</H3>
20894 <P> The previous section looked at converting a C++ date class to <TT>
20895 System.DateTime</TT> for parameters. This section extends this idea so
20896  that the correct marshalling is obtained when wrapping C++ variables.
20897  Consider the same <TT>CDate</TT> class from the previous section and a
20898  global variable:</P>
20899 <DIV class="code">
20900 <PRE>
20901 CDate ImportantDate = CDate(1999, 12, 31);
20902 </PRE>
20903 </DIV>
20904 <P> The aim is to use <TT>System.DateTime</TT> from C# when accessing
20905  this date as shown in the following usage where the module name is
20906  'example':</P>
20907 <DIV class="code">
20908 <PRE>
20909 example.ImportantDate = new System.DateTime(2000, 11, 22);
20910 System.DateTime importantDate = example.ImportantDate;
20911 Console.WriteLine(&quot;Important date: &quot; + importantDate);
20912 </PRE>
20913 </DIV>
20914 <P> When SWIG wraps a variable that is a class/struct/union, it is
20915  wrapped using a pointer to the type for the reasons given in <A href="#SWIG_structure_data_members">
20916 Stucture data members</A>. The typemap type required is thus <TT>CDate *</TT>
20917 . Given that the previous section already designed <TT>CDate *</TT>
20918  typemaps, we'll use those same typemaps plus the 'csvarin' and
20919  'csvarout' typemaps.<DIV class="code">
20920 <PRE>
20921 %typemap(cstype, out=&quot;System.DateTime&quot;) CDate * &quot;ref System.DateTime&quot;
20922
20923 %typemap(csin,
20924          pre=&quot;    CDate temp$csinput = new CDate($csinput.Year, $csinput.Month, $csinput.Day);&quot;,
20925          post=&quot;      $csinput = new System.DateTime(temp$csinput.getYear(),&quot;
20926               &quot; temp$csinput.getMonth(), temp$csinput.getDay(), 0, 0, 0);&quot;, 
20927          cshin=&quot;ref $csinput&quot;
20928         ) CDate *
20929          &quot;$csclassname.getCPtr(temp$csinput)&quot;
20930
20931 %typemap(csvarin, excode=SWIGEXCODE2) CDate * %{
20932     /* csvarin typemap code */
20933     set {
20934       CDate temp$csinput = new CDate($csinput.Year, $csinput.Month, $csinput.Day);
20935       $imcall;$excode
20936     } %}
20937
20938 %typemap(csvarout, excode=SWIGEXCODE2) CDate * %{
20939     /* csvarout typemap code */
20940     get {
20941       IntPtr cPtr = $imcall;
20942       CDate tempDate = (cPtr == IntPtr.Zero) ? null : new CDate(cPtr, $owner);$excode
20943       return new System.DateTime(tempDate.getYear(), tempDate.getMonth(), tempDate.getDay(),
20944                                  0, 0, 0);
20945     } %}
20946 </PRE>
20947 </DIV></P>
20948 <P> For a module called example, the typemaps result in the following
20949  code:</P>
20950 <DIV class="code">
20951 <PRE>
20952 public class example {
20953   public static System.DateTime ImportantDate {
20954     /* csvarin typemap code */
20955     set {
20956       CDate tempvalue = new CDate(value.Year, value.Month, value.Day);
20957       examplePINVOKE.ImportantDate_set(CDate.getCPtr(tempvalue));
20958     } 
20959     /* csvarout typemap code */
20960     get {
20961       IntPtr cPtr = examplePINVOKE.ImportantDate_get();
20962       CDate tempDate = (cPtr == IntPtr.Zero) ? null : new CDate(cPtr, false);
20963       return new System.DateTime(tempDate.getYear(), tempDate.getMonth(), tempDate.getDay(),
20964                                  0, 0, 0);
20965     } 
20966   }
20967   ...
20968 }
20969 </PRE>
20970 </DIV>
20971 <P> Some points to note:</P>
20972 <UL>
20973 <LI>The property set comes from the 'csvarin' typemap and the property
20974  get comes from the 'csvarout' typemap.</LI>
20975 <LI>The type used for the property comes from the 'cstype' typemap. This
20976  particular example has the 'out' attribute set in the typemap and as it
20977  is specified, it is used in preference to the type in the typemap body.
20978  This is because the type in the 'out' attribute can never include
20979  modifiers such as 'ref', thereby avoiding code such as <TT>public
20980  static ref System.DateTime ImportantDate { ...</TT>, which would of
20981  course not compile.</LI>
20982 <LI>The <TT>$excode</TT> special variable expands to nothing as there
20983  are no exception handlers specified in any of the unmanaged code
20984  typemaps (in fact the marshalling was done using the default unmanaged
20985  code typemaps.)</LI>
20986 <LI>The <TT>$imcall</TT> typemap expands to the appropriate intermediary
20987  method call in the <TT>examplePINVOKE</TT> class.</LI>
20988 <LI>The <TT>$csinput</TT> special variable in the 'csin' typemap always
20989  expands to <TT>value</TT> for properties. In this case <TT>
20990 $csclassname.getCPtr(temp$csinput)</TT> expands to <TT>
20991 CDate.getCPtr(tempvalue)</TT>.</LI>
20992 <LI>The 'csin' typemap has 'pre', 'post' and 'cshin' attributes, and
20993  these are all ignored in the property set. The code in these attributes
20994  must instead be replicated within the 'csvarin' typemap. The line
20995  creating the <TT>temp$csinput</TT> variable is such an example; it is
20996  identical to what is in the 'pre' attribute.</LI>
20997 </UL>
20998 <H3><A name="csharp_partial_classes"></A>18.6.5 Turning wrapped classes
20999  into partial classes</H3>
21000 <P> C# supports the notion of partial classes whereby a class definition
21001  can be split into more than one file. It is possible to turn the
21002  wrapped C++ class into a partial C# class using the <TT>
21003 csclassmodifiers</TT> typemap. Consider a C++ class called <TT>ExtendMe</TT>
21004 :</P>
21005 <DIV class="code">
21006 <PRE>
21007 class ExtendMe {
21008 public:
21009   int Part1() { return 1; }
21010 };
21011 </PRE>
21012 </DIV>
21013 <P> The default C# proxy class generated is:</P>
21014 <DIV class="code">
21015 <PRE>
21016 public class ExtendMe : IDisposable {
21017   ...
21018   public int Part1() {
21019     ...
21020   }
21021 }
21022 </PRE>
21023 </DIV>
21024 <P> The default csclassmodifiers typemap shipped with SWIG is</P>
21025 <DIV class="code">
21026 <PRE>
21027 %typemap(csclassmodifiers) SWIGTYPE &quot;public class&quot;
21028 </PRE>
21029 </DIV>
21030 <P> Note that the type used is the special catch all type <TT>SWIGTYPE</TT>
21031 . If instead we use the following typemap to override this for just the <TT>
21032 ExtendMe</TT> class:</P>
21033 <DIV class="code">
21034 <PRE>
21035 %typemap(csclassmodifiers) ExtendMe &quot;public partial class&quot;
21036 </PRE>
21037 </DIV>
21038 <P> The C# proxy class becomes a partial class:</P>
21039 <DIV class="code">
21040 <PRE>
21041 public partial class ExtendMe : IDisposable {
21042   ...
21043   public int Part1() {
21044     ...
21045   }
21046 }
21047 </PRE>
21048 </DIV>
21049 <P> You can then of course declare another part of the partial class
21050  elsewhere, for example:</P>
21051 <DIV class="code">
21052 <PRE>
21053 public partial class ExtendMe : IDisposable {
21054   public int Part2() {
21055     return 2;
21056   }
21057 }
21058 </PRE>
21059 </DIV>
21060 <P> and compile the following code:</P>
21061 <DIV class="code">
21062 <PRE>
21063 ExtendMe em = new ExtendMe();
21064 Console.WriteLine(&quot;part1: {0}&quot;, em.Part1());
21065 Console.WriteLine(&quot;part2: {0}&quot;, em.Part2());
21066 </PRE>
21067 </DIV>
21068 <P> demonstrating that the class contains methods calling both unmanaged
21069  code - <TT>Part1()</TT> and managed code - <TT>Part2()</TT>. The
21070  following example is an alternative approach to adding managed code to
21071  the generated proxy class.</P>
21072 <H3><A name="csharp_extending_proxy_class"></A>18.6.6 Extending proxy
21073  classes with additional C# code</H3>
21074 <P> The previous example showed how to use partial classes to add
21075  functionality to a generated C# proxy class. It is also possible to
21076  extend a wrapped struct/class with C/C++ code by using the <A href="#SWIGPlus_class_extension">
21077 %extend directive</A>. A third approach is to add some C# methods into
21078  the generated proxy class with the <TT>cscode</TT> typemap. If we
21079  declare the following typemap before SWIG parses the <TT>ExtendMe</TT>
21080  class used in the previous example</P>
21081 <DIV class="code">
21082 <PRE>
21083 %typemap(cscode) ExtendMe %{
21084   public int Part3() {
21085     return 3;
21086   }
21087 %}
21088
21089 </PRE>
21090 </DIV>
21091 <P> The generated C# proxy class will instead be:</P>
21092 <DIV class="code">
21093 <PRE>
21094 public class ExtendMe : IDisposable {
21095   ...
21096   public int Part3() {
21097     return 3;
21098   }
21099   public int Part1() {
21100     ...
21101   }
21102 }
21103 </PRE>
21104 </DIV><HR NOSHADE>
21105
21106 <!-- Hand-written HTML -->
21107 <H1><A name="Chicken"></A>19 SWIG and Chicken</H1>
21108
21109 <!-- INDEX -->
21110 <DIV class="sectiontoc">
21111 <UL>
21112 <LI><A href="#Chicken_nn2">Preliminaries</A>
21113 <UL>
21114 <LI><A href="#Chicken_nn3">Running SWIG in C mode</A></LI>
21115 <LI><A href="#Chicken_nn4">Running SWIG in C++ mode</A></LI>
21116 </UL>
21117 </LI>
21118 <LI><A href="#Chicken_nn5">Code Generation</A>
21119 <UL>
21120 <LI><A href="#Chicken_nn6">Naming Conventions</A></LI>
21121 <LI><A href="#Chicken_nn7">Modules</A></LI>
21122 <LI><A href="#Chicken_nn8">Constants and Variables</A></LI>
21123 <LI><A href="#Chicken_nn9">Functions</A></LI>
21124 <LI><A href="#Chicken_nn10">Exceptions</A></LI>
21125 </UL>
21126 </LI>
21127 <LI><A href="#Chicken_nn11">TinyCLOS</A></LI>
21128 <LI><A href="#Chicken_nn12">Linkage</A>
21129 <UL>
21130 <LI><A href="#Chicken_nn13">Static binary or shared library linked at
21131  compile time</A></LI>
21132 <LI><A href="#Chicken_nn14">Building chicken extension libraries</A></LI>
21133 <LI><A href="#Chicken_nn15">Linking multiple SWIG modules with TinyCLOS</A>
21134 </LI>
21135 </UL>
21136 </LI>
21137 <LI><A href="#Chicken_nn16">Typemaps</A></LI>
21138 <LI><A href="#Chicken_nn17">Pointers</A>
21139 <UL>
21140 <LI><A href="#collection">Garbage collection</A></LI>
21141 </UL>
21142 </LI>
21143 <LI><A href="#Chicken_nn18">Unsupported features and known problems</A>
21144 <UL>
21145 <LI><A href="#Chicken_nn19">TinyCLOS problems with Chicken version &lt;=
21146  1.92</A></LI>
21147 </UL>
21148 </LI>
21149 </UL>
21150 </DIV>
21151 <!-- INDEX -->
21152 <P> This chapter describes SWIG's support of CHICKEN. CHICKEN is a
21153  Scheme-to-C compiler supporting most of the language features as
21154  defined in the<I> Revised^5 Report on Scheme</I>. Its main attributes
21155  are that it</P>
21156 <OL>
21157 <LI>generates portable C code</LI>
21158 <LI>includes a customizable interpreter</LI>
21159 <LI>links to C libraries with a simple Foreign Function Interface</LI>
21160 <LI>supports full tail-recursion and first-class continuations</LI>
21161 </OL>
21162 <P> When confronted with a large C library, CHICKEN users can use SWIG
21163  to generate CHICKEN wrappers for the C library. However, the real
21164  advantages of using SWIG with CHICKEN are its<STRONG> support for C++</STRONG>
21165  -- object-oriented code is difficult to wrap by hand in CHICKEN -- and
21166  its<STRONG> typed pointer representation</STRONG>, essential for C and
21167  C++ libraries involving structures or classes.</P>
21168 <H2><A name="Chicken_nn2"></A>19.1 Preliminaries</H2>
21169 <P> CHICKEN support was introduced to SWIG in version 1.3.18. SWIG
21170  relies on some recent additions to CHICKEN, which are only present in
21171  releases of CHICKEN with version number<STRONG> greater than or equal
21172  to 1.89</STRONG>. To use a chicken version between 1.40 and 1.89, see
21173  the <A href="#collection">Garbage collection</A> section below.</P>
21174 <P> You may want to look at any of the examples in Examples/chicken/ or
21175  Examples/GIFPlot/Chicken for the basic steps to run SWIG CHICKEN.</P>
21176 <H3><A name="Chicken_nn3"></A>19.1.1 Running SWIG in C mode</H3>
21177 <P> To run SWIG CHICKEN in C mode, use the -chicken option.</P>
21178 <DIV class="shell">
21179 <PRE>% swig -chicken example.i</PRE>
21180 </DIV>
21181 <P> To allow the wrapper to take advantage of future CHICKEN code
21182  generation improvements, part of the wrapper is direct CHICKEN function
21183  calls (<TT>example_wrap.c</TT>) and part is CHICKEN Scheme (<TT>
21184 example.scm</TT>). The basic Scheme code must be compiled to C using
21185  your system's CHICKEN compiler or both files can be compiled directly
21186  using the much simpler <TT>csc</TT>.</P>
21187 <DIV class="shell">
21188 <PRE>
21189 % chicken example.scm -output-file oexample.c
21190 </PRE>
21191 </DIV>
21192 <P> So for the C mode of SWIG CHICKEN, <TT>example_wrap.c</TT> and <TT>
21193 oexample.c</TT> are the files that must be compiled to object files and
21194  linked into your project.</P>
21195 <H3><A name="Chicken_nn4"></A>19.1.2 Running SWIG in C++ mode</H3>
21196 <P> To run SWIG CHICKEN in C++ mode, use the -chicken -c++ option.</P>
21197 <DIV class="shell">
21198 <PRE>% swig -chicken -c++ example.i</PRE>
21199 </DIV>
21200 <P> This will generate <TT>example_wrap.cxx</TT> and <TT>example.scm</TT>
21201 . The basic Scheme code must be compiled to C using your system's
21202  CHICKEN compiler or both files can be compiled directly using the much
21203  simpler <TT>csc</TT>.</P>
21204 <DIV class="shell">
21205 <PRE>% chicken example.scm -output-file oexample.c</PRE>
21206 </DIV>
21207 <P> So for the C++ mode of SWIG CHICKEN, <TT>example_wrap.cxx</TT> and <TT>
21208 oexample.c</TT> are the files that must be compiled to object files and
21209  linked into your project.</P>
21210 <H2><A name="Chicken_nn5"></A>19.2 Code Generation</H2>
21211 <H3><A name="Chicken_nn6"></A>19.2.1 Naming Conventions</H3>
21212 <P> Given a C variable, function or constant declaration named <TT>
21213 Foo_Bar</TT>, the declaration will be available in CHICKEN as an
21214  identifier ending with <TT>Foo-Bar</TT>. That is, an underscore is
21215  converted to a dash.</P>
21216 <P> You may control what the CHICKEN identifier will be by using the <TT>
21217 %rename</TT> SWIG directive in the SWIG interface file.</P>
21218 <H3><A name="Chicken_nn7"></A>19.2.2 Modules</H3>
21219 <P> The name of the module must be declared one of two ways:</P>
21220 <UL>
21221 <LI>Placing <TT>%module example</TT> in the SWIG interface file.</LI>
21222 <LI>Using <TT>-module example</TT> on the SWIG command line.</LI>
21223 </UL>
21224 <P> The generated example.scm file then exports <CODE>(declare (unit
21225  modulename))</CODE>. If you do not want SWIG to export the <CODE>
21226 (declare (unit modulename))</CODE>, pass the -nounit option to SWIG.</P>
21227 <P> CHICKEN will be able to access the module using the <CODE>(declare
21228  (uses<I> modulename</I>))</CODE> CHICKEN Scheme form.</P>
21229 <H3><A name="Chicken_nn8"></A>19.2.3 Constants and Variables</H3>
21230 <P> Constants may be created using any of the four constructs in the
21231  interface file:</P>
21232 <OL>
21233 <LI><CODE>#define MYCONSTANT1 ...</CODE></LI>
21234 <LI><CODE>%constant int MYCONSTANT2 = ...</CODE></LI>
21235 <LI><CODE>const int MYCONSTANT3 = ...</CODE></LI>
21236 <LI><CODE>enum { MYCONSTANT4 = ... };</CODE></LI>
21237 </OL>
21238 <P> In all cases, the constants may be accessed from within CHICKEN
21239  using the form <TT>(MYCONSTANT1)</TT>; that is, the constants may be
21240  accessed using the read-only parameter form.</P>
21241 <P> Variables are accessed using the full parameter form. For example,
21242  to set the C variable &quot;int my_variable;&quot;, use the Scheme form <TT>
21243 (my-variable 2345)</TT>. To get the C variable, use <TT>(my-variable)</TT>
21244 .</P>
21245 <P> The <TT>%feature(&quot;constasvar&quot;)</TT> can be applied to any constant
21246  or immutable variable. Instead of exporting the constant as a function
21247  that must be called, the constant will appear as a scheme variable.
21248  This causes the generated .scm file to just contain the code <TT>(set!
21249  MYCONSTANT1 (MYCONSTANT1))</TT>. See <A href="#features">Features and
21250  the %feature directive</A> for info on how to apply the %feature.</P>
21251 <H3><A name="Chicken_nn9"></A>19.2.4 Functions</H3>
21252 <P> C functions declared in the SWIG interface file will have
21253  corresponding CHICKEN Scheme procedures. For example, the C function
21254  &quot;int sqrt(double x);&quot; will be available using the Scheme form <TT>(sqrt
21255  2345.0)</TT>. A <CODE>void</CODE> return value will give
21256  C_SCHEME_UNDEFINED as a result.</P>
21257 <P> A function may return more than one value by using the <CODE>OUTPUT</CODE>
21258  specifier (see Lib/chicken/typemaps.i). They will be returned as
21259  multiple values using <CODE>(values)</CODE> if there is more than one
21260  result (that is, a non-void return value and at least one argout
21261  parameter, or a void return value and at least two argout parameters).
21262  The return values can then be accessed with <CODE>(call-with-values)</CODE>
21263 .</P>
21264 <H3><A name="Chicken_nn10"></A>19.2.5 Exceptions</H3>
21265 <P>The SWIG chicken module has support for exceptions thrown from C or
21266  C++ code to be caught in scheme. See <A href="#exception">Exception
21267  handling with %exception</A> for more information about declaring
21268  exceptions in the interface file.</P>
21269 <P>Chicken supports both the <CODE>SWIG_exception(int code, const char
21270  *msg)</CODE> interface as well as a <CODE>SWIG_ThrowException(C_word
21271  val)</CODE> function for throwing exceptions from inside the %exception
21272  blocks. <CODE>SWIG_exception</CODE> will throw a list consisting of the
21273  code (as an integer) and the message. Both of these will throw an
21274  exception using <CODE>(abort)</CODE>, which can be handled by <CODE>
21275 (handle-exceptions)</CODE>. See <A href="http://www.call-with-current-continuation.org/manual/Exceptions.html#Exceptions">
21276 Chicken manual on Exceptions</A> and <A href="http://srfi.schemers.org/srfi-12/srfi-12.html">
21277 SFRI-12</A>. Since the exception values are thrown directly, if <CODE>
21278 (condition-case)</CODE> is used to catch an exception the exception will
21279  come through in the <CODE>val ()</CODE> case.</P>
21280 <P>The following simple module</P>
21281 <DIV class="code">
21282 <PRE>
21283 %module exception_test
21284
21285 %inline %{
21286   void test_throw(int i) throws (int) { 
21287     if (i == 1) throw 15; 
21288   }
21289 %}
21290 </PRE>
21291 </DIV>
21292 <P>could be run with</P>
21293 <DIV class="targetlang">
21294 <PRE>
21295 (handle-exceptions exvar 
21296   (if (= exvar 15)
21297     (print &quot;Correct!&quot;) 
21298     (print &quot;Threw something else &quot; exvar))
21299   (test-throw 1))
21300 </PRE>
21301 </DIV>
21302 <H2><A name="Chicken_nn11"></A>19.3 TinyCLOS</H2>
21303 <P> The author of TinyCLOS, Gregor Kiczales, describes TinyCLOS as:
21304  &quot;Tiny CLOS is a Scheme implementation of a `kernelized' CLOS, with a
21305  metaobject protocol. The implementation is even simpler than the simple
21306  CLOS found in `The Art of the Metaobject Protocol,' weighing in at
21307  around 850 lines of code, including (some) comments and documentation.&quot;</P>
21308 <P> Almost all good Scheme books describe how to use metaobjects and
21309  generic procedures to implement an object-oriented Scheme system.
21310  Please consult a Scheme book if you are unfamiliar with the concept.</P>
21311 <P> CHICKEN has a modified version of TinyCLOS, which SWIG CHICKEN uses
21312  if the -proxy argument is given. If -proxy is passed, then the
21313  generated example.scm file will contain TinyCLOS class definitions. A
21314  class named Foo is declared as &lt;Foo&gt;, and each member variable is
21315  allocated a slot. Member functions are exported as generic functions.</P>
21316 <P> Primitive symbols and functions (the interface that would be
21317  presented if -proxy was not passed) are hidden and no longer
21318  accessible. If the -unhideprimitive command line argument is passed to
21319  SWIG, then the primitive symbols will be available, but each will be
21320  prefixed by the string &quot;primitive:&quot;</P>
21321 <P> The exported symbol names can be controlled with the -closprefix and
21322  -useclassprefix arguments. If -useclassprefix is passed to SWIG, every
21323  member function will be generated with the class name as a prefix. If
21324  the -closprefix mymod: argument is passed to SWIG, then the exported
21325  functions will be prefixed by the string &quot;mymod:&quot;. If -useclassprefix
21326  is passed, -closprefix is ignored.</P>
21327 <H2><A name="Chicken_nn12"></A>19.4 Linkage</H2>
21328 <P> Please refer to<EM> CHICKEN - A practical and portable Scheme system
21329  - User's manual</EM> for detailed help on how to link object files to
21330  create a CHICKEN Scheme program. Briefly, to link object files, be sure
21331  to add <TT>`chicken-config -extra-libs -libs`</TT> or <TT>
21332 `chicken-config -shared -extra-libs -libs`</TT>to your linker options.
21333  Use the <TT>-shared</TT> option if you want to create a dynamically
21334  loadable module. You might also want to use the much simpler <TT>csc</TT>
21335  or <TT>csc.bat</TT>.</P>
21336 <P>Each scheme file that is generated by SWIG contains <CODE>(declare
21337  (uses<I> modname</I>))</CODE>. This means that to load the module from
21338  scheme code, the code must include <CODE>(declare (uses<I> modname</I>
21339 ))</CODE>.</P>
21340 <H3><A name="Chicken_nn13"></A>19.4.1 Static binary or shared library
21341  linked at compile time</H3>
21342 <P>We can easily use csc to build a static binary.</P>
21343 <DIV class="shell">
21344 <PRE>
21345 $ swig -chicken example.i
21346 $ csc -v example.scm example_impl.c example_wrap.c test_script.scm -o example
21347 $ ./example
21348 </PRE>
21349 </DIV>
21350 <P>Similar to the above, any number of <TT>module.scm</TT> files could
21351  be compiled into a shared library, and then that shared library linked
21352  when compiling the main application.</P>
21353 <DIV class="shell">
21354 <PRE>
21355 $ swig -chicken example.i
21356 $ csc -sv example.scm example_wrap.c example_impl.c -o example.so
21357 </PRE>
21358 </DIV>
21359 <P>The <TT>example.so</TT> file can then linked with <TT>test_script.scm</TT>
21360  when it is compiled, in which case <TT>test_script.scm</TT> must have <CODE>
21361 (declare (uses example))</CODE>. Multiple SWIG modules could have been
21362  linked into <TT>example.so</TT> and each one accessed with a <CODE>
21363 (declare (uses ... ))</CODE>.</P>
21364 <DIV class="shell">
21365 <PRE>
21366 $ csc -v test_script.scm -lexample
21367 </PRE>
21368 </DIV>
21369 <P>An alternative is that the test_script.scm can have the code <CODE>
21370 (load-library 'example &quot;example.so&quot;)</CODE>, in which case the test
21371  script does not need to be linked with example.so. The test_script.scm
21372  file can then be run with <TT>csi</TT>.</P>
21373 <H3><A name="Chicken_nn14"></A>19.4.2 Building chicken extension
21374  libraries</H3>
21375 <P>Building a shared library like in the above section only works if the
21376  library is linked at compile time with a script containing <CODE>
21377 (declare (uses ...))</CODE> or is loaded explicitly with <CODE>
21378 (load-library 'example &quot;example.so&quot;)</CODE>. It is not the format that
21379  CHICKEN expects for extension libraries and eggs. The problem is the <CODE>
21380 (declare (unit<I> modname</I>))</CODE> inside the <TT>modname.scm</TT>
21381  file. There are two possible solutions to this.</P>
21382 <P>First, SWIG accepts a <TT>-nounit</TT> argument, in which case the <CODE>
21383 (declare (unit<I> modname</I>))</CODE> is not generated. Then, the <TT>
21384 modname.scm</TT> and <TT>modname_wrap.c</TT> files<B> must</B> be
21385  compiled into their own shared library.</P>
21386 <DIV class="shell">
21387 <PRE>
21388 $ csc -sv modname.scm modname_wrap.c modname_impl.c -o modname.so
21389 </PRE>
21390 </DIV>
21391 <P>This library can then be loaded by scheme code with the <CODE>
21392 (require 'modname)</CODE> function. See <A href="http://www.call-with-current-continuation.org/manual/Loading-extension-libraries.html">
21393  Loading-extension-libraries</A> in the eval unit inside the CHICKEN
21394  manual for more information.</P>
21395 <P>Another alternative is to run SWIG normally and create a scheme file
21396  that contains <CODE>(declare (uses<I> modname</I>))</CODE> and then
21397  compile that file into the shared library as well. For example, inside
21398  the <TT>mod_load.scm</TT> file,</P>
21399 <DIV class="targetlang">
21400 <PRE>
21401 (declare (uses mod1))
21402 (declare (uses mod2))
21403 </PRE>
21404 </DIV>
21405 <P>Which would then be compiled with</P>
21406 <DIV class="shell">
21407 <PRE>
21408 $ swig -chicken mod1.i
21409 $ swig -chicken mod2.i
21410 $ csc -sv mod_load.scm mod1.scm mod2.scm mod1_wrap.c mod2_wrap.c mod1_impl.c mod2_impl.c -o mod.so
21411 </PRE>
21412 </DIV>
21413 <P>Then the extension library can be loaded with <CODE>(require 'mod)</CODE>
21414 . As we can see here, <TT>mod_load.scm</TT> contains the code that gets
21415  executed when the module is loaded. All this code does is load both
21416  mod1 and mod2. As we can see, this technique is more useful when you
21417  want to combine a few SWIG modules into one chicken extension library,
21418  especially if modules are related by <CODE>%import</CODE></P>
21419 <P>In either method, the files that are compiled into the shared library
21420  could also be packaged into an egg. The <TT>mod1_wrap.c</TT> and <TT>
21421 mod2_wrap.c</TT> files that are created by SWIG are stand alone and do
21422  not need SWIG to be installed to be compiled. Thus the egg could be
21423  distributed and used by anyone, even if SWIG is not installed.</P>
21424 <P>See the <TT>Examples/chicken/egg</TT> directory in the SWIG source
21425  for an example that builds two eggs, one using the first method and one
21426  using the second method.</P>
21427 <H3><A name="Chicken_nn15"></A>19.4.3 Linking multiple SWIG modules with
21428  TinyCLOS</H3>
21429 <P>Linking together multiple modules that share type information using
21430  the <CODE>%import</CODE> directive while also using <TT>-proxy</TT> is
21431  more complicated. For example, if <TT>mod2.i</TT> imports <TT>mod1.i</TT>
21432 , then the <TT>mod2.scm</TT> file contains references to symbols
21433  declared in <TT>mod1.scm</TT>, and thus a <CODE>(declare (uses<I> mod1</I>
21434 ))</CODE> or <CODE>(require '<I>mod1</I>)</CODE> must be exported to the
21435  top of <TT>mod2.scm</TT>. By default, when SWIG encounters an <CODE>
21436 %import &quot;modname.i&quot;</CODE> directive, it exports <CODE>(declare (uses<I>
21437  modname</I>))</CODE> into the scm file. This works fine unless mod1 was
21438  compiled with the <TT>-nounit</TT> argument or was compiled into an
21439  extension library with other modules under a different name.</P>
21440 <P>One option is to override the automatic generation of <CODE>(declare
21441  (uses mod1))</CODE> by passing the <TT>-noclosuses</TT> option to SWIG
21442  when compiling <TT>mod2.i</TT>. SWIG then provides the <CODE>
21443 %insert(closprefix) %{ %}</CODE> directive. Any scheme code inside that
21444  directive is inserted into the generated .scm file, and if <TT>mod1</TT>
21445  was compiled with <TT>-nounit</TT>, the directive should contain <CODE>
21446 (require 'mod1)</CODE>. This option allows for mixed loading as well,
21447  where some modules are imported with <CODE>(declare (uses<I> modname</I>
21448 ))</CODE> (which means they were compiled without -nounit) and some are
21449  imported with <CODE>(require 'modname)</CODE>.</P>
21450 <P>The other option is to use the second idea in the above section.
21451  Compile all the modules normally, without any <CODE>%insert(closprefix)</CODE>
21452 , <TT>-nounit</TT>, or <TT>-noclosuses</TT>. Then the modules will
21453  import each other correctly with <CODE>(declare (uses ...))</CODE>. To
21454  create an extension library or an egg, just create a <TT>
21455 module_load.scm</TT> file that <CODE>(declare (uses ...))</CODE> all the
21456  modules.</P>
21457 <H2><A name="Chicken_nn16"></A>19.5 Typemaps</H2>
21458 <P> The Chicken module handles all types via typemaps. This information
21459  is read from <CODE>Lib/chicken/typemaps.i</CODE> and <CODE>
21460 Lib/chicken/chicken.swg</CODE>.</P>
21461 <H2><A name="Chicken_nn17"></A>19.6 Pointers</H2>
21462 <P> For pointer types, SWIG uses CHICKEN tagged pointers. A tagged
21463  pointer is an ordinary CHICKEN pointer with an extra slot for a void *.
21464  With SWIG CHICKEN, this void * is a pointer to a type-info structure.
21465  So each pointer used as input or output from the SWIG-generated CHICKEN
21466  wrappers will have type information attached to it. This will let the
21467  wrappers correctly determine which method should be called according to
21468  the object type hierarchy exposed in the SWIG interface files.</P>
21469 <P> To construct a Scheme object from a C pointer, the wrapper code
21470  calls the function <CODE>SWIG_NewPointerObj(void *ptr, swig_type_info
21471  *type, int owner)</CODE>, The function that calls <CODE>
21472 SWIG_NewPointerObj</CODE> must have a variable declared <CODE>C_word
21473  *known_space = C_alloc(C_SIZEOF_SWIG_POINTER);</CODE> It is ok to call <CODE>
21474 SWIG_NewPointerObj</CODE> more than once, just make sure known_space has
21475  enough space for all the created pointers.</P>
21476 <P> To get the pointer represented by a CHICKEN tagged pointer, the
21477  wrapper code calls the function <CODE>SWIG_ConvertPtr(C_word s, void
21478  **result, swig_type_info *type, int flags)</CODE>, passing a pointer to
21479  a struct representing the expected pointer type. flags is either zero
21480  or SWIG_POINTER_DISOWN (see below).</P>
21481 <H3><A name="collection"></A>19.6.1 Garbage collection</H3>
21482 <P>If the owner flag passed to <CODE>SWIG_NewPointerObj</CODE> is 1, <CODE>
21483 NewPointerObj</CODE> will add a finalizer to the type which will call
21484  the destructor or delete method of that type. The destructor and delete
21485  functions are no longer exported for use in scheme code, instead SWIG
21486  and chicken manage pointers. In situations where SWIG knows that a
21487  function is returning a type that should be garbage collected, SWIG
21488  will automatically set the owner flag to 1. For other functions, the <CODE>
21489 %newobject</CODE> directive must be specified for functions whose return
21490  values should be garbage collected. See <A href="#ownership">Object
21491  ownership and %newobject</A> for more information.</P>
21492 <P>In situations where a C or C++ function will assume ownership of a
21493  pointer, and thus chicken should no longer garbage collect it, SWIG
21494  provides the <CODE>DISOWN</CODE> input typemap. After applying this
21495  typemap (see the <A href="Typemaps.html">Typemaps chapter</A> for more
21496  information on how to apply typemaps), any pointer that gets passed in
21497  will no longer be garbage collected. An object is disowned by passing
21498  the <CODE>SWIG_POINTER_DISOWN</CODE> flag to <CODE>SWIG_ConvertPtr</CODE>
21499 .<B> Warning:</B> Since the lifetime of the object is now controlled by
21500  the underlying code, the object might get deleted while the scheme code
21501  still holds a pointer to it. Further use of this pointer can lead to a
21502  crash.</P>
21503 <P>Adding a finalizer function from C code was added to chicken in the
21504  1.89 release, so garbage collection does not work for chicken versions
21505  below 1.89. If you would like the SWIG generated code to work with
21506  chicken 1.40 to 1.89, pass the <CODE>-nocollection</CODE> argument to
21507  SWIG. This will not export code inside the _wrap.c file to register
21508  finalizers, and will then export destructor functions which must be
21509  called manually.</P>
21510 <H2><A name="Chicken_nn18"></A>19.7 Unsupported features and known
21511  problems</H2>
21512 <UL>
21513 <LI>No director support.</LI>
21514 <LI>No support for c++ standard types like std::vector.</LI>
21515 <LI>The TinyCLOS wrappers for overloaded functions will not work
21516  correctly when using <A href="#SWIGPlus_default_args">
21517 %feature(compactdefaultargs)</A>.</LI>
21518 </UL>
21519 <H3><A name="Chicken_nn19"></A>19.7.1 TinyCLOS problems with Chicken
21520  version &lt;= 1.92</H3>
21521 <P>In Chicken versions equal to or below 1.92, TinyCLOS has a limitation
21522  such that generic methods do not properly work on methods with
21523  different number of specializers: TinyCLOS assumes that every method
21524  added to a generic function will have the same number of specializers.
21525  SWIG generates functions with different lengths of specializers when
21526  C/C++ functions are overloaded. For example, the code</P>
21527 <DIV class="code">
21528 <PRE>
21529 class Foo {};
21530 int foo(int a, Foo *b);
21531 int foo(int a);
21532 </PRE>
21533 </DIV>
21534 <P>will produce scheme code</P>
21535 <DIV class="targetlang">
21536 <PRE>
21537 (define-method (foo (arg0 &lt;top&gt;) (arg1 &lt;Foo&gt;)) (<I>call primitive function</I>))
21538 (define-method (foo (arg0 &lt;top&gt;)) (<I>call primitive function</I>))
21539 </PRE>
21540 </DIV>
21541 <P>Using unpatched TinyCLOS, the second <CODE>(define-method)</CODE>
21542  will replace the first one, so calling <CODE>(foo 3 f)</CODE> will
21543  produce an error.</P>
21544 <P>There are three solutions to this. The easist is to upgrade to the
21545  latest Chicken version. Otherwise, the file <TT>
21546 Lib/chicken/tinyclos-multi-generic.patch</TT> in the SWIG source
21547  contains a patch against tinyclos.scm inside the 1.92 chicken source to
21548  add support into TinyCLOS for multi-argument generics. (This patch was
21549  accepted into Chicken) This requires chicken to be rebuilt and custom
21550  install of chicken. An alternative is the <TT>
21551 Lib/chicken/multi-generic.scm</TT> file in the SWIG source. This file
21552  can be loaded after TinyCLOS is loaded, and it will override some
21553  functions inside TinyCLOS to correctly support multi-argument generics.
21554  Please see the comments at the top of both files for more information.</P>
21555 <HR NOSHADE>
21556
21557 <!-- Hand-written HTML -->
21558 <H1><A name="Guile"></A>20 SWIG and Guile</H1>
21559
21560 <!-- INDEX -->
21561 <DIV class="sectiontoc">
21562 <UL>
21563 <LI><A href="#Guile_nn2">Meaning of &quot;Module&quot;</A></LI>
21564 <LI><A href="#Guile_nn3">Using the SCM or GH Guile API</A></LI>
21565 <LI><A href="#Guile_nn4">Linkage</A>
21566 <UL>
21567 <LI><A href="#Guile_nn5">Simple Linkage</A></LI>
21568 <LI><A href="#Guile_nn6">Passive Linkage</A></LI>
21569 <LI><A href="#Guile_nn7">Native Guile Module Linkage</A></LI>
21570 <LI><A href="#Guile_nn8">Old Auto-Loading Guile Module Linkage</A></LI>
21571 <LI><A href="#Guile_nn9">Hobbit4D Linkage</A></LI>
21572 </UL>
21573 </LI>
21574 <LI><A href="#Guile_nn10">Underscore Folding</A></LI>
21575 <LI><A href="#Guile_nn11">Typemaps</A></LI>
21576 <LI><A href="#Guile_nn12">Representation of pointers as smobs</A>
21577 <UL>
21578 <LI><A href="#Guile_nn13">GH Smobs</A></LI>
21579 <LI><A href="#Guile_nn14">SCM Smobs</A></LI>
21580 <LI><A href="#Guile_nn15">Garbage Collection</A></LI>
21581 </UL>
21582 </LI>
21583 <LI><A href="#Guile_nn16">Exception Handling</A></LI>
21584 <LI><A href="#Guile_nn17">Procedure documentation</A></LI>
21585 <LI><A href="#Guile_nn18">Procedures with setters</A></LI>
21586 <LI><A href="#Guile_nn19">GOOPS Proxy Classes</A>
21587 <UL>
21588 <LI><A href="#Guile_nn20">Naming Issues</A></LI>
21589 <LI><A href="#Guile_nn21">Linking</A></LI>
21590 </UL>
21591 </LI>
21592 </UL>
21593 </DIV>
21594 <!-- INDEX -->
21595 <P> This section details guile-specific support in SWIG.</P>
21596 <H2><A name="Guile_nn2"></A>20.1 Meaning of &quot;Module&quot;</H2>
21597 <P> There are three different concepts of &quot;module&quot; involved, defined
21598  separately for SWIG, Guile, and Libtool. To avoid horrible confusion,
21599  we explicitly prefix the context, e.g., &quot;guile-module&quot;.</P>
21600 <H2><A name="Guile_nn3"></A>20.2 Using the SCM or GH Guile API</H2>
21601 <P>The guile module can currently export wrapper files that use the
21602  guile GH interface or the SCM interface. This is controlled by an
21603  argument passed to swig. The &quot;-gh&quot; argument causes swig to output GH
21604  code, and the &quot;-scm&quot; argument causes swig to output SCM code. Right now
21605  the &quot;-scm&quot; argument is the default. The &quot;-scm&quot; wrapper generation
21606  assumes a guile version &gt;= 1.6 and has several advantages over the
21607  &quot;-gh&quot; wrapper generation including garbage collection and GOOPS
21608  support. The &quot;-gh&quot; wrapper generation can be used for older versions of
21609  guile. The guile GH wrapper code generation is depreciated and the SCM
21610  interface is the default. The SCM and GH interface differ greatly in
21611  how they store pointers and have completely different run-time code.
21612  See below for more info.</P>
21613 <P>The GH interface to guile is deprecated. Read more about why in the <A
21614 href="http://www.gnu.org/software/guile/docs/guile-ref/GH-deprecation.html">
21615 Guile manual</A>. The idea of the GH interface was to provide a high
21616  level API that other languages and projects could adopt. This was a
21617  good idea, but didn't pan out well for general development. But for the
21618  specific, minimal uses that the SWIG typemaps put the GH interface to
21619  use is ideal for using a high level API. So even though the GH
21620  interface is depreciated, SWIG will continue to use the GH interface
21621  and provide mappings from the GH interface to whatever API we need. We
21622  can maintain this mapping where guile failed because SWIG uses a small
21623  subset of all the GH functions which map easily. All the guile typemaps
21624  like typemaps.i and std_vector.i will continue to use the GH functions
21625  to do things like create lists of values, convert strings to integers,
21626  etc. Then every language module will define a mapping between the GH
21627  interface and whatever custom API the language uses. This is currently
21628  implemented by the guile module to use the SCM guile API rather than
21629  the GH guile API. For example, here are some of the current mapping
21630  file for the SCM API</P>
21631 <DIV class="code">
21632 <PRE>
21633
21634 #define gh_append2(a, b) scm_append(scm_listify(a, b, SCM_UNDEFINED)) 
21635 #define gh_apply(a, b) scm_apply(a, b, SCM_EOL) 
21636 #define gh_bool2scm SCM_BOOL 
21637 #define gh_boolean_p SCM_BOOLP 
21638 #define gh_car SCM_CAR 
21639 #define gh_cdr SCM_CDR 
21640 #define gh_cons scm_cons 
21641 #define gh_double2scm scm_make_real 
21642 ...
21643 </PRE>
21644 </DIV>
21645 <P>This file is parsed by SWIG at wrapper generation time, so every
21646  reference to a gh_ function is replaced by a scm_ function in the
21647  wrapper file. Thus the gh_ function calls will never be seen in the
21648  wrapper; the wrapper will look exactly like it was generated for the
21649  specific API. Currently only the guile language module has created a
21650  mapping policy from gh_ to scm_, but there is no reason other languages
21651  (like mzscheme or chicken) couldn't also use this. If that happens,
21652  there is A LOT less code duplication in the standard typemaps.</P>
21653 <H2><A name="Guile_nn4"></A>20.3 Linkage</H2>
21654 <P> Guile support is complicated by a lack of user community
21655  cohesiveness, which manifests in multiple shared-library usage
21656  conventions. A set of policies implementing a usage convention is
21657  called a<B> linkage</B>.</P>
21658 <H3><A name="Guile_nn5"></A>20.3.1 Simple Linkage</H3>
21659 <P> The default linkage is the simplest; nothing special is done. In
21660  this case the function <CODE>SWIG_init()</CODE> is exported. Simple
21661  linkage can be used in several ways:</P>
21662 <UL>
21663 <LI><B>Embedded Guile, no modules.</B> You want to embed a Guile
21664  interpreter into your program; all bindings made by SWIG shall show up
21665  in the root module. Then call <CODE>SWIG_init()</CODE> in the <CODE>
21666 inner_main()</CODE> function. See the &quot;simple&quot; and &quot;matrix&quot; examples
21667  under <CODE>Examples/guile</CODE>.</LI>
21668 <LI>
21669 <P><B>Dynamic module mix-in.</B> You want to create a Guile module using
21670  <CODE>define-module</CODE>, containing both Scheme code and bindings
21671  made by SWIG; you want to load the SWIG modules as shared libraries
21672  into Guile.</P>
21673 <DIV class="targetlang">
21674 <PRE>
21675 (define-module (my module))
21676 (define my-so (dynamic-link &quot;./example.so&quot;))
21677 (dynamic-call &quot;SWIG_init&quot; my-so) ; make SWIG bindings
21678 ;; Scheme definitions can go here
21679 </PRE>
21680 </DIV>
21681 <P> Newer Guile versions provide a shorthand for <CODE>dynamic-link</CODE>
21682  and <CODE>dynamic-call</CODE>:</P>
21683 <DIV class="targetlang">
21684 <PRE>
21685 (load-extension &quot;./example.so&quot; &quot;SWIG_init&quot;)
21686 </PRE>
21687 </DIV>
21688 <P> You need to explicitly export those bindings made by SWIG that you
21689  want to import into other modules:</P>
21690 <DIV class="targetlang">
21691 <PRE>
21692 (export foo bar)
21693 </PRE>
21694 </DIV>
21695 <P> In this example, the procedures <CODE>foo</CODE> and <CODE>bar</CODE>
21696  would be exported. Alternatively, you can export all bindings with the
21697  following module-system hack:</P>
21698 <DIV class="targetlang">
21699 <PRE>
21700 (module-map (lambda (sym var)
21701               (module-export! (current-module) (list sym)))
21702             (current-module))
21703 </PRE>
21704 </DIV>
21705 <P>SWIG can also generate this Scheme stub (from <CODE>define-module</CODE>
21706  up to <CODE>export</CODE>) semi-automagically if you pass it the
21707  command-line argument <CODE>-scmstub</CODE>. The code will be exported
21708  in a file called <CODE><I>module</I>.scm</CODE> in the directory
21709  specified by <CODE>-outdir</CODE> or the current directory if <CODE>
21710 -outdir</CODE> is not specified. Since SWIG doesn't know how to load
21711  your extension module (with <CODE>dynamic-link</CODE> or <CODE>
21712 load-extension</CODE>), you need to supply this information by including
21713  a directive like this in the interface file:</P>
21714 <DIV class="code">
21715 <PRE>
21716 %scheme %{ (load-extension &quot;./example.so&quot; &quot;SWIG_init&quot;) %}
21717 </PRE>
21718 </DIV>
21719 <P> (The <CODE>%scheme</CODE> directive allows to insert arbitrary
21720  Scheme code into the generated file <CODE><VAR>module.scm</VAR></CODE>;
21721  it is placed between the <CODE>define-module</CODE> form and the <CODE>
21722 export</CODE> form.)</P>
21723 </LI>
21724 </UL>
21725 <P>If you want to include several SWIG modules, you would need to rename
21726  <CODE>SWIG_init</CODE> via a preprocessor define to avoid symbol
21727  clashes. For this case, however, passive linkage is available.</P>
21728 <H3><A name="Guile_nn6"></A>20.3.2 Passive Linkage</H3>
21729 <P>Passive linkage is just like simple linkage, but it generates an
21730  initialization function whose name is derived from the module and
21731  package name (see below).</P>
21732 <P>You should use passive linkage rather than simple linkage when you
21733  are using multiple modules.</P>
21734 <H3><A name="Guile_nn7"></A>20.3.3 Native Guile Module Linkage</H3>
21735 <P>SWIG can also generate wrapper code that does all the Guile module
21736  declarations on its own if you pass it the <CODE>-Linkage module</CODE>
21737  command-line option. This requires Guile 1.5.0 or later.</P>
21738 <P>The module name is set with the <CODE>-package</CODE> and <CODE>
21739 -module</CODE> command-line options. Suppose you want to define a module
21740  with name <CODE>(my lib foo)</CODE>; then you would have to pass the
21741  options <CODE>-package<VAR> my</VAR>/<VAR>lib</VAR> -module<VAR> foo</VAR>
21742 </CODE>. Note that the last part of the name can also be set via the
21743  SWIG directive <CODE>%module</CODE>.</P>
21744 <P>You can use this linkage in several ways:</P>
21745 <UL>
21746 <LI><B>Embedded Guile with SWIG modules.</B> You want to embed a Guile
21747  interpreter into your program; the SWIG bindings shall be put into
21748  different modules. Simply call the function <CODE>scm_init_<VAR>my</VAR>
21749 _<VAR>modules</VAR>_<VAR>foo</VAR>_module</CODE> in the <CODE>
21750 inner_main()</CODE> function.</LI>
21751 <LI><B>Dynamic Guile modules.</B> You want to load the SWIG modules as
21752  shared libraries into Guile; all bindings are automatically put in
21753  newly created Guile modules.<DIV class="targetlang">
21754 <PRE>
21755 (define my-so (dynamic-link &quot;./foo.so&quot;))
21756 ;; create new module and put bindings there:
21757 (dynamic-call &quot;scm_init_my_modules_foo_module&quot; my-so) 
21758 </PRE>
21759 </DIV> Newer Guile versions have a shorthand procedure for this:<DIV class="targetlang">
21760 <PRE>
21761 (load-extension &quot;./foo.so&quot; &quot;scm_init_my_modules_foo_module&quot;)
21762 </PRE>
21763 </DIV></LI>
21764 </UL>
21765 <H3><A name="Guile_nn8"></A>20.3.4 Old Auto-Loading Guile Module Linkage</H3>
21766 <P>Guile used to support an autoloading facility for object-code
21767  modules. This support has been marked deprecated in version 1.4.1 and
21768  is going to disappear sooner or later. SWIG still supports building
21769  auto-loading modules if you pass it the <CODE>-Linkage ltdlmod</CODE>
21770  command-line option.</P>
21771 <P>Auto-loading worked like this: Suppose a module with name <CODE>(my
21772  lib foo)</CODE> is required and not loaded yet. Guile will then search
21773  all directories in its search path for a Scheme file <CODE>
21774 my/modules/foo.scm</CODE> or a shared library <CODE><VAR>my</VAR>/<VAR>
21775 modules</VAR>/lib<VAR>foo</VAR>.so</CODE> (or <CODE><VAR>my</VAR>/<VAR>
21776 modules</VAR>/lib<VAR>foo</VAR>.la</CODE>; see the GNU libtool
21777  documentation). If a shared library is found that contains the symbol <CODE>
21778 scm_init_<VAR>my</VAR>_<VAR>modules</VAR>_<VAR>foo</VAR>_module</CODE>,
21779  the library is loaded, and the function at that symbol is called with
21780  no arguments in order to initialize the module.</P>
21781 <P>When invoked with the <CODE>-Linkage ltdlmod</CODE> command-line
21782  option, SWIG generates an exported module initialization function with
21783  an appropriate name.</P>
21784 <H3><A name="Guile_nn9"></A>20.3.5 Hobbit4D Linkage</H3>
21785 <P> The only other linkage supported at this time creates shared object
21786  libraries suitable for use by hobbit's <CODE>(hobbit4d link)</CODE>
21787  guile module. This is called the &quot;hobbit&quot; linkage, and requires also
21788  using the &quot;-package&quot; command line option to set the part of the module
21789  name before the last symbol. For example, both command lines:</P>
21790 <DIV class="shell">
21791 <PRE>
21792 swig -guile -package my/lib foo.i
21793 swig -guile -package my/lib -module foo foo.i
21794 </PRE>
21795 </DIV>
21796 <P> would create module <CODE>(my lib foo)</CODE> (assuming in the first
21797  case foo.i declares the module to be &quot;foo&quot;). The installed files are
21798  my/lib/libfoo.so.X.Y.Z and friends. This scheme is still very
21799  experimental; the (hobbit4d link) conventions are not well understood.</P>
21800 <H2><A name="Guile_nn10"></A>20.4 Underscore Folding</H2>
21801 <P> Underscores are converted to dashes in identifiers. Guile support
21802  may grow an option to inhibit this folding in the future, but no one
21803  has complained so far.</P>
21804 <P>You can use the SWIG directives <CODE>%name</CODE> and <CODE>%rename</CODE>
21805  to specify the Guile name of the wrapped functions and variables (see
21806  CHANGES).</P>
21807 <H2><A name="Guile_nn11"></A>20.5 Typemaps</H2>
21808 <P> The Guile module handles all types via typemaps. This information is
21809  read from <CODE>Lib/guile/typemaps.i</CODE>. Some non-standard typemap
21810  substitutions are supported:</P>
21811 <UL>
21812 <LI><CODE>$descriptor</CODE> expands to a type descriptor for use with
21813  the <CODE>SWIG_NewPointerObj()</CODE> and <CODE>SWIG_ConvertPtr</CODE>
21814  functions.</LI>
21815 <LI>For pointer types, <CODE>$*descriptor</CODE> expands to a descriptor
21816  for the direct base type (i.e., one pointer is stripped), whereas <CODE>
21817 $basedescriptor</CODE> expands to a descriptor for the base type (i.e.,
21818  all pointers are stripped).</LI>
21819 </UL>
21820 <P>A function returning <CODE>void</CODE> (more precisely, a function
21821  whose <CODE>out</CODE> typemap returns <CODE>SCM_UNSPECIFIED</CODE>) is
21822  treated as returning no values. In <CODE>argout</CODE> typemaps, one
21823  can use the macro <CODE>GUILE_APPEND_RESULT</CODE> in order to append a
21824  value to the list of function return values.</P>
21825 <P>Multiple values can be passed up to Scheme in one of three ways:</P>
21826 <UL>
21827 <LI>
21828 <P><EM>Multiple values as lists.</EM> By default, if more than one value
21829  is to be returned, a list of the values is created and returned; to
21830  switch back to this behavior, use</P>
21831 <DIV class="code">
21832 <PRE>
21833 %values_as_list;</PRE>
21834 </DIV></LI>
21835 <LI>
21836 <P><EM>Multiple values as vectors.</EM> By issuing</P>
21837 <DIV class="code">
21838 <PRE>
21839 %values_as_vector;</PRE>
21840 </DIV>
21841 <P> vectors instead of lists will be used.</P>
21842 </LI>
21843 <LI>
21844 <P><EM>Multiple values for multiple-value continuations.</EM><STRONG>
21845  This is the most elegant way.</STRONG> By issuing</P>
21846 <DIV class="code">
21847 <PRE>
21848 %multiple_values;</PRE>
21849 </DIV>
21850 <P> multiple values are passed to the multiple-value continuation, as
21851  created by <CODE>call-with-values</CODE> or the convenience macro <CODE>
21852 receive</CODE>. The latter is available if you issue <CODE>(use-modules
21853  (srfi srfi-8))</CODE>. Assuming that your <CODE>divide</CODE> function
21854  wants to return two values, a quotient and a remainder, you can write:</P>
21855 <DIV class="targetlang">
21856 <PRE>
21857 (receive (quotient remainder)
21858     (divide 35 17)
21859   <VAR>body</VAR>...)
21860 </PRE>
21861 </DIV>
21862 <P> In <CODE><VAR>body</VAR></CODE>, the first result of <CODE>divide</CODE>
21863  will be bound to the variable <CODE>quotient</CODE>, and the second
21864  result to <CODE>remainder</CODE>.</P>
21865 </LI>
21866 </UL>
21867 <P> See also the &quot;multivalue&quot; example.</P>
21868 <P>Constants are exported as a function that returns the value. The
21869  %feature(&quot;constasvar&quot;) can be applied to any constant, immutable
21870  variable, or enum. Instead of exporting the constant as a function that
21871  must be called, the constant will appear as a scheme variable. See <A href="#features">
21872 Features and the %feature directive</A> for info on how to apply the
21873  %feature.</P>
21874 <H2><A name="Guile_nn12"></A>20.6 Representation of pointers as smobs</H2>
21875 <P> For pointer types, SWIG uses Guile smobs. SWIG smobs print like
21876  this: <CODE>#&lt;swig struct xyzzy * 0x1234affe&gt;</CODE> Two of them are <CODE>
21877 equal?</CODE> if and only if they have the same type and value.</P>
21878 <P> To construct a Scheme object from a C pointer, the wrapper code
21879  calls the function <CODE>SWIG_NewPointerObj()</CODE>, passing a pointer
21880  to a struct representing the pointer type. The type index to store in
21881  the upper half of the CAR is read from this struct. To get the pointer
21882  represented by a smob, the wrapper code calls the function <CODE>
21883 SWIG_ConvertPtr()</CODE>, passing a pointer to a struct representing the
21884  expected pointer type. See also <A href="#runtime_type_checker">The
21885  run-time type checker</A>. If the Scheme object passed was not a SWIG
21886  smob representing a compatible pointer, a <CODE>wrong-type-arg</CODE>
21887  exception is raised.</P>
21888 <H3><A name="Guile_nn13"></A>20.6.1 GH Smobs</H3>
21889 <P> In earlier versions of SWIG, C pointers were represented as Scheme
21890  strings containing a hexadecimal rendering of the pointer value and a
21891  mangled type name. As Guile allows registering user types, so-called
21892  &quot;smobs&quot; (small objects), a much cleaner representation has been
21893  implemented now. The details will be discussed in the following.</P>
21894 <P> A smob is a cons cell where the lower half of the CAR contains the
21895  smob type tag, while the upper half of the CAR and the whole CDR are
21896  available. Every module creates its own smob type in the clientdata
21897  field of the module. So the lower 16 bits of the car of the smob store
21898  the tag and the upper 16 bits store the index this type is in the
21899  array. We can then, given a smob, find its swig_type_info struct by
21900  using the tag (lower 16 bits of car) to find which module this type is
21901  in (since each tag is unique for the module). Then we use the upper 16
21902  bits to index into the array of types attached to this module. Looking
21903  up the module from the tag is worst case O(# of modules) but average
21904  case O(1). This is because the modules are stored in a circularly
21905  linked list, and when we start searching the modules for the tag, we
21906  start looking with the module that the function doing the lookup is in.
21907  SWIG_Guile_ConvertPtr() takes as its first argument the
21908  swig_module_info * of the calling function, which is where we start
21909  comparing tags. Most types will be looked up in the same module that
21910  created them, so the first module we check will most likely be correct.
21911  Once we have a swig_type_info structure, we loop through the linked
21912  list of casts, using pointer comparisons.</P>
21913 <H3><A name="Guile_nn14"></A>20.6.2 SCM Smobs</H3>
21914 <P>The SCM interface (using the &quot;-scm&quot; argument to swig) uses
21915  swigrun.swg. The whole type system, when it is first initialized,
21916  creates two smobs named &quot;swig&quot; and &quot;collected_swig&quot;. The swig smob is
21917  used for non-garbage collected smobs, while the collected_swig smob is
21918  used as described below. Each smob has the same format, which is a
21919  double cell created by SCM_NEWSMOB2() The first word of data is the
21920  pointer to the object and the second word of data is the swig_type_info
21921  * structure describing this type. This is a lot easier than the GH
21922  interface above because we can store a pointer to the type info
21923  structure right in the type. With the GH interface, there was not
21924  enough room in the smob to store two whole words of data so we needed
21925  to store part of the &quot;swig_type_info address&quot; in the smob tag. If a
21926  generated GOOPS module has been loaded, smobs will be wrapped by the
21927  corresponding GOOPS class.</P>
21928 <H3><A name="Guile_nn15"></A>20.6.3 Garbage Collection</H3>
21929 <P>Garbage collection is a feature of the new SCM interface, and it is
21930  automatically included if you pass the &quot;-scm&quot; flag to swig. Thus the
21931  swig garbage collection support requires guile &gt;1.6. Garbage collection
21932  works like this. Every swig_type_info structure stores in its
21933  clientdata field a pointer to the destructor for this type. The
21934  destructor is the generated wrapper around the delete function. So swig
21935  still exports a wrapper for the destructor, it just does not call
21936  scm_c_define_gsubr() for the wrapped delete function. So the only way
21937  to delete an object is from the garbage collector, since the delete
21938  function is not available to scripts. How swig determines if a type
21939  should be garbage collected is exactly like described in <A href="#ownership">
21940  Object ownership and %newobject</A> in the SWIG manual. All typemaps
21941  use an $owner var, and the guile module replaces $owner with 0 or 1
21942  depending on feature:new.</P>
21943 <H2><A name="Guile_nn16"></A>20.7 Exception Handling</H2>
21944 <P> SWIG code calls <CODE>scm_error</CODE> on exception, using the
21945  following mapping:<DIV class="code">
21946 <PRE>
21947       MAP(SWIG_MemoryError,     &quot;swig-memory-error&quot;);
21948       MAP(SWIG_IOError,         &quot;swig-io-error&quot;);
21949       MAP(SWIG_RuntimeError,    &quot;swig-runtime-error&quot;);
21950       MAP(SWIG_IndexError,      &quot;swig-index-error&quot;);
21951       MAP(SWIG_TypeError,       &quot;swig-type-error&quot;);
21952       MAP(SWIG_DivisionByZero,  &quot;swig-division-by-zero&quot;);
21953       MAP(SWIG_OverflowError,   &quot;swig-overflow-error&quot;);
21954       MAP(SWIG_SyntaxError,     &quot;swig-syntax-error&quot;);
21955       MAP(SWIG_ValueError,      &quot;swig-value-error&quot;);
21956       MAP(SWIG_SystemError,     &quot;swig-system-error&quot;);
21957 </PRE>
21958 </DIV></P>
21959 <P> The default when not specified here is to use &quot;swig-error&quot;. See
21960  Lib/exception.i for details.</P>
21961 <H2><A name="Guile_nn17"></A>20.8 Procedure documentation</H2>
21962 <P>If invoked with the command-line option <CODE>-procdoc<VAR> file</VAR>
21963 </CODE>, SWIG creates documentation strings for the generated wrapper
21964  functions, describing the procedure signature and return value, and
21965  writes them to<VAR> file</VAR>. You need Guile 1.4 or later to make use
21966  of the documentation files.</P>
21967 <P>SWIG can generate documentation strings in three formats, which are
21968  selected via the command-line option <CODE>-procdocformat<VAR> format</VAR>
21969 </CODE>:</P>
21970 <UL>
21971 <LI><CODE>guile-1.4</CODE> (default): Generates a format suitable for
21972  Guile 1.4.</LI>
21973 <LI><CODE>plain</CODE>: Generates a format suitable for Guile 1.4.1 and
21974  later.</LI>
21975 <LI><CODE>texinfo</CODE>: Generates texinfo source, which must be run
21976  through texinfo in order to get a format suitable for Guile 1.4.1 and
21977  later.</LI>
21978 </UL>
21979 <P>You need to register the generated documentation file with Guile like
21980  this:<DIV class="targetlang">
21981 <PRE>
21982 (use-modules (ice-9 documentation))
21983 (set! documentation-files 
21984       (cons &quot;<VAR>file</VAR>&quot; documentation-files))
21985 </PRE>
21986 </DIV></P>
21987 <P>Documentation strings can be configured using the Guile-specific
21988  typemap argument <CODE>doc</CODE>. See <CODE>Lib/guile/typemaps.i</CODE>
21989  for details.</P>
21990 <H2><A name="Guile_nn18"></A>20.9 Procedures with setters</H2>
21991 <P>For global variables, SWIG creates a single wrapper procedure <CODE>(<VAR>
21992 variable</VAR> :optional value)</CODE>, which is used for both getting
21993  and setting the value. For struct members, SWIG creates two wrapper
21994  procedures <CODE>(<VAR>struct</VAR>-<VAR>member</VAR>-get pointer)</CODE>
21995  and <CODE>(<VAR>struct-member</VAR>-set pointer value)</CODE>.</P>
21996 <P>If invoked with the command-line option <CODE>-emit-setters</CODE> (<EM>
21997 recommended</EM>), SWIG will additionally create procedures with
21998  setters. For global variables, the procedure-with-setter <CODE><VAR>
21999 variable</VAR></CODE> is created, so you can use <CODE>(<VAR>variable</VAR>
22000 )</CODE> to get the value and <CODE>(set! (<VAR>variable</VAR>)<VAR>
22001  value</VAR>)</CODE> to set it. For struct members, the
22002  procedure-with-setter <CODE><VAR>struct</VAR>-<VAR>member</VAR></CODE>
22003  is created, so you can use <CODE>(<VAR>struct</VAR>-<VAR>member</VAR><VAR>
22004  pointer</VAR>)</CODE> to get the value and <CODE>(set! (<VAR>struct</VAR>
22005 -<VAR>member</VAR><VAR> pointer</VAR>)<VAR> value</VAR>)</CODE> to set
22006  it.</P>
22007 <P>If invoked with the command-line option <CODE>-only-setters</CODE>,
22008  SWIG will<EM> only</EM> create procedures with setters, i.e., for
22009  struct members, the procedures <CODE>(<VAR>struct</VAR>-<VAR>member</VAR>
22010 -get pointer)</CODE> and <CODE>(<VAR>struct-member</VAR>-set pointer
22011  value)</CODE> are<EM> not</EM> generated.</P>
22012 <H2><A name="Guile_nn19"></A>20.10 GOOPS Proxy Classes</H2>
22013 <P>SWIG can also generate classes and generic functions for use with
22014  Guile's Object-Oriented Programming System (GOOPS). GOOPS is a
22015  sophisticated object system in the spirit of the Common Lisp Object
22016  System (CLOS).</P>
22017 <P>GOOPS support is only available with the new SCM interface (enabled
22018  with the <CODE>-scm</CODE> command-line option of SWIG). To enable
22019  GOOPS support, pass the <CODE>-proxy</CODE> argument to swig. This will
22020  export the GOOPS wrapper definitions into the <CODE><I>module</I>.scm</CODE>
22021  file in the directory specified by -outdir or the current directory.
22022  GOOPS support requires either passive or module linkage.</P>
22023 <P>The generated file will contain definitions of GOOPS classes
22024  mimicking the C++ class hierarchy.</P>
22025 <P>Enabling GOOPS support implies <CODE>-emit-setters</CODE>.</P>
22026 <P>If <CODE>-emit-slot-accessors</CODE> is also passed as an argument,
22027  then the generated file will contain accessor methods for all the slots
22028  in the classes and for global variables. The input class</P>
22029 <DIV class="code">
22030 <PRE>
22031   class Foo {
22032     public:
22033       Foo(int i) : a(i) {}
22034       int a;
22035       int getMultBy(int i) { return a * i; }
22036       Foo getFooMultBy(int i) { return Foo(a * i); }
22037   }; 
22038   Foo getFooPlus(int i) { return Foo(a + i); }
22039 </PRE>
22040 </DIV>
22041 <P> will produce (if <CODE>-emit-slot-accessors</CODE> is not passed as
22042  a parameter)</P>
22043 <DIV class="targetlang">
22044 <PRE>
22045 (define-class &lt;Foo&gt; (&lt;swig&gt;)
22046   (a #:allocation #:swig-virtual 
22047      #:slot-ref primitive:Foo-a-get 
22048      #:slot-set! primitive:Foo-a-set)
22049   #:metaclass &lt;swig-metaclass&gt;
22050   #:new-function primitive:new-Foo
22051 )
22052 (define-method (getMultBy (swig_smob &lt;Foo&gt;) i)
22053   (primitive:Foo-getMultBy  (slot-ref swig_smob 'smob) i))
22054 (define-method (getFooMultBy (swig_smob &lt;Foo&gt;) i)
22055   (make &lt;Foo&gt; #:init-smob (primitive:Foo-getFooMultBy  (slot-ref swig_smob 'smob) i)))
22056
22057 (define-method (getFooPlus i)
22058   (make &lt;Foo&gt; #:init-smob (primitive:getFooPlus i)))
22059
22060 (export &lt;Foo&gt; getMultBy getFooMultBy getFooPlus )
22061 </PRE>
22062 </DIV>
22063 <P> and will produce (if <CODE>-emit-slot-accessors</CODE> is passed as
22064  a parameter)</P>
22065 <DIV class="targetlang">
22066 <PRE>
22067 (define-class &lt;Foo&gt; (&lt;swig&gt;)
22068   (a #:allocation #:swig-virtual 
22069      #:slot-ref primitive:Foo-a-get 
22070      #:slot-set! primitive:Foo-a-set 
22071      <B>#:accessor a</B>)
22072   #:metaclass &lt;swig-metaclass&gt;
22073   #:new-function primitive:new-Foo
22074 )
22075 (define-method (getMultBy (swig_smob &lt;Foo&gt;) i)
22076   (primitive:Foo-getMultBy  (slot-ref swig_smob 'smob) i))
22077 (define-method (getFooMultBy (swig_smob &lt;Foo&gt;) i)
22078   (make &lt;Foo&gt; #:init-smob (primitive:Foo-getFooMultBy  (slot-ref swig_smob 'smob) i)))
22079
22080 (define-method (getFooPlus i)
22081   (make &lt;Foo&gt; #:init-smob (primitive:getFooPlus i)))
22082
22083 (export &lt;Foo&gt; <B>a</B> getMultBy getFooMultBy getFooPlus )
22084 </PRE>
22085 </DIV>
22086 <P> which can then be used by this code</P>
22087 <DIV class="targetlang">
22088 <PRE>
22089 ;; not using getters and setters
22090 (define foo (make &lt;Foo&gt; #:args '(45)))
22091 (slot-ref foo 'a)
22092 (slot-set! foo 'a 3)
22093 (getMultBy foo 4)
22094 (define foo2 (getFooMultBy foo 7))
22095 (slot-ref foo 'a)
22096 (slot-ref (getFooPlus foo 4) 'a)
22097
22098 ;; using getters and setters
22099 (define foo (make &lt;Foo&gt; #:args '(45)))
22100 (a foo)
22101 (set! (a foo) 5)
22102 (getMultBy foo 4)
22103 (a (getFooMultBy foo 7))
22104 </PRE>
22105 </DIV>
22106 <P>Notice that constructor arguments are passed as a list after the <CODE>
22107 #:args</CODE> keyword. Hopefully in the future the following will be
22108  valid <CODE>(make &lt;Foo&gt; #:a 5 #:b 4)</CODE></P>
22109 <P>Also note that the order the declarations occur in the .i file make a
22110  difference. For example,</P>
22111 <DIV class="code">
22112 <PRE>
22113 %module test
22114
22115 %{ #include &quot;foo.h&quot; %}
22116
22117 %inline %{
22118   int someFunc(Foo &amp;a) {
22119     ...
22120   }
22121 %}
22122
22123 %include &quot;foo.h&quot;
22124 </PRE>
22125 </DIV>
22126 <P> This is a valid SWIG file it will work as you think it will for
22127  primitive support, but the generated GOOPS file will be broken. Since
22128  the <CODE>someFunc</CODE> definition is parsed by SWIG before all the
22129  declarations in foo.h, the generated GOOPS file will contain the
22130  definition of <CODE>someFunc()</CODE> before the definition of &lt;Foo&gt;.
22131  The generated GOOPS file would look like</P>
22132 <DIV class="targetlang">
22133 <PRE>
22134 ;;...
22135
22136 (define-method (someFunc (swig_smob &lt;Foo&gt;))
22137   (primitive:someFunc (slot-ref swig_smob 'smob)))
22138
22139 ;;...
22140
22141 (define-class &lt;Foo&gt; (&lt;swig&gt;)
22142   ;;...
22143 )
22144
22145 ;;...
22146 </PRE>
22147 </DIV>
22148 <P> Notice that &lt;Foo&gt; is used before it is defined. The fix is to just
22149  put the <CODE>%import &quot;foo.h&quot;</CODE> before the <CODE>%inline</CODE>
22150  block.</P>
22151 <H3><A name="Guile_nn20"></A>20.10.1 Naming Issues</H3>
22152 <P>As you can see in the example above, there are potential naming
22153  conflicts. The default exported accessor for the <CODE>Foo::a</CODE>
22154  variable is named <CODE>a</CODE>. The name of the wrapper global
22155  function is <CODE>getFooPlus</CODE>. If the <CODE>-useclassprefix</CODE>
22156  option is passed to swig, the name of all accessors and member
22157  functions will be prepended with the class name. So the accessor will
22158  be called <CODE>Foo-a</CODE> and the member functions will be called <CODE>
22159 Foo-getMultBy</CODE>. Also, if the <CODE>-goopsprefix goops:</CODE>
22160  argument is passed to swig, every identifier will be prefixed by <CODE>
22161 goops:</CODE></P>
22162 <P>Two guile-modules are created by SWIG. The first module contains the
22163  primitive definitions of all the wrapped functions and variables, and
22164  is located either in the _wrap.cxx file (with <CODE>-Linkage module</CODE>
22165 ) or in the scmstub file (if <CODE>-Linkage passive -scmstub</CODE>).
22166  The name of this guile-module is the swig-module name (given on the
22167  command line with the -module argument or with the %module directive)
22168  concatenated with the string &quot;-primitive&quot;. For example, if <CODE>
22169 %module Test</CODE> is set in the swig interface file, the name of the
22170  guile-module in the scmstub or <CODE>-Linkage module</CODE> will be <CODE>
22171 Test-primitive</CODE>. Also, the scmstub file will be named <CODE>
22172 Test-primitive.scm</CODE>. The string &quot;primitive&quot; can be changed by the <CODE>
22173 -primsuffix</CODE> swig argument. So the same interface, with the <CODE>
22174 -primsuffix base</CODE> will produce a module called <CODE>Test-base</CODE>
22175 . The second generated guile-module contains all the GOOPS class
22176  definitions and is located in a file named<I> module</I>.scm in the
22177  directory specified with -outdir or the current directory. The name of
22178  this guile-module is the name of the swig-module (given on the command
22179  line or with the <CODE>%module</CODE> directive). In the previous
22180  example, the GOOPS definitions will be in a file named Test.scm.</P>
22181 <P>Because of the naming conflicts, you can't in general use both the <CODE>
22182 -primitive</CODE> and the GOOPS guile-modules at the same time. To do
22183  this, you need to rename the exported symbols from one or both
22184  guile-modules. For example,</P>
22185 <DIV class="targetlang">
22186 <PRE>
22187 (use-modules ((Test-primitive) #:renamer (symbol-prefix-proc 'primitive:)))
22188 (use-modules ((Test) #:renamer (symbol-prefix-proc 'goops:)))
22189 </PRE>
22190 </DIV>
22191 <P>TODO: Renaming class name prefixes?</P>
22192 <H3><A name="Guile_nn21"></A>20.10.2 Linking</H3>
22193 <P>The guile-modules generated above all need to be linked together.
22194  GOOPS support requires either passive or module linkage. The exported
22195  GOOPS guile-module will be the name of the swig-module and should be
22196  located in a file called<I> Module</I>.scm. This should be installed on
22197  the autoload path for guile, so that <CODE>(use-modules (<I>Package
22198  Module</I>))</CODE> will load everything needed. Thus, the top of the
22199  GOOPS guile-module will contain code to load everything needed by the
22200  interface (the shared library, the scmstub module, etc.). The <CODE>
22201 %goops</CODE> directive inserts arbitrary code into the generated GOOPS
22202  guile-module, and should be used to load the dependent libraries.</P>
22203 <P>This breaks up into three cases</P>
22204 <UL>
22205 <LI><B>Passive Linkage without -scmstub</B>: Note that this linkage
22206  style has the potential for naming conflicts, since the primitive
22207  exported function and variable names are not wrapped in a guile-module
22208  and might conflict with names from the GOOPS guile-module (see above).
22209  Pass the -goopsprefix argument to solve this problem. If the <CODE>
22210 -exportprimitive</CODE> option is passed to SWIG the <CODE>(export ...)</CODE>
22211  code that would be exported into the scmstub file is exported at the
22212  bottom of the generated GOOPS guile-module. The <CODE>%goops</CODE>
22213  directive should contain code to load the .so library.<DIV class="code">
22214 <PRE>
22215 %goops %{ (load-extension &quot;./foo.so&quot; &quot;scm_init_my_modules_foo_module&quot;) %}
22216 </PRE>
22217 </DIV>
22218 <P> Produces the following code at the top of the generated GOOPS
22219  guile-module (with the <CODE>-package my/modules -module foo</CODE>
22220  command line arguments)</P>
22221 <DIV class="targetlang">
22222 <PRE>
22223 (define-module (my modules foo))
22224
22225 ;; %goops directive goes here
22226 (load-extension &quot;./foo.so&quot; &quot;scm_init_my_modules_foo_module&quot;) 
22227
22228 (use-modules (oop goops) (Swig common))
22229 </PRE>
22230 </DIV></LI>
22231 <LI>
22232 <P><B>Passive Linkage with -scmstub</B>: Here, the name of the scmstub
22233  file should be <CODE>Module-primitive.scm</CODE> (with<I> primitive</I>
22234  replaced with whatever is given with the <CODE>-primsuffix</CODE>
22235  argument. The code to load the <CODE>.so</CODE> library should be
22236  located in the <CODE>%scheme</CODE> directive, which will then be added
22237  to the scmstub file. Swig will automatically generate the line <CODE>
22238 (use-modules (<I>Package</I><I> Module-primitive</I>))</CODE> into the
22239  GOOPS guile-module. So if<I> Module-primitive.scm</I> is on the
22240  autoload path for guile, the <CODE>%goops</CODE> directive can be
22241  empty. Otherwise, the <CODE>%goops</CODE> directive should contain
22242  whatever code is needed to load the<I> Module-primitive.scm</I> file
22243  into guile.</P>
22244 <DIV class="targetlang">
22245 <PRE>
22246 %scheme %{ (load-extension &quot;./foo.so&quot; &quot;scm_init_my_modules_foo_module&quot;) %}
22247 // only include the following definition if (my modules foo) cannot
22248 // be loaded automatically
22249 %goops %{ 
22250   (primitive-load &quot;/path/to/foo-primitive.scm&quot;) 
22251   (primitive-load &quot;/path/to/Swig/common.scm&quot;)
22252 %}
22253 </PRE>
22254 </DIV>
22255 <P> Produces the following code at the top of the generated GOOPS
22256  guile-module</P>
22257 <DIV class="targetlang">
22258 <PRE>
22259 (define-module (my modules foo))
22260
22261 ;; %goops directive goes here (if any)
22262 (primitive-load &quot;/path/to/foo-primitive.scm&quot;)
22263 (primitive-load &quot;/path/to/Swig/common.scm&quot;)
22264
22265 (use-modules (oop goops) (Swig common))
22266 (use-modules ((my modules foo-primitive) :renamer (symbol-prefix-proc
22267                                                        'primitive:)))
22268
22269 </PRE>
22270 </DIV></LI>
22271 <LI>
22272 <P><B>Module Linkage</B>: This is very similar to passive linkage with a
22273  scmstub file. Swig will also automatically generate the line <CODE>
22274 (use-modules (<I>Package</I><I> Module-primitive</I>))</CODE> into the
22275  GOOPS guile-module. Again the <CODE>%goops</CODE> directive should
22276  contain whatever code is needed to get that module loaded into guile.</P>
22277 <DIV class="code">
22278 <PRE>
22279 %goops %{ (load-extension &quot;./foo.so&quot; &quot;scm_init_my_modules_foo_module&quot;) %}
22280 </PRE>
22281 </DIV>
22282 <P> Produces the following code at the top of the generated GOOPS
22283  guile-module</P>
22284 <DIV class="targetlang">
22285 <PRE>
22286 (define-module (my modules foo))
22287
22288 ;; %goops directive goes here (if any)
22289 (load-extension &quot;./foo.so&quot; &quot;scm_init_my_modules_foo_module&quot;) 
22290
22291 (use-modules (oop goops) (Swig common))
22292 (use-modules ((my modules foo-primitive) :renamer (symbol-prefix-proc
22293                                                          'primitive:)))
22294
22295 </PRE>
22296 </DIV></LI>
22297 </UL>
22298 <P><B>(Swig common)</B>: The generated GOOPS guile-module also imports
22299  definitions from the (Swig common) guile-module. This module is
22300  included with SWIG and should be installed by SWIG into the autoload
22301  path for guile (based on the configure script and whatever arguments
22302  are passed). If it is not, then the <CODE>%goops</CODE> directive also
22303  needs to contain code to load the <CODE>common.scm</CODE> file into
22304  guile. Also note that if you are trying to install the generated
22305  wrappers on a computer without SWIG installed, you will need to include
22306  the common.swg file along with the install.</P>
22307 <P><B>Multiple Modules</B>: Type dependencies between modules is
22308  supported. For example, if <CODE>mod1</CODE> includes definitions of
22309  some classes, and <CODE>mod2</CODE> includes some classes derived from
22310  classes in <CODE>mod1</CODE>, the generated GOOPS file for <CODE>mod2</CODE>
22311  will declare the correct superclasses. The only problem is that since <CODE>
22312 mod2</CODE> uses symbols from <CODE>mod1</CODE>, the <CODE>mod2</CODE>
22313  GOOPS file must include a <CODE>(use-modules (mod2))</CODE>. Currently,
22314  SWIG does not automatically export this line; it must be included in
22315  the <CODE>%goops</CODE> directive of <CODE>mod2</CODE>. Maybe in the
22316  future SWIG can detect dependencies and export this line. (how do other
22317  language modules handle this problem?)</P>
22318 <HR NOSHADE>
22319 <H1><A name="Java"></A>21 SWIG and Java</H1>
22320
22321 <!-- INDEX -->
22322 <DIV class="sectiontoc">
22323 <UL>
22324 <LI><A href="#java_overview">Overview</A></LI>
22325 <LI><A href="#java_preliminaries">Preliminaries</A>
22326 <UL>
22327 <LI><A href="#running_swig">Running SWIG</A></LI>
22328 <LI><A href="#java_commandline">Additional Commandline Options</A></LI>
22329 <LI><A href="#getting_right_headers">Getting the right header files</A></LI>
22330 <LI><A href="#compiling_dynamic">Compiling a dynamic module</A></LI>
22331 <LI><A href="#using_module">Using your module</A></LI>
22332 <LI><A href="#dynamic_linking_problems">Dynamic linking problems</A></LI>
22333 <LI><A href="#compilation_problems_cpp">Compilation problems and
22334  compiling with C++</A></LI>
22335 <LI><A href="#building_windows">Building on Windows</A>
22336 <UL>
22337 <LI><A href="#visual_studio">Running SWIG from Visual Studio</A></LI>
22338 <LI><A href="#nmake">Using NMAKE</A></LI>
22339 </UL>
22340 </LI>
22341 </UL>
22342 </LI>
22343 <LI><A href="#java_basic_tour">A tour of basic C/C++ wrapping</A>
22344 <UL>
22345 <LI><A href="#module_packages_classes">Modules, packages and generated
22346  Java classes</A></LI>
22347 <LI><A href="#functions">Functions</A></LI>
22348 <LI><A href="#global_variables">Global variables</A></LI>
22349 <LI><A href="#constants">Constants</A></LI>
22350 <LI><A href="#enumerations">Enumerations</A>
22351 <UL>
22352 <LI><A href="#anonymous_enums">Anonymous enums</A></LI>
22353 <LI><A href="#typesafe_enums">Typesafe enums</A></LI>
22354 <LI><A href="#proper_enums">Proper Java enums</A></LI>
22355 <LI><A href="#typeunsafe_enums">Type unsafe enums</A></LI>
22356 <LI><A href="#simple_enums">Simple enums</A></LI>
22357 </UL>
22358 </LI>
22359 <LI><A href="#pointers">Pointers</A></LI>
22360 <LI><A href="#structures">Structures</A></LI>
22361 <LI><A href="#classes">C++ classes</A></LI>
22362 <LI><A href="#inheritance">C++ inheritance</A></LI>
22363 <LI><A href="#pointers_refs_arrays">Pointers, references, arrays and
22364  pass by value</A>
22365 <UL>
22366 <LI><A href="#null_pointers">Null pointers</A></LI>
22367 </UL>
22368 </LI>
22369 <LI><A href="#overloaded_functions">C++ overloaded functions</A></LI>
22370 <LI><A href="#java_default_arguments">C++ default arguments</A></LI>
22371 <LI><A href="#namespaces">C++ namespaces</A></LI>
22372 <LI><A href="#templates">C++ templates</A></LI>
22373 <LI><A href="#smart_pointers">C++ Smart Pointers</A></LI>
22374 </UL>
22375 </LI>
22376 <LI><A href="#further_details">Further details on the generated Java
22377  classes</A>
22378 <UL>
22379 <LI><A href="#imclass">The intermediary JNI class</A>
22380 <UL>
22381 <LI><A href="#imclass_pragmas">The intermediary JNI class pragmas</A></LI>
22382 </UL>
22383 </LI>
22384 <LI><A href="#java_module_class">The Java module class</A>
22385 <UL>
22386 <LI><A href="#module_class_pragmas">The Java module class pragmas</A></LI>
22387 </UL>
22388 </LI>
22389 <LI><A href="#java_proxy_classes">Java proxy classes</A>
22390 <UL>
22391 <LI><A href="#memory_management">Memory management</A></LI>
22392 <LI><A href="#inheritance_mirroring">Inheritance</A></LI>
22393 <LI><A href="#proxy_classes_gc">Proxy classes and garbage collection</A></LI>
22394 <LI><A href="#java_pgcpp">The premature garbage collection prevention
22395  parameter for proxy class marshalling</A></LI>
22396 <LI><A href="#java_multithread_libraries">Single threaded applications
22397  and thread safety</A></LI>
22398 </UL>
22399 </LI>
22400 <LI><A href="#type_wrapper_classes">Type wrapper classes</A></LI>
22401 <LI><A href="#enum_classes">Enum classes</A>
22402 <UL>
22403 <LI><A href="#typesafe_enums_classes">Typesafe enum classes</A></LI>
22404 <LI><A href="#proper_enums_classes">Proper Java enum classes</A></LI>
22405 <LI><A href="#typeunsafe_enums_classes">Type unsafe enum classes</A></LI>
22406 </UL>
22407 </LI>
22408 </UL>
22409 </LI>
22410 <LI><A href="#java_directors">Cross language polymorphism using
22411  directors</A>
22412 <UL>
22413 <LI><A href="#java_enabling_directors">Enabling directors</A></LI>
22414 <LI><A href="#java_directors_classes">Director classes</A></LI>
22415 <LI><A href="#java_directors_overhead">Overhead and code bloat</A></LI>
22416 <LI><A href="#java_directors_example">Simple directors example</A></LI>
22417 <LI><A href="#java_directors_threading">Director threading issues</A></LI>
22418 </UL>
22419 </LI>
22420 <LI><A href="#java_allprotected">Accessing protected members</A></LI>
22421 <LI><A href="#common_customization">Common customization features</A>
22422 <UL>
22423 <LI><A href="#helper_functions">C/C++ helper functions</A></LI>
22424 <LI><A href="#class_extension">Class extension with %extend</A></LI>
22425 <LI><A href="#exception_handling">Exception handling with %exception and
22426  %javaexception</A></LI>
22427 <LI><A href="#method_access">Method access with %javamethodmodifiers</A></LI>
22428 </UL>
22429 </LI>
22430 <LI><A href="#tips_techniques">Tips and techniques</A>
22431 <UL>
22432 <LI><A href="#input_output_parameters">Input and output parameters using
22433  primitive pointers and references</A></LI>
22434 <LI><A href="#simple_pointers">Simple pointers</A></LI>
22435 <LI><A href="#c_arrays">Wrapping C arrays with Java arrays</A></LI>
22436 <LI><A href="#unbounded_c_arrays">Unbounded C Arrays</A></LI>
22437 <LI><A href="#java_heap_allocations">Overriding new and delete to
22438  allocate from Java heap</A></LI>
22439 </UL>
22440 </LI>
22441 <LI><A href="#java_typemaps">Java typemaps</A>
22442 <UL>
22443 <LI><A href="#default_primitive_type_mappings">Default primitive type
22444  mappings</A></LI>
22445 <LI><A href="#Java_default_non_primitive_typemaps">Default typemaps for
22446  non-primitive types</A></LI>
22447 <LI><A href="#jvm64">Sixty four bit JVMs</A></LI>
22448 <LI><A href="#what_is_typemap">What is a typemap?</A></LI>
22449 <LI><A href="#typemaps_c_to_java_types">Typemaps for mapping C/C++ types
22450  to Java types</A></LI>
22451 <LI><A href="#typemap_attributes">Java typemap attributes</A></LI>
22452 <LI><A href="#special_variables">Java special variables</A></LI>
22453 <LI><A href="#typemaps_for_c_and_cpp">Typemaps for both C and C++
22454  compilation</A></LI>
22455 <LI><A href="#java_code_typemaps">Java code typemaps</A></LI>
22456 <LI><A href="#java_directors_typemaps">Director specific typemaps</A></LI>
22457 </UL>
22458 </LI>
22459 <LI><A href="#typemap_examples">Typemap Examples</A>
22460 <UL>
22461 <LI><A href="#simpler_enum_classes">Simpler Java enums for enums without
22462  initializers</A></LI>
22463 <LI><A href="#exception_typemap">Handling C++ exception specifications
22464  as Java exceptions</A></LI>
22465 <LI><A href="#nan_exception_typemap">NaN Exception - exception handling
22466  for a particular type</A></LI>
22467 <LI><A href="#converting_java_string_arrays">Converting Java String
22468  arrays to char **</A></LI>
22469 <LI><A href="#expanding_java_object">Expanding a Java object to multiple
22470  arguments</A></LI>
22471 <LI><A href="#using_typemaps_return_arguments">Using typemaps to return
22472  arguments</A></LI>
22473 <LI><A href="#adding_downcasts">Adding Java downcasts to polymorphic
22474  return types</A></LI>
22475 <LI><A href="#adding_equals_method">Adding an equals method to the Java
22476  classes</A></LI>
22477 <LI><A href="#void_pointers">Void pointers and a common Java base class</A>
22478 </LI>
22479 <LI><A href="#struct_pointer_pointer">Struct pointer to pointer</A></LI>
22480 <LI><A href="#java_memory_management_member_variables">Memory management
22481  when returning references to member variables</A></LI>
22482 <LI><A href="#java_memory_management_objects">Memory management for
22483  objects passed to the C++ layer</A></LI>
22484 <LI><A href="#java_date_marshalling">Date marshalling using the javain
22485  typemap and associated attributes</A></LI>
22486 </UL>
22487 </LI>
22488 <LI><A href="#java_directors_faq">Living with Java Directors</A></LI>
22489 <LI><A href="#odds_ends">Odds and ends</A>
22490 <UL>
22491 <LI><A href="#javadoc_comments">JavaDoc comments</A></LI>
22492 <LI><A href="#functional_interface">Functional interface without proxy
22493  classes</A></LI>
22494 <LI><A href="#using_own_jni_functions">Using your own JNI functions</A></LI>
22495 <LI><A href="#performance">Performance concerns and hints</A></LI>
22496 <LI><A href="#java_debugging">Debugging</A></LI>
22497 </UL>
22498 </LI>
22499 <LI><A href="#java_examples">Examples</A></LI>
22500 </UL>
22501 </DIV>
22502 <!-- INDEX -->
22503 <P> This chapter describes SWIG's support of Java. It covers most SWIG
22504  features, but certain low-level details are covered in less depth than
22505  in earlier chapters.</P>
22506 <H2><A name="java_overview"></A>21.1 Overview</H2>
22507 <P> The 100% Pure Java effort is a commendable concept, however in the
22508  real world programmers often either need to re-use their existing code
22509  or in some situations want to take advantage of Java but are forced
22510  into using some native (C/C++) code. The Java extension to SWIG makes
22511  it very easy to plumb in existing C/C++ code for access from Java, as
22512  SWIG writes the Java Native Interface (JNI) code for you. It is
22513  different to using the 'javah' tool as SWIG will wrap existing C/C++
22514  code, whereas javah takes 'native' Java function declarations and
22515  creates C/C++ function prototypes. SWIG wraps C/C++ code using Java
22516  proxy classes and is very useful if you want to have access to large
22517  amounts of C/C++ code from Java. If only one or two JNI functions are
22518  needed then using SWIG may be overkill. SWIG enables a Java program to
22519  easily call into C/C++ code from Java. Historically, SWIG was not able
22520  to generate any code to call into Java code from C++. However, SWIG now
22521  supports full cross language polymorphism and code is generated to call
22522  up from C++ to Java when wrapping C++ virtual methods.</P>
22523 <P> Java is one of the few non-scripting language modules in SWIG. As
22524  SWIG utilizes the type safety that the Java language offers, it takes a
22525  somewhat different approach to that used for scripting languages. In
22526  particular runtime type checking and the runtime library are not used
22527  by Java. This should be borne in mind when reading the rest of the SWIG
22528  documentation. This chapter on Java is relatively self contained and
22529  will provide you with nearly everything you need for using SWIG and
22530  Java. However, the &quot;<A href="#SWIG">SWIG Basics</A>&quot; chapter will be a
22531  useful read in conjunction with this one.</P>
22532 <P> This chapter starts with a few practicalities on running SWIG and
22533  compiling the generated code. If you are looking for the minimum amount
22534  to read, have a look at the sections up to and including the <A href="#java_basic_tour">
22535 tour of basic C/C++ wrapping</A> section which explains how to call the
22536  various C/C++ code constructs from Java. Following this section are
22537  details of the C/C++ code and Java classes that SWIG generates. Due to
22538  the complexities of C and C++ there are different ways in which C/C++
22539  code could be wrapped and called from Java. SWIG is a powerful tool and
22540  the rest of the chapter details how the default code wrapping can be
22541  tailored. Various customisation tips and techniques using SWIG
22542  directives are covered. The latter sections cover the advanced
22543  techniques of using typemaps for complete control of the wrapping
22544  process.</P>
22545 <H2><A name="java_preliminaries"></A>21.2 Preliminaries</H2>
22546 <P> SWIG 1.1 works with JDKs from JDK 1.1 to JDK1.4 (Java 2 SDK1.4) and
22547  should also work with any later versions. Given the choice, you should
22548  probably use the latest version of Sun's JDK. The SWIG Java module is
22549  known to work using Sun's JVM on Solaris, Linux and the various
22550  flavours of Microsoft Windows including Cygwin. The Kaffe JVM is known
22551  to give a few problems and at the time of writing was not a fully
22552  fledged JVM with full JNI support. The generated code is also known to
22553  work on vxWorks using WindRiver's PJava 3.1. The best way to determine
22554  whether your combination of operating system and JDK will work is to
22555  test the examples and test-suite that comes with SWIG. Run <TT>make -k
22556  check</TT> from the SWIG root directory after installing SWIG on Unix
22557  systems.</P>
22558 <P> The Java module requires your system to support shared libraries and
22559  dynamic loading. This is the commonly used method to load JNI code so
22560  your system will more than likely support this.</P>
22561 <H3><A name="running_swig"></A>21.2.1 Running SWIG</H3>
22562 <P> Suppose that you defined a SWIG module such as the following:</P>
22563 <DIV class="code">
22564 <PRE>
22565 /* File: example.i */
22566 %module test
22567 %{
22568 #include &quot;stuff.h&quot;
22569 %}
22570 int fact(int n);
22571 </PRE>
22572 </DIV>
22573 <P> To build a Java module, run SWIG using the <TT>-java</TT> option :</P>
22574 <DIV class="code">
22575 <PRE>
22576 %swig -java example.i
22577 </PRE>
22578 </DIV>
22579 <P> If building C++, add the <TT>-c++</TT> option:</P>
22580 <DIV class="code">
22581 <PRE>
22582 $ swig -c++ -java example.i
22583 </PRE>
22584 </DIV>
22585 <P> This creates two different files; a C/C++ source file <TT>
22586 example_wrap.c</TT> or <TT>example_wrap.cxx</TT> and numerous Java
22587  files. The generated C/C++ source file contains the JNI wrapper code
22588  that needs to be compiled and linked with the rest of your C/C++
22589  application.</P>
22590 <P> The name of the wrapper file is derived from the name of the input
22591  file. For example, if the input file is <TT>example.i</TT>, the name of
22592  the wrapper file is <TT>example_wrap.c</TT>. To change this, you can
22593  use the <TT>-o</TT> option. It is also possible to change the <A href="#output">
22594 output directory</A> that the Java files are generated into using <TT>
22595 -outdir</TT>.</P>
22596 <P> The module name, specified with <TT>%module</TT>, determines the
22597  name of various generated classes as discussed <A href="#module_packages_classes">
22598 later</A>. Note that the module name does not define a Java package and
22599  by default, the generated Java classes do not have a Java package. The <TT>
22600 -package</TT> option described below can specify a Java package name to
22601  use.</P>
22602 <P> The following sections have further practical examples and details
22603  on how you might go about compiling and using the generated files.</P>
22604 <H3><A name="java_commandline"></A>21.2.2 Additional Commandline Options</H3>
22605 <P> The following table list the additional commandline options
22606  available for the Java module. They can also be seen by using:</P>
22607 <DIV class="code">
22608 <PRE>
22609 swig -java -help 
22610 </PRE>
22611 </DIV>
22612 <TABLE summary="Java specific options">
22613 <TR><TH>Java specific options</TH></TR>
22614 <TR><TD>-nopgcpp</TD><TD>suppress the premature garbage collection
22615  prevention parameter</TD></TR>
22616 <TR><TD>-noproxy</TD><TD>generate the low-level functional interface
22617  instead of proxy classes</TD></TR>
22618 <TR><TD>-package &lt;name&gt;</TD><TD>set name of the Java package to &lt;name&gt;</TD>
22619 </TR>
22620 </TABLE>
22621 <P> Their use will become clearer by the time you have finished reading
22622  this section on SWIG and Java.</P>
22623 <H3><A name="getting_right_headers"></A>21.2.3 Getting the right header
22624  files</H3>
22625 <P> In order to compile the C/C++ wrappers, the compiler needs the <TT>
22626 jni.h</TT> and <TT>jni_md.h</TT> header files which are part of the JDK.
22627  They are usually in directories like this:</P>
22628 <DIV class="code">
22629 <PRE>
22630 /usr/java/include
22631 /usr/java/include/&lt;operating_system&gt;
22632 </PRE>
22633 </DIV>
22634 <P> The exact location may vary on your machine, but the above locations
22635  are typical.</P>
22636 <H3><A name="compiling_dynamic"></A>21.2.4 Compiling a dynamic module</H3>
22637 <P> The JNI code exists in a dynamic module or shared library (DLL on
22638  Windows) and gets loaded by the JVM. To build a shared library file,
22639  you need to compile your module in a manner similar to the following
22640  (shown for Solaris):</P>
22641 <DIV class="code">
22642 <PRE>
22643 $ swig -java example.i
22644 $ gcc -c example_wrap.c  -I/usr/java/include -I/usr/java/include/solaris
22645 $ ld -G example_wrap.o  -o libexample.so
22646 </PRE>
22647 </DIV>
22648 <P> The exact commands for doing this vary from platform to platform.
22649  However, SWIG tries to guess the right options when it is installed.
22650  Therefore, you may want to start with one of the examples in the <TT>
22651 Examples/java</TT> directory. If that doesn't work, you will need to
22652  read the man-pages for your compiler and linker to get the right set of
22653  options. You might also check the <A href="http://www.dabeaz.com/cgi-bin/wiki.pl">
22654 SWIG Wiki</A> for additional information. <A href="http://weblogs.java.net/blog/kellyohair/archive/2006/01/compilation_of.html">
22655 JNI compilation</A> is a useful reference for compiling on different
22656  platforms.</P>
22657 <P><B> Important</B>
22658 <BR> If you are going to use optimisations turned on with gcc (for
22659  example -O2), ensure you also compile with -fno-strict-aliasing. The
22660  GCC optimisations have become more aggressive from gcc-4.0 onwards and
22661  will result in code that fails with strict aliasing optimisations
22662  turned on. See the <A href="#typemaps_c_to_java_types">C/C++ to Java
22663  typemaps</A> section for more details.</P>
22664 <P> The name of the shared library output file is important. If the name
22665  of your SWIG module is &quot;<TT>example</TT>&quot;, the name of the
22666  corresponding shared library file should be &quot;<TT>libexample.so</TT>&quot;
22667  (or equivalent depending on your machine, see <A href="#dynamic_linking_problems">
22668 Dynamic linking problems</A> for more information). The name of the
22669  module is specified using the <TT>%module</TT> directive or <TT>-module</TT>
22670  command line option.</P>
22671 <H3><A name="using_module"></A>21.2.5 Using your module</H3>
22672 <P> To load your shared native library module in Java, simply use Java's
22673  <TT>System.loadLibrary</TT> method in a Java class:</P>
22674 <DIV class="code">
22675 <PRE>
22676 // runme.java
22677
22678 public class runme {
22679   static {
22680 &nbsp;   System.loadLibrary(&quot;example&quot;);
22681   }
22682
22683   public static void main(String argv[]) {
22684     System.out.println(example.fact(4));
22685   }
22686 }
22687 </PRE>
22688 </DIV>
22689 <P> Compile all the Java files and run:</P>
22690 <DIV class="code">
22691 <PRE>
22692 $ javac *.java
22693 $ java runme
22694 24
22695 $
22696 </PRE>
22697 </DIV>
22698 <P> If it doesn't work have a look at the following section which
22699  discusses problems loading the shared library.</P>
22700 <H3><A name="dynamic_linking_problems"></A>21.2.6 Dynamic linking
22701  problems</H3>
22702 <P> As shown in the previous section the code to load a native library
22703  (shared library) is <TT>System.loadLibrary(&quot;name&quot;)</TT>. This can fail
22704  with an UnsatisfiedLinkError exception and can be due to a number of
22705  reasons.</P>
22706 <P> You may get an exception similar to this:</P>
22707 <DIV class="code">
22708 <PRE>
22709 $ java runme
22710 Exception in thread &quot;main&quot; java.lang.UnsatisfiedLinkError: no example in java.library.path
22711         at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1312)
22712         at java.lang.Runtime.loadLibrary0(Runtime.java:749)
22713         at java.lang.System.loadLibrary(System.java:820)
22714         at runme.&lt;clinit&gt;(runme.java:5)
22715 </PRE>
22716 </DIV>
22717 <P> The most common cause for this is an incorrect naming of the native
22718  library for the name passed to the <TT>loadLibrary</TT> function. The
22719  string passed to the <TT>loadLibrary</TT> function must not include the
22720  file extension name in the string, that is<I> .dll</I> or<I> .so</I>.
22721  The string must be<I> name</I> and not<I> libname</I> for all
22722  platforms. On Windows the native library must then be called<I>
22723  name.dll</I> and on most Unix systems it must be called<I> libname.so</I>
22724 .</P>
22725 <P> Another common reason for the native library not loading is because
22726  it is not in your path. On Windows make sure the<I> path</I>
22727  environment variable contains the path to the native library. On Unix
22728  make sure that your<I> LD_LIBRARY_PATH</I> contains the path to the
22729  native library. Adding paths to<I> LD_LIBRARY_PATH</I> can slow down
22730  other programs on your system so you may want to consider alternative
22731  approaches. For example you could recompile your native library with
22732  extra path information using <TT>-rpath</TT> if you're using GNU, see
22733  the GNU linker documentation (<TT>ld</TT> man page). You could use a
22734  command such as <TT>ldconfig</TT> (Linux) or <TT>crle</TT> (Solaris) to
22735  add additional search paths to the default system configuration (this
22736  requires root access and you will need to read the man pages).</P>
22737 <P> The native library will also not load if there are any unresolved
22738  symbols in the compiled C/C++ code. The following exception is
22739  indicative of this:</P>
22740 <DIV class="code">
22741 <PRE>
22742 $ java runme
22743 Exception in thread &quot;main&quot; java.lang.UnsatisfiedLinkError: libexample.so: undefined
22744 symbol: fact
22745         at java.lang.ClassLoader$NativeLibrary.load(Native Method)
22746         at java.lang.ClassLoader.loadLibrary0(ClassLoader.java, Compiled Code)
22747         at java.lang.ClassLoader.loadLibrary(ClassLoader.java, Compiled Code)
22748         at java.lang.Runtime.loadLibrary0(Runtime.java, Compiled Code)
22749         at java.lang.System.loadLibrary(System.java, Compiled Code)
22750         at runme.&lt;clinit&gt;(runme.java:5)
22751 $
22752 </PRE>
22753 </DIV>
22754 <P> This error usually indicates that you forgot to include some object
22755  files or libraries in the linking of the native library file. Make sure
22756  you compile both the SWIG wrapper file and the code you are wrapping
22757  into the native library file. If you forget to compile and link in the
22758  SWIG wrapper file into your native library file, you will get a message
22759  similar to the following:</P>
22760 <DIV class="code">
22761 <PRE>
22762 $ java runme
22763 Exception in thread &quot;main&quot; java.lang.UnsatisfiedLinkError: exampleJNI.gcd(II)I
22764         at exampleJNI.gcd(Native Method)
22765         at example.gcd(example.java:12)
22766         at runme.main(runme.java:18)
22767 </PRE>
22768 </DIV>
22769 <P> where <TT>gcd</TT> is the missing JNI function that SWIG generated
22770  into the wrapper file. Also make sure you pass all of the required
22771  libraries to the linker. The <TT>java -verbose:jni</TT> commandline
22772  switch is also a great way to get more information on unresolved
22773  symbols. One last piece of advice is to beware of the common faux pas
22774  of having more than one native library version in your path.</P>
22775 <P> In summary, ensure that you are using the correct C/C++ compiler and
22776  linker combination and options for successful native library loading.
22777  If you are using the examples that ship with SWIG, then the
22778  Examples/Makefile must have these set up correctly for your system. The
22779  SWIG installation package makes a best attempt at getting these correct
22780  but does not get it right 100% of the time. The <A href="http://www.dabeaz.com/cgi-bin/wiki.pl">
22781 SWIG Wiki</A> also has some settings for commonly used compiler and
22782  operating system combinations. The following section also contains some
22783  C++ specific linking problems and solutions.</P>
22784 <H3><A name="compilation_problems_cpp"></A>21.2.7 Compilation problems
22785  and compiling with C++</H3>
22786 <P> On most machines, shared library files should be linked using the
22787  C++ compiler. For example:</P>
22788 <DIV class="code">
22789 <PRE>
22790 % swig -c++ -java example.i
22791 % g++ -c -fpic example.cxx
22792 % g++ -c -fpic example_wrap.cxx -I/usr/java/j2sdk1.4.1/include -I/usr/java/
22793 j2sdk1.4.1/include/linux
22794 % g++ -shared example.o example_wrap.o -o libexample.so
22795 </PRE>
22796 </DIV>
22797 <P> In addition to this, you may need to include additional library
22798  files to make it work. For example, if you are using the Sun C++
22799  compiler on Solaris, you often need to add an extra library <TT>-lCrun</TT>
22800  like this:</P>
22801 <DIV class="code">
22802 <PRE>
22803 % swig -c++ -java example.i
22804 % CC -c example.cxx
22805 % CC -c example_wrap.cxx -I/usr/java/include -I/usr/java/include/solaris
22806 % CC -G example.o example_wrap.o -L/opt/SUNWspro/lib -o libexample.so -lCrun
22807 </PRE>
22808 </DIV>
22809 <P> If you aren't entirely sure about the linking for C++, you might
22810  look at an existing C++ program. On many Unix machines, the <TT>ldd</TT>
22811  command will list library dependencies. This should give you some clues
22812  about what you might have to include when you link your shared library.
22813  For example:</P>
22814 <DIV class="code">
22815 <PRE>
22816 $ ldd swig
22817         libstdc++-libc6.1-1.so.2 =&gt; /usr/lib/libstdc++-libc6.1-1.so.2 (0x40019000)
22818         libm.so.6 =&gt; /lib/libm.so.6 (0x4005b000)
22819         libc.so.6 =&gt; /lib/libc.so.6 (0x40077000)
22820         /lib/ld-linux.so.2 =&gt; /lib/ld-linux.so.2 (0x40000000)
22821 $
22822 </PRE>
22823 </DIV>
22824 <P> Finally make sure the version of JDK header files matches the
22825  version of Java that you are running as incompatibilities could lead to
22826  compilation problems or unpredictable behaviour.</P>
22827 <H3><A name="building_windows"></A>21.2.8 Building on Windows</H3>
22828 <P> Building on Windows is roughly similar to the process used with
22829  Unix. You will want to produce a DLL that can be loaded by the Java
22830  Virtual Machine. This section covers the process of using SWIG with
22831  Microsoft Visual C++ 6 although the procedure may be similar with other
22832  compilers. In order for everything to work, you will need to have a JDK
22833  installed on your machine in order to read the JNI header files.</P>
22834 <H4><A name="visual_studio"></A>21.2.8.1 Running SWIG from Visual Studio</H4>
22835 <P> If you are developing your application within Microsoft Visual
22836  studio, SWIG can be invoked as a custom build option. The Examples\java
22837  directory has a few <A href="#Windows_examples">Windows Examples</A>
22838  containing Visual Studio project (.dsp) files. The process to re-create
22839  the project files for a C project are roughly:</P>
22840 <UL>
22841 <LI>Open up a new workspace and use the AppWizard to select a DLL
22842  project.</LI>
22843 <LI>Add both the SWIG interface file (the .i file), any supporting C
22844  files, and the name of the wrapper file that will be created by SWIG
22845  (ie. <TT>example_wrap.c</TT>). Don't worry if the wrapper file doesn't
22846  exist yet--Visual Studio will keep a reference to it.</LI>
22847 <LI>Select the SWIG interface file and go to the settings menu. Under
22848  settings, select the &quot;Custom Build&quot; option.</LI>
22849 <LI>Enter &quot;SWIG&quot; in the description field.</LI>
22850 <LI>Enter &quot;<TT>swig -java -o $(ProjDir)\$(InputName)_wrap.c $(InputPath)</TT>
22851 &quot; in the &quot;Build command(s) field&quot;</LI>
22852 <LI>Enter &quot;<TT>$(ProjDir)\$(InputName)_wrap.c</TT>&quot; in the &quot;Output
22853  files(s) field&quot;.</LI>
22854 <LI>Next, select the settings for the entire project and go to C/C++ tab
22855  and select the Preprocessor category . Add the include directories to
22856  the JNI header files under &quot;Additional include directories&quot;, eg
22857  &quot;C:\jdk1.3\include,C:\jdk1.3\include\win32&quot;.</LI>
22858 <LI>Next, select the settings for the entire project and go to Link tab
22859  and select the General category. Set the name of the output file to
22860  match the name of your Java module (ie. example.dll).</LI>
22861 <LI>Next, select the example.c and example_wrap.c files and go to the
22862  C/C++ tab and select the Precompiled Headers tab in the project
22863  settings. Disabling precompiled headers for these files will overcome
22864  any precompiled header errors while building.</LI>
22865 <LI>Finally, add the java compilation as a post build rule in the
22866  Post-build step tab in project settings, eg, &quot;c:\jdk1.3\bin\javac
22867  *.java&quot;</LI>
22868 <LI>Build your project.</LI>
22869 </UL>
22870 <P> Note: If using C++, choose a C++ suffix for the wrapper file, for
22871  example <TT>example_wrap.cxx</TT>. Use <TT>_wrap.cxx</TT> instead of <TT>
22872 _wrap.c</TT> in the instructions above and add -c++ when invoking swig.</P>
22873 <P> Now, assuming all went well, SWIG will be automatically invoked when
22874  you build your project. When doing a build, any changes made to the
22875  interface file will result in SWIG being automatically invoked to
22876  produce a new version of the wrapper file.</P>
22877 <P> The Java classes that SWIG output should also be compiled into
22878  .class files. To run the native code in the DLL (example.dll), make
22879  sure that it is in your path then run your Java program which uses it,
22880  as described in the previous section. If the library fails to load have
22881  a look at <A href="#dynamic_linking_problems">Dynamic linking problems</A>
22882 .</P>
22883 <H4><A name="nmake"></A>21.2.8.2 Using NMAKE</H4>
22884 <P> Alternatively, a Makefile for use by NMAKE can be written. Make sure
22885  the environment variables for MSVC++ are available and the MSVC++ tools
22886  are in your path. Now, just write a short Makefile like this :</P>
22887 <DIV class="code">
22888 <PRE>
22889 # Makefile for using SWIG and Java for C code
22890
22891 SRCS          = example.c
22892 IFILE         = example
22893 INTERFACE     = $(IFILE).i
22894 WRAPFILE      = $(IFILE)_wrap.c
22895
22896 # Location of the Visual C++ tools (32 bit assumed)
22897
22898 TOOLS         = c:\msdev
22899 TARGET        = example.dll
22900 CC            = $(TOOLS)\bin\cl.exe
22901 LINK          = $(TOOLS)\bin\link.exe
22902 INCLUDE32     = -I$(TOOLS)\include
22903 MACHINE       = IX86
22904
22905 # C Library needed to build a DLL
22906
22907 DLLIBC        = msvcrt.lib oldnames.lib  
22908
22909 # Windows libraries that are apparently needed
22910 WINLIB        = kernel32.lib advapi32.lib user32.lib gdi32.lib comdlg32.lib winspool.lib
22911
22912 # Libraries common to all DLLs
22913 LIBS          = $(DLLIBC) $(WINLIB) 
22914
22915 # Linker options
22916 LOPT      = -debug:full -debugtype:cv /NODEFAULTLIB /RELEASE /NOLOGO \
22917              /MACHINE:$(MACHINE) -entry:_DllMainCRTStartup@12 -dll
22918
22919 # C compiler flags
22920
22921 CFLAGS        = /Z7 /Od /c /nologo
22922 JAVA_INCLUDE    = -ID:\jdk1.3\include -ID:\jdk1.3\include\win32
22923
22924 java::
22925         swig -java -o $(WRAPFILE) $(INTERFACE)
22926         $(CC) $(CFLAGS) $(JAVA_INCLUDE) $(SRCS) $(WRAPFILE)
22927         set LIB=$(TOOLS)\lib
22928         $(LINK) $(LOPT) -out:example.dll $(LIBS) example.obj example_wrap.obj
22929         javac *.java
22930 </PRE>
22931 </DIV>
22932 <P> To build the DLL and compile the java code, run NMAKE (you may need
22933  to run <TT>vcvars32</TT> first). This is a pretty simplistic Makefile,
22934  but hopefully its enough to get you started. Of course you may want to
22935  make changes for it to work for C++ by adding in the -c++ command line
22936  switch for swig and replacing .c with .cxx.</P>
22937 <H2><A name="java_basic_tour"></A>21.3 A tour of basic C/C++ wrapping</H2>
22938 <P> By default, SWIG attempts to build a natural Java interface to your
22939  C/C++ code. Functions are wrapped as functions, classes are wrapped as
22940  classes, variables are wrapped with JavaBean type getters and setters
22941  and so forth. This section briefly covers the essential aspects of this
22942  wrapping.</P>
22943 <H3><A name="module_packages_classes"></A>21.3.1 Modules, packages and
22944  generated Java classes</H3>
22945 <P> The SWIG <TT>%module</TT> directive specifies the name of the Java
22946  module. When you specify `<TT>%module example</TT>', the<I> module name</I>
22947  determines the name of some of the generated files in the module. The
22948  generated code consists of a<I> module class</I> file <TT>example.java</TT>
22949 , an<I> intermediary JNI class</I> file, <TT>exampleJNI.java</TT> as
22950  well as numerous other Java<I> proxy class</I> files. Each proxy class
22951  is named after the structs, unions and classes you are wrapping. You
22952  may also get a<I> constants interface</I> file if you are wrapping any
22953  unnamed enumerations or constants, for example <TT>
22954 exampleConstants.java</TT>. When choosing a module name, make sure you
22955  don't use the same name as one of the generated proxy class files nor a
22956  Java keyword. Sometimes a C/C++ type cannot be wrapped by a proxy
22957  class, for example a pointer to a primitive type. In these situations a<I>
22958  type wrapper class</I> is generated. Wrapping an enum generates an<I>
22959  enum class</I>, either a proper Java enum or a Java class that
22960  simulates the enums pattern. Details of all these generated classes
22961  will unfold as you read this section.</P>
22962 <P> The JNI (C/C++) code is generated into a file which also contains
22963  the module name, for example <TT>example_wrap.cxx</TT> or <TT>
22964 example_wrap.c</TT>. These C or C++ files complete the contents of the
22965  module.</P>
22966 <P> The generated Java classes can be placed into a Java package by
22967  using the <TT>-package</TT> commandline option. This is often combined
22968  with the <TT>-outdir</TT> to specify a package directory for generating
22969  the Java files.</P>
22970 <DIV class="code">
22971 <PRE>
22972 swig -java -package com.bloggs.swig -outdir com/bloggs/swig example.i
22973 </PRE>
22974 </DIV> SWIG won't create the directory, so make sure it exists
22975  beforehand.
22976 <H3><A name="functions"></A>21.3.2 Functions</H3>
22977 <P> There is no such thing as a global Java function so global C
22978  functions are wrapped as static methods in the module class. For
22979  example,</P>
22980 <DIV class="code">
22981 <PRE>
22982 %module example
22983 int fact(int n);
22984
22985 </PRE>
22986 </DIV>
22987 <P> creates a static function that works exactly like you think it
22988  might:</P>
22989 <DIV class="code">
22990 <PRE>
22991 public class example {
22992   public static int fact(int n) {
22993     // makes call using JNI to the C function
22994   }
22995 }
22996 </PRE>
22997 </DIV>
22998 <P> The Java class <TT>example</TT> is the<I> module class</I>. The
22999  function can be used as follows from Java:</P>
23000 <DIV class="code">
23001 <PRE>
23002 System.out.println(example.fact(4));
23003 </PRE>
23004 </DIV>
23005 <H3><A name="global_variables"></A>21.3.3 Global variables</H3>
23006 <P> C/C++ global variables are fully supported by SWIG. Java does not
23007  allow the overriding of the dot operator so all variables are accessed
23008  through getters and setters. Again because there is no such thing as a
23009  Java global variable, access to C/C++ global variables is done through
23010  static getter and setter functions in the module class.</P>
23011 <DIV class="code">
23012 <PRE>
23013 // SWIG interface file with global variables
23014 %module example
23015 ...
23016 %inline %{
23017 extern int My_variable;
23018 extern double density;
23019 %}
23020 ...
23021 </PRE>
23022 </DIV>
23023 <P> Now in Java :</P>
23024 <DIV class="code">
23025 <PRE>
23026 // Print out value of a C global variable
23027 System.out.println(&quot;My_variable = &quot; + example.getMy_variable());
23028 // Set the value of a C global variable
23029 example.setDensity(0.8442);
23030 </PRE>
23031 </DIV>
23032 <P> The value returned by the getter will always be up to date even if
23033  the value is changed in C. Note that the getters and setters produced
23034  follow the JavaBean property design pattern. That is the first letter
23035  of the variable name is capitalized and preceded with set or get. If
23036  you have the misfortune of wrapping two variables that differ only in
23037  the capitalization of their first letters, use %rename to change one of
23038  the variable names. For example:</P>
23039 <DIV class="code">
23040 <PRE>
23041 %rename Clash RenamedClash;
23042 float Clash;
23043 int clash;
23044 </PRE>
23045 </DIV>
23046 <P> If a variable is declared as <TT>const</TT>, it is wrapped as a
23047  read-only variable. That is only a getter is produced.</P>
23048 <P> To make ordinary variables read-only, you can use the <TT>%immutable</TT>
23049  directive. For example:</P>
23050 <DIV class="code">
23051 <PRE>
23052 %{
23053 extern char *path;
23054 %}
23055 %immutable;
23056 extern char *path;
23057 %mutable;
23058 </PRE>
23059 </DIV>
23060 <P> The <TT>%immutable</TT> directive stays in effect until it is
23061  explicitly disabled or cleared using <TT>%mutable</TT>. See the <A href="#SWIG_readonly_variables">
23062 Creating read-only variables</A> section for further details.</P>
23063 <P> If you just want to make a specific variable immutable, supply a
23064  declaration name. For example:</P>
23065 <DIV class="code">
23066 <PRE>
23067 %{
23068 extern char *path;
23069 %}
23070 %immutable path;
23071 ...
23072 extern char *path;      // Read-only (due to %immutable)
23073 </PRE>
23074 </DIV>
23075 <H3><A name="constants"></A>21.3.4 Constants</H3>
23076 <P> C/C++ constants are wrapped as Java static final variables. To
23077  create a constant, use <TT>#define</TT> or the <TT>%constant</TT>
23078  directive. For example:</P>
23079 <DIV class="code">
23080 <PRE>
23081 #define PI 3.14159
23082 #define VERSION &quot;1.0&quot;
23083 %constant int FOO = 42;
23084 %constant const char *path = &quot;/usr/local&quot;;
23085 </PRE>
23086 </DIV>
23087 <P> By default the generated static final variables are initialized by
23088  making a JNI call to get their value. The constants are generated into
23089  the constants interface and look like this:</P>
23090 <DIV class="code">
23091 <PRE>
23092 public interface exampleConstants {
23093   public final static double PI = exampleJNI.PI_get();
23094   public final static String VERSION = exampleJNI.VERSION_get();
23095   public final static int FOO = exampleJNI.FOO_get();
23096   public final static String path = exampleJNI.path_get();
23097 }
23098 </PRE>
23099 </DIV>
23100 <P> Note that SWIG has inferred the C type and used an appropriate Java
23101  type that will fit the range of all possible values for the C type. By
23102  default SWIG generates<B> runtime constants</B>. They are not<B>
23103  compiler constants</B> that can, for example, be used in a switch
23104  statement. This can be changed by using the <TT>%javaconst(flag)</TT>
23105  directive. It works like all the other <A href="#features">%feature
23106  directives</A>. The default is <TT>%javaconst(0)</TT>. It is possible
23107  to initialize all wrapped constants from pure Java code by placing a <TT>
23108 %javaconst(1)</TT><B> before</B> SWIG parses the constants. Putting it
23109  at the top of your interface file would ensure this. Here is an
23110  example:</P>
23111 <DIV class="code">
23112 <PRE>
23113 %javaconst(1);
23114 %javaconst(0) BIG;
23115 %javaconst(0) LARGE;
23116
23117 #define EXPRESSION (0x100+5)
23118 #define BIG 1000LL
23119 #define LARGE 2000ULL
23120 </PRE>
23121 </DIV>
23122 <P> generates:</P>
23123 <DIV class="code">
23124 <PRE>
23125 public interface exampleConstants {
23126   public final static int EXPRESSION = (0x100+5);
23127   public final static long BIG = exampleJNI.BIG_get();
23128   public final static java.math.BigInteger LARGE = exampleJNI.LARGE_get();
23129 }
23130 </PRE>
23131 </DIV>
23132 <P> Note that SWIG has inferred the C <TT>long long</TT> type from <TT>
23133 BIG</TT> and used an appropriate Java type (<TT>long</TT>) as a Java <TT>
23134 long</TT> is the smallest sized Java type that will take all possible
23135  values for a C <TT>long long</TT>. Similarly for <TT>LARGE</TT>.</P>
23136 <P> Be careful using the <TT>%javaconst(1)</TT> directive as not all C
23137  code will compile as Java code. For example neither the <TT>1000LL</TT>
23138  value for <TT>BIG</TT> nor <TT>2000ULL</TT> for <TT>LARGE</TT> above
23139  would generate valid Java code. The example demonstrates how you can
23140  target particular constants (<TT>BIG</TT> and <TT>LARGE</TT>) with <TT>
23141 %javaconst</TT>. SWIG doesn't use <TT>%javaconst(1)</TT> as the default
23142  as it tries to generate code that will always compile. However, using a
23143  <TT>%javaconst(1)</TT> at the top of your interface file is strongly
23144  recommended as the preferred compile time constants will be generated
23145  and most C constants will compile as Java code and in any case the odd
23146  constant that doesn't can be fixed using <TT>%javaconst(0)</TT>.</P>
23147 <P> There is an alternative directive which can be used for these rare
23148  constant values that won't compile as Java code. This is the <TT>
23149 %javaconstvalue(value)</TT> directive, where <TT>value</TT> is a Java
23150  code replacement for the C constant and can be either a string or a
23151  number. This is useful if you do not want to use either the parsed C
23152  value nor a JNI call, such as when the C parsed value will not compile
23153  as Java code and a compile time constant is required. The same example
23154  demonstrates this:</P>
23155 <DIV class="code">
23156 <PRE>
23157 %javaconst(1);
23158 %javaconstvalue(&quot;new java.math.BigInteger(\&quot;2000\&quot;)&quot;) LARGE;
23159 %javaconstvalue(1000) BIG;
23160
23161 #define EXPRESSION (0x100+5)
23162 #define BIG 1000LL
23163 #define LARGE 2000ULL
23164 </PRE>
23165 </DIV>
23166 <P> Note the string quotes for <TT>&quot;2000&quot;</TT> are escaped. The
23167  following is then generated:</P>
23168 <DIV class="code">
23169 <PRE>
23170 public interface exampleConstants {
23171   public final static int EXPRESSION = (0x100+5);
23172   public final static long BIG = 1000;
23173   public final static java.math.BigInteger LARGE = new java.math.BigInteger(&quot;2000&quot;);
23174 }
23175 </PRE>
23176 </DIV>
23177 <P> Note: declarations declared as <TT>const</TT> are wrapped as
23178  read-only variables and will be accessed using a getter as described in
23179  the previous section. They are not wrapped as constants. The exception
23180  to this rule are static const integral values defined within a
23181  class/struct, where they are wrapped as constants, eg:.</P>
23182 <DIV class="code">
23183 <PRE>
23184 struct Maths {
23185   static const int FIVE = 5;
23186 };
23187 </PRE>
23188 </DIV>
23189 <P><B> Compatibility Note:</B> In SWIG-1.3.19 and earlier releases, the
23190  constants were generated into the module class and the constants
23191  interface didn't exist. Backwards compatibility is maintained as the
23192  module class implements the constants interface (even though some
23193  consider this type of interface implementation to be bad practice):</P>
23194 <DIV class="code">
23195 <PRE>
23196 public class example implements exampleConstants {
23197 }
23198 </PRE>
23199 </DIV>
23200 <P> You thus have the choice of accessing these constants from either
23201  the module class or the constants interface, for example, <TT>
23202 example.EXPRESSION</TT> or <TT>exampleConstants.EXPRESSION</TT>. Or if
23203  you decide this practice isn't so bad and your own class implements <TT>
23204 exampleConstants</TT>, you can of course just use <TT>EXPRESSION</TT>.</P>
23205 <H3><A name="enumerations"></A>21.3.5 Enumerations</H3>
23206 <P> SWIG handles both named and unnamed (anonymous) enumerations. There
23207  is a choice of approaches to wrapping named C/C++ enums. This is due to
23208  historical reasons as SWIG's initial support for enums was limited and
23209  Java did not originally have support for enums. Each approach has
23210  advantages and disadvantages and it is important for the user to decide
23211  which is the most appropriate solution. There are four approaches of
23212  which the first is the default approach based on the so called Java
23213  typesafe enum pattern. The second generates proper Java enums. The
23214  final two approaches use simple integers for each enum item. Before
23215  looking at the various approaches for wrapping named C/C++ enums,
23216  anonymous enums are considered.</P>
23217 <H4><A name="anonymous_enums"></A>21.3.5.1 Anonymous enums</H4>
23218 <P> There is no name for anonymous enums and so they are handled like
23219  constants. For example:</P>
23220 <DIV class="code">
23221 <PRE>
23222 enum { ALE, LAGER=10, STOUT, PILSNER, PILZ=PILSNER };
23223 </PRE>
23224 </DIV>
23225 <P> is wrapped into the constants interface, in a similar manner as
23226  constants (see previous section):</P>
23227 <DIV class="code">
23228 <PRE>
23229 public interface exampleConstants {
23230   public final static int ALE = exampleJNI.ALE_get();
23231   public final static int LAGER = exampleJNI.LAGER_get();
23232   public final static int STOUT = exampleJNI.STOUT_get();
23233   public final static int PILSNER = exampleJNI.PILSNER_get();
23234   public final static int PILZ = exampleJNI.PILZ_get();
23235 }
23236 </PRE>
23237 </DIV>
23238 <P> The <TT>%javaconst(flag)</TT> and <TT>%javaconstvalue(value)</TT>
23239  directive introduced in the previous section on constants can also be
23240  used with enums. As is the case for constants, the default is <TT>
23241 %javaconst(0)</TT> as not all C values will compile as Java code.
23242  However, it is strongly recommended to add in a <TT>%javaconst(1)</TT>
23243  directive at the top of your interface file as it is only on very rare
23244  occasions that this will produce code that won't compile under Java.
23245  Using <TT>%javaconst(1)</TT> will ensure compile time constants are
23246  generated, thereby allowing the enum values to be used in Java switch
23247  statements. Example usage:</P>
23248 <DIV class="code">
23249 <PRE>
23250 %javaconst(1);
23251 %javaconst(0) PILSNER;
23252 enum { ALE, LAGER=10, STOUT, PILSNER, PILZ=PILSNER };
23253 </PRE>
23254 </DIV>
23255 <P> generates:</P>
23256 <DIV class="code">
23257 <PRE>
23258 public interface exampleConstants {
23259   public final static int ALE = 0;
23260   public final static int LAGER = 10;
23261   public final static int STOUT = LAGER + 1;
23262   public final static int PILSNER = exampleJNI.PILSNER_get();
23263   public final static int PILZ = PILSNER;
23264 }
23265 </PRE>
23266 </DIV>
23267 <P> As in the case of constants, you can access them through either the
23268  module class or the constants interface, for example, <TT>example.ALE</TT>
23269  or <TT>exampleConstants.ALE</TT>.</P>
23270 <H4><A name="typesafe_enums"></A>21.3.5.2 Typesafe enums</H4>
23271 <P> This is the default approach to wrapping named enums. The typesafe
23272  enum pattern is a relatively well known construct to work around the
23273  lack of enums in versions of Java prior to JDK 1.5. It basically
23274  defines a class for the enumeration and permits a limited number of
23275  final static instances of the class. Each instance equates to an enum
23276  item within the enumeration. The implementation is in the
23277  &quot;enumtypesafe.swg&quot; file. Let's look at an example:</P>
23278 <DIV class="code">
23279 <PRE>
23280 %include &quot;enumtypesafe.swg&quot; // optional as typesafe enums are the default
23281 enum Beverage { ALE, LAGER=10, STOUT, PILSNER, PILZ=PILSNER };
23282 </PRE>
23283 </DIV>
23284 <P>will generate:</P>
23285 <DIV class="code">
23286 <PRE>
23287 public final class Beverage {
23288   public final static Beverage ALE = new Beverage(&quot;ALE&quot;);
23289   public final static Beverage LAGER = new Beverage(&quot;LAGER&quot;, exampleJNI.LAGER_get());
23290   public final static Beverage STOUT = new Beverage(&quot;STOUT&quot;);
23291   public final static Beverage PILSNER = new Beverage(&quot;PILSNER&quot;);
23292   public final static Beverage PILZ = new Beverage(&quot;PILZ&quot;, exampleJNI.PILZ_get());
23293   [... additional support methods omitted for brevity ...]
23294 }
23295 </PRE>
23296 </DIV>
23297 <P> See <A href="#typesafe_enums_classes">Typesafe enum classes</A> to
23298  see the omitted support methods. Note that the enum item with an
23299  initializer (LAGER) is initialized with the enum value obtained via a
23300  JNI call. However, as with anonymous enums and constants, use of the <TT>
23301 %javaconst</TT> directive is strongly recommended to change this
23302  behaviour:</P>
23303 <DIV class="code">
23304 <PRE>
23305 %include &quot;enumtypesafe.swg&quot; // optional as typesafe enums are the default
23306 %javaconst(1);
23307 enum Beverage { ALE, LAGER=10, STOUT, PILSNER, PILZ=PILSNER };
23308 </PRE>
23309 </DIV>
23310 <P> will generate:</P>
23311 <DIV class="code">
23312 <PRE>
23313 public final class Beverage {
23314   public final static Beverage ALE = new Beverage(&quot;ALE&quot;);
23315   public final static Beverage LAGER = new Beverage(&quot;LAGER&quot;, 10);
23316   public final static Beverage STOUT = new Beverage(&quot;STOUT&quot;);
23317   public final static Beverage PILSNER = new Beverage(&quot;PILSNER&quot;);
23318   public final static Beverage PILZ = new Beverage(&quot;PILZ&quot;, PILSNER);
23319   [... additional support methods omitted for brevity ...]
23320 }
23321 </PRE>
23322 </DIV>
23323 <P> The generated code is easier to read and more efficient as a true
23324  constant is used instead of a JNI call. As is the case for constants,
23325  the default is <TT>%javaconst(0)</TT> as not all C values will compile
23326  as Java code. However, it is recommended to add in a <TT>%javaconst(1)</TT>
23327  directive at the top of your interface file as it is only on very rare
23328  occasions that this will produce code that won't compile under Java.
23329  The <TT>%javaconstvalue(value)</TT> directive can also be used for
23330  typesafe enums. Note that global enums are generated into a Java class
23331  within whatever package you are using. C++ enums defined within a C++
23332  class are generated into a static final inner Java class within the
23333  Java proxy class.</P>
23334 <P> Typesafe enums have their advantages over using plain integers in
23335  that they they can be used in a typesafe manner. However, there are
23336  limitations. For example, they cannot be used in switch statements and
23337  serialization is an issue. Please look at the following references for
23338  further information: <A href="http://java.sun.com/developer/Books/shiftintojava/page1.html#replaceenums">
23339 Replace Enums with Classes</A> in<I> Effective Java Programming</I> on
23340  the Sun website, <A href="http://www.javaworld.com/javaworld/jw-07-1997/jw-07-enumerated.html">
23341 Create enumerated constants in Java</A> JavaWorld article, <A href="http://www.javaworld.com/javaworld/javatips/jw-javatip133.html">
23342 Java Tip 133: More on typesafe enums</A> and <A href="http://www.javaworld.com/javaworld/javatips/jw-javatip122.html">
23343 Java Tip 122: Beware of Java typesafe enumerations</A> JavaWorld tips.</P>
23344 <P> Note that the syntax required for using typesafe enums is the same
23345  as that for proper Java enums. This is useful during the period that a
23346  project has to support legacy versions of Java. When upgrading to JDK
23347  1.5 or later, proper Java enums could be used instead, without users
23348  having to change their code. The following section details proper Java
23349  enum generation.</P>
23350 <H4><A name="proper_enums"></A>21.3.5.3 Proper Java enums</H4>
23351 <P> Proper Java enums were only introduced in JDK 1.5 so this approach
23352  is only compatible with more recent versions of Java. Java enums have
23353  been designed to overcome all the limitations of both typesafe and type
23354  unsafe enums and should be the choice solution, provided older versions
23355  of Java do not have to be supported. In this approach, each named C/C++
23356  enum is wrapped by a Java enum. Java enums, by default, do not support
23357  enums with initializers. Java enums are in many respects similar to
23358  Java classes in that they can be customised with additional methods.
23359  SWIG takes advantage of this feature to facilitate wrapping C/C++ enums
23360  that have initializers. In order to wrap all possible C/C++ enums using
23361  proper Java enums, the &quot;enums.swg&quot; file must be used. Let's take a look
23362  at an example.</P>
23363 <DIV class="code">
23364 <PRE>
23365 %include &quot;enums.swg&quot;
23366 %javaconst(1);
23367 enum Beverage { ALE, LAGER=10, STOUT, PILSNER, PILZ=PILSNER };
23368 </PRE>
23369 </DIV>
23370 <P> will generate:</P>
23371 <DIV class="code">
23372 <PRE>
23373 public enum Beverage {
23374   ALE,
23375   LAGER(10),
23376   STOUT,
23377   PILSNER,
23378   PILZ(PILSNER);
23379   [... additional support methods omitted for brevity ...]
23380 }
23381 </PRE>
23382 </DIV>
23383 <P> See <A href="#proper_enums_classes">Proper Java enum classes</A> to
23384  see the omitted support methods. The generated Java enum has numerous
23385  additional methods to support enums with initializers, such as <TT>
23386 LAGER</TT> above. Note that as with the typesafe enum pattern, enum
23387  items with initializers are by default initialized with the enum value
23388  obtained via a JNI call. However, this is not the case above as we have
23389  used the recommended <TT>%javaconst(1)</TT> to avoid the JNI call. The <TT>
23390 %javaconstvalue(value)</TT> directive covered in the <A href="#constants">
23391 Constants</A> section can also be used for proper Java enums.</P>
23392 <P> The additional support methods need not be generated if none of the
23393  enum items have initializers and this is covered later in the <A href="#simpler_enum_classes">
23394 Simpler Java enums for enums without initializers</A> section.</P>
23395 <H4><A name="typeunsafe_enums"></A>21.3.5.4 Type unsafe enums</H4>
23396 <P> In this approach each enum item in a named enumeration is wrapped as
23397  a static final integer in a class named after the C/C++ enum name. This
23398  is a commonly used pattern in Java to simulate C/C++ enums, but it is
23399  not typesafe. However, the main advantage over the typesafe enum
23400  pattern is enum items can be used in switch statements. In order to use
23401  this approach, the &quot;enumtypeunsafe.swg&quot; file must be used. Let's take a
23402  look at an example.</P>
23403 <DIV class="code">
23404 <PRE>
23405 %include &quot;enumtypeunsafe.swg&quot;
23406 %javaconst(1);
23407 enum Beverage { ALE, LAGER=10, STOUT, PILSNER, PILZ=PILSNER };
23408 </PRE>
23409 </DIV>
23410 <P> will generate:</P>
23411 <DIV class="code">
23412 <PRE>
23413 public final class Beverage {
23414   public final static int ALE = 0;
23415   public final static int LAGER = 10;
23416   public final static int STOUT = LAGER + 1;
23417   public final static int PILSNER = STOUT + 1;
23418   public final static int PILZ = PILSNER;
23419 }
23420 </PRE>
23421 </DIV>
23422 <P> As is the case previously, the default is <TT>%javaconst(0)</TT> as
23423  not all C/C++ values will compile as Java code. However, again it is
23424  recommended to add in a <TT>%javaconst(1)</TT> directive. and the <TT>
23425 %javaconstvalue(value)</TT> directive covered in the <A href="#constants">
23426 Constants</A> section can also be used for type unsafe enums. Note that
23427  global enums are generated into a Java class within whatever package
23428  you are using. C++ enums defined within a C++ class are generated into
23429  a static final inner Java class within the Java proxy class.</P>
23430 <P> Note that unlike typesafe enums, this approach requires users to
23431  mostly use different syntax compared with proper Java enums. Thus the
23432  upgrade path to proper enums provided in JDK 1.5 is more painful.</P>
23433 <H4><A name="simple_enums"></A>21.3.5.5 Simple enums</H4>
23434 <P> This approach is similar to the type unsafe approach. Each enum item
23435  is also wrapped as a static final integer. However, these integers are
23436  not generated into a class named after the C/C++ enum. Instead, global
23437  enums are generated into the constants interface. Also, enums defined
23438  in a C++ class have their enum items generated directly into the Java
23439  proxy class rather than an inner class within the Java proxy class. In
23440  fact, this approach is effectively wrapping the enums as if they were
23441  anonymous enums and the resulting code is as per <A href="#anonymous_enums">
23442 anonymous enums</A>. The implementation is in the &quot;enumsimple.swg&quot; file.</P>
23443 <P><B> Compatibility Note:</B> SWIG-1.3.21 and earlier versions wrapped
23444  all enums using this approach. The type unsafe approach is preferable
23445  to this one and this simple approach is only included for backwards
23446  compatibility with these earlier versions of SWIG.</P>
23447 <H3><A name="pointers"></A>21.3.6 Pointers</H3>
23448 <P> C/C++ pointers are fully supported by SWIG. Furthermore, SWIG has no
23449  problem working with incomplete type information. Here is a rather
23450  simple interface:</P>
23451 <DIV class="code">
23452 <PRE>
23453 %module example
23454
23455 FILE *fopen(const char *filename, const char *mode);
23456 int fputs(const char *, FILE *);
23457 int fclose(FILE *);
23458 </PRE>
23459 </DIV>
23460 <P> When wrapped, you will be able to use the functions in a natural way
23461  from Java. For example:</P>
23462 <DIV class="code">
23463 <PRE>
23464 SWIGTYPE_p_FILE f = example.fopen(&quot;junk&quot;,&quot;w&quot;);
23465 example.fputs(&quot;Hello World\n&quot;, f);
23466 example.fclose(f);
23467 </PRE>
23468 </DIV>
23469 <P> C pointers in the Java module are stored in a Java <TT>long</TT> and
23470  cross the JNI boundary held within this 64 bit number. Many other SWIG
23471  language modules use an encoding of the pointer in a string. These
23472  scripting languages use the SWIG runtime type checker for dynamic type
23473  checking as they do not support static type checking by a compiler. In
23474  order to implement static type checking of pointers within Java, they
23475  are wrapped by a simple Java class. In the example above the <TT>FILE *</TT>
23476  pointer is wrapped with a<I> type wrapper class</I> called <TT>
23477 SWIGTYPE_p_FILE</TT>.</P>
23478 <P> Once obtained, a type wrapper object can be freely passed around to
23479  different C functions that expect to receive an object of that type.
23480  The only thing you can't do is dereference the pointer from Java. Of
23481  course, that isn't much of a concern in this example.</P>
23482 <P> As much as you might be inclined to modify a pointer value directly
23483  from Java, don't. The value is not necessarily the same as the logical
23484  memory address of the underlying object. The value will vary depending
23485  on the native byte-ordering of the platform (i.e., big-endian vs.
23486  little-endian). Most JVMs are 32 bit applications so any JNI code must
23487  also be compiled as 32 bit. The net result is pointers in JNI code are
23488  also 32 bits and are stored in the high order 4 bytes on big-endian
23489  machines and in the low order 4 bytes on little-endian machines. By
23490  design it is also not possible to manually cast a pointer to a new type
23491  by using Java casts as it is particularly dangerous especially when
23492  casting C++ objects. If you need to cast a pointer or change its value,
23493  consider writing some helper functions instead. For example:</P>
23494 <DIV class="code">
23495 <PRE>
23496 %inline %{
23497 /* C-style cast */
23498 Bar *FooToBar(Foo *f) {
23499    return (Bar *) f;
23500 }
23501
23502 /* C++-style cast */
23503 Foo *BarToFoo(Bar *b) {
23504    return dynamic_cast&lt;Foo*&gt;(b);
23505 }
23506
23507 Foo *IncrFoo(Foo *f, int i) {
23508     return f+i;
23509 }
23510 %}
23511 </PRE>
23512 </DIV>
23513 <P> Also, if working with C++, you should always try to use the new C++
23514  style casts. For example, in the above code, the C-style cast may
23515  return a bogus result whereas as the C++-style cast will return a NULL
23516  pointer if the conversion can't be performed.</P>
23517 <H3><A name="structures"></A>21.3.7 Structures</H3>
23518 <P> If you wrap a C structure, it is wrapped by a Java class with
23519  getters and setters for access to the member variables. For example,</P>
23520 <DIV class="code">
23521 <PRE>
23522 struct Vector {
23523         double x,y,z;
23524 };
23525
23526 </PRE>
23527 </DIV>
23528 <P> is used as follows:</P>
23529 <DIV class="code">
23530 <PRE>
23531 Vector v = new Vector();
23532 v.setX(3.5);
23533 v.setY(7.2);
23534 double x = v.getX();
23535 double y = v.getY();
23536 </PRE>
23537 </DIV>
23538 <P> The variable setters and getters are also based on the JavaBean
23539  design pattern already covered under the Global variables section.
23540  Similar access is provided for unions and the public data members of
23541  C++ classes.</P>
23542 <P> This object is actually an instance of a Java class that has been
23543  wrapped around a pointer to the C structure. This instance doesn't
23544  actually do anything--it just serves as a proxy. The pointer to the C
23545  object is held in the Java proxy class in much the same way as pointers
23546  are held by type wrapper classes. Further details about Java proxy
23547  classes are covered a little later.</P>
23548 <P> <TT>const</TT> members of a structure are read-only. Data members
23549  can also be forced to be read-only using the <TT>%immutable</TT>
23550  directive. For example:</P>
23551 <DIV class="code">
23552 <PRE>
23553 struct Foo {
23554    ...
23555    %immutable;
23556    int x;        /* Read-only members */
23557    char *name;
23558    %mutable;
23559    ...
23560 };
23561 </PRE>
23562 </DIV>
23563 <P> When <TT>char *</TT> members of a structure are wrapped, the
23564  contents are assumed to be dynamically allocated using <TT>malloc</TT>
23565  or <TT>new</TT> (depending on whether or not SWIG is run with the -c++
23566  option). When the structure member is set, the old contents will be
23567  released and a new value created. If this is not the behavior you want,
23568  you will have to use a typemap (described later).</P>
23569 <P> If a structure contains arrays, access to those arrays is managed
23570  through pointers. For example, consider this:</P>
23571 <DIV class="code">
23572 <PRE>
23573 struct Bar {
23574     int  x[16];
23575 };
23576 </PRE>
23577 </DIV>
23578 <P> If accessed in Java, you will see behavior like this:</P>
23579 <DIV class="code">
23580 <PRE>
23581 Bar b = new Bar();
23582 SWIGTYPE_p_int x = b.getX();
23583 </PRE>
23584 </DIV>
23585 <P> This pointer can be passed around to functions that expect to
23586  receive an <TT>int *</TT> (just like C). You can also set the value of
23587  an array member using another pointer. For example:</P>
23588 <DIV class="code">
23589 <PRE>
23590 Bar b = new Bar();
23591 SWIGTYPE_p_int x = b.getX();
23592 Bar c = new Bar();
23593 c.setX(x);                    // Copy contents of b.x to c.x
23594 </PRE>
23595 </DIV>
23596 <P> For array assignment (setters not getters), SWIG copies the entire
23597  contents of the array starting with the data pointed to by <TT>b.x</TT>
23598 . In this example, 16 integers would be copied. Like C, SWIG makes no
23599  assumptions about bounds checking---if you pass a bad pointer, you may
23600  get a segmentation fault or access violation. The default wrapping
23601  makes it hard to set or get just one element of the array and so array
23602  access from Java is somewhat limited. This can be changed easily though
23603  by using the approach outlined later in the <A href="#c_arrays">
23604 Wrapping C arrays with Java arrays</A> and <A href="#unbounded_c_arrays">
23605 Unbounded C Arrays</A> sections.</P>
23606 <P> When a member of a structure is itself a structure, it is handled as
23607  a pointer. For example, suppose you have two structures like this:</P>
23608 <DIV class="code">
23609 <PRE>
23610 struct Foo {
23611    int a;
23612 };
23613
23614 struct Bar {
23615    Foo f;
23616 };
23617 </PRE>
23618 </DIV>
23619 <P> Now, suppose that you access the <TT>f</TT> member of <TT>Bar</TT>
23620  like this:</P>
23621 <DIV class="code">
23622 <PRE>
23623 Bar b = new Bar();
23624 Foo x = b.getF();
23625 </PRE>
23626 </DIV>
23627 <P> In this case, <TT>x</TT> is a pointer that points to the <TT>Foo</TT>
23628  that is inside <TT>b</TT>. This is the same value as generated by this
23629  C code:</P>
23630 <DIV class="code">
23631 <PRE>
23632 Bar b;
23633 Foo *x = &amp;b-&gt;f;       /* Points inside b */
23634 </PRE>
23635 </DIV>
23636 <P> Because the pointer points inside the structure, you can modify the
23637  contents and everything works just like you would expect. For example:</P>
23638 <DIV class="code">
23639 <PRE>
23640 Bar b = new Bar();
23641 b.getF().setA(3);   // Modify b.f.a
23642 Foo x = b.getF();                   
23643 x.setA(3);          // Modify x.a - this is the same as b.f.a
23644 </PRE>
23645 </DIV>
23646 <H3><A name="classes"></A>21.3.8 C++ classes</H3>
23647 <P> C++ classes are wrapped by Java classes as well. For example, if you
23648  have this class,</P>
23649 <DIV class="code">
23650 <PRE>
23651 class List {
23652 public:
23653   List();
23654   ~List();
23655   int  search(char *item);
23656   void insert(char *item);
23657   void remove(char *item);
23658   char *get(int n);
23659   int  length;
23660 };
23661 </PRE>
23662 </DIV>
23663 <P> you can use it in Java like this:</P>
23664 <DIV class="code">
23665 <PRE>
23666 List l = new List();
23667 l.insert(&quot;Ale&quot;);
23668 l.insert(&quot;Stout&quot;);
23669 l.insert(&quot;Lager&quot;);
23670 String item = l.get(2);
23671 int length = l.getLength();
23672 </PRE>
23673 </DIV>
23674 <P> Class data members are accessed in the same manner as C structures.</P>
23675 <P> Static class members are unsurprisingly wrapped as static members of
23676  the Java class:</P>
23677 <DIV class="code">
23678 <PRE>
23679 class Spam {
23680 public:
23681    static void foo();
23682    static int bar;
23683 };
23684 </PRE>
23685 </DIV>
23686 <P> The static members work like any other Java static member:</P>
23687 <DIV class="code">
23688 <PRE>
23689 Spam.foo();
23690 int bar = Spam.getBar();
23691 </PRE>
23692 </DIV>
23693 <H3><A name="inheritance"></A>21.3.9 C++ inheritance</H3>
23694 <P> SWIG is fully aware of issues related to C++ inheritance. Therefore,
23695  if you have classes like this</P>
23696 <DIV class="code">
23697 <PRE>
23698 class Foo {
23699 ...
23700 };
23701
23702 class Bar : public Foo {
23703 ...
23704 };
23705 </PRE>
23706 </DIV>
23707 <P> those classes are wrapped into a hierarchy of Java classes that
23708  reflect the same inheritance structure:</P>
23709 <DIV class="code">
23710 <PRE>
23711 Bar b = new Bar();
23712 Class c = b.getClass();
23713 System.out.println(c.getSuperclass().getName());
23714 </PRE>
23715 </DIV>
23716 <P> will of course display:</P>
23717 <DIV class="code">
23718 <PRE>
23719 Foo
23720 </PRE>
23721 </DIV>
23722 <P> Furthermore, if you have functions like this</P>
23723 <DIV class="code">
23724 <PRE>
23725 void spam(Foo *f);
23726 </PRE>
23727 </DIV>
23728 <P> then the Java function <TT>spam()</TT> accepts instances of <TT>Foo</TT>
23729  or instances of any other proxy classes derived from <TT>Foo</TT>.</P>
23730 <P> Note that Java does not support multiple inheritance so any multiple
23731  inheritance in the C++ code is not going to work. A warning is given
23732  when multiple inheritance is detected and only the first base class is
23733  used.</P>
23734 <H3><A name="pointers_refs_arrays"></A>21.3.10 Pointers, references,
23735  arrays and pass by value</H3>
23736 <P> In C++, there are many different ways a function might receive and
23737  manipulate objects. For example:</P>
23738 <DIV class="code">
23739 <PRE>
23740 void spam1(Foo *x);      // Pass by pointer
23741 void spam2(Foo &amp;x);      // Pass by reference
23742 void spam3(Foo x);       // Pass by value
23743 void spam4(Foo x[]);     // Array of objects
23744 </PRE>
23745 </DIV>
23746 <P> In Java, there is no detailed distinction like this--specifically,
23747  there are only instances of classes. There are no pointers nor
23748  references. Because of this, SWIG unifies all of these types together
23749  in the wrapper code. For instance, if you actually had the above
23750  functions, it is perfectly legal to do this from Java:</P>
23751 <DIV class="code">
23752 <PRE>
23753 Foo f = new Foo();  // Create a Foo
23754 example.spam1(f);   // Ok. Pointer
23755 example.spam2(f);   // Ok. Reference
23756 example.spam3(f);   // Ok. Value.
23757 example.spam4(f);   // Ok. Array (1 element)
23758 </PRE>
23759 </DIV>
23760 <P> Similar behavior occurs for return values. For example, if you had
23761  functions like this,</P>
23762 <DIV class="code">
23763 <PRE>
23764 Foo *spam5();
23765 Foo &amp;spam6();
23766 Foo  spam7();
23767 </PRE>
23768 </DIV>
23769 <P> then all three functions will return a pointer to some <TT>Foo</TT>
23770  object. Since the third function (spam7) returns a value, newly
23771  allocated memory is used to hold the result and a pointer is returned
23772  (Java will release this memory when the returned object's finalizer is
23773  run by the garbage collector).</P>
23774 <H4><A name="null_pointers"></A>21.3.10.1 Null pointers</H4>
23775 <P> Working with null pointers is easy. A Java <TT>null</TT> can be used
23776  whenever a method expects a proxy class or typewrapper class. However,
23777  it is not possible to pass null to C/C++ functions that take parameters
23778  by value or by reference. If you try you will get a
23779  NullPointerException.</P>
23780 <DIV class="code">
23781 <PRE>
23782 example.spam1(null);   // Pointer - ok
23783 example.spam2(null);   // Reference - NullPointerException
23784 example.spam3(null);   // Value - NullPointerException
23785 example.spam4(null);   // Array - ok
23786 </PRE>
23787 </DIV>
23788 <P> For <TT>spam1</TT> and <TT>spam4</TT> above the Java <TT>null</TT>
23789  gets translated into a NULL pointer for passing to the C/C++ function.
23790  The converse also occurs, that is, NULL pointers are translated into <TT>
23791 null</TT> Java objects when returned from a C/C++ function.</P>
23792 <H3><A name="overloaded_functions"></A>21.3.11 C++ overloaded functions</H3>
23793 <P> C++ overloaded functions, methods, and constructors are mostly
23794  supported by SWIG. For example, if you have two functions like this:</P>
23795 <DIV class="code">
23796 <PRE>
23797 %module example
23798
23799 void foo(int);
23800 void foo(char *c);
23801 </PRE>
23802 </DIV>
23803 <P> You can use them in Java in a straightforward manner:</P>
23804 <DIV class="code">
23805 <PRE>
23806 example.foo(3);           // foo(int)
23807 example.foo(&quot;Hello&quot;);     // foo(char *c)
23808 </PRE>
23809 </DIV>
23810 <P> Similarly, if you have a class like this,</P>
23811 <DIV class="code">
23812 <PRE>
23813 class Foo {
23814 public:
23815     Foo();
23816     Foo(const Foo &amp;);
23817     ...
23818 };
23819 </PRE>
23820 </DIV>
23821 <P> you can write Java code like this:</P>
23822 <DIV class="code">
23823 <PRE>
23824 Foo f = new Foo();        // Create a Foo
23825 Foo g = new Foo(f);       // Copy f
23826 </PRE>
23827 </DIV>
23828 <P> Overloading support is not quite as flexible as in C++. Sometimes
23829  there are methods that SWIG cannot disambiguate as there can be more
23830  than one C++ type mapping onto a single Java type. For example:</P>
23831 <DIV class="code">
23832 <PRE>
23833 void spam(int);
23834 void spam(unsigned short);
23835 </PRE>
23836 </DIV>
23837 <P> Here both int and unsigned short map onto a Java int. Here is
23838  another example:</P>
23839 <DIV class="code">
23840 <PRE>
23841 void foo(Bar *b);
23842 void foo(Bar &amp;b);
23843 </PRE>
23844 </DIV>
23845 <P> If declarations such as these appear, you will get a warning message
23846  like this:</P>
23847 <DIV class="code">
23848 <PRE>
23849 example.i:12: Warning(515): Overloaded method spam(unsigned short) ignored.
23850 Method spam(int) at example.i:11 used.
23851 </PRE>
23852 </DIV>
23853 <P> To fix this, you either need to either <A href="#SWIG_rename_ignore">
23854 rename or ignore</A> one of the methods. For example:</P>
23855 <DIV class="code">
23856 <PRE>
23857 %rename(spam_ushort) spam(unsigned short);
23858 ...
23859 void spam(int);    
23860 void spam(unsigned short);   // Now renamed to spam_ushort
23861 </PRE>
23862 </DIV>
23863 <P> or</P>
23864 <DIV class="code">
23865 <PRE>
23866 %ignore spam(unsigned short);
23867 ...
23868 void spam(int);    
23869 void spam(unsigned short);   // Ignored
23870 </PRE>
23871 </DIV>
23872 <H3><A name="java_default_arguments"></A>21.3.12 C++ default arguments</H3>
23873 <P> Any function with a default argument is wrapped by generating an
23874  additional function for each argument that is defaulted. For example,
23875  if we have the following C++:</P>
23876 <DIV class="code">
23877 <PRE>
23878 %module example
23879
23880 void defaults(double d=10.0, int i=0);
23881 </PRE>
23882 </DIV>
23883 <P> The following methods are generated in the Java module class:</P>
23884 <DIV class="code">
23885 <PRE>
23886 public class example {
23887   public static void defaults(double d, int i) { ... }
23888   public static void defaults(double d) { ... }
23889   public static void defaults() { ... }
23890 }
23891 </PRE>
23892 </DIV>
23893 <P> It is as if SWIG had parsed three separate overloaded methods. The
23894  same approach is taken for static methods, constructors and member
23895  methods.</P>
23896 <P><B> Compatibility note:</B> Versions of SWIG prior to SWIG-1.3.23
23897  wrapped these with a single wrapper method and so the default values
23898  could not be taken advantage of from Java. Further details on default
23899  arguments and how to restore this approach are given in the more
23900  general <A href="#SWIGPlus_default_args">Default arguments</A> section.</P>
23901 <H3><A name="namespaces"></A>21.3.13 C++ namespaces</H3>
23902 <P> SWIG is aware of C++ namespaces, but namespace names do not appear
23903  in the module nor do namespaces result in a module that is broken up
23904  into submodules or packages. For example, if you have a file like this,</P>
23905 <DIV class="code">
23906 <PRE>
23907 %module example
23908
23909 namespace foo {
23910    int fact(int n);
23911    struct Vector {
23912        double x,y,z;
23913    };
23914 };
23915 </PRE>
23916 </DIV>
23917 <P> it works in Java as follows:</P>
23918 <DIV class="code">
23919 <PRE>
23920 int f = example.fact(3);
23921 Vector v = new Vector();
23922 v.setX(3.4);
23923 double y = v.getY();
23924 </PRE>
23925 </DIV>
23926 <P> If your program has more than one namespace, name conflicts (if any)
23927  can be resolved using <TT>%rename</TT> For example:</P>
23928 <DIV class="code">
23929 <PRE>
23930 %rename(Bar_spam) Bar::spam;
23931
23932 namespace Foo {
23933     int spam();
23934 }
23935
23936 namespace Bar {
23937     int spam();
23938 }
23939 </PRE>
23940 </DIV>
23941 <P> If you have more than one namespace and you want to keep their
23942  symbols separate, consider wrapping them as separate SWIG modules. Each
23943  SWIG module can be placed into a separate package.</P>
23944 <H3><A name="templates"></A>21.3.14 C++ templates</H3>
23945 <P> C++ templates don't present a huge problem for SWIG. However, in
23946  order to create wrappers, you have to tell SWIG to create wrappers for
23947  a particular template instantiation. To do this, you use the <TT>
23948 %template</TT> directive. For example:</P>
23949 <DIV class="code">
23950 <PRE>
23951 %module example
23952 %{
23953 #include &lt;utility&gt;
23954 %}
23955
23956 template&lt;class T1, class T2&gt;
23957 struct pair {
23958    typedef T1 first_type;
23959    typedef T2 second_type;
23960    T1 first;
23961    T2 second;
23962    pair();
23963    pair(const T1&amp;, const T2&amp;);
23964   ~pair();
23965 };
23966
23967 %template(pairii) pair&lt;int,int&gt;;
23968 </PRE>
23969 </DIV>
23970 <P> In Java:</P>
23971 <DIV class="code">
23972 <PRE>
23973 pairii p = new pairii(3,4);
23974 int first = p.getFirst();
23975 int second = p.getSecond();
23976 </PRE>
23977 </DIV>
23978 <P> Obviously, there is more to template wrapping than shown in this
23979  example. More details can be found in the <A href="#SWIGPlus">SWIG and
23980  C++</A> chapter.</P>
23981 <H3><A name="smart_pointers"></A>21.3.15 C++ Smart Pointers</H3>
23982 <P> In certain C++ programs, it is common to use classes that have been
23983  wrapped by so-called &quot;smart pointers.&quot; Generally, this involves the use
23984  of a template class that implements <TT>operator-&gt;()</TT> like this:</P>
23985 <DIV class="code">
23986 <PRE>
23987 template&lt;class T&gt; class SmartPtr {
23988    ...
23989    T *operator-&gt;();
23990    ...
23991 }
23992 </PRE>
23993 </DIV>
23994 <P> Then, if you have a class like this,</P>
23995 <DIV class="code">
23996 <PRE>
23997 class Foo {
23998 public:
23999      int x;
24000      int bar();
24001 };
24002 </PRE>
24003 </DIV>
24004 <P> A smart pointer would be used in C++ as follows:</P>
24005 <DIV class="code">
24006 <PRE>
24007 SmartPtr&lt;Foo&gt; p = CreateFoo();   // Created somehow (not shown)
24008 ...
24009 p-&gt;x = 3;                        // Foo::x
24010 int y = p-&gt;bar();                // Foo::bar
24011 </PRE>
24012 </DIV>
24013 <P> To wrap this in Java, simply tell SWIG about the <TT>SmartPtr</TT>
24014  class and the low-level <TT>Foo</TT> object. Make sure you instantiate <TT>
24015 SmartPtr</TT> using <TT>%template</TT> if necessary. For example:</P>
24016 <DIV class="code">
24017 <PRE>
24018 %module example
24019 ...
24020 %template(SmartPtrFoo) SmartPtr&lt;Foo&gt;;
24021 ...
24022 </PRE>
24023 </DIV>
24024 <P> Now, in Java, everything should just &quot;work&quot;:</P>
24025 <DIV class="code">
24026 <PRE>
24027 SmartPtrFoo p = example.CreateFoo(); // Create a smart-pointer somehow
24028 p.setX(3);                           // Foo::x
24029 int y = p.bar();                     // Foo::bar
24030 </PRE>
24031 </DIV>
24032 <P> If you ever need to access the underlying pointer returned by <TT>
24033 operator-&gt;()</TT> itself, simply use the <TT>__deref__()</TT> method.
24034  For example:</P>
24035 <DIV class="code">
24036 <PRE>
24037 Foo f = p.__deref__();               // Returns underlying Foo *
24038 </PRE>
24039 </DIV>
24040 <H2><A name="further_details"></A>21.4 Further details on the generated
24041  Java classes</H2>
24042 <P> In the previous section, a high-level view of Java wrapping was
24043  presented. A key component of this wrapping is that structures and
24044  classes are wrapped by Java proxy classes and type wrapper classes are
24045  used in situations where no proxies are generated. This provides a very
24046  natural, type safe Java interface to the C/C++ code and fits in with
24047  the Java programming paradigm. However, a number of low-level details
24048  were omitted. This section provides a brief overview of how the proxy
24049  classes work and then covers the type wrapper classes. Finally enum
24050  classes are covered. First, the crucial intermediary JNI class is
24051  considered.</P>
24052 <H3><A name="imclass"></A>21.4.1 The intermediary JNI class</H3>
24053 <P> In the <A href="#SWIG">&quot;SWIG basics&quot;</A> and <A href="#SWIGPlus">
24054 &quot;SWIG and C++&quot;</A> chapters, details of low-level structure and class
24055  wrapping are described. To summarize those chapters, if you have a
24056  global function and class like this</P>
24057 <DIV class="code">
24058 <PRE>
24059 class Foo {
24060 public:
24061      int x;
24062      int spam(int num, Foo* foo);
24063 };
24064 void egg(Foo* chips);
24065 </PRE>
24066 </DIV>
24067 <P> then SWIG transforms the class into a set of low-level procedural
24068  wrappers. These procedural wrappers essentially perform the equivalent
24069  of this C++ code:</P>
24070 <DIV class="code">
24071 <PRE>
24072 Foo *new_Foo() {
24073     return new Foo();
24074 }
24075 void delete_Foo(Foo *f) {
24076     delete f;
24077 }
24078 int Foo_x_get(Foo *f) {
24079     return f-&gt;x;
24080 }
24081 void Foo_x_set(Foo *f, int value) {
24082     f-&gt;x = value;
24083 }
24084 int Foo_spam(Foo *f, int num, Foo* foo) {
24085     return f-&gt;spam(num, foo);
24086 }
24087 </PRE>
24088 </DIV>
24089 <P> These procedural function names don't actually exist, but their
24090  functionality appears inside the generated JNI functions. The JNI
24091  functions have to follow a particular naming convention so the function
24092  names are actually:</P>
24093 <DIV class="code">
24094 <PRE>
24095 SWIGEXPORT jlong JNICALL Java_exampleJNI_new_1Foo(JNIEnv *jenv, jclass jcls);
24096 SWIGEXPORT void JNICALL Java_exampleJNI_delete_1Foo(JNIEnv *jenv, jclass jcls,
24097                                                     jlong jarg1);
24098 SWIGEXPORT void JNICALL Java_exampleJNI_Foo_1x_1set(JNIEnv *jenv, jclass jcls,
24099                                                     jlong jarg1, jobject jarg1_, jint jarg2);
24100 SWIGEXPORT jint JNICALL Java_exampleJNI_Foo_1x_1get(JNIEnv *jenv, jclass jcls,
24101                                                     jlong jarg1, jobject jarg1_);
24102 SWIGEXPORT jint JNICALL Java_exampleJNI_Foo_1spam(JNIEnv *jenv, jclass jcls,
24103                                                   jlong jarg1, jobject jarg1_, jint jarg2,
24104                                                   jlong jarg3, jobject jarg3_);
24105 SWIGEXPORT void JNICALL Java_exampleJNI_egg(JNIEnv *jenv, jclass jcls,
24106                                             jlong jarg1, jobject jarg1_);
24107 </PRE>
24108 </DIV>
24109 <P> For every JNI C function there has to be a static native Java
24110  function. These appear in the intermediary JNI class:</P>
24111 <DIV class="code">
24112 <PRE>
24113 class exampleJNI {
24114   public final static native long new_Foo();
24115   public final static native void delete_Foo(long jarg1);
24116   public final static native void Foo_x_set(long jarg1, Foo jarg1_, int jarg2);
24117   public final static native int Foo_x_get(long jarg1, Foo jarg1_);
24118   public final static native int Foo_spam(long jarg1, Foo jarg1_, int jarg2,
24119                                           long jarg3, Foo jarg3_);
24120   public final static native void egg(long jarg1, Foo jarg1_);
24121 }
24122 </PRE>
24123 </DIV>
24124 <P> This class contains the complete Java - C/C++ interface so all
24125  function calls go via this class. As this class acts as a go-between
24126  for all JNI calls to C/C++ code from the Java <A href="#java_proxy_classes">
24127 proxy classes</A>, <A href="#type_wrapper_classes">type wrapper classes</A>
24128  and <A href="#java_module_class">module class</A>, it is known as the
24129  intermediary JNI class.</P>
24130 <P> You may notice that SWIG uses a Java long wherever a pointer or
24131  class object needs to be marshalled across the Java-C/C++ boundary.
24132  This approach leads to minimal JNI code which makes for better
24133  performance as JNI code involves a lot of string manipulation. SWIG
24134  favours generating Java code over JNI code as Java code is compiled
24135  into byte code and avoids the costly string operations needed in JNI
24136  code. This approach has a downside though as the proxy class might get
24137  collected before the native method has completed. You might notice
24138  above that there is an additional parameters with a underscore postfix,
24139  eg <TT>jarg1_</TT>. These are added in order to prevent <A href="#java_pgcpp">
24140 premature garbage collection when marshalling proxy classes</A>.</P>
24141 <P> The functions in the intermediary JNI class cannot be accessed
24142  outside of its package. Access to them is gained through the module
24143  class for globals otherwise the appropriate proxy class.</P>
24144  <A name="java_module_directive"></A>
24145 <P> The name of the intermediary JNI class can be changed from its
24146  default, that is, the module name with JNI appended after it. The
24147  module directive attribute <TT>jniclassname</TT> is used to achieve
24148  this:</P>
24149 <DIV class="code">
24150 <PRE>
24151 %module (jniclassname=&quot;name&quot;) modulename
24152 </PRE>
24153 </DIV>
24154 <P> If <TT>name</TT> is the same as <TT>modulename</TT> then the module
24155  class name gets changed from <TT>modulename</TT> to <TT>
24156 modulenameModule</TT>.</P>
24157 <H4><A name="imclass_pragmas"></A>21.4.1.1 The intermediary JNI class
24158  pragmas</H4>
24159 <P> The intermediary JNI class can be tailored through the use of
24160  pragmas, but is not commonly done. The pragmas for this class are:</P>
24161 <TABLE BORDER summary="Intermediary JNI class pragmas">
24162 <TR VALIGN="TOP"><TD><B>Pragma</B></TD><TD><B>Description</B></TD></TR>
24163 <TR><TD>jniclassbase</TD><TD>Base class for the intermediary JNI class</TD>
24164 </TR>
24165 <TR><TD>jniclassclassmodifiers</TD><TD>Class modifiers and class type
24166  for the intermediary JNI class</TD></TR>
24167 <TR><TD>jniclasscode</TD><TD>Java code is copied verbatim into the
24168  intermediary JNI class</TD></TR>
24169 <TR><TD>jniclassimports</TD><TD>Java code, usually one or more import
24170  statements, placed before the intermediary JNI class definition</TD></TR>
24171 <TR><TD>jniclassinterfaces</TD><TD>Comma separated interface classes for
24172  the intermediary JNI class</TD></TR>
24173 </TABLE>
24174 <P> The pragma code appears in the generated intermediary JNI class
24175  where you would expect:</P>
24176 <DIV class="code">
24177 <PRE>
24178 [ jniclassimports pragma ]
24179 [ jniclassclassmodifiers pragma ] jniclassname extends [ jniclassbase pragma ]
24180                                           implements [ jniclassinterfaces pragma ] {
24181 [ jniclasscode pragma ]
24182 ... SWIG generated native methods ...
24183 }
24184 </PRE>
24185 </DIV>
24186 <P> The <TT>jniclasscode</TT> pragma is quite useful for adding in a
24187  static block for loading the shared library / dynamic link library and
24188  demonstrates how pragmas work:</P>
24189 <DIV class="code">
24190 <PRE>
24191 %pragma(java) jniclasscode=%{
24192   static {
24193     try {
24194         System.loadLibrary(&quot;example&quot;);
24195     } catch (UnsatisfiedLinkError e) {
24196       System.err.println(&quot;Native code library failed to load. \n&quot; + e);
24197       System.exit(1);
24198     }
24199   }
24200 %}
24201 </PRE>
24202 </DIV>
24203 <P> Pragmas will take either <TT>&quot;&quot;</TT> or <TT>%{ %}</TT> as
24204  delimiters. For example, let's change the intermediary JNI class access
24205  to public.</P>
24206 <DIV class="code">
24207 <PRE>
24208 %pragma(java) jniclassclassmodifiers=&quot;public class&quot;
24209 </PRE>
24210 </DIV>
24211 <P> All the methods in the intermediary JNI class will then be callable
24212  outside of the package as the method modifiers are public by default.</P>
24213 <H3><A name="java_module_class"></A>21.4.2 The Java module class</H3>
24214 <P> All global functions and variable getters/setters appear in the
24215  module class. For our example, there is just one function:</P>
24216 <DIV class="code">
24217 <PRE>
24218 public class example {
24219   public static void egg(Foo chips) {
24220     exampleJNI.egg(Foo.getCPtr(chips), chips);
24221   }
24222 }
24223 </PRE>
24224 </DIV>
24225 <P> The module class is necessary as there is no such thing as a global
24226  in Java so all the C globals are put into this class. They are
24227  generated as static functions and so must be accessed as such by using
24228  the module name in the static function call:</P>
24229 <DIV class="code">
24230 <PRE>
24231 example.egg(new Foo());
24232 </PRE>
24233 </DIV>
24234 <P> The primary reason for having the module class wrapping the calls in
24235  the intermediary JNI class is to implement static type checking. In
24236  this case only a <TT>Foo</TT> can be passed to the <TT>egg</TT>
24237  function, whereas any <TT>long</TT> can be passed to the <TT>egg</TT>
24238  function in the intermediary JNI class.</P>
24239 <H4><A name="module_class_pragmas"></A>21.4.2.1 The Java module class
24240  pragmas</H4>
24241 <P> The module class can be tailored through the use of pragmas, in the
24242  same manner as the intermediary JNI class. The pragmas are similarly
24243  named and are used in the same way. The complete list follows:</P>
24244 <TABLE BORDER summary="Java module class pragmas">
24245 <TR VALIGN="TOP"><TD><B>Pragma</B></TD><TD><B>Description</B></TD></TR>
24246 <TR><TD>modulebase</TD><TD>Base class for the module class</TD></TR>
24247 <TR><TD>moduleclassmodifiers</TD><TD>Class modifiers and class type for
24248  the module class</TD></TR>
24249 <TR><TD>modulecode</TD><TD>Java code is copied verbatim into the module
24250  class</TD></TR>
24251 <TR><TD>moduleimports</TD><TD>Java code, usually one or more import
24252  statements, placed before the module class definition</TD></TR>
24253 <TR><TD>moduleinterfaces</TD><TD>Comma separated interface classes for
24254  the module class</TD></TR>
24255 </TABLE>
24256 <P> The pragma code appears in the generated module class like this:</P>
24257 <DIV class="code">
24258 <PRE>
24259 [ moduleimports pragma ]
24260 [ modulemodifiers pragma ] modulename extends [ modulebase pragma ]
24261                                       implements [ moduleinterfaces pragma ] {
24262 [ modulecode pragma ]
24263 ... SWIG generated wrapper functions ...
24264 }
24265 </PRE>
24266 </DIV>
24267 <P> See <A href="#imclass_pragmas">The intermediary JNI class pragmas</A>
24268  section for further details on using pragmas.</P>
24269 <H3><A name="java_proxy_classes"></A>21.4.3 Java proxy classes</H3>
24270 <P> A Java proxy class is generated for each structure, union or C++
24271  class that is wrapped. Proxy classes have also been called <A href="http://java.sun.com/developer/JDCTechTips/2001/tt0612.html#tip2">
24272 peer classes</A>. The default proxy class for our previous example looks
24273  like this:</P>
24274 <DIV class="code">
24275 <PRE>
24276 public class Foo {
24277   private long swigCPtr;
24278   protected boolean swigCMemOwn;
24279
24280   protected Foo(long cPtr, boolean cMemoryOwn) {
24281     swigCMemOwn = cMemoryOwn;
24282     swigCPtr = cPtr;
24283   }
24284
24285   protected static long getCPtr(Foo obj) {
24286     return (obj == null) ? 0 : obj.swigCPtr;
24287   }
24288
24289   protected void finalize() {
24290     delete();
24291   }
24292
24293   public synchronized void delete() {
24294     if(swigCPtr != 0 &amp;&amp; swigCMemOwn) {
24295       swigCMemOwn = false;
24296       exampleJNI.delete_Foo(swigCPtr);
24297     }
24298     swigCPtr = 0;
24299   }
24300
24301   public void setX(int value) {
24302     exampleJNI.Foo_x_set(swigCPtr, this, value);
24303   }
24304
24305   public int getX() {
24306     return exampleJNI.Foo_x_get(swigCPtr, this);
24307   }
24308
24309   public int spam(int num, Foo foo) {
24310     return exampleJNI.Foo_spam(swigCPtr, this, num, Foo.getCPtr(foo), foo);
24311   }
24312
24313   public Foo() {
24314     this(exampleJNI.new_Foo(), true);
24315   }
24316
24317 }
24318 </PRE>
24319 </DIV>
24320 <P> This class merely holds a pointer to the underlying C++ object (<TT>
24321 swigCPtr</TT>). It also contains all the methods in the C++ class it is
24322  proxying plus getters and setters for public member variables. These
24323  functions call the native methods in the intermediary JNI class. The
24324  advantage of having this extra layer is the type safety that the proxy
24325  class functions offer. It adds static type checking which leads to
24326  fewer surprises at runtime. For example, you can see that if you
24327  attempt to use the <TT>spam()</TT> function it will only compile when
24328  the parameters passed are an <TT>int</TT> and a <TT>Foo</TT>. From a
24329  user's point of view, it makes the class work as if it were a Java
24330  class:</P>
24331 <DIV class="code">
24332 <PRE>
24333 Foo f = new Foo();
24334 f.setX(3);
24335 int y = f.spam(5, new Foo());
24336 </PRE>
24337 </DIV>
24338 <H4><A name="memory_management"></A>21.4.3.1 Memory management</H4>
24339 <P> Each proxy class has an ownership flag <TT>swigCMemOwn</TT>. The
24340  value of this flag determines who is responsible for deleting the
24341  underlying C++ object. If set to <TT>true</TT>, the proxy class's
24342  finalizer will destroy the C++ object when the proxy class is garbage
24343  collected. If set to false, then the destruction of the proxy class has
24344  no effect on the C++ object.</P>
24345 <P> When an object is created by a constructor or returned by value,
24346  Java automatically takes ownership of the result. On the other hand,
24347  when pointers or references are returned to Java, there is often no way
24348  to know where they came from. Therefore, the ownership is set to false.
24349  For example:</P>
24350 <DIV class="code">
24351 <PRE>
24352 class Foo {
24353 public:
24354     Foo();
24355     Foo bar1();
24356     Foo &amp;bar2();
24357     Foo *bar2();
24358 };
24359 </PRE>
24360 </DIV>
24361 <P> In Java:</P>
24362 <DIV class="code">
24363 <PRE>
24364 Foo f = new Foo();   //  f.swigCMemOwn = true
24365 Foo f1 = f.bar1();   // f1.swigCMemOwn = true
24366 Foo f2 = f.bar2();   // f2.swigCMemOwn = false
24367 Foo f3 = f.bar3();   // f3.swigCMemOwn = false
24368 </PRE>
24369 </DIV>
24370 <P> This behavior for pointers and references is especially important
24371  for classes that act as containers. For example, if a method returns a
24372  pointer to an object that is contained inside another object, you
24373  definitely don't want Java to assume ownership and destroy it!</P>
24374 <P> For the most part, memory management issues remain hidden. However,
24375  there are situations where you might have to manually change the
24376  ownership of an object. For instance, consider code like this:</P>
24377 <DIV class="code">
24378 <PRE>
24379 class Obj {};
24380 class Node {
24381    Obj *value;
24382 public:
24383    void set_value(Obj *v) { value = v; }
24384 };
24385 </PRE>
24386 </DIV>
24387 <P> Now, consider the following Java code:</P>
24388 <DIV class="code">
24389 <PRE>
24390 Node n = new Node();    // Create a node
24391 {
24392   Obj o = new Obj();    // Create an object
24393   n.set_value(o);       // Set value
24394 }                       // o goes out of scope
24395 </PRE>
24396 </DIV>
24397 <P> In this case, the Node <TT>n</TT> is holding a reference to <TT>o</TT>
24398  internally. However, SWIG has no way to know that this has occurred.
24399  The Java proxy class still thinks that it has ownership of <TT>o</TT>.
24400  As <TT>o</TT> has gone out of scope, it could be garbage collected in
24401  which case the C++ destructor will be invoked and <TT>n</TT> will then
24402  be holding a stale-pointer to <TT>o</TT>. If you're lucky, you will
24403  only get a segmentation fault.</P>
24404 <P> To work around this, the ownership flag of <TT>o</TT> needs changing
24405  to <TT>false</TT>. The ownership flag is a private member variable of
24406  the proxy class so this is not possible without some customization of
24407  the proxy class. This can be achieved by using a typemap to customise
24408  the proxy class with pure Java code as detailed later in the section on
24409  <A href="#java_typemaps">Java typemaps</A>.</P>
24410 <P> Sometimes a function will create memory and return a pointer to a
24411  newly allocated object. SWIG has no way of knowing this so by default
24412  the proxy class does not manage the returned object. However, you can
24413  tell the proxy class to manage the memory if you specify the <TT>
24414 %newobject</TT> directive. Consider:</P>
24415 <DIV class="code">
24416 <PRE>
24417 class Obj {...};
24418 class Factory {
24419 public:
24420     static Obj *createObj() { return new Obj(); }
24421 };
24422 </PRE>
24423 </DIV>
24424 <P> If we call the factory function, then we have to manually delete the
24425  memory:</P>
24426 <DIV class="code">
24427 <PRE>
24428 Obj obj = Factory.createObj();   // obj.swigCMemOwn = false
24429 ...
24430 obj.delete();
24431 </PRE>
24432 </DIV>
24433 <P> Now add in the %newobject directive:</P>
24434 <DIV class="code">
24435 <PRE>
24436 %newobject Factory::createObj();
24437
24438 class Obj {...};
24439 class Factory {
24440 public:
24441     static Obj *createObj() { return new Obj(); }
24442 };
24443 </PRE>
24444 </DIV>
24445 <P> A call to <TT>delete()</TT> is no longer necessary as the garbage
24446  collector will make the C++ destructor call because <TT>swigCMemOwn</TT>
24447  is now true.</P>
24448 <DIV class="code">
24449 <PRE>
24450 Obj obj = Factory.createObj();   // obj.swigCMemOwn = true;
24451 ...
24452 </PRE>
24453 </DIV>
24454 <P> Some memory management issues are quite tricky to fix and may only
24455  be noticeable after using for a long time. One such issue is premature
24456  garbage collection of an object created from Java and resultant usage
24457  from C++ code. The section on typemap examples cover two such
24458  scenarios, <A href="#java_memory_management_objects">Memory management
24459  for objects passed to the C++ layer</A> and <A href="#java_memory_management_member_variables">
24460 Memory management when returning references to member variables</A></P>
24461 <H4><A name="inheritance_mirroring"></A>21.4.3.2 Inheritance</H4>
24462 <P> Java proxy classes will mirror C++ inheritance chains. For example,
24463  given the base class <TT>Base</TT> and its derived class <TT>Derived</TT>
24464 :</P>
24465 <DIV class="code">
24466 <PRE>
24467 class Base {
24468 public:
24469   virtual double foo();
24470 };
24471
24472 class Derived : public Base {
24473 public:
24474   virtual double foo();
24475 };
24476 </PRE>
24477 </DIV>
24478 <P> The base class is generated much like any other proxy class seen so
24479  far:</P>
24480 <DIV class="code">
24481 <PRE>
24482 public class Base {
24483   private long swigCPtr;
24484   protected boolean swigCMemOwn;
24485
24486   protected Base(long cPtr, boolean cMemoryOwn) {
24487     swigCMemOwn = cMemoryOwn;
24488     swigCPtr = cPtr;
24489   }
24490
24491   protected static long getCPtr(Base obj) {
24492     return (obj == null) ? 0 : obj.swigCPtr;
24493   }
24494
24495   protected void finalize() {
24496     delete();
24497   }
24498
24499   public synchronized void delete() {
24500     if(swigCPtr != 0 &amp;&amp; swigCMemOwn) {
24501       swigCMemOwn = false;
24502       exampleJNI.delete_Base(swigCPtr);
24503     }
24504     swigCPtr = 0;
24505   }
24506
24507   public double foo() {
24508     return exampleJNI.Base_foo(swigCPtr, this);
24509   }
24510
24511   public Base() {
24512     this(exampleJNI.new_Base(), true);
24513   }
24514
24515 }
24516 </PRE>
24517 </DIV>
24518 <P> The <TT>Derived</TT> class extends <TT>Base</TT> mirroring the C++
24519  class inheritance hierarchy.</P>
24520 <DIV class="code">
24521 <PRE>
24522 public class Derived extends Base {
24523   private long swigCPtr;
24524
24525   protected Derived(long cPtr, boolean cMemoryOwn) {
24526     super(exampleJNI.SWIGDerivedUpcast(cPtr), cMemoryOwn);
24527     swigCPtr = cPtr;
24528   }
24529
24530   protected static long getCPtr(Derived obj) {
24531     return (obj == null) ? 0 : obj.swigCPtr;
24532   }
24533
24534   protected void finalize() {
24535     delete();
24536   }
24537
24538   public synchronized void delete() {
24539     if(swigCPtr != 0 &amp;&amp; swigCMemOwn) {
24540       swigCMemOwn = false;
24541       exampleJNI.delete_Derived(swigCPtr);
24542     }
24543     swigCPtr = 0;
24544     super.delete();
24545   }
24546
24547   public double foo() {
24548     return exampleJNI.Derived_foo(swigCPtr, this);
24549   }
24550
24551   public Derived() {
24552     this(exampleJNI.new_Derived(), true);
24553   }
24554
24555 }
24556 </PRE>
24557 </DIV>
24558 <P> Note the memory ownership is controlled by the base class. However
24559  each class in the inheritance hierarchy has its own pointer value which
24560  is obtained during construction. The <TT>SWIGDerivedUpcast()</TT> call
24561  converts the pointer from a <TT>Derived *</TT> to a <TT>Base *</TT>.
24562  This is a necessity as C++ compilers are free to implement pointers in
24563  the inheritance hierarchy with different values.</P>
24564 <P> It is of course possible to extend <TT>Base</TT> using your own Java
24565  classes. If <TT>Derived</TT> is provided by the C++ code, you could for
24566  example add in a pure Java class <TT>Extended</TT> derived from <TT>
24567 Base</TT>. There is a caveat and that is any C++ code will not know
24568  about your pure Java class <TT>Extended</TT> so this type of derivation
24569  is restricted. However, true cross language polymorphism can be
24570  achieved using the <A href="#java_directors">directors</A> feature.</P>
24571 <H4><A name="proxy_classes_gc"></A>21.4.3.3 Proxy classes and garbage
24572  collection</H4>
24573 <P> By default each proxy class has a <TT>delete()</TT> and a <TT>
24574 finalize()</TT> method. The <TT>finalize()</TT> method calls <TT>
24575 delete()</TT> which frees any malloc'd memory for wrapped C structs or
24576  calls the C++ class destructors. The idea is for <TT>delete()</TT> to
24577  be called when you have finished with the C/C++ object. Ideally you
24578  need not call <TT>delete()</TT>, but rather leave it to the garbage
24579  collector to call it from the finalizer. When a program exits, the
24580  garbage collector does not guarantee to call all finalizers. An insight
24581  into the reasoning behind this can be obtained from <A href="http://www.hpl.hp.com/techreports/2002/HPL-2002-335.html">
24582 Hans Boehm's Destructors, Finalizers, and Synchronization</A> paper.
24583  Depending on what the finalizers do and which operating system you use,
24584  this may or may not be a problem.</P>
24585 <P> If the <TT>delete()</TT> call into JNI code is just for memory
24586  handling, there is not a problem when run on most operating systems,
24587  for example Windows and Unix. Say your JNI code creates memory on the
24588  heap which your finalizers should clean up, the finalizers may or may
24589  not be called before the program exits. In Windows and Unix all memory
24590  that a process uses is returned to the system on exit, so this isn't a
24591  problem. This is not the case in some operating systems like vxWorks.
24592  If however, your finalizer calls into JNI code invoking the C++
24593  destructor which in turn releases a TCP/IP socket for example, there is
24594  no guarantee that it will be released. Note that with long running
24595  programs the garbage collector will eventually run, thereby calling any
24596  unreferenced object's finalizers.</P>
24597 <P> Some not so ideal solutions are:</P>
24598 <OL>
24599 <LI>
24600 <P> Call the <TT>System.runFinalizersOnExit(true)</TT> or <TT>
24601 Runtime.getRuntime().runFinalizersOnExit(true)</TT> to ensure the
24602  finalizers are called before the program exits. The catch is that this
24603  is a deprecated function call as the documentation says:</P>
24604 <DIV class="code"><I> This method is inherently unsafe. It may result in
24605  finalizers being called on live objects while other threads are
24606  concurrently manipulating those objects, resulting in erratic behavior
24607  or deadlock.</I></DIV>
24608 <P>In many cases you will be lucky and find that it works, but it is not
24609  to be advocated. Have a look at <A href="http://java.sun.com">Sun's
24610  Java web site</A> and search for <TT>runFinalizersOnExit</TT>.</P>
24611 </LI>
24612 <LI>
24613 <P> From jdk1.3 onwards a new function, <TT>addShutdownHook()</TT>, was
24614  introduced which is guaranteed to be called when your program exits.
24615  You can encourage the garbage collector to call the finalizers, for
24616  example, add this static block to the class that has the <TT>main()</TT>
24617  function:</P>
24618 <DIV class="code">
24619 <PRE>
24620   static {
24621     Runtime.getRuntime().addShutdownHook( 
24622       new Thread() {
24623         public void run() { System.gc(); System.runFinalization(); }
24624       }
24625     );
24626   }
24627 </PRE>
24628 </DIV>
24629 <P>Although this usually works, the documentation doesn't guarantee that
24630  <TT>runFinalization()</TT> will actually call the finalizers. As the
24631  the shutdown hook is guaranteed you could also make a JNI call to clean
24632  up any resources that are being tracked by the C/C++ code.</P>
24633 </LI>
24634 <LI>
24635 <P>Call the <TT>delete()</TT> function manually which will immediately
24636  invoke the C++ destructor. As a suggestion it may be a good idea to set
24637  the object to null so that should the object be inadvertently used
24638  again a Java null pointer exception is thrown, the alternative would
24639  crash the JVM by using a null C pointer. For example given a SWIG
24640  generated class A:</P>
24641 <DIV class="code">
24642 <PRE>
24643 A myA = new A();
24644 // use myA ...
24645 myA.delete();
24646 // any use of myA here would crash the JVM 
24647 myA=null;
24648 // any use of myA here would cause a Java null pointer exception to be thrown
24649 </PRE>
24650 </DIV>
24651 <P> The SWIG generated code ensures that the memory is not deleted
24652  twice, in the event the finalizers get called in addition to the manual
24653  <TT>delete()</TT> call.</P>
24654 </LI>
24655 <LI>
24656 <P> Write your own object manager in Java. You could derive all SWIG
24657  classes from a single base class which could track which objects have
24658  had their finalizers run, then call the rest of them on program
24659  termination. The section on <A href="#java_typemaps">Java typemaps</A>
24660  details how to specify a pure Java base class.</P>
24661 </LI>
24662 </OL>
24663 <P> See the <A href="http://www.devx.com/Java/Article/30192">How to
24664  Handle Java Finalization's Memory-Retention Issues</A> article for
24665  alternative approaches to managing memory by avoiding finalizers
24666  altogether.</P>
24667 <H4><A name="java_pgcpp"></A>21.4.3.4 The premature garbage collection
24668  prevention parameter for proxy class marshalling</H4>
24669 <P> As covered earlier, the C/C++ struct/class pointer is stored in the
24670  proxy class as a Java long and when needed is passed into the native
24671  method where it is cast into the appropriate type. This approach
24672  provides very fast marshalling but could be susceptible to premature
24673  garbage collection. Consider the following C++ code:</P>
24674 <DIV class="code">
24675 <PRE>
24676 class Wibble {
24677 };
24678 void wobble(Wibble &amp;w);
24679 </PRE>
24680 </DIV>
24681 <P> The module class contains the Java wrapper for the global <TT>wobble</TT>
24682  method:</P>
24683 <DIV class="code">
24684 <PRE>
24685 public class example {
24686   ...
24687   public static void wobble(Wibble w) {
24688     exampleJNI.wobble(Wibble.getCPtr(w), w);
24689   }
24690 }
24691 </PRE>
24692 </DIV>
24693 <P> where <TT>example</TT> is the name of the module. All native methods
24694  go through the intermediary class which has the native method declared
24695  as such:</P>
24696 <DIV class="code">
24697 <PRE>
24698 public class exampleJNI {
24699   ...
24700   public final static native void wobble(long jarg1, Wibble jarg1_);
24701 }
24702 </PRE>
24703 </DIV>
24704 <P> The second parameter, <TT>jarg1_</TT>, is the premature garbage
24705  collection prevention parameter and is added to the native method
24706  parameter list whenever a C/C++ struct or class is marshalled as a Java
24707  long. In order to understand why, consider the alternative where the
24708  intermediary class method is declared without the additional parameter:</P>
24709 <DIV class="code">
24710 <PRE>
24711 public class exampleJNI {
24712   ...
24713   public final static native void wobble(long jarg1);
24714 }
24715 </PRE>
24716 </DIV>
24717 <P> and the following simple call to <TT>wobble</TT>:</P>
24718 <DIV class="code">
24719 <PRE>
24720 {
24721   Wibble w = new Wibble();
24722   example.wobble(w);
24723 }
24724 </PRE>
24725 </DIV>
24726 <P> The hotspot compiler effectively sees something like:</P>
24727 <DIV class="code">
24728 <PRE>
24729 {
24730   Wibble w = new Wibble();
24731   long w_ptr = Wibble.getCPtr(w);
24732   // w is no longer reachable
24733   exampleJNI.wobble(w_ptr);
24734 }
24735 </PRE>
24736 </DIV>
24737 <P> The <TT>Wibble</TT> object is no longer reachable after the point
24738  shown as in this bit of code, the <TT>Wibble</TT> object is not
24739  referenced again after this point. This means that it is a candidate
24740  for garbage collection. Should <TT>wobble</TT> be a long running
24741  method, it is quite likely that the finalizer for the <TT>Wibble</TT>
24742  instance will be called. This in turn will call its underlying C++
24743  destructor which is obviously disastrous while the method <TT>wobble</TT>
24744  is running using this object. Even if <TT>wobble</TT> is not a long
24745  running method, it is possible for the <TT>Wibble</TT> instance to be
24746  finalized. By passing the <TT>Wibble</TT> instance into the native
24747  method, it will not be finalized as the JVM guarantees not to finalize
24748  any objects until the native method returns. Effectively, the code then
24749  becomes</P>
24750 <DIV class="code">
24751 <PRE>
24752 {
24753   Wibble w = new Wibble();
24754   long w_ptr = Wibble.getCPtr(w);
24755   exampleJNI.wobble(w_ptr, w);
24756   // w is no longer reachable
24757 }
24758 </PRE>
24759 </DIV>
24760 <P> and therefore there is no possibility of premature garbage
24761  collection. In practice, this premature garbage collection was only
24762  ever observed in Sun's server JVM from jdk-1.3 onwards and in Sun's
24763  client JVM from jdk-1.6 onwards.</P>
24764 <P> The premature garbage collection prevention parameter for proxy
24765  classes is generated by default whenever proxy classes are passed by
24766  value, reference or with a pointer. The implementation for this extra
24767  parameter generation requires the &quot;jtype&quot; typemap to contain <TT>long</TT>
24768  and the &quot;jstype&quot; typemap to contain the name of a proxy class.</P>
24769 <P> The additional parameter does impose a slight performance overhead
24770  and the parameter generation can be suppressed globally with the <TT>
24771 -nopgcpp</TT> commandline option. More selective suppression is possible
24772  with the 'nopgcpp' attribute in the &quot;jtype&quot; <A href="#java_typemaps">
24773 Java typemap</A>. The attribute is a flag and so should be set to &quot;1&quot; to
24774  enable the suppression, or it can be omitted or set to &quot;0&quot; to disable.
24775  For example:</P>
24776 <DIV class="code">
24777 <PRE>
24778 %typemap(jtype, nopgcpp=&quot;1&quot;) Wibble &amp; &quot;long&quot;
24779 </PRE>
24780 </DIV>
24781 <P><B> Compatibility note:</B> The generation of this additional
24782  parameter did not occur in versions prior to SWIG-1.3.30.</P>
24783 <H4><A name="java_multithread_libraries"></A>21.4.3.5 Single threaded
24784  applications and thread safety</H4>
24785 <P> Single threaded Java applications using JNI need to consider thread
24786  safety. The same applies for the C# module where the .NET wrappers use
24787  PInvoke. Consider the C++ class:</P>
24788 <DIV class="code">
24789 <PRE>
24790 class Test {
24791   string str;
24792 public:
24793   Test() : str(&quot;initial&quot;) {}
24794 };
24795 </PRE>
24796 </DIV>
24797 <P> and the Java proxy class generated by SWIG:</P>
24798 <DIV class="code">
24799 <PRE>
24800 public class Test {
24801   private long swigCPtr;
24802   protected boolean swigCMemOwn;
24803
24804   protected Test(long cPtr, boolean cMemoryOwn) {
24805     swigCMemOwn = cMemoryOwn;
24806     swigCPtr = cPtr;
24807   }
24808
24809   protected static long getCPtr(Test obj) {
24810     return (obj == null) ? 0 : obj.swigCPtr;
24811   }
24812
24813   protected void finalize() {
24814     delete();
24815   }
24816
24817   // Call C++ destructor
24818   public synchronized void delete() {
24819     if(swigCPtr != 0 &amp;&amp; swigCMemOwn) {
24820       swigCMemOwn = false;
24821       exampleJNI.delete_Test(swigCPtr);
24822     }
24823     swigCPtr = 0;
24824   }
24825
24826   // Call C++ constructor
24827   public Test() {
24828     this(exampleJNI.new_Test(), true);
24829   }
24830
24831 }
24832 </PRE>
24833 </DIV>
24834 <P> It has two methods that call JNI methods, namely, <TT>
24835 exampleJNI.new_Test()</TT> for the C++ constructor and <TT>
24836 exampleJNI.delete_Test()</TT> for the C++ destructor. If the garbage
24837  collector collects an instance of this class, ie <TT>delete()</TT> is
24838  not explicitly called, then the C++ destructor will be run in a
24839  different thread to the main thread. This is because when an object is
24840  marked for garbage collection, any objects with finalizers are added to
24841  a finalization queue and the objects in the finalization queue have
24842  their <TT>finalize()</TT> methods run in a separate finalization
24843  thread. Therefore, if the C memory allocator is not thread safe, then
24844  the heap will get corrupted sooner or later, when a concurrent C++
24845  delete and new are executed. It is thus essential, even in single
24846  threaded usage, to link to the C multi-thread runtime libraries, for
24847  example, use the /MD option for Visual C++ on Windows. Alternatively,
24848  lock all access to C++ functions that have heap
24849  allocation/deallocation.</P>
24850 <P> Note that some of the STL in Visual C++ 6 is not thread safe, so
24851  although code might be linked to the multithread runtime libraries,
24852  undefined behaviour might still occur in a single threaded Java
24853  program. Similarly some older versions of Sun Studio have bugs in the
24854  multi-threaded implementation of the std::string class and so will lead
24855  to undefined behaviour in these supposedly single threaded Java
24856  applications.</P>
24857 <P> The following innocuous Java usage of Test is an example that will
24858  crash very quickly on a multiprocessor machine if the JNI compiled code
24859  is linked against the single thread C runtime libraries.</P>
24860 <DIV class="code">
24861 <PRE>
24862 for (int i=0; i&lt;100000; i++) {
24863   System.out.println(&quot;Iteration &quot; + i);
24864   for (int k=0; k&lt;10; k++) {
24865     Test test = new Test();
24866   }
24867   System.gc();
24868 }
24869 </PRE>
24870 </DIV>
24871 <H3><A name="type_wrapper_classes"></A>21.4.4 Type wrapper classes</H3>
24872 <P> The generated type wrapper class, for say an <TT>int *</TT>, looks
24873  like this:</P>
24874 <DIV class="code">
24875 <PRE>
24876 public class SWIGTYPE_p_int {
24877   private long swigCPtr;
24878
24879   protected SWIGTYPE_p_int(long cPtr, boolean bFutureUse) {
24880     swigCPtr = cPtr;
24881   }
24882
24883   protected SWIGTYPE_p_int() {
24884     swigCPtr = 0;
24885   }
24886
24887   protected static long getCPtr(SWIGTYPE_p_int obj) {
24888     return obj.swigCPtr;
24889   }
24890 }
24891 </PRE>
24892 </DIV>
24893 <P> The methods do not have public access, so by default it is
24894  impossible to do anything with objects of this class other than pass
24895  them around. The methods in the class are part of the inner workings of
24896  SWIG. If you need to mess around with pointers you will have to use
24897  some typemaps specific to the Java module to achieve this. The section
24898  on <A href="#java_typemaps">Java typemaps</A> details how to modify the
24899  generated code.</P>
24900 <P> Note that if you use a pointer or reference to a proxy class in a
24901  function then no type wrapper class is generated because the proxy
24902  class can be used as the function parameter. If however, you need
24903  anything more complicated like a pointer to a pointer to a proxy class
24904  then a typewrapper class is generated for your use.</P>
24905 <P> Note that SWIG generates a type wrapper class and not a proxy class
24906  when it has not parsed the definition of a type that gets used. For
24907  example, say SWIG has not parsed the definition of <TT>class Snazzy</TT>
24908  because it is in a header file that you may have forgotten to use the <TT>
24909 %include</TT> directive on. Should SWIG parse <TT>Snazzy *</TT> being
24910  used in a function parameter, it will then generates a type wrapper
24911  class around a <TT>Snazzy</TT> pointer. Also recall from earlier that
24912  SWIG will use a pointer when a class is passed by value or by
24913  reference:</P>
24914 <DIV class="code">
24915 <PRE>
24916 void spam(Snazzy *x, Snazzy &amp;y, Snazzy z);
24917 </PRE>
24918 </DIV>
24919 <P> Should SWIG not know anything about <TT>Snazzy</TT> then a <TT>
24920 SWIGTYPE_p_Snazzy</TT> must be used for all 3 parameters in the <TT>spam</TT>
24921  function. The Java function generated is:</P>
24922 <DIV class="code">
24923 <PRE>
24924 public static void spam(SWIGTYPE_p_Snazzy x, SWIGTYPE_p_Snazzy y, SWIGTYPE_p_Snazzy z) {
24925  ...
24926 }
24927 </PRE>
24928 </DIV>
24929 <P> Note that typedefs are tracked by SWIG and the typedef name is used
24930  to construct the type wrapper class name. For example, consider the
24931  case where <TT>Snazzy</TT> is a typedef to an <TT>int</TT> which SWIG
24932  does parse:</P>
24933 <DIV class="code">
24934 <PRE>
24935 typedef int Snazzy;
24936 void spam(Snazzy *x, Snazzy &amp;y, Snazzy z);
24937 </PRE>
24938 </DIV>
24939 <P> Because the typedefs have been tracked the Java function generated
24940  is:</P>
24941 <DIV class="code">
24942 <PRE>
24943 public static void spam(SWIGTYPE_p_int x, SWIGTYPE_p_int y, int z) { ... }
24944 </PRE>
24945 </DIV>
24946 <H3><A name="enum_classes"></A>21.4.5 Enum classes</H3>
24947 <P> SWIG can generate three types of enum classes. The <A href="#enumerations">
24948 Enumerations</A> section discussed these but omitted all the details.
24949  The following sub-sections detail the various types of enum classes
24950  that can be generated.</P>
24951 <H4><A name="typesafe_enums_classes"></A>21.4.5.1 Typesafe enum classes</H4>
24952 <P> The following example demonstrates the typesafe enum classes which
24953  SWIG generates:</P>
24954 <DIV class="code">
24955 <PRE>
24956 %include &quot;enumtypesafe.swg&quot;
24957 %javaconst(1);
24958 enum Beverage { ALE, LAGER=10, STOUT, PILSNER, PILZ=PILSNER };
24959 </PRE>
24960 </DIV>
24961 <P> The following is the code that SWIG generates:</P>
24962 <DIV class="code">
24963 <PRE>
24964 public final class Beverage {
24965   public final static Beverage ALE = new Beverage(&quot;ALE&quot;);
24966   public final static Beverage LAGER = new Beverage(&quot;LAGER&quot;, 10);
24967   public final static Beverage STOUT = new Beverage(&quot;STOUT&quot;);
24968   public final static Beverage PILSNER = new Beverage(&quot;PILSNER&quot;);
24969   public final static Beverage PILZ = new Beverage(&quot;PILZ&quot;, PILSNER);
24970
24971   public final int swigValue() {
24972     return swigValue;
24973   }
24974
24975   public String toString() {
24976     return swigName;
24977   }
24978
24979   public static Beverage swigToEnum(int swigValue) {
24980     if (swigValue &lt; swigValues.length &amp;&amp; swigValue &gt;= 0 &amp;&amp;
24981         swigValues[swigValue].swigValue == swigValue)
24982       return swigValues[swigValue];
24983     for (int i = 0; i &lt; swigValues.length; i++)
24984       if (swigValues[i].swigValue == swigValue)
24985         return swigValues[i];
24986     throw new IllegalArgumentException(&quot;No enum &quot; + Beverage.class + &quot; with value &quot; +
24987                                                                          swigValue);
24988   }
24989
24990   private Beverage(String swigName) {
24991     this.swigName = swigName;
24992     this.swigValue = swigNext++;
24993   }
24994
24995   private Beverage(String swigName, int swigValue) {
24996     this.swigName = swigName;
24997     this.swigValue = swigValue;
24998     swigNext = swigValue+1;
24999   }
25000
25001   private Beverage(String swigName, Beverage swigEnum) {
25002     this.swigName = swigName;
25003     this.swigValue = swigEnum.swigValue;
25004     swigNext = this.swigValue+1;
25005   }
25006
25007   private static Beverage[] swigValues = { ALE, LAGER, STOUT, PILSNER, PILZ };
25008   private static int swigNext = 0;
25009   private final int swigValue;
25010   private final String swigName;
25011 }
25012 </PRE>
25013 </DIV>
25014 <P> As can be seen, there are a fair number of support methods for the
25015  typesafe enum pattern. The typesafe enum pattern involves creating a
25016  fixed number of static instances of the enum class. The constructors
25017  are private to enforce this. Three constructors are available - two for
25018  C/C++ enums with an initializer and one for those without an
25019  initializer. Note that the two enums with initializers, <TT>LAGER</TT>
25020  and <TT>PILZ</TT>, each call one the two different initializer
25021  constructors. In order to use one of these typesafe enums, the <TT>
25022 swigToEnum</TT> static method must be called to return a reference to
25023  one of the static instances. The JNI layer returns the enum value from
25024  the C/C++ world as an integer and this method is used to find the
25025  appropriate Java enum static instance. The <TT>swigValue</TT> method is
25026  used for marshalling in the other direction. The <TT>toString</TT>
25027  method is overridden so that the enum name is available.</P>
25028 <H4><A name="proper_enums_classes"></A>21.4.5.2 Proper Java enum classes</H4>
25029 <P> The following example demonstrates the Java enums approach:</P>
25030 <DIV class="code">
25031 <PRE>
25032 %include &quot;enums.swg&quot;
25033 %javaconst(1);
25034 enum Beverage { ALE, LAGER=10, STOUT, PILSNER, PILZ=PILSNER };
25035 </PRE>
25036 </DIV>
25037 <P> SWIG will generate the following Java enum:</P>
25038 <DIV class="code">
25039 <PRE>
25040 public enum Beverage {
25041   ALE,
25042   LAGER(10),
25043   STOUT,
25044   PILSNER,
25045   PILZ(PILSNER);
25046
25047   public final int swigValue() {
25048     return swigValue;
25049   }
25050
25051   public static Beverage swigToEnum(int swigValue) {
25052     Beverage[] swigValues = Beverage.class.getEnumConstants();
25053     if (swigValue &lt; swigValues.length &amp;&amp; swigValue &gt;= 0 &amp;&amp;
25054         swigValues[swigValue].swigValue == swigValue)
25055       return swigValues[swigValue];
25056     for (Beverage swigEnum : swigValues)
25057       if (swigEnum.swigValue == swigValue)
25058         return swigEnum;
25059     throw new IllegalArgumentException(&quot;No enum &quot; + Beverage.class +
25060                                        &quot; with value &quot; + swigValue);
25061   }
25062
25063   private Beverage() {
25064     this.swigValue = SwigNext.next++;
25065   }
25066
25067   private Beverage(int swigValue) {
25068     this.swigValue = swigValue;
25069     SwigNext.next = swigValue+1;
25070   }
25071
25072   private Beverage(Beverage swigEnum) {
25073     this.swigValue = swigEnum.swigValue;
25074     SwigNext.next = this.swigValue+1;
25075   }
25076
25077   private final int swigValue;
25078
25079   private static class SwigNext {
25080     private static int next = 0;
25081   }
25082 }
25083 </PRE>
25084 </DIV>
25085 <P> The enum items appear first. Like the typesafe enum pattern, the
25086  constructors are private. The constructors are required to handle C/C++
25087  enums with initializers. The <TT>next</TT> variable is in the <TT>
25088 SwigNext</TT> inner class rather than in the enum class as static
25089  primitive variables cannot be modified from within enum constructors.
25090  Marshalling between Java enums and the C/C++ enum integer value is
25091  handled via the <TT>swigToEnum</TT> and <TT>swigValue</TT> methods. All
25092  the constructors and methods in the Java enum are required just to
25093  handle C/C++ enums with initializers. These needn't be generated if the
25094  enum being wrapped does not have any initializers and the <A href="#simpler_enum_classes">
25095 Simpler Java enums for enums without initializers</A> section describes
25096  how typemaps can be used to achieve this.</P>
25097 <H4><A name="typeunsafe_enums_classes"></A>21.4.5.3 Type unsafe enum
25098  classes</H4>
25099 <P> The following example demonstrates type unsafe enums:</P>
25100 <DIV class="code">
25101 <PRE>
25102 %include &quot;enumtypeunsafe.swg&quot;
25103 %javaconst(1);
25104 enum Beverage { ALE, LAGER=10, STOUT, PILSNER, PILZ=PILSNER };
25105 </PRE>
25106 </DIV>
25107 <P> SWIG will generate the following simple class:</P>
25108 <DIV class="code">
25109 <PRE>
25110 public final class Beverage {
25111   public final static int ALE = 0;
25112   public final static int LAGER = 10;
25113   public final static int STOUT = LAGER + 1;
25114   public final static int PILSNER = STOUT + 1;
25115   public final static int PILZ = PILSNER;
25116 }
25117 </PRE>
25118 </DIV>
25119 <H2><A name="java_directors"></A>21.5 Cross language polymorphism using
25120  directors</H2>
25121 <P> Proxy classes provide a natural, object-oriented way to wrap C++
25122  classes. as described earlier, each proxy instance has an associated
25123  C++ instance, and method calls from Java to the proxy are passed to the
25124  C++ instance transparently via C wrapper functions.</P>
25125 <P> This arrangement is asymmetric in the sense that no corresponding
25126  mechanism exists to pass method calls down the inheritance chain from
25127  C++ to Java. In particular, if a C++ class has been extended in Java
25128  (by deriving from the proxy class), these classes will not be visible
25129  from C++ code. Virtual method calls from C++ are thus not able to
25130  access the lowest implementation in the inheritance chain.</P>
25131 <P> SWIG can address this problem and make the relationship between C++
25132  classes and proxy classes more symmetric. To achieve this goal, new
25133  classes called directors are introduced at the bottom of the C++
25134  inheritance chain. The job of the directors is to route method calls
25135  correctly, either to C++ implementations higher in the inheritance
25136  chain or to Java implementations lower in the inheritance chain. The
25137  upshot is that C++ classes can be extended in Java and from C++ these
25138  extensions look exactly like native C++ classes. Neither C++ code nor
25139  Java code needs to know where a particular method is implemented: the
25140  combination of proxy classes, director classes, and C wrapper functions
25141  transparently takes care of all the cross-language method routing.</P>
25142 <H3><A name="java_enabling_directors"></A>21.5.1 Enabling directors</H3>
25143 <P> The director feature is disabled by default. To use directors you
25144  must make two changes to the interface file. First, add the &quot;directors&quot;
25145  option to the %module directive, like this:</P>
25146 <DIV class="code">
25147 <PRE>
25148 %module(directors=&quot;1&quot;) modulename
25149 </PRE>
25150 </DIV>
25151 <P> Without this option no director code will be generated. Second, you
25152  must use the %feature(&quot;director&quot;) directive to tell SWIG which classes
25153  and methods should get directors. The %feature directive can be applied
25154  globally, to specific classes, and to specific methods, like this:</P>
25155 <DIV class="code">
25156 <PRE>
25157 // generate directors for all classes that have virtual methods
25158 %feature(&quot;director&quot;);         
25159
25160 // generate directors for all virtual methods in class Foo
25161 %feature(&quot;director&quot;) Foo;      
25162
25163 // generate a director for just Foo::bar()
25164 %feature(&quot;director&quot;) Foo::bar; 
25165 </PRE>
25166 </DIV>
25167 <P> You can use the %feature(&quot;nodirector&quot;) directive to turn off
25168  directors for specific classes or methods. So for example,</P>
25169 <DIV class="code">
25170 <PRE>
25171 %feature(&quot;director&quot;) Foo;
25172 %feature(&quot;nodirector&quot;) Foo::bar;
25173 </PRE>
25174 </DIV>
25175 <P> will generate directors for all virtual methods of class Foo except
25176  bar().</P>
25177 <P> Directors can also be generated implicitly through inheritance. In
25178  the following, class Bar will get a director class that handles the
25179  methods one() and two() (but not three()):</P>
25180 <DIV class="code">
25181 <PRE>
25182 %feature(&quot;director&quot;) Foo;
25183 class Foo {
25184 public:
25185     virtual void one();
25186     virtual void two();
25187 };
25188
25189 class Bar: public Foo {
25190 public:
25191     virtual void three();
25192 };
25193 </PRE>
25194 </DIV>
25195 <H3><A name="java_directors_classes"></A>21.5.2 Director classes</H3>
25196 <P> For each class that has directors enabled, SWIG generates a new
25197  class that derives from both the class in question and a special <TT>
25198 Swig::Director</TT> class. These new classes, referred to as director
25199  classes, can be loosely thought of as the C++ equivalent of the Java
25200  proxy classes. The director classes store a pointer to their underlying
25201  Java proxy classes.</P>
25202 <P> For simplicity let's ignore the <TT>Swig::Director</TT> class and
25203  refer to the original C++ class as the director's base class. By
25204  default, a director class extends all virtual methods in the
25205  inheritance chain of its base class (see the preceding section for how
25206  to modify this behavior). Thus all virtual method calls, whether they
25207  originate in C++ or in Java via proxy classes, eventually end up in at
25208  the implementation in the director class. The job of the director
25209  methods is to route these method calls to the appropriate place in the
25210  inheritance chain. By &quot;appropriate place&quot; we mean the method that would
25211  have been called if the C++ base class and its Java derived classes
25212  were seamlessly integrated. That seamless integration is exactly what
25213  the director classes provide, transparently skipping over all the messy
25214  JNI glue code that binds the two languages together.</P>
25215 <P> In reality, the &quot;appropriate place&quot; is one of only two
25216  possibilities: C++ or Java. Once this decision is made, the rest is
25217  fairly easy. If the correct implementation is in C++, then the lowest
25218  implementation of the method in the C++ inheritance chain is called
25219  explicitly. If the correct implementation is in Java, the Java API is
25220  used to call the method of the underlying Java object (after which the
25221  usual virtual method resolution in Java automatically finds the right
25222  implementation).</P>
25223 <H3><A name="java_directors_overhead"></A>21.5.3 Overhead and code bloat</H3>
25224 <P> Enabling directors for a class will generate a new director method
25225  for every virtual method in the class' inheritance chain. This alone
25226  can generate a lot of code bloat for large hierarchies. Method
25227  arguments that require complex conversions to and from Java types can
25228  result in large director methods. For this reason it is recommended
25229  that directors are selectively enabled only for specific classes that
25230  are likely to be extended in Java and used in C++.</P>
25231 <P> Although directors make it natural to mix native C++ objects with
25232  Java objects (as director objects), one should be aware of the obvious
25233  fact that method calls to Java objects from C++ will be much slower
25234  than calls to C++ objects. Additionally, compared to classes that do
25235  not use directors, the call routing in the director methods adds a
25236  small overhead. This situation can be optimized by selectively enabling
25237  director methods (using the %feature directive) for only those methods
25238  that are likely to be extended in Java.</P>
25239 <H3><A name="java_directors_example"></A>21.5.4 Simple directors example</H3>
25240 <P> Consider the following SWIG interface file:</P>
25241 <DIV class="code">
25242 <PRE>
25243 %module(directors=&quot;1&quot;) example;
25244
25245 %feature(&quot;director&quot;) DirectorBase;
25246
25247 class DirectorBase {
25248 public:
25249   virtual ~DirectorBase() {}
25250   virtual void upcall_method() {}
25251 };
25252
25253 void callup(DirectorBase *director) {
25254   director-&gt;upcall_method();
25255 }
25256 </PRE>
25257 </DIV>
25258 <P> The following <CODE>DirectorDerived</CODE> Java class is derived
25259  from the Java proxy class <CODE>DirectorBase</CODE> and overrides <CODE>
25260 upcall_method()</CODE>. When C++ code invokes <CODE>upcall_method()</CODE>
25261 , the SWIG-generated C++ code redirects the call via JNI to the Java <CODE>
25262 DirectorDerived</CODE> subclass. Naturally, the SWIG generated C++ code
25263  and the generated Java intermediate class marshal and convert arguments
25264  between C++ and Java when needed.</P>
25265 <DIV class="code">
25266 <PRE>
25267 public class DirectorDerived extends DirectorBase {
25268   public DirectorDerived() {
25269   }
25270
25271   public void upcall_method() {
25272     System.out.println(&quot;DirectorDerived::upcall_method() invoked.&quot;);
25273   }
25274 }
25275 </PRE>
25276 </DIV>
25277 <P> Running the following Java code</P>
25278 <DIV class="code">
25279 <PRE>
25280 DirectorDerived director = new DirectorDerived();
25281 example.callup(director);
25282 </PRE>
25283 </DIV>
25284 <P> will result in the following being output:</P>
25285 <DIV class="code">
25286 <PRE>
25287 DirectorDerived::upcall_method() invoked.
25288 </PRE>
25289 </DIV>
25290 <H3><A name="java_directors_threading"></A>21.5.5 Director threading
25291  issues</H3>
25292 <P> Depending on your operating system and version of Java and how you
25293  are using threads, you might find the JVM hangs on exit. There are a
25294  couple of solutions to try out. The preferred solution requires jdk-1.4
25295  and later and uses <TT>AttachCurrentThreadAsDaemon</TT> instead of <TT>
25296 AttachCurrentThread</TT> whenever a call into the JVM is required. This
25297  can be enabled by defining the
25298  SWIG_JAVA_ATTACH_CURRENT_THREAD_AS_DAEMON macro when compiling the C++
25299  wrapper code. For older JVMs define SWIG_JAVA_NO_DETACH_CURRENT_THREAD
25300  instead, to avoid the <TT>DetachCurrentThread</TT> call but this will
25301  result in a memory leak instead. For further details inspect the source
25302  code in the java/director.swg library file.</P>
25303 <P> Macros can be defined on the commandline when compiling your C++
25304  code, or alternatively added to the C++ wrapper file as shown below:</P>
25305 <DIV class="code">
25306 <PRE>
25307 %insert(&quot;runtime&quot;) %{
25308 #define SWIG_JAVA_NO_DETACH_CURRENT_THREAD
25309 %}
25310 </PRE>
25311 </DIV>
25312 <H2><A name="java_allprotected"></A>21.6 Accessing protected members</H2>
25313 <P> When using directors, the protected virtual methods are also
25314  wrapped. These methods are wrapped with a protected Java proxy method,
25315  so the only way that Java code can access these is from within a Java
25316  class derived from the director class.</P>
25317 <P> Members which are protected and non-virtual can also be accessed
25318  when using the 'allprotected' mode. The allprotected mode requires
25319  directors and is turned on by setting the <TT>allprotected</TT> option
25320  in addition to the <TT>directors</TT> option in the %module directive,
25321  like this:</P>
25322 <DIV class="code">
25323 <PRE>
25324 %module(directors=&quot;1&quot;, allprotected=&quot;1&quot;) modulename
25325 </PRE>
25326 </DIV>
25327 <P> Protected member variables and methods (both static and non-static)
25328  will then be wrapped with protected access in the Java proxy class.</P>
25329 <P><B> Note:</B> Neither the directors option nor the allprotected mode
25330  support types defined with protected scope. This includes any enums or
25331  typedefs declared in the protected section of the C++ class.</P>
25332 <P> The following simple example is a class with numerous protected
25333  members, including the constructor and destructor:</P>
25334 <DIV class="code">
25335 <PRE>
25336 %module(directors=&quot;1&quot;, allprotected=&quot;1&quot;) example
25337
25338 %feature(&quot;director&quot;) ProtectedBase;
25339
25340 // Ignore use of unsupported types (those defined in the protected section)
25341 %ignore ProtectedBase::typedefs;
25342
25343 %inline %{
25344
25345 class ProtectedBase {
25346 protected:
25347   ProtectedBase() {}
25348   virtual ~ProtectedBase() {}
25349   virtual void virtualMethod() const {}
25350   void nonStaticMethod(double d) const {}
25351   static void staticMethod(int i) {}
25352   int instanceMemberVariable;
25353   static int staticMemberVariable;
25354
25355   // unsupported: types defined with protected access and the methods/variables which use them
25356   typedef int IntegerType;
25357   IntegerType typedefs(IntegerType it) { return it; }
25358 };
25359 int ProtectedBase::staticMemberVariable = 10;
25360
25361 %}
25362
25363 </PRE>
25364 </DIV>
25365 <P> Note that the <TT>IntegerType</TT> has protected scope and the
25366  members which use this type must be ignored as they cannot be wrapped.</P>
25367 <P> The proxy methods are protected, so the only way the protected
25368  members can be accessed is within a class that derives from the
25369  director class, such as the following:</P>
25370 <DIV class="code">
25371 <PRE>
25372 class MyProtectedBase extends ProtectedBase
25373 {
25374   public MyProtectedBase() {
25375   }
25376
25377   public void accessProtected() {
25378     virtualMethod();
25379     nonStaticMethod(1.2);
25380     staticMethod(99);
25381
25382     setInstanceMemberVariable(5);
25383     int i = getInstanceMemberVariable();
25384
25385     setStaticMemberVariable(10);
25386     i = getStaticMemberVariable();
25387   }
25388 }
25389 </PRE>
25390 </DIV>
25391 <H2><A name="common_customization"></A>21.7 Common customization
25392  features</H2>
25393 <P> An earlier section presented the absolute basics of C/C++ wrapping.
25394  If you do nothing but feed SWIG a header file, you will get an
25395  interface that mimics the behavior described. However, sometimes this
25396  isn't enough to produce a nice module. Certain types of functionality
25397  might be missing or the interface to certain functions might be
25398  awkward. This section describes some common SWIG features that are used
25399  to improve the interface to existing C/C++ code.</P>
25400 <H3><A name="helper_functions"></A>21.7.1 C/C++ helper functions</H3>
25401 <P> Sometimes when you create a module, it is missing certain bits of
25402  functionality. For example, if you had a function like this</P>
25403 <DIV class="code">
25404 <PRE>
25405 typedef struct Image {...};
25406 void set_transform(Image *im, double m[4][4]);
25407 </PRE>
25408 </DIV>
25409 <P> it would be accessible from Java, but there may be no easy way to
25410  call it. The problem here is that a type wrapper class is generated for
25411  the two dimensional array parameter so there is no easy way to
25412  construct and manipulate a suitable <TT>double [4][4]</TT> value. To
25413  fix this, you can write some extra C helper functions. Just use the <TT>
25414 %inline</TT> directive. For example:</P>
25415 <DIV class="code">
25416 <PRE>
25417 %inline %{
25418 /* Note: double[4][4] is equivalent to a pointer to an array double (*)[4] */
25419 double (*new_mat44())[4] {
25420    return (double (*)[4]) malloc(16*sizeof(double));
25421 }
25422 void free_mat44(double (*x)[4]) {
25423    free(x);
25424 }
25425 void mat44_set(double x[4][4], int i, int j, double v) {
25426    x[i][j] = v;
25427 }
25428 double mat44_get(double x[4][4], int i, int j) {
25429    return x[i][j];
25430 }
25431 %}
25432 </PRE>
25433 </DIV>
25434 <P> From Java, you could then write code like this:</P>
25435 <DIV class="code">
25436 <PRE>
25437 Image im = new Image();
25438 SWIGTYPE_p_a_4__double a = example.new_mat44();
25439 example.mat44_set(a,0,0,1.0);
25440 example.mat44_set(a,1,1,1.0);
25441 example.mat44_set(a,2,2,1.0);
25442 ...
25443 example.set_transform(im,a);
25444 example.free_mat44(a);
25445 </PRE>
25446 </DIV>
25447 <P> Admittedly, this is not the most elegant looking approach. However,
25448  it works and it wasn't too hard to implement. It is possible to improve
25449  on this using Java code, typemaps, and other customization features as
25450  covered in later sections, but sometimes helper functions are a quick
25451  and easy solution to difficult cases.</P>
25452 <H3><A name="class_extension"></A>21.7.2 Class extension with %extend</H3>
25453 <P> One of the more interesting features of SWIG is that it can extend
25454  structures and classes with new methods or constructors. Here is a
25455  simple example:</P>
25456 <DIV class="code">
25457 <PRE>
25458 %module example
25459 %{
25460 #include &quot;someheader.h&quot;
25461 %}
25462
25463 struct Vector {
25464    double x,y,z;
25465 };
25466
25467 %extend Vector {
25468    char *toString() {
25469        static char tmp[1024];
25470        sprintf(tmp,&quot;Vector(%g,%g,%g)&quot;, $self-&gt;x,$self-&gt;y,$self-&gt;z);
25471        return tmp;
25472    }
25473    Vector(double x, double y, double z) {
25474        Vector *v = (Vector *) malloc(sizeof(Vector));
25475        v-&gt;x = x;
25476        v-&gt;y = y;
25477        v-&gt;z = z;
25478        return v;
25479    }
25480 };
25481 </PRE>
25482 </DIV>
25483 <P> Now, in Java</P>
25484 <DIV class="code">
25485 <PRE>
25486 Vector v = new Vector(2,3,4);
25487 System.out.println(v);
25488 </PRE>
25489 </DIV>
25490 <P> will display</P>
25491 <DIV class="code">
25492 <PRE>
25493 Vector(2,3,4)
25494 </PRE>
25495 </DIV>
25496 <P> <TT>%extend</TT> works with both C and C++ code. It does not modify
25497  the underlying object in any way---the extensions only show up in the
25498  Java interface.</P>
25499 <H3><A name="exception_handling"></A>21.7.3 Exception handling with
25500  %exception and %javaexception</H3>
25501 <P> If a C or C++ function throws an error, you may want to convert that
25502  error into a Java exception. To do this, you can use the <TT>%exception</TT>
25503  directive. The <TT>%exception</TT> directive simply lets you rewrite
25504  part of the generated wrapper code to include an error check. It is
25505  detailed in full in the <A href="#exception">Exception handling with
25506  %exception</A> section.</P>
25507 <P> In C, a function often indicates an error by returning a status code
25508  (a negative number or a NULL pointer perhaps). Here is a simple example
25509  of how you might handle that:</P>
25510 <DIV class="code">
25511 <PRE>
25512 %exception malloc {
25513   $action
25514   if (!result) {
25515     jclass clazz = (*jenv)-&gt;FindClass(jenv, &quot;java/lang/OutOfMemoryError&quot;);
25516     (*jenv)-&gt;ThrowNew(jenv, clazz, &quot;Not enough memory&quot;);
25517     return $null;
25518   }
25519 }
25520 void *malloc(size_t nbytes);
25521 </PRE>
25522 </DIV>
25523 <P> In Java,</P>
25524 <DIV class="code">
25525 <PRE>
25526 SWIGTYPE_p_void a = example.malloc(2000000000);
25527 </PRE>
25528 </DIV>
25529 <P> will produce a familiar looking Java exception:</P>
25530 <DIV class="code">
25531 <PRE>
25532 Exception in thread &quot;main&quot; java.lang.OutOfMemoryError: Not enough memory
25533         at exampleJNI.malloc(Native Method)
25534         at example.malloc(example.java:16)
25535         at runme.main(runme.java:112)
25536 </PRE>
25537 </DIV>
25538 <P> If a library provides some kind of general error handling framework,
25539  you can also use that. For example:</P>
25540 <DIV class="code">
25541 <PRE>
25542 %exception malloc {
25543   $action
25544   if (err_occurred()) {
25545     jclass clazz = (*jenv)-&gt;FindClass(jenv, &quot;java/lang/OutOfMemoryError&quot;);
25546     (*jenv)-&gt;ThrowNew(jenv, clazz, &quot;Not enough memory&quot;);
25547     return $null;
25548   }
25549 }
25550 void *malloc(size_t nbytes);
25551 </PRE>
25552 </DIV>
25553 <P> If no declaration name is given to <TT>%exception</TT>, it is
25554  applied to all wrapper functions. The <TT>$action</TT> is a SWIG
25555  special variable and is replaced by the C/C++ function call being
25556  wrapped. The <TT>return $null;</TT> handles all native method return
25557  types, namely those that have a void return and those that do not. This
25558  is useful for typemaps that will be used in native method returning all
25559  return types. See the section on <A href="#special_variables">Java
25560  special variables</A> for further explanation.</P>
25561 <P> C++ exceptions are also easy to handle. We can catch the C++
25562  exception and rethrow it as a Java exception like this:</P>
25563 <DIV class="code">
25564 <PRE>
25565 %exception getitem {
25566   try {
25567      $action
25568   } catch (std::out_of_range &amp;e) {
25569     jclass clazz = jenv-&gt;FindClass(&quot;java/lang/Exception&quot;);
25570     jenv-&gt;ThrowNew(clazz, &quot;Range error&quot;);
25571     return $null;
25572    }
25573 }
25574
25575 class FooClass {
25576 public:
25577      FooClass *getitem(int index);      // Might throw std::out_of_range exception
25578      ...
25579 };
25580 </PRE>
25581 </DIV>
25582 <P> In the example above, <TT>java.lang.Exception</TT> is a checked
25583  exception class and so ought to be declared in the throws clause of <TT>
25584 getitem</TT>. Classes can be specified for adding to the throws clause
25585  using <TT>%javaexception(classes)</TT> instead of <TT>%exception</TT>,
25586  where <TT>classes</TT> is a string containing one or more comma
25587  separated Java classes. The <TT>%clearjavaexception</TT> feature is the
25588  equivalent to <TT>%clearexception</TT> and clears previously declared
25589  exception handlers. The <TT>%nojavaexception</TT> feature is the
25590  equivalent to <TT>%noexception</TT> and disables the exception handler.
25591  See <A href="#Customization_clearing_features">Clearing features</A>
25592  for the difference on disabling and clearing features.</P>
25593 <DIV class="code">
25594 <PRE>
25595 %javaexception(&quot;java.lang.Exception&quot;) getitem {
25596   try {
25597      $action
25598   } catch (std::out_of_range &amp;e) {
25599     jclass clazz = jenv-&gt;FindClass(&quot;java/lang/Exception&quot;);
25600     jenv-&gt;ThrowNew(clazz, &quot;Range error&quot;);
25601     return $null;
25602    }
25603 }
25604
25605 class FooClass {
25606 public:
25607      FooClass *getitem(int index);      // Might throw std::out_of_range exception
25608      ...
25609 };
25610 </PRE>
25611 </DIV>
25612 <P> The generated proxy method now generates a throws clause containing <TT>
25613 java.lang.Exception</TT>:</P>
25614 <DIV class="code">
25615 <PRE>
25616 public class FooClass {
25617   ...
25618   public FooClass getitem(int index) throws java.lang.Exception { ... }
25619   ...
25620 }
25621 </PRE>
25622 </DIV>
25623 <P> The examples above first use the C JNI calling syntax then the C++
25624  JNI calling syntax. The C++ calling syntax will not compile as C and
25625  also vice versa. It is however possible to write JNI calls which will
25626  compile under both C and C++ and is covered in the <A href="#typemaps_for_c_and_c++">
25627 Typemaps for both C and C++ compilation</A> section.</P>
25628 <P> The language-independent <TT>exception.i</TT> library file can also
25629  be used to raise exceptions. See the <A href="#Library">SWIG Library</A>
25630  chapter. The typemap example <A href="#exception_typemap">Handling C++
25631  exception specifications as Java exceptions</A> provides further
25632  exception handling capabilities.</P>
25633 <H3><A name="method_access"></A>21.7.4 Method access with
25634  %javamethodmodifiers</H3>
25635 <P> A Java feature called <TT>%javamethodmodifiers</TT> can be used to
25636  change the method modifiers from the default <TT>public</TT>. It
25637  applies to both module class methods and proxy class methods. For
25638  example:</P>
25639 <DIV class="code">
25640 <PRE>
25641 %javamethodmodifiers protect_me() &quot;protected&quot;;
25642 void protect_me();
25643 </PRE>
25644 </DIV>
25645 <P> Will produce the method in the module class with protected access.</P>
25646 <DIV class="code">
25647 <PRE>
25648 protected static void protect_me() {
25649   exampleJNI.protect_me();
25650 }
25651 </PRE>
25652 </DIV>
25653 <H2><A name="tips_techniques"></A>21.8 Tips and techniques</H2>
25654 <P> Although SWIG is largely automatic, there are certain types of
25655  wrapping problems that require additional user input. Examples include
25656  dealing with output parameters, strings and arrays. This chapter
25657  discusses the common techniques for solving these problems.</P>
25658 <H3><A name="input_output_parameters"></A>21.8.1 Input and output
25659  parameters using primitive pointers and references</H3>
25660 <P> A common problem in some C programs is handling parameters passed as
25661  simple pointers or references. For example:</P>
25662 <DIV class="code">
25663 <PRE>
25664 void add(int x, int y, int *result) {
25665    *result = x + y;
25666 }
25667 </PRE>
25668 </DIV>
25669 <P> or perhaps</P>
25670 <DIV class="code">
25671 <PRE>
25672 int sub(int *x, int *y) {
25673    return *x-*y;
25674 }
25675 </PRE>
25676 </DIV>
25677 <P> The <TT>typemaps.i</TT> library file will help in these situations.
25678  For example:</P>
25679 <DIV class="code">
25680 <PRE>
25681 %module example
25682 %include &quot;typemaps.i&quot;
25683
25684 void add(int, int, int *OUTPUT);
25685 int  sub(int *INPUT, int *INPUT);
25686 </PRE>
25687 </DIV>
25688 <P> In Java, this allows you to pass simple values. For example:</P>
25689 <DIV class="code">
25690 <PRE>
25691 int result = example.sub(7,4);
25692 System.out.println(&quot;7 - 4 = &quot; + result);
25693 int[] sum = {0};
25694 example.add(3,4,sum);
25695 System.out.println(&quot;3 + 4 = &quot; + sum[0]);
25696 </PRE>
25697 </DIV>
25698 <P> Which will display:</P>
25699 <DIV class="code">
25700 <PRE>
25701 7 - 4 = 3
25702 3 + 4 = 7
25703 </PRE>
25704 </DIV>
25705 <P> Notice how the <TT>INPUT</TT> parameters allow integer values to be
25706  passed instead of pointers and how the <TT>OUTPUT</TT> parameter will
25707  return the result in the first element of the integer array.</P>
25708 <P> If you don't want to use the names <TT>INPUT</TT> or <TT>OUTPUT</TT>
25709 , use the <TT>%apply</TT> directive. For example:</P>
25710 <DIV class="code">
25711 <PRE>
25712 %module example
25713 %include &quot;typemaps.i&quot;
25714
25715 %apply int *OUTPUT { int *result };
25716 %apply int *INPUT  { int *x, int *y};
25717
25718 void add(int x, int y, int *result);
25719 int  sub(int *x, int *y);
25720 </PRE>
25721 </DIV>
25722 <P> If a function mutates one of its parameters like this,</P>
25723 <DIV class="code">
25724 <PRE>
25725 void negate(int *x) {
25726    *x = -(*x);
25727 }
25728 </PRE>
25729 </DIV>
25730 <P> you can use <TT>INOUT</TT> like this:</P>
25731 <DIV class="code">
25732 <PRE>
25733 %include &quot;typemaps.i&quot;
25734 ...
25735 void negate(int *INOUT);
25736 </PRE>
25737 </DIV>
25738 <P> In Java, the input parameter is the first element in a 1 element
25739  array and is replaced by the output of the function. For example:</P>
25740 <DIV class="code">
25741 <PRE>
25742 int[] neg = {3};
25743 example.negate(neg);
25744 System.out.println(&quot;Negative of 3 = &quot; + neg[0]);
25745 </PRE>
25746 </DIV>
25747 <P> And no prizes for guessing the output:</P>
25748 <DIV class="code">
25749 <PRE>
25750 Negative of 3 = -3
25751 </PRE>
25752 </DIV>
25753 <P> These typemaps can also be applied to C++ references. The above
25754  examples would work the same if they had been defined using references
25755  instead of pointers. For example, the Java code to use the <TT>negate</TT>
25756  function would be the same if it were defined either as it is above:</P>
25757 <DIV class="code">
25758 <PRE>
25759 void negate(int *INOUT);
25760 </PRE>
25761 </DIV>
25762 <P> or using a reference:</P>
25763 <DIV class="code">
25764 <PRE>
25765 void negate(int &amp;INOUT);
25766 </PRE>
25767 </DIV>
25768 <P> Note: Since most Java primitive types are immutable and are passed
25769  by value, it is not possible to perform in-place modification of a type
25770  passed as a parameter.</P>
25771 <P> Be aware that the primary purpose of the <TT>typemaps.i</TT> file is
25772  to support primitive datatypes. Writing a function like this</P>
25773 <DIV class="code">
25774 <PRE>
25775 void foo(Bar *OUTPUT);
25776 </PRE>
25777 </DIV>
25778 <P> will not have the intended effect since <TT>typemaps.i</TT> does not
25779  define an OUTPUT rule for <TT>Bar</TT>.</P>
25780 <H3><A name="simple_pointers"></A>21.8.2 Simple pointers</H3>
25781 <P> If you must work with simple pointers such as <TT>int *</TT> or <TT>
25782 double *</TT> another approach to using <TT>typemaps.i</TT> is to use
25783  the <TT>cpointer.i</TT> pointer library file. For example:</P>
25784 <DIV class="code">
25785 <PRE>
25786 %module example
25787 %include &quot;cpointer.i&quot;
25788
25789 %inline %{
25790 extern void add(int x, int y, int *result);
25791 %}
25792
25793 %pointer_functions(int, intp);
25794 </PRE>
25795 </DIV>
25796 <P> The <TT>%pointer_functions(type,name)</TT> macro generates five
25797  helper functions that can be used to create, destroy, copy, assign, and
25798  dereference a pointer. In this case, the functions are as follows:</P>
25799 <DIV class="code">
25800 <PRE>
25801 int  *new_intp();
25802 int  *copy_intp(int *x);
25803 void  delete_intp(int *x);
25804 void  intp_assign(int *x, int value);
25805 int   intp_value(int *x);
25806 </PRE>
25807 </DIV>
25808 <P> In Java, you would use the functions like this:</P>
25809 <DIV class="code">
25810 <PRE>
25811 SWIGTYPE_p_int intPtr = example.new_intp();
25812 example.add(3,4,intPtr);
25813 int result = example.intp_value(intPtr);
25814 System.out.println(&quot;3 + 4 = &quot; + result);
25815 </PRE>
25816 </DIV>
25817 <P> If you replace <TT>%pointer_functions(int,intp)</TT> by <TT>
25818 %pointer_class(int,intp)</TT>, the interface is more class-like.</P>
25819 <DIV class="code">
25820 <PRE>
25821 intp intPtr = new intp();
25822 example.add(3,4,intPtr.cast());
25823 int result = intPtr.value();
25824 System.out.println(&quot;3 + 4 = &quot; + result);
25825 </PRE>
25826 </DIV>
25827 <P> See the <A href="#Library">SWIG Library</A> chapter for further
25828  details.</P>
25829 <H3><A name="c_arrays"></A>21.8.3 Wrapping C arrays with Java arrays</H3>
25830 <P> SWIG can wrap arrays in a more natural Java manner than the default
25831  by using the <TT>arrays_java.i</TT> library file. Let's consider an
25832  example:</P>
25833 <DIV class="code">
25834 <PRE>
25835 %include &quot;arrays_java.i&quot;;
25836 int array[4];
25837 void populate(int x[]) {
25838     int i;
25839     for (i=0; i&lt;4; i++)
25840         x[i] = 100 + i;
25841 }
25842 </PRE>
25843 </DIV>
25844 <P> These one dimensional arrays can then be used as if they were Java
25845  arrays:</P>
25846 <DIV class="code">
25847 <PRE>
25848 int[] array = new int[4];
25849 example.populate(array);
25850
25851 System.out.print(&quot;array: &quot;);
25852 for (int i=0; i&lt;array.length; i++)
25853     System.out.print(array[i] + &quot; &quot;);
25854
25855 example.setArray(array);
25856
25857 int[] global_array = example.getArray();
25858
25859 System.out.print(&quot;\nglobal_array: &quot;);
25860 for (int i=0; i&lt;array.length; i++)
25861     System.out.print(global_array[i] + &quot; &quot;);
25862 </PRE>
25863 </DIV>
25864 <P> Java arrays are always passed by reference, so any changes a
25865  function makes to the array will be seen by the calling function. Here
25866  is the output after running this code:</P>
25867 <DIV class="code">
25868 <PRE>
25869 array: 100 101 102 103
25870 global_array: 100 101 102 103
25871 </PRE>
25872 </DIV>
25873 <P> Note that for assigning array variables the length of the C variable
25874  is used, so it is possible to use a Java array that is bigger than the
25875  C code will cope with. Only the number of elements in the C array will
25876  be used. However, if the Java array is not large enough then you are
25877  likely to get a segmentation fault or access violation, just like you
25878  would in C. When arrays are used in functions like <TT>populate</TT>,
25879  the size of the C array passed to the function is determined by the
25880  size of the Java array.</P>
25881 <P> Please be aware that the typemaps in this library are not efficient
25882  as all the elements are copied from the Java array to a C array
25883  whenever the array is passed to and from JNI code. There is an
25884  alternative approach using the SWIG array library and this is covered
25885  in the next section.</P>
25886 <H3><A name="unbounded_c_arrays"></A>21.8.4 Unbounded C Arrays</H3>
25887 <P> Sometimes a C function expects an array to be passed as a pointer.
25888  For example,</P>
25889 <DIV class="code">
25890 <PRE>
25891 int sumitems(int *first, int nitems) {
25892     int i, sum = 0;
25893     for (i = 0; i &lt; nitems; i++) {
25894         sum += first[i];
25895     }
25896     return sum;
25897 }
25898 </PRE>
25899 </DIV>
25900 <P> One of the ways to wrap this is to apply the Java array typemaps
25901  that come in the <TT>arrays_java.i</TT> library file:</P>
25902 <DIV class="code">
25903 <PRE>
25904 %include &quot;arrays_java.i&quot;
25905 %apply int[] {int *};
25906 </PRE>
25907 </DIV>
25908 <P> The <TT>ANY</TT> size will ensure the typemap is applied to arrays
25909  of all sizes. You could narrow the typemap matching rules by specifying
25910  a particular array size. Now you can use a pure Java array and pass it
25911  to the C code:</P>
25912 <DIV class="code">
25913 <PRE>
25914 int[] array = new int[10000000];          // Array of 10-million integers
25915 for (int i=0; i&lt;array.length; i++) {      // Set some values
25916   array[i] = i;
25917 }
25918 int sum = example.sumitems(array,10000);
25919 System.out.println(&quot;Sum = &quot; + sum);
25920 </PRE>
25921 </DIV>
25922 <P> and the sum would be displayed:</P>
25923 <DIV class="code">
25924 <PRE>
25925 Sum = 49995000
25926 </PRE>
25927 </DIV>
25928 <P> This approach is probably the most natural way to use arrays.
25929  However, it suffers from performance problems when using large arrays
25930  as a lot of copying of the elements occurs in transferring the array
25931  from the Java world to the C++ world. An alternative approach to using
25932  Java arrays for C arrays is to use an alternative SWIG library file <TT>
25933 carrays.i</TT>. This approach can be more efficient for large arrays as
25934  the array is accessed one element at a time. For example:</P>
25935 <DIV class="code">
25936 <PRE>
25937 %include &quot;carrays.i&quot;
25938 %array_functions(int, intArray);
25939 </PRE>
25940 </DIV>
25941 <P> The <TT>%array_functions(type,name)</TT> macro generates four helper
25942  functions that can be used to create and destroy arrays and operate on
25943  elements. In this case, the functions are as follows:</P>
25944 <DIV class="code">
25945 <PRE>
25946 int *new_intArray(int nelements);
25947 void delete_intArray(int *x);
25948 int intArray_getitem(int *x, int index);
25949 void intArray_setitem(int *x, int index, int value);
25950 </PRE>
25951 </DIV>
25952 <P> In Java, you would use the functions like this:</P>
25953 <DIV class="code">
25954 <PRE>
25955 SWIGTYPE_p_int array = example.new_intArray(10000000);  // Array of 10-million integers
25956 for (int i=0; i&lt;10000; i++) {                           // Set some values
25957     example.intArray_setitem(array,i,i);
25958 }
25959 int sum = example.sumitems(array,10000);
25960 System.out.println(&quot;Sum = &quot; + sum);
25961 </PRE>
25962 </DIV>
25963 <P> If you replace <TT>%array_functions(int,intp)</TT> by <TT>
25964 %array_class(int,intp)</TT>, the interface is more class-like and a
25965  couple more helper functions are available for casting between the
25966  array and the type wrapper class.</P>
25967 <DIV class="code">
25968 <PRE>
25969 %include &quot;carrays.i&quot;
25970 %array_class(int, intArray);
25971 </PRE>
25972 </DIV>
25973 <P> The <TT>%array_class(type, name)</TT> macro creates wrappers for an
25974  unbounded array object that can be passed around as a simple pointer
25975  like <TT>int *</TT> or <TT>double *</TT>. For instance, you will be
25976  able to do this in Java:</P>
25977 <DIV class="code">
25978 <PRE>
25979 intArray array = new intArray(10000000);  // Array of 10-million integers
25980 for (int i=0; i&lt;10000; i++) {             // Set some values
25981     array.setitem(i,i);
25982 }
25983 int sum = example.sumitems(array.cast(),10000);
25984 System.out.println(&quot;Sum = &quot; + sum);
25985 </PRE>
25986 </DIV>
25987 <P> The array &quot;object&quot; created by <TT>%array_class()</TT> does not
25988  encapsulate pointers inside a special array object. In fact, there is
25989  no bounds checking or safety of any kind (just like in C). Because of
25990  this, the arrays created by this library are extremely low-level
25991  indeed. You can't iterate over them nor can you even query their
25992  length. In fact, any valid memory address can be accessed if you want
25993  (negative indices, indices beyond the end of the array, etc.). Needless
25994  to say, this approach is not going to suit all applications. On the
25995  other hand, this low-level approach is extremely efficient and well
25996  suited for applications in which you need to create buffers, package
25997  binary data, etc.</P>
25998 <H3><A name="java_heap_allocations"></A>21.8.5 Overriding new and delete
25999  to allocate from Java heap</H3>
26000 <P> Unlike some languages supported by SWIG, Java has a true garbage
26001  collection subsystem. Other languages will free SWIG wrapped objects
26002  when their reference count reaches zero. Java only schedules these
26003  objects for finalization, which may not occur for some time. Because
26004  SWIG objects are allocated on the C heap, Java users may find the JVM
26005  memory use quickly exceeds the assigned limits, as memory fills with
26006  unfinalized proxy objects. Forcing garbage collection is clearly an
26007  undesirable solution.</P>
26008 <P> An elegant fix for C++ users is to override new and delete using the
26009  following code (here shown included in a SWIG interface file)</P>
26010 <DIV class="code">
26011 <PRE>
26012 /* File: java_heap.i */
26013 %module test
26014 %{
26015 #include &lt;stdexcept&gt;
26016 #include &quot;jni.h&quot;
26017
26018 /**
26019  *  A stash area embedded in each allocation to hold java handles
26020  */
26021 struct Jalloc {
26022   jbyteArray jba;
26023   jobject ref;
26024 };
26025
26026 static JavaVM *cached_jvm = 0;
26027
26028 JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *jvm, void *reserved) {
26029   cached_jvm = jvm;
26030   return JNI_VERSION_1_2;
26031 }
26032
26033 static JNIEnv * JNU_GetEnv() {
26034   JNIEnv *env;
26035   jint rc = cached_jvm-&gt;GetEnv((void **)&amp;env, JNI_VERSION_1_2);
26036   if (rc == JNI_EDETACHED)
26037     throw std::runtime_error(&quot;current thread not attached&quot;);
26038   if (rc == JNI_EVERSION)
26039     throw std::runtime_error(&quot;jni version not supported&quot;);
26040   return env;
26041 }
26042
26043 void * operator new(size_t t) {
26044   if (cached_jvm != 0) {
26045     JNIEnv *env = JNU_GetEnv();
26046     jbyteArray jba = env-&gt;NewByteArray((int) t + sizeof(Jalloc));
26047     if (env-&gt;ExceptionOccurred())
26048       throw bad_alloc();
26049     void *jbuffer = static_cast&lt;void *&gt;(env-&gt;GetByteArrayElements(jba, 0));
26050     if (env-&gt;ExceptionOccurred())
26051       throw bad_alloc();
26052     Jalloc *pJalloc = static_cast&lt;Jalloc *&gt;(jbuffer);
26053     pJalloc-&gt;jba = jba;
26054     /* Assign a global reference so byte array will persist until delete'ed */
26055     pJalloc-&gt;ref = env-&gt;NewGlobalRef(jba);
26056     if (env-&gt;ExceptionOccurred())
26057       throw bad_alloc();
26058     return static_cast&lt;void *&gt;(static_cast&lt;char *&gt;(jbuffer) + sizeof(Jalloc));
26059   }
26060   else { /* JNI_OnLoad not called, use malloc and mark as special */
26061     Jalloc *pJalloc = static_cast&lt;Jalloc *&gt;(malloc((int) t + sizeof(Jalloc)));
26062     if (!pJalloc)
26063       throw bad_alloc();
26064     pJalloc-&gt;ref = 0;
26065     return static_cast&lt;void *&gt;(
26066         static_cast&lt;char *&gt;(static_cast&lt;void *&gt;(pJalloc)) + sizeof(Jalloc));
26067   }
26068 }
26069
26070 void operator delete(void *v) {
26071   if (v != 0) {
26072     void *buffer = static_cast&lt;void *&gt;( static_cast&lt;char *&gt;(v) - sizeof(Jalloc));
26073     Jalloc *pJalloc = static_cast&lt;Jalloc *&gt;(buffer);
26074     if (pJalloc-&gt;ref) {
26075       JNIEnv *env = JNU_GetEnv();
26076       env-&gt;DeleteGlobalRef(pJalloc-&gt;ref);
26077       env-&gt;ReleaseByteArrayElements(pJalloc-&gt;jba, static_cast&lt;jbyte *&gt;(buffer), 0);
26078     }
26079     else {
26080       free(buffer);
26081     }
26082   }
26083 }
26084 %}
26085 ...
26086 </PRE>
26087 </DIV>
26088 <P> This code caches the Java environment during initialization, and
26089  when new is called, a Java ByteArray is allocated to provide the SWIG
26090  objects with space in the Java heap. This has the combined effect of
26091  re-asserting the Java virtual machine's limit on memory allocation, and
26092  puts additional pressure on the garbage collection system to run more
26093  frequently. This code is made slightly more complicated because
26094  allowances must be made if new is called before the JNI_OnLoad is
26095  executed. This can happen during static class initialization, for
26096  example.</P>
26097 <P> Unfortunately, because most Java implementations call malloc and
26098  free, this solution will not work for C wrapped structures. However,
26099  you are free to make functions that allocate and free memory from the
26100  Java heap using this model and use these functions in place of malloc
26101  and free in your own code.</P>
26102 <H2><A name="java_typemaps"></A>21.9 Java typemaps</H2>
26103 <P> This section describes how you can modify SWIG's default wrapping
26104  behavior for various C/C++ datatypes using the <TT>%typemap</TT>
26105  directive. You are advised to be familiar with the the material in the
26106  &quot;<A href="#Typemaps">Typemaps</A>&quot; chapter. While not absolutely
26107  essential knowledge, this section assumes some familiarity with the
26108  Java Native Interface (JNI). JNI documentation can be consulted either
26109  online at <A href="http://java.sun.com">Sun's Java web site</A> or from
26110  a good JNI book. The following two books are recommended:</P>
26111 <UL>
26112 <LI> Title: 'Essential JNI: Java Native Interface.' Author: Rob Gordon.
26113  Publisher: Prentice Hall. ISBN: 0-13-679895-0.</LI>
26114 <LI> Title: 'The Java Native Interface: Programmer's Guide and
26115  Specification.' Author: Sheng Liang. Publisher: Addison-Wesley. ISBN:
26116  0-201-32577-2. Also available <A href="http://java.sun.com/docs/books/jni">
26117 online</A> at the Sun Developer Network.</LI>
26118 </UL>
26119 <P> Before proceeding, it should be stressed that typemaps are not a
26120  required part of using SWIG---the default wrapping behavior is enough
26121  in most cases. Typemaps are only used if you want to change some aspect
26122  of the generated code.</P>
26123 <H3><A name="default_primitive_type_mappings"></A>21.9.1 Default
26124  primitive type mappings</H3>
26125 <P> The following table lists the default type mapping from Java to
26126  C/C++.</P>
26127 <TABLE BORDER summary="Default primitive type mappings">
26128 <TR><TD><B>C/C++ type</B></TD><TD><B>Java type</B></TD><TD><B>JNI type</B>
26129 </TD></TR>
26130 <TR><TD>bool
26131 <BR> const bool &amp;</TD><TD>boolean</TD><TD>jboolean</TD></TR>
26132 <TR><TD>char
26133 <BR>const char &amp;</TD><TD>char</TD><TD>jchar</TD></TR>
26134 <TR><TD>signed char
26135 <BR>const signed char &amp;</TD><TD>byte</TD><TD>jbyte</TD></TR>
26136 <TR><TD>unsigned char
26137 <BR>const unsigned char &amp;</TD><TD>short</TD><TD>jshort</TD></TR>
26138 <TR><TD>short
26139 <BR>const short &amp;</TD><TD>short</TD><TD>jshort</TD></TR>
26140 <TR><TD>unsigned short
26141 <BR> const unsigned short &amp;</TD><TD>int</TD><TD>jint</TD></TR>
26142 <TR><TD>int
26143 <BR> const int &amp;</TD><TD>int</TD><TD>jint</TD></TR>
26144 <TR><TD>unsigned int
26145 <BR> const unsigned int &amp;</TD><TD>long</TD><TD>jlong</TD></TR>
26146 <TR><TD>long
26147 <BR>const long &amp;</TD><TD>int</TD><TD>jint</TD></TR>
26148 <TR><TD>unsigned long
26149 <BR>const unsigned long &amp;</TD><TD>long</TD><TD>jlong</TD></TR>
26150 <TR><TD>long long
26151 <BR> const long long &amp;</TD><TD>long</TD><TD>jlong</TD></TR>
26152 <TR><TD>unsigned long long
26153 <BR>const unsigned long long &amp;</TD><TD>java.math.BigInteger</TD><TD>
26154 jobject</TD></TR>
26155 <TR><TD>float
26156 <BR>const float &amp;</TD><TD>float</TD><TD>jfloat</TD></TR>
26157 <TR><TD>double
26158 <BR> const double &amp;</TD><TD>double</TD><TD>jdouble</TD></TR>
26159 <TR><TD>char *
26160 <BR>char []</TD><TD>String</TD><TD>jstring</TD></TR>
26161 </TABLE>
26162 <P> Note that SWIG wraps the C <TT>char</TT> type as a character.
26163  Pointers and arrays of this type are wrapped as strings. The <TT>signed
26164  char</TT> type can be used if you want to treat <TT>char</TT> as a
26165  signed number rather than a character. Also note that all const
26166  references to primitive types are treated as if they are passed by
26167  value.</P>
26168 <P> Given the following C function:</P>
26169 <DIV class="code">
26170 <PRE>
26171 void func(unsigned short a, char *b, const long &amp;c, unsigned long long d);
26172 </PRE>
26173 </DIV>
26174 <P> The module class method would be:</P>
26175 <DIV class="code">
26176 <PRE>
26177 public static void func(int a, String b, int c, java.math.BigInteger d) {...}
26178 </PRE>
26179 </DIV>
26180 <P> The intermediary JNI class would use the same types:</P>
26181 <DIV class="code">
26182 <PRE>
26183 public final static native void func(int jarg1, String jarg2, int jarg3,
26184                                      java.math.BigInteger jarg4);
26185 </PRE>
26186 </DIV>
26187 <P> and the JNI function would look like this:</P>
26188 <DIV class="code">
26189 <PRE>
26190 SWIGEXPORT void JNICALL Java_exampleJNI_func(JNIEnv *jenv, jclass jcls,
26191                 jint jarg1, jstring jarg2, jint jarg3, jobject jarg4) {...}
26192 </PRE>
26193 </DIV>
26194 <P> The mappings for C <TT>int</TT> and C <TT>long</TT> are appropriate
26195  for 32 bit applications which are used in the 32 bit JVMs. There is no
26196  perfect mapping between Java and C as Java doesn't support all the
26197  unsigned C data types. However, the mappings allow the full range of
26198  values for each C type from Java.</P>
26199 <H3><A name="Java_default_non_primitive_typemaps"></A>21.9.2 Default
26200  typemaps for non-primitive types</H3>
26201 <P> The previous section covered the primitive type mappings.
26202  Non-primitive types such as classes and structs are mapped using
26203  pointers on the C/C++ side and storing the pointer into a Java <TT>long</TT>
26204  variable which is held by the proxy class or type wrapper class. This
26205  applies whether the type is marshalled as a pointer, by reference or by
26206  value. It also applies for any unknown/incomplete types which use type
26207  wrapper classes.</P>
26208 <P> So in summary, the C/C++ pointer to non-primitive types is cast into
26209  the 64 bit Java <TT>long</TT> type and therefore the JNI type is a <TT>
26210 jlong</TT>. The Java type is either the proxy class or type wrapper
26211  class.</P>
26212 <H3><A name="jvm64"></A>21.9.3 Sixty four bit JVMs</H3>
26213 <P> If you are using a 64 bit JVM you may have to override the C long,
26214  but probably not C int default mappings. Mappings will be system
26215  dependent, for example long will need remapping on Unix LP64 systems
26216  (long, pointer 64 bits, int 32 bits), but not on Microsoft 64 bit
26217  Windows which will be using a P64 IL32 (pointer 64 bits and int, long
26218  32 bits) model. This may be automated in a future version of SWIG. Note
26219  that the Java write once run anywhere philosophy holds true for all
26220  pure Java code when moving to a 64 bit JVM. Unfortunately it won't of
26221  course hold true for JNI code.</P>
26222 <H3><A name="what_is_typemap"></A>21.9.4 What is a typemap?</H3>
26223 <P> A typemap is nothing more than a code generation rule that is
26224  attached to a specific C datatype. For example, to convert integers
26225  from Java to C, you might define a typemap like this:</P>
26226 <DIV class="code">
26227 <PRE>
26228 %module example
26229
26230 %typemap(in) int {
26231   $1 = $input;
26232   printf(&quot;Received an integer : %d\n&quot;,  $1);
26233 }
26234 %inline %{
26235 extern int fact(int nonnegative);
26236 %}
26237 </PRE>
26238 </DIV>
26239 <P> Typemaps are always associated with some specific aspect of code
26240  generation. In this case, the &quot;in&quot; method refers to the conversion of
26241  input arguments to C/C++. The datatype <TT>int</TT> is the datatype to
26242  which the typemap will be applied. The supplied C code is used to
26243  convert values. In this code a number of special variables prefaced by
26244  a <TT>$</TT> are used. The <TT>$1</TT> variable is a placeholder for a
26245  local variable of type <TT>int</TT>. The <TT>$input</TT> variable
26246  contains the Java data, the JNI <TT>jint</TT> in this case.</P>
26247 <P> When this example is compiled into a Java module, it can be used as
26248  follows:</P>
26249 <DIV class="code">
26250 <PRE>
26251 System.out.println(example.fact(6));
26252 </PRE>
26253 </DIV>
26254 <P> and the output will be:</P>
26255 <DIV class="code">
26256 <PRE>
26257 Received an integer : 6
26258 720
26259 </PRE>
26260 </DIV>
26261 <P> In this example, the typemap is applied to all occurrences of the <TT>
26262 int</TT> datatype. You can refine this by supplying an optional
26263  parameter name. For example:</P>
26264 <DIV class="code">
26265 <PRE>
26266 %module example
26267
26268 %typemap(in) int nonnegative {
26269   $1 = $input;
26270   printf(&quot;Received an integer : %d\n&quot;,  $1);
26271 }
26272
26273 %inline %{
26274 extern int fact(int nonnegative);
26275 %}
26276 </PRE>
26277 </DIV>
26278 <P> In this case, the typemap code is only attached to arguments that
26279  exactly match <TT>int nonnegative</TT>.</P>
26280 <P> The application of a typemap to specific datatypes and argument
26281  names involves more than simple text-matching--typemaps are fully
26282  integrated into the SWIG C++ type-system. When you define a typemap for
26283  <TT>int</TT>, that typemap applies to <TT>int</TT> and qualified
26284  variations such as <TT>const int</TT>. In addition, the typemap system
26285  follows <TT>typedef</TT> declarations. For example:</P>
26286 <DIV class="code">
26287 <PRE>
26288 %typemap(in) int nonnegative {
26289   $1 = $input;
26290   printf(&quot;Received an integer : %d\n&quot;,  $1);
26291 }
26292 %inline %{
26293 typedef int Integer;
26294 extern int fact(Integer nonnegative);    // Above typemap is applied
26295 %}
26296 </PRE>
26297 </DIV>
26298 <P> However, the matching of <TT>typedef</TT> only occurs in one
26299  direction. If you defined a typemap for <TT>Integer</TT>, it is not
26300  applied to arguments of type <TT>int</TT>.</P>
26301 <P> Typemaps can also be defined for groups of consecutive arguments.
26302  For example:</P>
26303 <DIV class="code">
26304 <PRE>
26305 %typemap(in) (char *str, int len) {
26306 ...
26307 };
26308
26309 int count(char c, char *str, int len);
26310 </PRE>
26311 </DIV>
26312 <P> When a multi-argument typemap is defined, the arguments are always
26313  handled as a single Java parameter. This allows the function to be used
26314  like this (notice how the length parameter is omitted):</P>
26315 <DIV class="code">
26316 <PRE>
26317 int c = example.count('e',&quot;Hello World&quot;);
26318 </PRE>
26319 </DIV>
26320 <H3><A name="typemaps_c_to_java_types"></A>21.9.5 Typemaps for mapping
26321  C/C++ types to Java types</H3>
26322 <P> The typemaps available to the Java module include the common
26323  typemaps listed in the main typemaps section. There are a number of
26324  additional typemaps which are necessary for using SWIG with Java. The
26325  most important of these implement the mapping of C/C++ types to Java
26326  types:</P>
26327 <BR> &nbsp;
26328 <TABLE BORDER summary="Typemap mappings for C/C++ types to Java types">
26329 <TR><TD><B>Typemap</B></TD><TD><B>Description</B></TD></TR>
26330 <TR><TD>jni</TD><TD>JNI C types. These provide the default mapping of
26331  types from C/C++ to JNI for use in the JNI (C/C++) code.</TD></TR>
26332 <TR><TD>jtype</TD><TD>Java intermediary types. These provide the default
26333  mapping of types from C/C++ to Java for use in the native functions in
26334  the intermediary JNI class. The type must be the equivalent Java type
26335  for the JNI C type specified in the &quot;jni&quot; typemap.</TD></TR>
26336 <TR><TD>jstype</TD><TD>Java types. These provide the default mapping of
26337  types from C/C++ to Java for use in the Java module class, proxy
26338  classes and type wrapper classes.</TD></TR>
26339 <TR><TD>javain</TD><TD>Conversion from jstype to jtype. These are Java
26340  code typemaps which transform the type used in the Java module class,
26341  proxy classes and type wrapper classes (as specified in the &quot;jstype&quot;
26342  typemap) to the type used in the Java intermediary JNI class (as
26343  specified in the &quot;jtype&quot; typemap). In other words the typemap provides
26344  the conversion to the native method call parameter types.</TD></TR>
26345 <TR><TD>javaout</TD><TD>Conversion from jtype to jstype. These are Java
26346  code typemaps which transform the type used in the Java intermediary
26347  JNI class (as specified in the &quot;jtype&quot; typemap) to the Java type used
26348  in the Java module class, proxy classes and type wrapper classes (as
26349  specified in the &quot;jstype&quot; typemap). In other words the typemap provides
26350  the conversion from the native method call return type.</TD></TR>
26351 <TR><TD>javadirectorin</TD><TD>Conversion from jtype to jstype for
26352  director methods. These are Java code typemaps which transform the type
26353  used in the Java intermediary JNI class (as specified in the &quot;jtype&quot;
26354  typemap) to the Java type used in the Java module class, proxy classes
26355  and type wrapper classes (as specified in the &quot;jstype&quot; typemap). This
26356  typemap provides the conversion for the parameters in the director
26357  methods when calling up from C++ to Java. See <A href="#java_directors_typemaps">
26358 Director typemaps</A>.</TD></TR>
26359 <TR><TD>javadirectorout</TD><TD>Conversion from jstype to jtype for
26360  director methods. These are Java code typemaps which transform the type
26361  used in the Java module class, proxy classes and type wrapper classes
26362  (as specified in the &quot;jstype&quot; typemap) to the type used in the Java
26363  intermediary JNI class (as specified in the &quot;jtype&quot; typemap). This
26364  typemap provides the conversion for the return type in the director
26365  methods when returning from the C++ to Java upcall. See <A href="#java_directors_typemaps">
26366 Director typemaps</A>.</TD></TR>
26367 <TR><TD>directorin</TD><TD>Conversion from C++ type to jni type for
26368  director methods. These are C++ typemaps which convert the parameters
26369  used in the C++ director method to the appropriate JNI intermediary
26370  type. The conversion is done in JNI code prior to calling the Java
26371  function from the JNI code. See <A href="#java_directors_typemaps">
26372 Director typemaps</A>.</TD></TR>
26373 <TR><TD>directorout</TD><TD>Conversion from jni type to C++ type for
26374  director methods. These are C++ typemaps which convert the JNI return
26375  type used in the C++ director method to the appropriate C++ return
26376  type. The conversion is done in JNI code after calling the Java
26377  function from the JNI code. See <A href="#java_directors_typemaps">
26378 Director typemaps</A>.</TD></TR>
26379 </TABLE>
26380 <P> If you are writing your own typemaps to handle a particular type,
26381  you will normally have to write a collection of them. The default
26382  typemaps are in &quot;<TT>java.swg</TT>&quot; and so might be a good place for
26383  finding typemaps to base any new ones on.</P>
26384 <P> The &quot;jni&quot;, &quot;jtype&quot; and &quot;jstype&quot; typemaps are usually defined
26385  together to handle the Java to C/C++ type mapping. An &quot;in&quot; typemap
26386  should be accompanied by a &quot;javain&quot; typemap and likewise an &quot;out&quot;
26387  typemap by a &quot;javaout&quot; typemap. If an &quot;in&quot; typemap is written, a
26388  &quot;freearg&quot; and &quot;argout&quot; typemap may also need to be written as some
26389  types have a default &quot;freearg&quot; and/or &quot;argout&quot; typemap which may need
26390  overriding. The &quot;freearg&quot; typemap sometimes releases memory allocated
26391  by the &quot;in&quot; typemap. The &quot;argout&quot; typemap sometimes sets values in
26392  function parameters which are passed by reference in Java.</P>
26393 <P> Note that the &quot;in&quot; typemap marshals the JNI type held in the &quot;jni&quot;
26394  typemap to the real C/C++ type and for the opposite direction, the
26395  &quot;out&quot; typemap marshals the real C/C++ type to the JNI type held in the
26396  &quot;jni&quot; typemap. For <A href="#Java_default_non_primitive_typemaps">
26397 non-primitive types</A> the &quot;in&quot; and &quot;out&quot; typemaps are responsible for
26398  casting between the C/C++ pointer and the 64 bit <TT>jlong</TT> type.
26399  There is no portable way to cast a pointer into a 64 bit integer type
26400  and the approach taken by SWIG is mostly portable, but breaks C/C++
26401  aliasing rules. In summary, these rules state that a pointer to any
26402  type must never be dereferenced by a pointer to any other incompatible
26403  type. The following code snippet might aid in understand aliasing rules
26404  better:</P>
26405 <DIV class="code">
26406 <PRE>
26407     short a;
26408     short* pa = 0;
26409     int i = 0x1234;
26410
26411     a = (short)i;    /* okay */
26412     a = *(short*)&amp;i; /* breaks aliasing rules */
26413 </PRE>
26414 </DIV>
26415 <P> An email posting, <A href="http://mail-index.netbsd.org/tech-kern/2003/08/11/0001.html">
26416 Aliasing, pointer casts and gcc 3.3</A> elaborates further on the
26417  subject. In SWIG, the &quot;in&quot; and &quot;out&quot; typemaps for pointers are
26418  typically</P>
26419 <DIV class="code">
26420 <PRE>
26421     %typemap(in) struct Foo * %{
26422       $1 = *(struct Foo **)&amp;$input; /* cast jlong into C ptr */
26423     %}
26424     %typemap(out) struct Bar * %{
26425       *(struct Bar **)&amp;$result = $1; /* cast C ptr into jlong */
26426     %} 
26427     struct Bar {...};
26428     struct Foo {...};
26429     struct Bar * FooBar(struct Foo *f);
26430 </PRE>
26431 </DIV>
26432 <P> resulting in the following code which breaks the aliasing rules:</P>
26433 <DIV class="code">
26434 <PRE>
26435 SWIGEXPORT jlong JNICALL Java_exampleJNI_FooBar(JNIEnv *jenv, jclass jcls,
26436                                                 jlong jarg1, jobject jarg1_) {
26437   jlong jresult = 0 ;
26438   struct Foo *arg1 = (struct Foo *) 0 ;
26439   struct Bar *result = 0 ;
26440   
26441   (void)jenv;
26442   (void)jcls;
26443   (void)jarg1_;
26444   arg1 = *(struct Foo **)&amp;jarg1; 
26445   result = (struct Bar *)FooBar(arg1);
26446   *(struct Bar **)&amp;jresult = result; 
26447   return jresult;
26448 }
26449 </PRE>
26450 </DIV>
26451 <P> If you are using gcc as your C compiler, you might get a
26452  &quot;dereferencing type-punned pointer will break strict-aliasing rules&quot;
26453  warning about this. Please see <A href="#compiling_dynamic">Compiling a
26454  dynamic module</A> to avoid runtime problems with these strict aliasing
26455  rules.</P>
26456 <P> The default code generated by SWIG for the Java module comes from
26457  the typemaps in the &quot;<TT>java.swg</TT>&quot; library file which implements
26458  the <A href="#default_primitive_type_mappings">Default primitive type
26459  mappings</A> and <A href="#Java_default_non_primitive_typemaps">Default
26460  typemaps for non-primitive types</A> covered earlier. There are other
26461  type mapping typemaps in the Java library. These are listed below:</P>
26462 <BR> &nbsp;
26463 <TABLE BORDER summary="Java library typemap mappings">
26464 <TR VALIGN="TOP"><TD><B>C Type</B></TD><TD><B>Typemap</B></TD><TD><B>
26465 File</B></TD><TD><B>Kind</B></TD><TD><B>Java Type</B></TD><TD><B>
26466 Function</B></TD></TR>
26467 <TR><TD>primitive pointers and references</TD><TD>INPUT</TD><TD>
26468 typemaps.i</TD><TD>input</TD><TD>Java basic types</TD><TD>Allows values
26469  to be used for C functions taking pointers for data input.</TD></TR>
26470 <TR><TD>primitive pointers and references</TD><TD>OUTPUT</TD><TD>
26471 typemaps.i</TD><TD>output</TD><TD>Java basic type arrays</TD><TD>Allows
26472  values held within an array to be used for C functions taking pointers
26473  for data output.</TD></TR>
26474 <TR><TD>primitive pointers and references</TD><TD>INOUT</TD><TD>
26475 typemaps.i</TD><TD>input
26476 <BR>output</TD><TD>Java basic type arrays</TD><TD>Allows values held
26477  within an array to be used for C functions taking pointers for data
26478  input and output.</TD></TR>
26479 <TR><TD>string
26480 <BR> wstring</TD><TD>[unnamed]</TD><TD>std_string.i</TD><TD>input
26481 <BR> output</TD><TD>String</TD><TD>Use for std::string mapping to Java
26482  String.</TD></TR>
26483 <TR><TD>arrays of primitive types</TD><TD>[unnamed]</TD><TD>
26484 arrays_java.i</TD><TD>input
26485 <BR> output</TD><TD>arrays of primitive Java types</TD><TD>Use for
26486  mapping C arrays to Java arrays.</TD></TR>
26487 <TR><TD>arrays of classes/structs/unions</TD><TD>JAVA_ARRAYSOFCLASSES
26488  macro</TD><TD>arrays_java.i</TD><TD>input
26489 <BR> output</TD><TD>arrays of proxy classes</TD><TD>Use for mapping C
26490  arrays to Java arrays.</TD></TR>
26491 <TR><TD>arrays of enums</TD><TD>ARRAYSOFENUMS</TD><TD>arrays_java.i</TD><TD>
26492 input
26493 <BR> output</TD><TD>int[]</TD><TD>Use for mapping C arrays to Java
26494  arrays (typeunsafe and simple enum wrapping approaches only).</TD></TR>
26495 <TR VALIGN="TOP"><TD>char *</TD><TD>BYTE</TD><TD>various.i</TD><TD>input</TD><TD>
26496 byte[]</TD><TD VALIGN="TOP">Java byte array is converted to char array</TD>
26497 </TR>
26498 <TR><TD>char **</TD><TD>STRING_ARRAY</TD><TD>various.i</TD><TD>input
26499 <BR> output</TD><TD>String[]</TD><TD>Use for mapping NULL terminated
26500  arrays of C strings to Java String arrays</TD></TR>
26501 </TABLE>
26502 <H3><A name="typemap_attributes"></A>21.9.6 Java typemap attributes</H3>
26503 <P> There are a few additional typemap attributes that the Java module
26504  supports.</P>
26505 <P> The first of these is the 'throws' attribute. The throws attribute
26506  is optional and specified after the typemap name and contains one or
26507  more comma separated classes for adding to the throws clause for any
26508  methods that use that typemap. It is analogous to the <A href="#exception_handling">
26509 %javaexception</A> feature's throws attribute.</P>
26510 <DIV class="code">
26511 <PRE>
26512 %typemap(typemapname, throws=&quot;ExceptionClass1, ExceptionClass2&quot;) type { ... }
26513 </PRE>
26514 </DIV>
26515 <P> The attribute is necessary for supporting Java checked exceptions
26516  and can be added to just about any typemap. The list of typemaps
26517  include all the C/C++ (JNI) typemaps in the &quot;<A href="#Typemaps">
26518 Typemaps</A>&quot; chapter and the Java specific typemaps listed in <A href="#typemaps_c_to_java_types">
26519 the previous section</A>, barring the &quot;jni&quot;, &quot;jtype&quot; and &quot;jstype&quot;
26520  typemaps as they could never contain code to throw an exception.</P>
26521 <P> The throws clause is generated for the proxy method as well as the
26522  JNI method in the JNI intermediary class. If a method uses more than
26523  one typemap and each of those typemaps have classes specified in the
26524  throws clause, the union of the exception classes is added to the
26525  throws clause ensuring there are no duplicate classes. See the <A href="#nan_exception_typemap">
26526 NaN exception example</A> for further usage.</P>
26527 <P> The &quot;jtype&quot; typemap has the optional 'nopgcpp' attribute which can
26528  be used to suppress the generation of the <A href="java_pgcpp">
26529 premature garbage collection prevention parameter</A>.</P>
26530 <P> The &quot;javain&quot; typemap has the optional 'pre', 'post' and 'pgcppname'
26531  attributes. These are used for generating code before and after the JNI
26532  call in the proxy class or module class. The 'pre' attribute contains
26533  code that is generated before the JNI call and the 'post' attribute
26534  contains code generated after the JNI call. The 'pgcppname' attribute
26535  is used to change the <A href="java_pgcpp">premature garbage collection
26536  prevention parameter</A> name passed to the JNI function. This is
26537  sometimes needed when the 'pre' typemap creates a temporary variable
26538  which is then passed to the JNI function.</P>
26539 <P> <A name="java_constructor_helper_function"></A> Note that when the
26540  'pre' or 'post' attributes are specified and the associated type is
26541  used in a constructor, a constructor helper function is generated. This
26542  is necessary as the Java proxy constructor wrapper makes a call to a
26543  support constructor using a<I> this</I> call. In Java the<I> this</I>
26544  call must be the first statement in the constructor body. The
26545  constructor body thus calls the helper function and the helper function
26546  instead makes the JNI call, ensuring the 'pre' code is called before
26547  the JNI call is made. There is a <A href="#java_date_marshalling">Date
26548  marshalling</A> example showing 'pre', 'post' and 'pgcppname'
26549  attributes in action.</P>
26550 <H3><A name="special_variables"></A>21.9.7 Java special variables</H3>
26551 <P> The standard SWIG special variables are available for use within
26552  typemaps as described in the <A href="#Typemaps">Typemaps documentation</A>
26553 , for example <TT>$1</TT>, <TT>$input</TT>,<TT>$result</TT> etc.</P>
26554 <P> The Java module uses a few additional special variables:</P>
26555 <P><B> <TT>$javaclassname</TT></B>
26556 <BR> This special variable works like the other <A href="#Typemaps_special_variables">
26557 special variables</A> and <TT>$javaclassname</TT> is similar to <TT>
26558 $1_type</TT>. It expands to the class name for use in Java given a
26559  pointer. SWIG wraps unions, structs and classes using pointers and in
26560  this case it expands to the Java proxy class name. For example, <TT>
26561 $javaclassname</TT> is replaced by the proxy classname <TT>Foo</TT> when
26562  wrapping a <TT>Foo *</TT> and <TT>$&amp;javaclassname</TT> expands to the
26563  proxy classname when wrapping the C/C++ type <TT>Foo</TT> and <TT>
26564 $*javaclassname</TT> expands to the proxy classname when wrapping <TT>
26565 Foo *&amp;</TT>. If the type does not have an associated proxy class, it
26566  expands to the type wrapper class name, for example, <TT>
26567 SWIGTYPE_p_unsigned_short</TT> is generated when wrapping <TT>unsigned
26568  short *</TT>.</P>
26569 <P><B> <TT>$null</TT></B>
26570 <BR> Used in input typemaps to return early from JNI functions that have
26571  either void or a non-void return type. Example:</P>
26572 <DIV class="code">
26573 <PRE>
26574 %typemap(check) int * %{ 
26575   if (error) {
26576     SWIG_JavaThrowException(jenv, SWIG_JavaIndexOutOfBoundsException, &quot;Array element error&quot;);
26577     return $null;
26578   }
26579 %}
26580 </PRE>
26581 </DIV>
26582 <P> If the typemap gets put into a function with void as return, $null
26583  will expand to nothing:</P>
26584 <DIV class="code">
26585 <PRE>
26586 SWIGEXPORT void JNICALL Java_jnifn(...) {
26587     if (error) {
26588       SWIG_JavaThrowException(jenv, SWIG_JavaIndexOutOfBoundsException, &quot;Array element error&quot;);
26589       return ;
26590     }
26591   ...
26592 }
26593 </PRE>
26594 </DIV>
26595 <P> otherwise $null expands to<I> NULL</I></P>
26596 <DIV class="code">
26597 <PRE>
26598 SWIGEXPORT jobject JNICALL Java_jnifn(...) {
26599     if (error) {
26600       SWIG_JavaThrowException(jenv, SWIG_JavaIndexOutOfBoundsException, &quot;Array element error&quot;);
26601       return NULL;
26602     }
26603   ...
26604 }
26605 </PRE>
26606 </DIV>
26607 <P><B> <TT>$javainput, $jnicall and $owner</TT></B>
26608 <BR> The $javainput special variable is used in &quot;javain&quot; typemaps and
26609  $jnicall and $owner are used in &quot;javaout&quot; typemaps. $jnicall is
26610  analogous to $action in %exception. It is replaced by the call to the
26611  native method in the intermediary JNI class. $owner is replaced by
26612  either <TT>true</TT> if %newobject has been used, otherwise <TT>false</TT>
26613 . $javainput is analogous to the $input special variable. It is replaced
26614  by the parameter name.</P>
26615 <P> Here is an example:</P>
26616 <DIV class="code">
26617 <PRE>
26618 %typemap(javain) Class &quot;Class.getCPtr($javainput)&quot;
26619 %typemap(javain) unsigned short &quot;$javainput&quot;
26620 %typemap(javaout) Class * {
26621     return new Class($jnicall, $owner);
26622   }
26623
26624 %inline %{
26625     class Class {...};
26626     Class * bar(Class cls, unsigned short ush) { return new Class(); };
26627 %}
26628 </PRE>
26629 </DIV>
26630 <P> The generated proxy code is then:</P>
26631 <DIV class="code">
26632 <PRE>
26633 public static Class bar(Class cls, int ush) {
26634   return new Class(exampleJNI.bar(Class.getCPtr(cls), cls, ush), false);
26635 }
26636 </PRE>
26637 </DIV>
26638 <P> Here $javainput has been replaced by <TT>cls</TT> and <TT>ush</TT>.
26639  $jnicall has been replaced by the native method call, <TT>
26640 exampleJNI.bar(...)</TT> and $owner has been replaced by <TT>false</TT>.
26641  If %newobject is used by adding the following at the beginning of our
26642  example:</P>
26643 <DIV class="code">
26644 <PRE>
26645 %newobject bar(Class cls, unsigned short ush);
26646 </PRE>
26647 </DIV>
26648 <P> The generated code constructs the return type using <TT>true</TT>
26649  indicating the proxy class <TT>Class</TT> is responsible for destroying
26650  the C++ memory allocated for it in <TT>bar</TT>:</P>
26651 <DIV class="code">
26652 <PRE>
26653 public static Class bar(Class cls, int ush) {
26654   return new Class(exampleJNI.bar(Class.getCPtr(cls), cls, ush), true);
26655 }
26656 </PRE>
26657 </DIV>
26658 <P><B> <TT>$static</TT></B>
26659 <BR> This special variable expands to either<I> static</I> or nothing
26660  depending on whether the class is an inner Java class or not. It is
26661  used in the &quot;javaclassmodifiers&quot; typemap so that global classes can be
26662  wrapped as Java proxy classes and nested C++ classes/enums can be
26663  wrapped with the Java equivalent, that is, static inner proxy classes.</P>
26664 <P><B> <TT>$jniinput, $javacall and $packagepath</TT></B>
26665 <BR> These special variables are used in the directors typemaps. See <A href="#java_directors_typemaps">
26666 Director specific typemaps</A> for details.</P>
26667 <P><B> <TT>$module</TT></B>
26668 <BR> This special variable expands to the module name, as specified by <TT>
26669 %module</TT> or the <TT>-module</TT> commandline option.</P>
26670 <P><B> <TT>$imclassname</TT></B>
26671 <BR> This special variable expands to the intermediary class name.
26672  Usually this is the same as '$moduleJNI', unless the jniclassname
26673  attribute is specified in the <A href="#java_module_directive">%module
26674  directive</A>.</P>
26675 <H3><A name="typemaps_for_c_and_cpp"></A>21.9.8 Typemaps for both C and
26676  C++ compilation</H3>
26677 <P> JNI calls must be written differently depending on whether the code
26678  is being compiled as C or C++. For example C compilation requires the
26679  pointer to a function pointer struct member syntax like</P>
26680 <DIV class="code">
26681 <PRE>
26682 const jclass clazz = (*jenv)-&gt;FindClass(jenv, &quot;java/lang/String&quot;);
26683 </PRE>
26684 </DIV>
26685 <P> whereas C++ code compilation of the same function call is a member
26686  function call using a class pointer like</P>
26687 <DIV class="code">
26688 <PRE>
26689 const jclass clazz = jenv-&gt;FindClass(&quot;java/lang/String&quot;);
26690 </PRE>
26691 </DIV>
26692 <P> To enable typemaps to be used for either C or C++ compilation, a set
26693  of JCALLx macros have been defined in Lib/java/javahead.swg, where x is
26694  the number of arguments in the C++ version of the JNI call. The above
26695  JNI calls would be written in a typemap like this</P>
26696 <DIV class="code">
26697 <PRE>
26698 const jclass clazz = JCALL1(FindClass, jenv, &quot;java/lang/String&quot;);
26699 </PRE>
26700 </DIV>
26701 <P> Note that the SWIG preprocessor expands these into the appropriate C
26702  or C++ JNI calling convention. The C calling convention is emitted by
26703  default and the C++ calling convention is emitted when using the -c++
26704  SWIG commandline option. If you do not intend your code to be targeting
26705  both C and C++ then your typemaps can use the appropriate JNI calling
26706  convention and need not use the JCALLx macros.</P>
26707 <H3><A name="java_code_typemaps"></A>21.9.9 Java code typemaps</H3>
26708 <P> Most of SWIG's typemaps are used for the generation of C/C++ code.
26709  The typemaps in this section are used solely for the generation of Java
26710  code. Elements of proxy classes and type wrapper classes come from the
26711  following typemaps (the defaults).</P>
26712 <P><TT>%typemap(javabase)</TT></P>
26713 <DIV class="indent"> base (extends) for Java class: empty default
26714 <BR> Note that this typemap accepts a <TT>replace</TT> attribute as an
26715  optional flag. When set to &quot;1&quot;, it will replace/override any C++ base
26716  classes that might have been parsed. If this flag is not specified and
26717  there are C++ base classes, then a multiple inheritance warning is
26718  issued and the code in the typemap is ignored. The typemap also accepts
26719  a <TT>notderived</TT> attribute as an optional flag. When set to &quot;1&quot;,
26720  it will not apply to classes that are derived from a C++ base. When
26721  used with the SWIGTYPE type, it is useful for giving a common base for
26722  all proxy classes, that is, providing a base class that sits in between
26723  all proxy classes and the Java base class <TT>Object</TT> for example: <TT>
26724 %typemap(javabase, notderived=&quot;1&quot;) SWIGTYPE &quot;CommonBase&quot;</TT>.</DIV>
26725 <P><TT>%typemap(javabody)</TT></P>
26726 <DIV class="indent"> the essential support body for proxy classes (proxy
26727  base classes only), typewrapper classes and enum classes. Default
26728  contains extra constructors, memory ownership control member variables
26729  (<TT>swigCMemOwn</TT>, <TT>swigCPtr</TT>), the <TT>getCPtr</TT> method
26730  etc.</DIV>
26731 <P><TT>%typemap(javabody_derived)</TT></P>
26732 <DIV class="indent"> the essential support body for proxy classes
26733  (derived classes only). Same as &quot;javabody&quot; typemap, but only used for
26734  proxy derived classes.</DIV>
26735 <P><TT>%typemap(javaclassmodifiers)</TT></P>
26736 <DIV class="indent"> class modifiers for the Java class: default is
26737  &quot;public class&quot;</DIV>
26738 <P><TT>%typemap(javacode)</TT></P>
26739 <DIV class="indent"> Java code is copied verbatim to the Java class:
26740  empty default</DIV>
26741 <P><TT>%typemap(javadestruct, methodname=&quot;delete&quot;,
26742  methodmodifiers=&quot;public synchronized&quot;)</TT>
26743 <BR></P>
26744 <DIV class="indent"> destructor wrapper - the <TT>delete()</TT> method
26745  (proxy classes only), used for all proxy classes except those which
26746  have a base class : default calls C++ destructor (or frees C memory)
26747  and resets <TT>swigCPtr</TT> and <TT>swigCMemOwn</TT> flags
26748 <BR>
26749 <BR> Note that the <TT>delete()</TT> method name is configurable and is
26750  specified by the <TT>methodname</TT> attribute. The method modifiers
26751  are also configurable via the <TT>methodmodifiers</TT> attribute.</DIV>
26752 <P><TT>%typemap(javadestruct_derived, methodname=&quot;delete&quot;,
26753  methodmodifiers=&quot;public synchronized&quot;)</TT></P>
26754 <DIV class="indent"> destructor wrapper - the <TT>delete()</TT> method
26755  (proxy classes only), same as &quot;javadestruct&quot; but only used for derived
26756  proxy classes : default calls C++ destructor (or frees C memory) and
26757  resets <TT>swigCPtr</TT> and <TT>swigCMemOwn</TT> flags
26758 <BR>
26759 <BR> Note that the <TT>delete()</TT> method name is configurable and is
26760  specified by the <TT>methodname</TT> attribute. The method modifiers
26761  are also configurable via the <TT>methodmodifiers</TT> attribute.</DIV>
26762 <P><TT>%typemap(javaimports)</TT></P>
26763 <DIV class="indent"> import statements for Java class: empty default</DIV>
26764 <P><TT>%typemap(javainterfaces)</TT></P>
26765 <DIV class="indent"> interfaces (extends) for Java class: empty default</DIV>
26766 <P><TT>%typemap(javafinalize)</TT></P>
26767 <DIV class="indent"> the <TT>finalize()</TT> method (proxy classes
26768  only): default calls the <TT>delete()</TT> method</DIV>
26769 <P><B> Compatibility Note:</B> In SWIG-1.3.21 and earlier releases,
26770  typemaps called &quot;javagetcptr&quot; and &quot;javaptrconstructormodifiers&quot; were
26771  available. These are deprecated and the &quot;javabody&quot; typemap can be used
26772  instead.</P>
26773 <P> In summary the contents of the typemaps make up a proxy class like
26774  this:</P>
26775 <DIV class="code">
26776 <PRE>
26777 [ javaimports typemap ]
26778 [ javaclassmodifiers typemap ] javaclassname extends [ javabase typemap ]
26779                                              implements [ javainterfaces typemap ] {
26780 [ javabody or javabody_derived typemap ]
26781 [ javafinalize typemap ]
26782 public synchronized void <I>delete</I>() [ javadestruct OR javadestruct_derived typemap ]
26783 [ javacode typemap ]
26784 ... proxy functions ...
26785 }
26786 </PRE>
26787 </DIV>
26788 <P> Note the <TT><I>delete</I>()</TT> methodname and method modifiers
26789  are configurable, see &quot;javadestruct&quot; and &quot;javadestruct_derived&quot;
26790  typemaps above.</P>
26791 <P> The type wrapper class is similar in construction:</P>
26792 <DIV class="code">
26793 <PRE>
26794 [ javaimports typemap ]
26795 [ javaclassmodifiers typemap ] javaclassname extends [ javabase typemap ]
26796                                              implements [ javainterfaces typemap ] {
26797 [ javabody typemap ]
26798 [ javacode typemap ]
26799 }
26800 </PRE>
26801 </DIV>
26802 <P>The enum class is also similar in construction:</P>
26803 <DIV class="code">
26804 <PRE>
26805 [ javaimports typemap ]
26806 [ javaclassmodifiers typemap ] javaclassname extends [ javabase typemap ]
26807                                              implements [ javainterfaces typemap ] {
26808 ... Enum values ...
26809 [ javabody typemap ]
26810 [ javacode typemap ]
26811 }
26812 </PRE>
26813 </DIV>
26814 <P> The &quot;javaimports&quot; typemap is ignored if the enum class is wrapped by
26815  an inner Java class, that is when wrapping an enum declared within a
26816  C++ class.</P>
26817 <P> The defaults can be overridden to tailor these classes. Here is an
26818  example which will change the <TT>getCPtr</TT> method and constructor
26819  from the default protected access to public access. This has a
26820  practical application if you are invoking SWIG more than once and
26821  generating the wrapped classes into different packages in each
26822  invocation. If the classes in one package are using the classes in
26823  another package, then these methods need to be public.</P>
26824 <DIV class="code">
26825 <PRE>
26826 %typemap(javabody) SWIGTYPE %{
26827   private long swigCPtr;
26828   protected boolean swigCMemOwn;
26829
26830   public $javaclassname(long cPtr, boolean cMemoryOwn) {
26831     swigCMemOwn = cMemoryOwn;
26832     swigCPtr = cPtr;
26833   }
26834
26835   public static long getCPtr($javaclassname obj) {
26836     return (obj == null) ? 0 : obj.swigCPtr;
26837   }
26838 %}
26839 </PRE>
26840 </DIV>
26841 <P> The typemap code is the same that is in &quot;<TT>java.swg</TT>&quot;, barring
26842  the two method modifiers. Note that <TT>SWIGTYPE</TT> will target all
26843  proxy classes, but not the type wrapper classes. Also the above typemap
26844  is only used for proxy classes that are potential base classes. To
26845  target proxy classes that are derived from a wrapped class as well, the
26846  &quot;javabody_derived&quot; typemap should also be overridden.</P>
26847 <P> For the typemap to be used in all type wrapper classes, all the
26848  different types that type wrapper classes could be used for should be
26849  targeted:</P>
26850 <DIV class="code">
26851 <PRE>
26852 %typemap(javabody) SWIGTYPE *, SWIGTYPE &amp;, SWIGTYPE [], SWIGTYPE (CLASS::*) %{
26853   private long swigCPtr;
26854
26855   public $javaclassname(long cPtr, boolean bFutureUse) {
26856     swigCPtr = cPtr;
26857   }
26858
26859   protected $javaclassname() {
26860     swigCPtr = 0;
26861   }
26862
26863   public static long getCPtr($javaclassname obj) {
26864     return (obj == null) ? 0 : obj.swigCPtr;
26865   }
26866 %}
26867 </PRE>
26868 </DIV>
26869 <P> Again this is the same that is in &quot;<TT>java.swg</TT>&quot;, barring the
26870  method modifier for <TT>getCPtr</TT>.</P>
26871 <H3><A name="java_directors_typemaps"></A>21.9.10 Director specific
26872  typemaps</H3>
26873 <P> The Java directors feature requires the &quot;javadirectorin&quot;,
26874  &quot;javadirectorout&quot;, &quot;directorin&quot; and the &quot;directorout&quot; typemaps in order
26875  to work properly. The &quot;javapackage&quot; typemap is an optional typemap used
26876  to identify the Java package path for individual SWIG generated proxy
26877  classes.</P>
26878 <P><TT>%typemap(directorin)</TT></P>
26879 <DIV class="indent">
26880 <P> The &quot;directorin&quot; typemap is used for converting arguments in the C++
26881  director class to the appropriate JNI type before the upcall to Java.
26882  This typemap also specifies the JNI field descriptor for the type in
26883  the &quot;descriptor&quot; attribute. For example, integers are converted as
26884  follows:</P>
26885 <DIV class="code">
26886 <PRE>
26887 %typemap(directorin,descriptor=&quot;I&quot;) int &quot;$input = (jint) $1;&quot;
26888 </PRE>
26889 </DIV>
26890 <P> <CODE>$input</CODE> is the SWIG name of the JNI temporary variable
26891  passed to Java in the upcall. The <CODE>descriptor=&quot;I&quot;</CODE> will put
26892  an <CODE>I</CODE> into the JNI field descriptor that identifies the
26893  Java method that will be called from C++. For more about JNI field
26894  descriptors and their importance, refer to the <A href="#java_typemaps">
26895 JNI documentation mentioned earlier</A>. A typemap for C character
26896  strings is:</P>
26897 <DIV class="code">
26898 <PRE>
26899 %typemap(directorin,descriptor=&quot;Ljava/lang/String;&quot;) char *
26900   %{ $input = jenv-&gt;NewStringUTF($1); %}
26901 </PRE>
26902 </DIV>
26903 <P> User-defined types have the default &quot;descriptor&quot; attribute &quot;<CODE>
26904 L$packagepath/$javaclassname;</CODE>&quot; where <CODE>$packagepath</CODE> is
26905  the package name passed from the SWIG command line and <CODE>
26906 $javaclassname</CODE> is the Java proxy class' name. If the <TT>-package</TT>
26907  commandline option is not used to specify the package, then
26908  '$packagepath/' will be removed from the resulting output JNI field
26909  descriptor.<B> Do not forget the terminating ';' for JNI field
26910  descriptors starting with 'L'.</B> If the ';' is left out, Java will
26911  generate a &quot;method not found&quot; runtime error.</P>
26912 </DIV>
26913 <P><TT>%typemap(directorout)</TT></P>
26914 <DIV class="indent">
26915 <P> The &quot;directorout&quot; typemap is used for converting the JNI return type
26916  in the C++ director class to the appropriate C++ type after the upcall
26917  to Java. For example, integers are converted as follows:</P>
26918 <DIV class="code">
26919 <PRE>
26920 %typemap(directorout) int %{ $result = (int)$input; %}
26921 </PRE>
26922 </DIV>
26923 <P> <CODE>$input</CODE> is the SWIG name of the JNI temporary variable
26924  returned from Java after the upcall. <CODE>$result</CODE> is the
26925  resulting output. A typemap for C character strings is:</P>
26926 <DIV class="code">
26927 <PRE>
26928 %typemap(directorout) char * {
26929   $1 = 0;
26930   if ($input) {
26931     $result = (char *)jenv-&gt;GetStringUTFChars($input, 0);
26932     if (!$1) return $null;
26933   }
26934 }
26935 </PRE>
26936 </DIV></DIV>
26937 <P><TT>%typemap(javadirectorin)</TT></P>
26938 <DIV class="indent">
26939 <P> Conversion from jtype to jstype for director methods. These are Java
26940  code typemaps which transform the type used in the Java intermediary
26941  JNI class (as specified in the &quot;jtype&quot; typemap) to the Java type used
26942  in the Java module class, proxy classes and type wrapper classes (as
26943  specified in the &quot;jstype&quot; typemap). This typemap provides the
26944  conversion for the parameters in the director methods when calling up
26945  from C++ to Java.</P>
26946 <P> For primitive types, this typemap is usually specified as:</P>
26947 <DIV class="code">
26948 <PRE>
26949 %typemap(javadirectorin) int &quot;$jniinput&quot;
26950 </PRE>
26951 </DIV>
26952 <P> The <CODE>$jniinput</CODE> special variable is analogous to <CODE>
26953 $javainput</CODE> special variable. It is replaced by the input
26954  parameter name.</P>
26955 </DIV>
26956 <P><TT>%typemap(javadirectorout)</TT></P>
26957 <DIV class="indent">
26958 <P> Conversion from jstype to jtype for director methods. These are Java
26959  code typemaps which transform the type used in the Java module class,
26960  proxy classes and type wrapper classes (as specified in the &quot;jstype&quot;
26961  typemap) to the type used in the Java intermediary JNI class (as
26962  specified in the &quot;jtype&quot; typemap). This typemap provides the conversion
26963  for the return type in the director methods when returning from the C++
26964  to Java upcall.</P>
26965 <P> For primitive types, this typemap is usually specified as:</P>
26966 <DIV class="code">
26967 <PRE>
26968 %typemap(javadirectorout) int &quot;$javacall&quot;
26969 </PRE>
26970 </DIV>
26971 <P> The <CODE>$javacall</CODE> special variable is analogous to the <CODE>
26972 $jnicall</CODE> special variable. It is replaced by the call to the
26973  target Java method. The target method is the method in the Java proxy
26974  class which overrides the virtual C++ method in the C++ base class.</P>
26975 </DIV>
26976 <P><TT>%typemap(javapackage)</TT></P>
26977 <DIV class="indent">
26978 <P> The &quot;javapackage&quot; typemap is optional; it serves to identify a
26979  class's Java package. This typemap should be used in conjunction with
26980  classes that are defined outside of the current SWIG interface file.
26981  For example:</P>
26982 <DIV class="code">
26983 <PRE>
26984 // class Foo is handled in a different interface file:
26985 %import &quot;Foo.i&quot;
26986
26987 %feature(&quot;director&quot;) Example;
26988
26989 %inline {
26990   class Bar { };
26991
26992   class Example {
26993   public:
26994     virtual ~Example();
26995     void     ping(Foo *arg1, Bar *arg2);
26996   };
26997 }
26998 </PRE>
26999 </DIV>
27000 <P> Assume that the Foo class is part of the Java package<I>
27001  com.wombat.foo</I> but the above interface file is part of the Java
27002  package<I> com.wombat.example</I>. Without the &quot;javapackage&quot; typemap,
27003  SWIG will assume that the Foo class belongs to<I> com.wombat.example</I>
27004  class. The corrected interface file looks like:</P>
27005 <DIV class="code">
27006 <PRE>
27007 // class Foo is handled in a different interface file:
27008 %import &quot;Foo.i&quot;
27009 %typemap(&quot;javapackage&quot;) Foo, Foo *, Foo &amp; &quot;com.wombat.foo&quot;;
27010 %feature(&quot;director&quot;) Example;
27011
27012 %inline {
27013   class Bar { };
27014
27015   class Example {
27016   public:
27017     virtual ~Example();
27018     void     ping(Foo *arg1, Bar *arg2);
27019   };
27020 }
27021 </PRE>
27022 </DIV>
27023 <P> SWIG looks up the package based on the<B> actual</B> type (plain
27024  Foo, Foo pointer and Foo reference), so it is important to associate
27025  all three types with the desired package. Practically speaking, you
27026  should create a separate SWIG interface file, which is %import-ed into
27027  each SWIG interface file, when you have multiple Java packages. Note
27028  the helper macros below, <CODE>OTHER_PACKAGE_SPEC</CODE> and <CODE>
27029 ANOTHER_PACKAGE_SPEC</CODE>, which reduce the amount of extra typing. &quot;<CODE>
27030 TYPE...</CODE>&quot; is useful when passing templated types to the macro,
27031  since multiargument template types appear to the SWIG preprocessor as
27032  multiple macro arguments.</P>
27033 <DIV class="code">
27034 <PRE>
27035 %typemap(&quot;javapackage&quot;) SWIGTYPE, SWIGTYPE *, SWIGTYPE &amp;
27036                                             &quot;package.for.most.classes&quot;;
27037
27038 %define OTHER_PACKAGE_SPEC(TYPE...)
27039 %typemap(&quot;javapackage&quot;) TYPE, TYPE *, TYPE &amp; &quot;package.for.other.classes&quot;;
27040 %enddef
27041
27042 %define ANOTHER_PACKAGE_SPEC(TYPE...)
27043 %typemap(&quot;javapackage&quot;) TYPE, TYPE *, TYPE &amp; &quot;package.for.another.set&quot;;
27044 %enddef
27045
27046 OTHER_PACKAGE_SPEC(Package_2_class_one)
27047 ANOTHER_PACKAGE_SPEC(Package_3_class_two)
27048 /* etc */
27049 </PRE>
27050 </DIV>
27051 <P> The basic strategy here is to provide a default package typemap for
27052  the majority of the classes, only providing &quot;javapackage&quot; typemaps for
27053  the exceptions.</P>
27054 </DIV>
27055 <H2><A name="typemap_examples"></A>21.10 Typemap Examples</H2>
27056 <P> This section includes a few examples of typemaps. For more examples,
27057  you might look at the files &quot;<TT>java.swg</TT>&quot; and &quot;<TT>typemaps.i</TT>
27058 &quot; in the SWIG library.</P>
27059 <H3><A name="simpler_enum_classes"></A>21.10.1 Simpler Java enums for
27060  enums without initializers</H3>
27061 <P> The default <A href="#proper_enums_classes">Proper Java enums</A>
27062  approach to wrapping enums is somewhat verbose. This is to handle all
27063  possible C/C++ enums, in particular enums with initializers. The
27064  generated code can be simplified if the enum being wrapped does not
27065  have any initializers.</P>
27066 <P> The following shows how to remove the support methods that are
27067  generated by default and instead use the methods in the Java enum base
27068  class <TT>java.lang.Enum</TT> and <TT>java.lang.Class</TT> for
27069  marshalling enums between C/C++ and Java. The type used for the
27070  typemaps below is <TT>enum SWIGTYPE</TT> which is the default type used
27071  for all enums. The &quot;enums.swg&quot; file should be examined in order to see
27072  the original overridden versions of the typemaps.</P>
27073 <DIV class="code">
27074 <PRE>
27075 %include &quot;enums.swg&quot;
27076
27077 %typemap(javain) enum SWIGTYPE &quot;$javainput.ordinal()&quot;
27078 %typemap(javaout) enum SWIGTYPE {
27079     return $javaclassname.class.getEnumConstants()[$jnicall];
27080   }
27081 %typemap(javabody) enum SWIGTYPE &quot;&quot;
27082
27083 %inline %{
27084   enum HairType { blonde, ginger, brunette };
27085   void setHair(HairType h);
27086   HairType getHair();
27087 %}
27088 </PRE>
27089 </DIV>
27090 <P> SWIG will generate the following Java enum, which is somewhat
27091  simpler than the default:</P>
27092 <DIV class="code">
27093 <PRE>
27094 public enum HairType {
27095   blonde,
27096   ginger,
27097   brunette;
27098 }
27099 </PRE>
27100 </DIV>
27101 <P> and the two Java proxy methods will be:</P>
27102 <DIV class="code">
27103 <PRE>
27104 public static void setHair(HairType h) {
27105   exampleJNI.setHair(h.ordinal());
27106 }
27107
27108 public static HairType getHair() {
27109   return HairType.class.getEnumConstants()[exampleJNI.getHair()];
27110 }
27111 </PRE>
27112 </DIV>
27113 <P> For marshalling Java enums to C/C++ enums, the <TT>ordinal</TT>
27114  method is used to convert the Java enum into an integer value for
27115  passing to the JNI layer, see the &quot;javain&quot; typemap. For marshalling
27116  C/C++ enums to Java enums, the C/C++ enum value is cast to an integer
27117  in the C/C++ typemaps (not shown). This integer value is then used to
27118  index into the array of enum constants that the Java language provides.
27119  See the <TT>getEnumConstants</TT> method in the &quot;javaout&quot; typemap.</P>
27120 <P> These typemaps can often be used as the default for wrapping enums
27121  as in many cases there won't be any enum initializers. In fact a good
27122  strategy is to always use these typemaps and to specifically handle
27123  enums with initializers using %apply. This would be done by using the
27124  original versions of these typemaps in &quot;enums.swg&quot; under another
27125  typemap name for applying using %apply.</P>
27126 <H3><A name="exception_typemap"></A>21.10.2 Handling C++ exception
27127  specifications as Java exceptions</H3>
27128 <P> This example demonstrates various ways in which C++ exceptions can
27129  be tailored and converted into Java exceptions. Let's consider a simple
27130  file class <TT>SimpleFile</TT> and an exception class <TT>FileException</TT>
27131  which it may throw on error:</P>
27132 <DIV class="code">
27133 <PRE>
27134 %include &quot;std_string.i&quot; // for std::string typemaps
27135 #include &lt;string&gt;
27136
27137 class FileException {
27138   std::string message;
27139 public:
27140   FileException(const std::string&amp; msg) : message(msg) {}
27141   std::string what() {
27142     return message;
27143   }
27144 };
27145
27146 class SimpleFile {
27147   std::string filename;
27148 public:
27149   SimpleFile(const std::string&amp; filename) : filename(filename) {}
27150   void open() throw(FileException) {
27151   ...
27152   }
27153 };
27154 </PRE>
27155 </DIV>
27156 <P> As the <TT>open</TT> method has a C++ exception specification, SWIG
27157  will parse this and know that the method can throw an exception. The <A href="#throws_typemap">
27158 &quot;throws&quot; typemap</A> is then used when SWIG encounters an exception
27159  specification. The default generic &quot;throws&quot; typemap looks like this:</P>
27160 <DIV class="code">
27161 <PRE>
27162 %typemap(throws) SWIGTYPE, SWIGTYPE &amp;, SWIGTYPE *, SWIGTYPE [ANY] %{
27163   SWIG_JavaThrowException(jenv, SWIG_JavaRuntimeException,
27164                           &quot;C++ $1_type exception thrown&quot;);
27165   return $null;
27166 %}
27167 </PRE>
27168 </DIV>
27169 <P> Basically SWIG will generate a C++ try catch block and the body of
27170  the &quot;throws&quot; typemap constitutes the catch block. The above typemap
27171  calls a SWIG supplied method which throws a <TT>
27172 java.lang.RuntimeException</TT>. This exception class is a runtime
27173  exception and therefore not a checked exception. If, however, we wanted
27174  to throw a checked exception, say <TT>java.io.IOException</TT>, then we
27175  could use the following typemap:</P>
27176 <DIV class="code">
27177 <PRE>
27178 %typemap(throws, throws=&quot;java.io.IOException&quot;) FileException {
27179   jclass excep = jenv-&gt;FindClass(&quot;java/io/IOException&quot;);
27180   if (excep)
27181     jenv-&gt;ThrowNew(excep, $1.what().c_str());
27182   return $null;
27183 }
27184 </PRE>
27185 </DIV>
27186 <P> Note that this typemap uses the 'throws' <A href="#typemap_attributes">
27187 typemap attribute</A> to ensure a throws clause is generated. The
27188  generated proxy method then specifies the checked exception by
27189  containing <TT>java.io.IOException</TT> in the throws clause:</P>
27190 <DIV class="code">
27191 <PRE>
27192 public class SimpleFile {
27193   ...
27194   public void open() throws java.io.IOException { ... }
27195 }
27196 </PRE>
27197 </DIV>
27198 <P> Lastly, if you don't want to map your C++ exception into one of the
27199  standard Java exceptions, the C++ class can be wrapped and turned into
27200  a custom Java exception class. If we go back to our example, the first
27201  thing we must do is get SWIG to wrap <TT>FileException</TT> and ensure
27202  that it derives from <TT>java.lang.Exception</TT>. Additionally, we
27203  might want to override the <TT>java.lang.Exception.getMessage()</TT>
27204  method. The typemaps to use then are as follows:</P>
27205 <DIV class="code">
27206 <PRE>
27207 %typemap(javabase) FileException &quot;java.lang.Exception&quot;;
27208 %typemap(javacode) FileException %{
27209   public String getMessage() {
27210     return what();
27211   }
27212 %}
27213 </PRE>
27214 </DIV>
27215 <P> This generates:</P>
27216 <DIV class="code">
27217 <PRE>
27218 public class FileException extends java.lang.Exception {
27219   ...
27220   public String getMessage() {
27221     return what();
27222   }
27223
27224   public FileException(String msg) { ... }
27225
27226   public String what() {
27227     return exampleJNI.FileException_what(swigCPtr, this);
27228   }
27229 }
27230 </PRE>
27231 </DIV>
27232 <P> We could alternatively have used <TT>%rename</TT> to rename <TT>
27233 what()</TT> into <TT>getMessage()</TT>.</P>
27234 <H3><A name="nan_exception_typemap"></A>21.10.3 NaN Exception -
27235  exception handling for a particular type</H3>
27236 <P> A Java exception can be thrown from any Java or JNI code. Therefore,
27237  as most typemaps contain either Java or JNI code, just about any
27238  typemap could throw an exception. The following example demonstrates
27239  exception handling on a type by type basis by checking for 'Not a
27240  number' (NaN) whenever a parameter of type <TT>float</TT> is wrapped.</P>
27241 <P> Consider the following C++ code:</P>
27242 <DIV class="code">
27243 <PRE>
27244 bool calculate(float first, float second);
27245 </PRE>
27246 </DIV>
27247 <P> To validate every <TT>float</TT> being passed to C++, we could
27248  precede the code being wrapped by the following typemap which throws a
27249  runtime exception whenever the <TT>float</TT> is 'Not a Number':</P>
27250 <DIV class="code">
27251 <PRE>
27252 %module example
27253 %typemap(javain) float &quot;$module.CheckForNaN($javainput)&quot;
27254 %pragma(java) modulecode=%{
27255   /** Simply returns the input value unless it is not a number,
27256       whereupon an exception is thrown. */
27257   static protected float CheckForNaN(float num) {
27258     if (Float.isNaN(num))
27259       throw new RuntimeException(&quot;Not a number&quot;);
27260     return num;
27261   }
27262 %}
27263 </PRE>
27264 </DIV>
27265 <P> Note that the <TT>CheckForNaN</TT> support method has been added to
27266  the module class using the <TT>modulecode</TT> pragma. The following
27267  shows the generated code of interest:</P>
27268 <DIV class="code">
27269 <PRE>
27270 public class example {
27271   ...
27272
27273   /** Simply returns the input value unless it is not a number,
27274       whereupon an exception is thrown. */
27275   static protected float CheckForNaN(float num) {
27276     if (Float.isNaN(num))
27277       throw new RuntimeException(&quot;Not a number&quot;);
27278     return num;
27279   }
27280
27281   public static boolean calculate(float first, float second) {
27282     return exampleJNI.calculate(example.CheckForNaN(first), example.CheckForNaN(second));
27283   }
27284 }
27285 </PRE>
27286 </DIV>
27287 <P> Note that the &quot;javain&quot; typemap is used for every occurrence of a <TT>
27288 float</TT> being used as an input. Of course, we could have targeted the
27289  typemap at a particular parameter by using <TT>float first</TT>, say,
27290  instead of just <TT>float</TT>.</P>
27291 <P> The exception checking could alternatively have been placed into the
27292  'pre' attribute that the &quot;javain&quot; typemap supports. The &quot;javain&quot;
27293  typemap above could be replaced with the following:</P>
27294 <DIV class="code">
27295 <PRE>
27296 %typemap(javain, pre=&quot;    $module.CheckForNaN($javainput);&quot;) float &quot;$javainput&quot;
27297 </PRE>
27298 </DIV>
27299 <P> which would modify the <TT>calculate</TT> function to instead be
27300  generated as:</P>
27301 <DIV class="code">
27302 <PRE>
27303 public class example {
27304   ...
27305   public static boolean calculate(float first, float second) {
27306     example.CheckForNaN(first);
27307     example.CheckForNaN(second);
27308     {
27309       return exampleJNI.calculate(first, second);
27310     }
27311   }
27312 }
27313 </PRE>
27314 </DIV>
27315 <P> See the <A href="#java_date_marshalling">Date marshalling example</A>
27316  for an example using further &quot;javain&quot; typemap attributes.</P>
27317 <P> If we decide that what we actually want is a checked exception
27318  instead of a runtime exception, we can change this easily enough. The
27319  proxy method that uses <TT>float</TT> as an input, must then add the
27320  exception class to the throws clause. SWIG can handle this as it
27321  supports the 'throws' <A href="#typemap_attributes">typemap attribute</A>
27322  for specifying classes for the throws clause. Thus we can modify the
27323  pragma and the typemap for the throws clause:</P>
27324 <DIV class="code">
27325 <PRE>
27326 %typemap(javain, throws=&quot;java.lang.Exception&quot;) float &quot;$module.CheckForNaN($javainput)&quot;
27327 %pragma(java) modulecode=%{
27328   /** Simply returns the input value unless it is not a number,
27329       whereupon an exception is thrown. */
27330   static protected float CheckForNaN(float num) throws java.lang.Exception {
27331     if (Float.isNaN(num))
27332       throw new RuntimeException(&quot;Not a number&quot;);
27333     return num;
27334   }
27335 %}
27336 </PRE>
27337 </DIV>
27338 <P> The <TT>calculate</TT> method now has a throws clause and even
27339  though the typemap is used twice for both <TT>float first</TT> and <TT>
27340 float second</TT>, the throws clause contains a single instance of <TT>
27341 java.lang.Exception</TT>:</P>
27342 <DIV class="code">
27343 <PRE>
27344 public class example {
27345   ...
27346
27347   /** Simply returns the input value unless it is not a number,
27348       whereupon an exception is thrown. */
27349   static protected float CheckForNaN(float num) throws java.lang.Exception {
27350     if (Float.isNaN(num))
27351       throw new RuntimeException(&quot;Not a number&quot;);
27352     return num;
27353   }
27354
27355   public static boolean calculate(float first, float second) throws java.lang.Exception {
27356     return exampleJNI.calculate(example.CheckForNaN(first), example.CheckForNaN(second));
27357   }
27358 }
27359 </PRE>
27360 </DIV>
27361 <P> If we were a martyr to the JNI cause, we could replace the succinct
27362  code within the &quot;javain&quot; typemap with a few pages of JNI code. If we
27363  had, we would have put it in the &quot;in&quot; typemap which, like all JNI and
27364  Java typemaps, also supports the 'throws' attribute.</P>
27365 <H3><A name="converting_java_string_arrays"></A>21.10.4 Converting Java
27366  String arrays to char **</H3>
27367 <P> A common problem in many C programs is the processing of command
27368  line arguments, which are usually passed in an array of NULL terminated
27369  strings. The following SWIG interface file allows a Java String array
27370  to be used as a <TT>char **</TT> object.</P>
27371 <DIV class="code">
27372 <PRE>
27373 %module example
27374
27375 /* This tells SWIG to treat char ** as a special case when used as a parameter
27376    in a function call */
27377 %typemap(in) char ** (jint size) {
27378     int i = 0;
27379     size = (*jenv)-&gt;GetArrayLength(jenv, $input);
27380     $1 = (char **) malloc((size+1)*sizeof(char *));
27381     /* make a copy of each string */
27382     for (i = 0; i&lt;size; i++) {
27383         jstring j_string = (jstring)(*jenv)-&gt;GetObjectArrayElement(jenv, $input, i);
27384         const char * c_string = (*jenv)-&gt;GetStringUTFChars(jenv, j_string, 0);
27385         $1[i] = malloc((strlen(c_string)+1)*sizeof(char));
27386         strcpy($1[i], c_string);
27387         (*jenv)-&gt;ReleaseStringUTFChars(jenv, j_string, c_string);
27388         (*jenv)-&gt;DeleteLocalRef(jenv, j_string);
27389     }
27390     $1[i] = 0;
27391 }
27392
27393 /* This cleans up the memory we malloc'd before the function call */
27394 %typemap(freearg) char ** {
27395     int i;
27396     for (i=0; i&lt;size$argnum-1; i++)
27397       free($1[i]);
27398     free($1);
27399 }
27400
27401 /* This allows a C function to return a char ** as a Java String array */
27402 %typemap(out) char ** {
27403     int i;
27404     int len=0;
27405     jstring temp_string;
27406     const jclass clazz = (*jenv)-&gt;FindClass(jenv, &quot;java/lang/String&quot;);
27407
27408     while ($1[len]) len++;    
27409     jresult = (*jenv)-&gt;NewObjectArray(jenv, len, clazz, NULL);
27410     /* exception checking omitted */
27411
27412     for (i=0; i&lt;len; i++) {
27413       temp_string = (*jenv)-&gt;NewStringUTF(jenv, *result++);
27414       (*jenv)-&gt;SetObjectArrayElement(jenv, jresult, i, temp_string);
27415       (*jenv)-&gt;DeleteLocalRef(jenv, temp_string);
27416     }
27417 }
27418
27419 /* These 3 typemaps tell SWIG what JNI and Java types to use */
27420 %typemap(jni) char ** &quot;jobjectArray&quot;
27421 %typemap(jtype) char ** &quot;String[]&quot;
27422 %typemap(jstype) char ** &quot;String[]&quot;
27423
27424 /* These 2 typemaps handle the conversion of the jtype to jstype typemap type
27425    and vice versa */
27426 %typemap(javain) char ** &quot;$javainput&quot;
27427 %typemap(javaout) char ** {
27428     return $jnicall;
27429   }
27430
27431 /* Now a few test functions */
27432 %inline %{
27433
27434 int print_args(char **argv) {
27435     int i = 0;
27436     while (argv[i]) {
27437          printf(&quot;argv[%d] = %s\n&quot;, i, argv[i]);
27438          i++;
27439     }
27440     return i;
27441 }
27442
27443 char **get_args() {
27444   static char *values[] = { &quot;Dave&quot;, &quot;Mike&quot;, &quot;Susan&quot;, &quot;John&quot;, &quot;Michelle&quot;, 0};
27445   return &amp;values[0];
27446 }
27447
27448 %}
27449 </PRE>
27450 </DIV>
27451 <P> Note that the 'C' JNI calling convention is used. Checking for any
27452  thrown exceptions after JNI function calls has been omitted. When this
27453  module is compiled, our wrapped C functions can be used by the
27454  following Java program:</P>
27455 <DIV class="code">
27456 <PRE>
27457 // File runme.java
27458
27459 public class runme {
27460
27461   static {
27462     try {
27463 &nbsp;    System.loadLibrary(&quot;example&quot;);
27464     } catch (UnsatisfiedLinkError e) {
27465       System.err.println(&quot;Native code library failed to load. &quot; + e);
27466       System.exit(1);
27467     }
27468   }
27469
27470   public static void main(String argv[]) {
27471     String animals[] = {&quot;Cat&quot;,&quot;Dog&quot;,&quot;Cow&quot;,&quot;Goat&quot;};
27472     example.print_args(animals);
27473     String args[] = example.get_args();
27474     for (int i=0; i&lt;args.length; i++)
27475         System.out.println(i + &quot;:&quot; + args[i]);
27476   }
27477 }
27478 </PRE>
27479 </DIV>
27480 <P> When compiled and run we get:</P>
27481 <DIV class="code">
27482 <PRE>
27483 $ java runme
27484 argv[0] = Cat
27485 argv[1] = Dog
27486 argv[2] = Cow
27487 argv[3] = Goat
27488 0:Dave
27489 1:Mike
27490 2:Susan
27491 3:John
27492 4:Michelle
27493 </PRE>
27494 </DIV>
27495 <P> In the example, a few different typemaps are used. The &quot;in&quot; typemap
27496  is used to receive an input argument and convert it to a C array. Since
27497  dynamic memory allocation is used to allocate memory for the array, the
27498  &quot;freearg&quot; typemap is used to later release this memory after the
27499  execution of the C function. The &quot;out&quot; typemap is used for function
27500  return values. Lastly the &quot;jni&quot;, &quot;jtype&quot; and &quot;jstype&quot; typemaps are also
27501  required to specify what Java types to use.</P>
27502 <H3><A name="expanding_java_object"></A>21.10.5 Expanding a Java object
27503  to multiple arguments</H3>
27504 <P> Suppose that you had a collection of C functions with arguments such
27505  as the following:</P>
27506 <DIV class="code">
27507 <PRE>
27508 int foo(int argc, char **argv);
27509 </PRE>
27510 </DIV>
27511 <P> In the previous example, a typemap was written to pass a Java String
27512  array as the <TT>char **argv</TT>. This allows the function to be used
27513  from Java as follows:</P>
27514 <DIV class="code">
27515 <PRE>
27516 example.foo(4, new String[]{&quot;red&quot;, &quot;green&quot;, &quot;blue&quot;, &quot;white&quot;});
27517 </PRE>
27518 </DIV>
27519 <P> Although this works, it's a little awkward to specify the argument
27520  count. To fix this, a multi-argument typemap can be defined. This is
27521  not very difficult--you only have to make slight modifications to the
27522  previous example's typemaps:</P>
27523 <DIV class="code">
27524 <PRE>
27525 %typemap(in) (int argc, char **argv) {
27526     int i = 0;
27527     $1 = (*jenv)-&gt;GetArrayLength(jenv, $input);
27528     $2 = (char **) malloc(($1+1)*sizeof(char *));
27529     /* make a copy of each string */
27530     for (i = 0; i&lt;$1; i++) {
27531         jstring j_string = (jstring)(*jenv)-&gt;GetObjectArrayElement(jenv, $input, i);
27532         const char * c_string = (*jenv)-&gt;GetStringUTFChars(jenv, j_string, 0);
27533         $2[i] = malloc((strlen(c_string)+1)*sizeof(char));
27534         strcpy($2[i], c_string);
27535         (*jenv)-&gt;ReleaseStringUTFChars(jenv, j_string, c_string);
27536         (*jenv)-&gt;DeleteLocalRef(jenv, j_string);
27537     }
27538     $2[i] = 0;
27539 }
27540
27541 %typemap(freearg) (int argc, char **argv) {
27542     int i;
27543     for (i=0; i&lt;$1-1; i++)
27544       free($2[i]);
27545     free($2);
27546 }
27547
27548 %typemap(jni) (int argc, char **argv) &quot;jobjectArray&quot;
27549 %typemap(jtype) (int argc, char **argv) &quot;String[]&quot;
27550 %typemap(jstype) (int argc, char **argv) &quot;String[]&quot;
27551
27552 %typemap(javain) (int argc, char **argv) &quot;$javainput&quot;
27553 </PRE>
27554 </DIV>
27555 <P> When writing a multiple-argument typemap, each of the types is
27556  referenced by a variable such as <TT>$1</TT> or <TT>$2</TT>. The
27557  typemap code simply fills in the appropriate values from the supplied
27558  Java parameter.</P>
27559 <P> With the above typemap in place, you will find it no longer
27560  necessary to supply the argument count. This is automatically set by
27561  the typemap code. For example:</P>
27562 <DIV class="code">
27563 <PRE>
27564 example.foo(new String[]{&quot;red&quot;, &quot;green&quot;, &quot;blue&quot;, &quot;white&quot;});
27565 </PRE>
27566 </DIV>
27567 <H3><A name="using_typemaps_return_arguments"></A>21.10.6 Using typemaps
27568  to return arguments</H3>
27569 <P> A common problem in some C programs is that values may be returned
27570  in function parameters rather than in the return value of a function.
27571  The <TT>typemaps.i</TT> file defines INPUT, OUTPUT and INOUT typemaps
27572  which can be used to solve some instances of this problem. This library
27573  file uses an array as a means of moving data to and from Java when
27574  wrapping a C function that takes non const pointers or non const
27575  references as parameters.</P>
27576 <P> Now we are going to outline an alternative approach to using arrays
27577  for C pointers. The INOUT typemap uses a <TT>double[]</TT> array for
27578  receiving and returning the <TT>double*</TT> parameters. In this
27579  approach we are able to use a Java class <TT>myDouble</TT> instead of <TT>
27580 double[]</TT> arrays where the C pointer <TT>double*</TT> is required.</P>
27581 <P> Here is our example function:</P>
27582 <DIV class="code">
27583 <PRE>
27584 /* Returns a status value and two values in out1 and out2 */
27585 int spam(double a, double b, double *out1, double *out2);
27586 </PRE>
27587 </DIV>
27588 <P> If we define a structure <TT>MyDouble</TT> containing a <TT>double</TT>
27589  member variable and use some typemaps we can solve this problem. For
27590  example we could put the following through SWIG:</P>
27591 <DIV class="code">
27592 <PRE>
27593 %module example
27594
27595 /* Define a new structure to use instead of double * */
27596 %inline %{
27597 typedef struct {
27598     double value;
27599 } MyDouble;
27600 %}
27601
27602
27603 %{
27604 /* Returns a status value and two values in out1 and out2 */
27605 int spam(double a, double b, double *out1, double *out2) {
27606   int status = 1;
27607   *out1 = a*10.0;
27608   *out2 = b*100.0;
27609   return status;
27610 };
27611 %}
27612
27613 /* 
27614 This typemap will make any double * function parameters with name <TT>OUTVALUE</TT> take an
27615 argument of MyDouble instead of double *. This will 
27616 allow the calling function to read the double * value after returning from the function.
27617 */
27618 %typemap(in) double *OUTVALUE {
27619     jclass clazz = jenv-&gt;FindClass(&quot;MyDouble&quot;);
27620     jfieldID fid = jenv-&gt;GetFieldID(clazz, &quot;swigCPtr&quot;, &quot;J&quot;);
27621     jlong cPtr = jenv-&gt;GetLongField($input, fid);
27622     MyDouble *pMyDouble = NULL;
27623     *(MyDouble **)&amp;pMyDouble = *(MyDouble **)&amp;cPtr;
27624     $1 = &amp;pMyDouble-&gt;value;
27625 }
27626
27627 %typemap(jtype) double *OUTVALUE &quot;MyDouble&quot;
27628 %typemap(jstype) double *OUTVALUE &quot;MyDouble&quot;
27629 %typemap(jni) double *OUTVALUE &quot;jobject&quot;
27630
27631 %typemap(javain) double *OUTVALUE &quot;$javainput&quot;
27632
27633 /* Now we apply the typemap to the named variables */
27634 %apply double *OUTVALUE { double *out1, double *out2 };
27635 int spam(double a, double b, double *out1, double *out2);
27636 </PRE>
27637 </DIV>
27638 <P> Note that the C++ JNI calling convention has been used this time and
27639  so must be compiled as C++ and the -c++ commandline must be passed to
27640  SWIG. JNI error checking has been omitted for clarity.</P>
27641 <P> What the typemaps do are make the named <TT>double*</TT> function
27642  parameters use our new <TT>MyDouble</TT> wrapper structure. The &quot;in&quot;
27643  typemap takes this structure, gets the C++ pointer to it, takes the <TT>
27644 double value</TT> member variable and passes it to the C++ <TT>spam</TT>
27645  function. In Java, when the function returns, we use the SWIG created <TT>
27646 getValue()</TT> function to get the output value. The following Java
27647  program demonstrates this:</P>
27648 <DIV class="code">
27649 <PRE>
27650 // File: runme.java
27651
27652 public class runme {
27653
27654   static {
27655     try {
27656 &nbsp;     System.loadLibrary(&quot;example&quot;);
27657     } catch (UnsatisfiedLinkError e) {
27658       System.err.println(&quot;Native code library failed to load. &quot; + e);
27659       System.exit(1);
27660     }
27661   }
27662
27663   public static void main(String argv[]) {
27664     MyDouble out1 = new MyDouble();
27665     MyDouble out2 = new MyDouble();
27666     int ret = example.spam(1.2, 3.4, out1, out2);
27667     System.out.println(ret + &quot;  &quot; + out1.getValue() + &quot;  &quot; + out2.getValue());
27668   }
27669 }
27670 </PRE>
27671 </DIV>
27672 <P> When compiled and run we get:</P>
27673 <DIV class="code">
27674 <PRE>
27675 $ java runme
27676 1 12.0  340.0
27677 </PRE>
27678 </DIV>
27679 <H3><A name="adding_downcasts"></A>21.10.7 Adding Java downcasts to
27680  polymorphic return types</H3>
27681 <P> SWIG support for polymorphism works in that the appropriate virtual
27682  function is called. However, the default generated code does not allow
27683  for downcasting. Let's examine this with the following code:</P>
27684 <DIV class="code">
27685 <PRE>
27686 %include &quot;std_string.i&quot;
27687
27688 #include &lt;iostream&gt;
27689 using namespace std;
27690 class Vehicle {
27691 public:
27692     virtual void start() = 0;
27693 ...
27694 };
27695
27696 class Ambulance : public Vehicle {
27697     string vol;
27698 public:
27699     Ambulance(string volume) : vol(volume) {}
27700     virtual void start() {
27701         cout &lt;&lt; &quot;Ambulance started&quot; &lt;&lt; endl;
27702     }
27703     void sound_siren() {
27704         cout &lt;&lt; vol &lt;&lt; &quot; siren sounded!&quot; &lt;&lt; endl;
27705     }
27706 ...
27707 };
27708
27709 Vehicle *vehicle_factory() {
27710     return new Ambulance(&quot;Very loud&quot;);
27711 }
27712 </PRE>
27713 </DIV>
27714 <P> If we execute the following Java code:</P>
27715 <DIV class="code">
27716 <PRE>
27717 Vehicle vehicle = example.vehicle_factory();
27718 vehicle.start();
27719
27720 Ambulance ambulance = (Ambulance)vehicle;
27721 ambulance.sound_siren();
27722 </PRE>
27723 </DIV>
27724 <P> We get:</P>
27725 <DIV class="code">
27726 <PRE>
27727 Ambulance started
27728 java.lang.ClassCastException
27729         at runme.main(runme.java:16)
27730 </PRE>
27731 </DIV>
27732 <P> Even though we know from examination of the C++ code that <TT>
27733 vehicle_factory</TT> returns an object of type <TT>Ambulance</TT>, we
27734  are not able to use this knowledge to perform the downcast in Java.
27735  This occurs because the runtime type information is not completely
27736  passed from C++ to Java when returning the type from <TT>
27737 vehicle_factory()</TT>. Usually this is not a problem as virtual
27738  functions do work by default, such as in the case of <TT>start()</TT>.
27739  There are a few solutions to getting downcasts to work.</P>
27740 <P> The first is not to use a Java cast but a call to C++ to make the
27741  cast. Add this to your code:</P>
27742 <DIV class="code">
27743 <PRE>
27744 %exception Ambulance::dynamic_cast(Vehicle *vehicle) {
27745     $action
27746     if (!result) {
27747         jclass excep = jenv-&gt;FindClass(&quot;java/lang/ClassCastException&quot;);
27748         if (excep) {
27749             jenv-&gt;ThrowNew(excep, &quot;dynamic_cast exception&quot;);
27750         }
27751     }
27752 }
27753 %extend Ambulance {
27754     static Ambulance *dynamic_cast(Vehicle *vehicle) {
27755         return dynamic_cast&lt;Ambulance *&gt;(vehicle);
27756     }
27757 };
27758 </PRE>
27759 </DIV>
27760 <P> It would then be used from Java like this</P>
27761 <DIV class="code">
27762 <PRE>
27763 Ambulance ambulance = Ambulance.dynamic_cast(vehicle);
27764 ambulance.sound_siren();
27765 </PRE>
27766 </DIV>
27767 <P> Should <TT>vehicle</TT> not be of type <TT>ambulance</TT> then a
27768  Java <TT>ClassCastException</TT> is thrown. The next solution is a
27769  purer solution in that Java downcasts can be performed on the types.
27770  Add the following before the definition of <TT>vehicle_factory</TT>:</P>
27771 <DIV class="code">
27772 <PRE>
27773 %typemap(out) Vehicle * {
27774     Ambulance *downcast = dynamic_cast&lt;Ambulance *&gt;($1);
27775     *(Ambulance **)&amp;$result = downcast;
27776 }
27777
27778 %typemap(javaout) Vehicle * {
27779     return new Ambulance($jnicall, $owner);
27780   }
27781 </PRE>
27782 </DIV>
27783 <P> Here we are using our knowledge that <TT>vehicle_factory</TT> always
27784  returns type <TT>Ambulance</TT> so that the Java proxy is created as a
27785  type <TT>Ambulance</TT>. If <TT>vehicle_factory</TT> can manufacture
27786  any type of <TT>Vehicle</TT> and we want to be able to downcast using
27787  Java casts for any of these types, then a different approach is needed.
27788  Consider expanding our example with a new Vehicle type and a more
27789  flexible factory function:</P>
27790 <DIV class="code">
27791 <PRE>
27792 class FireEngine : public Vehicle {
27793 public:
27794     FireEngine() {}
27795     virtual void start() {
27796         cout &lt;&lt; &quot;FireEngine started&quot; &lt;&lt; endl;
27797     }
27798     void roll_out_hose() {
27799         cout &lt;&lt; &quot;Hose rolled out&quot; &lt;&lt; endl;
27800     }
27801  ...
27802 };
27803 Vehicle *vehicle_factory(int vehicle_number) {
27804     if (vehicle_number == 0)
27805         return new Ambulance(&quot;Very loud&quot;);
27806     else
27807         return new FireEngine();
27808 }
27809 </PRE>
27810 </DIV>
27811 <P> To be able to downcast with this sort of Java code:</P>
27812 <DIV class="code">
27813 <PRE>
27814 FireEngine fireengine = (FireEngine)example.vehicle_factory(1);
27815 fireengine.roll_out_hose();
27816 Ambulance ambulance = (Ambulance)example.vehicle_factory(0);
27817 ambulance.sound_siren();
27818 </PRE>
27819 </DIV>
27820 <P> the following typemaps targeted at the <TT>vehicle_factory</TT>
27821  function will achieve this. Note that in this case, the Java class is
27822  constructed using JNI code rather than passing a pointer across the JNI
27823  boundary in a Java long for construction in Java code.</P>
27824 <DIV class="code">
27825 <PRE>
27826 %typemap(jni) Vehicle *vehicle_factory &quot;jobject&quot;
27827 %typemap(jtype) Vehicle *vehicle_factory &quot;Vehicle&quot;
27828 %typemap(jstype) Vehicle *vehicle_factory &quot;Vehicle&quot;
27829 %typemap(javaout) Vehicle *vehicle_factory {
27830     return $jnicall;
27831   }
27832
27833 %typemap(out) Vehicle *vehicle_factory {
27834     Ambulance *ambulance = dynamic_cast&lt;Ambulance *&gt;($1);
27835     FireEngine *fireengine = dynamic_cast&lt;FireEngine *&gt;($1);
27836     if (ambulance) {
27837         // call the Ambulance(long cPtr, boolean cMemoryOwn) constructor
27838         jclass clazz = jenv-&gt;FindClass(&quot;Ambulance&quot;);
27839         if (clazz) {
27840             jmethodID mid = jenv-&gt;GetMethodID(clazz, &quot;&lt;init&gt;&quot;, &quot;(JZ)V&quot;);
27841             if (mid) {
27842                 jlong cptr = 0;
27843                 *(Ambulance **)&amp;cptr = ambulance; 
27844                 $result = jenv-&gt;NewObject(clazz, mid, cptr, false);
27845             }
27846         }
27847     } else if (fireengine) {
27848         // call the FireEngine(long cPtr, boolean cMemoryOwn) constructor
27849         jclass clazz = jenv-&gt;FindClass(&quot;FireEngine&quot;);
27850         if (clazz) {
27851             jmethodID mid = jenv-&gt;GetMethodID(clazz, &quot;&lt;init&gt;&quot;, &quot;(JZ)V&quot;);
27852             if (mid) {
27853                 jlong cptr = 0;
27854                 *(FireEngine **)&amp;cptr = fireengine; 
27855                 $result = jenv-&gt;NewObject(clazz, mid, cptr, false);
27856             }
27857         }
27858     }
27859     else {
27860         cout &lt;&lt; &quot;Unexpected type &quot; &lt;&lt; endl;
27861     }
27862
27863     if (!$result)
27864         cout &lt;&lt; &quot;Failed to create new java object&quot; &lt;&lt; endl;
27865 }
27866 </PRE>
27867 </DIV>
27868 <P> Better error handling would need to be added into this code. There
27869  are other solutions to this problem, but this last example demonstrates
27870  some more involved JNI code. SWIG usually generates code which
27871  constructs the proxy classes using Java code as it is easier to handle
27872  error conditions and is faster. Note that the JNI code above uses a
27873  number of string lookups to call a constructor, whereas this would not
27874  occur using byte compiled Java code.</P>
27875 <H3><A name="adding_equals_method"></A>21.10.8 Adding an equals method
27876  to the Java classes</H3>
27877 <P> When a pointer is returned from a JNI function, it is wrapped using
27878  a new Java proxy class or type wrapper class. Even when the pointers
27879  are the same, it will not be possible to know that the two Java classes
27880  containing those pointers are actually the same object. It is common in
27881  Java to use the <TT>equals()</TT> method to check whether two objects
27882  are equivalent. The <TT>equals()</TT> method is usually accompanied by
27883  a <TT>hashCode()</TT> method in order to fulfill the requirement that
27884  the hash code is equal for equal objects. Pure Java code methods like
27885  these can be easily added:</P>
27886 <DIV class="code">
27887 <PRE>
27888 %typemap(javacode) SWIGTYPE %{
27889   public boolean equals(Object obj) {
27890     boolean equal = false;
27891     if (obj instanceof $javaclassname)
27892       equal = ((($javaclassname)obj).swigCPtr == this.swigCPtr);
27893     return equal;
27894   }
27895   public int hashCode() {
27896      return (int)getPointer();
27897   }
27898 %}
27899
27900 class Foo { };
27901 Foo* returnFoo(Foo *foo) { return foo; }
27902 </PRE>
27903 </DIV>
27904 <P> The following would display <TT>false</TT> without the <TT>javacode</TT>
27905  typemap above. With the typemap defining the <TT>equals</TT> method the
27906  result is <TT>true</TT>.</P>
27907 <DIV class="code">
27908 <PRE>
27909 Foo foo1 = new Foo();
27910 Foo foo2 = example.returnFoo(foo1);
27911 System.out.println(&quot;foo1? &quot; + foo1.equals(foo2));
27912 </PRE>
27913 </DIV>
27914 <H3><A name="void_pointers"></A>21.10.9 Void pointers and a common Java
27915  base class</H3>
27916 <P> One might wonder why the common code that SWIG emits for the proxy
27917  and type wrapper classes is not pushed into a base class. The reason is
27918  that although <TT>swigCPtr</TT> could be put into a common base class
27919  for all classes wrapping C structures, it would not work for C++
27920  classes involved in an inheritance chain. Each class derived from a
27921  base needs a separate <TT>swigCPtr</TT> because C++ compilers sometimes
27922  use a different pointer value when casting a derived class to a base.
27923  Additionally as Java only supports single inheritance, it would not be
27924  possible to derive wrapped classes from your own pure Java classes if
27925  the base class has been 'used up' by SWIG. However, you may want to
27926  move some of the common code into a base class. Here is an example
27927  which uses a common base class for all proxy classes and type wrapper
27928  classes:</P>
27929 <DIV class="code">
27930 <PRE>
27931 %typemap(javabase) SWIGTYPE, SWIGTYPE *, SWIGTYPE &amp;, SWIGTYPE [], 
27932                                                          SWIGTYPE (CLASS::*) &quot;SWIG&quot;
27933
27934 %typemap(javacode) SWIGTYPE, SWIGTYPE *, SWIGTYPE &amp;, SWIGTYPE [], 
27935                                                          SWIGTYPE (CLASS::*) %{
27936   protected long getPointer() {
27937     return swigCPtr;
27938   }
27939 %}
27940 </PRE>
27941 </DIV>
27942 <P> Define new base class called SWIG:</P>
27943 <DIV class="code">
27944 <PRE>
27945 public abstract class SWIG {
27946   protected abstract long getPointer();
27947
27948   public boolean equals(Object obj) {
27949     boolean equal = false;
27950     if (obj instanceof SWIG)
27951       equal = (((SWIG)obj).getPointer() == this.getPointer());
27952     return equal;
27953   }
27954   
27955   SWIGTYPE_p_void getVoidPointer() {
27956     return new SWIGTYPE_p_void(getPointer(), false);
27957   }
27958 }
27959 </PRE>
27960 </DIV>
27961 <P> This example contains some useful functionality which you may want
27962  in your code.</P>
27963 <UL>
27964 <LI> It has an <TT>equals()</TT> method. Unlike the previous example,
27965  the method code isn't replicated in all classes.</LI>
27966 <LI> It also has a function which effectively implements a cast from the
27967  type of the proxy/type wrapper class to a void pointer. This is
27968  necessary for passing a proxy class or a type wrapper class to a
27969  function that takes a void pointer.</LI>
27970 </UL>
27971 <H3><A name="struct_pointer_pointer"></A>21.10.10 Struct pointer to
27972  pointer</H3>
27973 <P> Pointers to pointers are often used as output parameters in C
27974  factory type functions. These are a bit more tricky to handle. Consider
27975  the following situation where a <TT>Butler</TT> can be hired and fired:</P>
27976 <DIV class="code">
27977 <PRE>
27978 typedef struct {
27979   int hoursAvailable;
27980   char *greeting;
27981 } Butler;
27982
27983 // Note: HireButler will allocate the memory 
27984 // The caller must free the memory by calling FireButler()!!
27985 extern int HireButler(Butler **ppButler);
27986 extern void FireButler(Butler *pButler);
27987 </PRE>
27988 </DIV>
27989 <P> C code implementation:</P>
27990 <DIV class="code">
27991 <PRE>
27992 int HireButler(Butler **ppButler) {
27993   Butler *pButler = (Butler *)malloc(sizeof(Butler));
27994   pButler-&gt;hoursAvailable = 24;
27995   pButler-&gt;greeting = (char *)malloc(32);
27996   strcpy(pButler-&gt;greeting, &quot;At your service Sir&quot;);
27997   *ppButler = pButler;
27998   return 1;
27999 }
28000 void FireButler(Butler *pButler) {
28001   free(pButler-&gt;greeting);
28002   free(pButler);
28003 }
28004 </PRE>
28005 </DIV>
28006 <P> Let's take two approaches to wrapping this code. The first is to
28007  provide a functional interface, much like the original C interface. The
28008  following Java code shows how we intend the code to be used:</P>
28009 <DIV class="code">
28010 <PRE>
28011     Butler jeeves = new Butler();
28012     example.HireButler(jeeves);
28013     System.out.println(&quot;Greeting:     &quot; + jeeves.getGreeting());
28014     System.out.println(&quot;Availability: &quot; + jeeves.getHoursAvailable() + &quot; hours per day&quot;);
28015     example.FireButler(jeeves);
28016 </PRE>
28017 </DIV>
28018 <P> Resulting in the following output when run:</P>
28019 <DIV class="shell">
28020 <PRE>
28021 Greeting:     At your service Sir
28022 Availability: 24 hours per day
28023 </PRE>
28024 </DIV>
28025 <P> Note the usage is very much like it would be used if we were writing
28026  C code, that is, explicit memory management is needed. No C memory is
28027  allocated in the construction of the <TT>Butler</TT> proxy class and
28028  the proxy class will not destroy the underlying C memory when it is
28029  collected. A number of typemaps and features are needed to implement
28030  this approach. The following interface file code should be placed
28031  before SWIG parses the above C code.</P>
28032 <DIV class="code">
28033 <PRE>
28034 %module example
28035
28036 // Do not generate the default proxy constructor or destructor
28037 %nodefaultctor Butler;
28038 %nodefaultdtor Butler;
28039
28040 // Add in pure Java code proxy constructor
28041 %typemap(javacode) Butler %{
28042   /** This constructor creates the proxy which initially does not create nor own any C memory */
28043   public Butler() {
28044     this(0, false);
28045   }
28046 %}
28047
28048 // Type typemaps for marshalling Butler **
28049 %typemap(jni) Butler ** &quot;jobject&quot;
28050 %typemap(jtype) Butler ** &quot;Butler&quot;
28051 %typemap(jstype) Butler ** &quot;Butler&quot;
28052
28053 // Typemaps for Butler ** as a parameter output type
28054 %typemap(in) Butler ** (Butler *ppButler = 0) %{
28055   $1 = &amp;ppButler;
28056 %}
28057 %typemap(argout) Butler ** {
28058   // Give Java proxy the C pointer (of newly created object)
28059   jclass clazz = (*jenv)-&gt;FindClass(jenv, &quot;Butler&quot;);
28060   jfieldID fid = (*jenv)-&gt;GetFieldID(jenv, clazz, &quot;swigCPtr&quot;, &quot;J&quot;);
28061   jlong cPtr = 0;
28062   *(Butler **)&amp;cPtr = *$1;
28063   (*jenv)-&gt;SetLongField(jenv, $input, fid, cPtr);
28064 }
28065 %typemap(javain) Butler ** &quot;$javainput&quot;
28066 </PRE>
28067 </DIV>
28068 <P> Note that the JNI code sets the proxy's <TT>swigCPtr</TT> member
28069  variable to point to the newly created object. The <TT>swigCMemOwn</TT>
28070  remains unchanged (at false), so that the proxy does not own the
28071  memory.</P>
28072 <P> Note: The old %nodefault directive disabled the default constructor
28073  and destructor at the same time. This is unsafe in most of the cases,
28074  and you can use the explicit %nodefaultctor and %nodefaultdtor
28075  directives to achieve the same result if needed.</P>
28076 <P> The second approach offers a more object oriented interface to the
28077  Java user. We do this by making the Java proxy class's constructor call
28078  the <TT>HireButler()</TT> method to create the underlying C object.
28079  Additionally we get the proxy to take ownership of the memory so that
28080  the finalizer will call the <TT>FireButler()</TT> function. The proxy
28081  class will thus take ownership of the memory and clean it up when no
28082  longer needed. We will also prevent the user from being able to
28083  explicitly call the <TT>HireButler()</TT> and <TT>FireButler()</TT>
28084  functions. Usage from Java will simply be:</P>
28085 <DIV class="code">
28086 <PRE>
28087 Butler jeeves = new Butler();
28088 System.out.println(&quot;Greeting:     &quot; + jeeves.getGreeting());
28089 System.out.println(&quot;Availability: &quot; + jeeves.getHoursAvailable() + &quot; hours per day&quot;);
28090 </PRE>
28091 </DIV>
28092 <P> Note that the Butler class is used just like any other Java class
28093  and no extra coding by the user needs to be written to clear up the
28094  underlying C memory as the finalizer will be called by the garbage
28095  collector which in turn will call the <TT>FireButler()</TT> function.
28096  To implement this, we use the above interface file code but remove the <TT>
28097 javacode</TT> typemap and add the following:</P>
28098 <DIV class="code">
28099 <PRE>
28100 // Don't expose the memory allocation/de-allocation functions
28101 %ignore FireButler(Butler *pButler);
28102 %ignore HireButler(Butler **ppButler);
28103
28104 // Add in a custom proxy constructor and destructor
28105 %extend Butler {
28106   Butler() {
28107     Butler *pButler = 0;
28108     HireButler(&amp;pButler);
28109     return pButler;
28110   }
28111   ~Butler() {
28112      FireButler($self);
28113    }
28114 }
28115 </PRE>
28116 </DIV>
28117 <P> Note that the code in <TT>%extend</TT> is using a C++ type
28118  constructor and destructor, yet the generated code will still compile
28119  as C code, see <A href="#SWIG_adding_member_functions">Adding member
28120  functions to C structures</A>. The C functional interface has been
28121  completely morphed into an object-oriented interface and the Butler
28122  class would behave much like any pure Java class and feel more natural
28123  to Java users.</P>
28124 <H3><A name="java_memory_management_member_variables"></A>21.10.11
28125  Memory management when returning references to member variables</H3>
28126 <P> This example shows how to prevent premature garbage collection of
28127  objects when the underlying C++ class returns a pointer or reference to
28128  a member variable.</P>
28129 <P> Consider the following C++ code:</P>
28130 <DIV class="code">
28131 <PRE>
28132 struct Wheel {
28133   int size;
28134   Wheel(int sz) : size(sz) {}
28135 };
28136
28137 class Bike {
28138   Wheel wheel;
28139 public:
28140   Bike(int val) : wheel(val) {}
28141   Wheel&amp; getWheel() { return wheel; }
28142 };
28143 </PRE>
28144 </DIV>
28145 <P> and the following usage from Java after running the code through
28146  SWIG:</P>
28147 <DIV class="code">
28148 <PRE>
28149     Wheel wheel = new Bike(10).getWheel();
28150     System.out.println(&quot;wheel size: &quot; + wheel.getSize());
28151     // Simulate a garbage collection
28152     System.gc();
28153     System.runFinalization();
28154     System.out.println(&quot;wheel size: &quot; + wheel.getSize());
28155 </PRE>
28156 </DIV>
28157 <P> Don't be surprised that if the resulting output gives strange
28158  results such as...</P>
28159 <DIV class="shell">
28160 <PRE>
28161 wheel size: 10
28162 wheel size: 135019664
28163 </PRE>
28164 </DIV>
28165 <P> What has happened here is the garbage collector has collected the <TT>
28166 Bike</TT> instance as it doesn't think it is needed any more. The proxy
28167  instance, <TT>wheel</TT>, contains a reference to memory that was
28168  deleted when the <TT>Bike</TT> instance was collected. In order to
28169  prevent the garbage collector from collecting the <TT>Bike</TT>
28170  instance a reference to the <TT>Bike</TT> must be added to the <TT>
28171 wheel</TT> instance. You can do this by adding the reference when the <TT>
28172 getWheel()</TT> method is called using the following typemaps.</P>
28173 <DIV class="code">
28174 <PRE>
28175 %typemap(javacode) Wheel %{
28176   // Ensure that the GC doesn't collect any Bike instance set from Java
28177   private Bike bikeReference;
28178   protected void addReference(Bike bike) {
28179     bikeReference = bike;
28180   }
28181 %}
28182
28183 // Add a Java reference to prevent premature garbage collection and resulting use
28184 // of dangling C++ pointer. Intended for methods that return pointers or
28185 // references to a member variable.
28186 %typemap(javaout) Wheel&amp; getWheel {
28187     long cPtr = $jnicall;
28188     $javaclassname ret = null;
28189     if (cPtr != 0) {
28190       ret = new $javaclassname(cPtr, $owner);
28191       ret.addReference(this);
28192     }
28193     return ret;
28194   }
28195 </PRE>
28196 </DIV>
28197 <P> The code in the first typemap gets added to the <TT>Wheel</TT> proxy
28198  class. The code in the second typemap constitutes the bulk of the code
28199  in the generated <TT>getWheel()</TT> function:</P>
28200 <DIV class="code">
28201 <PRE>
28202 public class Wheel {
28203   ...
28204   // Ensure that the GC doesn't collect any bike set from Java 
28205   private Bike bikeReference;
28206   protected void addReference(Bike bike) {
28207     bikeReference = bike;
28208   }
28209 }
28210
28211 public class Bike {
28212   ...
28213   public Wheel getWheel() {
28214     long cPtr = exampleJNI.Bike_getWheel(swigCPtr, this);
28215     Wheel ret = null;
28216     if (cPtr != 0) {
28217       ret = new Wheel(cPtr, false);
28218       ret.addReference(this);
28219     }
28220     return ret;
28221   }
28222 }
28223 </PRE>
28224 </DIV>
28225 <P> Note the <TT>addReference</TT> call.</P>
28226 <H3><A name="java_memory_management_objects"></A>21.10.12 Memory
28227  management for objects passed to the C++ layer</H3>
28228 <P> Managing memory can be tricky when using C++ and Java proxy classes.
28229  The previous example shows one such case and this example looks at
28230  memory management for a class passed to a C++ method which expects the
28231  object to remain in scope after the function has returned. Consider the
28232  following two C++ classes:</P>
28233 <DIV class="code">
28234 <PRE>
28235 struct Element {
28236   int value;
28237   Element(int val) : value(val) {}
28238 };
28239 class Container {
28240   Element* element;
28241 public:
28242   Container() : element(0) {}
28243   void setElement(Element* e) { element = e; }
28244   Element* getElement() { return element; }
28245 };
28246 </PRE>
28247 </DIV>
28248 <P> and usage from C++</P>
28249 <DIV class="code">
28250 <PRE>
28251     Container container;
28252     Element element(20);
28253     container.setElement(&amp;element);
28254     cout &lt;&lt; &quot;element.value: &quot; &lt;&lt; container.getElement()-&gt;value &lt;&lt; endl;
28255 </PRE>
28256 </DIV>
28257 <P> and more or less equivalent usage from Java</P>
28258 <DIV class="code">
28259 <PRE>
28260     Container container = new Container();
28261     container.setElement(new Element(20));
28262     System.out.println(&quot;element value: &quot; + container.getElement().getValue());
28263 </PRE>
28264 </DIV>
28265 <P> The C++ code will always print out 20, but the value printed out may
28266  not be this in the Java equivalent code. In order to understand why,
28267  consider a garbage collection occuring...</P>
28268 <DIV class="code">
28269 <PRE>
28270     Container container = new Container();
28271     container.setElement(new Element(20));
28272     // Simulate a garbage collection
28273     System.gc();
28274     System.runFinalization();
28275     System.out.println(&quot;element value: &quot; + container.getElement().getValue());
28276 </PRE>
28277 </DIV>
28278 <P> The temporary element created with <TT>new Element(20)</TT> could
28279  get garbage collected which ultimately means the <TT>container</TT>
28280  variable is holding a dangling pointer, thereby printing out any old
28281  random value instead of the expected value of 20. One solution is to
28282  add in the appropriate references in the Java layer...</P>
28283 <DIV class="code">
28284 <PRE>
28285 public class Container {
28286
28287   ...
28288
28289   // Ensure that the GC doesn't collect any Element set from Java
28290   // as the underlying C++ class stores a shallow copy
28291   private Element elementReference;
28292   private long getCPtrAndAddReference(Element element) {
28293     elementReference = element;
28294     return Element.getCPtr(element);
28295   }
28296
28297   public void setElement(Element e) {
28298     exampleJNI.Container_setElement(swigCPtr, this, getCPtrAndAddReference(e), e);
28299   }
28300 }
28301 </PRE>
28302 </DIV>
28303 <P> The following typemaps will generate the desired code. The 'javain'
28304  typemap matches the input parameter type for the <TT>setElement</TT>
28305  method. The 'javacode' typemap simply adds in the specified code into
28306  the Java proxy class.</P>
28307 <DIV class="code">
28308 <PRE>
28309 %typemap(javain) Element *e &quot;getCPtrAndAddReference($javainput)&quot;
28310
28311 %typemap(javacode) Container %{
28312   // Ensure that the GC doesn't collect any element set from Java
28313   // as the underlying C++ class stores a shallow copy
28314   private Element elementReference;
28315   private long getCPtrAndAddReference(Element element) {
28316     elementReference = element;
28317     return Element.getCPtr(element);
28318   }
28319 %}
28320 </PRE>
28321 </DIV>
28322 <H3><A name="java_date_marshalling"></A>21.10.13 Date marshalling using
28323  the javain typemap and associated attributes</H3>
28324 <P> The <A href="#nan_exception_typemap">NaN Exception example</A> is a
28325  simple example of the &quot;javain&quot; typemap and its 'pre' attribute. This
28326  example demonstrates how a C++ date class, say <TT>CDate</TT>, can be
28327  mapped onto the standard Java date class, <TT>
28328 java.util.GregorianCalendar</TT> by using the 'pre', 'post' and
28329  'pgcppname' attributes of the &quot;javain&quot; typemap. The idea is that the <TT>
28330 GregorianCalendar</TT> is used wherever the C++ API uses a <TT>CDate</TT>
28331 . Let's assume the code being wrapped is as follows:</P>
28332 <DIV class="code">
28333 <PRE>
28334 class CDate {
28335 public:
28336   CDate(int year, int month, int day);
28337   int getYear();
28338   int getMonth();
28339   int getDay();
28340   ...
28341 };
28342 struct Action {
28343   static int doSomething(const CDate &amp;dateIn, CDate &amp;dateOut);
28344   Action(const CDate &amp;date, CDate &amp;dateOut);
28345 };
28346 </PRE>
28347 </DIV>
28348 <P> Note that <TT>dateIn</TT> is const and therefore read only and <TT>
28349 dateOut</TT> is a non-const output type.</P>
28350 <P> First let's look at the code that is generated by default, where the
28351  Java proxy class <TT>CDate</TT> is used in the proxy interface:</P>
28352 <DIV class="code">
28353 <PRE>
28354 public class Action {
28355   ...
28356   public static int doSomething(CDate dateIn, CDate dateOut) {
28357     return exampleJNI.Action_doSomething(CDate.getCPtr(dateIn), dateIn, 
28358                                          CDate.getCPtr(dateOut), dateOut);
28359   }
28360
28361   public Action(CDate date, CDate dateOut) {
28362     this(exampleJNI.new_Action(CDate.getCPtr(date), date, 
28363                                CDate.getCPtr(dateOut), dateOut), true);
28364   }
28365 }
28366 </PRE>
28367 </DIV>
28368 <P> The <TT>CDate &amp;</TT> and <TT>const CDate &amp;</TT> Java code is
28369  generated from the following two default typemaps:</P>
28370 <DIV class="code">
28371 <PRE>
28372 %typemap(jstype) SWIGTYPE &amp; &quot;$javaclassname&quot;
28373 %typemap(javain) SWIGTYPE &amp; &quot;$javaclassname.getCPtr($javainput)&quot;
28374 </PRE>
28375 </DIV>
28376 <P> where '$javaclassname' is translated into the proxy class name, <TT>
28377 CDate</TT> and '$javainput' is translated into the name of the
28378  parameter, eg <TT>dateIn</TT>. From Java, the intention is then to call
28379  into a modifed API with something like:</P>
28380 <DIV class="code">
28381 <PRE>
28382 java.util.GregorianCalendar calendarIn = 
28383     new java.util.GregorianCalendar(2011, java.util.Calendar.APRIL, 13, 0, 0, 0);
28384 java.util.GregorianCalendar calendarOut = new java.util.GregorianCalendar();
28385
28386 // Note in calls below, calendarIn remains unchanged and calendarOut 
28387 // is set to a new value by the C++ call
28388 Action.doSomething(calendarIn, calendarOut);
28389 Action action = new Action(calendarIn, calendarOut);
28390 </PRE>
28391 </DIV>
28392 <P> To achieve this mapping, we need to alter the default code
28393  generation slightly so that at the Java layer, a <TT>GregorianCalendar</TT>
28394  is converted into a <TT>CDate</TT>. The JNI intermediary layer will
28395  still take a pointer to the underlying <TT>CDate</TT> class. The
28396  typemaps to achieve this are shown below.</P>
28397 <DIV class="code">
28398 <PRE>
28399 %typemap(jstype) const CDate&amp; &quot;java.util.GregorianCalendar&quot;
28400 %typemap(javain, 
28401          pre=&quot;    CDate temp$javainput = new CDate($javainput.get(java.util.Calendar.YEAR), &quot;
28402              &quot;$javainput.get(java.util.Calendar.MONTH), $javainput.get(java.util.Calendar.DATE));&quot;, 
28403          pgcppname=&quot;temp$javainput&quot;) const CDate &amp;
28404          &quot;$javaclassname.getCPtr(temp$javainput)&quot;
28405
28406 %typemap(jstype) CDate&amp; &quot;java.util.Calendar&quot;
28407 %typemap(javain, 
28408          pre=&quot;    CDate temp$javainput = new CDate($javainput.get(java.util.Calendar.YEAR), &quot;
28409              &quot;$javainput.get(java.util.Calendar.MONTH), $javainput.get(java.util.Calendar.DATE));&quot;, 
28410          post=&quot;      $javainput.set(temp$javainput.getYear(), temp$javainput.getMonth(), &quot;
28411               &quot;temp$javainput.getDay(), 0, 0, 0);&quot;, 
28412          pgcppname=&quot;temp$javainput&quot;) CDate &amp;
28413          &quot;$javaclassname.getCPtr(temp$javainput)&quot;
28414 </PRE>
28415 </DIV>
28416 <P> The resulting generated proxy code in the <TT>Action</TT> class
28417  follows:</P>
28418 <DIV class="code">
28419 <PRE>
28420 public class Action {
28421   ...
28422   public static int doSomething(java.util.GregorianCalendar dateIn, 
28423                                 java.util.Calendar dateOut) {
28424     CDate tempdateIn = new CDate(dateIn.get(java.util.Calendar.YEAR), 
28425                                  dateIn.get(java.util.Calendar.MONTH), 
28426                                  dateIn.get(java.util.Calendar.DATE));
28427     CDate tempdateOut = new CDate(dateOut.get(java.util.Calendar.YEAR), 
28428                                   dateOut.get(java.util.Calendar.MONTH), 
28429                                   dateOut.get(java.util.Calendar.DATE));
28430     try {
28431       return exampleJNI.Action_doSomething(CDate.getCPtr(tempdateIn), tempdateIn, 
28432                                            CDate.getCPtr(tempdateOut), tempdateOut);
28433     } finally {
28434       dateOut.set(tempdateOut.getYear(), tempdateOut.getMonth(), tempdateOut.getDay(), 0, 0, 0);
28435     }
28436   }
28437
28438   static private long SwigConstructAction(java.util.GregorianCalendar date, 
28439                                           java.util.Calendar dateOut) {
28440     CDate tempdate = new CDate(date.get(java.util.Calendar.YEAR), 
28441                                date.get(java.util.Calendar.MONTH), 
28442                                date.get(java.util.Calendar.DATE));
28443     CDate tempdateOut = new CDate(dateOut.get(java.util.Calendar.YEAR), 
28444                                   dateOut.get(java.util.Calendar.MONTH), 
28445                                   dateOut.get(java.util.Calendar.DATE));
28446     try {
28447       return exampleJNI.new_Action(CDate.getCPtr(tempdate), tempdate, 
28448                                    CDate.getCPtr(tempdateOut), tempdateOut);
28449     } finally {
28450       dateOut.set(tempdateOut.getYear(), tempdateOut.getMonth(), tempdateOut.getDay(), 0, 0, 0);
28451     }
28452   }
28453
28454   public Action(java.util.GregorianCalendar date, java.util.Calendar dateOut) {
28455     this(Action.SwigConstructAction(date, dateOut), true);
28456   }
28457 }
28458 </PRE>
28459 </DIV>
28460 <P> A few things to note:</P>
28461 <UL>
28462 <LI> The &quot;javatype&quot; typemap has changed the parameter type to <TT>
28463 java.util.GregorianCalendar</TT> or <TT>java.util.Calendar</TT> instead
28464  of the default generated <TT>CDate</TT> proxy.</LI>
28465 <LI> The code in the 'pre' attribute appears before the JNI call (<TT>
28466 exampleJNI.new_Action</TT> / <TT>exampleJNI.Action_doSomething</TT>).</LI>
28467 <LI> The code in the 'post' attribute appears after the JNI call.</LI>
28468 <LI> A try .. finally block is generated with the JNI call in the try
28469  block and 'post' code in the finally block. The alternative of just
28470  using a temporary variable for the return value from the JNI call and
28471  the 'post' code being generated before the return statement is not
28472  possible given that the JNI call is in one line and comes from the
28473  &quot;javaout&quot; typemap.</LI>
28474 <LI> The temporary variables in the &quot;javain&quot; typemaps are called <TT>
28475 temp$javain</TT>, where &quot;$javain&quot; is replaced with the parameter name.
28476  &quot;$javain&quot; is used to mangle the variable name so that more than one <TT>
28477 CDate &amp;</TT> type can be used as a parameter in a method, otherwise two
28478  or more local variables with the same name would be generated.</LI>
28479 <LI> The use of the &quot;javain&quot; typemap causes a constructor helper
28480  function (<TT>SwigConstructAction</TT>) to be generated. This allows
28481  Java code to be called before the JNI call and is required as the Java
28482  compiler won't compile code inserted before the 'this' call.</LI>
28483 <LI> The 'pgcppname' attribute is used to modify the object being passed
28484  as the <A href="#java_pgcpp">premature garbage collection prevention
28485  parameter</A> (the 2nd and 4th parameters in the JNI calls).</LI>
28486 </UL>
28487 <H2><A name="java_directors_faq"></A>21.11 Living with Java Directors</H2>
28488 <P> This section is intended to address frequently asked questions and
28489  frequently encountered problems when using Java directors.</P>
28490 <OL>
28491 <LI><I>When my program starts up, it complains that</I> method_foo<I>
28492  cannot be found in a Java method called</I> swig_module_init<I>. How do
28493  I fix this?</I>
28494 <P> Open up the C++ wrapper source code file and look for <CODE>
28495 &quot;method_foo&quot;</CODE> (include the double quotes, they are important!)
28496  Look at the JNI field descriptor and make sure that each class that
28497  occurs in the descriptor has the correct package name in front of it.
28498  If the package name is incorrect, put a &quot;javapackage&quot; typemap in your
28499  SWIG interface file.</P>
28500 </LI>
28501 <LI><I>I'm compiling my code and I'm using templates. I provided a
28502  javapackage typemap, but SWIG doesn't generate the right JNI field
28503  descriptor.</I>
28504 <P> Use the template's renamed name as the argument to the &quot;javapackage&quot;
28505  typemap:</P>
28506 <DIV class="code">
28507 <PRE>
28508 %typemap(javapackage)  std::vector&lt;int&gt;  &quot;your.package.here&quot;
28509 %template(VectorOfInt) std::vector&lt;int&gt;;
28510 </PRE>
28511 </DIV></LI>
28512 <LI>
28513 <P><I>When I pass class pointers or references through a C++ upcall and
28514  I try to type cast them, Java complains with a ClassCastException. What
28515  am I doing wrong?</I></P>
28516 <P> Normally, a non-director generated Java proxy class creates
28517  temporary Java objects as follows:</P>
28518 <DIV class="code">
28519 <PRE>
28520 public static void MyClass_method_upcall(MyClass self, long jarg1)
28521 {
28522   Foo darg1 = new Foo(jarg1, false);
28523
28524   self.method_upcall(darg1);
28525 }
28526 </PRE>
28527 </DIV>
28528 <P>Unfortunately, this loses the Java type information that is part of
28529  the underlying Foo director proxy class's Java object pointer causing
28530  the type cast to fail. The SWIG Java module's director code attempts to
28531  correct the problem,<B> but only for director-enabled classes</B>,
28532  since the director class retains a global reference to its Java object.
28533  Thus, for director-enabled classes<B> and only for director-enabled
28534  classes</B>, the generated proxy Java code looks something like:</P>
28535 <DIV class="code">
28536 <PRE>
28537 public static void MyClass_method_upcall(MyClass self, long jarg1,
28538                                          Foo jarg1_object)
28539 {
28540   Foo darg1 = (jarg1_object != null ? jarg1_object : new Foo(jarg1, false));
28541
28542   self.method_upcall(darg1);
28543 }
28544 </PRE>
28545 </DIV>
28546 <P> When you import a SWIG interface file containing class definitions,
28547  the classes you want to be director-enabled must be have the <CODE>
28548 feature(&quot;director&quot;)</CODE> enabled for type symmetry to work. This
28549  applies even when the class being wrapped isn't a director-enabled
28550  class but takes parameters that are director-enabled classes.</P>
28551 <P> The current &quot;type symmetry&quot; design will work for simple C++
28552  inheritance, but will most likely fail for anything more complicated
28553  such as tree or diamond C++ inheritance hierarchies. Those who are
28554  interested in challenging problems are more than welcome to hack the <CODE>
28555 Java::Java_director_declaration</CODE> method in <CODE>
28556 Source/Modules/java.cxx</CODE>.</P>
28557 <P> If all else fails, you can use the downcastXXXXX() method to attempt
28558  to recover the director class's Java object pointer. For the Java Foo
28559  proxy class, the Foo director class's java object pointer can be
28560  accessed through the javaObjectFoo() method. The generated method's
28561  signature is:</P>
28562 <DIV class="code">
28563 <PRE>
28564   public static Foo javaObjectFoo(Foo obj);
28565 </PRE>
28566 </DIV>
28567 <P> From your code, this method is invoked as follows:</P>
28568 <DIV class="code">
28569 <PRE>
28570 public class MyClassDerived {
28571   public void method_upcall(Foo foo_object)
28572   {
28573     FooDerived    derived = (foo_object != null ?
28574                  (FooDerived) Foo.downcastFoo(foo_object) : null);
28575     /* rest of your code here */
28576   }
28577 }
28578 </PRE>
28579 </DIV>
28580 <P> An good approach for managing downcasting is placing a static method
28581  in each derived class that performs the downcast from the superclass,
28582  e.g.,</P>
28583 <DIV class="code">
28584 <PRE>
28585 public class FooDerived extends Foo {
28586   /* ... */
28587   public static FooDerived downcastFooDerived(Foo foo_object)
28588   {
28589     try {
28590      return (foo_object != null ? (FooDerived) Foo.downcastFoo(foo_object);
28591     }
28592
28593     catch (ClassCastException exc) {
28594       // Wasn't a FooDerived object, some other subclass of Foo
28595       return null;
28596     }
28597   }
28598 }
28599 </PRE>
28600 </DIV>
28601 <P> Then change the code in MyClassDerived as follows:</P>
28602 <DIV class="code">
28603 <PRE>
28604 public class MyClassDerived extends MyClass {
28605   /* ... */
28606   public void method_upcall(Foo foo_object)
28607   {
28608     FooDerived    derived = FooDerived.downcastFooDerived(foo_object);
28609     /* rest of your code here */
28610   }
28611 }
28612 </PRE>
28613 </DIV></LI>
28614 <LI>
28615 <P><I>Why isn't the proxy class declared abstract? Why aren't the
28616  director upcall methods in the proxy class declared abstract?</I></P>
28617 <P> Declaring the proxy class and its methods abstract would break the
28618  JNI argument marshalling and SWIG's downcall functionality (going from
28619  Java to C++.) Create an abstract Java subclass that inherits from the
28620  director-enabled class instead. Using the previous Foo class example:</P>
28621 <DIV class="code">
28622 <PRE>
28623 public abstract class UserVisibleFoo extends Foo {
28624   /** Make sure user overrides this method, it's where the upcall
28625    * happens.
28626    */
28627   public abstract void method_upcall(Foo foo_object);
28628
28629   /// Downcast from Foo to UserVisibleFoo
28630   public static UserVisibleFoo downcastUserVisibleFoo(Foo foo_object)
28631   {
28632     try {
28633      return (foo_object != null ? (FooDerived) Foo.downcastFoo(foo_object) : null);
28634     }
28635
28636     catch (ClassCastException exc) {
28637       // Wasn't a FooDerived object, some other subclass of Foo
28638       return null;
28639     }
28640   }
28641 }
28642 </PRE>
28643 </DIV>
28644 <P>This doesn't prevent the user from creating subclasses derived from
28645  Foo, however, UserVisibleFoo provides the safety net that reminds the
28646  user to override the <CODE>method_upcall()</CODE> method.</P>
28647 </LI>
28648 </OL>
28649 <H2><A name="odds_ends"></A>21.12 Odds and ends</H2>
28650 <H3><A name="javadoc_comments"></A>21.12.1 JavaDoc comments</H3>
28651 <P> The SWIG documentation system is currently deprecated. When it is
28652  resurrected JavaDoc comments will be fully supported. If you can't wait
28653  for the full documentation system a couple of workarounds are
28654  available. The <TT>%javamethodmodifiers</TT> feature can be used for
28655  adding proxy class method comments and module class method comments.
28656  The &quot;javaimports&quot; typemap can be hijacked for adding in proxy class
28657  JavaDoc comments. The <TT>jniclassimports</TT> or <TT>
28658 jniclassclassmodifiers</TT> pragmas can also be used for adding
28659  intermediary JNI class comments and likewise the <TT>moduleimports</TT>
28660  or <TT>moduleclassmodifiers</TT> pragmas for the module class. Here is
28661  an example adding in a proxy class and method comment:</P>
28662 <DIV class="code">
28663 <PRE>
28664 %javamethodmodifiers Barmy::lose_marbles() &quot;
28665   /**
28666     * Calling this method will make you mad.
28667     * Use with &lt;b&gt;utmost&lt;/b&gt; caution. 
28668     */
28669   public&quot;;
28670
28671 %typemap(javaimports) Barmy &quot;
28672 /** The crazy class. Use as a last resort. */&quot;
28673
28674 class Barmy {
28675 public:
28676   void lose_marbles() {}
28677 };
28678 </PRE>
28679 </DIV>
28680 <P> Note the &quot;public&quot; added at the end of the <TT>%javamethodmodifiers</TT>
28681  as this is the default for this feature. The generated proxy class with
28682  JavaDoc comments is then as follows:</P>
28683 <DIV class="code">
28684 <PRE>
28685 /** The crazy class. Use as a last resort. */
28686 public class Barmy {
28687 ...
28688   /**
28689     * Calling this method will make you mad.
28690     * Use with &lt;b&gt;utmost&lt;/b&gt; caution. 
28691     */
28692   public void lose_marbles() {
28693     ...
28694   }
28695 ...
28696 }
28697 </PRE>
28698 </DIV>
28699 <H3><A name="functional_interface"></A>21.12.2 Functional interface
28700  without proxy classes</H3>
28701 <P> It is possible to run SWIG in a mode that does not produce proxy
28702  classes by using the -noproxy commandline option. The interface is
28703  rather primitive when wrapping structures or classes and is accessed
28704  through function calls to the module class. All the functions in the
28705  module class are wrapped by functions with identical names as those in
28706  the intermediary JNI class.</P>
28707 <P> Consider the example we looked at when examining proxy classes:</P>
28708 <DIV class="code">
28709 <PRE>
28710 class Foo {
28711 public:
28712      int x;
28713      int spam(int num, Foo* foo);
28714 };
28715 </PRE>
28716 </DIV>
28717 <P> When using <TT>-noproxy</TT>, type wrapper classes are generated
28718  instead of proxy classes. Access to all the functions and variables is
28719  through a C like set of functions where the first parameter passed is
28720  the pointer to the class, that is an instance of a type wrapper class.
28721  Here is what the module class looks like:</P>
28722 <DIV class="code">
28723 <PRE>
28724 public class example {
28725   public static void Foo_x_get(SWIGTYPE_p_Foo self, int x) {...}
28726   public static int Foo_x_get(SWIGTYPE_p_Foo self) {...}
28727   public static int Foo_spam(SWIGTYPE_p_Foo self, int num, SWIGTYPE_p_Foo foo) {...}
28728   public static SWIGTYPE_p_Foo new_Foo() {...}
28729   public static void delete_Foo(SWIGTYPE_p_Foo self) {...}
28730 }
28731 </PRE>
28732 </DIV>
28733 <P> This approach is not nearly as natural as using proxy classes as the
28734  functions need to be used like this:</P>
28735 <DIV class="code">
28736 <PRE>
28737 SWIGTYPE_p_Foo foo = example.new_Foo();
28738 example.Foo_x_set(foo, 10);
28739 int var = example.Foo_x_get(foo);
28740 example.Foo_spam(foo, 20, foo);
28741 example.delete_Foo(foo);
28742 </PRE>
28743 </DIV>
28744 <P> Unlike proxy classes, there is no attempt at tracking memory. All
28745  destructors have to be called manually for example the <TT>
28746 delete_Foo(foo)</TT> call above.</P>
28747 <H3><A name="using_own_jni_functions"></A>21.12.3 Using your own JNI
28748  functions</H3>
28749 <P> You may have some hand written JNI functions that you want to use in
28750  addition to the SWIG generated JNI functions. Adding these to your SWIG
28751  generated package is possible using the <TT>%native</TT> directive. If
28752  you don't want SWIG to wrap your JNI function then of course you can
28753  simply use the <TT>%ignore</TT> directive. However, if you want SWIG to
28754  generate just the Java code for a JNI function then use the <TT>%native</TT>
28755  directive. The C types for the parameters and return type must be
28756  specified in place of the JNI types and the function name must be the
28757  native method name. For example:</P>
28758 <DIV class="code">
28759 <PRE>
28760 %native (HandRolled) void HandRolled(int, char *);
28761 %{
28762 JNIEXPORT void JNICALL Java_packageName_moduleName_HandRolled(JNIEnv *, jclass,
28763                                                               jlong, jstring);
28764 %}
28765 </PRE>
28766 </DIV>
28767 <P> No C JNI function will be generated and the <TT>
28768 Java_packageName_moduleName_HandRolled</TT> function will be accessible
28769  using the SWIG generated Java native method call in the intermediary
28770  JNI class which will look like this:</P>
28771 <DIV class="code">
28772 <PRE>
28773   public final static native void HandRolled(int jarg1, String jarg2);
28774 </PRE>
28775 </DIV>
28776 <P> and as usual this function is wrapped by another which for a global
28777  C function would appear in the module class:</P>
28778 <DIV class="code">
28779 <PRE>
28780   public static void HandRolled(int arg0, String arg1) {
28781     exampleJNI.HandRolled(arg0, arg1);
28782   }
28783 </PRE>
28784 </DIV>
28785 <P> The <TT>packageName</TT> and <TT>moduleName</TT> must of course be
28786  correct else you will get linker errors when the JVM dynamically loads
28787  the JNI function. You may have to add in some &quot;jtype&quot;, &quot;jstype&quot;,
28788  &quot;javain&quot; and &quot;javaout&quot; typemaps when wrapping some JNI types. Here the
28789  default typemaps work for <TT>int</TT> and <TT>char *</TT>.</P>
28790 <P> In summary the <TT>%native</TT> directive is telling SWIG to
28791  generate the Java code to access the JNI C code, but not the JNI C
28792  function itself. This directive is only really useful if you want to
28793  mix your own hand crafted JNI code and the SWIG generated code into one
28794  Java class or package.</P>
28795 <H3><A name="performance"></A>21.12.4 Performance concerns and hints</H3>
28796 <P> If you're directly manipulating huge arrays of complex objects from
28797  Java, performance may suffer greatly when using the array functions in <TT>
28798 arrays_java.i</TT>. Try and minimise the expensive JNI calls to C/C++
28799  functions, perhaps by using temporary Java variables instead of
28800  accessing the information directly from the C/C++ object.</P>
28801 <P> Java classes without any finalizers generally speed up code
28802  execution as there is less for the garbage collector to do. Finalizer
28803  generation can be stopped by using an empty <TT>javafinalize</TT>
28804  typemap:</P>
28805 <DIV class="code">
28806 <PRE>
28807 %typemap(javafinalize) SWIGTYPE &quot;&quot;
28808 </PRE>
28809 </DIV>
28810 <P> However, you will have to be careful about memory management and
28811  make sure that you code in a call to the <TT>delete()</TT> member
28812  function. This method normally calls the C++ destructor or <TT>free()</TT>
28813  for C code.</P>
28814 <H3><A name="java_debugging"></A>21.12.5 Debugging</H3>
28815 <P> The generated code can be debugged using both a Java debugger and a
28816  C++ debugger using the usual debugging techniques. Breakpoints can be
28817  set in either Java or C++ code and so both can be debugged
28818  simultaneously. Most debuggers do not understand both Java and C++,
28819  with one noteable exception of Sun Studio, where it is possible to step
28820  from Java code into a JNI method within one environment.</P>
28821 <P> Alternatively, debugging can involve placing debug printout
28822  statements in the JNI layer using the <TT>%exception</TT> directive.
28823  See the <A href="#Customization_exception_special_variables">special
28824  variables for %exception</A> section. Many of the default typemaps can
28825  also be overidden and modified for adding in extra logging/debug
28826  display information.</P>
28827 <P> The <TT>-Xcheck:jni</TT> and <TT>-Xcheck:nabounds</TT> Java
28828  executable options are useful for debugging to make sure the JNI code
28829  is behaving. The -verbose:jni and -verbose:gc are also useful options
28830  for monitoring code behaviour.</P>
28831 <H2><A name="java_examples"></A>21.13 Examples</H2>
28832 <P> The directory Examples/java has a number of further examples. Take a
28833  look at these if you want to see some of the techniques described in
28834  action. The Examples/index.html file in the parent directory contains
28835  the SWIG Examples Documentation and is a useful starting point. If your
28836  SWIG installation went well Unix users should be able to type <TT>make</TT>
28837  in each example directory, then <TT>java main</TT> to see them running.
28838  For the benefit of Windows users, there are also Visual C++ project
28839  files in a couple of the <A href="#Windows_examples">Windows Examples</A>
28840 . There are also many regression tests in the Examples/test-suite
28841  directory. Many of these have runtime tests in the java subdirectory.</P>
28842 <HR NOSHADE>
28843 <H1><A name="Lisp_nn1"></A>22 SWIG and Common Lisp</H1>
28844
28845 <!-- INDEX -->
28846 <DIV class="sectiontoc">
28847 <UL>
28848 <LI><A href="#Lisp_nn2">Allegro Common Lisp</A></LI>
28849 <LI><A href="#Lisp_nn3">Common Foreign Function Interface(CFFI)</A>
28850 <UL>
28851 <LI><A href="#Lisp_nn4">Additional Commandline Options</A></LI>
28852 <LI><A href="#Lisp_nn5">Generating CFFI bindings</A></LI>
28853 <LI><A href="#Lisp_nn6">Generating CFFI bindings for C++ code</A></LI>
28854 <LI><A href="#Lisp_nn7">Inserting user code into generated files</A></LI>
28855 </UL>
28856 </LI>
28857 <LI><A href="#Lisp_nn8">CLISP</A>
28858 <UL>
28859 <LI><A href="#Lisp_nn9">Additional Commandline Options</A></LI>
28860 <LI><A href="#Lisp_nn10">Details on CLISP bindings</A></LI>
28861 </UL>
28862 </LI>
28863 <LI><A href="#Lisp_nn11">UFFI</A></LI>
28864 </UL>
28865 </DIV>
28866 <!-- INDEX -->
28867 <P> Common Lisp is a high-level, all-purpose, object-oriented, dynamic,
28868  functional programming language with long history. Common Lisp is used
28869  in many fields, ranging from web development to finance, and also
28870  common in computer science education. There are more than 9 different
28871  implementations of common lisp which are available, all have different
28872  foreign function interfaces. SWIG currently supports only the Allegro
28873  Common Lisp, Common Foreign Function Interface(CFFI), CLisp and UFFI
28874  foreign function interfaces.</P>
28875 <H2><A name="Lisp_nn2"></A>22.1 Allegro Common Lisp</H2>
28876 <P> Allegro Common Lisp support in SWIG has been updated to include
28877  support for both C and C++. You can read about the interface <A href="#Allegrocl_nn1">
28878 here</A></P>
28879 <H2><A name="Lisp_nn3"></A>22.2 Common Foreign Function Interface(CFFI)</H2>
28880 <P> CFFI, the Common Foreign Function Interface, is a portable foreign
28881  function interface for ANSI Common Lisp systems, similar in spirit to
28882  UFFI. Unlike UFFI, CFFI requires only a small set of low-level
28883  functionality from the Lisp implementation, such as calling a foreign
28884  function by name, allocating foreign memory, and dereferencing
28885  pointers.</P>
28886 <P> To run the cffi module of SWIG requires very little effort, you just
28887  need to run:</P>
28888 <DIV class="code">
28889 <PRE>
28890 swig -cffi -module <I>module-name</I>   <I>file-name</I> 
28891
28892 </PRE>
28893 </DIV>
28894 <P> But a better was of using all the power of SWIG is to write SWIG
28895  interface files. Below we will explain how to write interface files and
28896  the various things which you can do with them.</P>
28897 <H3><A name="Lisp_nn4"></A>22.2.1 Additional Commandline Options</H3>
28898 <P> The following table list the additional commandline options
28899  available for the CLISP module. They can also be seen by using:</P>
28900 <DIV class="code">
28901 <PRE>
28902 swig -cffi -help 
28903 </PRE>
28904 </DIV>
28905 <BR>
28906 <TABLE summary="CFFI specific options">
28907 <TR><TH> CFFI specific options</TH></TR>
28908 <TR><TD>-generate-typedef</TD><TD>If this option is given then defctype
28909  will be used to generate
28910 <!--br\-->
28911  shortcuts according to the typedefs in the input.</TD></TR>
28912 <TR><TD>-[no]cwrap</TD><TD>Turn on or turn off generation of an
28913  intermediate C file when
28914 <!--br\-->
28915  creating a C interface. By default this is only done for C++ code.</TD></TR>
28916 <TR><TD>-[no]swig-lisp</TD><TD>Turns on or off generation of code for
28917  helper lisp macro, functions, etc. which SWIG uses while generating
28918  wrappers. These macros, functions may still be used by generated
28919  wrapper code.</TD></TR>
28920 </TABLE>
28921 <H3><A name="Lisp_nn5"></A>22.2.2 Generating CFFI bindings</H3>
28922  As we mentioned earlier the ideal way to use SWIG is to use interface
28923  files. To illustrate the use of it, lets assume that we have a file
28924  named<I> test.h</I> with the following C code:<DIV class="code">
28925 <PRE>
28926 #define y 5
28927 #define x (y &gt;&gt;  1)
28928
28929 typedef int days;
28930
28931 struct bar {
28932   short p, q;
28933     char a, b;
28934     int *z[1000];
28935     struct bar * n;
28936 };
28937   
28938 struct   bar * my_struct;
28939
28940 struct foo {
28941     int a;
28942     struct foo * b[100];
28943   
28944 };
28945
28946 int pointer_func(void (*ClosureFun)( void* _fun, void* _data, void* _evt ), int p);
28947
28948 int func123(div_t * p,int **q[100],int r[][1000][10]);
28949
28950 void lispsort_double (int n, double * array);
28951
28952 enum color { RED, BLUE, GREEN};
28953 </PRE>
28954 </DIV> Corresponding to this we will write a simple interface file:<DIV class="code">
28955 <PRE>
28956 %module test
28957
28958 %include &quot;test.h&quot;
28959
28960 </PRE>
28961 </DIV> The generated SWIG Code will be:<DIV class="targetlang">
28962 <PRE>
28963 ;;;SWIG wrapper code starts here
28964
28965 (cl:defmacro defanonenum (&amp;body enums)
28966    &quot;Converts anonymous enums to defconstants.&quot;
28967   `(cl:progn ,@(cl:loop for value in enums
28968                         for index = 0 then (cl:1+ index)
28969                         when (cl:listp value) do (cl:setf index (cl:second value)
28970                                                           value (cl:first value))
28971                         collect `(cl:defconstant ,value ,index))))
28972
28973 (cl:eval-when (:compile-toplevel :load-toplevel)
28974   (cl:unless (cl:fboundp 'swig-lispify)
28975     (cl:defun swig-lispify (name flag cl:&amp;optional (package cl:*package*))
28976       (cl:labels ((helper (lst last rest cl:&amp;aux (c (cl:car lst)))
28977                     (cl:cond
28978                       ((cl:null lst)
28979                        rest)
28980                       ((cl:upper-case-p c)
28981                        (helper (cl:cdr lst) 'upper
28982                                (cl:case last
28983                                  ((lower digit) (cl:list* c #\- rest))
28984                                  (cl:t (cl:cons c rest)))))
28985                       ((cl:lower-case-p c)
28986                        (helper (cl:cdr lst) 'lower (cl:cons (cl:char-upcase c) rest)))
28987                       ((cl:digit-char-p c)
28988                        (helper (cl:cdr lst) 'digit 
28989                                (cl:case last
28990                                  ((upper lower) (cl:list* c #\- rest))
28991                                  (cl:t (cl:cons c rest)))))
28992                       ((cl:char-equal c #\_)
28993                        (helper (cl:cdr lst) '_ (cl:cons #\- rest)))
28994                       (cl:t
28995                        (cl:error &quot;Invalid character: ~A&quot; c)))))
28996         (cl:let ((fix (cl:case flag
28997                         ((constant enumvalue) &quot;+&quot;)
28998                         (variable &quot;*&quot;)
28999                         (cl:t &quot;&quot;))))
29000           (cl:intern
29001            (cl:concatenate
29002             'cl:string
29003             fix
29004             (cl:nreverse (helper (cl:concatenate 'cl:list name) cl:nil cl:nil))
29005             fix)
29006            package))))))
29007
29008 ;;;SWIG wrapper code ends here
29009
29010
29011 (cl:defconstant y 5)
29012
29013 (cl:defconstant x (cl:ash 5 -1))
29014
29015 (cffi:defcstruct bar
29016         (p :short)
29017         (q :short)
29018         (a :char)
29019         (b :char)
29020         (z :pointer)
29021         (n :pointer))
29022
29023 (cffi:defcvar (&quot;my_struct&quot; my_struct)
29024  :pointer)
29025
29026 (cffi:defcstruct foo
29027         (a :int)
29028         (b :pointer))
29029
29030 (cffi:defcfun (&quot;pointer_func&quot; pointer_func) :int
29031   (ClosureFun :pointer)
29032   (p :int))
29033
29034 (cffi:defcfun (&quot;func123&quot; func123) :int
29035   (p :pointer)
29036   (q :pointer)
29037   (r :pointer))
29038
29039 (cffi:defcfun (&quot;lispsort_double&quot; lispsort_double) :void
29040   (n :int)
29041   (array :pointer))
29042
29043 (cffi:defcenum color
29044         :RED
29045         :BLUE
29046         :GREEN)
29047 </PRE>
29048 </DIV>
29049 <P> The<I> SWIG wrapper</I> code refers to the special code which SWIG
29050  may need to use while wrapping C code. You can turn on/off the
29051  generation of this code by using the<I> -[no]swig-lisp</I> option. You
29052  must have noticed that SWIG goes one extra step to ensure that CFFI
29053  does not do automatic lispification of the C function names. The reason
29054  SWIG does this is because quite often developers want to build a nice
29055  CLOS based lispy API, and this one to one correspondence between C
29056  function names and lisp function name helps.</P>
29057 <P> Maybe you want to have your own convention for generating lisp
29058  function names for corresponding C function names, or you just want to
29059  lispify the names, also, before we forget you want to export the
29060  generated lisp names. To do this, we will use the SWIG <A href="#features">
29061 feature directive</A>. Let's edit the interface file such that the C
29062  type &quot;div_t*&quot; is changed to Lisp type &quot;:my-pointer&quot;, we lispify all
29063  names, export everything, and do some more stuff.</P>
29064 <DIV class="code">
29065 <PRE>
29066 %module test
29067
29068 %typemap(cin) div_t* &quot;:my-pointer&quot;;
29069
29070 %feature(&quot;intern_function&quot;,&quot;1&quot;);
29071 %feature(&quot;export&quot;);
29072
29073 %feature(&quot;inline&quot;) lispsort_double;
29074
29075 %feature(&quot;intern_function&quot;, &quot;my-lispify&quot;) lispsort_double;
29076 %rename func123 renamed_cool_func;
29077 %ignore &quot;pointer_func&quot;;
29078
29079 %include &quot;test.h&quot;
29080
29081 </PRE>
29082 </DIV>
29083 <P> The<I> typemap(cin)</I> ensures that for all arguments which are
29084  input to C with the type &quot;div_t*&quot;, the &quot;:my-pointer&quot; type be used.
29085  Similarly<I> typemap(cout)</I> are used for all types which are
29086  returned from C.</P>
29087 <P> The feature<I> intern_function</I> ensures that all C names are
29088  interned using the<B> swig-lispify</B> function. The &quot;1&quot; given to the
29089  feature is optional. The use of feature like<I>
29090  %feature(&quot;intern_function&quot;,&quot;1&quot;);</I> globally enables interning for
29091  everything. If you want to target a single function, or declaration
29092  then use the targeted version of feature,<I>
29093  %feature(&quot;intern_function&quot;, &quot;my-lispify&quot;) lispsort_double;</I>, here we
29094  are using an additional feature which allows us to use our lispify
29095  function.</P>
29096 <P>The<I> export</I> feature allows us to export the symbols. The<I>
29097  inline</I> feature declaims the declared function as inline. The<I>
29098  rename</I> directive allows us to change the name(it is useful when
29099  generating C wrapper code for handling overloaded functions). The<I>
29100  ignore</I> directive ignores a certain declaration.</P>
29101 <P>There are several other things which are possible, to see some
29102  example of usage of SWIG look at the Lispbuilder and wxCL projects. The
29103  generated code with 'noswig-lisp' option is:</P>
29104 <DIV class="targetlang">
29105 <PRE>
29106 (cl:defconstant #.(swig-lispify &quot;y&quot; 'constant) 5)
29107
29108 (cl:export '#.(swig-lispify &quot;y&quot; 'constant))
29109
29110 (cl:defconstant #.(swig-lispify &quot;x&quot; 'constant) (cl:ash 5 -1))
29111
29112 (cl:export '#.(swig-lispify &quot;x&quot; 'constant))
29113
29114 (cffi:defcstruct #.(swig-lispify &quot;bar&quot; 'classname)
29115         (#.(swig-lispify &quot;p&quot; 'slotname) :short)
29116         (#.(swig-lispify &quot;q&quot; 'slotname) :short)
29117         (#.(swig-lispify &quot;a&quot; 'slotname) :char)
29118         (#.(swig-lispify &quot;b&quot; 'slotname) :char)
29119         (#.(swig-lispify &quot;z&quot; 'slotname) :pointer)
29120         (#.(swig-lispify &quot;n&quot; 'slotname) :pointer))
29121
29122 (cl:export '#.(swig-lispify &quot;bar&quot; 'classname))
29123
29124 (cl:export '#.(swig-lispify &quot;p&quot; 'slotname))
29125
29126 (cl:export '#.(swig-lispify &quot;q&quot; 'slotname))
29127
29128 (cl:export '#.(swig-lispify &quot;a&quot; 'slotname))
29129
29130 (cl:export '#.(swig-lispify &quot;b&quot; 'slotname))
29131
29132 (cl:export '#.(swig-lispify &quot;z&quot; 'slotname))
29133
29134 (cl:export '#.(swig-lispify &quot;n&quot; 'slotname))
29135
29136 (cffi:defcvar (&quot;my_struct&quot; #.(swig-lispify &quot;my_struct&quot; 'variable))
29137  :pointer)
29138
29139 (cl:export '#.(swig-lispify &quot;my_struct&quot; 'variable))
29140
29141 (cffi:defcstruct #.(swig-lispify &quot;foo&quot; 'classname)
29142         (#.(swig-lispify &quot;a&quot; 'slotname) :int)
29143         (#.(swig-lispify &quot;b&quot; 'slotname) :pointer))
29144
29145 (cl:export '#.(swig-lispify &quot;foo&quot; 'classname))
29146
29147 (cl:export '#.(swig-lispify &quot;a&quot; 'slotname))
29148
29149 (cl:export '#.(swig-lispify &quot;b&quot; 'slotname))
29150
29151 (cffi:defcfun (&quot;renamed_cool_func&quot; #.(swig-lispify &quot;renamed_cool_func&quot; 'function)) :int
29152   (p :my-pointer)
29153   (q :pointer)
29154   (r :pointer))
29155
29156 (cl:export '#.(swig-lispify &quot;renamed_cool_func&quot; 'function))
29157
29158 (cl:declaim (cl:inline #.(my-lispify &quot;lispsort_double&quot; 'function)))
29159
29160 (cffi:defcfun (&quot;lispsort_double&quot; #.(my-lispify &quot;lispsort_double&quot; 'function)) :void
29161   (n :int)
29162   (array :pointer))
29163
29164 (cl:export '#.(my-lispify &quot;lispsort_double&quot; 'function))
29165
29166 (cffi:defcenum #.(swig-lispify &quot;color&quot; 'enumname)
29167         #.(swig-lispify &quot;RED&quot; 'enumvalue :keyword)
29168         #.(swig-lispify &quot;BLUE&quot; 'enumvalue :keyword)
29169         #.(swig-lispify &quot;GREEN&quot; 'enumvalue :keyword))
29170
29171 (cl:export '#.(swig-lispify &quot;color&quot; 'enumname))
29172
29173 </PRE>
29174 </DIV>
29175 <H3><A name="Lisp_nn6"></A>22.2.3 Generating CFFI bindings for C++ code</H3>
29176 <P>This feature to SWIG (for CFFI) is very new and still far from
29177  complete. Pitch in with your patches, bug reports and feature requests
29178  to improve it.</P>
29179 <P> Generating bindings for C++ code, requires<I> -c++</I> option to be
29180  present and it first generates C binding which will wrap the C++ code,
29181  and then generates the corresponding CFFI wrapper code. In the
29182  generated C wrapper code, you will often want to put your own C code,
29183  such as the code to include various files. This can be done by making
29184  use of &quot;%{&quot; and &quot;%}&quot; as shown below.</P>
29185 <DIV class="code">
29186 <PRE>
29187 %{
29188  #include &quot;Test/test.h&quot;
29189 %}
29190 </PRE>
29191 </DIV>
29192 <P> Also, while parsing the C++ file and generating C wrapper code SWIG
29193  may need to be able to understand various symbols used in other header
29194  files. To help SWIG in doing this while ensuring that wrapper code is
29195  generated for the target file, use the &quot;import&quot; directive. The
29196  &quot;include&quot; directive specifies the target file for which wrapper code
29197  will be generated.</P>
29198 <DIV class="code">
29199 <PRE>
29200
29201 %import &quot;ancillary/header.h&quot;
29202
29203 %include &quot;target/header.h&quot;
29204
29205 </PRE>
29206 </DIV> Various features which were available for C headers can also be
29207  used here. The target header which we are going to use here is:<DIV class="code">
29208 <PRE>
29209 namespace OpenDemo {
29210   class Test
29211     {
29212     public:
29213         float x;
29214         // constructors
29215         Test (void) {x = 0;}
29216         Test (float X) {x = X;}
29217
29218         // vector addition
29219         Test operator+ (const Test&amp; v) const {return Test (x+v.x);}
29220
29221       // length squared
29222         float lengthSquared (void) const {return this-&gt;dot (*this);}
29223
29224         static float distance (const Test&amp; a, const Test&amp; b){return(a-b).length();}
29225
29226         inline Test parallelComponent (const Test&amp; unitBasis) const {
29227           return unitBasis * projection;
29228         }
29229
29230         Test setYtoZero (void) const {return Test (this-&gt;x);}
29231
29232         static const Test zero;
29233     };
29234
29235
29236    inline Test operator* (float s, const Test&amp; v) {return v*s;}
29237
29238
29239     inline std::ostream&amp; operator&lt;&lt; (std::ostream&amp; o, const Test&amp; v)
29240     {
29241         return o &lt;&lt; &quot;(&quot; &lt;&lt; v.x &lt;&lt; &quot;)&quot;;
29242     }
29243
29244
29245     inline Test RandomUnitVectorOnXZPlane (void)
29246     {
29247         return RandomVectorInUnitRadiusSphere().setYtoZero().normalize();
29248     }
29249 }
29250 </PRE>
29251 </DIV>
29252 <P>The interface used is:</P>
29253 <DIV class="code">
29254 <PRE>
29255 %module test
29256 %include &quot;test.cpp&quot;
29257 </PRE>
29258 </DIV> SWIG generates 3 files, the first one is a C wrap which we don't
29259  show, the second is the plain CFFI wrapper which is as shown below:<DIV class="targetlang">
29260 <PRE>
29261 (cffi:defcfun (&quot;_wrap_Test_x_set&quot; Test_x_set) :void
29262   (self :pointer)
29263   (x :float))
29264
29265 (cffi:defcfun (&quot;_wrap_Test_x_get&quot; Test_x_get) :float
29266   (self :pointer))
29267
29268 (cffi:defcfun (&quot;_wrap_new_Test__SWIG_0&quot; new_Test) :pointer)
29269
29270 (cffi:defcfun (&quot;_wrap_new_Test__SWIG_1&quot; new_Test) :pointer
29271   (X :float))
29272
29273 (cffi:defcfun (&quot;_wrap_Test___add__&quot; Test___add__) :pointer
29274   (self :pointer)
29275   (v :pointer))
29276
29277 (cffi:defcfun (&quot;_wrap_Test_lengthSquared&quot; Test_lengthSquared) :float
29278   (self :pointer))
29279
29280 (cffi:defcfun (&quot;_wrap_Test_distance&quot; Test_distance) :float
29281   (a :pointer)
29282   (b :pointer))
29283
29284 (cffi:defcfun (&quot;_wrap_Test_parallelComponent&quot; Test_parallelComponent) :pointer
29285   (self :pointer)
29286   (unitBasis :pointer))
29287
29288 (cffi:defcfun (&quot;_wrap_Test_setYtoZero&quot; Test_setYtoZero) :pointer
29289   (self :pointer))
29290
29291 (cffi:defcvar (&quot;Test_zero&quot; Test_zero)
29292  :pointer)
29293
29294 (cffi:defcfun (&quot;_wrap_delete_Test&quot; delete_Test) :void
29295   (self :pointer))
29296
29297 (cffi:defcfun (&quot;_wrap___mul__&quot; __mul__) :pointer
29298   (s :float)
29299   (v :pointer))
29300
29301 (cffi:defcfun (&quot;_wrap___lshift__&quot; __lshift__) :pointer
29302   (o :pointer)
29303   (v :pointer))
29304
29305 (cffi:defcfun (&quot;_wrap_RandomUnitVectorOnXZPlane&quot; RandomUnitVectorOnXZPlane) :pointer)
29306 </PRE>
29307 </DIV> The output is pretty good but it fails in disambiguating
29308  overloaded functions such as the constructor, in this case. One way of
29309  resolving this problem is to make the interface use the rename
29310  directiv, but hopefully there are better solutions. In addition SWIG
29311  also generates, a CLOS file<DIV class="targetlang">
29312 <PRE>
29313 (clos:defclass test()
29314   ((ff :reader ff-pointer)))
29315
29316 (clos:defmethod (cl:setf x) (arg0 (obj test))
29317   (Test_x_set (ff-pointer obj) arg0))
29318
29319 (clos:defmethod x ((obj test))
29320   (Test_x_get (ff-pointer obj)))
29321
29322 (cl:shadow &quot;+&quot;)
29323 (clos:defmethod + ((obj test) (self test) (v test))
29324   (Test___add__ (ff-pointer obj) (ff-pointer self) (ff-pointer v)))
29325
29326 (clos:defmethod length-squared ((obj test) (self test))
29327   (Test_lengthSquared (ff-pointer obj) (ff-pointer self)))
29328
29329 (clos:defmethod parallel-component ((obj test) (self test) (unitBasis test))
29330   (Test_parallelComponent (ff-pointer obj) (ff-pointer self) (ff-pointer unitBasis)))
29331
29332 (clos:defmethod set-yto-zero ((obj test) (self test))
29333   (Test_setYtoZero (ff-pointer obj) (ff-pointer self)))
29334 </PRE>
29335 </DIV>
29336 <P>I agree that the CFFI C++ module needs lot more work. But I hope it
29337  provides a starting point, on which you can base your work of importing
29338  C++ libraries to Lisp.</P>
29339 <P> If you have any questions, suggestions, patches, etc., related to
29340  CFFI module feel free to contact us on the SWIG mailing list, and also
29341  please add a &quot;[CFFI]&quot; tag in the subject line.</P>
29342 <H3><A name="Lisp_nn7"></A>22.2.4 Inserting user code into generated
29343  files</H3>
29344 <P> It is often necessary to <A href="#SWIG_nn40">include user-defined
29345  code</A> into the automatically generated interface files. For example,
29346  when building a C++ interface, example_wrap.cxx will likely not compile
29347  unless you add a <TT>#include &quot;header.h&quot;</TT> directive. This can be
29348  done using the SWIG <TT>%insert(section) %{ ...code... %}</TT>
29349  directive:</P>
29350 <DIV class="code">
29351 <PRE>
29352 %module example
29353
29354 %{
29355 #include &quot;header.h&quot;
29356 %}
29357
29358 %include &quot;header.h&quot;
29359
29360 int fact(int n);
29361 </PRE>
29362 </DIV>
29363 <P> Additional sections have been added for inserting into the generated
29364  lisp interface file:</P>
29365 <UL>
29366 <LI><TT>lisphead</TT> - inserts before type declarations</LI>
29367 <LI><TT>swiglisp</TT> - inserts after type declarations according to
29368  where it appears in the .i file</LI>
29369 </UL>
29370 <P> Note that the block <TT>%{ ... %}</TT> is effectively a shortcut for
29371  <TT>%insert(&quot;header&quot;) %{ ... %}</TT>.</P>
29372 <H2><A name="Lisp_nn8"></A>22.3 CLISP</H2>
29373 <P> <A href="http://clisp.cons.org">CLISP</A> is a feature-loaded
29374  implementation of common lisp which is portable across most of the
29375  operating system environments and hardware. CLISP includes an
29376  interpreter, a compiler, a debugger, CLOS, MOP, a foreign language
29377  interface, i18n, regular expressions, a socket interface, and more. An
29378  X11 interface is available through CLX, Garnet and CLUE/CLIO. Command
29379  line editing is provided by readline. CLISP runs Maxima, ACL2 and many
29380  other Common Lisp packages.</P>
29381 <P> To run the clisp module of SWIG requires very little effort, you
29382  just need to execute:</P>
29383 <DIV class="code">
29384 <PRE>
29385 swig -clisp -module <I>module-name</I>   <I>file-name</I> 
29386
29387 </PRE>
29388 </DIV>
29389 <P> Because of the high level nature of the CLISP FFI, the bindings
29390  generated by SWIG may not be absolutely correct, and you may need to
29391  modify them. The good thing is that you don't need to complex interface
29392  file for the CLISP module. The CLISP module tries to produce code which
29393  is both human readable and easily modifyable.</P>
29394 <H3><A name="Lisp_nn9"></A>22.3.1 Additional Commandline Options</H3>
29395 <P> The following table list the additional commandline options
29396  available for the CLISP module. They can also be seen by using:</P>
29397 <DIV class="code">
29398 <PRE>
29399 swig -clisp -help 
29400 </PRE>
29401 </DIV>
29402 <BR>
29403 <TABLE summary="CLISP specific options">
29404 <TR><TH>CLISP specific options</TH></TR>
29405 <TR><TD>-extern-all</TD><TD>If this option is given then clisp
29406  definitions for all the functions
29407 <BR> and global variables will be created otherwise only definitions for
29408 <BR> externed functions and variables are created.</TD></TR>
29409 <TR><TD>-generate-typedef</TD><TD>If this option is given then
29410  def-c-type will be used to generate
29411 <BR> shortcuts according to the typedefs in the input.</TD></TR>
29412 </TABLE>
29413 <H3><A name="Lisp_nn10"></A>22.3.2 Details on CLISP bindings</H3>
29414 <P> As mentioned earlier the CLISP bindings generated by SWIG may need
29415  some modifications. The clisp module creates a lisp file with the same
29416  name as the module name. This lisp file contains a 'defpackage'
29417  declaration, with the package name same as the module name. This
29418  package uses the 'common-lisp' and 'ffi' packages. Also, package
29419  exports all the functions, structures and variables for which an ffi
29420  binding was generated.
29421 <BR> After generating the defpackage statement, the clisp module also
29422  sets the default language.<DIV class="targetlang">
29423 <PRE>
29424 (defpackage :test
29425     (:use :common-lisp :ffi)
29426   (:export
29427    :make-bar
29428    :bar-x
29429    :bar-y
29430    :bar-a
29431    :bar-b
29432    :bar-z
29433    :bar-n
29434    :pointer_func
29435    :func123
29436    :make-cfunr
29437    :lispsort_double
29438    :test123))
29439
29440 (in-package :test)
29441
29442 (default-foreign-language :stdc)
29443 </PRE>
29444 </DIV></P>
29445 <P> The ffi wrappers for functions and variables are generated as shown
29446  below. When functions have arguments of type &quot;double * array&quot;, SWIG
29447  doesn't knows whether it is an 'out' argument or it is an array which
29448  will be passed, so SWIG plays it safe by declaring it as an '(array
29449  (ffi:c-ptr DOUBLE-FLOAT))'. For arguments of type &quot;int **z[100]&quot; where
29450  SWIG has more information, i.e., it knows that 'z' is an array of
29451  pointers to pointers of integers, SWIG defines it to be '(z (ffi:c-ptr
29452  (ffi:c-array (ffi:c-ptr (ffi:c-ptr ffi:int)) 100)))'</P>
29453 <DIV class="code">
29454 <PRE>
29455 extern &quot;C&quot; {
29456 int pointer_func(void (*ClosureFun)( void* _fun, void* _data, void* _evt ), int y);
29457
29458 int func123(div_t * x,int **z[100],int y[][1000][10]);
29459
29460 void lispsort_double (int n, double * array);
29461
29462 void test123(float x , double y);
29463
29464 }
29465 </PRE>
29466 </DIV><DIV class="targetlang">
29467 <PRE>
29468 (ffi:def-call-out pointer_func
29469     (:name &quot;pointer_func&quot;)
29470   (:arguments (ClosureFun (ffi:c-function (:arguments (arg0 (ffi:c-pointer NIL))
29471                                                       (arg1 (ffi:c-pointer NIL))
29472                                                       (arg2 (ffi:c-pointer NIL)))
29473                                           (:return-type NIL)))
29474               (y ffi:int))
29475   (:return-type ffi:int)
29476   (:library +library-name+))
29477
29478 (ffi:def-call-out func123
29479     (:name &quot;func123&quot;)
29480   (:arguments (x (ffi:c-pointer div_t))
29481               (z (ffi:c-ptr (ffi:c-array (ffi:c-ptr (ffi:c-ptr ffi:int)) 100)))
29482               (y (ffi:c-ptr (ffi:c-ptr (ffi:c-array ffi:int (1000 10))))))
29483   (:return-type ffi:int)
29484   (:library +library-name+))
29485
29486
29487 (ffi:def-call-out lispsort_double
29488     (:name &quot;lispsort_double&quot;)
29489   (:arguments (n ffi:int)
29490               (array (ffi:c-ptr DOUBLE-FLOAT)))
29491   (:return-type NIL)
29492   (:library +library-name+))
29493
29494 (ffi:def-call-out test123
29495     (:name &quot;test&quot;)
29496   (:arguments (x SINGLE-FLOAT)
29497               (y DOUBLE-FLOAT))
29498   (:return-type NIL)
29499   (:library +library-name+))
29500
29501 </PRE>
29502 </DIV>
29503 <P> The module also handles strutcures and #define constants as shown
29504  below. SWIG automatically adds the constructors and accessors created
29505  for the struct to the list of symbols exported by the package.</P>
29506 <DIV class="code">
29507 <PRE>
29508 struct bar {
29509     short x, y;
29510     char a, b;
29511     int *z[1000];
29512     struct bar * n;
29513 };
29514
29515 #define max 1000
29516 </PRE>
29517 </DIV><DIV class="targetlang">
29518 <PRE>
29519 (ffi:def-c-struct bar
29520     (x :type ffi:short)
29521   (y :type ffi:short)
29522   (a :type character)
29523   (b :type character)
29524   (z :type (ffi:c-array (ffi:c-ptr ffi:int) 1000))
29525   (n :type (ffi:c-pointer bar)))
29526
29527 (defconstant max 1000)
29528
29529 </PRE>
29530 </DIV>
29531 <H2><A name="Lisp_nn11"></A>22.4 UFFI</H2>
29532 <HR NOSHADE>
29533 <H1><A name="Lua_nn1"></A>23 SWIG and Lua</H1>
29534
29535 <!-- INDEX -->
29536 <DIV class="sectiontoc">
29537 <UL>
29538 <LI><A href="#Lua_nn2">Preliminaries</A></LI>
29539 <LI><A href="#Lua_nn3">Running SWIG</A>
29540 <UL>
29541 <LI><A href="#Lua_nn4">Compiling and Linking and Interpreter</A></LI>
29542 <LI><A href="#Lua_nn5">Compiling a dynamic module</A></LI>
29543 <LI><A href="#Lua_nn6">Using your module</A></LI>
29544 </UL>
29545 </LI>
29546 <LI><A href="#Lua_nn7">A tour of basic C/C++ wrapping</A>
29547 <UL>
29548 <LI><A href="#Lua_nn8">Modules</A></LI>
29549 <LI><A href="#Lua_nn9">Functions</A></LI>
29550 <LI><A href="#Lua_nn10">Global variables</A></LI>
29551 <LI><A href="#Lua_nn11">Constants and enums</A></LI>
29552 <LI><A href="#Lua_nn12">Pointers</A></LI>
29553 <LI><A href="#Lua_nn13">Structures</A></LI>
29554 <LI><A href="#Lua_nn14">C++ classes</A></LI>
29555 <LI><A href="#Lua_nn15">C++ inheritance</A></LI>
29556 <LI><A href="#Lua_nn16">Pointers, references, values, and arrays</A></LI>
29557 <LI><A href="#Lua_nn17">C++ overloaded functions</A></LI>
29558 <LI><A href="#Lua_nn18">C++ operators</A></LI>
29559 <LI><A href="#Lua_nn19">Class extension with %extend</A></LI>
29560 <LI><A href="#Lua_nn20">C++ templates</A></LI>
29561 <LI><A href="#Lua_nn21">C++ Smart Pointers</A></LI>
29562 <LI><A href="#Lua_nn22">C++ Exceptions</A></LI>
29563 </UL>
29564 </LI>
29565 <LI><A href="#Lua_nn23">Typemaps</A>
29566 <UL>
29567 <LI><A href="#Lua_nn24">What is a typemap?</A></LI>
29568 <LI><A href="#Lua_nn25">Using typemaps</A></LI>
29569 <LI><A href="#Lua_nn26">Typemaps and arrays</A></LI>
29570 <LI><A href="#Lua_nn27">Typemaps and pointer-pointer functions</A></LI>
29571 </UL>
29572 </LI>
29573 <LI><A href="#Lua_nn28">Writing typemaps</A>
29574 <UL>
29575 <LI><A href="#Lua_nn29">Typemaps you can write</A></LI>
29576 <LI><A href="#Lua_nn30">SWIG's Lua-C API</A></LI>
29577 </UL>
29578 </LI>
29579 <LI><A href="#Lua_nn31">Customization of your Bindings</A>
29580 <UL>
29581 <LI><A href="#Lua_nn32">Writing your own custom wrappers</A></LI>
29582 <LI><A href="#Lua_nn33">Adding additional Lua code</A></LI>
29583 </UL>
29584 </LI>
29585 <LI><A href="#Lua_nn34">Details on the Lua binding</A>
29586 <UL>
29587 <LI><A href="#Lua_nn35">Binding global data into the module.</A></LI>
29588 <LI><A href="#Lua_nn36">Userdata and Metatables</A></LI>
29589 <LI><A href="#Lua_nn37">Memory management</A></LI>
29590 </UL>
29591 </LI>
29592 </UL>
29593 </DIV>
29594 <!-- INDEX -->
29595 <P> Lua is an extension programming language designed to support general
29596  procedural programming with data description facilities. It also offers
29597  good support for object-oriented programming, functional programming,
29598  and data-driven programming. Lua is intended to be used as a powerful,
29599  light-weight configuration language for any program that needs one. Lua
29600  is implemented as a library, written in clean C (that is, in the common
29601  subset of ANSI C and C++). Its also a<EM> really</EM> tiny language,
29602  less than 6000 lines of code, which compiles to &lt;100 kilobytes of
29603  binary code. It can be found at <A href="http://www.lua.org">
29604 http://www.lua.org</A></P>
29605 <H2><A name="Lua_nn2"></A>23.1 Preliminaries</H2>
29606 <P> The current SWIG implementation is designed to work with Lua 5.0.x
29607  and Lua 5.1.x. It should work with later versions of Lua, but certainly
29608  not with Lua 4.0 due to substantial API changes. ((Currently SWIG
29609  generated code has only been tested on Windows with MingW, though given
29610  the nature of Lua, is should not have problems on other OS's)). It is
29611  possible to either static link or dynamic link a Lua module into the
29612  interpreter (normally Lua static links its libraries, as dynamic
29613  linking is not available on all platforms).</P>
29614 <H2><A name="Lua_nn3"></A>23.2 Running SWIG</H2>
29615 <P> Suppose that you defined a SWIG module such as the following:</P>
29616 <DIV class="code">
29617 <PRE>
29618 %module example
29619 %{
29620 #include &quot;example.h&quot;
29621 %}
29622 int gcd(int x, int y);
29623 extern double Foo;
29624 </PRE>
29625 </DIV>
29626 <P> To build a Lua module, run SWIG using the <TT>-lua</TT> option.</P>
29627 <DIV class="shell">
29628 <PRE>
29629 $ swig -lua example.i
29630 </PRE>
29631 </DIV>
29632 <P> If building a C++ extension, add the <TT>-c++</TT> option:</P>
29633 <DIV class="shell">
29634 <PRE>
29635 $ swig -c++ -lua example.i
29636 </PRE>
29637 </DIV>
29638 <P> This creates a C/C++ source file <TT>example_wrap.c</TT> or <TT>
29639 example_wrap.cxx</TT>. The generated C source file contains the
29640  low-level wrappers that need to be compiled and linked with the rest of
29641  your C/C++ application to create an extension module.</P>
29642 <P> The name of the wrapper file is derived from the name of the input
29643  file. For example, if the input file is <TT>example.i</TT>, the name of
29644  the wrapper file is <TT>example_wrap.c</TT>. To change this, you can
29645  use the -o option. The wrappered module will export one function <TT>
29646 &quot;int luaopen_example(lua_State* L)&quot;</TT> which must be called to
29647  register the module with the Lua interpreter. The name
29648  &quot;luaopen_example&quot; depends upon the name of the module.</P>
29649 <H3><A name="Lua_nn4"></A>23.2.1 Compiling and Linking and Interpreter</H3>
29650 <P> Normally Lua is embedded into another program and will be statically
29651  linked. An extremely simple stand-alone interpreter (<TT>min.c</TT>) is
29652  given below:</P>
29653 <DIV class="code">
29654 <PRE>
29655 #include &lt;stdio.h&gt;
29656 #include &quot;lua.h&quot;
29657 #include &quot;lualib.h&quot;
29658 #include &quot;lauxlib.h&quot;
29659
29660 extern int luaopen_example(lua_State* L); // declare the wrapped module
29661
29662 int main(int argc,char* argv[])
29663 {
29664  lua_State *L;
29665  if (argc&lt;2)
29666  {
29667   printf(&quot;%s: &lt;filename.lua&gt;\n&quot;,argv[0]);
29668   return 0;
29669  }
29670  L=lua_open();
29671  luaopen_base(L);       // load basic libs (eg. print)
29672  luaopen_example(L);    // load the wrappered module
29673  if (luaL_loadfile(L,argv[1])==0) // load and run the file
29674   lua_pcall(L,0,0,0);
29675  else
29676   printf(&quot;unable to load %s\n&quot;,argv[1]);
29677  lua_close(L);
29678  return 0;
29679 }
29680 </PRE>
29681 </DIV>
29682 <P> A much improved set of code can be found in the Lua distribution <TT>
29683 src/lua/lua.c</TT>. Include your module, just add the external
29684  declaration &amp; add a <TT>#define LUA_EXTRALIBS
29685  {&quot;example&quot;,luaopen_example}</TT>, at the relevant place.</P>
29686 <P> The exact commands for compiling and linking vary from platform to
29687  platform. Here is a possible set of commands of doing this:</P>
29688 <DIV class="shell">
29689 <PRE>
29690 $ swig -lua example.i -o example_wrap.c
29691 $ gcc -I/usr/include/lua -c min.c -o min.o
29692 $ gcc -I/usr/include/lua -c example_wrap.c -o example_wrap.o
29693 $ gcc -c example.c -o example.o
29694 $ gcc -I/usr/include/lua -L/usr/lib/lua min.o example_wrap.o example.o -o my_lua
29695 </PRE>
29696 </DIV>
29697 <H3><A name="Lua_nn5"></A>23.2.2 Compiling a dynamic module</H3>
29698 <P> Most, but not all platforms support the dynamic loading of modules
29699  (Windows &amp; Linux do). Refer to the Lua manual to determine if your
29700  platform supports it. For compiling a dynamically loaded module the
29701  same wrapper can be used. The commands will be something like this:</P>
29702 <DIV class="shell">
29703 <PRE>
29704 $ swig -lua example.i -o example_wrap.c
29705 $ gcc -I/usr/include/lua -c example_wrap.c -o example_wrap.o
29706 $ gcc -c example.c -o example.o
29707 $ gcc -shared -I/usr/include/lua -L/usr/lib/lua example_wrap.o example.o -o example.so
29708 </PRE>
29709 </DIV>
29710 <P> The wrappers produced by SWIG can be compiled and linked with Lua
29711  5.1.x. The loading is extremely simple.</P>
29712 <DIV class="targetlang">
29713 <PRE>
29714 require(&quot;example&quot;)
29715 </PRE>
29716 </DIV>
29717 <P> For those using Lua 5.0.x, you will also need an interpreter with
29718  the loadlib function (such as the default interpreter compiled with
29719  Lua). In order to dynamically load a module you must call the loadlib
29720  function with two parameters: the filename of the shared library, and
29721  the function exported by SWIG. Calling loadlib should return the
29722  function, which you then call to initialise the module</P>
29723 <DIV class="targetlang">
29724 <PRE>
29725 my_init=loadlib(&quot;example.so&quot;,&quot;luaopen_example&quot;) -- for Unix/Linux
29726 --my_init=loadlib(&quot;example.dll&quot;,&quot;luaopen_example&quot;) -- for Windows
29727 assert(my_init) -- name sure its not nil
29728 my_init()       -- call the init fn of the lib
29729 </PRE>
29730 </DIV>
29731 <P> Or can be done in a single line of Lua code</P>
29732 <DIV class="targetlang">
29733 <PRE>
29734 assert(loadlib(&quot;example.so&quot;,&quot;luaopen_example&quot;))()
29735 </PRE>
29736 </DIV>
29737 <P> If the code didn't work, don't panic. The best thing to do is to
29738  copy the module and your interpreter into a single directory and then
29739  execute the interpreter and try to manually load the module (take care,
29740  all this code is case sensitive).</P>
29741 <DIV class="targetlang">
29742 <PRE>
29743 a,b,c=package.loadlib(&quot;example.so&quot;,&quot;luaopen_example&quot;) -- for Unix/Linux
29744 --a,b,c=package.loadlib(&quot;example.dll&quot;,&quot;luaopen_example&quot;) -- for Windows
29745 print(a,b,c)
29746 </PRE>
29747 </DIV>
29748 <P> Note: for Lua 5.0:
29749 <BR> The loadlib() function is in the global namespace, not in package.
29750  So its just loadlib().</P>
29751 <P> if 'a' is a function, this its all working fine, all you need to do
29752  is call it</P>
29753 <DIV class="targetlang">
29754 <PRE>
29755   a()
29756 </PRE>
29757 </DIV>
29758 <P> to load your library which will add a table 'example' with all the
29759  functions added.</P>
29760 <P> If it doesn't work, look at the error messages, in particular mesage
29761  'b'
29762 <BR> <TT> The specified module could not be found.</TT>
29763 <BR> Means that is cannot find the module, check your the location and
29764  spelling of the module.
29765 <BR> <TT> The specified procedure could not be found.</TT>
29766 <BR> Means that it loaded the module, but cannot find the named
29767  function. Again check the spelling, and if possible check to make sure
29768  the functions were exported correctly.
29769 <BR> <TT> 'loadlib' not installed/supported</TT>
29770 <BR> Is quite obvious (Go back and consult the Lua documents on how to
29771  enable loadlib for your platform).</P>
29772 <H3><A name="Lua_nn6"></A>23.2.3 Using your module</H3>
29773 <P> Assuming all goes well, you will be able to this:</P>
29774 <DIV class="targetlang">
29775 <PRE>
29776 $ ./my_lua
29777 &gt; print(example.gcd(4,6))
29778 2
29779 &gt; print(example.Foo)
29780 3
29781 &gt; example.Foo=4
29782 &gt; print(example.Foo)
29783 4
29784 &gt;
29785 </PRE>
29786 </DIV>
29787 <H2><A name="Lua_nn7"></A>23.3 A tour of basic C/C++ wrapping</H2>
29788 <P> By default, SWIG tries to build a very natural Lua interface to your
29789  C/C++ code. This section briefly covers the essential aspects of this
29790  wrapping.</P>
29791 <H3><A name="Lua_nn8"></A>23.3.1 Modules</H3>
29792 <P> The SWIG module directive specifies the name of the Lua module. If
29793  you specify `module example', then everything is wrapped into a Lua
29794  table 'example' containing all the functions and variables. When
29795  choosing a module name, make sure you don't use the same name as a
29796  built-in Lua command or standard module name.</P>
29797 <H3><A name="Lua_nn9"></A>23.3.2 Functions</H3>
29798 <P> Global functions are wrapped as new Lua built-in functions. For
29799  example,</P>
29800 <DIV class="code">
29801 <PRE>
29802 %module example
29803 int fact(int n);</PRE>
29804 </DIV>
29805 <P> creates a built-in function <TT>example.fact(n)</TT> that works
29806  exactly like you think it does:</P>
29807 <DIV class="targetlang">
29808 <PRE>
29809 &gt; print example.fact(4)
29810 24
29811 &gt;
29812 </PRE>
29813 </DIV>
29814 <P> To avoid name collisions, SWIG create a Lua table which it keeps all
29815  the functions and global variables in. It is possible to copy the
29816  functions out of this and into the global environment with the
29817  following code. This can easily overwrite existing functions, so this
29818  must be used with care.</P>
29819 <DIV class="targetlang">
29820 <PRE>
29821 &gt; for k,v in pairs(example) do _G[k]=v end
29822 &gt; print(fact(4))
29823 24
29824 &gt;
29825 </PRE>
29826 </DIV>
29827 <P> It is also possible to rename the module with an assignment.</P>
29828 <DIV class="targetlang">
29829 <PRE>
29830 &gt; e=example
29831 &gt; print(e.fact(4))
29832 24
29833 &gt; print(example.fact(4))
29834 24
29835 </PRE>
29836 </DIV>
29837 <H3><A name="Lua_nn10"></A>23.3.3 Global variables</H3>
29838 <P> Global variables (which are linked to C code) are supported, and
29839  appear to be just another variable in Lua. However the actual mechanism
29840  is more complex. Given a global variable:</P>
29841 <DIV class="code">
29842 <PRE>%module example
29843 extern double Foo;
29844 </PRE>
29845 </DIV>
29846 <P> SWIG will effectively generate two functions <TT>example.Foo_set()</TT>
29847  and <TT>example.Foo_get()</TT>. It then adds a metatable to the table
29848  'example' to call these functions at the correct time (when you attempt
29849  to set or get examples.Foo). Therefore if you were to attempt to assign
29850  the global to another variable, you will get a local copy within the
29851  interpreter, which is no longer linked to the C code.</P>
29852 <DIV class="targetlang">
29853 <PRE>
29854 &gt; print(example.Foo)
29855 3
29856 &gt; c=example.Foo   -- c is a COPY of example.Foo, not the same thing
29857 &gt; example.Foo=4
29858 &gt; print(c)
29859 3
29860 &gt; c=5 -- this will not effect the original example.Foo
29861 &gt; print(example.Foo,c)
29862 4    5
29863 </PRE>
29864 </DIV>
29865 <P> Its is therefore not possible to 'move' the global variable into the
29866  global namespace as it is with functions. It is however, possible to
29867  rename the module with an assignment, to make it more convenient.</P>
29868 <DIV class="targetlang">
29869 <PRE>
29870 &gt; e=example
29871 &gt; -- e and example are the same table
29872 &gt; -- so e.Foo and example.Foo are the same thing
29873 &gt; example.Foo=4
29874 &gt; print(e.Foo)
29875 4
29876 </PRE>
29877 </DIV>
29878 <P> If a variable is marked with the %immutable directive then any
29879  attempts to set this variable will cause an Lua error. Given a global
29880  variable:</P>
29881 <DIV class="code">
29882 <PRE>%module example
29883 %immutable;
29884 extern double Foo;
29885 %mutable;
29886 </PRE>
29887 </DIV>
29888 <P> SWIG will allow the the reading of <TT>Foo</TT> but when a set
29889  attempt is made, an error function will be called.</P>
29890 <DIV class="targetlang">
29891 <PRE>
29892 &gt; print(e.Foo) -- reading works ok
29893 4
29894 &gt; example.Foo=40 -- but writing does not
29895 This variable is immutable
29896 stack traceback:
29897         [C]: ?
29898         [C]: ?
29899         stdin:1: in main chunk
29900         [C]: ?
29901 </PRE>
29902 </DIV>
29903 <P> For those people who would rather that SWIG silently ignore the
29904  setting of immutables (as previous versions of the Lua bindings did),
29905  adding a <TT>-DSWIGLUA_IGNORE_SET_IMMUTABLE</TT> compile option will
29906  remove this.</P>
29907 <P> Unlike earlier versions of the binding, it is now possible to add
29908  new functions or variables to the module, just as if it were a normal
29909  table. This also allows the user to rename/remove existing functions
29910  and constants (but not linked variables, mutable or immutable).
29911  Therefore users are recommended to be careful when doing so.</P>
29912 <DIV class="targetlang">
29913 <PRE>
29914 &gt; -- example.PI does not exist
29915 &gt; print(example.PI)
29916 nil
29917 &gt; example.PI=3.142 -- new value added
29918 &gt; print(example.PI)
29919 3.142
29920 </PRE>
29921 </DIV>
29922 <H3><A name="Lua_nn11"></A>23.3.4 Constants and enums</H3>
29923 <P> Because Lua doesn't really have the concept of constants, C/C++
29924  constants are not really constant in Lua. They are actually just a copy
29925  of the value into the Lua interpreter. Therefore they can be changed
29926  just as any other value. For example given some constants:</P>
29927 <DIV class="code">
29928 <PRE>%module example
29929 %constant int ICONST=42;
29930 #define    SCONST      &quot;Hello World&quot;
29931 enum Days{SUNDAY,MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY};
29932 </PRE>
29933 </DIV>
29934 <P> This is 'effectively' converted into the following Lua code:</P>
29935 <DIV class="targetlang">
29936 <PRE>
29937 example.ICONST=42
29938 example.SCONST=&quot;Hello World&quot;
29939 example.SUNDAY=0
29940 ....
29941 </PRE>
29942 </DIV>
29943 <P> Constants are not guaranteed to remain constant in Lua. The name of
29944  the constant could be accidentally reassigned to refer to some other
29945  object. Unfortunately, there is no easy way for SWIG to generate code
29946  that prevents this. You will just have to be careful.</P>
29947 <H3><A name="Lua_nn12"></A>23.3.5 Pointers</H3>
29948 <P> C/C++ pointers are fully supported by SWIG. Furthermore, SWIG has no
29949  problem working with incomplete type information. Given a wrapping of
29950  the &lt;file.h&gt; interface:</P>
29951 <DIV class="code">
29952 <PRE>%module example
29953
29954 FILE *fopen(const char *filename, const char *mode);
29955 int fputs(const char *, FILE *);
29956 int fclose(FILE *);
29957 </PRE>
29958 </DIV>
29959 <P> When wrapped, you will be able to use the functions in a natural way
29960  from Lua. For example:</P>
29961 <DIV class="targetlang">
29962 <PRE>
29963 &gt; f=example.fopen(&quot;junk&quot;,&quot;w&quot;)
29964 &gt; example.fputs(&quot;Hello World&quot;,f)
29965 &gt; example.fclose(f)
29966 </PRE>
29967 </DIV>
29968 <P> Unlike many scripting languages, Lua has had support for pointers to
29969  C/C++ object built in for a long time. They are called 'userdata'.
29970  Unlike many other SWIG versions which use some kind of encoded
29971  character string, all objects will be represented as a userdata. The
29972  SWIG-Lua bindings provides a special function <TT>swig_type()</TT>,
29973  which if given a userdata object will return the type of object pointed
29974  to as a string (assuming it was a SWIG wrappered object).</P>
29975 <DIV class="targetlang">
29976 <PRE>
29977 &gt; print(f)
29978 userdata: 003FDA80
29979 &gt; print(swig_type(f))
29980 FILE * -- its a FILE*
29981 </PRE>
29982 </DIV>
29983 <P> Lua enforces the integrity of its userdata, so it is virtually
29984  impossible to corrupt the data. But as the user of the pointer, you are
29985  responsible for freeing it, or closing any resources associated with it
29986  (just as you would in a C program). This does not apply so strictly to
29987  classes &amp; structs (see below). One final note: if a function returns a
29988  NULL pointer, this is not encoded as a userdata, but as a Lua nil.</P>
29989 <DIV class="targetlang">
29990 <PRE>
29991 &gt; f=example.fopen(&quot;not there&quot;,&quot;r&quot;) -- this will return a NULL in C
29992 &gt; print(f)
29993 nil
29994 </PRE>
29995 </DIV>
29996 <H3><A name="Lua_nn13"></A>23.3.6 Structures</H3>
29997 <P> If you wrap a C structure, it is also mapped to a Lua userdata. By
29998  adding a metatable to the userdata, this provides a very natural
29999  interface. For example,</P>
30000 <DIV class="code">
30001 <PRE>struct Point{
30002   int x,y;
30003 };
30004 </PRE>
30005 </DIV>
30006 <P> is used as follows:</P>
30007 <DIV class="targetlang">
30008 <PRE>
30009 &gt; p=example.new_Point()
30010 &gt; p.x=3
30011 &gt; p.y=5
30012 &gt; print(p.x,p.y)
30013 3       5
30014 &gt;
30015 </PRE>
30016 </DIV>
30017 <P> Similar access is provided for unions and the data members of C++
30018  classes.
30019 <BR> C structures are created using a function <TT>new_Point()</TT>, but
30020  for C++ classes are created using just the name <TT>Point()</TT>.</P>
30021 <P> If you print out the value of p in the above example, you will see
30022  something like this:</P>
30023 <DIV class="targetlang">
30024 <PRE>
30025 &gt; print(p)
30026 userdata: 003FA320
30027 </PRE>
30028 </DIV>
30029 <P> Like the pointer in the previous section, this is held as a
30030  userdata. However, additional features have been added to make this
30031  more usable. SWIG effectivly creates some accessor/mutator functions to
30032  get and set the data. These functions will be added to the userdata's
30033  metatable. This provides the natural access to the member variables
30034  that were shown above (see end of the document for full details).</P>
30035 <P> <TT>const</TT> members of a structure are read-only. Data members
30036  can also be forced to be read-only using the immutable directive. As
30037  with other immutable's, setting attempts will be cause an error. For
30038  example:</P>
30039 <DIV class="code">
30040 <PRE>struct Foo {
30041    ...
30042    %immutable;
30043    int x;        // Read-only members
30044    char *name;
30045    %mutable;
30046    ...
30047 };
30048 </PRE>
30049 </DIV>
30050 <P> The mechanism for managing char* members as well as array members is
30051  similar to other languages. It is somewhat cumbersome and should
30052  probably be better handled by defining of typemaps (described later).</P>
30053 <P> When a member of a structure is itself a structure, it is handled as
30054  a pointer. For example, suppose you have two structures like this:</P>
30055 <DIV class="code">
30056 <PRE>struct Foo {
30057    int a;
30058 };
30059
30060 struct Bar {
30061    Foo f;
30062 };
30063 </PRE>
30064 </DIV>
30065 <P> Now, suppose that you access the f attribute of Bar like this:</P>
30066 <DIV class="targetlang">
30067 <PRE>
30068 &gt; b = Bar()
30069 &gt; x = b.f
30070 </PRE>
30071 </DIV>
30072 <P> In this case, x is a pointer that points to the Foo that is inside
30073  b. This is the same value as generated by this C code:</P>
30074 <DIV class="code">
30075 <PRE>
30076 Bar b;
30077 Foo *x = &amp;b-&gt;f;       // Points inside b
30078 </PRE>
30079 </DIV>
30080 <P> Because the pointer points inside the structure, you can modify the
30081  contents and everything works just like you would expect. For example:</P>
30082 <DIV class="targetlang">
30083 <PRE>
30084 &gt; b = Bar()
30085 &gt; b.f.a = 3               -- Modify attribute of structure member
30086 &gt; x = b.f
30087 &gt; x.a = 3                 -- Modifies the same structure
30088 </PRE>
30089 </DIV>
30090 <H3><A name="Lua_nn14"></A>23.3.7 C++ classes</H3>
30091 <P> C++ classes are wrapped by a Lua userdata as well. For example, if
30092  you have this class,</P>
30093 <DIV class="code">
30094 <PRE>class List {
30095 public:
30096   List();
30097   ~List();
30098   int  search(char *item);
30099   void insert(char *item);
30100   void remove(char *item);
30101   char *get(int n);
30102   int  length;
30103 };
30104 </PRE>
30105 </DIV>
30106 <P> you can use it in Lua like this:</P>
30107 <DIV class="targetlang">
30108 <PRE>
30109 &gt; l = example.List()
30110 &gt; l:insert(&quot;Ale&quot;)
30111 &gt; l:insert(&quot;Stout&quot;)
30112 &gt; l:insert(&quot;Lager&quot;)
30113 &gt; print(l:get(1))
30114 Stout
30115 &gt; print(l:length)
30116 3
30117 &gt;
30118 </PRE>
30119 </DIV>
30120 <P> (Note: for calling methods of a class, you use <TT>
30121 class:method(args)</TT>, not <TT>class.method(args)</TT>, its an easy
30122  mistake to make. However for data attributes it is <TT>class.attribute</TT>
30123 )</P>
30124 <P> Class data members are accessed in the same manner as C structures.
30125  Static class members present a special problem for Lua, as Lua doesn't
30126  have support for such features. Therefore, SWIG generates wrappers that
30127  try to work around some of these issues. To illustrate, suppose you
30128  have a class like this:</P>
30129 <DIV class="targetlang">
30130 <PRE>class Spam {
30131 public:
30132    static void foo();
30133    static int bar;
30134
30135 };
30136 </PRE>
30137 </DIV>
30138 <P> In Lua, the static members can be accessed as follows:</P>
30139 <DIV class="code">
30140 <PRE>
30141 &gt; example.Spam_foo()            -- calling Spam::foo()
30142 &gt; a=example.Spam_bar            -- reading Spam::bar 
30143 &gt; example.Spam_bar=b            -- writing to Spam::bar
30144 </PRE>
30145 </DIV>
30146 <P> It is not (currently) possible to access static members of an
30147  instance:</P>
30148 <DIV class="targetlang">
30149 <PRE>
30150 &gt; s=example.Spam()      -- s is a Spam instance
30151 &gt; s.foo()                       -- Spam::foo() via an instance
30152                                 -- does NOT work
30153 </PRE>
30154 </DIV>
30155 <H3><A name="Lua_nn15"></A>23.3.8 C++ inheritance</H3>
30156 <P> SWIG is fully aware of issues related to C++ inheritance. Therefore,
30157  if you have classes like this</P>
30158 <DIV class="code">
30159 <PRE>class Foo {
30160 ...
30161 };
30162
30163 class Bar : public Foo {
30164 ...
30165 };
30166 </PRE>
30167 </DIV>
30168 <P> And if you have functions like this</P>
30169 <DIV class="code">
30170 <PRE>void spam(Foo *f);
30171 </PRE>
30172 </DIV>
30173 <P> then the function <TT>spam()</TT> accepts a Foo pointer or a pointer
30174  to any class derived from Foo.</P>
30175 <P> It is safe to use multiple inheritance with SWIG.</P>
30176 <H3><A name="Lua_nn16"></A>23.3.9 Pointers, references, values, and
30177  arrays</H3>
30178 <P> In C++, there are many different ways a function might receive and
30179  manipulate objects. For example:</P>
30180 <DIV class="code">
30181 <PRE>void spam1(Foo *x);      // Pass by pointer
30182 void spam2(Foo &amp;x);      // Pass by reference
30183 void spam3(Foo x);       // Pass by value
30184 void spam4(Foo x[]);     // Array of objects
30185 </PRE>
30186 </DIV>
30187 <P> In SWIG, there is no detailed distinction like this--specifically,
30188  there are only &quot;objects&quot;. There are no pointers, references, arrays,
30189  and so forth. Because of this, SWIG unifies all of these types together
30190  in the wrapper code. For instance, if you actually had the above
30191  functions, it is perfectly legal to do this:</P>
30192 <DIV class="targetlang">
30193 <PRE>
30194 &gt; f = Foo()           -- Create a Foo
30195 &gt; spam1(f)            -- Ok. Pointer
30196 &gt; spam2(f)            -- Ok. Reference
30197 &gt; spam3(f)            -- Ok. Value.
30198 &gt; spam4(f)            -- Ok. Array (1 element)
30199 </PRE>
30200 </DIV>
30201 <P> Similar behaviour occurs for return values. For example, if you had
30202  functions like this,</P>
30203 <DIV class="code">
30204 <PRE>Foo *spam5();
30205 Foo &amp;spam6();
30206 Foo  spam7();
30207 </PRE>
30208 </DIV>
30209 <P> then all three functions will return a pointer to some Foo object.
30210  Since the third function (spam7) returns a value, newly allocated
30211  memory is used to hold the result and a pointer is returned (Lua will
30212  release this memory when the return value is garbage collected). The
30213  other two are pointers which are assumed to be managed by the C code
30214  and so will not be garbage collected.</P>
30215 <H3><A name="Lua_nn17"></A>23.3.10 C++ overloaded functions</H3>
30216 <P> C++ overloaded functions, methods, and constructors are mostly
30217  supported by SWIG. For example, if you have two functions like this:</P>
30218 <DIV class="code">
30219 <PRE>void foo(int);
30220 void foo(char *c);
30221 </PRE>
30222 </DIV>
30223 <P> You can use them in Lua in a straightforward manner:</P>
30224 <DIV class="targetlang">
30225 <PRE>
30226 &gt; foo(3)           -- foo(int)
30227 &gt; foo(&quot;Hello&quot;)     -- foo(char *c)
30228 </PRE>
30229 </DIV>
30230 <P> However due to Lua's coercion mechanism is can sometimes do strange
30231  things.</P>
30232 <DIV class="targetlang">
30233 <PRE>
30234 &gt; foo(&quot;3&quot;)           -- &quot;3&quot; can be coerced into an int, so it calls foo(int)!
30235 </PRE>
30236 </DIV>
30237 <P> As this coercion mechanism is an integral part of Lua, there is no
30238  easy way to get around this other than renaming of functions (see
30239  below).</P>
30240 <P> Similarly, if you have a class like this,</P>
30241 <DIV class="code">
30242 <PRE>class Foo {
30243 public:
30244     Foo();
30245     Foo(const Foo &amp;);
30246     ...
30247 };
30248 </PRE>
30249 </DIV>
30250 <P> you can write Lua code like this:</P>
30251 <DIV class="targetlang">
30252 <PRE>
30253 &gt; f = Foo()          -- Create a Foo
30254 &gt; g = Foo(f)         -- Copy f
30255 </PRE>
30256 </DIV>
30257 <P> Overloading support is not quite as flexible as in C++. Sometimes
30258  there are methods that SWIG can't disambiguate. For example:</P>
30259 <DIV class="code">
30260 <PRE>void spam(int);
30261 void spam(short);
30262 </PRE>
30263 </DIV>
30264 <P> or</P>
30265 <DIV CLASS="CODE">
30266 <PRE>VOID FOO(bAR *B);
30267 void foo(Bar &amp;b);
30268 </PRE>
30269 </DIV>
30270 <P> If declarations such as these appear, you will get a warning message
30271  like this:</P>
30272 <DIV class="shell">
30273 <PRE>
30274 example.i:12: Warning(509): Overloaded spam(short) is shadowed by spam(int)
30275 at example.i:11.
30276 </PRE>
30277 </DIV>
30278 <P> To fix this, you either need to ignore or rename one of the methods.
30279  For example:</P>
30280 <DIV class="code">
30281 <PRE>%rename(spam_short) spam(short);
30282 ...
30283 void spam(int);
30284 void spam(short);   // Accessed as spam_short
30285 </PRE>
30286 </DIV>
30287 <P> or</P>
30288 <DIV class="code">
30289 <PRE>%ignore spam(short);
30290 ...
30291 void spam(int);
30292 void spam(short);   // Ignored
30293 </PRE>
30294 </DIV>
30295 <P> SWIG resolves overloaded functions and methods using a
30296  disambiguation scheme that ranks and sorts declarations according to a
30297  set of type-precedence rules. The order in which declarations appear in
30298  the input does not matter except in situations where ambiguity
30299  arises--in this case, the first declaration takes precedence.</P>
30300 <P> Please refer to the &quot;SWIG and C++&quot; chapter for more information
30301  about overloading.</P>
30302 <P> Dealing with the Lua coercion mechanism, the priority is roughly
30303  (integers, floats, strings, userdata). But it is better to rename the
30304  functions rather than rely upon the ordering.</P>
30305 <H3><A name="Lua_nn18"></A>23.3.11 C++ operators</H3>
30306 <P> Certain C++ overloaded operators can be handled automatically by
30307  SWIG. For example, consider a class like this:</P>
30308 <DIV class="code">
30309 <PRE>class Complex {
30310 private:
30311   double rpart, ipart;
30312 public:
30313   Complex(double r = 0, double i = 0) : rpart(r), ipart(i) { }
30314   Complex(const Complex &amp;c) : rpart(c.rpart), ipart(c.ipart) { }
30315   Complex &amp;operator=(const Complex &amp;c);
30316   Complex operator+(const Complex &amp;c) const;
30317   Complex operator-(const Complex &amp;c) const;
30318   Complex operator*(const Complex &amp;c) const;
30319   Complex operator-() const;
30320
30321   double re() const { return rpart; }
30322   double im() const { return ipart; }
30323 };
30324 </PRE>
30325 </DIV>
30326 <P> When wrapped, it works like you expect:</P>
30327 <DIV class="targetlang">
30328 <PRE>
30329 &gt; c = Complex(3,4)
30330 &gt; d = Complex(7,8)
30331 &gt; e = c + d
30332 &gt; e:re()
30333 10.0
30334 &gt; e:im()
30335 12.0
30336 </PRE>
30337 </DIV>
30338 <P> One restriction with operator overloading support is that SWIG is
30339  not able to fully handle operators that aren't defined as part of the
30340  class. For example, if you had code like this</P>
30341 <DIV class="targetlang">
30342 <PRE>class Complex {
30343 ...
30344 friend Complex operator+(double, const Complex &amp;c);
30345 ...
30346 };
30347 </PRE>
30348 </DIV>
30349 <P> then SWIG doesn't know what to do with the friend function--in fact,
30350  it simply ignores it and issues a warning. You can still wrap the
30351  operator, but you may have to encapsulate it in a special function. For
30352  example:</P>
30353 <DIV class="targetlang">
30354 <PRE>%rename(Complex_add_dc) operator+(double, const Complex &amp;);
30355 ...
30356 Complex operator+(double, const Complex &amp;c);
30357 </PRE>
30358 </DIV>
30359 <P> There are ways to make this operator appear as part of the class
30360  using the <TT>%extend</TT> directive. Keep reading.</P>
30361 <P> Also, be aware that certain operators don't map cleanly to Lua, and
30362  some Lua operators don't map cleanly to C++ operators. For instance,
30363  overloaded assignment operators don't map to Lua semantics and will be
30364  ignored, and C++ doesn't support Lua's concatenation operator (<TT>..</TT>
30365 ).</P>
30366 <P> In order to keep maximum compatibility within the different
30367  languages in SWIG, the Lua bindings uses the same set of operator names
30368  as python. Although internally it renames the functions to something
30369  else (on order to work with Lua).</P>
30370 <P> The current list of operators which can be overloaded (and the
30371  alternative function names) are:</P>
30372 <UL>
30373 <LI><TT>__add__</TT> operator+</LI>
30374 <LI><TT>__sub__</TT> operator-</LI>
30375 <LI><TT>__mul__</TT> operator *</LI>
30376 <LI><TT>__div__</TT> operator/</LI>
30377 <LI><TT>__neg__</TT> unary minus</LI>
30378 <LI><TT>__call__</TT> operator<TT>()</TT> (often used in functor
30379  classes)</LI>
30380 <LI><TT>__pow__</TT> the exponential fn (no C++ equivalent, Lua uses <TT>
30381 ^</TT>)</LI>
30382 <LI><TT>__concat__</TT> the concatenation operator (SWIG maps C++'s <TT>
30383 ~</TT> to Lua's <TT>..</TT>)</LI>
30384 <LI><TT>__eq__</TT> operator<TT>==</TT></LI>
30385 <LI><TT>__lt__</TT> operator<TT>&lt;</TT></LI>
30386 <LI><TT>__le__</TT> operator<TT>&lt;=</TT></LI>
30387 </UL>
30388 <P> Note: in Lua, only the equals, less than, and less than equals
30389  operators are defined. The other operators (!=,&gt;,&gt;=) are achieved by
30390  using a logical not applied to the results of other operators.</P>
30391 <P> The following operators cannot be overloaded (mainly because they
30392  are not supported in Lua)</P>
30393 <UL>
30394 <LI>++ and --</LI>
30395 <LI>+=,-=,*= etc</LI>
30396 <LI>% operator (you have to use math.mod)</LI>
30397 <LI>assignment operator</LI>
30398 <LI>all bitwise/logical operations</LI>
30399 </UL>
30400 <P> SWIG also accepts the <TT>__str__()</TT> member function which
30401  converts an object to a string. This function should return a const
30402  char*, preferably to static memory. This will be used for the <TT>
30403 print()</TT> and <TT>tostring()</TT> functions in Lua. Assuming the
30404  complex class has a function</P>
30405 <DIV class="code">
30406 <PRE>const char* __str__()
30407 {
30408         static char buffer[255];
30409         sprintf(buffer,&quot;Complex(%g,%g)&quot;,this-&gt;re(),this-&gt;im());
30410         return buffer;
30411 }
30412 </PRE>
30413 </DIV>
30414 <P> Then this will support the following code in Lua</P>
30415 <DIV class="targetlang">
30416 <PRE>
30417 &gt; c = Complex(3,4)
30418 &gt; d = Complex(7,8)
30419 &gt; e = c + d
30420 &gt; print(e)
30421 Complex(10,12)
30422 &gt; s=tostring(e) -- s is the number in string form
30423 &gt; print(s)
30424 Complex(10,12)
30425 </PRE>
30426 </DIV>
30427 <P> It is also possible to overload the operator<TT>[]</TT>, but
30428  currently this cannot be automatically performed. To overload the
30429  operator<TT>[]</TT> you need to provide two functions, <TT>
30430 __getitem__()</TT> and <TT>__setitem__()</TT></P>
30431 <DIV class="code">
30432 <PRE>class Complex
30433 {
30434         //....
30435         double __getitem__(int i)const; // i is the index, returns the data
30436         void __setitem__(int i,double d); // i is the index, d is the data
30437 };
30438 </PRE>
30439 </DIV>
30440 <H3><A name="Lua_nn19"></A>23.3.12 Class extension with %extend</H3>
30441 <P> One of the more interesting features of SWIG is that it can extend
30442  structures and classes with new methods. In the previous section, the
30443  Complex class would have benefited greatly from an __str__() method as
30444  well as some repairs to the operator overloading. It can also be used
30445  to add additional functions to the class if they are needed.</P>
30446 <P> Take the original Complex class</P>
30447 <DIV class="code">
30448 <PRE>class Complex {
30449 private:
30450   double rpart, ipart;
30451 public:
30452   Complex(double r = 0, double i = 0) : rpart(r), ipart(i) { }
30453   Complex(const Complex &amp;c) : rpart(c.rpart), ipart(c.ipart) { }
30454   Complex &amp;operator=(const Complex &amp;c);
30455   Complex operator+(const Complex &amp;c) const;
30456   Complex operator-(const Complex &amp;c) const;
30457   Complex operator*(const Complex &amp;c) const;
30458   Complex operator-() const;
30459
30460   double re() const { return rpart; }
30461   double im() const { return ipart; }
30462 };
30463 </PRE>
30464 </DIV>
30465 <P> Now we extend it with some new code</P>
30466 <DIV class="code">
30467 <PRE>%extend Complex {
30468    const char *__str__() {
30469        static char tmp[1024];
30470        sprintf(tmp,&quot;Complex(%g,%g)&quot;, $self-&gt;re(),$self-&gt;im());
30471        return tmp;
30472    }
30473    bool operator==(const Complex&amp; c)
30474    {    return ($self-&gt;re()==c.re() &amp;&amp; $self-&gt;im()==c.im();}
30475 };
30476 </PRE>
30477 </DIV>
30478 <P> Now, in Lua</P>
30479 <DIV class="targetlang">
30480 <PRE>
30481 &gt; c = Complex(3,4)
30482 &gt; d = Complex(7,8)
30483 &gt; e = c + d
30484 &gt; print(e)      -- print uses __str__ to get the string form to print
30485 Complex(10,12)
30486 &gt; print(e==Complex(10,12))      -- testing the == operator
30487 true
30488 &gt; print(e!=Complex(12,12))  -- the != uses the == operator
30489 true
30490 </PRE>
30491 </DIV>
30492 <P> Extend works with both C and C++ code, on classes and structs. It
30493  does not modify the underlying object in any way---the extensions only
30494  show up in the Lua interface. The only item to take note of is the code
30495  has to use the '$self' instead of 'this', and that you cannot access
30496  protected/private members of the code (as you are not officially part
30497  of the class).</P>
30498 <H3><A name="Lua_nn20"></A>23.3.13 C++ templates</H3>
30499 <P> C++ templates don't present a huge problem for SWIG. However, in
30500  order to create wrappers, you have to tell SWIG to create wrappers for
30501  a particular template instantiation. To do this, you use the template
30502  directive. For example:</P>
30503 <DIV class="code">
30504 <PRE>%module example
30505 %{
30506 #include &quot;pair.h&quot;
30507 %}
30508
30509 template&lt;class T1, class T2&gt;
30510 struct pair {
30511    typedef T1 first_type;
30512    typedef T2 second_type;
30513    T1 first;
30514    T2 second;
30515    pair();
30516    pair(const T1&amp;, const T2&amp;);
30517   ~pair();
30518 };
30519
30520 %template(pairii) pair&lt;int,int&gt;;
30521 </PRE>
30522 </DIV>
30523 <P> In Lua:</P>
30524 <DIV class="targetlang">
30525 <PRE>
30526 &gt; p = example.pairii(3,4)
30527 &gt; print(p.first,p.second)
30528 3    4
30529 </PRE>
30530 </DIV>
30531 <P> Obviously, there is more to template wrapping than shown in this
30532  example. More details can be found in the SWIG and C++ chapter. Some
30533  more complicated examples will appear later.</P>
30534 <H3><A name="Lua_nn21"></A>23.3.14 C++ Smart Pointers</H3>
30535 <P> In certain C++ programs, it is common to use classes that have been
30536  wrapped by so-called &quot;smart pointers.&quot; Generally, this involves the use
30537  of a template class that implements operator-&gt;() like this:</P>
30538 <DIV class="code">
30539 <PRE>template&lt;class T&gt; class SmartPtr {
30540    ...
30541    T *operator-&gt;();
30542    ...
30543 }
30544 </PRE>
30545 </DIV>
30546 <P> Then, if you have a class like this,</P>
30547 <DIV class="code">
30548 <PRE>class Foo {
30549 public:
30550      int x;
30551      int bar();
30552 };
30553 </PRE>
30554 </DIV>
30555 <P> A smart pointer would be used in C++ as follows:</P>
30556 <DIV class="code">
30557 <PRE>SmartPtr&lt;Foo&gt; p = CreateFoo();   // Created somehow (not shown)
30558 ...
30559 p-&gt;x = 3;                        // Foo::x
30560 int y = p-&gt;bar();                // Foo::bar
30561 </PRE>
30562 </DIV>
30563 <P> To wrap this, simply tell SWIG about the SmartPtr class and the
30564  low-level Foo object. Make sure you instantiate SmartPtr using template
30565  if necessary. For example:</P>
30566 <DIV class="code">
30567 <PRE>%module example
30568 ...
30569 %template(SmartPtrFoo) SmartPtr&lt;Foo&gt;;
30570 ...
30571 </PRE>
30572 </DIV>
30573 <P> Now, in Lua, everything should just &quot;work&quot;:</P>
30574 <DIV class="targetlang">
30575 <PRE>
30576 &gt; p = example.CreateFoo()          -- Create a smart-pointer somehow
30577 &gt; p.x = 3                          -- Foo::x
30578 &gt; print(p:bar())                   -- Foo::bar
30579 </PRE>
30580 </DIV>
30581 <P> If you ever need to access the underlying pointer returned by <TT>
30582 operator-&gt;()</TT> itself, simply use the <TT>__deref__()</TT> method.
30583  For example:</P>
30584 <DIV class="targetlang">
30585 <PRE>
30586 &gt; f = p:__deref__()     -- Returns underlying Foo *
30587 </PRE>
30588 </DIV>
30589 <H3><A name="Lua_nn22"></A>23.3.15 C++ Exceptions</H3>
30590 <P> Lua does not natively support exceptions, but it has errors which
30591  are similar. When a Lua function terminates with an error it returns
30592  one value back to the caller. SWIG automatically maps any basic type
30593  which is thrown into a Lua error. Therefore for a function:</P>
30594 <DIV class="code">
30595 <PRE>
30596 int message() throw(const char *) {
30597   throw(&quot;I died.&quot;);
30598   return 1;
30599 }
30600 </PRE>
30601 </DIV>
30602 <P> SWIG will automatically convert this to a Lua error.</P>
30603 <DIV class="targetlang">
30604 <PRE>
30605 &gt; message()
30606 I died.
30607 stack traceback:
30608         [C]: in function 'message'
30609         stdin:1: in main chunk
30610         [C]: ?
30611 &gt;
30612 </PRE>
30613 </DIV>
30614 <P> If you want to catch an exception, you must use either pcall() or
30615  xpcall(), which are documented in the Lua manual. Using xpcall will
30616  allow you to obtain additional debug information (such as a
30617  stacktrace).</P>
30618 <DIV class="targetlang">
30619 <PRE>
30620 &gt; function a() b() end -- function a() calls function b()
30621 &gt; function b() message() end -- function b() calls C++ function message(), which throws 
30622 &gt; ok,res=pcall(a)  -- call the function
30623 &gt; print(ok,res)
30624 false   I died.
30625 &gt; ok,res=xpcall(a,debug.traceback)  -- call the function
30626 &gt; print(ok,res)
30627 false   I died.
30628 stack traceback:
30629         [C]: in function 'message'
30630         runme.lua:70: in function 'b'
30631         runme.lua:67: in function &lt;runme.lua:66&gt;
30632         [C]: in function 'xpcall'
30633         runme.lua:95: in main chunk
30634         [C]: ?
30635 </PRE>
30636 </DIV>
30637 <P> SWIG is able to throw numeric types, enums, chars, char*'s and
30638  std::string's without problem. It has also written typemaps for
30639  std::exception and its derived classes, which convert the exception
30640  into and error string.</P>
30641 <P> However its not so simple for to throw other types of objects.
30642  Thrown objects are not valid outside the 'catch' block. Therefore they
30643  cannot be returned to the interpreter. The obvious ways to overcome
30644  this would be to either return a copy of the object, or so convert the
30645  object to a string and return that. Though it seems obvious to perform
30646  the former, in some cases this is not possible, most notably when SWIG
30647  has no information about the object, or the object is not
30648  copyable/creatable.</P>
30649 <P> Therefore by default SWIG converts all thrown object into strings
30650  and returns them. So given a function:</P>
30651 <DIV class="code">
30652 <PRE>
30653 void throw_A() throw(A*) {
30654   throw new A();
30655 }
30656 </PRE>
30657 </DIV>
30658 <P> SWIG will just convert it (poorly) to a string and use that as its
30659  error. (Yes its not that useful, but it always works).</P>
30660 <DIV class="targetlang">
30661 <PRE>
30662 &gt; throw_A()
30663 object exception:A *
30664 stack traceback:
30665         [C]: in function 'unknown'
30666         stdin:1: in main chunk
30667         [C]: ?
30668 &gt;
30669 </PRE>
30670 </DIV>
30671 <P> To get a more useful behaviour out of SWIG you must either: provide
30672  a way to convert your exceptions into strings, or throw objects which
30673  can be copied.</P>
30674 <P> If you have your own class which you want output as a string you
30675  will need to add a typemap something like this:</P>
30676 <DIV class="code">
30677 <PRE>
30678 %typemap(throws) my_except
30679 %{ 
30680   lua_pushstring(L,$1.what()); // assuming my_except::what() returns a const char* message
30681   SWIG_fail; // trigger the error handler
30682 %}
30683 </PRE>
30684 </DIV>
30685 <P> If you wish your exception to be returned to the interpreter, it
30686  must firstly be copyable. Then you must have and additional <TT>%apply</TT>
30687  statement, to inform SWIG to return a copy of this object to the
30688  interpreter. For example:</P>
30689 <DIV class="code">
30690 <PRE>
30691 %apply SWIGTYPE EXCEPTION_BY_VAL {Exc}; // tell SWIG to return Exc by value to interpreter
30692
30693 class Exc {
30694 public:
30695   Exc(int c, const char *m) {
30696     code = c;
30697     strncpy(msg,m,256);
30698   }
30699   int code;
30700   char msg[256];
30701 };
30702
30703 void throw_exc() throw(Exc) {
30704   throw(Exc(42,&quot;Hosed&quot;));
30705
30706 </PRE>
30707 </DIV>
30708 <P> Then the following code can be used (note: we use pcall to catch the
30709  error so we can process the exception).</P>
30710 <DIV class="targetlang">
30711 <PRE>
30712 &gt; ok,res=pcall(throw_exc)
30713 &gt; print(ok)
30714 false
30715 &gt; print(res)
30716 userdata: 0003D880
30717 &gt; print(res.code,res.msg)
30718 42      Hosed
30719 &gt;
30720 </PRE>
30721 </DIV>
30722 <P> Note: is is also possible (though tedious) to have a function throw
30723  several different kinds of exceptions. To process this will require a
30724  pcall, followed by a set of if statements checking the type of the
30725  error.</P>
30726 <P> All of this code assumes that your C++ code uses exception
30727  specification (which a lot doesn't). If it doesn't consult the &quot;<A href="#SWIGPlus_catches">
30728 Exception handling with %catches</A>&quot; section and the &quot;<A href="#exception">
30729 Exception handling with %exception</A>&quot; section, for more details on how
30730  to add exception specification to functions or globally (respectively).</P>
30731 <H2><A name="Lua_nn23"></A>23.4 Typemaps</H2>
30732 <P>This section explains what typemaps are and the usage of them. The
30733  default wrappering behaviour of SWIG is enough in most cases. However
30734  sometimes SWIG may need a little additional assistance to know which
30735  typemap to apply to provide the best wrappering. This section will be
30736  explaining how to use typemaps to best effect</P>
30737 <H3><A name="Lua_nn24"></A>23.4.1 What is a typemap?</H3>
30738 <P>A typemap is nothing more than a code generation rule that is
30739  attached to a specific C datatype. For example, to convert integers
30740  from Lua to C, you might define a typemap like this:</P>
30741 <DIV class="code">
30742 <PRE>%module example
30743
30744 %typemap(in) int {
30745         $1 = (int) lua_tonumber(L,$input);
30746         printf(&quot;Received an integer : %d\n&quot;,$1);
30747 }
30748 %inline %{
30749 extern int fact(int n);
30750 %}
30751 </PRE>
30752 </DIV>
30753 <P><I>Note: you shouldn't use this typemap, as SWIG already has a
30754  typemap for this task. This is purely for example.</I></P>
30755 <P>Typemaps are always associated with some specific aspect of code
30756  generation. In this case, the &quot;in&quot; method refers to the conversion of
30757  input arguments to C/C++. The datatype int is the datatype to which the
30758  typemap will be applied. The supplied C code is used to convert values.
30759  In this code a number of special variable prefaced by a $ are used. The
30760  $1 variable is placeholder for a local variable of type int. The $input
30761  is the index on the Lua stack for the value to be used.</P>
30762 <P>When this example is compiled into a Lua module, it operates as
30763  follows:</P>
30764 <DIV class="targetlang">
30765 <PRE>&gt; require &quot;example&quot;
30766 &gt; print(example.fact(6))
30767 Received an integer : 6
30768 720
30769 </PRE>
30770 </DIV>
30771 <H3><A name="Lua_nn25"></A>23.4.2 Using typemaps</H3>
30772 <P>There are many ready written typemaps built into SWIG for all common
30773  types (int, float, short, long, char*, enum and more), which SWIG uses
30774  automatically, with no effort required on your part.</P>
30775 <P>However for more complex functions which use input/output parameters
30776  or arrays, you will need to make use of &lt;typemaps.i&gt;, which contains
30777  typemaps for these situations. For example, consider these functions:</P>
30778 <DIV class="code">
30779 <PRE>void add(int x, int y, int *result) {
30780    *result = x + y;
30781 }
30782
30783 int sub(int *x1, int *y1) {
30784    return *x1-*y1;
30785 }
30786
30787 void swap(int *sx, int *sy) {
30788    int t=*sx;
30789    *sx=*sy;
30790    *sy=t;
30791 }
30792 </PRE>
30793 </DIV>
30794 <P>It is clear to the programmer, that 'result' is an output parameter,
30795  'x1' and 'y1' are input parameters and 'sx' and 'sy' are input/output
30796  parameters. However is not apparent to SWIG, so SWIG must to informed
30797  about which kind they are, so it can wrapper accordingly.</P>
30798 <P>One means would be to rename the argument name to help SWIG, eg <TT>
30799 void add(int x, int y, int *OUTPUT)</TT>, however it is easier to use
30800  the <TT>%apply</TT> to achieve the same result, as shown below.</P>
30801 <DIV class="code">
30802 <PRE>%include &lt;typemaps.i&gt;
30803 %apply int* OUTPUT {int *result}; // int *result is output
30804 %apply int* INPUT {int *x1, int *y1}; // int *x1 and int *y1 are input
30805 %apply int* INOUT {int *sx, int *sy}; // int *sx and int *sy are input and output
30806
30807 void add(int x, int y, int *result);
30808 int sub(int *x1, int *y1);
30809 void swap(int *sx, int *sy);
30810 </PRE>
30811 </DIV>
30812 <P>When wrapped, it gives the following results:</P>
30813 <DIV class="targetlang">
30814 <PRE>&gt; require &quot;example&quot;
30815 &gt; print(example.add(1,2))
30816 3
30817 &gt; print(demo.sub(1,2))
30818 -1
30819 &gt; a,b=1,2
30820 &gt; c,d=demo.swap(a,b)
30821 &gt; print(a,b,c,d)
30822 1       2       2       1
30823 </PRE>
30824 </DIV>
30825 <P>Notice, that 'result' is not required in the arguments to call the
30826  function, as it an output parameter only. For 'sx' and 'sy' they must
30827  be passed in (as they are input), but the original value is not
30828  modified (Lua does not have a pass by reference feature). The modified
30829  results are then returned as two return values. All INPUT/OUTPUT/INOUT
30830  arguments will behave in a similar manner.</P>
30831 <P>Note: C++ references must be handled exactly the same way. However
30832  SWIG will automatically wrap a <TT>const int&amp;</TT> as an input
30833  parameter (since that it obviously input).</P>
30834 <H3><A name="Lua_nn26"></A>23.4.3 Typemaps and arrays</H3>
30835 <P>Arrays present a challenge for SWIG, because like pointers SWIG does
30836  not know whether these are input or output values, nor does SWIG have
30837  any indication of how large an array should be. However with the proper
30838  guidance SWIG can easily wrapper arrays for convenient usage.</P>
30839 <P>Given the functions:</P>
30840 <DIV class="code">
30841 <PRE>extern void sort_int(int* arr, int len);
30842 extern void sort_double(double* arr, int len);
30843 </PRE>
30844 </DIV>
30845 <P>There are basically two ways that SWIG can deal with this. The first
30846  way, uses the <TT>&lt;carrays.i&gt;</TT> library to create an array in C/C++
30847  then this can be filled within Lua and passed into the function. It
30848  works, but its a bit tedious. More details can be found in the <A href="Library.html#Library_nn5">
30849 carrays.i</A> documention.</P>
30850 <P>The second and more intuitive way, would be to pass a Lua table
30851  directly into the function, and have SWIG automatically convert between
30852  Lua-table and C-array. Within the <TT>&lt;typemaps.i&gt;</TT> file there are
30853  typemaps ready written to perform this task. To use them is again a
30854  matter of using %appy in the correct manner.</P>
30855 <P>The wrapper file below, shows both the use of carrays as well as the
30856  use of the typemap to wrap arrays.</P>
30857 <DIV class="code">
30858 <PRE>// using the C-array
30859 %include &lt;carrays.i&gt;
30860 // this declares a batch of function for manipulating C integer arrays
30861 %array_functions(int,int)
30862
30863 extern void sort_int(int* arr, int len); // the function to wrap
30864
30865 // using typemaps
30866 %include &lt;typemaps.i&gt;
30867 %apply (double *INOUT,int) {(double* arr,int len)};
30868
30869 extern void sort_double(double* arr, int len); // the function to wrap
30870 </PRE>
30871 </DIV>
30872 <P>Once wrappered, the functions can both be called, though with
30873  different ease of use:</P>
30874 <DIV class="targetlang">
30875 <PRE>require &quot;example&quot;
30876 ARRAY_SIZE=10
30877
30878 -- passing a C array to the sort_int()
30879 arr=example.new_int(ARRAY_SIZE) -- create the array
30880 for i=0,ARRAY_SIZE-1 do -- index 0..9 (just like C)
30881     example.int_setitem(arr,i,math.random(1000))
30882 end
30883 example.sort_int(arr,ARRAY_SIZE)  -- call the function
30884 example.delete_int(arr) -- must delete the allocated memory
30885
30886 -- use a typemap to call with a Lua-table
30887 -- one item of note: the typemap creates a copy, rather than edit-in-place
30888 t={} -- a Lua table
30889 for i=1,ARRAY_SIZE do -- index 1..10 (Lua style)
30890     t[i]=math.random(1000)/10
30891 end
30892 t=example.sort_double(t) -- replace t with the result
30893 </PRE>
30894 </DIV>
30895 <P>Obviously the first version could be made less tedious by writing a
30896  Lua function to perform the conversion from a table to a C-array. The <TT>
30897 %luacode</TT> directive is good for this. See SWIG\Examples\lua\arrays
30898  for an example of this.</P>
30899 <P><B>Warning:</B> in C indexes start at ZERO, in Lua indexes start at
30900  ONE. SWIG expects C-arrays to be filled for 0..N-1 and Lua tables to be
30901  1..N, (the indexing follows the norm for the language). In the typemap
30902  when it converts the table to an array it quietly changes the indexing
30903  accordingly. Take note of this behaviour if you have a C function which
30904  returns indexes.</P>
30905 <P>Note: SWIG also can support arrays of pointers in a similar manner.</P>
30906 <H3><A name="Lua_nn27"></A>23.4.4 Typemaps and pointer-pointer functions</H3>
30907 <P>Several C++ libraries use a pointer-pointer functions to create its
30908  objects. These functions require a pointer to a pointer which is then
30909  filled with the pointer to the new object. Microsoft's COM and DirectX
30910  as well as many other libraries have this kind of function. An example
30911  is given below:</P>
30912 <DIV class="code">
30913 <PRE>struct iMath;    // some structure
30914 int Create_Math(iMath** pptr); // its creator (assume it mallocs)
30915 </PRE>
30916 </DIV>
30917 <P>Which would be used with the following C code:</P>
30918 <DIV class="code">
30919 <PRE>iMath* ptr;
30920 int ok;
30921 ok=Create_Math(&amp;ptr);
30922 // do things with ptr
30923 //...
30924 free(ptr); // dispose of iMath
30925 </PRE>
30926 </DIV>
30927 <P>SWIG has a ready written typemap to deal with such a kind of function
30928  in &lt;typemaps.i&gt;. It provides the correct wrappering as well as setting
30929  the flag to inform Lua that the object in question should be garbage
30930  collected. Therefore the code is simply:</P>
30931 <DIV class="code">
30932 <PRE>%include &lt;typemaps.i&gt;
30933 %apply SWIGTYPE** OUTPUT{iMath **pptr }; // tell SWIG its an output
30934
30935 struct iMath;    // some structure
30936 int Create_Math(iMath** pptr); // its creator (assume it mallocs)
30937 </PRE>
30938 </DIV>
30939 <P>The usage is as follows:</P>
30940 <DIV class="targetlang">
30941 <PRE>ok,ptr=Create_Math() -- ptr is a iMath* which is returned with the int (ok)
30942 ptr=nil -- the iMath* will be GC'ed as normal
30943 </PRE>
30944 </DIV>
30945 <H2><A name="Lua_nn28"></A>23.5 Writing typemaps</H2>
30946 <P>This section describes how you can modify SWIG's default wrapping
30947  behavior for various C/C++ datatypes using the <TT>%typemap</TT>
30948  directive. This is an advanced topic that assumes familiarity with the
30949  Lua C API as well as the material in the &quot;<A href="#Typemaps">Typemaps</A>
30950 &quot; chapter.</P>
30951 <P>Before proceeding, it should be stressed that writing typemaps is
30952  rarely needed unless you want to change some aspect of the wrappering,
30953  or to achieve an effect which in not available with the default
30954  bindings.</P>
30955 <P>Before proceeding, you should read the previous section on using
30956  typemaps, as well as read the ready written typemaps found in
30957  luatypemaps.swg and typemaps.i. These are both well documented and
30958  fairly easy to read. You should not attempt to write your own typemaps
30959  until you have read and can understand both of these files (they may
30960  well also give you a idea to base your worn on).</P>
30961 <H3><A name="Lua_nn29"></A>23.5.1 Typemaps you can write</H3>
30962 <P>There are many different types of typemap that can be written, the
30963  full list can be found in the &quot;<A href="#Typemaps">Typemaps</A>&quot;
30964  chapter. However the following are the most commonly used ones.</P>
30965 <UL>
30966 <LI><TT>in</TT> this is for input arguments to functions</LI>
30967 <LI><TT>out</TT> this is for return types from functions</LI>
30968 <LI><TT>argout</TT> this is for a function argument which is actually
30969  returning something</LI>
30970 <LI><TT>typecheck</TT> this is used to determine which overloaded
30971  function should be called (the syntax for the typecheck is different
30972  from the typemap, see typemaps for details).</LI>
30973 </UL>
30974 <H3><A name="Lua_nn30"></A>23.5.2 SWIG's Lua-C API</H3>
30975 <P>This section explains the SWIG specific Lua-C API. It does not cover
30976  the main Lua-C api, as this is well documented and not worth covering.</P>
30977 <P><TT>int SWIG_ConvertPtr(lua_State* L,int index,void**
30978  ptr,swig_type_info *type,int flags);</TT></P>
30979 <DIV class="indent"> This is the standard function used for converting a
30980  Lua userdata to a void*. It takes the value at the given index in the
30981  Lua state and converts it to a userdata. It will then provide the
30982  neccesary type checks, confirming that the pointer is compatible with
30983  the type given in 'type'. Then finally setting '*ptr' to the pointer.
30984  If flags is set to SWIG_POINTER_DISOWN, this is will clear any
30985  ownership flag set on the object.
30986 <BR> The returns a value which can be checked with the macro SWIG_IsOK()</DIV>
30987 <P><TT>void SWIG_NewPointerObj(lua_State* L,void* ptr,swig_type_info
30988  *type,int own);</TT></P>
30989 <DIV class="indent"> This is the opposite of SWIG_ConvertPtr, as it
30990  pushes a new userdata which wrappers the pointer 'ptr' of type 'type'.
30991  The parameter 'own' specifies if the object is owned be Lua and if it
30992  is 1 then Lua will GC the object when the userdata is disposed of.</DIV>
30993 <P><TT>void* SWIG_MustGetPtr(lua_State* L,int index,swig_type_info
30994  *type,int flags,int argnum,const char* func_name);</TT></P>
30995 <DIV class="indent"> This function is a version of SWIG_ConvertPtr(),
30996  except that it will either work, or it will trigger a lua_error() with
30997  a text error message. This function is rarely used, and may be
30998  deprecated in the future.</DIV>
30999 <P><TT>SWIG_fail</TT></P>
31000 <DIV class="indent"> This macro, when called within the context of a
31001  SWIG wrappered function, will jump to the error handler code. This will
31002  call any cleanup code (freeing any temp variables) and then triggers a
31003  lua_error.
31004 <BR> A common use for this code is:
31005 <BR>
31006 <PRE>
31007 if (!SWIG_IsOK(SWIG_ConvertPtr( .....)){
31008  lua_pushstring(L,&quot;something bad happened&quot;);
31009  SWIG_fail;
31010 }</PRE>
31011 </DIV>
31012 <P><TT>SWIG_fail_arg(char* func_name,int argnum,char* type)</TT></P>
31013 <DIV class="indent"> This macro, when called within the context of a
31014  SWIG wrappered function, will display the error message and jump to the
31015  error handler code. The error message is of the form
31016 <PRE>
31017 &quot;Error in <I>func_name</I> (arg <I>argnum</I>), expected '<I>type</I>' got '<I>whatever the type was</I>'&quot;
31018 </PRE>
31019 </DIV>
31020 <P><TT>SWIG_fail_ptr(const char* fn_name,int argnum,swig_type_info*
31021  type);</TT></P>
31022 <DIV class="indent"> Similar to SWIG_fail_arg, except that it will
31023  display the swig_type_info information instead.</DIV>
31024 <H2><A name="Lua_nn31"></A>23.6 Customization of your Bindings</H2>
31025 <P> This section covers adding of some small extra bits to your module
31026  to add the last finishing touches.</P>
31027 <H3><A name="Lua_nn32"></A>23.6.1 Writing your own custom wrappers</H3>
31028 <P> Sometimes, it may be neccesary to add your own special functions,
31029  which bypass the normal SWIG wrappering method, and just use the native
31030  Lua API calls. These 'native' functions allow direct adding of your own
31031  code into the module. This is performed with the <TT>%native</TT>
31032  directive as follows:</P>
31033 <DIV class="code">
31034 <PRE>%native(my_func) int native_function(lua_State*L);  // registers native_function() with SWIG
31035 ...
31036 %{
31037 int native_function(lua_State*L) // my native code
31038 {
31039  ...
31040 }
31041 %}
31042 </PRE>
31043 </DIV>
31044 <P> The <TT>%native</TT> directive in the above example, tells SWIG that
31045  there is a function <TT>int native_function(lua_State*L);</TT> which is
31046  to be added into the module under the name '<TT>my_func</TT>'. SWIG
31047  will not add any wrappering for this function, beyond adding it into
31048  the function table. How you write your code is entirely up to you.</P>
31049 <H3><A name="Lua_nn33"></A>23.6.2 Adding additional Lua code</H3>
31050 <P> As well as adding additional C/C++ code, its also possible to add
31051  your own Lua code to the module as well. This code is executed once all
31052  other initialisation, including the %init code has been called.</P>
31053 <P> The directive <TT>%luacode</TT> adds code into the module which is
31054  executed upon loading. Normally you would use this to add your own
31055  functions to the module. Though you could easily perform other tasks.</P>
31056 <DIV class="code">
31057 <PRE>%module example;
31058
31059 %luacode {
31060   function example.greet() 
31061     print &quot;hello world&quot; 
31062   end
31063
31064   print &quot;Module loaded ok&quot;
31065 }
31066 ...
31067 %}
31068 </PRE>
31069 </DIV>
31070 <P> Notice that the code is not part of the module table. Therefore any
31071  references to the module must have the module name added.</P>
31072 <P> Should there be an error in the Lua code, this will<EM> not</EM>
31073  stop loading of the module. The default behaviour of SWIG is to print a
31074  error message to stderr and then continue. It is possible to change
31075  this behaviour by using a <TT>#define SWIG_DOSTRING_FAIL(STR)</TT> to
31076  define a different behaviour should the code fail.</P>
31077 <P> Good uses for this feature is adding of new code, or writing helper
31078  functions to simplify some of the code. See Examples/lua/arrays for an
31079  example of this code.</P>
31080 <H2><A name="Lua_nn34"></A>23.7 Details on the Lua binding</H2>
31081 <P> In the previous section, a high-level view of Lua wrapping was
31082  presented. Obviously a lot of stuff happens behind the scenes to make
31083  this happen. This section will explain some of the low-level details on
31084  how this is achieved.</P>
31085 <P><I> If you just want to use SWIG and don't care how it works, then
31086  stop reading here. This is going into the guts of the code and how it
31087  works. Its mainly for people who need to know whats going on within the
31088  code.</I></P>
31089 <H3><A name="Lua_nn35"></A>23.7.1 Binding global data into the module.</H3>
31090 <P> Assuming that you had some global data that you wanted to share
31091  between C and Lua. How does SWIG do it?</P>
31092 <DIV class="code">
31093 <PRE>%module example;
31094 extern double Foo;
31095 </PRE>
31096 </DIV>
31097 <P> SWIG will effectively generate the pair of functions</P>
31098 <DIV class="code">
31099 <PRE>void Foo_set(double);
31100 double Foo_get();
31101 </PRE>
31102 </DIV>
31103 <P> At initialisation time, it will then add to the interpreter a table
31104  called 'example', which represents the module. It will then add all its
31105  functions to the module. (Note: older versions of SWIG actually added
31106  the Foo_set() and Foo_get() functions, current implementation does not
31107  add these functions any more.) But it also adds a metatable to this
31108  table, which has two functions (<TT>__index</TT> and <TT>__newindex</TT>
31109 ) as well as two tables (<TT>.get</TT> and <TT>.set</TT>) The following
31110  Lua code will show these hidden features.</P>
31111 <DIV class="targetlang">
31112 <PRE>
31113 &gt; print(example)
31114 table: 003F8F90
31115 &gt; m=getmetatable(example)
31116 &gt; table.foreach(m,print)
31117 .set    table: 003F9088
31118 .get    table: 003F9038
31119 __index function: 003F8FE0
31120 __newindex      function: 003F8FF8
31121 &gt; g=m['.get']
31122 &gt; table.foreach(g,print)
31123 Foo     function: 003FAFD8
31124 &gt;
31125 </PRE>
31126 </DIV>
31127 <P> The .get and .set tables are lookups connecting the variable name
31128  'Foo' to the accessor/mutator functions (Foo_set,Foo_get)</P>
31129 <P> The Lua equivalent of the code for the <TT>__index</TT> and <TT>
31130 __newindex</TT> looks a bit like this</P>
31131 <DIV class="targetlang">
31132 <PRE>
31133 function __index(mod,name)
31134         local g=getmetatable(mod)['.get'] -- gets the table
31135         if not g then return nil end
31136         local f=g[name] -- looks for the function
31137         -- calls it &amp; returns the value
31138         if type(f)==&quot;function&quot; then return f() end
31139         return nil
31140 end
31141
31142 function __newindex(mod,name,value)
31143         local s=getmetatable(mod)['.set'] -- gets the table
31144         if not s then return end
31145         local f=s[name] -- looks for the function
31146         -- calls it to set the value
31147         if type(f)==&quot;function&quot; then f(value)
31148         else rawset(mod,name,value) end
31149 end
31150 </PRE>
31151 </DIV>
31152 <P> That way when you call '<TT>a=example.Foo</TT>', the interpreter
31153  looks at the table 'example' sees that there is no field 'Foo' and
31154  calls __index. This will in turn check in '.get' table and find the
31155  existence of 'Foo' and then return the value of the C function call
31156  'Foo_get()'. Similarly for the code '<TT>example.Foo=10</TT>', the
31157  interpreter will check the table, then call the __newindex which will
31158  then check the '.set' table and call the C function 'Foo_set(10)'.</P>
31159 <H3><A name="Lua_nn36"></A>23.7.2 Userdata and Metatables</H3>
31160 <P> As mentioned earlier, classes and structures, are all held as
31161  pointer, using the Lua 'userdata' structure. This structure is actually
31162  a pointer to a C structure 'swig_lua_userdata', which contains the
31163  pointer to the data, a pointer to the swig_type_info (an internal SWIG
31164  struct) and a flag which marks if the object is to be disposed of when
31165  the interpreter no longer needs it. The actual accessing of the object
31166  is done via the metatable attached to this userdata.</P>
31167 <P> The metatable is a Lua 5.0 feature (which is also why SWIG cannot
31168  wrap Lua 4.0). Its a table which holds a list of functions, operators
31169  and attributes. This is what gives the userdata the feeling that it is
31170  a real object and not just a hunk of memory.</P>
31171 <P> Given a class</P>
31172 <DIV class="code">
31173 <PRE>%module excpp;
31174
31175 class Point
31176 {
31177 public:
31178  int x,y;
31179  Point(){x=y=0;}
31180  ~Point(){}
31181  virtual void Print(){printf(&quot;Point @%p (%d,%d)\n&quot;,this,x,y);}
31182 };
31183 </PRE>
31184 </DIV>
31185 <P> SWIG will create a module excpp, with all the various function
31186  inside. However to allow the intuitive use of the userdata is also
31187  creates up a set of metatables. As seen in the above section on global
31188  variables, use of the metatables allows for wrappers to be used
31189  intuitively. To save effort, the code creates one metatable per class
31190  and stores it inside Lua's registry. Then when an new object is
31191  instantiated, the metatable is found in the registry and the userdata
31192  associated to the metatable. Currently derived classes make a complete
31193  copy of the base classes table and then add on their own additional
31194  function.</P>
31195 <P> Some of the internals can be seen by looking at a classes metatable.</P>
31196 <DIV class="targetlang">
31197 <PRE>
31198 &gt; p=excpp.Point()
31199 &gt; print(p)
31200 userdata: 003FDB28
31201 &gt; m=getmetatable(p)
31202 &gt; table.foreach(m,print)
31203 .type   Point
31204 __gc    function: 003FB6C8
31205 __newindex      function: 003FB6B0
31206 __index function: 003FB698
31207 .get    table: 003FB4D8
31208 .set    table: 003FB500
31209 .fn     table: 003FB528
31210 </PRE>
31211 </DIV>
31212 <P> The '.type' attribute is the name of the class. The '.get' and
31213  '.set' tables work in a similar manner to the modules, the main
31214  difference is the '.fn' table which also holds all the member
31215  functions. (The '__gc' function is the classes destructor function)</P>
31216 <P> The Lua equivalent of the code for enabling functions looks a little
31217  like this</P>
31218 <DIV class="targetlang">
31219 <PRE>
31220 function __index(obj,name)
31221         local m=getmetatable(obj) -- gets the metatable
31222         if not m then return nil end
31223         local g=m['.get'] -- gets the attribute table
31224         if not g then return nil end
31225         local f=g[name] -- looks for the get_attribute function
31226         -- calls it &amp; returns the value
31227         if type(f)==&quot;function&quot; then return f() end
31228         -- ok, so it not an attribute, maybe its a function
31229         local fn=m['.fn'] -- gets the function table
31230         if not fn then return nil end
31231         local f=fn[name] -- looks for the function
31232         -- if found the fn then return the function
31233         -- so the interpreter can call it
31234         if type(f)==&quot;function&quot; then return f end
31235         return nil
31236 end
31237 </PRE>
31238 </DIV>
31239 <P> So when 'p:Print()' is called, the __index looks on the object
31240  metatable for a 'Print' attribute, then looks for a 'Print' function.
31241  When it finds the function, it returns the function, and then
31242  interpreter can call 'Point_Print(p)'</P>
31243 <P> In theory, you can play with this usertable &amp; add new features, but
31244  remember that it is a shared table between all instances of one class,
31245  and you could very easily corrupt the functions in all the instances.</P>
31246 <P> Note: Both the opaque structures (like the FILE*) and normal
31247  wrappered classes/structs use the same 'swig_lua_userdata' structure.
31248  Though the opaque structures has do not have a metatable attached, or
31249  any information on how to dispose of them when the interpreter has
31250  finished with them.</P>
31251 <P> Note: Operator overloads are basically done in the same way, by
31252  adding functions such as '__add' &amp; '__call' to the classes metatable.
31253  The current implementation is a bit rough as it will add any member
31254  function beginning with '__' into the metatable too, assuming its an
31255  operator overload.</P>
31256 <H3><A name="Lua_nn37"></A>23.7.3 Memory management</H3>
31257 <P> Lua is very helpful with the memory management. The
31258  'swig_lua_userdata' is fully managed by the interpreter itself. This
31259  means that neither the C code nor the Lua code can damage it. Once a
31260  piece of userdata has no references to it, it is not instantly
31261  collected, but will be collected when Lua deems is necessary. (You can
31262  force collection by calling the Lua function <TT>collectgarbage()</TT>
31263 ). Once the userdata is about to be free'ed, the interpreter will check
31264  the userdata for a metatable and for a function '__gc'. If this exists
31265  this is called. For all complete types (ie normal wrappered classes &amp;
31266  structs) this should exist. The '__gc' function will check the
31267  'swig_lua_userdata' to check for the 'own' field and if this is true
31268  (which is will be for all owned data's) it will then call the
31269  destructor on the pointer.</P>
31270 <P> It is currently not recommended to edit this field or add some user
31271  code, to change the behaviour. Though for those who wish to try, here
31272  is where to look.</P>
31273 <P> It is also currently not possible to change the ownership flag on
31274  the data (unlike most other scripting languages, Lua does not permit
31275  access to the data from within the interpreter)</P>
31276 <HR NOSHADE>
31277 <H1><A name="Modula3"></A>24 SWIG and Modula-3</H1>
31278
31279 <!-- INDEX -->
31280 <DIV class="sectiontoc">
31281 <UL>
31282 <LI><A href="#modula3_overview">Overview</A>
31283 <UL>
31284 <LI><A href="#whyscripting">Why not scripting ?</A></LI>
31285 <LI><A href="#whymodula3">Why Modula-3 ?</A></LI>
31286 <LI><A href="#whycpp">Why C / C++ ?</A></LI>
31287 <LI><A href="#whyswig">Why SWIG ?</A></LI>
31288 </UL>
31289 </LI>
31290 <LI><A href="#conception">Conception</A>
31291 <UL>
31292 <LI><A href="#cinterface">Interfaces to C libraries</A></LI>
31293 <LI><A href="#cppinterface">Interfaces to C++ libraries</A></LI>
31294 </UL>
31295 </LI>
31296 <LI><A href="#preliminaries">Preliminaries</A>
31297 <UL>
31298 <LI><A href="#compilers">Compilers</A></LI>
31299 <LI><A href="#commandline">Additional Commandline Options</A></LI>
31300 </UL>
31301 </LI>
31302 <LI><A href="#modula3_typemaps">Modula-3 typemaps</A>
31303 <UL>
31304 <LI><A href="#inoutparam">Inputs and outputs</A></LI>
31305 <LI><A href="#ordinals">Subranges, Enumerations, Sets</A></LI>
31306 <LI><A href="#class">Objects</A></LI>
31307 <LI><A href="#imports">Imports</A></LI>
31308 <LI><A href="#exceptions">Exceptions</A></LI>
31309 <LI><A href="#typemap_example">Example</A></LI>
31310 </UL>
31311 </LI>
31312 <LI><A href="#hints">More hints to the generator</A>
31313 <UL>
31314 <LI><A href="#features">Features</A></LI>
31315 <LI><A href="#pragmas">Pragmas</A></LI>
31316 </UL>
31317 </LI>
31318 <LI><A href="#remarks">Remarks</A></LI>
31319 </UL>
31320 </DIV>
31321 <!-- INDEX -->
31322 <P> This chapter describes SWIG's support of <A href="http://www.m3.org/">
31323 Modula-3</A>. You should be familiar with the <A href="#SWIG">basics</A>
31324  of SWIG, especially <A href="Typemaps.html">typemaps</A>.</P>
31325 <H2><A name="modula3_overview"></A>24.1 Overview</H2>
31326 <P> The Modula-3 support is very basic and highly experimental! Many
31327  features are still not designed satisfyingly and I need more discussion
31328  about the odds and ends. Don't rely on any feature, incompatible
31329  changes are likely in the future! The Modula-3 generator was already
31330  useful for interfacing to the libraries</P>
31331 <OL>
31332 <LI> <A href="http://www.elegosoft.com/cgi-bin/cvsweb.cgi/cm3/m3-libs/plplot/">
31333  PLPlot</A></LI>
31334 <LI> <A href="http://www.elegosoft.com/cgi-bin/cvsweb.cgi/cm3/m3-libs/fftw/">
31335  FFTW</A> .</LI>
31336 </OL>
31337 <P> I took some more time to explain why I think it's right what I'm
31338  doing. So the introduction got a bit longer than it should ... ;-)</P>
31339 <H3><A name="whyscripting"></A>24.1.1 Why not scripting ?</H3>
31340 <P> SWIG started as wrapper from the fast compiled languages C and C++
31341  to high level scripting languages like Python. Although scripting
31342  languages are designed to make programming life easier by hiding
31343  machine internals from the programmer there are several aspects of
31344  today's scripting languages that are unfavourable in my opinion.</P>
31345 <P> Besides C, C++, Cluster (a Modula derivate for Amiga computers) I
31346  evaluated several scripting like languages in the past: Different
31347  dialects of BASIC, Perl, ARexx (a variant of Rexx for Amiga computers),
31348  shell scripts. I found them too inconsistent, too weak in
31349  distinguishing types, too weak in encapsulating pieces of code.
31350  Eventually I have started several projects in Python because of the
31351  fine syntax. But when projects became larger I lost the track. I got
31352  convinced that one can not have maintainable code in a language that is
31353  not statically typed. In fact the main advantages of scripting
31354  languages e.g. matching regular expressions, complex built-in datatypes
31355  like lists, dictionaries, are not advantages of the language itself but
31356  can be provided by function libraries.</P>
31357 <H3><A name="whymodula3"></A>24.1.2 Why Modula-3 ?</H3>
31358 <P> Modula-3 is a compiler language in the tradition of Niklaus Wirth's
31359  Modula 2, which is in turn a successor of the popular Pascal. I have
31360  chosen Modula-3 because of its logical syntax, strong modularization,
31361  the type system which is very detailed for machine types compared to
31362  other languages. Of course it supports all of the modern games like
31363  exceptions, objects, garbage collection, threads. While C++ programmers
31364  must control three languages, namely the preprocessor, C and ++,
31365  Modula-3 is made in one go and the language definition is really
31366  compact.</P>
31367 <P> On the one hand Modula-3 can be safe (but probably less efficient)
31368  in normal modules while providing much static and dynamic safety. On
31369  the other hand you can write efficient but less safe code in the style
31370  of C within <TT>UNSAFE</TT> modules.</P>
31371 <P> Unfortunately Modula's safety and strength requires more writing
31372  than scripting languages do. Today if I want to safe characters I
31373  prefer Haskell (similar to OCAML) - it's statically typed, too.</P>
31374 <H3><A name="whycpp"></A>24.1.3 Why C / C++ ?</H3>
31375 <P> Although it is no problem to write Modula-3 programs that performs
31376  as fast as C most libraries are not written in Modula-3 but in C.
31377  Fortunately the binary interface of most function libraries can be
31378  addressed by Modula-3. Even more fortunately even non-C libraries may
31379  provide C header files. This is where SWIG becomes helpful.</P>
31380 <H3><A name="whyswig"></A>24.1.4 Why SWIG ?</H3>
31381 <P> The C headers and the possibility to interface to C libraries still
31382  leaves the work for you to write Modula-3 interfaces to them. To make
31383  things comfortable you will also need wrappers that convert between
31384  high-level features of Modula-3 (garbage collecting, exceptions) and
31385  the low level of the C libraries.</P>
31386 <P> SWIG converts C headers to Modula-3 interfaces for you. You could
31387  call the C functions without loss of efficiency but it won't be joy
31388  because you could not pass <TT>TEXT</TT>s or open arrays and you would
31389  have to process error return codes rather then exceptions. But using
31390  some typemaps SWIG will also generate wrappers that bring the whole
31391  Modula-3 comfort to you. If the library API is ill designed writing
31392  appropriate typemaps can be still time-consuming. E.g. C programmers
31393  are very creative to work-around missing data types like (real)
31394  enumerations and sets. You should turn such work-arounds back to the
31395  Modula-3 way otherwise you lose static safety and consistency.</P>
31396 <P> But you have still a problem: C library interfaces are often ill.
31397  They lack for certain information because C compilers wouldn't care
31398  about. You should integrate detailed type information by adding <TT>
31399 typedef</TT>s and <TT>const</TT>s and you should persuade the C library
31400  programmer to add this information to his interface. Only this way
31401  other language users can benefit from your work and only this way you
31402  can easily update your interfaces when a new library version is
31403  released. You will realise that writing<B> good</B> SWIG interfaces is
31404  very costly and it will only amortise when considering evolving
31405  libraries.</P>
31406 <P> Without SWIG you would probably never consider to call C++ libraries
31407  from Modula-3. But with SWIG this is worth a consideration. SWIG can
31408  write C wrappers to C++ functions and object methods that may throw
31409  exceptions. In fact it breaks down C++ libraries to C interfaces which
31410  can be in turn called from Modula-3. To make it complete you can hide
31411  the C interface with Modula-3 classes and exceptions.</P>
31412 <P> Although SWIG does the best it can do it can only serve as a one-way
31413  strategy. That means you can use C++ libraries with Modula-3 (even with
31414  call back functions), but it's certainly not possible to smoothly
31415  integrate Modula-3 code into a C / C++ project.</P>
31416 <H2><A name="conception"></A>24.2 Conception</H2>
31417 <H3><A name="cinterface"></A>24.2.1 Interfaces to C libraries</H3>
31418 <P> Modula-3 has an integrated support for calling C functions. This is
31419  also extensively used by the standard Modula-3 libraries to call OS
31420  functions. The Modula-3 part of SWIG and the corresponding SWIG library
31421  <A href="../../Lib/modula3/modula3.swg"><TT>modula3.swg</TT></A>
31422  contain code that uses these features. Because of the built-in support
31423  there is no need for calling the SWIG kernel to generate wrappers
31424  written in C. All conversion and argument checking can be done in
31425  Modula-3 and the interfacing is quite efficient. All you have to do is
31426  to write pieces of Modula-3 code that SWIG puts together.</P>
31427 <TABLE border summary="Modula-3 C library support">
31428 <TR><TH colspan="2">C library support integrated in Modula-3</TH><TH></TH>
31429 </TR>
31430 <TR><TD>Pragma <TT>&lt;* EXTERNAL *&gt;</TT></TD><TD>Precedes a declaration of
31431  a PROCEDURE that is implemented in an external library instead of a
31432  Modula-3 module.</TD></TR>
31433 <TR><TD>Pragma <TT>&lt;* CALLBACK *&gt;</TT></TD><TD>Precedes a declaration of
31434  a PROCEDURE that should be called by external library code.</TD></TR>
31435 <TR><TD>Module <TT>Ctypes</TT></TD><TD>Contains Modula-3 types that
31436  match some basic C types.</TD></TR>
31437 <TR><TD>Module <TT>M3toC</TT></TD><TD>Contains routines that convert
31438  between Modula-3's <TT>TEXT</TT> type and C's <TT>char *</TT> type.</TD>
31439 </TR>
31440 </TABLE>
31441 <P> In each run of SWIG the Modula-3 part generates several files:</P>
31442 <TABLE border summary="Modula-3 generated files">
31443 <TR><TH>Module name scheme</TH><TH>Identifier for <TT>%insert</TT></TH><TH>
31444 Description</TH></TR>
31445 <TR><TD>Module<TT>Raw.i3</TT></TD><TD><TT>m3rawintf</TT></TD><TD>
31446 Declaration of types that are equivalent to those of the C library, <TT>
31447 EXTERNAL</TT> procedures as interface to the C library functions</TD></TR>
31448 <TR><TD>Module<TT>Raw.m3</TT></TD><TD><TT>m3rawimpl</TT></TD><TD>Almost
31449  empty.</TD></TR>
31450 <TR><TD>Module<TT>.i3</TT></TD><TD><TT>m3wrapintf</TT></TD><TD>
31451 Declaration of comfortable wrappers to the C library functions.</TD></TR>
31452 <TR><TD>Module<TT>.m3</TT></TD><TD><TT>m3wrapimpl</TT></TD><TD>
31453 Implementation of the wrappers that convert between Modula-3 and C
31454  types, check for validity of values, hand-over resource management to
31455  the garbage collector using <TT>WeakRef</TT>s and raises exceptions.</TD>
31456 </TR>
31457 <TR><TD><TT>m3makefile</TT></TD><TD><TT>m3makefile</TT></TD><TD>Add the
31458  modules above to the Modula-3 project and specify the name of the
31459  Modula-3 wrapper library to be generated. Today I'm not sure if it is a
31460  good idea to create a <TT>m3makefile</TT> in each run, because SWIG
31461  must be started for each Modula-3 module it creates. Thus the
31462  m3makefile is overwritten each time. :-(</TD></TR>
31463 </TABLE>
31464 <P> Here's a scheme of how the function calls to Modula-3 wrappers are
31465  redirected to C library functions:</P>
31466 <TABLE summary="Modula-3 C library">
31467 <TR><TD align="center"> Modula-3 wrapper
31468 <BR> Module<TT>.i3</TT>
31469 <BR> generated by Modula-3 part of SWIG</TD><TD></TD><TD align="center"></TD>
31470 </TR>
31471 <TR><TD align="center">
31472 <!-- pre tag overrides centering -->
31473  |
31474 <BR> v</TD><TD></TD><TD align="center"></TD></TR>
31475 <TR><TD align="center"> Modula-3 interface to C
31476 <BR> Module<TT>Raw.i3</TT>
31477 <BR> generated by Modula-3 part of SWIG</TD><TD>--&gt;</TD><TD align="center">
31478  C library</TD></TR>
31479 </TABLE>
31480 <P> I have still no good conception how one can split C library
31481  interfaces into type oriented interfaces. A Module in Modula-3
31482  represents an Abstract DataType (or call it a static classes, i.e. a
31483  class without virtual methods). E.g. if you have a principal type, say <TT>
31484 Database</TT>, it is good Modula-3 style to set up one Module with the
31485  name <TT>Database</TT> where the database type is declared with the
31486  name <TT>T</TT> and where all functions are declared that operates on
31487  it.</P>
31488 <P> The normal operation of SWIG is to generate a fixed set of files per
31489  call. To generate multiple modules one has to write one SWIG interface
31490  (different SWIG interfaces can share common data) per module.
31491  Identifiers belonging to a different module may ignored (<TT>%ignore</TT>
31492 ) and the principal type must be renamed (<TT>%typemap</TT>).</P>
31493 <H3><A name="cppinterface"></A>24.2.2 Interfaces to C++ libraries</H3>
31494 <P> Interfaces to C++ files are much more complicated and there are some
31495  more design decisions that are not made, yet. Modula-3 has no support
31496  for C++ functions but C++ compilers should support generating C++
31497  functions with a C interface.</P>
31498 <P> Here's a scheme of how the function calls to Modula-3 wrappers a
31499  redirected to C library functions:</P>
31500 <TABLE summary="Modula-3 C++ library">
31501 <TR><TD align="center"> Modula-3 wrapper
31502 <BR> Module<TT>.i3</TT>
31503 <BR> generated by Modula-3 part of SWIG</TD><TD></TD><TD align="center">
31504 C++ library</TD></TR>
31505 <TR><TD align="center">
31506 <!-- pre tag overrides centering -->
31507  |
31508 <BR> v</TD><TD></TD><TD align="center"> ^
31509 <BR> |</TD></TR>
31510 <TR><TD align="center"> Modula-3 interface to C
31511 <BR> Module<TT>Raw.i3</TT>
31512 <BR> generated by Modula-3 part of SWIG</TD><TD>--&gt;</TD><TD align="center">
31513  C interface to C++
31514 <BR> module<TT>_wrap.cxx</TT>
31515 <BR> generated by the SWIG core</TD></TR>
31516 </TABLE>
31517 <P> Wrapping C++ libraries arises additional problems:</P>
31518 <UL>
31519 <LI> Is it sensible to wrap C++ classes with Modula-3 classes?</LI>
31520 <LI> How to find the wrapping Modula-3 class for a class pointer that is
31521  returned by a C++ routine?</LI>
31522 <LI> How to deal with multiple inheritance which was neglected for
31523  Modula-3 for good reasons?</LI>
31524 <LI> Is it possible to sub-class C++ classes with Modula-3 code? This
31525  issue is addressed by directors, a feature that was experimentally
31526  added to some Language modules like <A href="#java_directors">Java</A>
31527  and <A href="Python.html#directors">Python</A>.</LI>
31528 <LI> How to manage storage with the garbage collector of Modula-3?
31529  Support for <A href="#ownership"> <TT>%newobject</TT> and <TT>
31530 %typemap(newfree)</TT></A> isn't implemented, yet. What's about
31531  resources that are managed by the garbage collector but shall be passed
31532  back to the storage management of the C++ library? This is a general
31533  issue which is not solved in a satisfying fashion as far as I know.</LI>
31534 <LI> How to turn C++ exceptions into Modula-3 exceptions? There's also
31535  no support for <A href="#exception"> <TT>%exception</TT></A>, yet.</LI>
31536 </UL>
31537 <P> Be warned: There is no C++ library I wrote a SWIG interface for, so
31538  I'm not sure if this is possible or sensible, yet.</P>
31539 <H2><A name="preliminaries"></A>24.3 Preliminaries</H2>
31540 <H3><A name="compilers"></A>24.3.1 Compilers</H3>
31541 <P> There are different Modula-3 compilers around: cm3, pm3, ezm3,
31542  Klagenfurth Modula-3, Cambridge Modula-3. SWIG itself does not contain
31543  compiler specific code but the library file <A href="../../Lib/modula3/modula3.swg">
31544 <TT>modula3.swg</TT></A> may do so. For testing examples I use Critical
31545  Mass cm3.</P>
31546 <H3><A name="commandline"></A>24.3.2 Additional Commandline Options</H3>
31547 <P> There are some experimental command line options that prevent SWIG
31548  from generating interface files. Instead files are emitted that may
31549  assist you when writing SWIG interface files.</P>
31550 <TABLE border summary="Modula-3 specific options">
31551 <TR><TH>Modula-3 specific options</TH><TH>Description</TH></TR>
31552 <TR><TD valign="top">-generateconst &lt;file&gt;</TD><TD> Disable generation
31553  of interfaces and wrappers. Instead write code for computing numeric
31554  values of constants to the specified file.
31555 <BR> C code may contain several constant definitions written as
31556  preprocessor macros. Other language modules of SWIG use
31557  compute-once-use-readonly variables or functions to wrap such
31558  definitions. All of them can invoke C code dynamically for computing
31559  the macro values. But if one wants to turn them into Modula-3 integer
31560  constants, enumerations or set types, the values of these expressions
31561  has to be known statically. Although definitions like <TT>(1 &lt;&lt;
31562  FLAG_MAXIMIZEWINDOW)</TT> must be considered as good C style they are
31563  hard to convert to Modula-3 since the value computation can use every
31564  feature of C.
31565 <BR> Thus I implemented these switch to extract all constant definitions
31566  and write a C program that output the values of them. It works for
31567  numeric constants only and treats all of them as <TT>double</TT>.
31568  Future versions may generate a C++ program that can detect the type of
31569  the macros by overloaded output functions. Then strings can also be
31570  processed.</TD></TR>
31571 <TR><TD valign="top">-generaterename &lt;file&gt;</TD><TD> Disable generation
31572  of interfaces and wrappers. Instead generate suggestions for <TT>
31573 %rename</TT>.
31574 <BR> C libraries use a naming style that is neither homogeneous nor
31575  similar to that of Modula-3. C function names often contain a prefix
31576  denoting the library and some name components separated by underscores
31577  or capitalization changes. To get library interfaces that are really
31578  Modula-3 like you should rename the function names with the <TT>%rename</TT>
31579  directive. This switch outputs a list of such directives with a name
31580  suggestion generated by a simple heuristic.</TD></TR>
31581 <TR><TD valign="top">-generatetypemap &lt;file&gt;</TD><TD> Disable generation
31582  of interfaces and wrappers. Instead generate templates for some basic
31583  typemaps.</TD></TR>
31584 </TABLE>
31585 <H2><A name="modula3_typemaps"></A>24.4 Modula-3 typemaps</H2>
31586 <H3><A name="inoutparam"></A>24.4.1 Inputs and outputs</H3>
31587 <P> Each C procedure has a bunch of inputs and outputs. Inputs are
31588  passed as function arguments, outputs are updated referential arguments
31589  and the function value.</P>
31590 <P> Each C type can have several typemaps that apply only in case if a
31591  type is used for an input argument, for an output argument, or for a
31592  return value. A further typemap may specify the direction that is used
31593  for certain parameters. I have chosen this separation in order to be
31594  able to write general typemaps for the typemap library <A href="../../Lib/modula3/modula3.swg">
31595 <TT>modula3.swg</TT></A> . In the library code the final usage of the
31596  type is not known. Using separate typemaps for each possible use allows
31597  appropriate definitions for each case. If these pre-definitions are
31598  fine then the direction of the function parameter is the only hint the
31599  user must give.</P>
31600 <P> The typemaps specific to Modula-3 have a common name scheme: A
31601  typemap name starts with &quot;m3&quot;, followed by &quot;raw&quot; or &quot;wrap&quot; depending on
31602  whether it controls the generation of the Module<TT>Raw.i3</TT> or the
31603  Module<TT>.i3</TT>, respectively. It follows an &quot;in&quot; for typemaps
31604  applied to input argument, &quot;out&quot; for output arguments, &quot;arg&quot; for all
31605  kind of arguments, &quot;ret&quot; for returned values.</P>
31606 <P> The main task of SWIG is to build wrapper function, i.e. functions
31607  that convert values between C and Modula-3 and call the corresponding C
31608  function. Modula-3 wrapper functions generated by SWIG consist of the
31609  following parts:</P>
31610 <UL>
31611 <LI>Generate <TT>PROCEDURE</TT> signature.</LI>
31612 <LI>Declare local variables.</LI>
31613 <LI>Convert input values from Modula-3 to C.</LI>
31614 <LI>Check for input value integrity.</LI>
31615 <LI>Call the C function.</LI>
31616 <LI>Check returned values, e.g. error codes.</LI>
31617 <LI>Convert and write back values into Modula-3 records.</LI>
31618 <LI>Free temporary storage.</LI>
31619 <LI>Return values.</LI>
31620 </UL>
31621 <TABLE border summary="Modula-3 typemaps">
31622 <TR><TH>Typemap</TH><TH>Example</TH><TH>Description</TH></TR>
31623 <TR><TD>m3wrapargvar</TD><TD><TT>$1: INTEGER := $1_name;</TT></TD><TD>
31624  Declaration of some variables needed for temporary results.</TD></TR>
31625 <TR><TD>m3wrapargconst</TD><TD><TT>$1 = &quot;$1_name&quot;;</TT></TD><TD>
31626  Declaration of some constant, maybe for debug purposes.</TD></TR>
31627 <TR><TD>m3wrapargraw</TD><TD><TT>ORD($1_name)</TT></TD><TD> The
31628  expression that should be passed as argument to the raw Modula-3
31629  interface function.</TD></TR>
31630 <TR><TD>m3wrapargdir</TD><TD><TT>out</TT></TD><TD> Referential arguments
31631  can be used for input, output, update. ???</TD></TR>
31632 <TR><TD>m3wrapinmode</TD><TD><TT>READONLY</TT></TD><TD> One of Modula-3
31633  parameter modes <TT>VALUE</TT> (or empty), <TT>VAR</TT>, <TT>READONLY</TT>
31634 </TD></TR>
31635 <TR><TD>m3wrapinname</TD><TD></TD><TD> New name of the input argument.</TD>
31636 </TR>
31637 <TR><TD>m3wrapintype</TD><TD></TD><TD> Modula-3 type of the input
31638  argument.</TD></TR>
31639 <TR><TD>m3wrapindefault</TD><TD></TD><TD> Default value of the input
31640  argument</TD></TR>
31641 <TR><TD>m3wrapinconv</TD><TD><TT>$1 := M3toC.SharedTtoS($1_name);</TT></TD><TD>
31642  Statement for converting the Modula-3 input value to C compliant value.</TD>
31643 </TR>
31644 <TR><TD>m3wrapincheck</TD><TD><TT>IF Text.Length($1_name) &gt; 10 THEN
31645  RAISE E(&quot;str too long&quot;); END;</TT></TD><TD> Check the integrity of the
31646  input value.</TD></TR>
31647 <TR><TD>m3wrapoutname</TD><TD></TD><TD> Name of the <TT>RECORD</TT>
31648  field to be used for returning multiple values. This applies to
31649  referential output arguments that shall be turned into return values.</TD>
31650 </TR>
31651 <TR><TD>m3wrapouttype</TD><TD></TD><TD> Type of the value that is
31652  returned instead of a referential output argument.</TD></TR>
31653 <TR><TD>m3wrapoutconv</TD><TD></TD><TD></TD></TR>
31654 <TR><TD>m3wrapoutcheck</TD><TD></TD><TD></TD></TR>
31655 <TR><TD>m3wrapretraw</TD><TD></TD><TD></TD></TR>
31656 <TR><TD>m3wrapretname</TD><TD></TD><TD></TD></TR>
31657 <TR><TD>m3wraprettype</TD><TD></TD><TD></TD></TR>
31658 <TR><TD>m3wrapretvar</TD><TD></TD><TD></TD></TR>
31659 <TR><TD>m3wrapretconv</TD><TD></TD><TD></TD></TR>
31660 <TR><TD>m3wrapretcheck</TD><TD></TD><TD></TD></TR>
31661 <TR><TD>m3wrapfreearg</TD><TD><TT>M3toC.FreeSharedS(str,arg1);</TT></TD><TD>
31662  Free resources that were temporarily used in the wrapper. Since this
31663  step should never be skipped, SWIG will put it in the <TT>FINALLY</TT>
31664  branch of a <TT>TRY .. FINALLY</TT> structure.</TD></TR>
31665 </TABLE>
31666 <H3><A name="ordinals"></A>24.4.2 Subranges, Enumerations, Sets</H3>
31667 <P> Subranges, enumerations, and sets are machine oriented types that
31668  make Modula very strong and expressive compared with the type systems
31669  of many other languages.</P>
31670 <UL>
31671 <LI> Subranges are used for statically restricted choices of integers.</LI>
31672 <LI> Enumerations are used for named choices.</LI>
31673 <LI> Sets are commonly used for flag (option) sets.</LI>
31674 </UL>
31675 <P> Using them extensively makes Modula code very safe and readable.</P>
31676 <P> C supports enumerations, too, but they are not as safe as the ones
31677  of Modula. Thus they are abused for many things: For named choices, for
31678  integer constant definitions, for sets. To make it complete every way
31679  of defining a value in C (<TT>#define</TT>, <TT>const int</TT>, <TT>
31680 enum</TT>) is somewhere used for defining something that must be handled
31681  completely different in Modula-3 (<TT>INTEGER</TT>, enumeration, <TT>
31682 SET</TT>).</P>
31683 <P> I played around with several <TT>%feature</TT>s and <TT>%pragma</TT>
31684 s that split the task up into converting the C bit patterns (integer or
31685  bit set) into Modula-3 bit patterns (integer or bit set) and change the
31686  type as requested. See the corresponding example in the
31687  Examples/modula3/enum/example.i file. This is quite messy and not
31688  satisfying. So the best what you can currently do is to rewrite
31689  constant definitions manually. Though this is a tedious work that I'd
31690  like to automate.</P>
31691 <H3><A name="class"></A>24.4.3 Objects</H3>
31692 <P> Declarations of C++ classes are mapped to <TT>OBJECT</TT> types
31693  while it is tried to retain the access hierarchy &quot;public - protected -
31694  private&quot; using partial revelation. Though the example in
31695  Examples/modula3/class/example.i is not really useful, yet.</P>
31696 <H3><A name="imports"></A>24.4.4 Imports</H3>
31697 <P> Pieces of Modula-3 code provided by typemaps may contain identifiers
31698  from foreign modules. If the typemap <TT>m3wrapinconv</TT> for <TT>blah
31699  *</TT> contains code using the function <TT>M3toC.SharedTtoS</TT> you
31700  may declare <TT>%typemap(&quot;m3wrapinconv:import&quot;) blah * %{M3toC%}</TT>.
31701  Then the module <TT>M3toC</TT> is imported if the <TT>m3wrapinconv</TT>
31702  typemap for <TT>blah *</TT> is used at least once. Use <TT>
31703 %typemap(&quot;m3wrapinconv:import&quot;) blah * %{MyConversions AS M3toC%}</TT>
31704  if you need module renaming. Unqualified import is not supported.</P>
31705 <P> It is cumbersome to add this typemap to each piece of Modula-3 code.
31706  It is especially useful when writing general typemaps for the typemap
31707  library <A href="../../Lib/modula3/modula3.swg"><TT>modula3.swg</TT></A>
31708  . For a monolithic module you might be better off if you add the
31709  imports directly:</P>
31710 <DIV class="code">
31711 <PRE>
31712 %insert(m3rawintf) %{
31713 IMPORT M3toC;
31714 %}
31715 </PRE>
31716 </DIV>
31717 <H3><A name="exceptions"></A>24.4.5 Exceptions</H3>
31718 <P> Modula-3 provides another possibility of an output of a function:
31719  exceptions.</P>
31720 <P> Any piece of Modula-3 code that SWIG inserts due to a typemap can
31721  raise an exception. This way you can also convert an error code from a
31722  C function into a Modula-3 exception.</P>
31723 <P> The <TT>RAISES</TT> clause is controlled by typemaps with the <TT>
31724 throws</TT> extension. If the typemap <TT>m3wrapinconv</TT> for <TT>blah
31725  *</TT> contains code that may raise the exceptions <TT>OSError.E</TT>
31726  you should declare <TT>%typemap(&quot;m3wrapinconv:throws&quot;) blah *
31727  %{OSError.E%}</TT>.</P>
31728 <H3><A name="typemap_example"></A>24.4.6 Example</H3>
31729 <P> The generation of wrappers in Modula-3 needs very fine control to
31730  take advantage of the language features. Here is an example of a
31731  generated wrapper where almost everything is generated by a typemap:</P>
31732 <DIV class="code">
31733 <PRE>
31734 <I>         (* %relabel  m3wrapinmode m3wrapinname m3wrapintype  m3wrapindefault *)</I>
31735   PROCEDURE Name     (READONLY       str       :    TEXT    :=      &quot;&quot;       )
31736 <I>              (* m3wrapoutcheck:throws *)</I>
31737      : NameResult RAISES {E} =
31738     CONST
31739       arg1name = &quot;str&quot;;                  <I>(* m3wrapargconst *)</I>
31740     VAR
31741       arg0   : C.char_star;              <I>(* m3wrapretvar *)</I>
31742       arg1   : C.char_star;              <I>(* m3wrapargvar *)</I>
31743       arg2   : C.int;
31744       result : RECORD
31745 <I>           (*m3wrapretname  m3wraprettype*)</I>
31746                  unixPath : TEXT;
31747 <I>           (*m3wrapoutname  m3wrapouttype*)</I>
31748                  checksum : CARDINAL;
31749                END;
31750     BEGIN
31751       TRY
31752         arg1 := M3toC.SharedTtoS(str);   <I>(* m3wrapinconv *)</I>
31753         IF Text.Length(arg1) &gt; 10 THEN   <I>(* m3wrapincheck *)</I>
31754           RAISE E(&quot;str too long&quot;);
31755         END;
31756 <I> (* m3wrapretraw           m3wrapargraw *)</I>
31757         arg0 := MessyToUnix  (arg1,   arg2);
31758         result.unixPath := M3toC.CopyStoT(arg0);  <I>(* m3wrapretconv *)</I>
31759         result.checksum := arg2;         <I>(* m3wrapoutconv *)</I>
31760         IF result.checksum = 0 THEN      <I>(* m3wrapoutcheck *)</I>
31761           RAISE E(&quot;invalid checksum&quot;);
31762         END;
31763       FINALLY
31764         M3toC.FreeSharedS(str,arg1);     <I>(* m3wrapfreearg *)</I>
31765       END;
31766     END Name;
31767 </PRE>
31768 </DIV>
31769 <H2><A name="hints"></A>24.5 More hints to the generator</H2>
31770 <H3><A name="features"></A>24.5.1 Features</H3>
31771 <TABLE border summary="Modula-3 features">
31772 <TR><TH>Feature</TH><TH>Example</TH><TH>Description</TH></TR>
31773 <TR><TD>multiretval</TD><TD><TT>%m3multiretval get_box;</TT> or <TT>
31774 %feature(&quot;modula3:multiretval&quot;) get_box;</TT></TD><TD>Let the denoted
31775  function return a <TT>RECORD</TT> rather than a plain value. This <TT>
31776 RECORD</TT> contains all arguments with &quot;out&quot; direction including the
31777  return value of the C function (if there is one). If more than one
31778  argument is &quot;out&quot; then the function<B> must</B> have the <TT>
31779 multiretval</TT> feature activated, but it is explicitly requested from
31780  the user to prevent mistakes.</TD></TR>
31781 <TR><TD>constnumeric</TD><TD><TT>%constnumeric(12) twelve;</TT> or <TT>
31782 %feature(&quot;constnumeric&quot;,&quot;12&quot;) twelve;</TT></TD><TD>This feature can be
31783  used to tell Modula-3's back-end of SWIG the value of an identifier.
31784  This is necessary in the cases where it was defined by a non-trivial C
31785  expression. This feature is used by the <TT>-generateconst</TT> <A href="#options">
31786 option</A>. In future it may be generalized to other kind of values such
31787  as strings.</TD></TR>
31788 </TABLE>
31789 <H3><A name="pragmas"></A>24.5.2 Pragmas</H3>
31790 <TABLE border summary="Modula-3 pragmas">
31791 <TR><TH>Pragma</TH><TH>Example</TH><TH>Description</TH></TR>
31792 <TR><TD>unsafe</TD><TD><TT>%pragma(modula3) unsafe=&quot;true&quot;;</TT></TD><TD>
31793 Mark the raw interface modules as <TT>UNSAFE</TT>. This will be
31794  necessary in many cases.</TD></TR>
31795 <TR><TD>library</TD><TD><TT>%pragma(modula3) library=&quot;m3fftw&quot;;</TT></TD><TD>
31796 Specifies the library name for the wrapper library to be created. It
31797  should be distinct from the name of the library to be wrapped.</TD></TR>
31798 </TABLE>
31799 <H2><A name="remarks"></A>24.6 Remarks</H2>
31800 <UL>
31801 <LI> The Modula-3 part of SWIG doesn't try to generate nicely formatted
31802  code. Use <TT>m3pp</TT> to postprocess the Modula files, it does a very
31803  good job here.</LI>
31804 </UL>
31805 <HR NOSHADE>
31806
31807 <!-- Hand-written HTML -->
31808 <H1><A name="MzScheme"></A>25 SWIG and MzScheme</H1>
31809
31810 <!-- INDEX -->
31811 <DIV class="sectiontoc">
31812 <UL>
31813 <LI><A href="#MzScheme_nn2">Creating native MzScheme structures</A></LI>
31814 </UL>
31815 </DIV>
31816 <!-- INDEX -->
31817 <P> This section contains information on SWIG's support of MzScheme.</P>
31818 <H2><A name="MzScheme_nn2"></A>25.1 Creating native MzScheme structures</H2>
31819 <P> Example interface file:</P>
31820 <DIV class="code">
31821 <PRE>
31822 /* define a macro for the struct creation */
31823 %define handle_ptr(TYPE,NAME)
31824 %typemap(argout) TYPE *NAME{
31825     Scheme_Object *o = SWIG_NewStructFromPtr($1, $*1_mangle);
31826     SWIG_APPEND_VALUE(o);
31827 }
31828
31829 %typemap(in,numinputs=0) TYPE *NAME (TYPE temp) {
31830     $1 = &amp;temp;
31831 }
31832 %enddef
31833
31834 /* setup the typemaps for the pointer to an output parameter cntrs */
31835 handle_ptr(struct diag_cntrs, cntrs);
31836 </PRE>
31837 </DIV>
31838 <P> Then in scheme, you can use regular struct access procedures like</P>
31839 <DIV class="code">
31840 <PRE>
31841         ; suppose a function created a struct foo as 
31842         ; (define foo (make-diag-cntrs (#x1 #x2 #x3) (make-inspector))
31843         ; Then you can do
31844         (format &quot;0x~x&quot; (diag-cntrs-field1 foo))
31845         (format &quot;0x~x&quot; (diag-cntrs-field2 foo))
31846         ;etc...
31847 </PRE>
31848 </DIV>
31849 <P> That's pretty much it. It works with nested structs as well.</P>
31850 <HR NOSHADE>
31851  <A name="n1"></A>
31852 <H1><A name="Ocaml"></A>26 SWIG and Ocaml</H1>
31853
31854 <!-- INDEX -->
31855 <DIV class="sectiontoc">
31856 <UL>
31857 <LI><A href="#Ocaml_nn2">Preliminaries</A>
31858 <UL>
31859 <LI><A href="#Ocaml_nn3">Running SWIG</A></LI>
31860 <LI><A href="#Ocaml_nn4">Compiling the code</A></LI>
31861 <LI><A href="#Ocaml_nn5">The camlp4 module</A></LI>
31862 <LI><A href="#Ocaml_nn6">Using your module</A></LI>
31863 <LI><A href="#Ocaml_nn7">Compilation problems and compiling with C++</A></LI>
31864 </UL>
31865 </LI>
31866 <LI><A href="#Ocaml_nn8">The low-level Ocaml/C interface</A>
31867 <UL>
31868 <LI><A href="#Ocaml_nn9">The generated module</A></LI>
31869 <LI><A href="#Ocaml_nn10">Enums</A>
31870 <UL>
31871 <LI><A href="#Ocaml_nn11">Enum typing in Ocaml</A></LI>
31872 </UL>
31873 </LI>
31874 <LI><A href="#Ocaml_nn12">Arrays</A>
31875 <UL>
31876 <LI><A href="#Ocaml_nn13">Simple types of bounded arrays</A></LI>
31877 <LI><A href="#Ocaml_nn14">Complex and unbounded arrays</A></LI>
31878 <LI><A href="#Ocaml_nn15">Using an object</A></LI>
31879 <LI><A href="#Ocaml_nn16">Example typemap for a function taking float *
31880  and int</A></LI>
31881 </UL>
31882 </LI>
31883 <LI><A href="#Ocaml_nn17">C++ Classes</A>
31884 <UL>
31885 <LI><A href="#Ocaml_nn18">STL vector and string Example</A></LI>
31886 <LI><A href="#Ocaml_nn19">C++ Class Example</A></LI>
31887 <LI><A href="#Ocaml_nn20">Compiling the example</A></LI>
31888 <LI><A href="#Ocaml_nn21">Sample Session</A></LI>
31889 </UL>
31890 </LI>
31891 <LI><A href="#Ocaml_nn22">Director Classes</A>
31892 <UL>
31893 <LI><A href="#Ocaml_nn23">Director Introduction</A></LI>
31894 <LI><A href="#Ocaml_nn24">Overriding Methods in Ocaml</A></LI>
31895 <LI><A href="#Ocaml_nn25">Director Usage Example</A></LI>
31896 <LI><A href="#Ocaml_nn26">Creating director objects</A></LI>
31897 <LI><A href="#Ocaml_nn27">Typemaps for directors, <TT>directorin,
31898  directorout, directorargout</TT></A></LI>
31899 <LI><A href="#Ocaml_nn28"><TT>directorin</TT> typemap</A></LI>
31900 <LI><A href="#Ocaml_nn29"><TT>directorout</TT> typemap</A></LI>
31901 <LI><A href="#Ocaml_nn30"><TT>directorargout</TT> typemap</A></LI>
31902 </UL>
31903 </LI>
31904 <LI><A href="#Ocaml_nn31">Exceptions</A></LI>
31905 </UL>
31906 </LI>
31907 </UL>
31908 </DIV>
31909 <!-- INDEX -->
31910 <P> This chapter describes SWIG's support of Ocaml. Ocaml is a
31911  relatively recent addition to the ML family, and is a recent addition
31912  to SWIG. It's the second compiled, typed language to be added. Ocaml
31913  has widely acknowledged benefits for engineers, mostly derived from a
31914  sophisticated type system, compile-time checking which eliminates
31915  several classes of common programming errors, and good native
31916  performance. While all of this is wonderful, there are well-written C
31917  and C++ libraries that Ocaml users will want to take advantage of as
31918  part of their arsenal (such as SSL and gdbm), as well as their own
31919  mature C and C++ code. SWIG allows this code to be used in a natural,
31920  type-safe way with Ocaml, by providing the necessary, but repetitive
31921  glue code which creates and uses Ocaml values to communicate with C and
31922  C++ code. In addition, SWIG also produces the needed Ocaml source that
31923  binds variants, functions, classes, etc.</P>
31924 <P> If you're not familiar with the Objective Caml language, you can
31925  visit <A href="http://www.ocaml.org/">The Ocaml Website</A>.</P>
31926 <H2><A name="Ocaml_nn2"></A>26.1 Preliminaries</H2>
31927 <P> SWIG 1.3 works with Ocaml 3.04 and above. Given the choice, you
31928  should use the latest stable release. The SWIG Ocaml module has been
31929  tested on Linux (x86,PPC,Sparc) and Cygwin on Windows. The best way to
31930  determine whether your system will work is to compile the examples and
31931  test-suite which come with SWIG. You can do this by running <TT>make
31932  check</TT> from the SWIG root directory after installing SWIG. The
31933  Ocaml module has been tested using the system's dynamic linking (the
31934  usual -lxxx against libxxx.so, as well as with Gerd Stolpmann's <A href="http://www.ocaml-programming.de/packages/documentation/dl/">
31935 Dl package</A> . The ocaml_dynamic and ocaml_dynamic_cpp targets in the
31936  file Examples/Makefile illustrate how to compile and link SWIG modules
31937  that will be loaded dynamically. This has only been tested on Linux so
31938  far.</P>
31939 <H3><A name="Ocaml_nn3"></A>26.1.1 Running SWIG</H3>
31940 <P> The basics of getting a SWIG Ocaml module up and running can be seen
31941  from one of SWIG's example Makefiles, but is also described here. To
31942  build an Ocaml module, run SWIG using the <TT>-ocaml</TT> option.</P>
31943 <DIV class="code">
31944 <PRE>
31945 %swig -ocaml example.i
31946   </PRE>
31947 </DIV>
31948 <P> This will produce 3 files. The file <TT>example_wrap.c</TT> contains
31949  all of the C code needed to build an Ocaml module. To build the module,
31950  you will compile the file <TT>example_wrap.c</TT> with <TT>ocamlc</TT>
31951  or <TT>ocamlopt</TT> to create the needed .o file. You will need to
31952  compile the resulting .ml and .mli files as well, and do the final link
31953  with -custom (not needed for native link).</P>
31954 <H3><A name="Ocaml_nn4"></A>26.1.2 Compiling the code</H3>
31955 <P> The O'Caml SWIG module now requires you to compile a module (<TT>
31956 Swig</TT>) separately. In addition to aggregating common SWIG
31957  functionality, the Swig module contains the data structure that
31958  represents C/C++ values. This allows easier data sharing between
31959  modules if two or more are combined, because the type of each SWIG'ed
31960  module's c_obj is derived from Swig.c_obj_t. This also allows SWIG to
31961  acquire new conversions painlessly, as well as giving the user more
31962  freedom with respect to custom typing. Use <TT>ocamlc</TT> or <TT>
31963 ocamlopt</TT> to compile your SWIG interface like:</P>
31964 <DIV class="code">
31965 <PRE>
31966 % swig -ocaml -co swig.mli ; swig -ocaml co swig.ml
31967 % ocamlc -c swig.mli ; ocamlc -c swig.ml
31968 % ocamlc -c -ccopt &quot;-I/usr/include/foo&quot; example_wrap.c
31969 % ocamlc -c example.mli
31970 % ocamlc -c example.ml
31971   </PRE>
31972 </DIV>
31973 <P> <TT>ocamlc</TT> is aware of .c files and knows how to handle them.
31974  Unfortunately, it does not know about .cxx, .cc, or .cpp files, so when
31975  SWIG is invoked in C++ mode, you must:</P>
31976 <DIV class="code">
31977 <PRE>
31978 % cp example_wrap.cxx example_wrap.cxx.c
31979 <BR>% ocamlc -c ... -ccopt -xc++ example_wrap.cxx.c
31980 <BR>% ...
31981 <BR>
31982   </PRE>
31983 </DIV>
31984 <H3><A name="Ocaml_nn5"></A>26.1.3 The camlp4 module</H3>
31985 <P> The camlp4 module (swigp4.ml -&gt; swigp4.cmo) contains a simple
31986  rewriter which makes C++ code blend more seamlessly with objective caml
31987  code. It's use is optional, but encouraged. The source file is included
31988  in the Lib/ocaml directory of the SWIG source distribution. You can
31989  checkout this file with <TT>&quot;swig -ocaml -co swigp4.ml&quot;</TT>. You
31990  should compile the file with <TT>&quot;ocamlc -I `camlp4 -where` -pp
31991  'camlp4o pa_extend.cmo q_MLast.cmo' -c swigp4.ml&quot;</TT></P>
31992 <P> The basic principle of the module is to recognize certain non-caml
31993  expressions and convert them for use with C++ code as interfaced by
31994  SWIG. The camlp4 module is written to work with generated SWIG
31995  interfaces, and probably isn't great to use with anything else.</P>
31996 <P> Here are the main rewriting rules:</P>
31997 <TABLE border="1" summary="Rewriting rules">
31998 <TR><TH>Input</TH><TH>Rewritten to</TH></TR>
31999 <TR><TD>f'( ... ) as in
32000 <BR> atoi'(&quot;0&quot;) or
32001 <BR> _exit'(0)</TD><TD>f(C_list [ ... ]) as in
32002 <BR> atoi (C_list [ C_string &quot;0&quot; ]) or
32003 <BR> _exit (C_list [ C_int 0 ])</TD></TR>
32004 <TR><TD>object -&gt; method ( ... )</TD><TD>(invoke object) &quot;method&quot;
32005  (C_list [ ... ])</TD></TR>
32006 <TR><TD> object<I> 'binop</I> argument as in
32007 <BR> a '+= b</TD><TD> (invoke object) &quot;+=&quot; argument as in
32008 <BR> (invoke a) &quot;+=&quot; b</TD><TD></TD></TR>
32009 <TR><TH colspan="2">Note that because camlp4 always recognizes &lt;&lt; and
32010  &gt;&gt;, they are replaced by lsl and lsr in operator names.</TH></TR>
32011 <TR><TD><I> 'unop</I> object as in
32012 <BR> '! a</TD><TD> (invoke a) &quot;!&quot; C_void</TD></TR>
32013 <TR><TD><B> Smart pointer access like this</B>
32014 <BR> object '-&gt; method ( args )
32015 <BR></TD><TD> (invoke (invoke object &quot;-&gt;&quot; C_void))</TD></TR>
32016 <TR><TD><B> Invoke syntax</B>
32017 <BR> object . '( ... )</TD><TD> (invoke object) &quot;()&quot; (C_list [ ... ])</TD>
32018 </TR>
32019 <TR><TD><B> Array syntax</B>
32020 <BR> object '[ 10 ]</TD><TD> (invoke object) &quot;[]&quot; (C_int 10)</TD></TR>
32021 <TR><TD><B> Assignment syntax</B>
32022 <BR> let a = '10 and b = '&quot;foo&quot; and c = '1.0 and d = 'true</TD><TD> let
32023  a = C_int 10 and b = C_string &quot;foo&quot; and c = C_double 1.0 and d = C_bool
32024  true</TD></TR>
32025 <TR><TD><B> Cast syntax</B>
32026 <BR> let a = _atoi '(&quot;2&quot;) as int
32027 <BR> let b = (getenv &quot;PATH&quot;) to string
32028 <BR> This works for int, string, float, bool</TD><TD> let a = get_int
32029  (_atoi (C_string &quot;2&quot;))
32030 <BR> let b = C_string (getenv &quot;PATH&quot;)</TD></TR>
32031 </TABLE>
32032 <H3><A name="Ocaml_nn6"></A>26.1.4 Using your module</H3>
32033 <P> You can test-drive your module by building a toplevel ocaml
32034  interpreter. Consult the ocaml manual for details.</P>
32035 <P> When linking any ocaml bytecode with your module, use the -custom
32036  option to build your functions into the primitive list. This option is
32037  not needed when you build native code.</P>
32038 <H3><A name="Ocaml_nn7"></A>26.1.5 Compilation problems and compiling
32039  with C++</H3>
32040 <P> As mentioned above, .cxx files need special handling to be compiled
32041  with <TT>ocamlc</TT>. Other than that, C code that uses <TT>class</TT>
32042  as a non-keyword, and C code that is too liberal with pointer types may
32043  not compile under the C++ compiler. Most code meant to be compiled as
32044  C++ will not have problems.</P>
32045 <H2><A name="Ocaml_nn8"></A>26.2 The low-level Ocaml/C interface</H2>
32046 <P> In order to provide access to overloaded functions, and provide
32047  sensible outputs from them, all C entities are represented as members
32048  of the c_obj type:</P>
32049 <P> In the code as seen by the typemap writer, there is a value,
32050  swig_result, that always contains the current return data. It is a
32051  list, and must be appended with the caml_list_append function, or with
32052  functions and macros provided by objective caml.
32053 <BR></P>
32054 <DIV class="code">
32055 <PRE>
32056 type c_obj =
32057     C_void
32058   | C_bool of bool
32059   | C_char of char
32060   | C_uchar of char
32061   | C_short of int
32062   | C_ushort of int
32063   | C_int of int
32064   | C_uint of int32
32065   | C_int32 of int32
32066   | C_int64 of int64
32067   | C_float of float
32068   | C_double of float
32069   | C_ptr of int64 * int64
32070   | C_array of c_obj array
32071   | C_list of c_obj list
32072   | C_obj of (string -&gt; c_obj -&gt; c_obj)
32073   | C_string of string
32074   | C_enum of c_enum_t
32075 </PRE>
32076 </DIV>
32077 <P> A few functions exist which generate and return these:</P>
32078 <UL>
32079 <LI>caml_ptr_val receives a c_obj and returns a void *. &nbsp;This should be
32080  used for all pointer purposes.</LI>
32081 <LI>caml_long_val receives a c_obj and returns a long. &nbsp;This should be
32082  used for most integral purposes.
32083 <BR></LI>
32084 <LI>caml_val_ptr receives a void * and returns a c_obj.</LI>
32085 <LI>caml_val_bool receives a C int and returns a c_obj representing it's
32086  bool value.</LI>
32087 <LI>caml_val_(u)?(char|short|int|long|float|double) receives an
32088  appropriate C value and returns a c_obj representing it.</LI>
32089 <LI>caml_val_string receives a char * and returns a string value.</LI>
32090 <LI>caml_val_string_len receives a char * and a length and returns a
32091  string value.</LI>
32092 <LI>caml_val_obj receives a void * and an object type and returns a
32093  C_obj, which contains a closure giving method access.</LI>
32094 </UL>
32095 <P> Because of this style, a typemap can return any kind of value it
32096  wants from a function. &nbsp;This enables out typemaps and inout typemaps to
32097  work well. &nbsp;The one thing to remember about outputting values is that
32098  you must append them to the return list with swig_result =
32099  caml_list_append(swig_result,v).</P>
32100 <P> &nbsp;This function will return a new list that has your element
32101  appended. Upon return to caml space, the fnhelper function beautifies
32102  the result. A list containing a single item degrades to only that item
32103  (i.e. [ C_int 3 ] -&gt; C_int 3), and a list containing more than one item
32104  is wrapped in C_list (i.e. [ C_char 'a' ; C_char 'b' -&gt; C_list [ C_char
32105  'a' ; C_char b ]). &nbsp;This is in order to make return values easier to
32106  handle when functions have only one return value, such as constructors,
32107  and operators. &nbsp;In addition, string, pointer, and object values are
32108  interchangeable with respect to caml_ptr_val, so you can allocate
32109  memory as caml strings and still use the resulting pointers for C
32110  purposes, even using them to construct simple objects on. Note, though,
32111  that foreign C++ code does not respect the garbage collector, although
32112  the SWIG interface does.</P>
32113 <P> The wild card type that you can use in lots of different ways is
32114  C_obj. It allows you to wrap any type of thing you like as an object
32115  using the same mechanism that the ocaml module does. &nbsp;When evaluated in
32116  caml_ptr_val, the returned value is the result of a call to the
32117  object's &quot;&amp;&quot; operator, taken as a pointer.</P>
32118 <P> You should only construct values using objective caml, or using the
32119  functions caml_val_* functions provided as static functions to a SWIG
32120  ocaml module, as well as the caml_list_* functions. These functions
32121  provide everything a typemap needs to produce values. In addition,
32122  value items pass through directly, but you must make your own type
32123  signature for a function that uses value in this way.</P>
32124 <H3><A name="Ocaml_nn9"></A>26.2.1 The generated module</H3>
32125 <P> The SWIG <TT>%module</TT> directive specifies the name of the Ocaml
32126  module to be generated. If you specified `<TT>%module example</TT>',
32127  then your Ocaml code will be accessible in the module Example. The
32128  module name is always capitalized as is the ocaml convention. Note that
32129  you must not use any Ocaml keyword to name your module. Remember that
32130  the keywords are not the same as the C++ ones.</P>
32131 <P> You can introduce extra code into the output wherever you like with
32132  SWIG. These are the places you can introduce code:</P>
32133 <TABLE border="1" summary="Extra code sections">
32134 <TR><TD>&quot;header&quot;</TD><TD>This code is inserted near the beginning of the
32135  C wrapper file, before any function definitions.</TD></TR>
32136 <TR><TD>&quot;wrapper&quot;</TD><TD>This code is inserted in the function
32137  definition section.</TD></TR>
32138 <TR><TD>&quot;runtime&quot;</TD><TD>This code is inserted near the end of the C
32139  wrapper file.</TD></TR>
32140 <TR><TD>&quot;mli&quot;</TD><TD>This code is inserted into the caml interface
32141  file. Special signatures should be inserted here.</TD></TR>
32142 <TR><TD>&quot;ml&quot;</TD><TD>This code is inserted in the caml code defining the
32143  interface to your C code. Special caml code, as well as any
32144  initialization which should run when the module is loaded may be
32145  inserted here.</TD></TR>
32146 <TR><TD>&quot;classtemplate&quot;</TD><TD>The &quot;classtemplate&quot; place is special
32147  because it describes the output SWIG will generate for class
32148  definitions.</TD></TR>
32149 </TABLE>
32150 <H3><A name="Ocaml_nn10"></A>26.2.2 Enums</H3>
32151 <P> SWIG will wrap enumerations as polymorphic variants in the output
32152  Ocaml code, as above in C_enum.&nbsp; In order to support all C++-style uses
32153  of enums, the function int_to_enum and enum_to_int are provided for
32154  ocaml code to produce and consume these values as integers. &nbsp;Other than
32155  that, correct uses of enums will not have a problem. &nbsp;Since enum labels
32156  may overlap between enums, the enum_to_int and int_to_enum functions
32157  take an enum type label as an argument. Example:</P>
32158 <DIV class="code">
32159 <PRE>
32160 %module enum_test
32161 %{
32162 enum c_enum_type { a = 1, b, c = 4, d = 8 };
32163 %}
32164 enum c_enum_type { a = 1, b, c = 4, d = 8 };
32165 </PRE>
32166 </DIV>
32167 <P> The output mli contains:</P>
32168 <DIV class="code">
32169 <PRE>
32170 type c_enum_type = [
32171   `unknown
32172 | `c_enum_type
32173 ]
32174 type c_enum_tag = [
32175   `int of int
32176 | `a
32177 | `b
32178 | `c
32179 | `d
32180 ]
32181 val int_to_enum c_enum_type -&gt; int -&gt; c_obj
32182 val enum_to_int c_enum_type -&gt; c_obj -&gt; c_obj
32183 </PRE>
32184 </DIV>
32185 <P> So it's possible to do this:</P>
32186 <DIV class="code">
32187 <PRE>
32188 bash-2.05a$ ocamlmktop -custom enum_test_wrap.o enum_test.cmo -o enum_test_top
32189 bash-2.05a$ ./enum_test_top 
32190         Objective Caml version 3.04
32191
32192 # open Enum_test ;;
32193 # let x = C_enum `a ;;
32194 val x : Enum_test.c_obj = C_enum `a
32195 # enum_to_int `c_enum_type x ;;
32196 - : Enum_test.c_obj = C_int 1
32197 # int_to_enum `c_enum_type 4 ;;
32198 - : Enum_test.c_obj = C_enum `c
32199 </PRE>
32200 </DIV>
32201 <H4><A name="Ocaml_nn11"></A>26.2.2.1 Enum typing in Ocaml</H4>
32202 <P> The ocaml SWIG module now has support for loading and using multiple
32203  SWIG modules at the same time. This enhances modularity, but presents
32204  problems when used with a language which assumes that each module's
32205  types are complete at compile time. In order to achieve total soundness
32206  enum types are now isolated per-module. The type issue matters when
32207  values are shared between functions imported from different modules.
32208  You must convert values to master values using the swig_val function
32209  before sharing them with another module.</P>
32210 <H3><A name="Ocaml_nn12"></A>26.2.3 Arrays</H3>
32211 <H4><A name="Ocaml_nn13"></A>26.2.3.1 Simple types of bounded arrays</H4>
32212 <P> SWIG has support for array types, but you generally will need to
32213  provide a typemap to handle them. You can currently roll your own, or
32214  expand some of the macros provided (but not included by default) with
32215  the SWIG distribution.</P>
32216 <P> By including &quot;carray.i&quot;, you will get access to some macros that
32217  help you create typemaps for array types fairly easily.</P>
32218 <P> <TT>%make_simple_array_typemap</TT> is the easiest way to get access
32219  to arrays of simple types with known bounds in your code, but this only
32220  works for arrays whose bounds are completely specified.</P>
32221 <H4><A name="Ocaml_nn14"></A>26.2.3.2 Complex and unbounded arrays</H4>
32222 <P> Unfortunately, unbounded arrays and pointers can't be handled in a
32223  completely general way by SWIG, because the end-condition of such an
32224  array can't be predicted. In some cases, it will be by consent (e.g. an
32225  array of four or more chars), sometimes by explicit length (char
32226  *buffer, int len), and sometimes by sentinel value (0,-1,etc.). SWIG
32227  can't predict which of these methods will be used in the array, so you
32228  have to specify it for yourself in the form of a typemap.</P>
32229 <H4><A name="Ocaml_nn15"></A>26.2.3.3 Using an object</H4>
32230 <P> It's possible to use C++ to your advantage by creating a simple
32231  object that provides access to your array. This may be more desirable
32232  in some cases, since the object can provide bounds checking, etc., that
32233  prevents crashes.</P>
32234 <P> Consider writing an object when the ending condition of your array
32235  is complex, such as using a required sentinel, etc.</P>
32236 <H4><A name="Ocaml_nn16"></A>26.2.3.4 Example typemap for a function
32237  taking float * and int</H4>
32238 <P> This is a simple example <TT>in</TT> typemap for an array of float,
32239  where the length of the array is specified as an extra parameter. Other
32240  such typemaps will work similarly. In the example, the function
32241  printfloats is called with a float array, and specified length. The
32242  actual length reported in the len argument is the length of the array
32243  passed from ocaml, making passing an array into this type of function
32244  convenient.</P>
32245 <TABLE bgcolor="#dddddd" border="1" summary="float * and int typemap example">
32246 <TR><TH>
32247 <CENTER>tarray.i</CENTER>
32248 </TH></TR>
32249 <TR><TD>
32250 <PRE>
32251 %module tarray
32252 %{
32253 #include &lt;stdio.h&gt;
32254
32255 void printfloats( float *tab, int len ) {
32256         int i;
32257
32258         for( i = 0; i &lt; len; i++ ) {
32259                 printf( &quot;%f &quot;, tab[i] );
32260         }
32261
32262         printf( &quot;\n&quot; );  
32263 }
32264 %}
32265
32266 %typemap(in) (float *tab, int len) {
32267     int i;
32268     /* $*1_type */
32269     $2 = caml_array_len($input);
32270     $1 = ($*1_type *)malloc( $2 * sizeof( float ) );
32271     for( i = 0; i &lt; $2; i++ ) {
32272         $1[i] = caml_double_val(caml_array_nth($input,i));
32273     }
32274 }
32275
32276 void printfloats( float *tab, int len );
32277 </PRE>
32278 </TD></TR>
32279 <TR><TH>Sample Run</TH></TR>
32280 <TR><TD>
32281 <PRE>
32282 # open Tarray ;;
32283 # _printfloats (C_array [| C_double 1.0 ; C_double 3.0 ; C_double 5.6666 |]) ;;
32284 1.000000 3.000000 5.666600
32285 - : Tarray.c_obj = C_void
32286 </PRE>
32287 </TD></TR>
32288 </TABLE>
32289 <H3><A name="Ocaml_nn17"></A>26.2.4 C++ Classes</H3>
32290 <P> C++ classes, along with structs and unions are represented by C_obj
32291  (string -&gt; c_obj -&gt; c_obj) wrapped closures. &nbsp;These objects contain a
32292  method list, and a type, which allow them to be used like C++ objects.
32293  When passed into typemaps that use pointers, they degrade to pointers
32294  through their &quot;&amp;&quot; method. &nbsp;Every method an object has is represented as
32295  a string in the object's method table, and each method table exists in
32296  memory only once. &nbsp;In addition to any other operators an object might
32297  have, certain builtin ones are provided by SWIG: (all of these take no
32298  arguments (C_void))</P>
32299 <TABLE summary="SWIG provided operators">
32300 <TR><TD>&quot;~&quot;</TD><TD>Delete this object</TD></TR>
32301 <TR><TD>&quot;&amp;&quot;</TD><TD>Return an ordinary C_ptr value representing this
32302  object's address</TD></TR>
32303 <TR><TD>&quot;sizeof&quot;</TD><TD>If enabled with (&quot;sizeof&quot;=&quot;1&quot;) on the module
32304  node, return the object's size in char.</TD></TR>
32305 <TR><TD>&quot;:methods&quot;</TD><TD>Returns a list of strings containing the
32306  names of the methods this object contains</TD></TR>
32307 <TR><TD>&quot;:classof&quot;</TD><TD>Returns the name of the class this object
32308  belongs to.</TD></TR>
32309 <TR><TD>&quot;:parents&quot;</TD><TD>Returns a list of all direct parent classes
32310  which have been wrapped by SWIG.</TD></TR>
32311 <TR><TD>&quot;::[parent-class]&quot;</TD><TD>Returns a view of the object as the
32312  indicated parent class. This is mainly used internally by the SWIG
32313  module, but may be useful to client programs.</TD></TR>
32314 <TR><TD>&quot;[member-variable]&quot;</TD><TD>Each member variable is wrapped as a
32315  method with an optional parameter. Called with one argument, the member
32316  variable is set to the value of the argument. With zero arguments, the
32317  value is returned.</TD></TR>
32318 </TABLE>
32319 <P> Note that this string belongs to the wrapper object, and not the
32320  underlying pointer, so using create_[x]_from_ptr alters the returned
32321  value for the same object.</P>
32322 <H4><A name="Ocaml_nn18"></A>26.2.4.1 STL vector and string Example</H4>
32323 <P> Standard typemaps are now provided for STL vector and string. More
32324  are in the works. STL strings are passed just like normal strings, and
32325  returned as strings. STL string references don't mutate the original
32326  string, (which might be surprising), because Ocaml strings are mutable
32327  but have fixed length. Instead, use multiple returns, as in the
32328  argout_ref example.</P>
32329 <TABLE bgcolor="#dddddd" border="1" summary="STL vector and string example">
32330 <TR><TH>
32331 <CENTER>example.i</CENTER>
32332 </TH></TR>
32333 <TR><TD>
32334 <PRE>
32335 %module example
32336 %{
32337 #include &quot;example.h&quot;
32338 %}
32339
32340 %include &lt;stl.i&gt;
32341
32342 namespace std {
32343         %template(StringVector) std::vector &lt; string &gt;;
32344 };
32345
32346 %include &quot;example.h&quot;
32347 </PRE>
32348 </TD></TR>
32349 <TR><TD><FONT size="-1"><I>This example is in Examples/ocaml/stl</I></FONT>
32350 </TD></TR>
32351 </TABLE>
32352 <P> Since there's a makefile in that directory, the example is easy to
32353  build.</P>
32354 <P> Here's a sample transcript of an interactive session using a string
32355  vector after making a toplevel (make toplevel). This example uses the
32356  camlp4 module.</P>
32357 <DIV class="code">
32358 <PRE>
32359 bash-2.05a$ ./example_top 
32360         Objective Caml version 3.06
32361
32362         Camlp4 Parsing version 3.06
32363
32364 # open Swig ;;
32365 # open Example ;;
32366 # let x = new_StringVector '() ;;
32367 val x : Example.c_obj = C_obj &lt;fun&gt;
32368 # x -&gt; &quot;:methods&quot; () ;;
32369 - : Example.c_obj =
32370 C_list
32371  [C_string &quot;nop&quot;; C_string &quot;size&quot;; C_string &quot;empty&quot;; C_string &quot;clear&quot;;
32372   C_string &quot;push_back&quot;; C_string &quot;[]&quot;; C_string &quot;=&quot;; C_string &quot;set&quot;;
32373   C_string &quot;~&quot;; C_string &quot;&amp;&quot;; C_string &quot;:parents&quot;; C_string &quot;:classof&quot;;
32374   C_string &quot;:methods&quot;]
32375 # x -&gt; push_back (&quot;foo&quot;) ;;
32376 - : Example.c_obj = C_void
32377 # x -&gt; push_back (&quot;bar&quot;) ;;
32378 - : Example.c_obj = C_void
32379 # x -&gt; push_back (&quot;baz&quot;) ;;
32380 - : Example.c_obj = C_void
32381 # x '[1] ;;
32382 - : Example.c_obj = C_string &quot;bar&quot;
32383 # x -&gt; set (1,&quot;spam&quot;) ;;
32384 - : Example.c_obj = C_void
32385 # x '[1] ;;
32386 - : Example.c_obj = C_string &quot;spam&quot;
32387 # for i = 0 to (x -&gt; size() as int) - 1 do 
32388     print_endline ((x '[i to int]) as string) 
32389   done ;;
32390 foo
32391 bar
32392 baz
32393 - : unit = ()
32394
32395 </PRE>
32396 </DIV>
32397 <H4><A name="Ocaml_nn19"></A>26.2.4.2 C++ Class Example</H4>
32398 <P> Here's a simple example using Trolltech's Qt Library:</P>
32399 <TABLE bgcolor="#dddddd" border="1" summary="Qt Library example">
32400 <TR><TH>
32401 <CENTER>qt.i</CENTER>
32402 </TH></TR>
32403 <TR><TD>
32404 <PRE>
32405 %module qt
32406 %{
32407 #include &lt;qapplication.h&gt;
32408 #include &lt;qpushbutton.h&gt;
32409 %}
32410 class QApplication {
32411 public:
32412         QApplication( int argc, char **argv );
32413         void setMainWidget( QWidget *widget );
32414         void exec();
32415 };
32416
32417 class QPushButton {
32418 public:
32419         QPushButton( char *str, QWidget *w );
32420         void resize( int x, int y );
32421         void show();
32422 };
32423 </PRE>
32424 </TD></TR>
32425 </TABLE>
32426 <H4><A name="Ocaml_nn20"></A>26.2.4.3 Compiling the example</H4>
32427 <DIV class="code">
32428 <PRE>
32429 bash-2.05a$ QTPATH=/your/qt/path
32430 bash-2.05a$ for file in swig.mli swig.ml swigp4.ml ; do swig -ocaml -co $file ; done
32431 bash-2.05a$ ocamlc -c swig.mli ; ocamlc -c swig.ml
32432 bash-2.05a$ ocamlc -I `camlp4 -where` -pp &quot;camlp4o pa_extend.cmo q_MLast.cmo&quot; -c swigp4.ml
32433 bash-2.05a$ swig -ocaml -c++ -I$QTPATH/include  qt.i
32434 bash-2.05a$ mv qt_wrap.cxx qt_wrap.c
32435 bash-2.05a$ ocamlc -c -ccopt -xc++ -ccopt -g -g -ccopt -I$QTPATH/include qt_wrap.c 
32436 bash-2.05a$ ocamlc -c qt.mli
32437 bash-2.05a$ ocamlc -c qt.ml
32438 bash-2.05a$ ocamlmktop -custom swig.cmo -I `camlp4 -where` \
32439   camlp4o.cma swigp4.cmo qt_wrap.o qt.cmo -o qt_top -cclib \
32440   -L$QTPATH/lib -cclib -lqt
32441 </PRE>
32442 </DIV>
32443 <H4><A name="Ocaml_nn21"></A>26.2.4.4 Sample Session</H4>
32444 <DIV class="code">
32445 <PRE>
32446 bash-2.05a$ ./qt_top 
32447         Objective Caml version 3.06
32448
32449         Camlp4 Parsing version 3.06
32450
32451 # open Swig ;;
32452 # open Qt ;;
32453 # let a = new_QApplication '(0,0) ;;
32454 val a : Qt.c_obj = C_obj &lt;fun&gt;
32455 # let hello = new_QPushButton '(&quot;hi&quot;,0) ;;
32456 val hello : Qt.c_obj = C_obj &lt;fun&gt;
32457 # hello -&gt; resize (100,30) ;;
32458 - : Qt.c_obj = C_void
32459 # hello -&gt; show () ;;
32460 - : Qt.c_obj = C_void
32461 # a -&gt; exec () ;;
32462 </PRE>
32463 </DIV>
32464 <P> Assuming you have a working installation of QT, you will see a
32465  window containing the string &quot;hi&quot; in a button.</P>
32466 <H3><A name="Ocaml_nn22"></A>26.2.5 Director Classes</H3>
32467 <H4><A name="Ocaml_nn23"></A>26.2.5.1 Director Introduction</H4>
32468 <P> Director classes are classes which allow Ocaml code to override the
32469  public methods of a C++ object. This facility allows the user to use
32470  C++ libraries that require a derived class to provide application
32471  specific functionality in the context of an application or utility
32472  framework.</P>
32473 <P> You can turn on director classes by using an optional module
32474  argument like this:</P>
32475 <DIV class="code">
32476 <PRE>
32477 %module(directors=&quot;1&quot;)
32478
32479 ...
32480
32481 // Turn on the director class for a specific class like this:
32482 %feature(&quot;director&quot;)
32483 class foo {
32484   ...
32485 };
32486 </PRE>
32487 </DIV>
32488 <H4><A name="Ocaml_nn24"></A>26.2.5.2 Overriding Methods in Ocaml</H4>
32489 <P> Because the Ocaml language module treats C++ method calls as calls
32490  to a certain function, all you need to do is to define the function
32491  that will handle the method calls in terms of the public methods of the
32492  object, and any other relevant information. The function <TT>
32493 new_derived_object</TT> uses a stub class to call your methods in place
32494  of the ones provided by the underlying implementation. The object you
32495  receive is the underlying object, so you are free to call any methods
32496  you want from within your derived method. Note that calls to the
32497  underlying object do not invoke Ocaml code. You need to handle that
32498  yourself.</P>
32499 <P> <TT>new_derived_object</TT> receives your function, the function
32500  that creates the underlying object, and any constructor arguments, and
32501  provides an object that you can use in any usual way. When C++ code
32502  calls one of the object's methods, the object invokes the Ocaml
32503  function as if it had been invoked from Ocaml, allowing any method
32504  definitions to override the C++ ones.</P>
32505 <P> In this example, I'll examine the objective caml code involved in
32506  providing an overloaded class. This example is contained in
32507  Examples/ocaml/shapes.</P>
32508 <H4><A name="Ocaml_nn25"></A>26.2.5.3 Director Usage Example</H4>
32509 <TABLE bgcolor="#dddddd" border="1" summary="Director usage example">
32510 <TR><TH>
32511 <CENTER>example_prog.ml</CENTER>
32512 </TH></TR>
32513 <TR><TD>
32514 <PRE>
32515 open Swig
32516 open Example
32517
32518 ...
32519
32520 let triangle_class pts ob meth args =
32521   match meth with
32522       &quot;cover&quot; -&gt;
32523         (match args with
32524              C_list [ x_arg ; y_arg ] -&gt;
32525              let xa = x_arg as float
32526              and ya = y_arg as float in
32527                (point_in_triangle pts xa ya) to bool
32528            | _ -&gt; raise (Failure &quot;cover needs two double arguments.&quot;))
32529     | _ -&gt; (invoke ob) meth args ;;
32530
32531 let triangle =
32532   new_derived_object 
32533     new_shape
32534     (triangle_class ((0.0,0.0),(0.5,1.0),(1.0,0.0)))
32535     '() ;;
32536
32537 let _ = _draw_shape_coverage '(triangle, C_int 60, C_int 20) ;;
32538 </PRE>
32539 </TD></TR>
32540 </TABLE>
32541 <P> This is the meat of what you need to do. The actual &quot;class&quot;
32542  definition containing the overloaded method is defined in the function
32543  triangle_class. This is a lot like the class definitions emitted by
32544  SWIG, if you look at example.ml, which is generated when SWIG consumes
32545  example.i. Basically, you are given the arguments as a c_obj and the
32546  method name as a string, and you must intercept the method you are
32547  interested in and provide whatever return value you need. Bear in mind
32548  that the underlying C++ code needs the right return type, or an
32549  exception will be thrown. This exception will generally be Failure, or
32550  NotObject. You must call other ocaml methods that you rely on yourself.
32551  Due to the way directors are implemented, method calls on your object
32552  from with ocaml code will always invoke C++ methods even if they are
32553  overridden in ocaml.</P>
32554 <P> In the example, the draw_shape_coverage function plots the indicated
32555  number of points as either covered (<TT>x</TT>) or uncovered ( )
32556  between 0 and 1 on the X and Y axes. Your shape implementation can
32557  provide any coverage map it likes, as long as it responds to the
32558  &quot;cover&quot; method call with a boolean return (the underlying method
32559  returns bool). This might allow a tricky shape implementation, such as
32560  a boolean combination, to be expressed in a more effortless style in
32561  ocaml, while leaving the &quot;engine&quot; part of the program in C++.</P>
32562 <H4><A name="Ocaml_nn26"></A>26.2.5.4 Creating director objects</H4>
32563 <P> The definition of the actual object triangle can be described this
32564  way:</P>
32565 <DIV class="code">
32566 <PRE>
32567 let triangle =
32568   new_derived_object 
32569     new_shape
32570     (triangle_class ((0.0,0.0),(0.5,1.0),(1.0,0.0)))
32571     '()
32572 </PRE>
32573 </DIV>
32574 <P> The first argument to <TT>new_derived_object</TT>, new_shape is the
32575  method which returns a shape instance. This function will be invoked
32576  with the third argument will be appended to the argument list [ C_void
32577  ]. In the example, the actual argument list is sent as (C_list [ C_void
32578  ; C_void ]). The augmented constructor for a director class needs the
32579  first argument to determine whether it is being constructed as a
32580  derived object, or as an object of the indicated type only (in this
32581  case <TT>shape</TT>). The Second argument is a closure that will be
32582  added to the final C_obj.</P>
32583 <P> The actual object passed to the self parameter of the director
32584  object will be a C_director_core, containing a c_obj option ref and a
32585  c_obj. The c_obj provided is the same object that will be returned from
32586  new_derived object, that is, the object exposing the overridden
32587  methods. The other part is an option ref that will have its value
32588  extracted before becoming the <TT>ob</TT> parameter of your class
32589  closure. This ref will contain <TT>None</TT> if the C++ object
32590  underlying is ever destroyed, and will consequently trigger an
32591  exception when any method is called on the object after that point (the
32592  actual raise is from an inner function used by new_derived_object, and
32593  throws NotObject). This prevents a deleted C++ object from causing a
32594  core dump, as long as the object is destroyed properly.</P>
32595 <H4><A name="Ocaml_nn27"></A>26.2.5.5 Typemaps for directors, <TT>
32596 directorin, directorout, directorargout</TT></H4>
32597 <P> Special typemaps exist for use with directors, the <TT>directorin,
32598  directorout, directorargout</TT> are used in place of <TT>in, out,
32599  argout</TT> typemaps, except that their direction is reversed. They
32600  provide for you to provide argout values, as well as a function return
32601  value in the same way you provide function arguments, and to receive
32602  arguments the same way you normally receive function returns.</P>
32603 <H4><A name="Ocaml_nn28"></A>26.2.5.6 <TT>directorin</TT> typemap</H4>
32604 <P> The <TT>directorin</TT> typemap is used when you will receive
32605  arguments from a call made by C++ code to you, therefore, values will
32606  be translated from C++ to ocaml. You must provide some valid C_obj
32607  value. This is the value your ocaml code receives when you are called.
32608  In general, a simple <TT>directorin</TT> typemap can use the same body
32609  as a simple <TT>out</TT> typemap.</P>
32610 <H4><A name="Ocaml_nn29"></A>26.2.5.7 <TT>directorout</TT> typemap</H4>
32611 <P> The <TT>directorout</TT> typemap is used when you will send an
32612  argument from your code back to the C++ caller. That is; directorout
32613  specifies a function return conversion. You can usually use the same
32614  body as an <TT>in</TT> typemap for the same type, except when there are
32615  special requirements for object ownership, etc.</P>
32616 <H4><A name="Ocaml_nn30"></A>26.2.5.8 <TT>directorargout</TT> typemap</H4>
32617 <P> C++ allows function arguments which are by pointer (*) and by
32618  reference (&amp;) to receive a value from the called function, as well as
32619  sending one there. Sometimes, this is the main purpose of the argument
32620  given. <TT>directorargout</TT> typemaps allow your caml code to emulate
32621  this by specifying additional return values to be put into the output
32622  parameters. The SWIG ocaml module is a bit loose in order to make code
32623  easier to write. In this case, your return to the caller must be a list
32624  containing the normal function return first, followed by any argout
32625  values in order. These argout values will be taken from the list and
32626  assigned to the values to be returned to C++ through directorargout
32627  typemaps. In the event that you don't specify all of the necessary
32628  values, integral values will read zero, and struct or object returns
32629  have undefined results.</P>
32630 <H3><A name="Ocaml_nn31"></A>26.2.6 Exceptions</H3>
32631 <P> Catching exceptions is now supported using SWIG's %exception
32632  feature. A simple but not too useful example is provided by the
32633  throw_exception testcase in Examples/test-suite. You can provide your
32634  own exceptions, too.</P>
32635 <HR NOSHADE>
32636 <H1><A name="Octave"></A>27 SWIG and Octave</H1>
32637
32638 <!-- INDEX -->
32639 <DIV class="sectiontoc">
32640 <UL>
32641 <LI><A href="#Octave_nn2">Preliminaries</A></LI>
32642 <LI><A href="#Octave_nn3">Running SWIG</A>
32643 <UL>
32644 <LI><A href="#Octave_nn5">Compiling a dynamic module</A></LI>
32645 <LI><A href="#Octave_nn6">Using your module</A></LI>
32646 </UL>
32647 </LI>
32648 <LI><A href="#Octave_nn7">A tour of basic C/C++ wrapping</A>
32649 <UL>
32650 <LI><A href="#Octave_nn8">Modules</A></LI>
32651 <LI><A href="#Octave_nn9">Functions</A></LI>
32652 <LI><A href="#Octave_nn10">Global variables</A></LI>
32653 <LI><A href="#Octave_nn11">Constants and enums</A></LI>
32654 <LI><A href="#Octave_nn12">Pointers</A></LI>
32655 <LI><A href="#Octave_nn13">Structures and C++ classes</A></LI>
32656 <LI><A href="#Octave_nn15">C++ inheritance</A></LI>
32657 <LI><A href="#Octave_nn17">C++ overloaded functions</A></LI>
32658 <LI><A href="#Octave_nn18">C++ operators</A></LI>
32659 <LI><A href="#Octave_nn19">Class extension with %extend</A></LI>
32660 <LI><A href="#Octave_nn20">C++ templates</A></LI>
32661 <LI><A href="#Octave_nn21">C++ Smart Pointers</A></LI>
32662 <LI><A href="#Octave_nn22">Directors (calling Octave from C++ code)</A></LI>
32663 <LI><A href="#Octave_nn23">Threads</A></LI>
32664 <LI><A href="#Octave_nn24">Memory management</A></LI>
32665 <LI><A href="#Octave_nn25">STL support</A></LI>
32666 <LI><A href="#Octave_nn26">Matrix typemaps</A></LI>
32667 </UL>
32668 </LI>
32669 </UL>
32670 </DIV>
32671 <!-- INDEX -->
32672 <P> Octave is a high-level language intended for numerical programming
32673  that is mostly compatible with MATLAB. More information can be found at
32674  <A href="http://www.octave.org">www.octave.org</A>.</P>
32675 <P> This chapter is intended to give an introduction to using the
32676  module. You should also read the SWIG documentation that is not
32677  specific to Octave. Also, there are a dozen or so examples in the
32678  Examples/octave directory, and hundreds in the test suite
32679  (Examples/test-suite and Examples/test-suite/octave).</P>
32680 <H2><A name="Octave_nn2"></A>27.1 Preliminaries</H2>
32681 <P> The current SWIG implemention is based on Octave 2.9.12. Support for
32682  other versions (in particular the recent 3.0) has not been tested, nor
32683  has support for any OS other than Linux.</P>
32684 <H2><A name="Octave_nn3"></A>27.2 Running SWIG</H2>
32685 <P> Let's start with a very simple SWIG interface file:</P>
32686 <DIV class="code">
32687 <PRE>%module example
32688 %{
32689 #include &quot;example.h&quot;
32690 %}
32691 int gcd(int x, int y);
32692 extern double Foo; </PRE>
32693 </DIV>
32694 <P> To build an Octave module, run SWIG using the <TT>-octave</TT>
32695  option. The <TT>-c++</TT> option is required (for now) as Octave itself
32696  is written in C++ and thus the wrapper code must also be.</P>
32697 <DIV class="shell">
32698 <PRE>$ swig -octave -c++ example.i </PRE>
32699 </DIV>
32700 <P> This creates a C/C++ source file <TT>example_wrap.cxx</TT>. The
32701  generated C++ source file contains the low-level wrappers that need to
32702  be compiled and linked with the rest of your C/C++ application (in this
32703  case, the gcd implementation) to create an extension module.</P>
32704 <P> The swig command line has a number of options you can use, like to
32705  redirect it's output. Use <TT>swig --help</TT> to learn about these.</P>
32706 <H3><A name="Octave_nn5"></A>27.2.1 Compiling a dynamic module</H3>
32707 <P> Octave modules are DLLs/shared objects having the &quot;.oct&quot; suffix.
32708  Building an oct file is usually done with the mkoctfile command (either
32709  within Octave itself, or from the shell). For example,</P>
32710 <DIV class="shell">
32711 <PRE>
32712 $ swig -octave -c++ example.i -o example_wrap.cxx
32713 $ mkoctfile example_wrap.cxx example.c
32714 </PRE>
32715 </DIV>
32716 <P> where example.c is the file containing the gcd() implementation.</P>
32717 <P> mkoctfile can also be used to extract the build parameters required
32718  to invoke the compiler and linker yourself. See the Octave manual and
32719  mkoctfile man page.</P>
32720 <P> mkoctfile will produce example.oct, which contains the compiled
32721  extension module. Loading it into Octave is then a matter of invoking</P>
32722 <DIV class="targetlang">
32723 <PRE>octave:1&gt; example</PRE>
32724 </DIV>
32725 <H3><A name="Octave_nn6"></A>27.2.2 Using your module</H3>
32726 <P> Assuming all goes well, you will be able to do this:
32727 <BR></P>
32728 <DIV class="targetlang">
32729 <PRE>$ octave -q
32730 octave:1&gt; example
32731 octave:2&gt; example.gcd(4,6)
32732 ans =  2
32733 octave:3&gt; example.cvar.Foo
32734 ans =  3
32735 octave:4&gt; example.cvar.Foo=4;
32736 octave:5&gt; example.cvar.Foo
32737 ans =  4 </PRE>
32738 </DIV>
32739 <H2><A name="Octave_nn7"></A>27.3 A tour of basic C/C++ wrapping</H2>
32740 <H3><A name="Octave_nn8"></A>27.3.1 Modules</H3>
32741 <P> The SWIG module directive specifies the name of the Octave module.
32742  If you specify `module example', then in Octave everything in the
32743  module will be accessible under &quot;example&quot;, as in the above example.
32744  When choosing a module name, make sure you don't use the same name as a
32745  built-in Octave command or standard module name.</P>
32746 <P> When Octave is asked to invoke <TT>example</TT>, it will try to find
32747  the .m or .oct file that defines the function &quot;example&quot;. It will thusly
32748  find example.oct, that upon loading will register all of the module's
32749  symbols.</P>
32750 <P> Giving this function a parameter &quot;global&quot; will cause it to load all
32751  symbols into the global namespace in addition to the <TT>example</TT>
32752  namespace. For example:</P>
32753 <DIV class="targetlang">
32754 <PRE>$ octave -q
32755 octave:1&gt; example(&quot;global&quot;)
32756 octave:2&gt; gcd(4,6)
32757 ans =  2
32758 octave:3&gt; cvar.Foo
32759 ans =  3
32760 octave:4&gt; cvar.Foo=4;
32761 octave:5&gt; cvar.Foo
32762 ans =  4 
32763 </PRE>
32764 </DIV>
32765 <P> It is also possible to rename the module namespace with an
32766  assignment, as in:
32767 <BR><DIV class="targetlang">
32768 <PRE>octave:1&gt; example;
32769 octave:2&gt; c=example;
32770 octave:3&gt; c.gcd(10,4)
32771 ans =  2 </PRE>
32772 </DIV></P>
32773 <P> All global variables are put into the cvar namespace object. This is
32774  accessible either as <TT>my_module.cvar</TT>, or just <TT>cvar</TT> (if
32775  the module is imported into the global namespace).</P>
32776 <P> One can also rename it by simple assignment, e.g.,</P>
32777 <DIV class="targetlang">
32778 <PRE>
32779 octave:1&gt; some_vars = cvar;
32780 </PRE>
32781 </DIV>
32782 <H3><A name="Octave_nn9"></A>27.3.2 Functions</H3>
32783 <P> Global functions are wrapped as new Octave built-in functions. For
32784  example,</P>
32785 <DIV class="code">
32786 <PRE>%module example
32787 int fact(int n); </PRE>
32788 </DIV>
32789 <P> creates a built-in function <TT>example.fact(n)</TT> that works
32790  exactly like you think it does:</P>
32791 <DIV class="targetlang">
32792 <PRE>octave:1&gt; example.fact(4)
32793 24 </PRE>
32794 </DIV>
32795 <H3><A name="Octave_nn10"></A>27.3.3 Global variables</H3>
32796 <P> Global variables are a little special in Octave. Given a global
32797  variable:</P>
32798 <DIV class="code">
32799 <PRE>%module example
32800 extern double Foo;
32801       </PRE>
32802 </DIV>
32803 <P> To expose variables, SWIG actually generates two functions, to get
32804  and set the value. In this case, Foo_set and Foo_set would be
32805  generated. SWIG then automatically calls these functions when you get
32806  and set the variable-- in the former case creating a local copy in the
32807  interpreter of the C variables, and in the latter case copying an
32808  interpreter variables onto the C variable.</P>
32809 <DIV class="targetlang">
32810 <PRE>octave:1&gt; example;
32811 octave:2&gt; c=example.cvar.Foo
32812 c =  3
32813 octave:3&gt; example.cvar.Foo=4;
32814 octave:4&gt; c
32815 c =  3
32816 octave:5&gt; example.cvar.Foo
32817 ans =  4</PRE>
32818 </DIV>
32819 <P> If a variable is marked with the %immutable directive then any
32820  attempts to set this variable will cause an Octave error. Given a
32821  global variable:</P>
32822 <DIV class="code">
32823 <PRE>%module example
32824 %immutable;
32825 extern double Foo;
32826 %mutable;
32827 </PRE>
32828 </DIV>
32829 <P> SWIG will allow the the reading of <TT>Foo</TT> but when a set
32830  attempt is made, an error function will be called.</P>
32831 <DIV class="targetlang">
32832 <PRE>octave:1&gt; example
32833 octave:2&gt; example.Foo=4
32834 error: attempt to set immutable member variable
32835 error: assignment failed, or no method for `swig_type = scalar'
32836 error: evaluating assignment expression near line 2, column 12 </PRE>
32837 </DIV>
32838 <P> It is possible to add new functions or variables to the module. This
32839  also allows the user to rename/remove existing functions and constants
32840  (but not linked variables, mutable or immutable). Therefore users are
32841  recommended to be careful when doing so.</P>
32842 <DIV class="targetlang">
32843 <PRE>octave:1&gt; example;
32844 octave:2&gt; example.PI=3.142;
32845 octave:3&gt; example.PI
32846 ans =  3.1420 </PRE>
32847 </DIV>
32848 <H3><A name="Octave_nn11"></A>27.3.4 Constants and enums</H3>
32849 <P> Because Octave doesn't really have the concept of constants, C/C++
32850  constants are not really constant in Octave. They are actually just a
32851  copy of the value into the Octave interpreter. Therefore they can be
32852  changed just as any other value. For example given some constants:</P>
32853 <DIV class="code">
32854 <PRE>%module example
32855 %constant int ICONST=42;
32856 #define    SCONST      &quot;Hello World&quot;
32857 enum Days{SUNDAY,MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY};
32858 </PRE>
32859 </DIV>
32860 <P> This is 'effectively' converted into the following Octave code:</P>
32861 <DIV class="targetlang">
32862 <PRE>example.ICONST=42
32863 example.SCONST=&quot;Hello World&quot;
32864 example.SUNDAY=0
32865 .... </PRE>
32866 </DIV>
32867 <H3><A name="Octave_nn12"></A>27.3.5 Pointers</H3>
32868 <P> C/C++ pointers are fully supported by SWIG. Furthermore, SWIG has no
32869  problem working with incomplete type information. Given a wrapping of
32870  the &lt;file.h&gt; interface: C/C++ pointers are fully supported by SWIG.
32871  Furthermore, SWIG has no problem working with incomplete type
32872  information. Given a wrapping of the &lt;file.h&gt; interface:</P>
32873 <DIV class="code">
32874 <PRE>%module example
32875 FILE *fopen(const char *filename, const char *mode);
32876 int fputs(const char *, FILE *);
32877 int fclose(FILE *);
32878 </PRE>
32879 </DIV>
32880 <P> When wrapped, you will be able to use the functions in a natural way
32881  from Octave. For example:</P>
32882 <DIV class="targetlang">
32883 <PRE>
32884 octave:1&gt; example;
32885 octave:2&gt; f=example.fopen(&quot;w&quot;,&quot;junk&quot;);
32886 octave:3&gt; example.fputs(&quot;Hello world&quot;,f);
32887 octave:4&gt; example.fclose(f);
32888 </PRE>
32889 </DIV>
32890 <P> Simply printing the value of a wrapped C++ type will print it's
32891  typename. E.g.,</P>
32892 <DIV class="targetlang">
32893 <PRE>octave:1&gt; example;
32894 octave:2&gt; f=example.fopen(&quot;junk&quot;,&quot;w&quot;);
32895 octave:3&gt; f
32896 f =
32897
32898 {
32899   _p_FILE, ptr = 0x9b0cd00
32900 } </PRE>
32901 </DIV>
32902 <P> As the user of the pointer, you are responsible for freeing it, or
32903  closing any resources associated with it (just as you would in a C
32904  program). This does not apply so strictly to classes and structs (see
32905  below).</P>
32906 <DIV class="targetlang">
32907 <PRE>octave:1&gt; example;
32908 octave:2&gt; f=example.fopen(&quot;not there&quot;,&quot;r&quot;);
32909 error: value on right hand side of assignment is undefined
32910 error: evaluating assignment expression near line 2, column 2 </PRE>
32911 </DIV>
32912 <H3><A name="Octave_nn13"></A>27.3.6 Structures and C++ classes</H3>
32913 <P> SWIG wraps C structures and C++ classes by using a special Octave
32914  type called a <TT>swig_ref</TT>. A <TT>swig_ref</TT> contains a
32915  reference to one or more instances of C/C++ objects, or just the type
32916  information for an object. For each wrapped structure and class, a <TT>
32917 swig_ref</TT> will be exposed that has the name of the type. When
32918  invoked as a function, it creates a new object of its type and returns
32919  a <TT>swig_ref</TT> that points to that instance. This provides a very
32920  natural interface. For example,</P>
32921 <DIV class="code">
32922 <PRE>struct Point{
32923   int x,y;
32924 };
32925 </PRE>
32926 </DIV>
32927 <P> is used as follows:</P>
32928 <DIV class="targetlang">
32929 <PRE>octave:1&gt; example;
32930 octave:2&gt; p=example.Point();
32931 octave:3&gt; p.x=3;
32932 octave:4&gt; p.y=5;
32933 octave:5&gt; p.x, p.y
32934 ans =  3
32935 ans =  5 
32936 </PRE>
32937 </DIV>
32938 <P> In C++, invoking the type object in this way calls the object's
32939  constructor. <TT>swig_ref</TT> objects can also be acquired by having a
32940  wrapped function return a pointer, reference, or value of a
32941  non-primitive type.</P>
32942 <P> The swig_ref type handles indexing operations such that usage maps
32943  closely to what you would have in C/C++. Structure members are accessed
32944  as in the above example, by calling set and get methods for C++
32945  variables. Methods also work as expected. For example, code wrapped in
32946  the following way</P>
32947 <DIV class="code">
32948 <PRE>class Point{
32949 public:
32950   int x,y;
32951   Point(int _x,int _y) : x(_x),y(_y) {}
32952   double distance(const Point&amp; rhs) {
32953     return sqrt(pow(x-rhs.x,2)+pow(y-rhs.y,2));
32954   }
32955   void set(int _x,int _y) {
32956     x=_x; y=_y;
32957   }
32958 };
32959 </PRE>
32960 </DIV>
32961 <P> can be used from Octave like this</P>
32962 <DIV class="targetlang">
32963 <PRE>octave:1&gt; example;
32964 octave:2&gt; p1=example.Point(3,5);
32965 octave:3&gt; p2=example.Point(1,2);
32966 octave:4&gt; p1.distance(p2)
32967 ans =  3.6056
32968 </PRE>
32969 </DIV>
32970 <P> By using the <TT>swig_this()</TT> and <TT>swig_type()</TT>
32971  functions, one can discover the pointers to and types of the underlying
32972  C/C++ object.</P>
32973 <DIV class="targetlang">
32974 <PRE>
32975 octave:5&gt; swig_this(p1)
32976 ans = 162504808
32977 octave:6&gt; swig_type(p1)
32978 ans = Point
32979 </PRE>
32980 </DIV>
32981 <P> Note that <TT>swig_ref</TT> is a reference-counted pointer to a
32982  C/C++ object/type, and as such has pass-by-reference semantics. For
32983  example if one has a allocated a single object but has two <TT>swig_ref</TT>
32984 's pointing to it, modifying the object through either of them will
32985  change the single allocated object. This differs from the usual
32986  pass-by-value (copy-on-write) semantics that Octave maintains for
32987  built-in types. For example, in the following snippet, modifying <TT>b</TT>
32988  does not modify <TT>a</TT>,</P>
32989 <DIV class="targetlang">
32990 <PRE>
32991 octave:7&gt; a=struct('x',4)
32992 a =
32993 {
32994   x =  4
32995 }
32996
32997 octave:8&gt; b=a
32998 b =
32999 {
33000   x =  4
33001 }
33002
33003 octave:9&gt; b.y=4
33004 b =
33005 {
33006   x =  4
33007   y =  4
33008 }
33009
33010 octave:10&gt; a
33011 a =
33012 {
33013   x =  4
33014 }
33015 </PRE>
33016 </DIV>
33017 <P> However, when dealing with wrapped objects, one gets the behavior</P>
33018 <DIV class="targetlang">
33019 <PRE>
33020 octave:2&gt; a=Point(3,5)
33021 a =
33022
33023 {
33024   Point, ptr = 0x9afbbb0
33025 }
33026
33027 octave:3&gt; b=a
33028 b =
33029
33030 {
33031   Point, ptr = 0x9afbbb0
33032 }
33033
33034 octave:4&gt; b.set(2,1);
33035 octave:5&gt; b.x, b.y
33036 ans =  2
33037 ans =  1
33038 octave:6&gt; a.x, a.y
33039 ans =  2
33040 ans =  1
33041 </PRE>
33042 </DIV>
33043 <P> Depending on the ownership setting of a <TT>swig_ref</TT>, it may
33044  call C++ destructors when its reference count goes to zero. See the
33045  section on memory management below for details.</P>
33046 <H3><A name="Octave_nn15"></A>27.3.7 C++ inheritance</H3>
33047 <P> Single and multiple inheritance are fully supported. The <TT>
33048 swig_ref</TT> type carries type information along with any C++ object
33049  pointer it holds. This information contains the full class hierarchy.
33050  When an indexing operation (such as a method invocation) occurs, the
33051  tree is walked to find a match in the current class as well as any of
33052  its bases. The lookup is then cached in the <TT>swig_ref</TT>.</P>
33053 <H3><A name="Octave_nn17"></A>27.3.8 C++ overloaded functions</H3>
33054 <P> Overloaded functions are supported, and handled as in other modules.
33055  That is, each overload is wrapped separately (under internal names),
33056  and a dispatch function is also emitted under the external/visible
33057  name. The dispatch function selects which overload to call (if any)
33058  based on the passed arguments. <TT>typecheck</TT> typemaps are used to
33059  analyze each argument, as well as assign precedence. See the chapter on
33060  typemaps for details.</P>
33061 <H3><A name="Octave_nn18"></A>27.3.9 C++ operators</H3>
33062 <P> C++ operator overloading is supported, in a way similar to other
33063  modules. The <TT>swig_ref</TT> type supports all unary and binary
33064  operators between itself and all other types that exist in the system
33065  at module load time. When an operator is used (where one of the
33066  operands is a <TT>swig_ref</TT>), the runtime routes the call to either
33067  a member function of the given object, or to a global function whose
33068  named is derived from the types of the operands (either both or just
33069  the lhs or rhs).</P>
33070 <P> For example, if <TT>a</TT> and <TT>b</TT> are SWIG variables in
33071  Octave, <TT>a+b</TT> becomes <TT>a.__add(b)</TT>. The wrapper is then
33072  free to implement __add to do whatever it wants. A wrapper may define
33073  the <TT>__add</TT> function manually, %rename some other function to
33074  it, or %rename a C++ operator to it.</P>
33075 <P> By default the C++ operators are renamed to their corresponding
33076  Octave operators. So without doing any work, the following interface</P>
33077 <DIV class="code">
33078 <PRE>
33079 %inline {
33080 struct A {
33081   int value;
33082   A(int _value) : value(_value) {}
33083   A operator+ (const A&amp; x) {
33084     return A(value+x.value);
33085   }
33086 };
33087 }
33088 </PRE>
33089 </DIV>
33090 <P> is usable from Octave like this:</P>
33091 <DIV class="targetlang">
33092 <PRE>
33093 a=A(2), b=A(3), c=a+b
33094 assert(c.value==5);
33095 </PRE>
33096 </DIV>
33097 <P> Octave operators are mapped in the following way:</P>
33098 <DIV class="code">
33099 <PRE>
33100 __brace      a{args}
33101 __brace_asgn a{args} = rhs
33102 __paren      a(args)
33103 __paren_asgn a(args) = rhs
33104 __str        generates string rep
33105 __not        !a
33106 __uplus      +a
33107 __uminus     -a
33108 __transpose  a.'
33109 __hermitian  a'
33110 __incr       a++
33111 __decr       a--
33112 __add        a + b
33113 __sub        a - b
33114 __mul        a * b
33115 __div        a / b
33116 __pow        a ^ b
33117 __ldiv       a \ b
33118 __lshift     a &lt;&lt;b
33119 __rshift     a &gt;&gt; b
33120 __lt         a  &lt;b
33121 __le         a  &lt;= b
33122 __eq         a == b
33123 __ge         a &gt;= b
33124 __gt         a &gt; b
33125 __ne         a != b
33126 __el_mul     a .* b
33127 __el_div     a ./ b
33128 __el_pow     a .^ b
33129 __el_ldiv    a .\ b
33130 __el_and     a &amp; b
33131 __el_or      a | b
33132 </PRE>
33133 </DIV>
33134 <P> On the C++ side, the default mappings are as follows:</P>
33135 <DIV class="code">
33136 <PRE>
33137 %rename(__add)       *::operator+;
33138 %rename(__add)       *::operator+();
33139 %rename(__add)       *::operator+() const;
33140 %rename(__sub)       *::operator-;
33141 %rename(__uminus)    *::operator-();
33142 %rename(__uminus)    *::operator-() const;
33143 %rename(__mul)       *::operator*;
33144 %rename(__div)       *::operator/;
33145 %rename(__mod)       *::operator%;
33146 %rename(__lshift)    *::operator&lt;
33147 <!--;
33148 %rename(__rshift)    *::operator-->
33149 &gt;;
33150 %rename(__el_and)    *::operator&amp;&amp;;
33151 %rename(__el_or)     *::operator||;
33152 %rename(__xor)       *::operator^;
33153 %rename(__invert)    *::operator~;
33154 %rename(__lt)        *::operator
33155 <!--;
33156 %rename(__le)        *::operator&lt;=;
33157 %rename(__gt)        *::operator-->
33158 ;
33159 %rename(__ge)        *::operator&gt;=;
33160 %rename(__eq)        *::operator==;
33161 %rename(__ne)        *::operator!=;
33162 %rename(__not)       *::operator!;
33163 %rename(__incr)      *::operator++;
33164 %rename(__decr)      *::operator--;
33165 %rename(__paren)     *::operator();
33166 %rename(__brace)     *::operator[];
33167 </PRE>
33168 </DIV>
33169 <H3><A name="Octave_nn19"></A>27.3.10 Class extension with %extend</H3>
33170 <P> The %extend directive works the same as in other modules.</P>
33171 <P> You can use it to define special behavior, like for example defining
33172  Octave operators not mapped to C++ operators, or defining certain
33173  Octave mechanisms such as how an object prints. For example, the <TT>
33174 octave_value::{is_string,string_value,print}</TT> functions are routed
33175  to a special method <TT>__str</TT> that can be defined inside an
33176  %extend.</P>
33177 <DIV class="code">
33178 <PRE>
33179 %extend A {
33180 string __str() {
33181   stringstream sout;
33182   sout&lt;&lt;$self-&gt;value;
33183   return sout.str();
33184 }
33185 }
33186 </PRE>
33187 </DIV>
33188 <P> Then in Octave one gets,</P>
33189 <DIV class="targetlang">
33190 <PRE>
33191 octave:1&gt; a=A(4);
33192 octave:2&gt; a
33193 a = 4
33194 octave:3&gt; printf(&quot;%s\n&quot;,a);
33195 4
33196 octave:4&gt; a.__str()
33197 4
33198 </PRE>
33199 </DIV>
33200 <H3><A name="Octave_nn20"></A>27.3.11 C++ templates</H3>
33201 <P> C++ class and function templates are fully supported as in other
33202  modules, in that the %template directive may used to create explicit
33203  instantiations of templated types. For example, function templates can
33204  be instantiated as follows:</P>
33205 <DIV class="code">
33206 <PRE>%module example
33207 %inline {
33208  template&lt;class __scalar&gt;
33209    __scalar mul(__scalar a,__scalar b) {
33210    return a*b;
33211  }
33212 }
33213 %include &lt;std_complex.i&gt;
33214 %template(mul) mul&lt;std::complex&lt;double&gt; &gt;
33215 %template(mul) mul&lt;double&gt;
33216 </PRE>
33217 </DIV>
33218 <P> and then used from Octave</P>
33219 <DIV class="targetlang">
33220 <PRE>
33221 octave:1&gt; mul(4,3)
33222 ans =  12
33223 octave:2&gt; mul(4.2,3.6)
33224 ans =  15.120
33225 octave:3&gt; mul(3+4i,10+2i)
33226 ans =  22 + 46i
33227 </PRE>
33228 </DIV>
33229 <P> Similarly, class templates can be instantiated as in the following
33230  example,</P>
33231 <DIV class="code">
33232 <PRE>%module example
33233 %include &lt;std_complex.i&gt;
33234 %include &lt;std_string.i&gt;
33235 %inline {
33236   #include &lt;sstream&gt;
33237   template&lt;class __scalar&gt; class sum {
33238     __scalar s;
33239   public:
33240     sum(__scalar _s=0) : s(_s) {}
33241     sum&amp; add(__scalar _s) {
33242       s+=_s;
33243       return *this;
33244     }
33245     std::string __str() const {
33246       std::stringstream sout;
33247       sout&lt;&lt;s;
33248       return sout.str();
33249     }
33250   };
33251 }
33252 %template(sum_complex) sum&lt;std::complex&lt;double&gt; &gt;;
33253 %template(sum_double) sum&lt;double&gt;;
33254 </PRE>
33255 </DIV>
33256 <P> and then used from Octave</P>
33257 <DIV class="targetlang">
33258 <PRE>
33259 octave:2&gt; a=sum_complex(2+3i);
33260 octave:3&gt; a.add(2)
33261 ans =
33262
33263 (4,3)
33264 octave:4&gt; a.add(3+i)
33265 ans =
33266
33267 (7,4)
33268 </PRE>
33269 </DIV>
33270 <H3><A name="Octave_nn21"></A>27.3.12 C++ Smart Pointers</H3>
33271 <P> C++ smart pointers are fully supported as in other modules.</P>
33272 <H3><A name="Octave_nn22"></A>27.3.13 Directors (calling Octave from C++
33273  code)</H3>
33274 <P> There is full support for SWIG Directors, which permits Octave code
33275  to subclass C++ classes, and implement their virtual methods.</P>
33276 <P> Octave has no direct support for object oriented programming,
33277  however the <TT>swig_ref</TT> type provides some of this support. You
33278  can manufacture a <TT>swig_ref</TT> using the <TT>subclass</TT>
33279  function (provided by the SWIG/Octave runtime).</P>
33280 <P> For example,</P>
33281 <DIV class="targetlang">
33282 <PRE>
33283 octave:1&gt; a=subclass();
33284 octave:2&gt; a.my_var = 4;
33285 octave:3&gt; a.my_method = @(self) printf(&quot;my_var = &quot;,self.my_var);
33286 octave:4&gt; a.my_method();
33287 my_var = 4
33288 </PRE>
33289 </DIV>
33290 <P> <TT>subclass()</TT> can also be used to subclass one or more C++
33291  types. Suppose you have an interface defined by</P>
33292 <DIV class="code">
33293 <PRE>
33294 %inline {
33295 class A {
33296 public:
33297   virtual my_method() {
33298     printf(&quot;c-side routine called\n&quot;);
33299   }
33300 };
33301 void call_your_method(A&amp; a) {
33302   a.my_method();
33303 }
33304 }
33305 </PRE>
33306 </DIV>
33307 <P> Then from Octave you can say:</P>
33308 <DIV class="targetlang">
33309 <PRE>
33310 octave:1&gt; B=@() subclass(A(),@my_method);
33311 octave:2&gt; function my_method(self)
33312 octave:3&gt;   printf(&quot;octave-side routine called\n&quot;);
33313 octave:4&gt; end
33314 octave:5&gt; call_your_method(B());
33315 octave-side routine called
33316 </PRE>
33317 </DIV>
33318 <P> or more concisely,</P>
33319 <DIV class="targetlang">
33320 <PRE>
33321 octave:1&gt; B=@() subclass(A(),'my_method',@(self) printf(&quot;octave-side routine called\n&quot;));
33322 octave:2&gt; call_your_method(B());
33323 octave-side routine called
33324 </PRE>
33325 </DIV>
33326 <P> Note that you have to enable directors via the %feature directive
33327  (see other modules for this).</P>
33328 <P> <TT>subclass()</TT> will accept any number of C++ bases or other <TT>
33329 subclass()</TT>'ed objects, <TT>(string,octave_value)</TT> pairs, and <TT>
33330 function_handles</TT>. In the first case, these are taken as base
33331  classes; in the second case, as named members (either variables or
33332  functions, depending on whether the given value is a function handle);
33333  in the third case, as member functions whose name is taken from the
33334  given function handle. E.g.,</P>
33335 <DIV class="targetlang">
33336 <PRE>
33337 octave:1&gt; B=@(some_var=2) subclass(A(),'some_var',some_var,@some_func,'another_func',@(self) do_stuff())
33338 </PRE>
33339 </DIV>
33340 <P> You can also assign non-C++ member variables and functions after
33341  construct time. There is no support for non-C++ static members.</P>
33342 <P> There is limited support for explicitly referencing C++ bases. So,
33343  in the example above, we could have</P>
33344 <DIV class="targetlang">
33345 <PRE>
33346 octave:1&gt; B=@() subclass(A(),@my_method);
33347 octave:2&gt; function my_method(self)
33348 octave:3&gt;   self.A.my_method();
33349 octave:4&gt;   printf(&quot;octave-side routine called\n&quot;);
33350 octave:5&gt; end
33351 octave:6&gt; call_your_method(B());
33352 c-side routine called
33353 octave-side routine called
33354 </PRE>
33355 </DIV>
33356 <H3><A name="Octave_nn23"></A>27.3.14 Threads</H3>
33357 <P> The use of threads in wrapped Director code is not supported; i.e.,
33358  an Octave-side implementation of a C++ class must be called from the
33359  Octave interpreter's thread. Anything fancier (apartment/queue model,
33360  whatever) is left to the user. Without anything fancier, this amounts
33361  to the limitation that Octave must drive the module... like, for
33362  example, an optimization package that calls Octave to evaluate an
33363  objective function.</P>
33364 <H3><A name="Octave_nn24"></A>27.3.15 Memory management</H3>
33365 <P> As noted above, <TT>swig_ref</TT> represents a reference counted
33366  pointer to a C/C++-side object. It also contains a flag indicating
33367  whether Octave or the C/C++ code owns the object. If Octave owns it,
33368  any destructors will be called when the reference count reaches zero.
33369  If the C/C++ side owns the object, then destructors will not be called
33370  when the reference count goes to zero.</P>
33371 <P> For example,<DIV class="code">
33372 <PRE>
33373 %inline {
33374 class A {
33375 public:
33376   A() { printf(&quot;A constructing\n&quot;); }
33377   ~A() { printf(&quot;A destructing\n&quot;); }
33378 };
33379 }
33380 </PRE>
33381 </DIV></P>
33382 <P> Would produce this behavior in Octave:</P>
33383 <DIV class="targetlang">
33384 <PRE>
33385 octave:1&gt; a=A();
33386 A constructing
33387 octave:2&gt; b=a;
33388 octave:3&gt; clear a;
33389 octave:4&gt; b=4;
33390 A destructing
33391 </PRE>
33392 </DIV>
33393 <P> The %newobject directive may be used to control this behavior for
33394  pointers returned from functions.</P>
33395 <P> In the case where one wishes for the C++ side to own an object that
33396  was created in Octave (especially a Director object), one can use the
33397  __disown() method to invert this logic. Then letting the Octave
33398  reference count go to zero will not destroy the object, but destroying
33399  the object will invalidate the Octave-side object if it still exists
33400  (and call destructors of other C++ bases in the case of multiple
33401  inheritance/<TT>subclass()</TT>'ing).</P>
33402 <H3><A name="Octave_nn25"></A>27.3.16 STL support</H3>
33403 <P> This is some skeleton support for various STL containers.</P>
33404 <H3><A name="Octave_nn26"></A>27.3.17 Matrix typemaps</H3>
33405 <P> Octave provides a rich set of classes for dealing with matrices.
33406  Currently there are no built-in typemaps to deal with those. However,
33407  these are relatively straight forward for users to add themselves (see
33408  the docs on typemaps). Without much work (a single typemap decl-- say,
33409  5 lines of code in the interface file), it would be possible to have a
33410  function</P>
33411 <DIV class="code">
33412 <PRE>
33413 double my_det(const double* mat,int m,int n);
33414 </PRE>
33415 </DIV>
33416 <P> that is accessed from Octave as,</P>
33417 <DIV class="targetlang">
33418 <PRE>
33419 octave:1&gt; my_det(rand(4));
33420 ans = -0.18388
33421 </PRE>
33422 </DIV> <TT>
33423 <BR></TT><HR NOSHADE>
33424 <H1><A name="Perl5"></A>28 SWIG and Perl5</H1>
33425
33426 <!-- INDEX -->
33427 <DIV class="sectiontoc">
33428 <UL>
33429 <LI><A href="#Perl5_nn2">Overview</A></LI>
33430 <LI><A href="#Perl5_nn3">Preliminaries</A>
33431 <UL>
33432 <LI><A href="#Perl5_nn4">Getting the right header files</A></LI>
33433 <LI><A href="#Perl5_nn5">Compiling a dynamic module</A></LI>
33434 <LI><A href="#Perl5_nn6">Building a dynamic module with MakeMaker</A></LI>
33435 <LI><A href="#Perl5_nn7">Building a static version of Perl</A></LI>
33436 <LI><A href="#Perl5_nn8">Using the module</A></LI>
33437 <LI><A href="#Perl5_nn9">Compilation problems and compiling with C++</A></LI>
33438 <LI><A href="#Perl5_nn10">Compiling for 64-bit platforms</A></LI>
33439 </UL>
33440 </LI>
33441 <LI><A href="#Perl5_nn11">Building Perl Extensions under Windows</A>
33442 <UL>
33443 <LI><A href="#Perl5_nn12">Running SWIG from Developer Studio</A></LI>
33444 <LI><A href="#Perl5_nn13">Using other compilers</A></LI>
33445 </UL>
33446 </LI>
33447 <LI><A href="#Perl5_nn14">The low-level interface</A>
33448 <UL>
33449 <LI><A href="#Perl5_nn15">Functions</A></LI>
33450 <LI><A href="#Perl5_nn16">Global variables</A></LI>
33451 <LI><A href="#Perl5_nn17">Constants</A></LI>
33452 <LI><A href="#Perl5_nn18">Pointers</A></LI>
33453 <LI><A href="#Perl5_nn19">Structures</A></LI>
33454 <LI><A href="#Perl5_nn20">C++ classes</A></LI>
33455 <LI><A href="#Perl5_nn21">C++ classes and type-checking</A></LI>
33456 <LI><A href="#Perl5_nn22">C++ overloaded functions</A></LI>
33457 <LI><A href="#Perl5_nn23">Operators</A></LI>
33458 <LI><A href="#Perl5_nn24">Modules and packages</A></LI>
33459 </UL>
33460 </LI>
33461 <LI><A href="#Perl5_nn25">Input and output parameters</A></LI>
33462 <LI><A href="#Perl5_nn26">Exception handling</A></LI>
33463 <LI><A href="#Perl5_nn27">Remapping datatypes with typemaps</A>
33464 <UL>
33465 <LI><A href="#Perl5_nn28">A simple typemap example</A></LI>
33466 <LI><A href="#Perl5_nn29">Perl5 typemaps</A></LI>
33467 <LI><A href="#Perl5_nn30">Typemap variables</A></LI>
33468 <LI><A href="#Perl5_nn31">Useful functions</A></LI>
33469 </UL>
33470 </LI>
33471 <LI><A href="#Perl5_nn32">Typemap Examples</A>
33472 <UL>
33473 <LI><A href="#Perl5_nn33">Converting a Perl5 array to a char **</A></LI>
33474 <LI><A href="#Perl5_nn34">Return values</A></LI>
33475 <LI><A href="#Perl5_nn35">Returning values from arguments</A></LI>
33476 <LI><A href="#Perl5_nn36">Accessing array structure members</A></LI>
33477 <LI><A href="#Perl5_nn37">Turning Perl references into C pointers</A></LI>
33478 <LI><A href="#Perl5_nn38">Pointer handling</A></LI>
33479 </UL>
33480 </LI>
33481 <LI><A href="#Perl5_nn39">Proxy classes</A>
33482 <UL>
33483 <LI><A href="#Perl5_nn40">Preliminaries</A></LI>
33484 <LI><A href="#Perl5_nn41">Structure and class wrappers</A></LI>
33485 <LI><A href="#Perl5_nn42">Object Ownership</A></LI>
33486 <LI><A href="#Perl5_nn43">Nested Objects</A></LI>
33487 <LI><A href="#Perl5_nn44">Proxy Functions</A></LI>
33488 <LI><A href="#Perl5_nn45">Inheritance</A></LI>
33489 <LI><A href="#Perl5_nn46">Modifying the proxy methods</A></LI>
33490 </UL>
33491 </LI>
33492 <LI><A href="#Perl5_nn47">Adding additional Perl code</A></LI>
33493 </UL>
33494 </DIV>
33495 <!-- INDEX -->
33496 <P><B> Caution: This chapter is under repair!</B></P>
33497 <P> This chapter describes SWIG's support of Perl5. Although the Perl5
33498  module is one of the earliest SWIG modules, it has continued to evolve
33499  and has been improved greatly with the help of SWIG users. For the best
33500  results, it is recommended that SWIG be used with Perl5.003 or later.
33501  Earlier versions are problematic and SWIG generated extensions may not
33502  compile or run correctly.</P>
33503 <H2><A name="Perl5_nn2"></A>28.1 Overview</H2>
33504 <P> To build Perl extension modules, SWIG uses a layered approach. At
33505  the lowest level, simple procedural wrappers are generated for
33506  functions, classes, methods, and other declarations in the input file.
33507  Then, for structures and classes, an optional collection of Perl proxy
33508  classes can be generated in order to provide a more natural object
33509  oriented Perl interface. These proxy classes simply build upon the
33510  low-level interface.</P>
33511 <P> In describing the Perl interface, this chapter begins by covering
33512  the essentials. First, the problem of configuration, compiling, and
33513  installing Perl modules is discussed. Next, the low-level procedural
33514  interface is presented. Finally, proxy classes are described. Advanced
33515  customization features, typemaps, and other options are found near the
33516  end of the chapter.</P>
33517 <H2><A name="Perl5_nn3"></A>28.2 Preliminaries</H2>
33518 <P> To build a Perl5 module, run Swig using the <TT>-perl</TT> option as
33519  follows :</P>
33520 <DIV class="code">
33521 <PRE>
33522 swig -perl example.i
33523
33524 </PRE>
33525 </DIV>
33526 <P> This produces two files. The first file, <TT>example_wrap.c</TT>
33527  contains all of the C code needed to build a Perl5 module. The second
33528  file, <TT>example.pm</TT> contains supporting Perl code needed to
33529  properly load the module.</P>
33530 <P> To build the module, you will need to compile the file <TT>
33531 example_wrap.c</TT> and link it with the rest of your program.</P>
33532 <H3><A name="Perl5_nn4"></A>28.2.1 Getting the right header files</H3>
33533 <P> In order to compile, SWIG extensions need the following Perl5 header
33534  files :</P>
33535 <DIV class="code">
33536 <PRE>
33537 #include &quot;Extern.h&quot;
33538 #include &quot;perl.h&quot;
33539 #include &quot;XSUB.h&quot;
33540 </PRE>
33541 </DIV>
33542 <P> These are typically located in a directory like this</P>
33543 <DIV class="code">
33544 <PRE>
33545 /usr/lib/perl5/5.00503/i386-linux/CORE
33546 </PRE>
33547 </DIV>
33548 <P> The SWIG configuration script automatically tries to locate this
33549  directory so that it can compile examples. However, if you need to find
33550  out where the directory is loaded, an easy way to find out is to run
33551  Perl itself.</P>
33552 <DIV class="code">
33553 <PRE>
33554 % perl -e 'use Config; print $Config{archlib};'
33555 /usr/lib/perl5/5.00503/i386-linux
33556 </PRE>
33557 </DIV>
33558 <H3><A name="Perl5_nn5"></A>28.2.2 Compiling a dynamic module</H3>
33559 <P> The preferred approach to building an extension module is to compile
33560  it into a shared object file or DLL. To do this, you will need to
33561  compile your program using commands like this (shown for Linux):</P>
33562 <DIV class="code">
33563 <PRE>
33564 $ swig -perl example.i
33565 % gcc example.c
33566 % gcc -c example_wrap.c -I/usr/lib/perl5/5.00503/i386-linux/CORE -Dbool=char
33567 % gcc -shared example.o example_wrap.o -o example.so
33568 </PRE>
33569 </DIV>
33570 <P> The exact compiler options vary from platform to platform. SWIG
33571  tries to guess the right options when it is installed. Therefore, you
33572  may want to start with one of the examples in the <TT>
33573 SWIG/Examples/perl5</TT> directory. If that doesn't work, you will need
33574  to read the man-pages for your compiler and linker to get the right set
33575  of options. You might also check the <A href="http://www.dabeaz.com/cgi-bin/wiki.pl">
33576 SWIG Wiki</A> for additional information.</P>
33577 <P> When linking the module, the name of the shared object file must
33578  match the module name used in the SWIG interface file. If you used `<TT>
33579 %module example</TT>', then the target should be named `<TT>example.so</TT>
33580 ', `<TT>example.sl</TT>', or the appropriate dynamic module name on your
33581  system.</P>
33582 <H3><A name="Perl5_nn6"></A>28.2.3 Building a dynamic module with
33583  MakeMaker</H3>
33584 <P> It is also possible to use Perl to build dynamically loadable
33585  modules for you using the MakeMaker utility. To do this, write a Perl
33586  script such as the following :</P>
33587 <DIV class="targetlang">
33588 <PRE>
33589 # File : Makefile.PL
33590 use ExtUtils::MakeMaker;
33591 WriteMakefile(
33592         `NAME'    =&gt; `example',                  # Name of package
33593         `LIBS'    =&gt; [`-lm'],                    # Name of custom libraries
33594         `OBJECT'  =&gt; `example.o example_wrap.o'  # Object files
33595 );
33596
33597 </PRE>
33598 </DIV>
33599 <P> Now, to build a module, simply follow these steps :</P>
33600 <DIV class="code">
33601 <PRE>
33602 % perl Makefile.PL
33603 % make
33604 % make install
33605 </PRE>
33606 </DIV>
33607 <P> If you are planning to distribute a SWIG-generated module, this is
33608  the preferred approach to compilation. More information about MakeMaker
33609  can be found in &quot;Programming Perl, 2nd ed.&quot; by Larry Wall, Tom
33610  Christiansen, and Randal Schwartz.</P>
33611 <H3><A name="Perl5_nn7"></A>28.2.4 Building a static version of Perl</H3>
33612 <P> If you machine does not support dynamic loading or if you've tried
33613  to use it without success, you can build a new version of the Perl
33614  interpreter with your SWIG extensions added to it. To build a static
33615  extension, you first need to invoke SWIG as follows :</P>
33616 <DIV class="code">
33617 <PRE>
33618 % swig -perl -static example.i
33619 </PRE>
33620 </DIV>
33621 <P> By default SWIG includes code for dynamic loading, but the <TT>
33622 -static</TT> option takes it out.</P>
33623 <P> Next, you will need to supply a <TT>main()</TT> function that
33624  initializes your extension and starts the Perl interpreter. While, this
33625  may sound daunting, SWIG can do this for you automatically as follows :</P>
33626 <DIV class="targetlang">
33627 <PRE>
33628 %module example
33629
33630 %inline %{
33631 extern double My_variable;
33632 extern int fact(int);
33633 %}
33634
33635 // Include code for rebuilding Perl
33636 %include &lt;perlmain.i&gt;
33637 </PRE>
33638 </DIV>
33639 <P> The same thing can be accomplished by running SWIG as follows :</P>
33640 <DIV class="code">
33641 <PRE>
33642 % swig -perl -static -lperlmain.i example.i
33643 </PRE>
33644 </DIV>
33645 <P> The <TT>perlmain.i</TT> file inserts Perl's <TT>main()</TT> function
33646  into the wrapper code and automatically initializes the SWIG generated
33647  module. If you just want to make a quick a dirty module, this may be
33648  the easiest way. By default, the <TT>perlmain.i</TT> code does not
33649  initialize any other Perl extensions. If you need to use other
33650  packages, you will need to modify it appropriately. You can do this by
33651  just copying <TT>perlmain.i</TT> out of the SWIG library, placing it in
33652  your own directory, and modifying it to suit your purposes.</P>
33653 <P> To build your new Perl executable, follow the exact same procedure
33654  as for a dynamic module, but change the link line to something like
33655  this:</P>
33656 <DIV class="code">
33657 <PRE>
33658 % gcc example.o example_wrap.o -L/usr/lib/perl5/5.00503/i386-linux/CORE \
33659         -lperl -lsocket -lnsl -lm -o myperl
33660 </PRE>
33661 </DIV>
33662 <P> This will produce a new version of Perl called <TT>myperl</TT>. It
33663  should be functionality identical to Perl with your C/C++ extension
33664  added to it. Depending on your machine, you may need to link with
33665  additional libraries such as <TT>-lsocket, -lnsl, -ldl</TT>, etc.</P>
33666 <H3><A name="Perl5_nn8"></A>28.2.5 Using the module</H3>
33667 <P> To use the module, simply use the Perl <TT>use</TT> statement. If
33668  all goes well, you will be able to do this:</P>
33669 <DIV class="targetlang">
33670 <PRE>
33671 $ perl
33672 use example;
33673 print example::fact(4),&quot;\n&quot;;
33674 24
33675 </PRE>
33676 </DIV>
33677 <P> A common error received by first-time users is the following:</P>
33678 <DIV class="targetlang">
33679 <PRE>
33680 use example;
33681 Can't locate example.pm in @INC (@INC contains: /usr/lib/perl5/5.00503/i386-lin
33682 ux /usr/lib/perl5/5.00503 /usr/lib/perl5/site_perl/5.005/i386-linux /usr/lib/pe
33683 rl5/site_perl/5.005 .) at - line 1.
33684 BEGIN failed--compilation aborted at - line 1.
33685 </PRE>
33686 </DIV>
33687 <P> This error is almost caused when the name of the shared object file
33688  you created doesn't match the module name you specified with the <TT>
33689 %module</TT> directive.</P>
33690 <P> A somewhat related, but slightly different error is this:</P>
33691 <DIV class="targetlang">
33692 <PRE>
33693 use example;
33694 Can't find 'boot_example' symbol in ./example.so
33695  at - line 1
33696 BEGIN failed--compilation aborted at - line 1.
33697 </PRE>
33698 </DIV>
33699 <P> This error is generated because Perl can't locate the module
33700  bootstrap function in the SWIG extension module. This could be caused
33701  by a mismatch between the module name and the shared library name.
33702  However, another possible cause is forgetting to link the
33703  SWIG-generated wrapper code with the rest of your application when you
33704  linked the extension module.</P>
33705 <P> Another common error is the following:</P>
33706 <DIV class="targetlang">
33707 <PRE>
33708 use example;
33709 Can't load './example.so' for module example: ./example.so: 
33710 undefined symbol: Foo at /usr/lib/perl5/5.00503/i386-linux/DynaLoader.pm line 169.
33711
33712  at - line 1
33713 BEGIN failed--compilation aborted at - line 1.
33714 </PRE>
33715 </DIV>
33716 <P> This error usually indicates that you forgot to include some object
33717  files or libraries in the linking of the shared library file. Make sure
33718  you compile both the SWIG wrapper file and your original program into a
33719  shared library file. Make sure you pass all of the required libraries
33720  to the linker.</P>
33721 <P> Sometimes unresolved symbols occur because a wrapper has been
33722  created for a function that doesn't actually exist in a library. This
33723  usually occurs when a header file includes a declaration for a function
33724  that was never actually implemented or it was removed from a library
33725  without updating the header file. To fix this, you can either edit the
33726  SWIG input file to remove the offending declaration or you can use the <TT>
33727 %ignore</TT> directive to ignore the declaration. Better yet, update the
33728  header file so that it doesn't have an undefined declaration.</P>
33729 <P> Finally, suppose that your extension module is linked with another
33730  library like this:</P>
33731 <DIV class="code">
33732 <PRE>
33733 $ gcc -shared example.o example_wrap.o -L/home/beazley/projects/lib -lfoo \
33734       -o example.so
33735 </PRE>
33736 </DIV>
33737 <P> If the <TT>foo</TT> library is compiled as a shared library, you
33738  might get the following error when you try to use your module:</P>
33739 <DIV class="targetlang">
33740 <PRE>
33741 use example;
33742 Can't load './example.so' for module example: libfoo.so: cannot open shared object file: 
33743 No such file or directory at /usr/lib/perl5/5.00503/i386-linux/DynaLoader.pm line 169.
33744
33745  at - line 1
33746 BEGIN failed--compilation aborted at - line 1.
33747 &gt;&gt;&gt;                 
33748 </PRE>
33749 </DIV>
33750 <P> This error is generated because the dynamic linker can't locate the <TT>
33751 libfoo.so</TT> library. When shared libraries are loaded, the system
33752  normally only checks a few standard locations such as <TT>/usr/lib</TT>
33753  and <TT>/usr/local/lib</TT>. To get the loader to look in other
33754  locations, there are several things you can do. First, you can
33755  recompile your extension module with extra path information. For
33756  example, on Linux you can do this:</P>
33757 <DIV class="code">
33758 <PRE>
33759 $ gcc -shared example.o example_wrap.o -L/home/beazley/projects/lib -lfoo \
33760       <B>-Xlinker -rpath /home/beazley/projects/lib \</B>
33761       -o example.so
33762 </PRE>
33763 </DIV>
33764 <P> Alternatively, you can set the <TT>LD_LIBRARY_PATH</TT> environment
33765  variable to include the directory with your shared libraries. If
33766  setting <TT>LD_LIBRARY_PATH</TT>, be aware that setting this variable
33767  can introduce a noticeable performance impact on all other applications
33768  that you run. To set it only for Perl, you might want to do this
33769  instead:</P>
33770 <DIV class="code">
33771 <PRE>
33772 $ env LD_LIBRARY_PATH=/home/beazley/projects/lib perl
33773 </PRE>
33774 </DIV>
33775 <P> Finally, you can use a command such as <TT>ldconfig</TT> (Linux) or <TT>
33776 crle</TT> (Solaris) to add additional search paths to the default system
33777  configuration (this requires root access and you will need to read the
33778  man pages).</P>
33779 <H3><A name="Perl5_nn9"></A>28.2.6 Compilation problems and compiling
33780  with C++</H3>
33781 <P> Compilation of C++ extensions has traditionally been a tricky
33782  problem. Since the Perl interpreter is written in C, you need to take
33783  steps to make sure C++ is properly initialized and that modules are
33784  compiled correctly.</P>
33785 <P> On most machines, C++ extension modules should be linked using the
33786  C++ compiler. For example:</P>
33787 <DIV class="code">
33788 <PRE>
33789 % swig -c++ -perl example.i
33790 % g++ -c example.cxx
33791 % g++ -c example_wrap.cxx -I/usr/lib/perl5/5.00503/i386-linux/CORE
33792 % <B>g++ -shared example.o example_wrap.o -o example.so</B>
33793 </PRE>
33794 </DIV>
33795 <P> In addition to this, you may need to include additional library
33796  files to make it work. For example, if you are using the Sun C++
33797  compiler on Solaris, you often need to add an extra library <TT>-lCrun</TT>
33798  like this:</P>
33799 <DIV class="code">
33800 <PRE>
33801 % swig -c++ -perl example.i
33802 % g++ -c example.cxx
33803 % g++ -c example_wrap.cxx -I/usr/lib/perl5/5.00503/i386-linux/CORE
33804 % g++ -shared example.o example_wrap.o -o example.so <B>-lCrun</B>
33805 </PRE>
33806 </DIV>
33807 <P> Of course, the names of the extra libraries are completely
33808  non-portable---you will probably need to do some experimentation.</P>
33809 <P> Another possible compile problem comes from recent versions of Perl
33810  (5.8.0) and the GNU tools. If you see errors having to do with
33811  _crypt_struct, that means _GNU_SOURCE is not defined and it needs to
33812  be. So you should compile the wrapper like:</P>
33813 <DIV class="code">
33814 <PRE>
33815 % g++ -c example_wrap.cxx -I/usr/lib/perl/5.8.0/CORE -D_GNU_SOURCE
33816 </PRE>
33817 </DIV>
33818 <P> -D_GNU_SOURCE is also included in the Perl ccflags, which can be
33819  found by running</P>
33820 <DIV class="code">
33821 <PRE>
33822 % perl -e 'use Config; print $Config{ccflags};'
33823 </PRE>
33824 </DIV>
33825 <P> So you could also compile the wrapper like</P>
33826 <DIV class="code">
33827 <PRE>
33828 % g++ -c example_wrap.cxx -I/usr/lib/perl/5.8.0/CORE \
33829 `perl -e 'use Config; print $Config{ccflags}'`
33830 </PRE>
33831 </DIV>
33832 <P> Sometimes people have suggested that it is necessary to relink the
33833  Perl interpreter using the C++ compiler to make C++ extension modules
33834  work. In the experience of this author, this has never actually
33835  appeared to be necessary on most platforms. Relinking the interpreter
33836  with C++ really only includes the special run-time libraries described
33837  above---as long as you link your extension modules with these
33838  libraries, it should not be necessary to rebuild Perl.</P>
33839 <P> If you aren't entirely sure about the linking of a C++ extension,
33840  you might look at an existing C++ program. On many Unix machines, the <TT>
33841 ldd</TT> command will list library dependencies. This should give you
33842  some clues about what you might have to include when you link your
33843  extension module. For example, notice the first line of output here:</P>
33844 <DIV class="code">
33845 <PRE>
33846 $ ldd swig
33847         <B>libstdc++-libc6.1-1.so.2 =&gt; /usr/lib/libstdc++-libc6.1-1.so.2 (0x40019000)</B>
33848         libm.so.6 =&gt; /lib/libm.so.6 (0x4005b000)
33849         libc.so.6 =&gt; /lib/libc.so.6 (0x40077000)
33850         /lib/ld-linux.so.2 =&gt; /lib/ld-linux.so.2 (0x40000000)
33851 $
33852 </PRE>
33853 </DIV>
33854 <P> If linking wasn't enough of a problem, another major complication of
33855  C++ is that it does not define any sort of standard for binary linking
33856  of libraries. This means that C++ code compiled by different compilers
33857  will not link together properly as libraries nor is the memory layout
33858  of classes and data structures implemented in any kind of portable
33859  manner. In a monolithic C++ program, this problem may be unnoticed.
33860  However, in Perl, it is possible for different extension modules to be
33861  compiled with different C++ compilers. As long as these modules are
33862  self-contained, this probably won't matter. However, if these modules
33863  start sharing data, you will need to take steps to avoid segmentation
33864  faults and other erratic program behavior. Also, be aware that certain
33865  C++ features, especially RTTI, can behave strangely when working with
33866  multiple modules.</P>
33867 <P> It should be noted that you may get a lot of error messages about
33868  the `<TT>bool</TT>' datatype when compiling a C++ Perl module. If you
33869  experience this problem, you can try the following :</P>
33870 <UL>
33871 <LI>Use <TT>-DHAS_BOOL</TT> when compiling the SWIG wrapper code</LI>
33872 <LI>Or use <TT>-Dbool=char</TT> when compiling.</LI>
33873 </UL>
33874 <P> Finally, recent versions of Perl (5.8.0) have namespace conflict
33875  problems. Perl defines a bunch of short macros to make the Perl API
33876  function names shorter. For example, in
33877  /usr/lib/perl/5.8.0/CORE/embed.h there is a line:</P>
33878 <DIV class="code">
33879 <PRE>
33880 #define do_open Perl_do_open
33881 </PRE>
33882 </DIV>
33883 <P> The problem is, in the &lt;iostream&gt; header from GNU libstdc++v3 there
33884  is a private function named do_open. If &lt;iostream&gt; is included after
33885  the perl headers, then the Perl macro causes the iostream do_open to be
33886  renamed, which causes compile errors. Hopefully in the future Perl will
33887  support a PERL_NO_SHORT_NAMES flag, but for now the only solution is to
33888  undef the macros that conflict. Lib/perl5/noembed.h in the SWIG source
33889  has a list of macros that are known to conflict with either standard
33890  headers or other headers. But if you get macro type conflicts from
33891  other macros not included in Lib/perl5/noembed.h while compiling the
33892  wrapper, you will have to find the macro that conflicts and add an
33893  #undef into the .i file. Please report any conflicting macros you find
33894  to <A href="http://www.swig.org/mail.html">swig-user mailing list</A>.</P>
33895 <H3><A name="Perl5_nn10"></A>28.2.7 Compiling for 64-bit platforms</H3>
33896 <P> On platforms that support 64-bit applications (Solaris, Irix, etc.),
33897  special care is required when building extension modules. On these
33898  machines, 64-bit applications are compiled and linked using a different
33899  set of compiler/linker options. In addition, it is not generally
33900  possible to mix 32-bit and 64-bit code together in the same
33901  application.</P>
33902 <P> To utilize 64-bits, the Perl executable will need to be recompiled
33903  as a 64-bit application. In addition, all libraries, wrapper code, and
33904  every other part of your application will need to be compiled for
33905  64-bits. If you plan to use other third-party extension modules, they
33906  will also have to be recompiled as 64-bit extensions.</P>
33907 <P> If you are wrapping commercial software for which you have no source
33908  code, you will be forced to use the same linking standard as used by
33909  that software. This may prevent the use of 64-bit extensions. It may
33910  also introduce problems on platforms that support more than one linking
33911  standard (e.g., -o32 and -n32 on Irix).</P>
33912 <H2><A name="Perl5_nn11"></A>28.3 Building Perl Extensions under Windows</H2>
33913 <P> Building a SWIG extension to Perl under Windows is roughly similar
33914  to the process used with Unix. Normally, you will want to produce a DLL
33915  that can be loaded into the Perl interpreter. This section assumes you
33916  are using SWIG with Microsoft Visual C++ although the procedure may be
33917  similar with other compilers.</P>
33918 <H3><A name="Perl5_nn12"></A>28.3.1 Running SWIG from Developer Studio</H3>
33919 <P> If you are developing your application within Microsoft developer
33920  studio, SWIG can be invoked as a custom build option. The process
33921  roughly requires these steps :</P>
33922 <UL>
33923 <LI>Open up a new workspace and use the AppWizard to select a DLL
33924  project.</LI>
33925 <LI>Add both the SWIG interface file (the .i file), any supporting C
33926  files, and the name of the wrapper file that will be created by SWIG
33927  (ie. <TT>example_wrap.c</TT>). Note : If using C++, choose a different
33928  suffix for the wrapper file such as <TT>example_wrap.cxx</TT>. Don't
33929  worry if the wrapper file doesn't exist yet--Developer studio will keep
33930  a reference to it around.</LI>
33931 <LI>Select the SWIG interface file and go to the settings menu. Under
33932  settings, select the &quot;Custom Build&quot; option.</LI>
33933 <LI>Enter &quot;SWIG&quot; in the description field.</LI>
33934 <LI>Enter &quot;<TT>swig -perl5 -o $(ProjDir)\$(InputName)_wrap.cxx
33935  $(InputPath)</TT>&quot; in the &quot;Build command(s) field&quot;</LI>
33936 <LI>Enter &quot;<TT>$(ProjDir)\$(InputName)_wrap.c</TT>xx&quot; in the &quot;Output
33937  files(s) field&quot;.</LI>
33938 <LI>Next, select the settings for the entire project and go to
33939  &quot;C++:Preprocessor&quot;. Add the include directories for your Perl 5
33940  installation under &quot;Additional include directories&quot;.</LI>
33941 <LI>Define the symbols WIN32 and MSWIN32 under preprocessor options. If
33942  using the ActiveWare port, also define the symbol PERL_OBJECT. Note
33943  that all extensions to the ActiveWare port must be compiled with the
33944  C++ compiler since Perl has been encapsulated in a C++ class.</LI>
33945 <LI>Finally, select the settings for the entire project and go to &quot;Link
33946  Options&quot;. Add the Perl library file to your link libraries. For example
33947  &quot;perl.lib&quot;. Also, set the name of the output file to match the name of
33948  your Perl module (ie. example.dll).</LI>
33949 <LI>Build your project.</LI>
33950 </UL>
33951 <P> Now, assuming you made it this far, SWIG will be automatically
33952  invoked when you build your project. Any changes made to the interface
33953  file will result in SWIG being automatically invoked to produce a new
33954  version of the wrapper file. To run your new Perl extension, simply run
33955  Perl and use the use command as normal. For example :</P>
33956 <DIV class="targetlang">
33957 <PRE>
33958 DOS &gt; perl
33959 use example;
33960 $a = example::fact(4);
33961 print &quot;$a\n&quot;;
33962
33963 </PRE>
33964 </DIV>
33965 <H3><A name="Perl5_nn13"></A>28.3.2 Using other compilers</H3>
33966 <P> SWIG is known to work with Cygwin and may work with other compilers
33967  on Windows. For general hints and suggestions refer to the <A href="#Windows">
33968 Windows</A> chapter.</P>
33969 <H2><A name="Perl5_nn14"></A>28.4 The low-level interface</H2>
33970 <P> At its core, the Perl module uses a simple low-level interface to C
33971  function, variables, constants, and classes. This low-level interface
33972  can be used to control your application. However, it is also used to
33973  construct more user-friendly proxy classes as described in the next
33974  section.</P>
33975 <H3><A name="Perl5_nn15"></A>28.4.1 Functions</H3>
33976 <P> C functions are converted into new Perl built-in commands (or
33977  subroutines). For example:</P>
33978 <DIV class="targetlang">
33979 <PRE>
33980 %module example
33981 int fact(int a);
33982 ...
33983 </PRE>
33984 </DIV>
33985 <P> Now, in Perl:</P>
33986 <DIV class="targetlang">
33987 <PRE>
33988 use example;
33989 $a = &amp;example::fact(2);
33990 </PRE>
33991 </DIV>
33992 <H3><A name="Perl5_nn16"></A>28.4.2 Global variables</H3>
33993 <P> Global variables are handled using Perl's magic variable mechanism.
33994  SWIG generates a pair of functions that intercept read/write operations
33995  and attaches them to a Perl variable with the same name as the C global
33996  variable. Thus, an interface like this</P>
33997 <DIV class="targetlang">
33998 <PRE>
33999 %module example;
34000 ...
34001 double Spam;
34002 ...
34003 </PRE>
34004 </DIV>
34005 <P> is accessed as follows :</P>
34006 <DIV class="targetlang">
34007 <PRE>
34008 use example;
34009 print $example::Spam,&quot;\n&quot;;
34010 $example::Spam = $example::Spam + 4
34011 # ... etc ...
34012
34013 </PRE>
34014 </DIV>
34015 <P> If a variable is declared as <TT>const</TT>, it is wrapped as a
34016  read-only variable. Attempts to modify its value will result in an
34017  error.</P>
34018 <P> To make ordinary variables read-only, you can also use the <TT>
34019 %immutable</TT> directive. For example:</P>
34020 <DIV class="code">
34021 <PRE>
34022 %{
34023 extern char *path;
34024 %}
34025 %immutable;
34026 extern char *path;
34027 %mutable;
34028 </PRE>
34029 </DIV>
34030 <P> The <TT>%immutable</TT> directive stays in effect until it is
34031  explicitly disabled or cleared using <TT>%mutable</TT>. See the <A href="#SWIG_readonly_variables">
34032 Creating read-only variables</A> section for further details.</P>
34033 <P> It is also possible to tag a specific variable as read-only like
34034  this:</P>
34035 <DIV class="code">
34036 <PRE>
34037 %{
34038 extern char *path;
34039 %}
34040 %immutable path; 
34041 ...
34042 ...
34043 extern char *path;       // Declared later in the input
34044 </PRE>
34045 </DIV>
34046 <H3><A name="Perl5_nn17"></A>28.4.3 Constants</H3>
34047 <P> By default, constants are wrapped as read-only Perl variables. For
34048  example:</P>
34049 <DIV class="code">
34050 <PRE>
34051 %module example
34052
34053 #define FOO 42
34054 </PRE>
34055 </DIV>
34056 <P> In Perl:</P>
34057 <DIV class="targetlang">
34058 <PRE>
34059 use example;
34060 print $example::FOO,&quot;\n&quot;;    # OK
34061 $example::FOO = 2;           # Error
34062 </PRE>
34063 </DIV>
34064 <P> Alternatively, if you use swig's <TT>-const</TT> option, constants
34065  are wrapped such that the leading $ isn't required (by using a constant
34066  subroutine), which usually gives a more natural Perl interface, for
34067  example:</P>
34068 <DIV class="targetlang">
34069 <PRE>
34070 use example;
34071 print example::FOO,&quot;\n&quot;;
34072 </PRE>
34073 </DIV>
34074 <H3><A name="Perl5_nn18"></A>28.4.4 Pointers</H3>
34075 <P> SWIG represents pointers as blessed references. A blessed reference
34076  is the same as a Perl reference except that it has additional
34077  information attached to it indicating what kind of reference it is.
34078  That is, if you have a C declaration like this :</P>
34079 <DIV class="code">
34080 <PRE>
34081 Matrix *new_Matrix(int n, int m);
34082 </PRE>
34083 </DIV>
34084 <P> The module returns a value generated as follows:</P>
34085 <DIV class="targetlang">
34086 <PRE>
34087 $ptr = new_Matrix(int n, int m);     # Save pointer return result
34088 bless $ptr, &quot;p_Matrix&quot;;              # Bless it as a pointer to Matrix
34089 </PRE>
34090 </DIV>
34091 <P> SWIG uses the &quot;blessing&quot; to check the datatype of various pointers.
34092  In the event of a mismatch, an error or warning message is generated.</P>
34093 <P> To check to see if a value is the NULL pointer, use the <TT>
34094 defined()</TT> command :</P>
34095 <DIV class="targetlang">
34096 <PRE>
34097 if (defined($ptr)) {
34098         print &quot;Not a NULL pointer.&quot;;
34099 } else {
34100         print &quot;Is a NULL pointer.&quot;;
34101 }
34102
34103 </PRE>
34104 </DIV>
34105 <P> To create a NULL pointer, you should pass the <TT>undef</TT> value
34106  to a function.</P>
34107 <P> The &quot;value&quot; of a Perl reference is not the same as the underlying C
34108  pointer that SWIG wrapper functions return. Suppose that <TT>$a</TT>
34109  and <TT>$b</TT> are two references that point to the same C object. In
34110  general, <TT>$a</TT> and <TT>$b</TT> will be different--since they are
34111  different references. Thus, it is a mistake to check the equality of <TT>
34112 $a</TT> and <TT>$b</TT> to check the equality of two C pointers. The
34113  correct method to check equality of C pointers is to dereference them
34114  as follows :</P>
34115 <DIV class="targetlang">
34116 <PRE>
34117 if ($$a == $$b) {
34118         print &quot;a and b point to the same thing in C&quot;;
34119 } else {
34120         print &quot;a and b point to different objects.&quot;;
34121 }
34122
34123 </PRE>
34124 </DIV>
34125 <P> As much as you might be inclined to modify a pointer value directly
34126  from Perl, don't. Manipulating pointer values is architecture dependent
34127  and could cause your program to crash. Similarly, don't try to manually
34128  cast a pointer to a new type by reblessing a pointer. This may not work
34129  like you expect and it is particularly dangerous when casting C++
34130  objects. If you need to cast a pointer or change its value, consider
34131  writing some helper functions instead. For example:</P>
34132 <DIV class="code">
34133 <PRE>
34134 %inline %{
34135 /* C-style cast */
34136 Bar *FooToBar(Foo *f) {
34137    return (Bar *) f;
34138 }
34139
34140 /* C++-style cast */
34141 Foo *BarToFoo(Bar *b) {
34142    return dynamic_cast&lt;Foo*&gt;(b);
34143 }
34144
34145 Foo *IncrFoo(Foo *f, int i) {
34146     return f+i;
34147 }
34148 %}
34149 </PRE>
34150 </DIV>
34151 <P> Also, if working with C++, you should always try to use the new C++
34152  style casts. For example, in the above code, the C-style cast may
34153  return a bogus result whereas as the C++-style cast will return <TT>
34154 NULL</TT> if the conversion can't be performed.</P>
34155 <P><B> Compatibility Note:</B> In earlier versions, SWIG tried to
34156  preserve the same pointer naming conventions as XS and <TT>xsubpp</TT>.
34157  Given the advancement of the SWIG typesystem and the growing
34158  differences between SWIG and XS, this is no longer supported.</P>
34159 <H3><A name="Perl5_nn19"></A>28.4.5 Structures</H3>
34160 <P> Access to the contents of a structure are provided through a set of
34161  low-level accessor functions as described in the &quot;SWIG Basics&quot; chapter.
34162  For example,</P>
34163 <DIV class="code">
34164 <PRE>
34165 struct Vector {
34166         double x,y,z;
34167 };
34168 </PRE>
34169 </DIV>
34170 <P> gets mapped into the following collection of accessor functions:</P>
34171 <DIV class="code">
34172 <PRE>
34173 struct Vector *new_Vector();
34174 void           delete_Vector(Vector *v);
34175 double         Vector_x_get(Vector *obj)
34176 void           Vector_x_set(Vector *obj, double x)
34177 double         Vector_y_get(Vector *obj)
34178 void           Vector_y_set(Vector *obj, double y)
34179 double         Vector_z_get(Vector *obj)
34180 void           Vector_z_set(Vector *obj, double z)
34181
34182 </PRE>
34183 </DIV>
34184 <P> These functions are then used to access structure data from Perl as
34185  follows:</P>
34186 <DIV class="targetlang">
34187 <PRE>
34188 $v = example::new_Vector();
34189 print example::Vector_x_get($v),&quot;\n&quot;;    # Get x component
34190 example::Vector_x_set($v,7.8);          # Change x component
34191 </PRE>
34192 </DIV>
34193 <P> Similar access is provided for unions and the data members of C++
34194  classes.</P>
34195 <P> <TT>const</TT> members of a structure are read-only. Data members
34196  can also be forced to be read-only using the <TT>%immutable</TT>
34197  directive. For example:</P>
34198 <DIV class="code">
34199 <PRE>
34200 struct Foo {
34201    ...
34202    %immutable;
34203    int x;        /* Read-only members */
34204    char *name;
34205    %mutable;
34206    ...
34207 };
34208 </PRE>
34209 </DIV>
34210 <P> When <TT>char *</TT> members of a structure are wrapped, the
34211  contents are assumed to be dynamically allocated using <TT>malloc</TT>
34212  or <TT>new</TT> (depending on whether or not SWIG is run with the -c++
34213  option). When the structure member is set, the old contents will be
34214  released and a new value created. If this is not the behavior you want,
34215  you will have to use a typemap (described later).</P>
34216 <P> Array members are normally wrapped as read-only. For example,</P>
34217 <DIV class="code">
34218 <PRE>
34219 struct Foo {
34220    int  x[50];
34221 };
34222 </PRE>
34223 </DIV>
34224 <P> produces a single accessor function like this:</P>
34225 <DIV class="code">
34226 <PRE>
34227 int *Foo_x_get(Foo *self) {
34228     return self-&gt;x;
34229 };
34230 </PRE>
34231 </DIV>
34232 <P> If you want to set an array member, you will need to supply a
34233  &quot;memberin&quot; typemap described later in this chapter. As a special case,
34234  SWIG does generate code to set array members of type <TT>char</TT>
34235  (allowing you to store a Python string in the structure).</P>
34236 <P> When structure members are wrapped, they are handled as pointers.
34237  For example,</P>
34238 <DIV class="code">
34239 <PRE>
34240 struct Foo {
34241    ...
34242 };
34243
34244 struct Bar {
34245    Foo f;
34246 };
34247 </PRE>
34248 </DIV>
34249 <P> generates accessor functions such as this:</P>
34250 <DIV class="code">
34251 <PRE>
34252 Foo *Bar_f_get(Bar *b) {
34253     return &amp;b-&gt;f;
34254 }
34255
34256 void Bar_f_set(Bar *b, Foo *val) {
34257     b-&gt;f = *val;
34258 }
34259 </PRE>
34260 </DIV>
34261 <H3><A name="Perl5_nn20"></A>28.4.6 C++ classes</H3>
34262 <P> C++ classes are wrapped by building a set of low level accessor
34263  functions. Consider the following class :</P>
34264 <DIV class="code">
34265 <PRE>
34266 class List {
34267 public:
34268   List();
34269   ~List();
34270   int  search(char *item);
34271   void insert(char *item);
34272   void remove(char *item);
34273   char *get(int n);
34274   int  length;
34275 static void print(List *l);
34276 };
34277 </PRE>
34278 </DIV>
34279 <P> When wrapped by SWIG, the following functions are created :</P>
34280 <DIV class="code">
34281 <PRE>
34282 List    *new_List();
34283 void     delete_List(List *l);
34284 int      List_search(List *l, char *item);
34285 void     List_insert(List *l, char *item);
34286 void     List_remove(List *l, char *item);
34287 char    *List_get(List *l, int n);
34288 int      List_length_get(List *l);
34289 void     List_length_set(List *l, int n);
34290 void     List_print(List *l);
34291
34292 </PRE>
34293 </DIV>
34294 <P> In Perl, these functions are used in a straightforward manner:</P>
34295 <DIV class="targetlang">
34296 <PRE>
34297 use example;
34298 $l = example::new_List();
34299 example::List_insert($l,&quot;Ale&quot;);
34300 example::List_insert($l,&quot;Stout&quot;);
34301 example::List_insert($l,&quot;Lager&quot;)
34302 example::List_print($l)
34303 Lager
34304 Stout
34305 Ale
34306 print example::List_length_get($l),&quot;\n&quot;;
34307 3
34308 </PRE>
34309 </DIV>
34310 <P> At this low level, C++ objects are really just typed pointers.
34311  Member functions are accessed by calling a C-like wrapper with an
34312  instance pointer as the first argument. Although this interface is
34313  fairly primitive, it provides direct access to C++ objects. A higher
34314  level interface using Perl proxy classes can be built using these
34315  low-level accessors. This is described shortly.</P>
34316 <H3><A name="Perl5_nn21"></A>28.4.7 C++ classes and type-checking</H3>
34317 <P> The SWIG type-checker is fully aware of C++ inheritance. Therefore,
34318  if you have classes like this</P>
34319 <DIV class="code">
34320 <PRE>
34321 class Foo {
34322 ...
34323 };
34324
34325 class Bar : public Foo {
34326 ...
34327 };
34328 </PRE>
34329 </DIV>
34330 <P> and a function</P>
34331 <DIV class="code">
34332 <PRE>
34333 void spam(Foo *f);
34334 </PRE>
34335 </DIV>
34336 <P> then the function <TT>spam()</TT> accepts <TT>Foo *</TT> or a
34337  pointer to any class derived from <TT>Foo</TT>. If necessary, the
34338  type-checker also adjusts the value of the pointer (as is necessary
34339  when multiple inheritance is used).</P>
34340 <H3><A name="Perl5_nn22"></A>28.4.8 C++ overloaded functions</H3>
34341 <P> If you have a C++ program with overloaded functions or methods, you
34342  will need to disambiguate those methods using <TT>%rename</TT>. For
34343  example:</P>
34344 <DIV class="code">
34345 <PRE>
34346 /* Forward renaming declarations */
34347 %rename(foo_i) foo(int); 
34348 %rename(foo_d) foo(double);
34349 ...
34350 void foo(int);           // Becomes 'foo_i'
34351 void foo(char *c);       // Stays 'foo' (not renamed)
34352
34353 class Spam {
34354 public:
34355    void foo(int);      // Becomes 'foo_i'
34356    void foo(double);   // Becomes 'foo_d'
34357    ...
34358 };
34359 </PRE>
34360 </DIV>
34361 <P> Now, in Perl, the methods are accessed as follows:</P>
34362 <DIV class="targetlang">
34363 <PRE>
34364 use example;
34365 example::foo_i(3);
34366 $s = example::new_Spam();
34367 example::Spam_foo_i($s,3);
34368 example::Spam_foo_d($s,3.14);
34369 </PRE>
34370 </DIV>
34371 <P> Please refer to the &quot;SWIG Basics&quot; chapter for more information.</P>
34372 <H3><A name="Perl5_nn23"></A>28.4.9 Operators</H3>
34373 <P> As of version 1.3.27 SWIG automatically renames the most common C++
34374  operators, and maps them into the perl module with the proper 'use
34375  overload ...' so you don't need to do any work.</P>
34376 <P> The following C++ operators are currently supported by the Perl
34377  module:</P>
34378 <UL>
34379 <LI>operator++</LI>
34380 <LI>operator--</LI>
34381 <LI>operator+</LI>
34382 <LI>operator-</LI>
34383 <LI>operator*</LI>
34384 <LI>operator/</LI>
34385 <LI>operator==</LI>
34386 <LI>operator!=</LI>
34387 <LI>operator%</LI>
34388 <LI>operator&gt;</LI>
34389 <LI>operator&lt;</LI>
34390 <LI>operator and</LI>
34391 <LI>operator or</LI>
34392 </UL>
34393 <H3><A name="Perl5_nn24"></A>28.4.10 Modules and packages</H3>
34394 <P> When you create a SWIG extension, everything gets placed into a
34395  single Perl module. The name of the module is determined by the <TT>
34396 %module</TT> directive. To use the module, do the following :</P>
34397 <DIV class="targetlang">
34398 <PRE>
34399 % perl5
34400 use example;                      # load the example module
34401 print example::fact(4),&quot;\n&quot;       # Call a function in it
34402 24
34403 </PRE>
34404 </DIV>
34405 <P> Usually, a module consists of a collection of code that is contained
34406  within a single file. A package, on the other hand, is the Perl
34407  equivalent of a namespace. A package is a lot like a module, except
34408  that it is independent of files. Any number of files may be part of the
34409  same package--or a package may be broken up into a collection of
34410  modules if you prefer to think about it in this way.</P>
34411 <P> SWIG installs its functions into a package with the same name as the
34412  module.</P>
34413 <P><B> Incompatible Change:</B> previous versions of SWIG enabled you to
34414  change the name of the package by using the -package option, this
34415  feature has been removed in order to properly support modules that used
34416  nested namespaces, e.g. Foo::Bar::Baz. To give your module a nested
34417  namespace simply provide the fully qualified name in your %module
34418  directive:</P>
34419 <DIV class="code">
34420 <PRE>
34421 %module &quot;Foo::Bar::Baz&quot;
34422 </PRE>
34423 </DIV>
34424 <P><B> NOTE:</B> the double quotes are necessary.</P>
34425 <P> Using the <TT>package</TT> option of the <TT>%module</TT> directive
34426  allows you to specify what Perl namespace that the module will be
34427  living in when installed. This is useful in the situation where a
34428  module maintainer wants to split a large module into smaller pieces to
34429  make maintenance easier, but doesn't want to have that affect the
34430  module name used by applications. So for example, if I wanted to split <TT>
34431 XML::Xerces</TT> into <TT>XML::Xerces::SAX</TT>, etc. , but I wanted all
34432  the applications to be able to access the classes using the <TT>
34433 XML::Xerces</TT> namespace I could use:</P>
34434 <DIV class="code">
34435 <PRE>
34436 %module(package=&quot;XML::Xerces&quot;) &quot;XML::Xerces::SAX
34437 </PRE>
34438 </DIV>
34439 <P> And now all the applications could use the class <TT>
34440 XML::Xerces::SAXParser</TT>. Without the <TT>package</TT> directive
34441  splitting the module would force applications to use the class <TT>
34442 XML::Xerces::SAX::SAXParser</TT>. This could break compatibility for
34443  existing applications that are already using the class under the name <TT>
34444 XML::Xerces::SAXParser</TT>.</P>
34445
34446 <!--
34447 &lt;p&gt;
34448 This can be changed by giving SWIG the -package
34449 option :
34450 &lt;/p&gt;
34451
34452 &lt;div class=&quot;code&quot;&gt;&lt;pre&gt;
34453 % swig -perl -package Foo example.i
34454 &lt;/pre&gt;&lt;/div&gt;
34455
34456 &lt;p&gt;
34457 In this case, you still create a module called `&lt;tt&gt;example&lt;/tt&gt;' exactly as before, but
34458 all of the functions in that module will be installed into the package
34459 `&lt;tt&gt;Foo&lt;/tt&gt;.' For example :
34460 &lt;/p&gt;
34461
34462 &lt;div class=&quot;targetlang&quot;&gt;&lt;pre&gt;
34463 use example;   # Load the module like before
34464 print Foo::fact(4),&quot;\n&quot;;        # Call a function in package FooBar
34465 &lt;/pre&gt;&lt;/div&gt;
34466 -->
34467 <H2><A name="Perl5_nn25"></A>28.5 Input and output parameters</H2>
34468 <P> A common problem in some C programs is handling parameters passed as
34469  simple pointers. For example:</P>
34470 <DIV class="code">
34471 <PRE>
34472 void add(int x, int y, int *result) {
34473    *result = x + y;
34474 }
34475 </PRE>
34476 </DIV>
34477 <P> or perhaps</P>
34478 <DIV class="code">
34479 <PRE>
34480 int sub(int *x, int *y) {
34481    return *x+*y;
34482 }
34483 </PRE>
34484 </DIV>
34485 <P> The easiest way to handle these situations is to use the <TT>
34486 typemaps.i</TT> file. For example:</P>
34487 <DIV class="code">
34488 <PRE>
34489 %module example
34490 %include &quot;typemaps.i&quot;
34491
34492 void add(int, int, int *OUTPUT);
34493 int  sub(int *INPUT, int *INPUT);
34494 </PRE>
34495 </DIV>
34496 <P> In Perl, this allows you to pass simple values. For example:</P>
34497 <DIV class="targetlang">
34498 <PRE>
34499 $a = example::add(3,4);
34500 print &quot;$a\n&quot;;
34501 7
34502 $b = example::sub(7,4);
34503 print &quot;$b\n&quot;;
34504 3
34505 </PRE>
34506 </DIV>
34507 <P> Notice how the <TT>INPUT</TT> parameters allow integer values to be
34508  passed instead of pointers and how the <TT>OUTPUT</TT> parameter
34509  creates a return result.</P>
34510 <P> If you don't want to use the names <TT>INPUT</TT> or <TT>OUTPUT</TT>
34511 , use the <TT>%apply</TT> directive. For example:</P>
34512 <DIV class="code">
34513 <PRE>
34514 %module example
34515 %include &quot;typemaps.i&quot;
34516
34517 %apply int *OUTPUT { int *result };
34518 %apply int *INPUT  { int *x, int *y};
34519
34520 void add(int x, int y, int *result);
34521 int  sub(int *x, int *y);
34522 </PRE>
34523 </DIV>
34524 <P> If a function mutates one of its parameters like this,</P>
34525 <DIV class="code">
34526 <PRE>
34527 void negate(int *x) {
34528    *x = -(*x);
34529 }
34530 </PRE>
34531 </DIV>
34532 <P> you can use <TT>INOUT</TT> like this:</P>
34533 <DIV class="code">
34534 <PRE>
34535 %include &quot;typemaps.i&quot;
34536 ...
34537 void negate(int *INOUT);
34538 </PRE>
34539 </DIV>
34540 <P> In Perl, a mutated parameter shows up as a return value. For
34541  example:</P>
34542 <DIV class="targetlang">
34543 <PRE>
34544 $a = example::negate(3);
34545 print &quot;$a\n&quot;;
34546 -3
34547 </PRE>
34548 </DIV>
34549 <P> The most common use of these special typemap rules is to handle
34550  functions that return more than one value. For example, sometimes a
34551  function returns a result as well as a special error code:</P>
34552 <DIV class="code">
34553 <PRE>
34554 /* send message, return number of bytes sent, along with success code */
34555 int send_message(char *text, int len, int *success);
34556 </PRE>
34557 </DIV>
34558 <P> To wrap such a function, simply use the <TT>OUTPUT</TT> rule above.
34559  For example:</P>
34560 <DIV class="code">
34561 <PRE>
34562 %module example
34563 %include &quot;typemaps.i&quot;
34564 %apply int *OUTPUT { int *success };
34565 ...
34566 int send_message(char *text, int *success);
34567 </PRE>
34568 </DIV>
34569 <P> When used in Perl, the function will return multiple values.</P>
34570 <DIV class="targetlang">
34571 <PRE>
34572 ($bytes, $success) = example::send_message(&quot;Hello World&quot;);
34573 </PRE>
34574 </DIV>
34575 <P> Another common use of multiple return values are in query functions.
34576  For example:</P>
34577 <DIV class="code">
34578 <PRE>
34579 void get_dimensions(Matrix *m, int *rows, int *columns);
34580 </PRE>
34581 </DIV>
34582 <P> To wrap this, you might use the following:</P>
34583 <DIV class="code">
34584 <PRE>
34585 %module example
34586 %include &quot;typemaps.i&quot;
34587 %apply int *OUTPUT { int *rows, int *columns };
34588 ...
34589 void get_dimensions(Matrix *m, int *rows, *columns);
34590 </PRE>
34591 </DIV>
34592 <P> Now, in Perl:</P>
34593 <DIV class="targetlang">
34594 <PRE>
34595 ($r,$c) = example::get_dimensions($m);
34596 </PRE>
34597 </DIV>
34598 <P> In certain cases, it is possible to treat Perl references as C
34599  pointers. To do this, use the <TT>REFERENCE</TT> typemap. For example:</P>
34600 <DIV class="code">
34601 <PRE>
34602 %module example
34603 %include &quot;typemaps.i&quot;
34604
34605 void add(int x, int y, int *REFERENCE);
34606 </PRE>
34607 </DIV>
34608 <P> In Perl:</P>
34609 <DIV class="targetlang">
34610 <PRE>
34611 use example;
34612 $c = 0.0;
34613 example::add(3,4,\$c);
34614 print &quot;$c\n&quot;;
34615 7
34616 </PRE>
34617 </DIV>
34618 <P><B> Note:</B> The <TT>REFERENCE</TT> feature is only currently
34619  supported for numeric types (integers and floating point).</P>
34620 <H2><A name="Perl5_nn26"></A>28.6 Exception handling</H2>
34621 <P> The SWIG <TT>%exception</TT> directive can be used to create a
34622  user-definable exception handler for converting exceptions in your
34623  C/C++ program into Perl exceptions. The chapter on customization
34624  features contains more details, but suppose you have a C++ class like
34625  the following :</P>
34626 <DIV class="code">
34627 <PRE>
34628 class RangeError {};   // Used for an exception
34629
34630 class DoubleArray {
34631   private:
34632     int n;
34633     double *ptr;
34634   public:
34635     // Create a new array of fixed size
34636     DoubleArray(int size) {
34637       ptr = new double[size];
34638       n = size;
34639     }
34640     // Destroy an array
34641     ~DoubleArray() {
34642        delete ptr;
34643     }
34644     // Return the length of the array
34645     int   length() {
34646       return n;
34647     }
34648
34649     // Get an item from the array and perform bounds checking.
34650     double getitem(int i) {
34651       if ((i &gt;= 0) &amp;&amp; (i &lt; n))
34652         return ptr[i];
34653       else
34654         throw RangeError();
34655     }
34656
34657     // Set an item in the array and perform bounds checking.
34658     void setitem(int i, double val) {
34659       if ((i &gt;= 0) &amp;&amp; (i &lt; n))
34660         ptr[i] = val;
34661       else {
34662         throw RangeError();
34663       }
34664     }
34665   };
34666 </PRE>
34667 </DIV>
34668 <P> Since several methods in this class can throw an exception for an
34669  out-of-bounds access, you might want to catch this in the Perl
34670  extension by writing the following in an interface file:</P>
34671 <DIV class="code">
34672 <PRE>
34673 %exception {
34674   try {
34675     $action
34676   }
34677   catch (RangeError) {
34678     croak(&quot;Array index out-of-bounds&quot;);
34679   }
34680 }
34681
34682 class DoubleArray {
34683 ...
34684 };
34685 </PRE>
34686 </DIV>
34687 <P> The exception handling code is inserted directly into generated
34688  wrapper functions. The <TT>$action</TT> variable is replaced with the
34689  C/C++ code being executed by the wrapper. When an exception handler is
34690  defined, errors can be caught and used to gracefully generate a Perl
34691  error instead of forcing the entire program to terminate with an
34692  uncaught error.</P>
34693 <P> As shown, the exception handling code will be added to every wrapper
34694  function. Since this is somewhat inefficient. You might consider
34695  refining the exception handler to only apply to specific methods like
34696  this:</P>
34697 <DIV class="code">
34698 <PRE>
34699 %exception getitem {
34700   try {
34701     $action
34702   }
34703   catch (RangeError) {
34704     croak(&quot;Array index out-of-bounds&quot;);
34705   }
34706 }
34707
34708 %exception setitem {
34709   try {
34710     $action
34711   }
34712   catch (RangeError) {
34713     croak(&quot;Array index out-of-bounds&quot;);
34714   }
34715 }
34716 </PRE>
34717 </DIV>
34718 <P> In this case, the exception handler is only attached to methods and
34719  functions named <TT>getitem</TT> and <TT>setitem</TT>.</P>
34720 <P> If you had a lot of different methods, you can avoid extra typing by
34721  using a macro. For example:</P>
34722 <DIV class="code">
34723 <PRE>
34724 %define RANGE_ERROR
34725 {
34726   try {
34727     $action
34728   }
34729   catch (RangeError) {
34730     croak(&quot;Array index out-of-bounds&quot;);
34731   }
34732 }
34733 %enddef
34734
34735 %exception getitem RANGE_ERROR;
34736 %exception setitem RANGE_ERROR;
34737 </PRE>
34738 </DIV>
34739 <P> Since SWIG's exception handling is user-definable, you are not
34740  limited to C++ exception handling. See the chapter on &quot;<A href="#Customization">
34741 Customization features</A>&quot; for more examples.</P>
34742 <P><B> Compatibility note:</B> In SWIG1.1, exceptions were defined using
34743  the older <TT>%except</TT> directive:</P>
34744 <DIV class="code">
34745 <PRE>
34746 %except(python) {
34747   try {
34748     $function
34749   }
34750   catch (RangeError) {
34751     croak(&quot;Array index out-of-bounds&quot;);
34752   }
34753 }
34754 </PRE>
34755 </DIV>
34756 <P> This is still supported, but it is deprecated. The newer <TT>
34757 %exception</TT> directive provides the same functionality, but it has
34758  additional capabilities that make it more powerful.</P>
34759 <H2><A name="Perl5_nn27"></A>28.7 Remapping datatypes with typemaps</H2>
34760 <P> This section describes how you can modify SWIG's default wrapping
34761  behavior for various C/C++ datatypes using the <TT>%typemap</TT>
34762  directive. This is an advanced topic that assumes familiarity with the
34763  Perl C API as well as the material in the &quot;<A href="#Typemaps">Typemaps</A>
34764 &quot; chapter.</P>
34765 <P> Before proceeding, it should be stressed that typemaps are<EM> not</EM>
34766  a required part of using SWIG---the default wrapping behavior is enough
34767  in most cases. Typemaps are only used if you want to change some aspect
34768  of the primitive C-Perl interface.</P>
34769 <H3><A name="Perl5_nn28"></A>28.7.1 A simple typemap example</H3>
34770 <P> A typemap is nothing more than a code generation rule that is
34771  attached to a specific C datatype. For example, to convert integers
34772  from Perl to C, you might define a typemap like this:</P>
34773 <DIV class="code">
34774 <PRE>
34775 %module example
34776
34777 %typemap(in) int {
34778         $1 = (int) SvIV($input);
34779         printf(&quot;Received an integer : %d\n&quot;, $1);
34780 }
34781 ...
34782 %inline %{
34783 extern int fact(int n);
34784 %}
34785
34786 </PRE>
34787 </DIV>
34788 <P> Typemaps are always associated with some specific aspect of code
34789  generation. In this case, the &quot;in&quot; method refers to the conversion of
34790  input arguments to C/C++. The datatype <TT>int</TT> is the datatype to
34791  which the typemap will be applied. The supplied C code is used to
34792  convert values. In this code a number of special variable prefaced by a
34793  <TT>$</TT> are used. The <TT>$1</TT> variable is placeholder for a
34794  local variable of type <TT>int</TT>. The <TT>$input</TT> variable is
34795  the input object (usually a <TT>SV *</TT>).</P>
34796 <P> When this example is used in Perl5, it will operate as follows :</P>
34797 <DIV class="targetlang">
34798 <PRE>
34799 use example;
34800 $n = example::fact(6);
34801 print &quot;$n\n&quot;;
34802 ...
34803
34804 Output :
34805 Received an integer : 6
34806 720
34807 </PRE>
34808 </DIV>
34809 <P> The application of a typemap to specific datatypes and argument
34810  names involves more than simple text-matching--typemaps are fully
34811  integrated into the SWIG type-system. When you define a typemap for <TT>
34812 int</TT>, that typemap applies to <TT>int</TT> and qualified variations
34813  such as <TT>const int</TT>. In addition, the typemap system follows <TT>
34814 typedef</TT> declarations. For example:</P>
34815 <DIV class="targetlang">
34816 <PRE>
34817 %typemap(in) int n {
34818         $1 = (int) SvIV($input);
34819         printf(&quot;n = %d\n&quot;,$1);
34820 }
34821 %inline %{
34822 typedef int Integer;
34823 extern int fact(Integer n);    // Above typemap is applied
34824 %}
34825 </PRE>
34826 </DIV>
34827 <P> It should be noted that the matching of <TT>typedef</TT> only occurs
34828  in one direction. If you defined a typemap for <TT>Integer</TT>, it is
34829  not applied to arguments of type <TT>int</TT>.</P>
34830 <P> Typemaps can also be defined for groups of consecutive arguments.
34831  For example:</P>
34832 <DIV class="targetlang">
34833 <PRE>
34834 %typemap(in) (char *str, unsigned len) {
34835     $1 = SvPV($input,$2);
34836 };
34837
34838 int count(char c, char *str, unsigned len);
34839 </PRE>
34840 </DIV>
34841 <P> When a multi-argument typemap is defined, the arguments are always
34842  handled as a single Perl object. This allows the function to be used
34843  like this (notice how the length parameter is omitted):</P>
34844 <DIV class="targetlang">
34845 <PRE>
34846 example::count(&quot;e&quot;,&quot;Hello World&quot;);
34847 1
34848 &gt;&gt;&gt;
34849 </PRE>
34850 </DIV>
34851 <H3><A name="Perl5_nn29"></A>28.7.2 Perl5 typemaps</H3>
34852 <P> The previous section illustrated an &quot;in&quot; typemap for converting Perl
34853  objects to C. A variety of different typemap methods are defined by the
34854  Perl module. For example, to convert a C integer back into a Perl
34855  object, you might define an &quot;out&quot; typemap like this:</P>
34856 <DIV class="targetlang">
34857 <PRE>
34858 %typemap(out) int {
34859     $result = sv_newmortal();
34860     set_setiv($result, (IV) $1);
34861     argvi++;
34862 }
34863 </PRE>
34864 </DIV>
34865 <P> The following typemap methods are available:</P>
34866 <P> <TT>%typemap(in)</TT></P>
34867 <DIV class="indent"> Converts Perl5 object to input function arguments.</DIV>
34868 <P> <TT>%typemap(out)</TT></P>
34869 <DIV class="indent"> Converts function return value to a Perl5 value.</DIV>
34870 <P> <TT>%typemap(varin)</TT></P>
34871 <DIV class="indent"> Converts a Perl5 object to a global variable.</DIV>
34872 <P> <TT>%typemap(varout)</TT></P>
34873 <DIV class="indent"> Converts a global variable to a Perl5 object.</DIV>
34874 <P> <TT>%typemap(freearg)</TT></P>
34875 <DIV class="indent"> Cleans up a function argument after a function call</DIV>
34876 <P> <TT>%typemap(argout)</TT></P>
34877 <DIV class="indent"> Output argument handling</DIV>
34878 <P> <TT>%typemap(ret)</TT></P>
34879 <DIV class="indent"> Clean up return value from a function.</DIV>
34880 <P> <TT>%typemap(memberin)</TT></P>
34881 <DIV class="indent"> Setting of C++ member data (all languages).</DIV>
34882 <P> <TT>%typemap(memberout)</TT></P>
34883 <DIV class="indent"> Return of C++ member data (all languages).</DIV>
34884 <P> <TT>%typemap(check)</TT></P>
34885 <DIV class="indent"> Check value of input parameter.</DIV>
34886 <H3><A name="Perl5_nn30"></A>28.7.3 Typemap variables</H3>
34887 <P> Within typemap code, a number of special variables prefaced with a <TT>
34888 $</TT> may appear. A full list of variables can be found in the &quot;<A href="#Typemaps">
34889 Typemaps</A>&quot; chapter. This is a list of the most common variables:</P>
34890 <P> <TT>$1</TT></P>
34891 <DIV class="indent"> A C local variable corresponding to the actual type
34892  specified in the <TT>%typemap</TT> directive. For input values, this is
34893  a C local variable that's supposed to hold an argument value. For
34894  output values, this is the raw result that's supposed to be returned to
34895  Perl.</DIV>
34896 <P> <TT>$input</TT></P>
34897 <DIV class="indent"> A Perl object holding the value of an argument of
34898  variable value.</DIV>
34899 <P> <TT>$result</TT></P>
34900 <DIV class="indent"> A Perl object that holds the result to be returned
34901  to Perl.</DIV>
34902 <P> <TT>$1_name</TT></P>
34903 <DIV class="indent"> The parameter name that was matched.</DIV>
34904 <P> <TT>$1_type</TT></P>
34905 <DIV class="indent"> The actual C datatype matched by the typemap.</DIV>
34906 <P> <TT>$1_ltype</TT></P>
34907 <DIV class="indent"> An assignable version of the datatype matched by
34908  the typemap (a type that can appear on the left-hand-side of a C
34909  assignment operation). This type is stripped of qualifiers and may be
34910  an altered version of <TT>$1_type</TT>. All arguments and local
34911  variables in wrapper functions are declared using this type so that
34912  their values can be properly assigned.</DIV>
34913 <P> <TT>$symname</TT></P>
34914 <DIV class="indent"> The Perl name of the wrapper function being
34915  created.</DIV>
34916 <H3><A name="Perl5_nn31"></A>28.7.4 Useful functions</H3>
34917 <P> When writing typemaps, it is necessary to work directly with Perl5
34918  objects. This, unfortunately, can be a daunting task. Consult the
34919  &quot;perlguts&quot; man-page for all of the really ugly details. A short summary
34920  of commonly used functions is provided here for reference. It should be
34921  stressed that SWIG can be used quite effectively without knowing any of
34922  these details--especially now that there are typemap libraries that can
34923  already been written.</P>
34924 <P><B> Perl Integer Functions</B></P>
34925 <DIV class="code">
34926 <PRE>
34927 int   SvIV(SV *);
34928 void  sv_setiv(SV *sv, IV value);
34929 SV   *newSViv(IV value);
34930 int   SvIOK(SV *);
34931 </PRE>
34932 </DIV>
34933 <P><B> Perl Floating Point Functions</B></P>
34934 <DIV class="code">
34935 <PRE>
34936 double SvNV(SV *);
34937 void   sv_setnv(SV *, double value);
34938 SV    *newSVnv(double value);
34939 int    SvNOK(SV *);
34940 </PRE>
34941 </DIV>
34942 <P><B> Perl String Functions</B></P>
34943 <DIV class="code">
34944 <PRE>
34945 char     *SvPV(SV *, STRLEN len);
34946 void      sv_setpv(SV *, char *val);
34947 void      sv_setpvn(SV *, char *val, STRLEN len);
34948 SV       *newSVpv(char *value, STRLEN len);
34949 int       SvPOK(SV *);
34950 void      sv_catpv(SV *, char *);
34951 void      sv_catpvn(SV *, char *, STRLEN);
34952 </PRE>
34953 </DIV>
34954 <P><B> Perl References</B></P>
34955 <DIV class="code">
34956 <PRE>
34957 void      sv_setref_pv(SV *, char *, void *ptr);
34958 int       sv_isobject(SV *);
34959 SV       *SvRV(SV *);
34960 int       sv_isa(SV *, char *0;
34961 </PRE>
34962 </DIV>
34963 <H2><A name="Perl5_nn32"></A>28.8 Typemap Examples</H2>
34964 <P> This section includes a few examples of typemaps. For more examples,
34965  you might look at the files &quot;<TT>perl5.swg</TT>&quot; and &quot;<TT>typemaps.i</TT>
34966 &quot; in the SWIG library.</P>
34967 <H3><A name="Perl5_nn33"></A>28.8.1 Converting a Perl5 array to a char
34968  **</H3>
34969 <P> A common problem in many C programs is the processing of command
34970  line arguments, which are usually passed in an array of NULL terminated
34971  strings. The following SWIG interface file allows a Perl5 array
34972  reference to be used as a char ** datatype.</P>
34973 <DIV class="code">
34974 <PRE>
34975 %module argv
34976
34977 // This tells SWIG to treat char ** as a special case
34978 %typemap(in) char ** {
34979         AV *tempav;
34980         I32 len;
34981         int i;
34982         SV  **tv;
34983         if (!SvROK($input))
34984             croak(&quot;Argument $argnum is not a reference.&quot;);
34985         if (SvTYPE(SvRV($input)) != SVt_PVAV)
34986             croak(&quot;Argument $argnum is not an array.&quot;);
34987         tempav = (AV*)SvRV($input);
34988         len = av_len(tempav);
34989         $1 = (char **) malloc((len+2)*sizeof(char *));
34990         for (i = 0; i &lt;= len; i++) {
34991             tv = av_fetch(tempav, i, 0);        
34992             $1[i] = (char *) SvPV(*tv,PL_na);
34993         }
34994         $1[i] = NULL;
34995 };
34996
34997 // This cleans up the char ** array after the function call
34998 %typemap(freearg) char ** {
34999         free($1);
35000 }
35001
35002 // Creates a new Perl array and places a NULL-terminated char ** into it
35003 %typemap(out) char ** {
35004         AV *myav;
35005         SV **svs;
35006         int i = 0,len = 0;
35007         /* Figure out how many elements we have */
35008         while ($1[len])
35009            len++;
35010         svs = (SV **) malloc(len*sizeof(SV *));
35011         for (i = 0; i &lt; len ; i++) {
35012             svs[i] = sv_newmortal();
35013             sv_setpv((SV*)svs[i],$1[i]);
35014         };
35015         myav =  av_make(len,svs);
35016         free(svs);
35017         $result = newRV_noinc((SV*)myav);
35018         sv_2mortal($result);
35019         argvi++;
35020 }
35021
35022 // Now a few test functions
35023 %inline %{
35024 int print_args(char **argv) {
35025     int i = 0;
35026     while (argv[i]) {
35027          printf(&quot;argv[%d] = %s\n&quot;, i,argv[i]);
35028          i++;
35029     }
35030     return i;
35031 }
35032
35033 // Returns a char ** list 
35034 char **get_args() {
35035     static char *values[] = { &quot;Dave&quot;, &quot;Mike&quot;, &quot;Susan&quot;, &quot;John&quot;, &quot;Michelle&quot;, 0};
35036     return &amp;values[0];
35037 }
35038 %}
35039
35040 </PRE>
35041 </DIV>
35042 <P> When this module is compiled, the wrapped C functions can be used in
35043  a Perl script as follows :</P>
35044 <DIV class="targetlang">
35045 <PRE>
35046 use argv;
35047 @a = (&quot;Dave&quot;, &quot;Mike&quot;, &quot;John&quot;, &quot;Mary&quot;);           # Create an array of strings
35048 argv::print_args(\@a);                           # Pass it to our C function
35049 $b = argv::get_args();                           # Get array of strings from C
35050 print @$b,&quot;\n&quot;;                                  # Print it out
35051 </PRE>
35052 </DIV>
35053 <H3><A name="Perl5_nn34"></A>28.8.2 Return values</H3>
35054 <P> Return values are placed on the argument stack of each wrapper
35055  function. The current value of the argument stack pointer is contained
35056  in a variable <TT>argvi</TT>. Whenever a new output value is added, it
35057  is critical that this value be incremented. For multiple output values,
35058  the final value of <TT>argvi</TT> should be the total number of output
35059  values.</P>
35060 <P> The total number of return values should not exceed the number of
35061  input values unless you explicitly extend the argument stack. This can
35062  be done using the <TT>EXTEND()</TT> macro as in :</P>
35063 <DIV class="code">
35064 <PRE>
35065 %typemap(argout) int *OUTPUT {
35066         if (argvi &gt;= items) {            
35067                 EXTEND(sp,1);              /* Extend the stack by 1 object */
35068         }
35069         $result = sv_newmortal();
35070         sv_setiv($target,(IV) *($1));
35071         argvi++;
35072 }
35073 </PRE>
35074 </DIV>
35075 <H3><A name="Perl5_nn35"></A>28.8.3 Returning values from arguments</H3>
35076 <P> Sometimes it is desirable for a function to return a value in one of
35077  its arguments. This example describes the implementation of the <TT>
35078 OUTPUT</TT> typemap.</P>
35079 <DIV class="code">
35080 <PRE>
35081 %module return
35082
35083 // This tells SWIG to treat an double * argument with name 'OutDouble' as
35084 // an output value.  
35085
35086 %typemap(argout) double *OUTPUT {
35087         $result = sv_newmortal();
35088         sv_setnv($result, *$input);
35089         argvi++;                     /* Increment return count -- important! */
35090 }
35091
35092 // We don't care what the input value is. Ignore, but set to a temporary variable
35093
35094 %typemap(in,numinputs=0) double *OUTPUT(double junk) {
35095         $1 = &amp;junk;
35096 }
35097
35098 // Now a function to test it
35099 %{
35100 /* Returns the first two input arguments */
35101 int multout(double a, double b, double *out1, double *out2) {
35102         *out1 = a;
35103         *out2 = b;
35104         return 0;
35105 };
35106 %}
35107
35108 // If we name both parameters OutDouble both will be output
35109
35110 int multout(double a, double b, double *OUTPUT, double *OUTPUT);
35111 ...
35112 </PRE>
35113 </DIV>
35114 <P> When this function is called, the output arguments are appended to
35115  the stack used to return results. This shows up an array in Perl. For
35116  example :</P>
35117 <DIV class="targetlang">
35118 <PRE>
35119 @r = multout(7,13);
35120 print &quot;multout(7,13) = @r\n&quot;;
35121 ($x,$y) = multout(7,13);
35122 </PRE>
35123 </DIV>
35124 <H3><A name="Perl5_nn36"></A>28.8.4 Accessing array structure members</H3>
35125 <P> Consider the following data structure :</P>
35126 <DIV class="code">
35127 <PRE>
35128 #define SIZE  8
35129 typedef struct {
35130     int   values[SIZE];
35131     ...
35132 } Foo;
35133
35134 </PRE>
35135 </DIV>
35136 <P> By default, SWIG doesn't know how to the handle the values structure
35137  member it's an array, not a pointer. In this case, SWIG makes the array
35138  member read-only. Reading will simply return a pointer to the first
35139  item in the array. To make the member writable, a &quot;memberin&quot; typemap
35140  can be used.</P>
35141 <DIV class="code">
35142 <PRE>
35143 %typemap(memberin) int [SIZE] {
35144     int i;
35145     for (i = 0; i &lt; SIZE; i++) {
35146         $1[i] = $input[i];
35147     }
35148 }
35149
35150 </PRE>
35151 </DIV>
35152 <P> Whenever a <TT>int [SIZE]</TT> member is encountered in a structure
35153  or class, this typemap provides a safe mechanism for setting its value.</P>
35154 <P> As in the previous example, the typemap can be generalized for any
35155  dimension. For example:</P>
35156 <DIV class="code">
35157 <PRE>
35158 %typemap(memberin) int [ANY] {
35159    int i;
35160    for (i = 0; i &lt; $1_dim0; i++) {
35161       $1[i] = $input[i];
35162    }
35163 }
35164 </PRE>
35165 </DIV>
35166 <P> When setting structure members, the input object is always assumed
35167  to be a C array of values that have already been converted from the
35168  target language. Because of this, the <TT>memberin</TT> typemap is
35169  almost always combined with the use of an &quot;in&quot; typemap. For example,
35170  the &quot;in&quot; typemap in the previous section would be used to convert an <TT>
35171 int[]</TT> array to C whereas the &quot;memberin&quot; typemap would be used to
35172  copy the converted array into a C data structure.</P>
35173 <H3><A name="Perl5_nn37"></A>28.8.5 Turning Perl references into C
35174  pointers</H3>
35175 <P> A frequent confusion on the SWIG mailing list is errors caused by
35176  the mixing of Perl references and C pointers. For example, suppose you
35177  have a C function that modifies its arguments like this :</P>
35178 <DIV class="code">
35179 <PRE>
35180 void add(double a, double b, double *c) {
35181         *c = a + b;
35182 }
35183 </PRE>
35184 </DIV>
35185 <P> A common misinterpretation of this function is the following Perl
35186  script :</P>
35187 <DIV class="targetlang">
35188 <PRE>
35189 # Perl script
35190 $a = 3.5;
35191 $b = 7.5;
35192 $c = 0.0;          # Output value
35193 add($a,$b,\$c);    # Place result in c (Except that it doesn't work)
35194 </PRE>
35195 </DIV>
35196 <P> To make this work with a reference, you can use a typemap such as
35197  this:</P>
35198 <DIV class="code">
35199 <PRE>
35200 %typemap(in) double * (double dvalue) {
35201   SV* tempsv;
35202   if (!SvROK($input)) {
35203     croak(&quot;expected a reference\n&quot;);
35204   }
35205   tempsv = SvRV($input);
35206   if ((!SvNOK(tempsv)) &amp;&amp; (!SvIOK(tempsv))) {
35207     croak(&quot;expected a double reference\n&quot;);
35208   }
35209   dvalue = SvNV(tempsv);
35210   $1 = &amp;dvalue;
35211 }
35212
35213 %typemap(argout) double * {
35214   SV *tempsv;
35215   tempsv = SvRV($input);
35216   sv_setnv(tempsv, *$1);
35217 }
35218 </PRE>
35219 </DIV>
35220 <P> Now, if you place this before the add function, you can do this :</P>
35221 <DIV class="targetlang">
35222 <PRE>
35223 $a = 3.5;
35224 $b = 7.5;
35225 $c = 0.0;
35226 add($a,$b,\$c);            # Now it works!
35227 print &quot;$c\n&quot;;
35228
35229 </PRE>
35230 </DIV>
35231 <H3><A name="Perl5_nn38"></A>28.8.6 Pointer handling</H3>
35232 <P> Occasionally, it might be necessary to convert pointer values that
35233  have been stored using the SWIG typed-pointer representation. To
35234  convert a pointer from Perl to C, the following function is used:</P>
35235 <P> <TT>int SWIG_ConvertPtr(SV *obj, void **ptr, swig_type_info *ty, int
35236  flags)</TT></P>
35237 <DIV class="indent"> Converts a Perl object <TT>obj</TT> to a C pointer.
35238  The result of the conversion is placed into the pointer located at <TT>
35239 ptr</TT>. <TT>ty</TT> is a SWIG type descriptor structure. <TT>flags</TT>
35240  is used to handle error checking and other aspects of conversion. <TT>
35241 flags</TT> is currently undefined and reserved for future expansion.
35242  Returns 0 on success and -1 on error.</DIV>
35243 <P> <TT>void *SWIG_MakePtr(SV *obj, void *ptr, swig_type_info *ty, int
35244  flags)</TT></P>
35245 <DIV class="indent"> Creates a new Perl pointer object. <TT>obj</TT> is
35246  a Perl SV that has been initialized to hold the result, <TT>ptr</TT> is
35247  the pointer to convert, <TT>ty</TT> is the SWIG type descriptor
35248  structure that describes the type, and <TT>flags</TT> is a flag that
35249  controls properties of the conversion. <TT>flags</TT> is currently
35250  undefined and reserved.</DIV>
35251 <P> Both of these functions require the use of a special SWIG
35252  type-descriptor structure. This structure contains information about
35253  the mangled name of the datatype, type-equivalence information, as well
35254  as information about converting pointer values under C++ inheritance.
35255  For a type of <TT>Foo *</TT>, the type descriptor structure is usually
35256  accessed as follows:</P>
35257 <DIV class="code">
35258 <PRE>
35259 Foo *f;
35260 if (SWIG_ConvertPtr($input, (void **) &amp;f, SWIGTYPE_p_Foo, 0) == -1) return NULL;
35261
35262 SV *sv = sv_newmortal();
35263 SWIG_MakePtr(sv, f, SWIGTYPE_p_Foo, 0);
35264 </PRE>
35265 </DIV>
35266 <P> In a typemap, the type descriptor should always be accessed using
35267  the special typemap variable <TT>$1_descriptor</TT>. For example:</P>
35268 <DIV class="code">
35269 <PRE>
35270 %typemap(in) Foo * {
35271    if ((SWIG_ConvertPtr($input,(void **) &amp;$1, $1_descriptor,0)) == -1) return NULL;
35272 }
35273 </PRE>
35274 </DIV>
35275 <P> If necessary, the descriptor for any type can be obtained using the <TT>
35276 $descriptor()</TT> macro in a typemap. For example:</P>
35277 <DIV class="code">
35278 <PRE>
35279 %typemap(in) Foo * {
35280    if ((SWIG_ConvertPtr($input,(void **) &amp;$1, $descriptor(Foo *), 0)) == -1) return NULL;
35281 }
35282 </PRE>
35283 </DIV>
35284 <H2><A name="Perl5_nn39"></A>28.9 Proxy classes</H2>
35285 <P><B> Out of date. Needs update.</B></P>
35286 <P> Using the low-level procedural interface, SWIG can also construct a
35287  high-level object oriented interface to C structures and C++ classes.
35288  This is done by constructing a Perl proxy class (also known as a shadow
35289  class) that provides an OO wrapper to the underlying code. This section
35290  describes the implementation details of the proxy interface.</P>
35291 <H3><A name="Perl5_nn40"></A>28.9.1 Preliminaries</H3>
35292 <P> Proxy classes, are generated by default. If you want to turn them
35293  off, use the <TT>-noproxy</TT> command line option. For example:</P>
35294 <DIV class="code">
35295 <PRE>
35296 $ swig -c++ -perl -noproxy example.i
35297 </PRE>
35298 </DIV>
35299 <P> When proxy classes are used, SWIG moves all of the low-level
35300  procedural wrappers to another package name. By default, this package
35301  is named 'modulec' where 'module' is the name of the module you
35302  provided with the <TT>%module</TT> directive. Then, in place of the
35303  original module, SWIG creates a collection of high-level Perl wrappers.
35304  In your scripts, you will use these high level wrappers. The wrappers,
35305  in turn, interact with the low-level procedural module.</P>
35306 <H3><A name="Perl5_nn41"></A>28.9.2 Structure and class wrappers</H3>
35307 <P> Suppose you have the following SWIG interface file :</P>
35308 <DIV class="code">
35309 <PRE>
35310 %module example
35311 struct Vector {
35312         Vector(double x, double y, double z);
35313         ~Vector();
35314         double x,y,z;
35315 };
35316
35317 </PRE>
35318 </DIV>
35319 <P> When wrapped, SWIG creates the following set of low-level accessor
35320  functions as described in previous sections.</P>
35321 <DIV class="code">
35322 <PRE>
35323 Vector *new_Vector(double x, double y, double z);
35324 void    delete_Vector(Vector *v);
35325 double  Vector_x_get(Vector *v);
35326 double  Vector_x_set(Vector *v, double value);
35327 double  Vector_y_get(Vector *v);
35328 double  Vector_y_set(Vector *v, double value);
35329 double  Vector_z_get(Vector *v);
35330 double  Vector_z_set(Vector *v, double value);
35331
35332 </PRE>
35333 </DIV>
35334 <P> However, when proxy classes are enabled, these accessor functions
35335  are wrapped inside a Perl class like this:</P>
35336 <DIV class="targetlang">
35337 <PRE>
35338 package example::Vector;
35339 @ISA = qw( example );
35340 %OWNER = ();
35341 %BLESSEDMEMBERS = ();
35342
35343 sub new () {
35344     my $self = shift;
35345     my @args = @_;
35346     $self = vectorc::new_Vector(@args);
35347     return undef if (!defined($self));
35348     bless $self, &quot;example::Vector&quot;;
35349     $OWNER{$self} = 1;
35350     my %retval;
35351     tie %retval, &quot;example::Vector&quot;, $self;
35352     return bless \%retval,&quot;Vector&quot;;
35353 }
35354
35355 sub DESTROY {
35356     return unless $_[0]-&gt;isa('HASH');
35357     my $self = tied(%{$_[0]});
35358     delete $ITERATORS{$self};
35359     if (exists $OWNER{$self}) {
35360          examplec::delete_Vector($self));
35361          delete $OWNER{$self};
35362 }
35363
35364 sub FETCH {
35365     my ($self,$field) = @_;
35366     my $member_func = &quot;vectorc::Vector_${field}_get&quot;;
35367     my $val = &amp;$member_func($self);
35368     if (exists $BLESSEDMEMBERS{$field}) {
35369         return undef if (!defined($val));
35370         my %retval;
35371         tie %retval,$BLESSEDMEMBERS{$field},$val;
35372         return bless \%retval, $BLESSEDMEMBERS{$field};
35373     }
35374     return $val;
35375 }
35376
35377 sub STORE {
35378     my ($self,$field,$newval) = @_;
35379     my $member_func = &quot;vectorc::Vector_${field}_set&quot;;
35380     if (exists $BLESSEDMEMBERS{$field}) {
35381         &amp;$member_func($self,tied(%{$newval}));
35382     } else {
35383         &amp;$member_func($self,$newval);
35384     }
35385 }
35386 </PRE>
35387 </DIV>
35388 <P> Each structure or class is mapped into a Perl package of the same
35389  name. The C++ constructors and destructors are mapped into constructors
35390  and destructors for the package and are always named &quot;new&quot; and
35391  &quot;DESTROY&quot;. The constructor always returns a tied hash table. This hash
35392  table is used to access the member variables of a structure in addition
35393  to being able to invoke member functions. The <TT>%OWNER</TT> and <TT>
35394 %BLESSEDMEMBERS</TT> hash tables are used internally and described
35395  shortly.</P>
35396 <P> To use our new proxy class we can simply do the following:</P>
35397 <DIV class="targetlang">
35398 <PRE>
35399 # Perl code using Vector class
35400 $v = new Vector(2,3,4);
35401 $w = Vector-&gt;new(-1,-2,-3);
35402
35403 # Assignment of a single member
35404 $v-&gt;{x} = 7.5;
35405
35406 # Assignment of all members
35407 %$v = ( x=&gt;3,
35408          y=&gt;9,
35409          z=&gt;-2);
35410
35411 # Reading members
35412 $x = $v-&gt;{x};
35413
35414 # Destruction
35415 $v-&gt;DESTROY();
35416
35417 </PRE>
35418 </DIV>
35419 <H3><A name="Perl5_nn42"></A>28.9.3 Object Ownership</H3>
35420 <P> In order for proxy classes to work properly, it is necessary for
35421  Perl to manage some mechanism of object ownership. Here's the crux of
35422  the problem---suppose you had a function like this :</P>
35423 <DIV class="code">
35424 <PRE>
35425 Vector *Vector_get(Vector *v, int index) {
35426         return &amp;v[i];
35427 }
35428 </PRE>
35429 </DIV>
35430 <P> This function takes a Vector pointer and returns a pointer to
35431  another Vector. Such a function might be used to manage arrays or lists
35432  of vectors (in C). Now contrast this function with the constructor for
35433  a Vector object :</P>
35434 <DIV class="code">
35435 <PRE>
35436 Vector *new_Vector(double x, double y, double z) {
35437         Vector *v;
35438         v = new Vector(x,y,z);        // Call C++ constructor
35439         return v;
35440 }
35441 </PRE>
35442 </DIV>
35443 <P> Both functions return a Vector, but the constructor is returning a
35444  brand-new Vector while the other function is returning a Vector that
35445  was already created (hopefully). In Perl, both vectors will be
35446  indistinguishable---clearly a problem considering that we would
35447  probably like the newly created Vector to be destroyed when we are done
35448  with it.</P>
35449 <P> To manage these problems, each class contains two methods that
35450  access an internal hash table called <TT>%OWNER</TT>. This hash keeps a
35451  list of all of the objects that Perl knows that it has created. This
35452  happens in two cases: (1) when the constructor has been called, and (2)
35453  when a function implicitly creates a new object (as is done when SWIG
35454  needs to return a complex datatype by value). When the destructor is
35455  invoked, the Perl proxy class module checks the <TT>%OWNER</TT> hash to
35456  see if Perl created the object. If so, the C/C++ destructor is invoked.
35457  If not, we simply destroy the Perl object and leave the underlying C
35458  object alone (under the assumption that someone else must have created
35459  it).</P>
35460 <P> This scheme works remarkably well in practice but it isn't
35461  foolproof. In fact, it will fail if you create a new C object in Perl,
35462  pass it on to a C function that remembers the object, and then destroy
35463  the corresponding Perl object (this situation turns out to come up
35464  frequently when constructing objects like linked lists and trees). When
35465  C takes possession of an object, you can change Perl's ownership by
35466  simply deleting the object from the <TT>%OWNER</TT> hash. This is done
35467  using the <TT>DISOWN</TT> method.</P>
35468 <DIV class="targetlang">
35469 <PRE>
35470 # Perl code to change ownership of an object
35471 $v = new Vector(x,y,z);
35472 $v-&gt;DISOWN();     
35473 </PRE>
35474 </DIV>
35475 <P> To acquire ownership of an object, the <TT>ACQUIRE</TT> method can
35476  be used.</P>
35477 <DIV class="targetlang">
35478 <PRE>
35479 # Given Perl ownership of a file
35480 $u = Vector_get($v);
35481 $u-&gt;ACQUIRE();
35482
35483 </PRE>
35484 </DIV>
35485 <P> As always, a little care is in order. SWIG does not provide
35486  reference counting, garbage collection, or advanced features one might
35487  find in sophisticated languages.</P>
35488 <H3><A name="Perl5_nn43"></A>28.9.4 Nested Objects</H3>
35489 <P> Suppose that we have a new object that looks like this :</P>
35490 <DIV class="code">
35491 <PRE>
35492 struct Particle {
35493         Vector r;
35494         Vector v;
35495         Vector f;
35496         int     type;
35497 }
35498
35499 </PRE>
35500 </DIV>
35501 <P> In this case, the members of the structure are complex objects that
35502  have already been encapsulated in a Perl proxy class. To handle these
35503  correctly, we use the <TT>%BLESSEDMEMBERS</TT> hash which would look
35504  like this (along with some supporting code) :</P>
35505 <DIV class="targetlang">
35506 <PRE>
35507 package Particle;
35508 ...
35509 %BLESSEDMEMBERS = (
35510         r =&gt; `Vector',
35511         v =&gt; `Vector',
35512         f =&gt; `Vector',
35513 );
35514
35515 </PRE>
35516 </DIV>
35517 <P> When fetching members from the structure, <TT>%BLESSEDMEMBERS</TT>
35518  is checked. If the requested field is present, we create a tied-hash
35519  table and return it. If not, we just return the corresponding member
35520  unmodified.</P>
35521 <P> This implementation allows us to operate on nested structures as
35522  follows :</P>
35523 <DIV class="targetlang">
35524 <PRE>
35525 # Perl access of nested structure
35526 $p = new Particle();
35527 $p-&gt;{f}-&gt;{x} = 0.0;
35528 %${$p-&gt;{v}} = ( x=&gt;0, y=&gt;0, z=&gt;0);         
35529 </PRE>
35530 </DIV>
35531 <H3><A name="Perl5_nn44"></A>28.9.5 Proxy Functions</H3>
35532 <P> When functions take arguments involving a complex object, it is
35533  sometimes necessary to write a proxy function. For example :</P>
35534 <DIV class="code">
35535 <PRE>
35536 double dot_product(Vector *v1, Vector *v2);
35537 </PRE>
35538 </DIV>
35539 <P> Since Vector is an object already wrapped into a proxy class, we
35540  need to modify this function to accept arguments that are given in the
35541  form of tied hash tables. This is done by creating a Perl function like
35542  this :</P>
35543 <DIV class="targetlang">
35544 <PRE>
35545 sub dot_product {
35546     my @args = @_;
35547     $args[0] = tied(%{$args[0]});         # Get the real pointer values
35548     $args[1] = tied(%{$args[1]});
35549     my $result = vectorc::dot_product(@args);
35550     return $result;
35551 }
35552 </PRE>
35553 </DIV>
35554 <P> This function replaces the original function, but operates in an
35555  identical manner.</P>
35556 <H3><A name="Perl5_nn45"></A>28.9.6 Inheritance</H3>
35557 <P> Simple C++ inheritance is handled using the Perl <TT>@ISA</TT> array
35558  in each class package. For example, if you have the following interface
35559  file :</P>
35560 <DIV class="code">
35561 <PRE>
35562 // shapes.i
35563 // SWIG interface file for shapes class
35564 %module shapes
35565 %{
35566 #include &quot;shapes.h&quot;
35567 %}
35568
35569 class Shape {
35570 public:
35571         virtual double area() = 0;
35572         virtual double perimeter() = 0;
35573         void    set_location(double x, double y);
35574 };
35575 class Circle : public Shape {
35576 public:
35577         Circle(double radius);
35578         ~Circle();
35579         double area();
35580         double perimeter();
35581 };
35582 class Square : public Shape {
35583 public:
35584         Square(double size);
35585         ~Square();
35586         double area();
35587         double perimeter();
35588 }
35589
35590 </PRE>
35591 </DIV>
35592 <P> The resulting, Perl wrapper class will create the following code :</P>
35593 <DIV class="targetlang">
35594 <PRE>
35595 Package Shape;
35596 @ISA = (shapes);
35597 ...
35598 Package Circle;
35599 @ISA = (shapes Shape);
35600 ...
35601 Package Square;
35602 @ISA = (shapes Shape);
35603
35604 </PRE>
35605 </DIV>
35606 <P> The <TT>@ISA</TT> array determines where to look for methods of a
35607  particular class. In this case, both the <TT>Circle</TT> and <TT>Square</TT>
35608  classes inherit functions from <TT>Shape</TT> so we'll want to look in
35609  the <TT>Shape</TT> base class for them. All classes also inherit from
35610  the top-level module <TT>shapes</TT>. This is because certain common
35611  operations needed to implement proxy classes are implemented only once
35612  and reused in the wrapper code for various classes and structures.</P>
35613 <P> Since SWIG proxy classes are implemented in Perl, it is easy to
35614  subclass from any SWIG generated class. To do this, simply put the name
35615  of a SWIG class in the <TT>@ISA</TT> array for your new class. However,
35616  be forewarned that this is not a trivial problem. In particular,
35617  inheritance of data members is extremely tricky (and I'm not even sure
35618  if it really works).</P>
35619 <H3><A name="Perl5_nn46"></A>28.9.7 Modifying the proxy methods</H3>
35620 <P> It is possible to override the SWIG generated proxy/shadow methods,
35621  using <TT>%feature(&quot;shadow&quot;)</TT>. It works like all the other <A href="#features">
35622 %feature directives</A>. Here is a simple example showing how to add
35623  some Perl debug code to the constructor:</P>
35624 <DIV class="targetlang">
35625 <PRE>
35626 /* Let's make the constructor of the class Square more verbose */
35627 %feature(&quot;shadow&quot;) Square(double w)
35628 %{
35629   sub new {
35630     my $pkg = shift;
35631     my $self = examplec::new_Square(@_);
35632     print STDERR &quot;Constructed an @{[ref($self)]}\n&quot;;
35633     bless $self, $pkg if defined($self);
35634   }
35635 %}
35636
35637 class Square {
35638 public:
35639   Square(double w);
35640   ...
35641 };
35642 </PRE>
35643 </DIV>
35644 <H2><A name="Perl5_nn47"></A>28.10 Adding additional Perl code</H2>
35645 <P> If writing support code in C isn't enough, it is also possible to
35646  write code in Perl. This code gets inserted in to the <TT>.pm</TT> file
35647  created by SWIG. One use of Perl code might be to supply a high-level
35648  interface to certain functions. For example:</P>
35649 <DIV class="code">
35650 <PRE>
35651 void set_transform(Image *im, double x[4][4]);
35652
35653 ...
35654 /* Rewrite the high level interface to set_transform */
35655 %perlcode %{
35656 sub set_transform
35657 {
35658   my ($im, $x) = @_;
35659   my $a = new_mat44();
35660   for (my $i = 0; $i &lt; 4, $i++)
35661   {
35662     for (my $j = 0; $j &lt; 4, $j++)
35663     {
35664       mat44_set($a, $i, $j, $x-&gt;[i][j])
35665       }
35666   }
35667   example.set_transform($im, $a);
35668   free_mat44($a);
35669 }
35670 %}
35671 </PRE>
35672 </DIV>
35673 <P> In this example, <TT>set_transform()</TT> provides a high-level Perl
35674  interface built on top of low-level helper functions. For example, this
35675  code now seems to work:</P>
35676 <DIV class="targetlang">
35677 <PRE>
35678 my $a =
35679   [[1,0,0,0],
35680    [0,1,0,0],
35681    [0,0,1,0],
35682    [0,0,0,1]];
35683 set_transform($im, $a);
35684 </PRE>
35685 </DIV><HR NOSHADE>
35686
35687 <!-- Hand crafted HTML -->
35688 <H1><A name="Php"></A>29 SWIG and PHP</H1>
35689
35690 <!-- INDEX -->
35691 <DIV class="sectiontoc">
35692 <UL>
35693 <LI><A href="#Php_nn1">Generating PHP Extensions</A>
35694 <UL>
35695 <LI><A href="#Php_nn1_1">Building a loadable extension</A></LI>
35696 <LI><A href="#Php_nn1_3">Using PHP Extensions</A></LI>
35697 </UL>
35698 </LI>
35699 <LI><A href="#Php_nn2">Basic PHP interface</A>
35700 <UL>
35701 <LI><A href="#Php_nn2_1">Constants</A></LI>
35702 <LI><A href="#Php_nn2_2">Global Variables</A></LI>
35703 <LI><A href="#Php_nn2_3">Functions</A></LI>
35704 <LI><A href="#Php_nn2_4">Overloading</A></LI>
35705 <LI><A href="#Php_nn2_5">Pointers and References</A></LI>
35706 <LI><A href="#Php_nn2_6">Structures and C++ classes</A>
35707 <UL>
35708 <LI><A href="#Php_nn2_6_1">Using <TT>-noproxy</TT></A></LI>
35709 <LI><A href="#Php_nn2_6_2">Constructors and Destructors</A></LI>
35710 <LI><A href="#Php_nn2_6_3">Static Member Variables</A></LI>
35711 <LI><A href="#Php_nn2_6_4">Static Member Functions</A></LI>
35712 </UL>
35713 </LI>
35714 <LI><A href="#Php_nn2_7">PHP Pragmas, Startup and Shutdown code</A></LI>
35715 </UL>
35716 </LI>
35717 <LI><A href="#Php_nn3">Cross language polymorphism</A>
35718 <UL>
35719 <LI><A href="#Php_nn3_1">Enabling directors</A></LI>
35720 <LI><A href="#Php_nn3_2">Director classes</A></LI>
35721 <LI><A href="#Php_nn3_3">Ownership and object destruction</A></LI>
35722 <LI><A href="#Php_nn3_4">Exception unrolling</A></LI>
35723 <LI><A href="#Php_nn3_5">Overhead and code bloat</A></LI>
35724 <LI><A href="#Php_nn3_6">Typemaps</A></LI>
35725 <LI><A href="#Php_nn3_7">Miscellaneous</A></LI>
35726 </UL>
35727 </LI>
35728 </UL>
35729 </DIV>
35730 <!-- INDEX -->
35731 <P> SWIG supports generating wrappers for PHP5. Support for PHP4 has
35732  been removed as of SWIG 1.3.37. The PHP developers are no longer making
35733  new PHP4 releases, and won't even be patching critical security issues
35734  after 2008-08-08, so it doesn't make much sense for SWIG to continue to
35735  support PHP4 at this point. If you need to continue to use PHP4, stick
35736  with SWIG 1.3.36.</P>
35737 <P> In this chapter, we discuss SWIG's support of PHP. The PHP module
35738  was extensively rewritten in release 1.3.26, and support for generating
35739  OO wrappers for PHP5 was added in 1.3.30. The PHP module works fairly
35740  well, but currently does not implement all the features available in
35741  some of the other languages.</P>
35742 <P> In order to use this module, you will need to have a copy of the
35743  PHP5 include files to compile the SWIG generated files. If you
35744  installed PHP from a binary package, you may need to install a
35745  &quot;php-dev&quot; or &quot;php-devel&quot; package for these to be installed. You can
35746  find out where these files are by running <TT>php-config --includes</TT>
35747 . To use the built PHP module you will need either the php binary or the
35748  Apache php module. If you want to build your extension into php
35749  directly, you will need the complete PHP source tree available.</P>
35750 <H2><A name="Php_nn1"></A>29.1 Generating PHP Extensions</H2>
35751 <P> To build a PHP extension, run swig using the <TT>-php</TT> option as
35752  follows:</P>
35753 <DIV class="code">
35754 <PRE>
35755 swig -php example.i
35756 </PRE>
35757 </DIV>
35758 <P> This will produce 3 files example_wrap.c, php_example.h and
35759  example.php. The first file, <TT>example_wrap.c</TT> contains all of
35760  the C code needed to build a PHP extension. The second file, <TT>
35761 php_example.h</TT> contains the header information needed if you wish to
35762  statically link the extension into the php interpreter. The third file,
35763  <TT>example.php</TT> can be included by PHP scripts. It attempts to
35764  dynamically load the extension and contains extra php code specified in
35765  the interface file. If wrapping C++ code with PHP classes, it will also
35766  contain PHP5 class wrappers.</P>
35767 <P> Swig can generate PHP extensions from C++ libraries as well when
35768  given the <TT>-c++</TT> option. The support for C++ is discussed in
35769  more detail in <A href="#Php_nn2_6">section 27.2.6</A>.</P>
35770 <P> The usual (and recommended) way is to build the extension as a
35771  separate dynamically loaded module (which is supported by all modern
35772  operating systems). You can then specify that this be loaded
35773  automatically in <TT>php.ini</TT> or load it explicitly for any script
35774  which needs it.</P>
35775 <P> It is also possible to rebuild PHP from source so that your module
35776  is statically linked into the php executable/library. This is a lot
35777  more work, and also requires a full rebuild of PHP to update your
35778  module, and it doesn't play nicely with package system. We don't
35779  recommend this approach, or provide explicit support for it.</P>
35780 <H3><A name="Php_nn1_1"></A>29.1.1 Building a loadable extension</H3>
35781 <P> To build your module as a dynamically loadable extension, use
35782  compilation commands like these (if you aren't using GCC, the commands
35783  will be different, and there may be some variation between platforms -
35784  these commands should at least work for Linux though):</P>
35785 <DIV class="code">
35786 <PRE>
35787         gcc `php-config --includes` -fpic -c example_wrap.c
35788         gcc -shared example_wrap.o -o example.so
35789 </PRE>
35790 </DIV>
35791 <H3><A name="Php_nn1_3"></A>29.1.2 Using PHP Extensions</H3>
35792 <P> To test the extension from a PHP script, you need to load it first.
35793  You can load it for every script by adding this line the <TT>[PHP]</TT>
35794  section of <TT>php.ini</TT>:</P>
35795 <DIV class="code">
35796 <PRE>
35797         extension=/path/to/modulename.so
35798 </PRE>
35799 </DIV>
35800 <P> Alternatively, you can load it explicitly only for scripts which
35801  need it by adding this line:</P>
35802 <DIV class="code">
35803 <PRE>
35804         dl(&quot;/path/to/modulename.so&quot;); // Load the module
35805 </PRE>
35806 </DIV>
35807 <P> to the start of each PHP file. SWIG also generates a php module,
35808  which attempts to do the <TT>dl()</TT> call for you:</P>
35809 <DIV class="code">
35810 <PRE>
35811         include(&quot;example.php&quot;);
35812 </PRE>
35813 </DIV>
35814 <H2><A name="Php_nn2"></A>29.2 Basic PHP interface</H2>
35815 <P> It is important to understand that PHP uses a single global
35816  namespace into which all symbols from extension modules are loaded. It
35817  is quite possible for names of symbols in one extension module to clash
35818  with other symbols unless care is taken to <TT>%rename</TT> them.</P>
35819 <H3><A name="Php_nn2_1"></A>29.2.1 Constants</H3>
35820 <P> These work in much the same way as in C/C++, constants can be
35821  defined by using either the normal C pre-processor declarations, or the
35822  <TT>%constant</TT> SWIG directive. These will then be available from
35823  your PHP script as a PHP constant, (i.e. no dollar sign is needed to
35824  access them.) For example, with a swig interface file like this,</P>
35825 <DIV class="code">
35826 <PRE>
35827 %module example
35828
35829 #define PI 3.14159
35830
35831 %constant int E  = 2.71828
35832 </PRE>
35833 </DIV>
35834 <P> you can access the constants in your php script like this,</P>
35835 <DIV class="code">
35836 <PRE>
35837 include(&quot;example.php&quot;);
35838
35839 echo &quot;PI = &quot; . PI . &quot;\n&quot;;
35840
35841 echo &quot;E = &quot; . E . &quot;\n&quot;;
35842
35843 </PRE>
35844 </DIV>
35845 <P> There are two peculiarities with using constants in PHP. The first
35846  is that if you try to use an undeclared constant, it will evaluate to a
35847  string set to the constant's name. For example,</P>
35848 <DIV class="code">
35849 <PRE>
35850 %module example
35851
35852 #define EASY_TO_MISPELL 0
35853 </PRE>
35854 </DIV>
35855 <P> accessed incorrectly in PHP,</P>
35856 <DIV class="code">
35857 <PRE>
35858 include(&quot;example.php&quot;);
35859
35860 if(EASY_TO_MISPEL) {
35861         ....
35862 } else {
35863         ....
35864 }
35865
35866 </PRE>
35867 </DIV>
35868 <P> will issue a warning about the undeclared constant, but will then
35869  evaluate it and turn it into a string ('EASY_TO_MISPEL'), which
35870  evaluates to true, rather than the value of the constant which would be
35871  false. This is a feature!</P>
35872 <P> The second 'feature' is that although constants are case sensitive
35873  (by default), you cannot declare a constant twice with alternative
35874  cases. E.g.,</P>
35875 <DIV class="code">
35876 <PRE>
35877 %module example
35878
35879 #define TEST    Hello
35880 #define Test    World
35881 </PRE>
35882 </DIV>
35883 <P> accessed from PHP,</P>
35884 <DIV class="code">
35885 <PRE>
35886 include(&quot;example.php&quot;);
35887
35888 echo TEST, Test;
35889 </PRE>
35890 </DIV>
35891 <P> will output &quot;Hello Test&quot; rather than &quot;Hello World&quot;. This is because
35892  internally, all constants are stored in a hash table by their lower
35893  case name, so 'TEST' and 'Test' will map to the same hash element
35894  ('Test'). But, because we declared them case sensitive, the Zend engine
35895  will test if the case matches with the case the constant was declared
35896  with first.</P>
35897 <P> So, in the example above, the TEST constant was declared first, and
35898  will be stored under the hash element 'test'. The 'Test' constant will
35899  also map to the same hash element 'test', but will not overwrite it.
35900  When called from the script, the TEST constant will again be mapped to
35901  the hash element 'test' so the constant will be retrieved. The case
35902  will then be checked, and will match up, so the value ('Hello') will be
35903  returned. When 'Test' is evaluated, it will also map to the same hash
35904  element 'test'. The same constant will be retrieved, this time though
35905  the case check will fail as 'Test' != 'TEST'. So PHP will assume that
35906  Test is a undeclared constant, and as explained above, will return it
35907  as a string set to the constant name ('Test'). Hence the script above
35908  will print 'Hello Test'. If they were declared non-case sensitive, the
35909  output would be 'Hello Hello', as both point to the same value, without
35910  the case test taking place. ( Apologies, this paragraph needs rewriting
35911  to make some sense. )</P>
35912 <H3><A name="Php_nn2_2"></A>29.2.2 Global Variables</H3>
35913 <P> Because PHP does not provide a mechanism to intercept access and
35914  assignment of global variables, global variables are supported through
35915  the use of automatically generated accessor functions.</P>
35916 <DIV class="code">
35917 <PRE>
35918 %module example;
35919
35920 %inline %{
35921   double seki = 2;
35922   void print_seki() {
35923     zend_printf(&quot;seki is now %f\n&quot;,seki);
35924   }
35925 %}
35926 </PRE>
35927 </DIV>
35928 <P> is accessed as follows:</P>
35929 <DIV class="code">
35930 <PRE>
35931 include(&quot;example.php&quot;);
35932 print seki_get();
35933 seki_set( seki_get() * 2);      # The C variable is now 4.
35934 print seki_get();
35935 </PRE>
35936 </DIV>
35937 <P> SWIG supports global variables of all C datatypes including pointers
35938  and complex objects. Additional types can be supported by using the <TT>
35939 varinit</TT> typemap.</P>
35940 <P> SWIG honors the <TT>%immutable</TT> modifier by not generating code
35941  for the <TT>_set</TT> method. This provides read-only access to the
35942  variable from the php script. Attempting to access the <TT>_set</TT>
35943  method will result in a php fatal error because the function is
35944  undefined.</P>
35945 <P> At this time SWIG does not support custom accessor methods.</P>
35946 <H3><A name="Php_nn2_3"></A>29.2.3 Functions</H3>
35947 <P> C functions are converted into PHP functions. Default/optional
35948  arguments are also allowed. An interface file like this :</P>
35949 <DIV class="code">
35950 <PRE>
35951 %module example
35952 int foo(int a);
35953 double bar(double, double b = 3.0);
35954 ...
35955 </PRE>
35956 </DIV>
35957 <P> Will be accessed in PHP like this :</P>
35958 <DIV class="code">
35959 <PRE>
35960 include(&quot;example.php&quot;);
35961 $a = foo(2);
35962 $b = bar(3.5, -1.5);
35963 $c = bar(3.5);          # Use default argument for 2nd parameter
35964
35965 </PRE>
35966 </DIV>
35967 <!-- This isn't correct for 1.3.30 and needs rewriting to reflect reality
35968 &lt;p&gt;
35969 Because PHP is a dynamically typed language, the default typemaps
35970 used for simple types will attempt to coerce the arguments into the appropriate type.  That is the following invocations are equivalent:
35971 &lt;/p&gt;
35972
35973 &lt;div class=&quot;code&quot;&gt;&lt;pre&gt;
35974 $a = foo(2);
35975 $a = foo(&quot;2&quot;);
35976 $a = foo(2.0);
35977 &lt;/pre&gt;&lt;/div&gt;
35978
35979 &lt;p&gt;
35980 Functions are invoked using pass by value semantics like all of PHP.
35981 This means the conversion which automatically takes place when
35982 invoking a swig wrapped method does not change the native type of the
35983 argument variable.
35984 &lt;/p&gt;
35985 &lt;div class=&quot;code&quot;&gt;&lt;pre&gt;
35986 $s = &quot;2 A string representing two&quot;;
35987 $a = foo($s);  # invokes 'foo(2)';
35988 print $s;      # The value of $s was not changed.
35989 &lt;/pre&gt;&lt;/div&gt;
35990 -->
35991 <H3><A name="Php_nn2_4"></A>29.2.4 Overloading</H3>
35992 <P> Although PHP does not support overloading functions natively, swig
35993  will generate dispatch functions which will use <TT>%typecheck</TT>
35994  typemaps to allow overloading. This dispatch function's operation and
35995  precedence is described in <A href="#SWIGPlus_overloaded_methods">
35996 Wrapping Overloaded Functions and Methods</A>.</P>
35997
35998 <!-- This isn't correct for 1.3.30 and needs rewriting to reflect reality
35999 &lt;p&gt;
36000 Because PHP is a dynamically typed language, simple values can be
36001 silently converted from one type to another.  For example, integers,
36002 doubles and strings silently convert to each other depending on
36003 context.  This situation make overloading slightly problematic because
36004 given the following function:
36005 &lt;/p&gt;
36006
36007 &lt;div class=&quot;code&quot;&gt;&lt;pre&gt;
36008 void doit( int i );
36009 void doit( double i );
36010 &lt;/pre&gt;&lt;/div&gt;
36011
36012 &lt;p&gt;
36013 it is questionable which to invoke when &lt;tt&gt;doit(&quot;2&quot;);&lt;/tt&gt; is used in
36014 PHP.  The string &lt;tt&gt;&quot;2&quot;&lt;/tt&gt; simultaneously represents the integer
36015 &lt;tt&gt;2&lt;/tt&gt; and the double &lt;tt&gt;2.0&lt;/tt&gt;.
36016 &lt;/p&gt;
36017
36018 &lt;p&gt;
36019 In order to provide the most natural experience to PHP programmers,
36020 the default &lt;tt&gt;%typecheck&lt;/tt&gt; implemented in &lt;tt&gt;php.swg&lt;/tt&gt;
36021 allows any simple type (integer, double, string) in PHP to be used for
36022 any simple C type (int, double, char *).  The function selected then
36023 depends only on the argument type precedence defined by SWIG.
36024 &lt;/p&gt;
36025
36026 &lt;p&gt;
36027 It should be noted that &lt;tt&gt;SWIGTYPE&lt;/tt&gt; references and pointers will
36028 not be silently converted.  So these two functions:
36029 &lt;/p&gt;
36030
36031 &lt;div class=&quot;code&quot;&gt;&lt;pre&gt;
36032 void doit( const Vector &amp; );
36033 void doit( int i );
36034 &lt;/pre&gt;&lt;/div&gt;
36035
36036 &lt;p&gt;
36037 Cause less confusion and &lt;tt&gt;doit(&quot;2&quot;);&lt;/tt&gt; will invoke the function
36038 taking the integer argument.
36039 &lt;/p&gt;
36040 -->
36041 <H3><A name="Php_nn2_5"></A>29.2.5 Pointers and References</H3>
36042 <P> Pointers to C/C++ objects are represented as PHP resources, rather
36043  like MySQL connection handles.</P>
36044 <P> There are multiple ways to wrap pointers to simple types. Given the
36045  following C method:</P>
36046 <DIV class="code">
36047 <PRE>
36048   void add( int *in1, int *in2, int *result);
36049 </PRE>
36050 </DIV>
36051 <P> One can include<B> cpointer.i</B> to generate PHP wrappers to <TT>
36052 int *</TT>.</P>
36053 <DIV class="code">
36054 <PRE>
36055 %module example
36056 %include &quot;cpointer.i&quot;
36057 %pointer_functions(int,intp)
36058
36059 void add( int *in1, int *in2, int *result);
36060 </PRE>
36061 </DIV>
36062 <P> This will result in the following usage in PHP:</P>
36063 <DIV class="code">
36064 <PRE>
36065 &lt;?php
36066
36067 include(&quot;example.php&quot;);
36068
36069 $in1=copy_intp(3);
36070 $in2=copy_intp(5);
36071 $result=new_intp();
36072
36073 add( $in1, $in2, $result );
36074
36075 echo &quot;The sum &quot; . intp_value($in1) . &quot; + &quot; . intp_value($in2) . &quot; = &quot; . intp_value( $result) . &quot;\n&quot;;
36076 ?&gt;
36077 </PRE>
36078 </DIV>
36079 <P> An alternative would be to use the include<B> typemaps.i</B> which
36080  defines named typemaps for INPUT, OUTPUT and INOUT variables. One needs
36081  to either <TT>%apply</TT> the appropriate typemap or adjust the
36082  parameter names as appropriate.</P>
36083 <DIV class="code">
36084 <PRE>
36085 %module example
36086 %include &quot;typemaps.i&quot;
36087
36088 void add( int *INPUT, int *INPUT, int *OUTPUT);
36089
36090 </PRE>
36091 </DIV>
36092 <P> This will result in the following usage in PHP:</P>
36093 <DIV class="code">
36094 <PRE>
36095 &lt;?php
36096
36097 include(&quot;example.php&quot;);
36098
36099 $in1 = 3;
36100 $in2 = 5;
36101 $result= add($in1,$in2);  # Note using variables for the input is unnecessary.
36102
36103 echo &quot;The sum $in1 + $in2 = $result\n&quot;;
36104 ?&gt;
36105 </PRE>
36106 </DIV>
36107 <P> Because PHP has a native concept of reference, it may seem more
36108  natural to the PHP developer to use references to pass pointers. To
36109  enable this, one needs to include<B> phppointers.i</B> which defines
36110  the named typemap REFERENCE.</P>
36111 <DIV class="code">
36112 <PRE>
36113 %module example
36114 %include &quot;phppointers.i&quot;
36115
36116 void add( int *REF, int *REF, int *REF);
36117
36118 </PRE>
36119 </DIV>
36120 <P> This will result in the following usage in PHP:</P>
36121 <DIV class="code">
36122 <PRE>
36123 &lt;?php
36124
36125 include(&quot;example.php&quot;);
36126
36127 $in1 = 3;
36128 $in2 = 5;
36129 $result = 0;
36130 add(&amp;$in1,&amp;$in2,&amp;$result);
36131
36132 echo &quot;The sum $in1 + $in2 = $result\n&quot;;
36133 ?&gt;
36134 </PRE>
36135 </DIV>
36136 <P> It is important to note that a php variable which is NULL when
36137  passed by reference would end up passing a NULL pointer into the
36138  function. In PHP, an unassigned variable (i.e. where the first
36139  reference to the variable is not an assignment) is NULL. In the above
36140  example, if any of the three variables had not been assigned, a NULL
36141  pointer would have been passed into <TT>add</TT>. Depending on the
36142  implementation of the function, this may or may not be a good thing.</P>
36143 <P> We chose to allow passing NULL pointers into functions because that
36144  is sometimes required in C libraries. A NULL pointer can be created in
36145  PHP in a number of ways: by using <TT>unset</TT> on an existing
36146  variable, or assigning <TT>NULL</TT> to a variable.</P>
36147 <H3><A name="Php_nn2_6"></A>29.2.6 Structures and C++ classes</H3>
36148 <P> SWIG defaults to wrapping C++ structs and classes with PHP classes
36149  unless &quot;-noproxy&quot; is specified. For PHP5, a PHP wrapper class is
36150  generated which calls a set of flat functions wrapping the C++ class.</P>
36151 <P> This interface file</P>
36152 <DIV class="code">
36153 <PRE>
36154 %module vector
36155
36156 class Vector {
36157 public:
36158         double x,y,z;
36159         Vector();
36160         ~Vector();
36161         double magnitude();
36162 };
36163
36164 struct Complex {
36165  double re, im;
36166 };
36167 </PRE>
36168 </DIV>
36169 <P> Would be used in the following way from PHP5:</P>
36170 <DIV class="code">
36171 <PRE>
36172 &lt;?php
36173   require &quot;vector.php&quot;;
36174
36175   $v = new Vector();
36176   $v-&gt;x = 3;
36177   $v-&gt;y = 4;
36178   $v-&gt;z = 5;
36179
36180   echo &quot;Magnitude of ($v-&gt;x,$v-&gt;y,$v-&gt;z) = &quot; . $v-&gt;magnitude() . &quot;\n&quot;;
36181
36182   $v = NULL;   # destructor called.
36183
36184   $c = new Complex();
36185
36186   $c-&gt;re = 0;
36187   $c-&gt;im = 0;
36188
36189   # $c destructor called when $c goes out of scope.
36190 ?&gt;
36191 </PRE>
36192 </DIV>
36193 <P> Member variables and methods are accessed using the <TT>-&gt;</TT>
36194  operator.</P>
36195 <H4><A name="Php_nn2_6_1"></A>29.2.6.1 Using <TT>-noproxy</TT></H4>
36196 <P> The <TT>-noproxy</TT> option flattens the object structure and
36197  generates collections of named functions (these are the functions which
36198  the PHP5 class wrappers call). The above example results in the
36199  following PHP functions:</P>
36200 <DIV class="code">
36201 <PRE>
36202 new_Vector();
36203 Vector_x_set($obj,$d);
36204 Vector_x_get($obj);
36205 Vector_y_set($obj,$d);
36206 Vector_y_get($obj);
36207 Vector_z_set($obj,$d);
36208 Vector_z_get($obj);
36209 Vector_magnitude($obj);
36210 new_Complex();
36211 Complex_re_set($obj,$d);
36212 Complex_re_get($obj);
36213 Complex_im_set($obj,$d);
36214 Complex_im_get($obj);
36215 </PRE>
36216 </DIV>
36217 <H4><A name="Php_nn2_6_2"></A>29.2.6.2 Constructors and Destructors</H4>
36218 <P> The constructor is called when <TT>new Object()</TT> (or <TT>
36219 new_Object()</TT> if using <TT>-noproxy</TT>) is used to create an
36220  instance of the object. If multiple constructors are defined for an
36221  object, function overloading will be used to determine which
36222  constructor to execute.</P>
36223 <P> Because PHP uses reference counting to manage resources, simple
36224  assignment of one variable to another such as:</P>
36225 <DIV class="code">
36226 <PRE>
36227 $ref = $v;
36228 </PRE>
36229 </DIV>
36230 <P> causes the symbol <TT>$ref</TT> to refer to the same underlying
36231  object as <TT>$v</TT>. This does not result in a call to the C++ copy
36232  constructor or copy assignment operator.</P>
36233 <P> One can force execution of the copy constructor by using:</P>
36234 <DIV class="code">
36235 <PRE>
36236 $o_copy = new Object($o);
36237 </PRE>
36238 </DIV>
36239 <P> Destructors are automatically called when all variables referencing
36240  the instance are reassigned or go out of scope. The destructor is not
36241  available to be called manually. To force a destructor to be called the
36242  programmer can either reassign the variable or call <TT>unset($v)</TT></P>
36243 <H4><A name="Php_nn2_6_3"></A>29.2.6.3 Static Member Variables</H4>
36244 <P> Static member variables in C++ are not wrapped as such in PHP as it
36245  does not appear to be possible to intercept accesses to such variables.
36246  Therefore, static member variables are wrapped using a class function
36247  with the same name, which returns the current value of the class
36248  variable. For example</P>
36249 <DIV class="code">
36250 <PRE>
36251 %module example
36252
36253 class Ko {
36254         static int threats;
36255 };
36256
36257 </PRE>
36258 </DIV>
36259 <P> would be accessed in PHP as,</P>
36260 <DIV class="code">
36261 <PRE>
36262 include(&quot;example.php&quot;);
36263
36264 echo &quot;There has now been &quot; . Ko::threats() . &quot; threats\n&quot;;
36265
36266 </PRE>
36267 </DIV>
36268 <P> To set the static member variable, pass the value as the argument to
36269  the class function, e.g.</P>
36270 <DIV class="code">
36271 <PRE>
36272
36273 Ko::threats(10);
36274
36275 echo &quot;There has now been &quot; . Ko::threats() . &quot; threats\n&quot;;
36276
36277 </PRE>
36278 </DIV>
36279 <H4><A name="Php_nn2_6_4"></A>29.2.6.4 Static Member Functions</H4>
36280 <P> Static member functions are supported in PHP using the <TT>
36281 class::function()</TT> syntax. For example</P>
36282 <DIV class="code">
36283 <PRE>
36284 %module example
36285 class Ko {
36286   static void threats();
36287 };
36288 </PRE>
36289 </DIV> would be executed in PHP as,<DIV class="code">
36290 <PRE>
36291 include(&quot;example.php&quot;);
36292 Ko::threats();
36293 </PRE>
36294 </DIV>
36295 <H3><A name="Php_nn2_7"></A>29.2.7 PHP Pragmas, Startup and Shutdown
36296  code</H3>
36297 <P> To place PHP code in the generated &quot;example.php&quot; file one can use
36298  the<B> code</B> pragma. The code is inserted after loading the shared
36299  object.</P>
36300 <DIV class="code">
36301 <PRE>
36302 %module example
36303 %pragma(php) code=&quot;
36304 # This code is inserted into example.php
36305 echo \&quot;example.php execution\\n\&quot;;
36306 &quot;
36307 </PRE>
36308 </DIV>
36309 <P> Results in the following in &quot;example.php&quot;</P>
36310 <DIV class="code">
36311 <PRE>
36312 # This code is inserted into example.php
36313 echo &quot;example.php execution\n&quot;;
36314 </PRE>
36315 </DIV>
36316 <P> The<B> include</B> pragma is a short cut to add include statements
36317  to the example.php file.</P>
36318 <DIV class="code">
36319 <PRE>
36320 %module example
36321 %pragma(php) code=&quot;
36322 include \&quot;include.php\&quot;;
36323 &quot;
36324 %pragma(php) include=&quot;include.php&quot;   // equivalent.
36325 </PRE>
36326 </DIV>
36327 <P> The<B> phpinfo</B> pragma inserts code in the <TT>PHP_MINFO_FUNCTION</TT>
36328  which is called from PHP's phpinfo() function.</P>
36329 <DIV class="code">
36330 <PRE>
36331 %module example;
36332 %pragma(php) phpinfo=&quot;
36333   zend_printf(&quot;An example of PHP support through SWIG\n&quot;);
36334   php_info_print_table_start();
36335   php_info_print_table_header(2, \&quot;Directive\&quot;, \&quot;Value\&quot;);
36336   php_info_print_table_row(2, \&quot;Example support\&quot;, \&quot;enabled\&quot;);
36337   php_info_print_table_end();
36338 &quot;
36339 </PRE>
36340 </DIV>
36341 <P> To insert code into the <TT>PHP_MINIT_FUNCTION</TT>, one can use
36342  either <TT>%init</TT> or <TT>%minit</TT>.</P>
36343 <DIV class="code">
36344 <PRE>
36345 %module example;
36346 %init {
36347   zend_printf(&quot;Inserted into PHP_MINIT_FUNCTION\n&quot;);
36348 }
36349 %minit {
36350   zend_printf(&quot;Inserted into PHP_MINIT_FUNCTION\n&quot;);
36351 }
36352 </PRE>
36353 </DIV>
36354 <P> To insert code into the <TT>PHP_MSHUTDOWN_FUNCTION</TT>, one can use
36355  either <TT>%init</TT> or <TT>%minit</TT>.</P>
36356 <DIV class="code">
36357 <PRE>
36358 %module example;
36359 %mshutdown {
36360   zend_printf(&quot;Inserted into PHP_MSHUTDOWN_FUNCTION\n&quot;);
36361 }
36362 </PRE>
36363 </DIV>
36364 <P> The <TT>%rinit</TT> and <TT>%rshutdown</TT> statements insert code
36365  into the request init and shutdown code respectively.</P>
36366 <H2><A name="Php_nn3"></A>29.3 Cross language polymorphism</H2>
36367 <P> Proxy classes provide a more natural, object-oriented way to access
36368  extension classes. As described above, each proxy instance has an
36369  associated C++ instance, and method calls to the proxy are passed to
36370  the C++ instance transparently via C wrapper functions.</P>
36371 <P> This arrangement is asymmetric in the sense that no corresponding
36372  mechanism exists to pass method calls down the inheritance chain from
36373  C++ to PHP. In particular, if a C++ class has been extended in PHP (by
36374  extending the proxy class), these extensions will not be visible from
36375  C++ code. Virtual method calls from C++ are thus not able access the
36376  lowest implementation in the inheritance chain.</P>
36377 <P> Changes have been made to SWIG 1.3.18 to address this problem and
36378  make the relationship between C++ classes and proxy classes more
36379  symmetric. To achieve this goal, new classes called directors are
36380  introduced at the bottom of the C++ inheritance chain. Support for
36381  generating PHP classes has been added in SWIG 1.3.40. The job of the
36382  directors is to route method calls correctly, either to C++
36383  implementations higher in the inheritance chain or to PHP
36384  implementations lower in the inheritance chain. The upshot is that C++
36385  classes can be extended in PHP and from C++ these extensions look
36386  exactly like native C++ classes. Neither C++ code nor PHP code needs to
36387  know where a particular method is implemented: the combination of proxy
36388  classes, director classes, and C wrapper functions takes care of all
36389  the cross-language method routing transparently.</P>
36390 <H3><A name="Php_nn3_1"></A>29.3.1 Enabling directors</H3>
36391 <P> The director feature is disabled by default. To use directors you
36392  must make two changes to the interface file. First, add the &quot;directors&quot;
36393  option to the %module directive, like this:</P>
36394 <DIV class="code">
36395 <PRE>
36396 %module(directors=&quot;1&quot;) modulename
36397 </PRE>
36398 </DIV>
36399 <P> Without this option no director code will be generated. Second, you
36400  must use the %feature(&quot;director&quot;) directive to tell SWIG which classes
36401  and methods should get directors. The %feature directive can be applied
36402  globally, to specific classes, and to specific methods, like this:</P>
36403 <DIV class="code">
36404 <PRE>
36405 // generate directors for all classes that have virtual methods
36406 %feature(&quot;director&quot;);         
36407
36408 // generate directors for all virtual methods in class Foo
36409 %feature(&quot;director&quot;) Foo;      
36410
36411 // generate a director for just Foo::bar()
36412 %feature(&quot;director&quot;) Foo::bar; 
36413 </PRE>
36414 </DIV>
36415 <P> You can use the %feature(&quot;nodirector&quot;) directive to turn off
36416  directors for specific classes or methods. So for example,</P>
36417 <DIV class="code">
36418 <PRE>
36419 %feature(&quot;director&quot;) Foo;
36420 %feature(&quot;nodirector&quot;) Foo::bar;
36421 </PRE>
36422 </DIV>
36423 <P> will generate directors for all virtual methods of class Foo except
36424  bar().</P>
36425 <P> Directors can also be generated implicitly through inheritance. In
36426  the following, class Bar will get a director class that handles the
36427  methods one() and two() (but not three()):</P>
36428 <DIV class="code">
36429 <PRE>
36430 %feature(&quot;director&quot;) Foo;
36431 class Foo {
36432 public:
36433     Foo(int foo);
36434     virtual void one();
36435     virtual void two();
36436 };
36437
36438 class Bar: public Foo {
36439 public:
36440     virtual void three();
36441 };
36442 </PRE>
36443 </DIV>
36444 <P> then at the PHP side you can define</P>
36445 <DIV class="targetlang">
36446 <PRE>
36447 require(&quot;mymodule.php&quot;);
36448
36449 class MyFoo extends Foo {
36450   function one() {
36451      print &quot;one from php\n&quot;;
36452   }
36453 }
36454 </PRE>
36455 </DIV>
36456 <H3><A name="Php_nn3_2"></A>29.3.2 Director classes</H3>
36457 <P> For each class that has directors enabled, SWIG generates a new
36458  class that derives from both the class in question and a special <TT>
36459 Swig::Director</TT> class. These new classes, referred to as director
36460  classes, can be loosely thought of as the C++ equivalent of the PHP
36461  proxy classes. The director classes store a pointer to their underlying
36462  PHP object. Indeed, this is quite similar to the &quot;_cPtr&quot; and &quot;thisown&quot;
36463  members of the PHP proxy classes.</P>
36464 <P> For simplicity let's ignore the <TT>Swig::Director</TT> class and
36465  refer to the original C++ class as the director's base class. By
36466  default, a director class extends all virtual methods in the
36467  inheritance chain of its base class (see the preceding section for how
36468  to modify this behavior). Thus all virtual method calls, whether they
36469  originate in C++ or in PHP via proxy classes, eventually end up in at
36470  the implementation in the director class. The job of the director
36471  methods is to route these method calls to the appropriate place in the
36472  inheritance chain. By &quot;appropriate place&quot; we mean the method that would
36473  have been called if the C++ base class and its extensions in PHP were
36474  seamlessly integrated. That seamless integration is exactly what the
36475  director classes provide, transparently skipping over all the messy
36476  extension API glue that binds the two languages together.</P>
36477 <P> In reality, the &quot;appropriate place&quot; is one of only two
36478  possibilities: C++ or PHP. Once this decision is made, the rest is
36479  fairly easy. If the correct implementation is in C++, then the lowest
36480  implementation of the method in the C++ inheritance chain is called
36481  explicitly. If the correct implementation is in PHP, the Zend API is
36482  used to call the method of the underlying PHP object (after which the
36483  usual virtual method resolution in PHP automatically finds the right
36484  implementation).</P>
36485 <P> Now how does the director decide which language should handle the
36486  method call? The basic rule is to handle the method in PHP, unless
36487  there's a good reason not to. The reason for this is simple: PHP has
36488  the most &quot;extended&quot; implementation of the method. This assertion is
36489  guaranteed, since at a minimum the PHP proxy class implements the
36490  method. If the method in question has been extended by a class derived
36491  from the proxy class, that extended implementation will execute exactly
36492  as it should. If not, the proxy class will route the method call into a
36493  C wrapper function, expecting that the method will be resolved in C++.
36494  The wrapper will call the virtual method of the C++ instance, and since
36495  the director extends this the call will end up right back in the
36496  director method. Now comes the &quot;good reason not to&quot; part. If the
36497  director method were to blindly call the PHP method again, it would get
36498  stuck in an infinite loop. We avoid this situation by adding special
36499  code to the C wrapper function that tells the director method to not do
36500  this. The C wrapper function compares the called and the declaring
36501  class name of the given method. If these are not the same, then the C
36502  wrapper function tells the director to resolve the method by calling up
36503  the C++ inheritance chain, preventing an infinite loop.</P>
36504 <P> One more point needs to be made about the relationship between
36505  director classes and proxy classes. When a proxy class instance is
36506  created in PHP, SWIG creates an instance of the original C++ class and
36507  assigns it to <TT>-&gt;_cPtr</TT>. This is exactly what happens without
36508  directors and is true even if directors are enabled for the particular
36509  class in question. When a class<I> derived</I> from a proxy class is
36510  created, however, SWIG then creates an instance of the corresponding
36511  C++ director class. The reason for this difference is that user-defined
36512  subclasses may override or extend methods of the original class, so the
36513  director class is needed to route calls to these methods correctly. For
36514  unmodified proxy classes, all methods are ultimately implemented in C++
36515  so there is no need for the extra overhead involved with routing the
36516  calls through PHP.</P>
36517 <H3><A name="Php_nn3_3"></A>29.3.3 Ownership and object destruction</H3>
36518 <P> Memory management issues are slightly more complicated with
36519  directors than for proxy classes alone. PHP instances hold a pointer to
36520  the associated C++ director object, and the director in turn holds a
36521  pointer back to the PHP object. By default, proxy classes own their C++
36522  director object and take care of deleting it when they are garbage
36523  collected.</P>
36524 <P> This relationship can be reversed by calling the special <TT>
36525 -&gt;thisown</TT> property of the proxy class. After setting this property
36526  to <TT>0</TT>, the director class no longer destroys the PHP object.
36527  Assuming no outstanding references to the PHP object remain, the PHP
36528  object will be destroyed at the same time. This is a good thing, since
36529  directors and proxies refer to each other and so must be created and
36530  destroyed together. Destroying one without destroying the other will
36531  likely cause your program to segfault.</P>
36532 <P> Here is an example:</P>
36533 <DIV class="code">
36534 <PRE>
36535 class Foo {
36536 public:
36537     ...
36538 };
36539 class FooContainer {
36540 public:
36541     void addFoo(Foo *);
36542     ...
36543 };
36544 </PRE>
36545 </DIV>
36546 <BR><DIV class="targetlang">
36547 <PRE>
36548 $c = new FooContainer();
36549 $a = new Foo();
36550 $a-&gt;thisown = 0;
36551 $c-&gt;addFoo($a);
36552 </PRE>
36553 </DIV>
36554 <P> In this example, we are assuming that FooContainer will take care of
36555  deleting all the Foo pointers it contains at some point.</P>
36556 <H3><A name="Php_nn3_4"></A>29.3.4 Exception unrolling</H3>
36557 <P> With directors routing method calls to PHP, and proxies routing them
36558  to C++, the handling of exceptions is an important concern. By default,
36559  the directors ignore exceptions that occur during method calls that are
36560  resolved in PHP. To handle such exceptions correctly, it is necessary
36561  to temporarily translate them into C++ exceptions. This can be done
36562  with the %feature(&quot;director:except&quot;) directive. The following code
36563  should suffice in most cases:</P>
36564 <DIV class="code">
36565 <PRE>
36566 %feature(&quot;director:except&quot;) {
36567     if ($error == FAILURE) {
36568         throw Swig::DirectorMethodException();
36569     }
36570 }
36571 </PRE>
36572 </DIV>
36573 <P> This code will check the PHP error state after each method call from
36574  a director into PHP, and throw a C++ exception if an error occurred.
36575  This exception can be caught in C++ to implement an error handler.
36576  Currently no information about the PHP error is stored in the
36577  Swig::DirectorMethodException object, but this will likely change in
36578  the future.</P>
36579 <P> It may be the case that a method call originates in PHP, travels up
36580  to C++ through a proxy class, and then back into PHP via a director
36581  method. If an exception occurs in PHP at this point, it would be nice
36582  for that exception to find its way back to the original caller. This
36583  can be done by combining a normal %exception directive with the <TT>
36584 director:except</TT> handler shown above. Here is an example of a
36585  suitable exception handler:</P>
36586 <DIV class="code">
36587 <PRE>
36588 %exception {
36589     try { $action }
36590     catch (Swig::DirectorException &amp;e) { SWIG_fail; }
36591 }
36592 </PRE>
36593 </DIV>
36594 <P> The class Swig::DirectorException used in this example is actually a
36595  base class of Swig::DirectorMethodException, so it will trap this
36596  exception. Because the PHP error state is still set when
36597  Swig::DirectorMethodException is thrown, PHP will register the
36598  exception as soon as the C wrapper function returns.</P>
36599 <H3><A name="Php_nn3_5"></A>29.3.5 Overhead and code bloat</H3>
36600 <P> Enabling directors for a class will generate a new director method
36601  for every virtual method in the class' inheritance chain. This alone
36602  can generate a lot of code bloat for large hierarchies. Method
36603  arguments that require complex conversions to and from target language
36604  types can result in large director methods. For this reason it is
36605  recommended that you selectively enable directors only for specific
36606  classes that are likely to be extended in PHP and used in C++.</P>
36607 <P> Compared to classes that do not use directors, the call routing in
36608  the director methods does add some overhead. In particular, at least
36609  one dynamic cast and one extra function call occurs per method call
36610  from PHP. Relative to the speed of PHP execution this is probably
36611  completely negligible. For worst case routing, a method call that
36612  ultimately resolves in C++ may take one extra detour through PHP in
36613  order to ensure that the method does not have an extended PHP
36614  implementation. This could result in a noticeable overhead in some
36615  cases.</P>
36616 <P> Although directors make it natural to mix native C++ objects with
36617  PHP objects (as director objects) via a common base class pointer, one
36618  should be aware of the obvious fact that method calls to PHP objects
36619  will be much slower than calls to C++ objects. This situation can be
36620  optimized by selectively enabling director methods (using the %feature
36621  directive) for only those methods that are likely to be extended in
36622  PHP.</P>
36623 <H3><A name="Php_nn3_6"></A>29.3.6 Typemaps</H3>
36624 <P> Typemaps for input and output of most of the basic types from
36625  director classes have been written. These are roughly the reverse of
36626  the usual input and output typemaps used by the wrapper code. The
36627  typemap operation names are 'directorin', 'directorout', and
36628  'directorargout'. The director code does not currently use any of the
36629  other kinds of typemaps. It is not clear at this point which kinds are
36630  appropriate and need to be supported.</P>
36631 <H3><A name="Php_nn3_7"></A>29.3.7 Miscellaneous</H3>
36632 <P> Director typemaps for STL classes are mostly in place, and hence you
36633  should be able to use std::string, etc., as you would any other type.</P>
36634 <HR NOSHADE>
36635 <H1><A name="Pike"></A>30 SWIG and Pike</H1>
36636
36637 <!-- INDEX -->
36638 <DIV class="sectiontoc">
36639 <UL>
36640 <LI><A href="#Pike_nn2">Preliminaries</A>
36641 <UL>
36642 <LI><A href="#Pike_nn3">Running SWIG</A></LI>
36643 <LI><A href="#Pike_nn4">Getting the right header files</A></LI>
36644 <LI><A href="#Pike_nn5">Using your module</A></LI>
36645 </UL>
36646 </LI>
36647 <LI><A href="#Pike_nn6">Basic C/C++ Mapping</A>
36648 <UL>
36649 <LI><A href="#Pike_nn7">Modules</A></LI>
36650 <LI><A href="#Pike_nn8">Functions</A></LI>
36651 <LI><A href="#Pike_nn9">Global variables</A></LI>
36652 <LI><A href="#Pike_nn10">Constants and enumerated types</A></LI>
36653 <LI><A href="#Pike_nn11">Constructors and Destructors</A></LI>
36654 <LI><A href="#Pike_nn12">Static Members</A></LI>
36655 </UL>
36656 </LI>
36657 </UL>
36658 </DIV>
36659 <!-- INDEX -->
36660 <P> This chapter describes SWIG support for Pike. As of this writing,
36661  the SWIG Pike module is still under development and is not considered
36662  ready for prime time. The Pike module is being developed against the
36663  Pike 7.4.10 release and may not be compatible with previous versions of
36664  Pike.</P>
36665 <P> This chapter covers most SWIG features, but certain low-level
36666  details are covered in less depth than in earlier chapters. At the very
36667  least, make sure you read the &quot;<A href="#SWIG">SWIG Basics</A>&quot;
36668  chapter.
36669 <BR></P>
36670 <H2><A name="Pike_nn2"></A>30.1 Preliminaries</H2>
36671 <H3><A name="Pike_nn3"></A>30.1.1 Running SWIG</H3>
36672 <P> Suppose that you defined a SWIG module such as the following:</P>
36673 <DIV class="code">
36674 <PRE>%module example
36675 <BR>
36676 <BR>%{
36677 <BR>#include &quot;example.h&quot;
36678 <BR>%}
36679 <BR>
36680 <BR>int fact(int n);
36681 <BR></PRE>
36682 </DIV>
36683 <P> To build a C extension module for Pike, run SWIG using the <TT>-pike</TT>
36684  option :</P>
36685 <DIV class="code">
36686 <PRE>$ <B>swig -pike example.i</B>
36687 <BR></PRE>
36688 </DIV>
36689 <P> If you're building a C++ extension, be sure to add the <TT>-c++</TT>
36690  option:</P>
36691 <DIV class="code">
36692 <PRE>$ <B>swig -c++ -pike example.i</B>
36693 <BR></PRE>
36694 </DIV>
36695 <P> This creates a single source file named <TT>example_wrap.c</TT> (or <TT>
36696 example_wrap.cxx</TT>, if you ran SWIG with the <TT>-c++</TT> option).
36697  The SWIG-generated source file contains the low-level wrappers that
36698  need to be compiled and linked with the rest of your C/C++ application
36699  to create an extension module.</P>
36700 <P> The name of the wrapper file is derived from the name of the input
36701  file. For example, if the input file is <TT>example.i</TT>, the name of
36702  the wrapper file is <TT>example_wrap.c</TT>. To change this, you can
36703  use the <TT>-o</TT> option:</P>
36704 <DIV class="code">
36705 <PRE>$ <B>swig -pike -o pseudonym.c example.i</B>
36706 <BR></PRE>
36707 </DIV>
36708 <H3><A name="Pike_nn4"></A>30.1.2 Getting the right header files</H3>
36709 <P> In order to compile the C/C++ wrappers, the compiler needs to know
36710  the path to the Pike header files. These files are usually contained in
36711  a directory such as</P>
36712 <DIV class="code">
36713 <PRE>/usr/local/pike/7.4.10/include/pike
36714 <BR></PRE>
36715 </DIV>
36716 <P> There doesn't seem to be any way to get Pike itself to reveal the
36717  location of these files, so you may need to hunt around for them.
36718  You're looking for files with the names <TT>global.h</TT>, <TT>
36719 program.h</TT> and so on.</P>
36720 <H3><A name="Pike_nn5"></A>30.1.3 Using your module</H3>
36721 <P> To use your module, simply use Pike's <TT>import</TT> statement:</P>
36722 <DIV class="code">
36723 <PRE>
36724 $ <B>pike</B>
36725 Pike v7.4 release 10 running Hilfe v3.5 (Incremental Pike Frontend)
36726 &gt; <B>import example;</B>
36727 &gt; <B>fact(4);</B>
36728 (1) Result: 24
36729 </PRE>
36730 </DIV>
36731 <H2><A name="Pike_nn6"></A>30.2 Basic C/C++ Mapping</H2>
36732 <H3><A name="Pike_nn7"></A>30.2.1 Modules</H3>
36733 <P> All of the code for a given SWIG module is wrapped into a single
36734  Pike module. Since the name of the shared library that implements your
36735  module ultimately determines the module's name (as far as Pike is
36736  concerned), SWIG's <TT>%module</TT> directive doesn't really have any
36737  significance.</P>
36738 <H3><A name="Pike_nn8"></A>30.2.2 Functions</H3>
36739 <P> Global functions are wrapped as new Pike built-in functions. For
36740  example,</P>
36741 <DIV class="code">
36742 <PRE>
36743 %module example
36744
36745 int fact(int n);
36746 </PRE>
36747 </DIV>
36748 <P> creates a new built-in function <TT>example.fact(n)</TT> that works
36749  exactly as you'd expect it to:</P>
36750 <DIV class="code">
36751 <PRE>
36752 &gt; <B>import example;</B>
36753 &gt; <B>fact(4);</B>
36754 (1) Result: 24
36755 </PRE>
36756 </DIV>
36757 <H3><A name="Pike_nn9"></A>30.2.3 Global variables</H3>
36758 <P> Global variables are currently wrapped as a pair of of functions,
36759  one to get the current value of the variable and another to set it. For
36760  example, the declaration</P>
36761 <DIV class="code">
36762 <PRE>
36763 %module example
36764
36765 double Foo;
36766 </PRE>
36767 </DIV>
36768 <P> will result in two functions, <TT>Foo_get()</TT> and <TT>Foo_set()</TT>
36769 :</P>
36770 <DIV class="code">
36771 <PRE>
36772 &gt; <B>import example;</B>
36773 &gt; <B>Foo_get();</B>
36774 (1) Result: 3.000000
36775 &gt; <B>Foo_set(3.14159);</B>
36776 (2) Result: 0
36777 &gt; <B>Foo_get();</B>
36778 (3) Result: 3.141590
36779 </PRE>
36780 </DIV>
36781 <H3><A name="Pike_nn10"></A>30.2.4 Constants and enumerated types</H3>
36782 <P> Enumerated types in C/C++ declarations are wrapped as Pike
36783  constants, not as Pike enums.</P>
36784 <H3><A name="Pike_nn11"></A>30.2.5 Constructors and Destructors</H3>
36785 <P> Constructors are wrapped as <TT>create()</TT> methods, and
36786  destructors are wrapped as <TT>destroy()</TT> methods, for Pike
36787  classes.</P>
36788 <H3><A name="Pike_nn12"></A>30.2.6 Static Members</H3>
36789 <P> Since Pike doesn't support static methods or data for Pike classes,
36790  static member functions in your C++ classes are wrapped as regular
36791  functions and static member variables are wrapped as pairs of functions
36792  (one to get the value of the static member variable, and another to set
36793  it). The names of these functions are prepended with the name of the
36794  class. For example, given this C++ class declaration:</P>
36795 <DIV class="code">
36796 <PRE>
36797 class Shape
36798 {
36799 public:
36800     static void print();
36801     static int nshapes;
36802 };
36803 </PRE>
36804 </DIV>
36805 <P> SWIG will generate a <TT>Shape_print()</TT> method that invokes the
36806  static <TT>Shape::print()</TT> member function, as well as a pair of
36807  methods, <TT>Shape_nshapes_get()</TT> and <TT>Shape_nshapes_set()</TT>,
36808  to get and set the value of <TT>Shape::nshapes</TT>.</P>
36809 <HR NOSHADE>
36810 <H1><A name="Python"></A>31 SWIG and Python</H1>
36811
36812 <!-- INDEX -->
36813 <DIV class="sectiontoc">
36814 <UL>
36815 <LI><A href="#Python_nn2">Overview</A></LI>
36816 <LI><A href="#Python_nn3">Preliminaries</A>
36817 <UL>
36818 <LI><A href="#Python_nn4">Running SWIG</A></LI>
36819 <LI><A href="#Python_nn6">Using distutils</A></LI>
36820 <LI><A href="#Python_nn7">Hand compiling a dynamic module</A></LI>
36821 <LI><A href="#Python_nn8">Static linking</A></LI>
36822 <LI><A href="#Python_nn9">Using your module</A></LI>
36823 <LI><A href="#Python_nn10">Compilation of C++ extensions</A></LI>
36824 <LI><A href="#Python_nn11">Compiling for 64-bit platforms</A></LI>
36825 <LI><A href="#Python_nn12">Building Python Extensions under Windows</A></LI>
36826 </UL>
36827 </LI>
36828 <LI><A href="#Python_nn13">A tour of basic C/C++ wrapping</A>
36829 <UL>
36830 <LI><A href="#Python_nn14">Modules</A></LI>
36831 <LI><A href="#Python_nn15">Functions</A></LI>
36832 <LI><A href="#Python_nn16">Global variables</A></LI>
36833 <LI><A href="#Python_nn17">Constants and enums</A></LI>
36834 <LI><A href="#Python_nn18">Pointers</A></LI>
36835 <LI><A href="#Python_nn19">Structures</A></LI>
36836 <LI><A href="#Python_nn20">C++ classes</A></LI>
36837 <LI><A href="#Python_nn21">C++ inheritance</A></LI>
36838 <LI><A href="#Python_nn22">Pointers, references, values, and arrays</A></LI>
36839 <LI><A href="#Python_nn23">C++ overloaded functions</A></LI>
36840 <LI><A href="#Python_nn24">C++ operators</A></LI>
36841 <LI><A href="#Python_nn25">C++ namespaces</A></LI>
36842 <LI><A href="#Python_nn26">C++ templates</A></LI>
36843 <LI><A href="#Python_nn27">C++ Smart Pointers</A></LI>
36844 <LI><A href="#Python_nn27a">C++ Reference Counted Objects (ref/unref)</A>
36845 </LI>
36846 </UL>
36847 </LI>
36848 <LI><A href="#Python_nn28">Further details on the Python class interface</A>
36849 <UL>
36850 <LI><A href="#Python_nn29">Proxy classes</A></LI>
36851 <LI><A href="#Python_nn30">Memory management</A></LI>
36852 <LI><A href="#Python_nn31">Python 2.2 and classic classes</A></LI>
36853 </UL>
36854 </LI>
36855 <LI><A href="#Python_directors">Cross language polymorphism</A>
36856 <UL>
36857 <LI><A href="#Python_nn33">Enabling directors</A></LI>
36858 <LI><A href="#Python_nn34">Director classes</A></LI>
36859 <LI><A href="#Python_nn35">Ownership and object destruction</A></LI>
36860 <LI><A href="#Python_nn36">Exception unrolling</A></LI>
36861 <LI><A href="#Python_nn37">Overhead and code bloat</A></LI>
36862 <LI><A href="#Python_nn38">Typemaps</A></LI>
36863 <LI><A href="#Python_nn39">Miscellaneous</A></LI>
36864 </UL>
36865 </LI>
36866 <LI><A href="#Python_nn40">Common customization features</A>
36867 <UL>
36868 <LI><A href="#Python_nn41">C/C++ helper functions</A></LI>
36869 <LI><A href="#Python_nn42">Adding additional Python code</A></LI>
36870 <LI><A href="#Python_nn43">Class extension with %extend</A></LI>
36871 <LI><A href="#Python_nn44">Exception handling with %exception</A></LI>
36872 </UL>
36873 </LI>
36874 <LI><A href="#Python_nn45">Tips and techniques</A>
36875 <UL>
36876 <LI><A href="#Python_nn46">Input and output parameters</A></LI>
36877 <LI><A href="#Python_nn47">Simple pointers</A></LI>
36878 <LI><A href="#Python_nn48">Unbounded C Arrays</A></LI>
36879 <LI><A href="#Python_nn49">String handling</A></LI>
36880 <LI><A href="#Python_nn50">Arrays</A></LI>
36881 <LI><A href="#Python_nn51">String arrays</A></LI>
36882 <LI><A href="#Python_nn52">STL wrappers</A></LI>
36883 </UL>
36884 </LI>
36885 <LI><A href="#Python_nn53">Typemaps</A>
36886 <UL>
36887 <LI><A href="#Python_nn54">What is a typemap?</A></LI>
36888 <LI><A href="#Python_nn55">Python typemaps</A></LI>
36889 <LI><A href="#Python_nn56">Typemap variables</A></LI>
36890 <LI><A href="#Python_nn57">Useful Python Functions</A></LI>
36891 </UL>
36892 </LI>
36893 <LI><A href="#Python_nn58">Typemap Examples</A>
36894 <UL>
36895 <LI><A href="#Python_nn59">Converting Python list to a char **</A></LI>
36896 <LI><A href="#Python_nn60">Expanding a Python object into multiple
36897  arguments</A></LI>
36898 <LI><A href="#Python_nn61">Using typemaps to return arguments</A></LI>
36899 <LI><A href="#Python_nn62">Mapping Python tuples into small arrays</A></LI>
36900 <LI><A href="#Python_nn63">Mapping sequences to C arrays</A></LI>
36901 <LI><A href="#Python_nn64">Pointer handling</A></LI>
36902 </UL>
36903 </LI>
36904 <LI><A href="#Python_nn65">Docstring Features</A>
36905 <UL>
36906 <LI><A href="#Python_nn66">Module docstring</A></LI>
36907 <LI><A href="#Python_nn67">%feature(&quot;autodoc&quot;)</A>
36908 <UL>
36909 <LI><A href="#Python_nn68">%feature(&quot;autodoc&quot;, &quot;0&quot;)</A></LI>
36910 <LI><A href="#Python_nn69">%feature(&quot;autodoc&quot;, &quot;1&quot;)</A></LI>
36911 <LI><A href="#Python_nn70">%feature(&quot;autodoc&quot;, &quot;docstring&quot;)</A></LI>
36912 </UL>
36913 </LI>
36914 <LI><A href="#Python_nn71">%feature(&quot;docstring&quot;)</A></LI>
36915 </UL>
36916 </LI>
36917 <LI><A href="#Python_nn72">Python Packages</A></LI>
36918 <LI><A href="#Python_python3support">Python 3 Support</A>
36919 <UL>
36920 <LI><A href="#Python_nn74">Function annotation</A></LI>
36921 <LI><A href="#Python_nn75">Buffer interface</A></LI>
36922 <LI><A href="#Python_nn76">Abstract base classes</A></LI>
36923 </UL>
36924 </LI>
36925 </UL>
36926 </DIV>
36927 <!-- INDEX -->
36928 <P><B> Caution: This chapter is under repair!</B></P>
36929 <P> This chapter describes SWIG's support of Python. SWIG is compatible
36930  with most recent Python versions including Python 3.0 and Python 2.6,
36931  as well as older versions dating back to Python 2.0. For the best
36932  results, consider using Python 2.3 or newer.</P>
36933 <P> This chapter covers most SWIG features, but certain low-level
36934  details are covered in less depth than in earlier chapters. At the very
36935  least, make sure you read the &quot;<A href="#SWIG">SWIG Basics</A>&quot;
36936  chapter.</P>
36937 <H2><A name="Python_nn2"></A>31.1 Overview</H2>
36938 <P> To build Python extension modules, SWIG uses a layered approach in
36939  which parts of the extension module are defined in C and other parts
36940  are defined in Python. The C layer contains low-level wrappers whereas
36941  Python code is used to define high-level features.</P>
36942 <P> This layered approach recognizes the fact that certain aspects of
36943  extension building are better accomplished in each language (instead of
36944  trying to do everything in C or C++). Furthermore, by generating code
36945  in both languages, you get a lot more flexibility since you can enhance
36946  the extension module with support code in either language.</P>
36947 <P> In describing the Python interface, this chapter starts by covering
36948  the basics of configuration, compiling, and installing Python modules.
36949  Next, the Python interface to common C and C++ programming features is
36950  described. Advanced customization features such as typemaps are then
36951  described followed by a discussion of low-level implementation details.</P>
36952 <H2><A name="Python_nn3"></A>31.2 Preliminaries</H2>
36953 <H3><A name="Python_nn4"></A>31.2.1 Running SWIG</H3>
36954 <P> Suppose that you defined a SWIG module such as the following:</P>
36955 <DIV class="code">
36956 <PRE>
36957 /* File: example.i */
36958 %module example
36959
36960 %{
36961 #define SWIG_FILE_WITH_INIT
36962 #include &quot;example.h&quot;
36963 %}
36964
36965 int fact(int n);
36966 </PRE>
36967 </DIV>
36968 <P> The <TT>#define SWIG_FILE_WITH_INIT</TT> line inserts a macro that
36969  specifies that the resulting C file should be built as a python
36970  extension, inserting the module <TT>init</TT> code. This <TT>.i</TT>
36971  file wraps the following simple C file:</P>
36972 <DIV class="code">
36973 <PRE>
36974 /* File: example.c */
36975
36976 #include &quot;example.h&quot;
36977
36978 int fact(int n) {
36979     if (n &lt; 0){ /* This should probably return an error, but this is simpler */
36980         return 0;
36981     }
36982     if (n == 0) {
36983         return 1;
36984     }
36985     else {
36986         /* testing for overflow would be a good idea here */
36987         return n * fact(n-1);
36988     }
36989 }
36990
36991 </PRE>
36992 </DIV>
36993 <P> With the header file:</P>
36994 <DIV class="code">
36995 <PRE>
36996 /* File: example.h */
36997
36998 int fact(int n);
36999 </PRE>
37000 </DIV>
37001 <P> To build a Python module, run SWIG using the <TT>-python</TT>
37002  option:</P>
37003 <DIV class="shell">
37004 <PRE>
37005 $ swig -python example.i
37006 </PRE>
37007 </DIV>
37008 <P> If building a C++ extension, add the <TT>-c++</TT> option:</P>
37009 <DIV class="shell">
37010 <PRE>
37011 $ swig -c++ -python example.i
37012 </PRE>
37013 </DIV>
37014 <P> This creates two different files; a C/C++ source file <TT>
37015 example_wrap.c</TT> or <TT>example_wrap.cxx</TT> and a Python source
37016  file <TT>example.py</TT>. The generated C source file contains the
37017  low-level wrappers that need to be compiled and linked with the rest of
37018  your C/C++ application to create an extension module. The Python source
37019  file contains high-level support code. This is the file that you will
37020  import to use the module.</P>
37021 <P> The name of the wrapper file is derived from the name of the input
37022  file. For example, if the input file is <TT>example.i</TT>, the name of
37023  the wrapper file is <TT>example_wrap.c</TT>. To change this, you can
37024  use the <TT>-o</TT> option. The name of the Python file is derived from
37025  the module name specified with <TT>%module</TT>. If the module name is <TT>
37026 example</TT>, then a file <TT>example.py</TT> is created.</P>
37027 <P> The following sections have further practical examples and details
37028  on how you might go about compiling and using the generated files.</P>
37029 <H3><A name="Python_nn6"></A>31.2.2 Using distutils</H3>
37030 <P> The preferred approach to building an extension module for python is
37031  to compile it with distutils, which comes with all recent versions of
37032  python (<A href="http://docs.python.org/dist/dist.html">Distutils Docs</A>
37033 ).</P>
37034 <P> Distutils takes care of making sure that your extension is built
37035  with all the correct flags, headers, etc. for the version of Python it
37036  is run with. Distutils will compile your extension into a shared object
37037  file or DLL (<TT>.so</TT> on Linux, <TT>.pyd</TT> on Windows, etc). In
37038  addition, distutils can handle installing your package into
37039  site-packages, if that is desired. A configuration file (conventionally
37040  called: <TT>setup.py</TT>) describes the extension (and related python
37041  modules). The distutils will then generate all the right compiler
37042  directives to build it for you.</P>
37043 <P> Here is a sample <TT>setup.py</TT> file for the above example:</P>
37044 <DIV class="code">
37045 <PRE>
37046 #!/usr/bin/env python
37047
37048 &quot;&quot;&quot;
37049 setup.py file for SWIG example
37050 &quot;&quot;&quot;
37051
37052 from distutils.core import setup, Extension
37053
37054
37055 example_module = Extension('_example',
37056                            sources=['example_wrap.c', 'example.c'],
37057                            )
37058
37059 setup (name = 'example',
37060        version = '0.1',
37061        author      = &quot;SWIG Docs&quot;,
37062        description = &quot;&quot;&quot;Simple swig example from docs&quot;&quot;&quot;,
37063        ext_modules = [example_module],
37064        py_modules = [&quot;example&quot;],
37065        )
37066 </PRE>
37067 </DIV>
37068 <P> In this example, the line: <TT>example_module = Extension(....)</TT>
37069  creates an Extension module object, defining the name as <TT>_example</TT>
37070 , and using the source code files: <TT>example_wrap.c</TT>, generated by
37071  swig, and <TT>example.c</TT>, your original c source. The swig (and
37072  other python extension modules) tradition is for the compiled extension
37073  to have the name of the python portion, prefixed by an underscore. If
37074  the name of your python module is &quot;<TT>example.py</TT>&quot;, then the name
37075  of the corresponding object file will be&quot;<TT>_example.so</TT>&quot;</P>
37076 <P> The <TT>setup</TT> call then sets up distutils to build your
37077  package, defining some meta data, and passing in your extension module
37078  object. Once this is saved as <TT>setup.py</TT>, you can build your
37079  extension with these commands:</P>
37080 <DIV class="shell">
37081 <PRE>
37082 $ swig -python example.i
37083 $ python setup.py build_ext --inplace
37084 </PRE>
37085 </DIV>
37086 <P> And a .so, or .pyd or... will be created for you. It will build a
37087  version that matches the python that you run the command with. Taking
37088  apart the command line:</P>
37089 <UL>
37090 <LI> <TT>python</TT> -- the version of python you want to build for</LI>
37091 <LI> <TT>setup.py</TT> -- the name of your setup script (it can be
37092  called anything, but setup.py is the tradition)</LI>
37093 <LI> <TT>build_ext</TT> -- telling distutils to build extensions</LI>
37094 <LI> <TT>--inplace</TT> -- this tells distutils to put the extension lib
37095  in the current dir. Otherwise, it will put it inside a build hierarchy,
37096  and you'd have to move it to use it.</LI>
37097 </UL>
37098 <P> The distutils have many other features, consult the python distutils
37099  docs for details.</P>
37100 <P> This same approach works on all platforms if the appropriate
37101  compiler is installed. (it can even build extensions to the standard
37102  Windows Python using MingGW)</P>
37103 <H3><A name="Python_nn7"></A>31.2.3 Hand compiling a dynamic module</H3>
37104 <P> While the preferred approach to building an extension module is to
37105  use the distutils, some people like to integrate building extensions
37106  with a larger build system, and thus may wish to compile their modules
37107  without the distutils. To do this, you need to compile your program
37108  using commands like this (shown for Linux):</P>
37109 <DIV class="shell">
37110 <PRE>
37111 $ swig -python example.i
37112 $ gcc -O2 -fPIC -c example.c
37113 $ gcc -O2 -fPIC -c example_wrap.c -I/usr/local/include/python2.5
37114 $ gcc -shared example.o example_wrap.o -o _example.so
37115 </PRE>
37116 </DIV>
37117 <P> The exact commands for doing this vary from platform to platform.
37118  However, SWIG tries to guess the right options when it is installed.
37119  Therefore, you may want to start with one of the examples in the <TT>
37120 SWIG/Examples/python</TT> directory. If that doesn't work, you will need
37121  to read the man-pages for your compiler and linker to get the right set
37122  of options. You might also check the <A href="http://www.dabeaz.com/cgi-bin/wiki.pl">
37123 SWIG Wiki</A> for additional information.</P>
37124 <P> When linking the module,<B> the name of the output file has to match
37125  the name of the module prefixed by an underscore</B>. If the name of
37126  your module is &quot;<TT>example</TT>&quot;, then the name of the corresponding
37127  object file should be &quot;<TT>_example.so</TT>&quot; or &quot;<TT>_examplemodule.so</TT>
37128 &quot;. The name of the module is specified using the <TT>%module</TT>
37129  directive or the <TT>-module</TT> command line option.</P>
37130 <P><B> Compatibility Note:</B> In SWIG-1.3.13 and earlier releases,
37131  module names did not include the leading underscore. This is because
37132  modules were normally created as C-only extensions without the extra
37133  Python support file (instead, creating Python code was supported as an
37134  optional feature). This has been changed in SWIG-1.3.14 and is
37135  consistent with other Python extension modules. For example, the <TT>
37136 socket</TT> module actually consists of two files; <TT>socket.py</TT>
37137  and <TT>_socket.so</TT>. Many other built-in Python modules follow a
37138  similar convention.</P>
37139 <H3><A name="Python_nn8"></A>31.2.4 Static linking</H3>
37140 <P> An alternative approach to dynamic linking is to rebuild the Python
37141  interpreter with your extension module added to it. In the past, this
37142  approach was sometimes necessary due to limitations in dynamic loading
37143  support on certain machines. However, the situation has improved
37144  greatly over the last few years and you should not consider this
37145  approach unless there is really no other option.</P>
37146 <P> The usual procedure for adding a new module to Python involves
37147  finding the Python source, adding an entry to the <TT>Modules/Setup</TT>
37148  file, and rebuilding the interpreter using the Python Makefile.
37149  However, newer Python versions have changed the build process. You may
37150  need to edit the 'setup.py' file in the Python distribution instead.</P>
37151 <P> In earlier versions of SWIG, the <TT>embed.i</TT> library file could
37152  be used to rebuild the interpreter. For example:</P>
37153 <DIV class="code">
37154 <PRE>
37155 %module example
37156
37157 %inline %{
37158 extern int fact(int);
37159 extern int mod(int, int);
37160 extern double My_variable;
37161 %}
37162
37163 %include &quot;embed.i&quot;       // Include code for a static version of Python
37164
37165 </PRE>
37166 </DIV>
37167 <P> The <TT>embed.i</TT> library file includes supporting code that
37168  contains everything needed to rebuild Python. To rebuild the
37169  interpreter, you simply do something like this:</P>
37170 <DIV class="shell">
37171 <PRE>
37172 $ swig -python example.i
37173 $ gcc example.c example_wrap.c \
37174         -Xlinker -export-dynamic \
37175         -DHAVE_CONFIG_H -I/usr/local/include/python2.1 \
37176         -I/usr/local/lib/python2.1/config \
37177         -L/usr/local/lib/python2.1/config -lpython2.1 -lm -ldl \
37178         -o mypython
37179
37180 </PRE>
37181 </DIV>
37182 <P> You will need to supply the same libraries that were used to build
37183  Python the first time. This may include system libraries such as <TT>
37184 -lsocket</TT>, <TT>-lnsl</TT>, and <TT>-lpthread</TT>. Assuming this
37185  actually works, the new version of Python should be identical to the
37186  default version except that your extension module will be a built-in
37187  part of the interpreter.</P>
37188 <P><B> Comment:</B> In practice, you should probably try to avoid static
37189  linking if possible. Some programmers may be inclined to use static
37190  linking in the interest of getting better performance. However, the
37191  performance gained by static linking tends to be rather minimal in most
37192  situations (and quite frankly not worth the extra hassle in the opinion
37193  of this author).</P>
37194 <P><B> Compatibility note:</B> The <TT>embed.i</TT> library file is
37195  deprecated and has not been maintained for several years. Even though
37196  it appears to &quot;work&quot; with Python 2.1, no future support is guaranteed.
37197  If using static linking, you might want to rely on a different approach
37198  (perhaps using distutils).</P>
37199 <H3><A name="Python_nn9"></A>31.2.5 Using your module</H3>
37200 <P> To use your module, simply use the Python <TT>import</TT> statement.
37201  If all goes well, you will be able to this:</P>
37202 <DIV class="targetlang">
37203 <PRE>
37204 $ python
37205 &gt;&gt;&gt; import example
37206 &gt;&gt;&gt; example.fact(4)
37207 24
37208 &gt;&gt;&gt;
37209 </PRE>
37210 </DIV>
37211 <P> A common error received by first-time users is the following:</P>
37212 <DIV class="targetlang">
37213 <PRE>
37214 &gt;&gt;&gt; import example
37215 Traceback (most recent call last):
37216   File &quot;&lt;stdin&gt;&quot;, line 1, in ?
37217   File &quot;example.py&quot;, line 2, in ?
37218     import _example
37219 ImportError: No module named _example
37220 </PRE>
37221 </DIV>
37222 <P> If you get this message, it means that you either forgot to compile
37223  the wrapper code into an extension module or you didn't give the
37224  extension module the right name. Make sure that you compiled the
37225  wrappers into a module called <TT>_example.so</TT>. And don't forget
37226  the leading underscore (_).</P>
37227 <P> Another possible error is the following:</P>
37228 <DIV class="targetlang">
37229 <PRE>
37230 &gt;&gt;&gt; import example
37231 Traceback (most recent call last):
37232   File &quot;&lt;stdin&gt;&quot;, line 1, in ?
37233 ImportError: dynamic module does not define init function (init_example)
37234 &gt;&gt;&gt;                                                               
37235 </PRE>
37236 </DIV>
37237 <P> This error is almost always caused when a bad name is given to the
37238  shared object file. For example, if you created a file <TT>example.so</TT>
37239  instead of <TT>_example.so</TT> you would get this error.
37240  Alternatively, this error could arise if the name of the module is
37241  inconsistent with the module name supplied with the <TT>%module</TT>
37242  directive. Double-check the interface to make sure the module name and
37243  the shared object filename match. Another possible cause of this error
37244  is forgetting to link the SWIG-generated wrapper code with the rest of
37245  your application when creating the extension module.</P>
37246 <P> Another common error is something similar to the following:</P>
37247 <DIV class="targetlang">
37248 <PRE>
37249 Traceback (most recent call last):
37250   File &quot;example.py&quot;, line 3, in ?
37251     import example
37252 ImportError: ./_example.so: undefined symbol: fact
37253 </PRE>
37254 </DIV>
37255 <P> This error usually indicates that you forgot to include some object
37256  files or libraries in the linking of the shared library file. Make sure
37257  you compile both the SWIG wrapper file and your original program into a
37258  shared library file. Make sure you pass all of the required libraries
37259  to the linker.</P>
37260 <P> Sometimes unresolved symbols occur because a wrapper has been
37261  created for a function that doesn't actually exist in a library. This
37262  usually occurs when a header file includes a declaration for a function
37263  that was never actually implemented or it was removed from a library
37264  without updating the header file. To fix this, you can either edit the
37265  SWIG input file to remove the offending declaration or you can use the <TT>
37266 %ignore</TT> directive to ignore the declaration.</P>
37267 <P> Finally, suppose that your extension module is linked with another
37268  library like this:</P>
37269 <DIV class="shell">
37270 <PRE>
37271 $ gcc -shared example.o example_wrap.o -L/home/beazley/projects/lib <B>-lfoo</B> \
37272       -o _example.so
37273 </PRE>
37274 </DIV>
37275 <P> If the <TT>foo</TT> library is compiled as a shared library, you
37276  might encounter the following problem when you try to use your module:</P>
37277 <DIV class="targetlang">
37278 <PRE>
37279 &gt;&gt;&gt; import example
37280 Traceback (most recent call last):
37281   File &quot;&lt;stdin&gt;&quot;, line 1, in ?
37282 ImportError: libfoo.so: cannot open shared object file: No such file or directory
37283 &gt;&gt;&gt;                 
37284 </PRE>
37285 </DIV>
37286 <P> This error is generated because the dynamic linker can't locate the <TT>
37287 libfoo.so</TT> library. When shared libraries are loaded, the system
37288  normally only checks a few standard locations such as <TT>/usr/lib</TT>
37289  and <TT>/usr/local/lib</TT>. To fix this problem, there are several
37290  things you can do. First, you can recompile your extension module with
37291  extra path information. For example, on Linux you can do this:</P>
37292 <DIV class="shell">
37293 <PRE>
37294 $ gcc -shared example.o example_wrap.o -L/home/beazley/projects/lib -lfoo \
37295       <B>-Xlinker -rpath /home/beazley/projects/lib </B> \
37296       -o _example.so
37297 </PRE>
37298 </DIV>
37299 <P> Alternatively, you can set the <TT>LD_LIBRARY_PATH</TT> environment
37300  variable to include the directory with your shared libraries. If
37301  setting <TT>LD_LIBRARY_PATH</TT>, be aware that setting this variable
37302  can introduce a noticeable performance impact on all other applications
37303  that you run. To set it only for Python, you might want to do this
37304  instead:</P>
37305 <DIV class="shell">
37306 <PRE>
37307 $ env LD_LIBRARY_PATH=/home/beazley/projects/lib python
37308 </PRE>
37309 </DIV>
37310 <P> Finally, you can use a command such as <TT>ldconfig</TT> (Linux) or <TT>
37311 crle</TT> (Solaris) to add additional search paths to the default system
37312  configuration (this requires root access and you will need to read the
37313  man pages).</P>
37314 <H3><A name="Python_nn10"></A>31.2.6 Compilation of C++ extensions</H3>
37315 <P> Compilation of C++ extensions has traditionally been a tricky
37316  problem. Since the Python interpreter is written in C, you need to take
37317  steps to make sure C++ is properly initialized and that modules are
37318  compiled correctly. This should be a non-issue if you're using
37319  distutils, as it takes care of all that for you. The following is
37320  included for historical reasons, and in case you need to compile on
37321  your own.</P>
37322 <P> On most machines, C++ extension modules should be linked using the
37323  C++ compiler. For example:</P>
37324 <DIV class="shell">
37325 <PRE>
37326 $ swig -c++ -python example.i
37327 $ g++ -O2 -fPIC -c example.cxx
37328 $ g++ -O2 -fPIC -c example_wrap.cxx -I/usr/local/include/python2.5
37329 $ g++ -shared example.o example_wrap.o -o _example.so
37330 </PRE>
37331 </DIV>
37332 <P> The -fPIC option tells GCC to generate position-independent code
37333  (PIC) which is required for most architectures (it's not vital on x86,
37334  but still a good idea as it allows code pages from the library to be
37335  shared between processes). Other compilers may need a different option
37336  specified instead of -fPIC.</P>
37337 <P> In addition to this, you may need to include additional library
37338  files to make it work. For example, if you are using the Sun C++
37339  compiler on Solaris, you often need to add an extra library <TT>-lCrun</TT>
37340  like this:</P>
37341 <DIV class="shell">
37342 <PRE>
37343 $ swig -c++ -python example.i
37344 $ CC -c example.cxx
37345 $ CC -c example_wrap.cxx -I/usr/local/include/python2.5
37346 $ CC -G example.o example_wrap.o -L/opt/SUNWspro/lib -o _example.so -lCrun
37347 </PRE>
37348 </DIV>
37349 <P> Of course, the extra libraries to use are completely
37350  non-portable---you will probably need to do some experimentation.</P>
37351 <P> Sometimes people have suggested that it is necessary to relink the
37352  Python interpreter using the C++ compiler to make C++ extension modules
37353  work. In the experience of this author, this has never actually
37354  appeared to be necessary. Relinking the interpreter with C++ really
37355  only includes the special run-time libraries described above---as long
37356  as you link your extension modules with these libraries, it should not
37357  be necessary to rebuild Python.</P>
37358 <P> If you aren't entirely sure about the linking of a C++ extension,
37359  you might look at an existing C++ program. On many Unix machines, the <TT>
37360 ldd</TT> command will list library dependencies. This should give you
37361  some clues about what you might have to include when you link your
37362  extension module. For example:</P>
37363 <DIV class="shell">
37364 <PRE>
37365 $ ldd swig
37366         libstdc++-libc6.1-1.so.2 =&gt; /usr/lib/libstdc++-libc6.1-1.so.2 (0x40019000)
37367         libm.so.6 =&gt; /lib/libm.so.6 (0x4005b000)
37368         libc.so.6 =&gt; /lib/libc.so.6 (0x40077000)
37369         /lib/ld-linux.so.2 =&gt; /lib/ld-linux.so.2 (0x40000000)
37370 </PRE>
37371 </DIV>
37372 <P> As a final complication, a major weakness of C++ is that it does not
37373  define any sort of standard for binary linking of libraries. This means
37374  that C++ code compiled by different compilers will not link together
37375  properly as libraries nor is the memory layout of classes and data
37376  structures implemented in any kind of portable manner. In a monolithic
37377  C++ program, this problem may be unnoticed. However, in Python, it is
37378  possible for different extension modules to be compiled with different
37379  C++ compilers. As long as these modules are self-contained, this
37380  probably won't matter. However, if these modules start sharing data,
37381  you will need to take steps to avoid segmentation faults and other
37382  erratic program behavior. If working with lots of software components,
37383  you might want to investigate using a more formal standard such as COM.</P>
37384 <H3><A name="Python_nn11"></A>31.2.7 Compiling for 64-bit platforms</H3>
37385 <P> On platforms that support 64-bit applications (Solaris, Irix, etc.),
37386  special care is required when building extension modules. On these
37387  machines, 64-bit applications are compiled and linked using a different
37388  set of compiler/linker options. In addition, it is not generally
37389  possible to mix 32-bit and 64-bit code together in the same
37390  application.</P>
37391 <P> To utilize 64-bits, the Python executable will need to be recompiled
37392  as a 64-bit application. In addition, all libraries, wrapper code, and
37393  every other part of your application will need to be compiled for
37394  64-bits. If you plan to use other third-party extension modules, they
37395  will also have to be recompiled as 64-bit extensions.</P>
37396 <P> If you are wrapping commercial software for which you have no source
37397  code, you will be forced to use the same linking standard as used by
37398  that software. This may prevent the use of 64-bit extensions. It may
37399  also introduce problems on platforms that support more than one linking
37400  standard (e.g., -o32 and -n32 on Irix).</P>
37401 <P> On the Linux x86_64 platform (Opteron or EM64T), besides of the
37402  required compiler option -fPIC discussed above, you will need to be
37403  careful about the libraries you link with or the library path you use.
37404  In general, a Linux distribution will have two set of libraries, one
37405  for native x86_64 programs (under /usr/lib64), and another for 32 bits
37406  compatibility (under /usr/lib). Also, the compiler options -m32 and
37407  -m64 allow you to choose the desired binary format for your python
37408  extension.</P>
37409 <H3><A name="Python_nn12"></A>31.2.8 Building Python Extensions under
37410  Windows</H3>
37411 <P> Building a SWIG extension to Python under Windows is roughly similar
37412  to the process used with Unix. Using the distutils, it is essentially
37413  identical. If you have the same version of the MS compiler that Python
37414  was built with (the python2.4 and python2.5 distributed by python.org
37415  are built with Visual Studio 2003), the standard <TT>python setup.py
37416  build</TT> should just work.</P>
37417 <P> As of python2.5, the distutils support building extensions with
37418  MingGW out of the box. Following the instruction here: <A href="http://boodebr.org/main/python/build-windows-extensions">
37419 Building Python extensions for Windows with only free tools</A> should
37420  get you started.</P>
37421 <P> If you need to build it on your own, the following notes are
37422  provided:</P>
37423 <P> You will need to create a DLL that can be loaded into the
37424  interpreter. This section briefly describes the use of SWIG with
37425  Microsoft Visual C++. As a starting point, many of SWIG's examples
37426  include project files. You might want to take a quick look at these in
37427  addition to reading this section.</P>
37428 <P> In Developer Studio, SWIG should be invoked as a custom build
37429  option. This is usually done as follows:</P>
37430 <UL>
37431 <LI>Open up a new workspace and use the AppWizard to select a DLL
37432  project.</LI>
37433 <LI>Add both the SWIG interface file (the .i file), any supporting C
37434  files, and the name of the wrapper file that will be created by SWIG
37435  (ie. <TT>example_wrap.c</TT>). Note : If using C++, choose a different
37436  suffix for the wrapper file such as <TT>example_wrap.cxx</TT>. Don't
37437  worry if the wrapper file doesn't exist yet--Developer Studio keeps a
37438  reference to it.</LI>
37439 <LI>Select the SWIG interface file and go to the settings menu. Under
37440  settings, select the &quot;Custom Build&quot; option.</LI>
37441 <LI>Enter &quot;SWIG&quot; in the description field.</LI>
37442 <LI>Enter &quot;<TT>swig -python -o $(ProjDir)\$(InputName)_wrap.c
37443  $(InputPath)</TT>&quot; in the &quot;Build command(s) field&quot;</LI>
37444 <LI>Enter &quot;<TT>$(ProjDir)\$(InputName)_wrap.c</TT>&quot; in the &quot;Output
37445  files(s) field&quot;.</LI>
37446 <LI>Next, select the settings for the entire project and go to
37447  &quot;C++:Preprocessor&quot;. Add the include directories for your Python
37448  installation under &quot;Additional include directories&quot;.</LI>
37449 <LI>Define the symbol __WIN32__ under preprocessor options.</LI>
37450 <LI>Finally, select the settings for the entire project and go to &quot;Link
37451  Options&quot;. Add the Python library file to your link libraries. For
37452  example &quot;python21.lib&quot;. Also, set the name of the output file to match
37453  the name of your Python module, ie. _example.pyd - Note that
37454  _example.dll also worked with Python-2.4 and earlier.</LI>
37455 <LI>Build your project.</LI>
37456 </UL>
37457 <P> If all went well, SWIG will be automatically invoked whenever you
37458  build your project. Any changes made to the interface file will result
37459  in SWIG being automatically executed to produce a new version of the
37460  wrapper file.</P>
37461 <P> To run your new Python extension, simply run Python and use the <TT>
37462 import</TT> command as normal. For example :</P>
37463 <DIV class="targetlang">
37464 <PRE>
37465 $ python
37466 &gt;&gt;&gt; import example
37467 &gt;&gt;&gt; print example.fact(4)
37468 24
37469 &gt;&gt;&gt;
37470 </PRE>
37471 </DIV>
37472 <P> If you get an <TT>ImportError</TT> exception when importing the
37473  module, you may have forgotten to include additional library files when
37474  you built your module. If you get an access violation or some kind of
37475  general protection fault immediately upon import, you have a more
37476  serious problem. This is often caused by linking your extension module
37477  against the wrong set of Win32 debug or thread libraries. You will have
37478  to fiddle around with the build options of project to try and track
37479  this down.</P>
37480 <P> Some users have reported success in building extension modules using
37481  Cygwin and other compilers. However, the problem of building usable
37482  DLLs with these compilers tends to be rather problematic. For the
37483  latest information, you may want to consult the <A href="http://www.dabeaz.com/cgi-bin/wiki.pl">
37484  SWIG Wiki</A>.</P>
37485 <H2><A name="Python_nn13"></A>31.3 A tour of basic C/C++ wrapping</H2>
37486 <P> By default, SWIG tries to build a very natural Python interface to
37487  your C/C++ code. Functions are wrapped as functions, classes are
37488  wrapped as classes, and so forth. This section briefly covers the
37489  essential aspects of this wrapping.</P>
37490 <H3><A name="Python_nn14"></A>31.3.1 Modules</H3>
37491 <P> The SWIG <TT>%module</TT> directive specifies the name of the Python
37492  module. If you specify `<TT>%module example</TT>', then everything is
37493  wrapped into a Python '<TT>example</TT>' module. Underneath the covers,
37494  this module consists of a Python source file <TT>example.py</TT> and a
37495  low-level extension module <TT>_example.so</TT>. When choosing a module
37496  name, make sure you don't use the same name as a built-in Python
37497  command or standard module name.</P>
37498 <H3><A name="Python_nn15"></A>31.3.2 Functions</H3>
37499 <P> Global functions are wrapped as new Python built-in functions. For
37500  example,</P>
37501 <DIV class="code">
37502 <PRE>
37503 %module example
37504 int fact(int n);
37505 </PRE>
37506 </DIV>
37507 <P> creates a built-in function <TT>example.fact(n)</TT> that works
37508  exactly like you think it does:</P>
37509 <DIV class="targetlang">
37510 <PRE>
37511 &gt;&gt;&gt; import example
37512 &gt;&gt;&gt; print example.fact(4)
37513 24
37514 &gt;&gt;&gt;
37515 </PRE>
37516 </DIV>
37517 <H3><A name="Python_nn16"></A>31.3.3 Global variables</H3>
37518 <P> C/C++ global variables are fully supported by SWIG. However, the
37519  underlying mechanism is somewhat different than you might expect due to
37520  the way that Python assignment works. When you type the following in
37521  Python</P>
37522 <DIV class="targetlang">
37523 <PRE>
37524 a = 3.4
37525 </PRE>
37526 </DIV>
37527 <P> &quot;a&quot; becomes a name for an object containing the value 3.4. If you
37528  later type</P>
37529 <DIV class="targetlang">
37530 <PRE>
37531 b = a
37532 </PRE>
37533 </DIV>
37534 <P> then &quot;a&quot; and &quot;b&quot; are both names for the object containing the value
37535  3.4. Thus, there is only one object containing 3.4 and &quot;a&quot; and &quot;b&quot; are
37536  both names that refer to it. This is quite different than C where a
37537  variable name refers to a memory location in which a value is stored
37538  (and assignment copies data into that location). Because of this, there
37539  is no direct way to map variable assignment in C to variable assignment
37540  in Python.</P>
37541 <P> To provide access to C global variables, SWIG creates a special
37542  object called `<TT>cvar</TT>' that is added to each SWIG generated
37543  module. Global variables are then accessed as attributes of this
37544  object. For example, consider this interface</P>
37545 <DIV class="code">
37546 <PRE>
37547 // SWIG interface file with global variables
37548 %module example
37549 ...
37550 %inline %{
37551 extern int My_variable;
37552 extern double density;
37553 %}
37554 ...
37555 </PRE>
37556 </DIV>
37557 <P> Now look at the Python interface:</P>
37558 <DIV class="targetlang">
37559 <PRE>
37560 &gt;&gt;&gt; import example
37561 &gt;&gt;&gt; # Print out value of a C global variable
37562 &gt;&gt;&gt; print example.cvar.My_variable
37563 4
37564 &gt;&gt;&gt; # Set the value of a C global variable
37565 &gt;&gt;&gt; example.cvar.density = 0.8442
37566 &gt;&gt;&gt; # Use in a math operation
37567 &gt;&gt;&gt; example.cvar.density = example.cvar.density*1.10
37568 </PRE>
37569 </DIV>
37570 <P> If you make an error in variable assignment, you will receive an
37571  error message. For example:</P>
37572 <DIV class="targetlang">
37573 <PRE>
37574 &gt;&gt;&gt; example.cvar.density = &quot;Hello&quot;
37575 Traceback (most recent call last):
37576   File &quot;&lt;stdin&gt;&quot;, line 1, in ?
37577 TypeError: C variable 'density (double )'
37578 &gt;&gt;&gt; 
37579 </PRE>
37580 </DIV>
37581 <P> If a variable is declared as <TT>const</TT>, it is wrapped as a
37582  read-only variable. Attempts to modify its value will result in an
37583  error.</P>
37584 <P> To make ordinary variables read-only, you can use the <TT>%immutable</TT>
37585  directive. For example:</P>
37586 <DIV class="code">
37587 <PRE>
37588 %{
37589 extern char *path;
37590 %}
37591 %immutable;
37592 extern char *path;
37593 %mutable;
37594 </PRE>
37595 </DIV>
37596 <P> The <TT>%immutable</TT> directive stays in effect until it is
37597  explicitly disabled or cleared using <TT>%mutable</TT>. See the <A href="#SWIG_readonly_variables">
37598 Creating read-only variables</A> section for further details.</P>
37599 <P> If you just want to make a specific variable immutable, supply a
37600  declaration name. For example:</P>
37601 <DIV class="code">
37602 <PRE>
37603 %{
37604 extern char *path;
37605 %}
37606 %immutable path;
37607 ...
37608 extern char *path;      // Read-only (due to %immutable)
37609 </PRE>
37610 </DIV>
37611 <P> If you would like to access variables using a name other than &quot;<TT>
37612 cvar</TT>&quot;, it can be changed using the <TT>-globals</TT> option :</P>
37613 <DIV class="shell">
37614 <PRE>
37615 $ swig -python -globals myvar example.i
37616 </PRE>
37617 </DIV>
37618 <P> Some care is in order when importing multiple SWIG modules. If you
37619  use the &quot;<TT>from &lt;file&gt; import *</TT>&quot; style of importing, you will
37620  get a name clash on the variable `<TT>cvar</TT>' and you will only be
37621  able to access global variables from the last module loaded. To prevent
37622  this, you might consider renaming <TT>cvar</TT> or making it private to
37623  the module by giving it a name that starts with a leading underscore.
37624  SWIG does not create <TT>cvar</TT> if there are no global variables in
37625  a module.</P>
37626 <H3><A name="Python_nn17"></A>31.3.4 Constants and enums</H3>
37627 <P> C/C++ constants are installed as Python objects containing the
37628  appropriate value. To create a constant, use <TT>#define</TT>, <TT>enum</TT>
37629 , or the <TT>%constant</TT> directive. For example:</P>
37630 <DIV class="code">
37631 <PRE>
37632 #define PI 3.14159
37633 #define VERSION &quot;1.0&quot;
37634
37635 enum Beverage { ALE, LAGER, STOUT, PILSNER };
37636
37637 %constant int FOO = 42;
37638 %constant const char *path = &quot;/usr/local&quot;;
37639 </PRE>
37640 </DIV>
37641 <P> For enums, make sure that the definition of the enumeration actually
37642  appears in a header file or in the wrapper file somehow---if you just
37643  stick an enum in a SWIG interface without also telling the C compiler
37644  about it, the wrapper code won't compile.</P>
37645 <P> Note: declarations declared as <TT>const</TT> are wrapped as
37646  read-only variables and will be accessed using the <TT>cvar</TT> object
37647  described in the previous section. They are not wrapped as constants.
37648  For further discussion about this, see the <A href="#SWIG">SWIG Basics</A>
37649  chapter.</P>
37650 <P> Constants are not guaranteed to remain constant in Python---the name
37651  of the constant could be accidentally reassigned to refer to some other
37652  object. Unfortunately, there is no easy way for SWIG to generate code
37653  that prevents this. You will just have to be careful.</P>
37654 <H3><A name="Python_nn18"></A>31.3.5 Pointers</H3>
37655 <P> C/C++ pointers are fully supported by SWIG. Furthermore, SWIG has no
37656  problem working with incomplete type information. Here is a rather
37657  simple interface:</P>
37658 <DIV class="code">
37659 <PRE>
37660 %module example
37661
37662 FILE *fopen(const char *filename, const char *mode);
37663 int fputs(const char *, FILE *);
37664 int fclose(FILE *);
37665 </PRE>
37666 </DIV>
37667 <P> When wrapped, you will be able to use the functions in a natural way
37668  from Python. For example:</P>
37669 <DIV class="targetlang">
37670 <PRE>
37671 &gt;&gt;&gt; import example
37672 &gt;&gt;&gt; f = example.fopen(&quot;junk&quot;,&quot;w&quot;)
37673 &gt;&gt;&gt; example.fputs(&quot;Hello World\n&quot;, f)
37674 &gt;&gt;&gt; example.fclose(f)
37675 </PRE>
37676 </DIV>
37677 <P> If this makes you uneasy, rest assured that there is no deep magic
37678  involved. Underneath the covers, pointers to C/C++ objects are simply
37679  represented as opaque values using an especial python container object:</P>
37680 <DIV class="targetlang">
37681 <PRE>
37682 &gt;&gt;&gt; print f
37683 &lt;Swig Object at _08a71808_p_FILE&gt;
37684 </PRE>
37685 </DIV>
37686 <P> This pointer value can be freely passed around to different C
37687  functions that expect to receive an object of type <TT>FILE *</TT>. The
37688  only thing you can't do is dereference the pointer from Python. Of
37689  course, that isn't much of a concern in this example.</P>
37690 <P> In older versions of Swig (1.3.22 or older), pointers were
37691  represented using a plain string object. If you have an old package
37692  that still requires that representation, or you just feel nostalgic,
37693  you can always retrieve it by casting the pointer object to a string:</P>
37694 <DIV class="targetlang">
37695 <PRE>
37696 &gt;&gt;&gt; print str(f)
37697 _c0671108_p_FILE
37698 </PRE>
37699 </DIV>
37700 <P> Also, if you need to pass the raw pointer value to some external
37701  python library, you can do it by casting the pointer object to an
37702  integer:</P>
37703 <DIV class="targetlang">
37704 <PRE>
37705 &gt;&gt;&gt; print int(f)
37706 135833352
37707 </PRE>
37708 </DIV>
37709 <P> However, the inverse operation is not possible, i.e., you can't
37710  build a Swig pointer object from a raw integer value.</P>
37711 <P> Note also that the '0' or NULL pointer is always represented by <TT>
37712 None</TT>, no matter what type swig is addressing. In the previous
37713  example, you can call:</P>
37714 <DIV class="targetlang">
37715 <PRE>
37716 &gt;&gt;&gt; example.fclose(None)
37717 </PRE>
37718 </DIV>
37719 <P> and that will be equivalent to the following, but not really useful,
37720  C code:</P>
37721 <DIV class="code">
37722 <PRE>
37723 FILE *f = NULL;
37724 fclose(f);
37725 </PRE>
37726 </DIV>
37727 <P> As much as you might be inclined to modify a pointer value directly
37728  from Python, don't. The hexadecimal encoding is not necessarily the
37729  same as the logical memory address of the underlying object. Instead it
37730  is the raw byte encoding of the pointer value. The encoding will vary
37731  depending on the native byte-ordering of the platform (i.e., big-endian
37732  vs. little-endian). Similarly, don't try to manually cast a pointer to
37733  a new type by simply replacing the type-string. This may not work like
37734  you expect, it is particularly dangerous when casting C++ objects. If
37735  you need to cast a pointer or change its value, consider writing some
37736  helper functions instead. For example:</P>
37737 <DIV class="code">
37738 <PRE>
37739 %inline %{
37740 /* C-style cast */
37741 Bar *FooToBar(Foo *f) {
37742    return (Bar *) f;
37743 }
37744
37745 /* C++-style cast */
37746 Foo *BarToFoo(Bar *b) {
37747    return dynamic_cast&lt;Foo*&gt;(b);
37748 }
37749
37750 Foo *IncrFoo(Foo *f, int i) {
37751     return f+i;
37752 }
37753 %}
37754 </PRE>
37755 </DIV>
37756 <P> Also, if working with C++, you should always try to use the new C++
37757  style casts. For example, in the above code, the C-style cast may
37758  return a bogus result whereas as the C++-style cast will return <TT>
37759 None</TT> if the conversion can't be performed.</P>
37760 <H3><A name="Python_nn19"></A>31.3.6 Structures</H3>
37761 <P> If you wrap a C structure, it is wrapped by a Python class. This
37762  provides a very natural interface. For example,</P>
37763 <DIV class="code">
37764 <PRE>
37765 struct Vector {
37766         double x,y,z;
37767 };
37768
37769 </PRE>
37770 </DIV>
37771 <P> is used as follows:</P>
37772 <DIV class="targetlang">
37773 <PRE>
37774 &gt;&gt;&gt; v = example.Vector()
37775 &gt;&gt;&gt; v.x = 3.5
37776 &gt;&gt;&gt; v.y = 7.2
37777 &gt;&gt;&gt; print v.x, v.y, v.z
37778 7.8 -4.5 0.0
37779 &gt;&gt;&gt; 
37780 </PRE>
37781 </DIV>
37782 <P> Similar access is provided for unions and the data members of C++
37783  classes.</P>
37784 <P> If you print out the value of <TT>v</TT> in the above example, you
37785  will see something like this:</P>
37786 <DIV class="targetlang">
37787 <PRE>
37788 &gt;&gt;&gt; print v
37789 &lt;C Vector instance at _18e31408_p_Vector&gt;
37790 </PRE>
37791 </DIV>
37792 <P> This object is actually a Python instance that has been wrapped
37793  around a pointer to the low-level C structure. This instance doesn't
37794  actually do anything--it just serves as a proxy. The pointer to the C
37795  object can be found in the the <TT>.this</TT> attribute. For example:</P>
37796 <DIV class="targetlang">
37797 <PRE>
37798 &gt;&gt;&gt; print v.this
37799 _18e31408_p_Vector
37800 &gt;&gt;&gt;
37801 </PRE>
37802 </DIV>
37803 <P> Further details about the Python proxy class are covered a little
37804  later.</P>
37805 <P> <TT>const</TT> members of a structure are read-only. Data members
37806  can also be forced to be read-only using the <TT>%immutable</TT>
37807  directive. For example:</P>
37808 <DIV class="code">
37809 <PRE>
37810 struct Foo {
37811    ...
37812    %immutable;
37813    int x;        /* Read-only members */
37814    char *name;
37815    %mutable;
37816    ...
37817 };
37818 </PRE>
37819 </DIV>
37820 <P> When <TT>char *</TT> members of a structure are wrapped, the
37821  contents are assumed to be dynamically allocated using <TT>malloc</TT>
37822  or <TT>new</TT> (depending on whether or not SWIG is run with the -c++
37823  option). When the structure member is set, the old contents will be
37824  released and a new value created. If this is not the behavior you want,
37825  you will have to use a typemap (described later).</P>
37826 <P> If a structure contains arrays, access to those arrays is managed
37827  through pointers. For example, consider this:</P>
37828 <DIV class="code">
37829 <PRE>
37830 struct Bar {
37831     int  x[16];
37832 };
37833 </PRE>
37834 </DIV>
37835 <P> If accessed in Python, you will see behavior like this:</P>
37836 <DIV class="targetlang">
37837 <PRE>
37838 &gt;&gt;&gt; b = example.Bar()
37839 &gt;&gt;&gt; print b.x
37840 _801861a4_p_int
37841 &gt;&gt;&gt; 
37842 </PRE>
37843 </DIV>
37844 <P> This pointer can be passed around to functions that expect to
37845  receive an <TT>int *</TT> (just like C). You can also set the value of
37846  an array member using another pointer. For example:</P>
37847 <DIV class="targetlang">
37848 <PRE>
37849 &gt;&gt;&gt; c = example.Bar()
37850 &gt;&gt;&gt; c.x = b.x             # Copy contents of b.x to c.x
37851 </PRE>
37852 </DIV>
37853 <P> For array assignment, SWIG copies the entire contents of the array
37854  starting with the data pointed to by <TT>b.x</TT>. In this example, 16
37855  integers would be copied. Like C, SWIG makes no assumptions about
37856  bounds checking---if you pass a bad pointer, you may get a segmentation
37857  fault or access violation.</P>
37858 <P> When a member of a structure is itself a structure, it is handled as
37859  a pointer. For example, suppose you have two structures like this:</P>
37860 <DIV class="code">
37861 <PRE>
37862 struct Foo {
37863    int a;
37864 };
37865
37866 struct Bar {
37867    Foo f;
37868 };
37869 </PRE>
37870 </DIV>
37871 <P> Now, suppose that you access the <TT>f</TT> attribute of <TT>Bar</TT>
37872  like this:</P>
37873 <DIV class="targetlang">
37874 <PRE>
37875 &gt;&gt;&gt; b = Bar()
37876 &gt;&gt;&gt; x = b.f
37877 </PRE>
37878 </DIV>
37879 <P> In this case, <TT>x</TT> is a pointer that points to the <TT>Foo</TT>
37880  that is inside <TT>b</TT>. This is the same value as generated by this
37881  C code:</P>
37882 <DIV class="code">
37883 <PRE>
37884 Bar b;
37885 Foo *x = &amp;b-&gt;f;       /* Points inside b */
37886 </PRE>
37887 </DIV>
37888 <P> Because the pointer points inside the structure, you can modify the
37889  contents and everything works just like you would expect. For example:</P>
37890 <DIV class="targetlang">
37891 <PRE>
37892 &gt;&gt;&gt; b = Bar()
37893 &gt;&gt;&gt; b.f.a = 3               # Modify attribute of structure member
37894 &gt;&gt;&gt; x = b.f                   
37895 &gt;&gt;&gt; x.a = 3                 # Modifies the same structure
37896 </PRE>
37897 </DIV>
37898 <H3><A name="Python_nn20"></A>31.3.7 C++ classes</H3>
37899 <P> C++ classes are wrapped by Python classes as well. For example, if
37900  you have this class,</P>
37901 <DIV class="code">
37902 <PRE>
37903 class List {
37904 public:
37905   List();
37906   ~List();
37907   int  search(char *item);
37908   void insert(char *item);
37909   void remove(char *item);
37910   char *get(int n);
37911   int  length;
37912 };
37913 </PRE>
37914 </DIV>
37915 <P> you can use it in Python like this:</P>
37916 <DIV class="targetlang">
37917 <PRE>
37918 &gt;&gt;&gt; l = example.List()
37919 &gt;&gt;&gt; l.insert(&quot;Ale&quot;)
37920 &gt;&gt;&gt; l.insert(&quot;Stout&quot;)
37921 &gt;&gt;&gt; l.insert(&quot;Lager&quot;)
37922 &gt;&gt;&gt; l.get(1)
37923 'Stout'
37924 &gt;&gt;&gt; print l.length
37925 3
37926 &gt;&gt;&gt;
37927 </PRE>
37928 </DIV>
37929 <P> Class data members are accessed in the same manner as C structures.</P>
37930 <P> Static class members present a special problem for Python. Prior to
37931  Python-2.2, Python classes had no support for static methods and no
37932  version of Python supports static member variables in a manner that
37933  SWIG can utilize. Therefore, SWIG generates wrappers that try to work
37934  around some of these issues. To illustrate, suppose you have a class
37935  like this:</P>
37936 <DIV class="code">
37937 <PRE>
37938 class Spam {
37939 public:
37940    static void foo();
37941    static int bar;
37942
37943 };
37944 </PRE>
37945 </DIV>
37946 <P> In Python, the static member can be access in three different ways:</P>
37947 <DIV class="targetlang">
37948 <PRE>
37949 &gt;&gt;&gt; example.Spam_foo()    # Spam::foo()
37950 &gt;&gt;&gt; s = example.Spam()
37951 &gt;&gt;&gt; s.foo()               # Spam::foo() via an instance
37952 &gt;&gt;&gt; example.Spam.foo()    # Spam::foo(). Python-2.2 only
37953 </PRE>
37954 </DIV>
37955 <P> The first two methods of access are supported in all versions of
37956  Python. The last technique is only available in Python-2.2 and later
37957  versions.</P>
37958 <P> Static member variables are currently accessed as global variables.
37959  This means, they are accessed through <TT>cvar</TT> like this:</P>
37960 <DIV class="targetlang">
37961 <PRE>
37962 &gt;&gt;&gt; print example.cvar.Spam_bar
37963 7
37964 </PRE>
37965 </DIV>
37966 <H3><A name="Python_nn21"></A>31.3.8 C++ inheritance</H3>
37967 <P> SWIG is fully aware of issues related to C++ inheritance. Therefore,
37968  if you have classes like this</P>
37969 <DIV class="code">
37970 <PRE>
37971 class Foo {
37972 ...
37973 };
37974
37975 class Bar : public Foo {
37976 ...
37977 };
37978 </PRE>
37979 </DIV>
37980 <P> those classes are wrapped into a hierarchy of Python classes that
37981  reflect the same inheritance structure. All of the usual Python utility
37982  functions work normally:</P>
37983 <DIV class="targetlang">
37984 <PRE>
37985 &gt;&gt;&gt; b = Bar()
37986 &gt;&gt;&gt; instance(b,Foo)
37987 1
37988 &gt;&gt;&gt; issubclass(Bar,Foo)
37989 1
37990 &gt;&gt;&gt; issubclass(Foo,Bar)
37991 0
37992 </PRE>
37993 </DIV>
37994 <P> Furthermore, if you have functions like this</P>
37995 <DIV class="code">
37996 <PRE>
37997 void spam(Foo *f);
37998 </PRE>
37999 </DIV>
38000 <P> then the function <TT>spam()</TT> accepts <TT>Foo *</TT> or a
38001  pointer to any class derived from <TT>Foo</TT>.</P>
38002 <P> It is safe to use multiple inheritance with SWIG.</P>
38003 <H3><A name="Python_nn22"></A>31.3.9 Pointers, references, values, and
38004  arrays</H3>
38005 <P> In C++, there are many different ways a function might receive and
38006  manipulate objects. For example:</P>
38007 <DIV class="code">
38008 <PRE>
38009 void spam1(Foo *x);      // Pass by pointer
38010 void spam2(Foo &amp;x);      // Pass by reference
38011 void spam3(const Foo &amp;x);// Pass by const reference
38012 void spam4(Foo x);       // Pass by value
38013 void spam5(Foo x[]);     // Array of objects
38014 </PRE>
38015 </DIV>
38016 <P> In Python, there is no detailed distinction like this--specifically,
38017  there are only &quot;objects&quot;. There are no pointers, references, arrays,
38018  and so forth. Because of this, SWIG unifies all of these types together
38019  in the wrapper code. For instance, if you actually had the above
38020  functions, it is perfectly legal to do this:</P>
38021 <DIV class="targetlang">
38022 <PRE>
38023 &gt;&gt;&gt; f = Foo()           # Create a Foo
38024 &gt;&gt;&gt; spam1(f)            # Ok. Pointer
38025 &gt;&gt;&gt; spam2(f)            # Ok. Reference
38026 &gt;&gt;&gt; spam3(f)            # Ok. Const reference
38027 &gt;&gt;&gt; spam4(f)            # Ok. Value.
38028 &gt;&gt;&gt; spam5(f)            # Ok. Array (1 element)
38029 </PRE>
38030 </DIV>
38031 <P> Similar behavior occurs for return values. For example, if you had
38032  functions like this,</P>
38033 <DIV class="code">
38034 <PRE>
38035 Foo *spam6();
38036 Foo &amp;spam7();
38037 Foo  spam8();
38038 const Foo &amp;spam9();
38039 </PRE>
38040 </DIV>
38041 <P> then all three functions will return a pointer to some <TT>Foo</TT>
38042  object. Since the third function (spam8) returns a value, newly
38043  allocated memory is used to hold the result and a pointer is returned
38044  (Python will release this memory when the return value is garbage
38045  collected). The fourth case (spam9) which returns a const reference, in
38046  most of the cases will be treated as a returning value, and it will
38047  follow the same allocation/deallocation process.</P>
38048 <H3><A name="Python_nn23"></A>31.3.10 C++ overloaded functions</H3>
38049 <P> C++ overloaded functions, methods, and constructors are mostly
38050  supported by SWIG. For example, if you have two functions like this:</P>
38051 <DIV class="code">
38052 <PRE>
38053 void foo(int);
38054 void foo(char *c);
38055 </PRE>
38056 </DIV>
38057 <P> You can use them in Python in a straightforward manner:</P>
38058 <DIV class="targetlang">
38059 <PRE>
38060 &gt;&gt;&gt; foo(3)           # foo(int)
38061 &gt;&gt;&gt; foo(&quot;Hello&quot;)     # foo(char *c)
38062 </PRE>
38063 </DIV>
38064 <P> Similarly, if you have a class like this,</P>
38065 <DIV class="code">
38066 <PRE>
38067 class Foo {
38068 public:
38069     Foo();
38070     Foo(const Foo &amp;);
38071     ...
38072 };
38073 </PRE>
38074 </DIV>
38075 <P> you can write Python code like this:</P>
38076 <DIV class="targetlang">
38077 <PRE>
38078 &gt;&gt;&gt; f = Foo()          # Create a Foo
38079 &gt;&gt;&gt; g = Foo(f)         # Copy f
38080 </PRE>
38081 </DIV>
38082 <P> Overloading support is not quite as flexible as in C++. Sometimes
38083  there are methods that SWIG can't disambiguate. For example:</P>
38084 <DIV class="code">
38085 <PRE>
38086 void spam(int);
38087 void spam(short);
38088 </PRE>
38089 </DIV>
38090 <P> or</P>
38091 <DIV class="code">
38092 <PRE>
38093 void foo(Bar *b);
38094 void foo(Bar &amp;b);
38095 </PRE>
38096 </DIV>
38097 <P> If declarations such as these appear, you will get a warning message
38098  like this:</P>
38099 <DIV class="shell">
38100 <PRE>
38101 example.i:12: Warning(509): Overloaded spam(short) is shadowed by spam(int)
38102 at example.i:11.
38103 </PRE>
38104 </DIV>
38105 <P> To fix this, you either need to ignore or rename one of the methods.
38106  For example:</P>
38107 <DIV class="code">
38108 <PRE>
38109 %rename(spam_short) spam(short);
38110 ...
38111 void spam(int);    
38112 void spam(short);   // Accessed as spam_short
38113 </PRE>
38114 </DIV>
38115 <P> or</P>
38116 <DIV class="code">
38117 <PRE>
38118 %ignore spam(short);
38119 ...
38120 void spam(int);    
38121 void spam(short);   // Ignored
38122 </PRE>
38123 </DIV>
38124 <P> SWIG resolves overloaded functions and methods using a
38125  disambiguation scheme that ranks and sorts declarations according to a
38126  set of type-precedence rules. The order in which declarations appear in
38127  the input does not matter except in situations where ambiguity
38128  arises--in this case, the first declaration takes precedence.</P>
38129 <P> Please refer to the &quot;SWIG and C++&quot; chapter for more information
38130  about overloading.</P>
38131 <H3><A name="Python_nn24"></A>31.3.11 C++ operators</H3>
38132 <P> Certain C++ overloaded operators can be handled automatically by
38133  SWIG. For example, consider a class like this:</P>
38134 <DIV class="code">
38135 <PRE>
38136 class Complex {
38137 private:
38138   double rpart, ipart;
38139 public:
38140   Complex(double r = 0, double i = 0) : rpart(r), ipart(i) { }
38141   Complex(const Complex &amp;c) : rpart(c.rpart), ipart(c.ipart) { }
38142   Complex &amp;operator=(const Complex &amp;c);
38143
38144   Complex operator+=(const Complex &amp;c) const;
38145   Complex operator+(const Complex &amp;c) const;
38146   Complex operator-(const Complex &amp;c) const;
38147   Complex operator*(const Complex &amp;c) const;
38148   Complex operator-() const;
38149   
38150   double re() const { return rpart; }
38151   double im() const { return ipart; }
38152 };
38153 </PRE>
38154 </DIV>
38155 <P> When wrapped, it works like you expect:</P>
38156 <DIV class="targetlang">
38157 <PRE>
38158 &gt;&gt;&gt; c = Complex(3,4)
38159 &gt;&gt;&gt; d = Complex(7,8)
38160 &gt;&gt;&gt; e = c + d
38161 &gt;&gt;&gt; e.re()
38162 10.0
38163 &gt;&gt;&gt; e.im()
38164 12.0
38165 &gt;&gt;&gt; c += d
38166 &gt;&gt;&gt; c.re()
38167 10.0
38168 &gt;&gt;&gt; c.im()
38169 12.0
38170
38171 </PRE>
38172 </DIV>
38173 <P> One restriction with operator overloading support is that SWIG is
38174  not able to fully handle operators that aren't defined as part of the
38175  class. For example, if you had code like this</P>
38176 <DIV class="code">
38177 <PRE>
38178 class Complex {
38179 ...
38180 friend Complex operator+(double, const Complex &amp;c);
38181 ...
38182 };
38183 </PRE>
38184 </DIV>
38185 <P> then SWIG ignores it and issues a warning. You can still wrap the
38186  operator, but you may have to encapsulate it in a special function. For
38187  example:</P>
38188 <DIV class="code">
38189 <PRE>
38190 %rename(Complex_add_dc) operator+(double, const Complex &amp;);
38191 </PRE>
38192 </DIV>
38193 <P> There are ways to make this operator appear as part of the class
38194  using the <TT>%extend</TT> directive. Keep reading.</P>
38195 <P> Also, be aware that certain operators don't map cleanly to Python.
38196  For instance, overloaded assignment operators don't map to Python
38197  semantics and will be ignored.</P>
38198 <H3><A name="Python_nn25"></A>31.3.12 C++ namespaces</H3>
38199 <P> SWIG is aware of C++ namespaces, but namespace names do not appear
38200  in the module nor do namespaces result in a module that is broken up
38201  into submodules or packages. For example, if you have a file like this,</P>
38202 <DIV class="code">
38203 <PRE>
38204 %module example
38205
38206 namespace foo {
38207    int fact(int n);
38208    struct Vector {
38209        double x,y,z;
38210    };
38211 };
38212 </PRE>
38213 </DIV>
38214 <P> it works in Python as follows:</P>
38215 <DIV class="targetlang">
38216 <PRE>
38217 &gt;&gt;&gt; import example
38218 &gt;&gt;&gt; example.fact(3)
38219 6
38220 &gt;&gt;&gt; v = example.Vector()
38221 &gt;&gt;&gt; v.x = 3.4
38222 &gt;&gt;&gt; print v.y
38223 0.0
38224 &gt;&gt;&gt;
38225 </PRE>
38226 </DIV>
38227 <P> If your program has more than one namespace, name conflicts (if any)
38228  can be resolved using <TT>%rename</TT> For example:</P>
38229 <DIV class="code">
38230 <PRE>
38231 %rename(Bar_spam) Bar::spam;
38232
38233 namespace Foo {
38234     int spam();
38235 }
38236
38237 namespace Bar {
38238     int spam();
38239 }
38240 </PRE>
38241 </DIV>
38242 <P> If you have more than one namespace and your want to keep their
38243  symbols separate, consider wrapping them as separate SWIG modules. For
38244  example, make the module name the same as the namespace and create
38245  extension modules for each namespace separately. If your program
38246  utilizes thousands of small deeply nested namespaces each with
38247  identical symbol names, well, then you get what you deserve.</P>
38248 <H3><A name="Python_nn26"></A>31.3.13 C++ templates</H3>
38249 <P> C++ templates don't present a huge problem for SWIG. However, in
38250  order to create wrappers, you have to tell SWIG to create wrappers for
38251  a particular template instantiation. To do this, you use the <TT>
38252 %template</TT> directive. For example:</P>
38253 <DIV class="code">
38254 <PRE>
38255 %module example
38256 %{
38257 #include &quot;pair.h&quot;
38258 %}
38259
38260 template&lt;class T1, class T2&gt;
38261 struct pair {
38262    typedef T1 first_type;
38263    typedef T2 second_type;
38264    T1 first;
38265    T2 second;
38266    pair();
38267    pair(const T1&amp;, const T2&amp;);
38268   ~pair();
38269 };
38270
38271 %template(pairii) pair&lt;int,int&gt;;
38272 </PRE>
38273 </DIV>
38274 <P> In Python:</P>
38275 <DIV class="targetlang">
38276 <PRE>
38277 &gt;&gt;&gt; import example
38278 &gt;&gt;&gt; p = example.pairii(3,4)
38279 &gt;&gt;&gt; p.first
38280 3
38281 &gt;&gt;&gt; p.second
38282 4
38283 </PRE>
38284 </DIV>
38285 <P> Obviously, there is more to template wrapping than shown in this
38286  example. More details can be found in the <A href="#SWIGPlus">SWIG and
38287  C++</A> chapter. Some more complicated examples will appear later.</P>
38288 <H3><A name="Python_nn27"></A>31.3.14 C++ Smart Pointers</H3>
38289 <P> In certain C++ programs, it is common to use classes that have been
38290  wrapped by so-called &quot;smart pointers.&quot; Generally, this involves the use
38291  of a template class that implements <TT>operator-&gt;()</TT> like this:</P>
38292 <DIV class="code">
38293 <PRE>
38294 template&lt;class T&gt; class SmartPtr {
38295    ...
38296    T *operator-&gt;();
38297    ...
38298 }
38299 </PRE>
38300 </DIV>
38301 <P> Then, if you have a class like this,</P>
38302 <DIV class="code">
38303 <PRE>
38304 class Foo {
38305 public:
38306      int x;
38307      int bar();
38308 };
38309 </PRE>
38310 </DIV>
38311 <P> A smart pointer would be used in C++ as follows:</P>
38312 <DIV class="code">
38313 <PRE>
38314 SmartPtr&lt;Foo&gt; p = CreateFoo();   // Created somehow (not shown)
38315 ...
38316 p-&gt;x = 3;                        // Foo::x
38317 int y = p-&gt;bar();                // Foo::bar
38318 </PRE>
38319 </DIV>
38320 <P> To wrap this in Python, simply tell SWIG about the <TT>SmartPtr</TT>
38321  class and the low-level <TT>Foo</TT> object. Make sure you instantiate <TT>
38322 SmartPtr</TT> using <TT>%template</TT> if necessary. For example:</P>
38323 <DIV class="code">
38324 <PRE>
38325 %module example
38326 ...
38327 %template(SmartPtrFoo) SmartPtr&lt;Foo&gt;;
38328 ...
38329 </PRE>
38330 </DIV>
38331 <P> Now, in Python, everything should just &quot;work&quot;:</P>
38332 <DIV class="targetlang">
38333 <PRE>
38334 &gt;&gt;&gt; p = example.CreateFoo()          # Create a smart-pointer somehow
38335 &gt;&gt;&gt; p.x = 3                          # Foo::x
38336 &gt;&gt;&gt; p.bar()                          # Foo::bar
38337 </PRE>
38338 </DIV>
38339 <P> If you ever need to access the underlying pointer returned by <TT>
38340 operator-&gt;()</TT> itself, simply use the <TT>__deref__()</TT> method.
38341  For example:</P>
38342 <DIV class="targetlang">
38343 <PRE>
38344 &gt;&gt;&gt; f = p.__deref__()     # Returns underlying Foo *
38345 </PRE>
38346 </DIV>
38347 <H3><A name="Python_nn27a"></A>31.3.15 C++ Reference Counted Objects
38348  (ref/unref)</H3>
38349 <P> Another usual idiom in C++ is the use of reference counted objects.
38350  Consider for example:<DIV class="code">
38351 <PRE>
38352 class RCObj  {
38353   // implement the ref counting mechanism
38354   int add_ref();
38355   int del_ref();
38356   int ref_count();
38357
38358 public:
38359   virtual ~RCObj() = 0;
38360
38361   int ref() const {
38362     return add_ref();
38363   }
38364
38365   int unref() const   {
38366     if (ref_count() == 0 || del_ref() == 0 ) {
38367         delete this;
38368         return 0;
38369       } 
38370     return ref_count();
38371   }
38372 };
38373
38374
38375 class A : RCObj {
38376 public:
38377   A();
38378   int foo();
38379 };
38380
38381
38382 class B {
38383   A *_a;
38384
38385 public:
38386   B(A *a) : _a(a) { 
38387     a-&gt;ref(); 
38388   }
38389
38390   ~B() { 
38391     a-&gt;unref(); 
38392   }
38393 };
38394
38395 int main() {
38396   A *a  = new A();
38397   a-&gt;ref();           // 'a' is ref here
38398
38399   B *b1 = new B(a);   // 'a' is ref here
38400   if (1 + 1 == 2) {
38401     B *b2 = new B(a); // 'a' is ref here
38402     delete b2;        // 'a' is unref, but not deleted   
38403   }
38404
38405   delete b1;          // 'a' is unref, but not deleted   
38406   a-&gt;unref();         // 'a' is unref and deleted
38407 }
38408 </PRE>
38409 </DIV></P>
38410 <P> In the example above, the 'A' class instance 'a' is a reference
38411  counted object, which can't be deleted arbitrarily since it is shared
38412  between the objects 'b1' and 'b2'. 'A' is derived from an Reference
38413  Counted Object 'RCObj', which implements the ref/unref idiom.</P>
38414 <P> To tell SWIG that 'RCObj' and all its derived classes are reference
38415  counted objects, you use the &quot;ref&quot; and &quot;unref&quot; features, or <TT>%ref</TT>
38416  and <TT>%unref</TT> directives (since 1.3.28). For example:</P>
38417 <DIV class="code">
38418 <PRE>
38419 %module example
38420 ...
38421
38422 %feature(&quot;ref&quot;)   RCObj &quot;$this-&gt;ref();&quot;
38423 %feature(&quot;unref&quot;) RCObj &quot;$this-&gt;unref();&quot;
38424
38425 %include &quot;rcobj.h&quot;
38426 %include &quot;A.h&quot;
38427 ...
38428 </PRE>
38429 </DIV> or, using the directive form:<DIV class="code">
38430 <PRE>
38431 %module example
38432 ...
38433
38434 %ref   RCObj &quot;$this-&gt;ref();&quot;
38435 %unref RCObj &quot;$this-&gt;unref();&quot;
38436
38437 %include &quot;rcobj.h&quot;
38438 %include &quot;A.h&quot;
38439 ...
38440 </PRE>
38441 </DIV>
38442 <P> where the code passed to the &quot;ref&quot; and &quot;unref&quot; features will be
38443  executed as needed whenever a new object is passed to python, or when
38444  python tries to release the shadow object instance, respectively.</P>
38445 <P> In the python side, the use of a reference counted object is not
38446  different than any other regular instance:</P>
38447 <DIV class="targetlang">
38448 <PRE>
38449 def create_A():
38450   a = A()         # SWIG ref 'a' (new object is passed to python)
38451   b1 = B(a)       # C++  ref 'a'
38452   if 1 + 1 == 2:
38453      b2 = B(a)    # C++ ref 'a'
38454   return a        # 'b1' and 'b2' are released, C++ unref 'a' twice
38455
38456 a = create_A()   
38457 exit              # 'a' is released, SWIG unref 'a'
38458 </PRE>
38459 </DIV>
38460 <P> Note that the user doesn't explicitly need to call 'a-&gt;ref()' nor
38461  'a-&gt;unref()' (as neither 'delete a'). Instead, SWIG take cares of
38462  executing the &quot;ref&quot; and &quot;unref&quot; codes as needed. If the user doesn't
38463  specify the &quot;ref/unref&quot; features, SWIG will produce a code equivalent
38464  to define them as:</P>
38465 <DIV class="code">
38466 <PRE>
38467 %feature(&quot;ref&quot;)   &quot;&quot;
38468 %feature(&quot;unref&quot;) &quot;delete $this;&quot;
38469 </PRE>
38470 </DIV>
38471 <P> In other words, SWIG will not do anything special when a new object
38472  is passed to python, and it will always 'delete' the object when python
38473  releases the proxy instance.</P>
38474 <H2><A name="Python_nn28"></A>31.4 Further details on the Python class
38475  interface</H2>
38476 <P> In the previous section, a high-level view of Python wrapping was
38477  presented. A key component of this wrapping is that structures and
38478  classes are wrapped by Python proxy classes. This provides a very
38479  natural Python interface and allows SWIG to support a number of
38480  advanced features such as operator overloading. However, a number of
38481  low-level details were omitted. This section provides a brief overview
38482  of how the proxy classes work.</P>
38483 <H3><A name="Python_nn29"></A>31.4.1 Proxy classes</H3>
38484 <P> In the <A href="#SWIG">&quot;SWIG basics&quot;</A> and <A href="#SWIGPlus">
38485 &quot;SWIG and C++&quot;</A> chapters, details of low-level structure and class
38486  wrapping are described. To summarize those chapters, if you have a
38487  class like this</P>
38488 <DIV class="code">
38489 <PRE>
38490 class Foo {
38491 public:
38492      int x;
38493      int spam(int);
38494      ...
38495 </PRE>
38496 </DIV>
38497 <P> then SWIG transforms it into a set of low-level procedural wrappers.
38498  For example:</P>
38499 <DIV class="code">
38500 <PRE>
38501 Foo *new_Foo() {
38502     return new Foo();
38503 }
38504 void delete_Foo(Foo *f) {
38505     delete f;
38506 }
38507 int Foo_x_get(Foo *f) {
38508     return f-&gt;x;
38509 }
38510 void Foo_x_set(Foo *f, int value) {
38511     f-&gt;x = value;
38512 }
38513 int Foo_spam(Foo *f, int arg1) {
38514     return f-&gt;spam(arg1);
38515 }
38516 </PRE>
38517 </DIV>
38518 <P> These wrappers can be found in the low-level extension module (e.g.,
38519  <TT>_example</TT>).</P>
38520 <P> Using these wrappers, SWIG generates a high-level Python proxy class
38521  (also known as a shadow class) like this (shown for Python 2.2):</P>
38522 <DIV class="targetlang">
38523 <PRE>
38524 import _example
38525
38526 class Foo(object):
38527      def __init__(self):
38528          self.this = _example.new_Foo()
38529          self.thisown = 1
38530      def __del__(self):
38531          if self.thisown:
38532                _example.delete_Foo(self.this)
38533      def spam(self,arg1):
38534          return _example.Foo_spam(self.this,arg1)
38535      x = property(_example.Foo_x_get, _example.Foo_x_set)
38536 </PRE>
38537 </DIV>
38538 <P> This class merely holds a pointer to the underlying C++ object (<TT>
38539 .this</TT>) and dispatches methods and member variable access to that
38540  object using the low-level accessor functions. From a user's point of
38541  view, it makes the class work normally:</P>
38542 <DIV class="targetlang">
38543 <PRE>
38544 &gt;&gt;&gt; f = example.Foo()
38545 &gt;&gt;&gt; f.x = 3
38546 &gt;&gt;&gt; y = f.spam(5)
38547 </PRE>
38548 </DIV>
38549 <P> The fact that the class has been wrapped by a real Python class
38550  offers certain advantages. For instance, you can attach new Python
38551  methods to the class and you can even inherit from it (something not
38552  supported by Python built-in types until Python 2.2).</P>
38553 <H3><A name="Python_nn30"></A>31.4.2 Memory management</H3>
38554 <P> Associated with proxy object, is an ownership flag <TT>.thisown</TT>
38555  The value of this flag determines who is responsible for deleting the
38556  underlying C++ object. If set to 1, the Python interpreter will destroy
38557  the C++ object when the proxy class is garbage collected. If set to 0
38558  (or if the attribute is missing), then the destruction of the proxy
38559  class has no effect on the C++ object.</P>
38560 <P> When an object is created by a constructor or returned by value,
38561  Python automatically takes ownership of the result. For example:</P>
38562 <DIV class="code">
38563 <PRE>
38564 class Foo {
38565 public:
38566     Foo();
38567     Foo bar();
38568 };
38569 </PRE>
38570 </DIV>
38571 <P> In Python:</P>
38572 <DIV class="targetlang">
38573 <PRE>
38574 &gt;&gt;&gt; f = Foo()
38575 &gt;&gt;&gt; f.thisown
38576 1
38577 &gt;&gt;&gt; g = f.bar()
38578 &gt;&gt;&gt; g.thisown
38579 1
38580 </PRE>
38581 </DIV>
38582 <P> On the other hand, when pointers are returned to Python, there is
38583  often no way to know where they came from. Therefore, the ownership is
38584  set to zero. For example:</P>
38585 <DIV class="code">
38586 <PRE>
38587 class Foo {
38588 public:
38589     ...
38590     Foo *spam();
38591     ...
38592 };
38593 </PRE>
38594 </DIV>
38595 <BR><DIV class="targetlang">
38596 <PRE>
38597 &gt;&gt;&gt; f = Foo()
38598 &gt;&gt;&gt; s = f.spam()
38599 &gt;&gt;&gt; print s.thisown
38600 0
38601 &gt;&gt;&gt;
38602 </PRE>
38603 </DIV>
38604 <P> This behavior is especially important for classes that act as
38605  containers. For example, if a method returns a pointer to an object
38606  that is contained inside another object, you definitely don't want
38607  Python to assume ownership and destroy it!</P>
38608 <P> A good way to indicate that ownership should be set for a returned
38609  pointer is to use the <A href="#Library_nn11">%newobject directive</A>.</P>
38610 <P> Related to containers, ownership issues can arise whenever an object
38611  is assigned to a member or global variable. For example, consider this
38612  interface:</P>
38613 <DIV class="code">
38614 <PRE>
38615 %module example
38616
38617 struct Foo {
38618     int  value;
38619     Foo  *next;
38620 };
38621
38622 Foo *head = 0;
38623 </PRE>
38624 </DIV>
38625 <P> When wrapped in Python, careful observation will reveal that
38626  ownership changes whenever an object is assigned to a global variable.
38627  For example:</P>
38628 <DIV class="targetlang">
38629 <PRE>
38630 &gt;&gt;&gt; f = example.Foo()
38631 &gt;&gt;&gt; f.thisown
38632 1
38633 &gt;&gt;&gt; example.cvar.head = f           
38634 &gt;&gt;&gt; f.thisown
38635 0
38636 &gt;&gt;&gt;
38637 </PRE>
38638 </DIV>
38639 <P> In this case, C is now holding a reference to the object---you
38640  probably don't want Python to destroy it. Similarly, this occurs for
38641  members. For example:</P>
38642 <DIV class="targetlang">
38643 <PRE>
38644 &gt;&gt;&gt; f = example.Foo()
38645 &gt;&gt;&gt; g = example.Foo()
38646 &gt;&gt;&gt; f.thisown
38647 1
38648 &gt;&gt;&gt; g.thisown
38649 1
38650 &gt;&gt;&gt; f.next = g
38651 &gt;&gt;&gt; g.thisown
38652 0
38653 &gt;&gt;&gt;
38654 </PRE>
38655 </DIV>
38656 <P> For the most part, memory management issues remain hidden. However,
38657  there are occasionally situations where you might have to manually
38658  change the ownership of an object. For instance, consider code like
38659  this:</P>
38660 <DIV class="code">
38661 <PRE>
38662 class Node {
38663    Object *value;
38664 public:
38665    void set_value(Object *v) { value = v; }
38666    ...
38667 };
38668 </PRE>
38669 </DIV>
38670 <P> Now, consider the following Python code:</P>
38671 <DIV class="targetlang">
38672 <PRE>
38673 &gt;&gt;&gt; v = Object()           # Create an object
38674 &gt;&gt;&gt; n = Node()             # Create a node
38675 &gt;&gt;&gt; n.set_value(v)         # Set value
38676 &gt;&gt;&gt; v.thisown
38677 1
38678 &gt;&gt;&gt; del v
38679 </PRE>
38680 </DIV>
38681 <P> In this case, the object <TT>n</TT> is holding a reference to <TT>v</TT>
38682  internally. However, SWIG has no way to know that this has occurred.
38683  Therefore, Python still thinks that it has ownership of the object.
38684  Should the proxy object be destroyed, then the C++ destructor will be
38685  invoked and <TT>n</TT> will be holding a stale-pointer. If you're
38686  lucky, you will only get a segmentation fault.</P>
38687 <P> To work around this, it is always possible to flip the ownership
38688  flag. For example,</P>
38689 <DIV class="targetlang">
38690 <PRE>
38691 &gt;&gt;&gt; v.thisown = 0
38692 </PRE>
38693 </DIV>
38694 <P> It is also possible to deal with situations like this using
38695  typemaps--an advanced topic discussed later.</P>
38696 <H3><A name="Python_nn31"></A>31.4.3 Python 2.2 and classic classes</H3>
38697 <P> SWIG makes every attempt to preserve backwards compatibility with
38698  older versions of Python to the extent that it is possible. However, in
38699  Python-2.2, an entirely new type of class system was introduced. This
38700  new-style class system offers many enhancements including static member
38701  functions, properties (managed attributes), and class methods. Details
38702  about all of these changes can be found on <A href="//www.python.org">
38703 www.python.org</A> and is not repeated here.</P>
38704 <P> To address differences between Python versions, SWIG currently emits
38705  dual-mode proxy class wrappers. In Python-2.2 and newer releases, these
38706  wrappers encapsulate C++ objects in new-style classes that take
38707  advantage of new features (static methods and properties). However, if
38708  these very same wrappers are imported into an older version of Python,
38709  old-style classes are used instead.</P>
38710 <P> This dual-nature of the wrapper code means that you can create
38711  extension modules with SWIG and those modules will work with all
38712  versions of Python ranging from Python-1.4 to the very latest release.
38713  Moreover, the wrappers take advantage of Python-2.2 features when
38714  available.</P>
38715 <P> For the most part, the interface presented to users is the same
38716  regardless of what version of Python is used. The only incompatibility
38717  lies in the handling of static member functions. In Python-2.2, they
38718  can be accessed via the class itself. In Python-2.1 and earlier, they
38719  have to be accessed as a global function or through an instance (see
38720  the earlier section).</P>
38721 <H2><A name="Python_directors"></A>31.5 Cross language polymorphism</H2>
38722 <P> Proxy classes provide a more natural, object-oriented way to access
38723  extension classes. As described above, each proxy instance has an
38724  associated C++ instance, and method calls to the proxy are passed to
38725  the C++ instance transparently via C wrapper functions.</P>
38726 <P> This arrangement is asymmetric in the sense that no corresponding
38727  mechanism exists to pass method calls down the inheritance chain from
38728  C++ to Python. In particular, if a C++ class has been extended in
38729  Python (by extending the proxy class), these extensions will not be
38730  visible from C++ code. Virtual method calls from C++ are thus not able
38731  access the lowest implementation in the inheritance chain.</P>
38732 <P> Changes have been made to SWIG 1.3.18 to address this problem and
38733  make the relationship between C++ classes and proxy classes more
38734  symmetric. To achieve this goal, new classes called directors are
38735  introduced at the bottom of the C++ inheritance chain. The job of the
38736  directors is to route method calls correctly, either to C++
38737  implementations higher in the inheritance chain or to Python
38738  implementations lower in the inheritance chain. The upshot is that C++
38739  classes can be extended in Python and from C++ these extensions look
38740  exactly like native C++ classes. Neither C++ code nor Python code needs
38741  to know where a particular method is implemented: the combination of
38742  proxy classes, director classes, and C wrapper functions takes care of
38743  all the cross-language method routing transparently.</P>
38744 <H3><A name="Python_nn33"></A>31.5.1 Enabling directors</H3>
38745 <P> The director feature is disabled by default. To use directors you
38746  must make two changes to the interface file. First, add the &quot;directors&quot;
38747  option to the %module directive, like this:</P>
38748 <DIV class="code">
38749 <PRE>
38750 %module(directors=&quot;1&quot;) modulename
38751 </PRE>
38752 </DIV>
38753 <P> Without this option no director code will be generated. Second, you
38754  must use the %feature(&quot;director&quot;) directive to tell SWIG which classes
38755  and methods should get directors. The %feature directive can be applied
38756  globally, to specific classes, and to specific methods, like this:</P>
38757 <DIV class="code">
38758 <PRE>
38759 // generate directors for all classes that have virtual methods
38760 %feature(&quot;director&quot;);         
38761
38762 // generate directors for all virtual methods in class Foo
38763 %feature(&quot;director&quot;) Foo;      
38764
38765 // generate a director for just Foo::bar()
38766 %feature(&quot;director&quot;) Foo::bar; 
38767 </PRE>
38768 </DIV>
38769 <P> You can use the %feature(&quot;nodirector&quot;) directive to turn off
38770  directors for specific classes or methods. So for example,</P>
38771 <DIV class="code">
38772 <PRE>
38773 %feature(&quot;director&quot;) Foo;
38774 %feature(&quot;nodirector&quot;) Foo::bar;
38775 </PRE>
38776 </DIV>
38777 <P> will generate directors for all virtual methods of class Foo except
38778  bar().</P>
38779 <P> Directors can also be generated implicitly through inheritance. In
38780  the following, class Bar will get a director class that handles the
38781  methods one() and two() (but not three()):</P>
38782 <DIV class="code">
38783 <PRE>
38784 %feature(&quot;director&quot;) Foo;
38785 class Foo {
38786 public:
38787     Foo(int foo);
38788     virtual void one();
38789     virtual void two();
38790 };
38791
38792 class Bar: public Foo {
38793 public:
38794     virtual void three();
38795 };
38796 </PRE>
38797 </DIV>
38798 <P> then at the python side you can define</P>
38799 <DIV class="targetlang">
38800 <PRE>
38801 import mymodule
38802
38803 class MyFoo(mymodule.Foo):
38804   def __init__(self, foo):
38805      mymodule.Foo(self, foo)  
38806
38807   def one(self):
38808      print &quot;one from python&quot;
38809 </PRE>
38810 </DIV>
38811 <H3><A name="Python_nn34"></A>31.5.2 Director classes</H3>
38812 <P> For each class that has directors enabled, SWIG generates a new
38813  class that derives from both the class in question and a special <TT>
38814 Swig::Director</TT> class. These new classes, referred to as director
38815  classes, can be loosely thought of as the C++ equivalent of the Python
38816  proxy classes. The director classes store a pointer to their underlying
38817  Python object and handle various issues related to object ownership.
38818  Indeed, this is quite similar to the &quot;this&quot; and &quot;thisown&quot; members of
38819  the Python proxy classes.</P>
38820 <P> For simplicity let's ignore the <TT>Swig::Director</TT> class and
38821  refer to the original C++ class as the director's base class. By
38822  default, a director class extends all virtual methods in the
38823  inheritance chain of its base class (see the preceding section for how
38824  to modify this behavior). Thus all virtual method calls, whether they
38825  originate in C++ or in Python via proxy classes, eventually end up in
38826  at the implementation in the director class. The job of the director
38827  methods is to route these method calls to the appropriate place in the
38828  inheritance chain. By &quot;appropriate place&quot; we mean the method that would
38829  have been called if the C++ base class and its extensions in Python
38830  were seamlessly integrated. That seamless integration is exactly what
38831  the director classes provide, transparently skipping over all the messy
38832  extension API glue that binds the two languages together.</P>
38833 <P> In reality, the &quot;appropriate place&quot; is one of only two
38834  possibilities: C++ or Python. Once this decision is made, the rest is
38835  fairly easy. If the correct implementation is in C++, then the lowest
38836  implementation of the method in the C++ inheritance chain is called
38837  explicitly. If the correct implementation is in Python, the Python API
38838  is used to call the method of the underlying Python object (after which
38839  the usual virtual method resolution in Python automatically finds the
38840  right implementation).</P>
38841 <P> Now how does the director decide which language should handle the
38842  method call? The basic rule is to handle the method in Python, unless
38843  there's a good reason not to. The reason for this is simple: Python has
38844  the most &quot;extended&quot; implementation of the method. This assertion is
38845  guaranteed, since at a minimum the Python proxy class implements the
38846  method. If the method in question has been extended by a class derived
38847  from the proxy class, that extended implementation will execute exactly
38848  as it should. If not, the proxy class will route the method call into a
38849  C wrapper function, expecting that the method will be resolved in C++.
38850  The wrapper will call the virtual method of the C++ instance, and since
38851  the director extends this the call will end up right back in the
38852  director method. Now comes the &quot;good reason not to&quot; part. If the
38853  director method were to blindly call the Python method again, it would
38854  get stuck in an infinite loop. We avoid this situation by adding
38855  special code to the C wrapper function that tells the director method
38856  to not do this. The C wrapper function compares the pointer to the
38857  Python object that called the wrapper function to the pointer stored by
38858  the director. If these are the same, then the C wrapper function tells
38859  the director to resolve the method by calling up the C++ inheritance
38860  chain, preventing an infinite loop.</P>
38861 <P> One more point needs to be made about the relationship between
38862  director classes and proxy classes. When a proxy class instance is
38863  created in Python, SWIG creates an instance of the original C++ class
38864  and assigns it to <TT>.this</TT>. This is exactly what happens without
38865  directors and is true even if directors are enabled for the particular
38866  class in question. When a class<I> derived</I> from a proxy class is
38867  created, however, SWIG then creates an instance of the corresponding
38868  C++ director class. The reason for this difference is that user-defined
38869  subclasses may override or extend methods of the original class, so the
38870  director class is needed to route calls to these methods correctly. For
38871  unmodified proxy classes, all methods are ultimately implemented in C++
38872  so there is no need for the extra overhead involved with routing the
38873  calls through Python.</P>
38874 <H3><A name="Python_nn35"></A>31.5.3 Ownership and object destruction</H3>
38875 <P> Memory management issues are slightly more complicated with
38876  directors than for proxy classes alone. Python instances hold a pointer
38877  to the associated C++ director object, and the director in turn holds a
38878  pointer back to the Python object. By default, proxy classes own their
38879  C++ director object and take care of deleting it when they are garbage
38880  collected.</P>
38881 <P> This relationship can be reversed by calling the special <TT>
38882 __disown__()</TT> method of the proxy class. After calling this method,
38883  the <TT>.thisown</TT> flag is set to zero, and the director class
38884  increments the reference count of the Python object. When the director
38885  class is deleted it decrements the reference count. Assuming no
38886  outstanding references to the Python object remain, the Python object
38887  will be destroyed at the same time. This is a good thing, since
38888  directors and proxies refer to each other and so must be created and
38889  destroyed together. Destroying one without destroying the other will
38890  likely cause your program to segfault.</P>
38891 <P> To help ensure that no references to the Python object remain after
38892  calling <TT>__disown__()</TT>, this method returns a weak reference to
38893  the Python object. Weak references are only available in Python
38894  versions 2.1 and higher, so for older versions you must explicitly
38895  delete all references. Here is an example:</P>
38896 <DIV class="code">
38897 <PRE>
38898 class Foo {
38899 public:
38900     ...
38901 };
38902 class FooContainer {
38903 public:
38904     void addFoo(Foo *);
38905     ...
38906 };
38907 </PRE>
38908 </DIV>
38909 <BR><DIV class="targetlang">
38910 <PRE>
38911 &gt;&gt;&gt; c = FooContainer()
38912 &gt;&gt;&gt; a = Foo().__disown()__
38913 &gt;&gt;&gt; c.addFoo(a)
38914 &gt;&gt;&gt; b = Foo()
38915 &gt;&gt;&gt; b = b.__disown()__
38916 &gt;&gt;&gt; c.addFoo(b)
38917 &gt;&gt;&gt; c.addFoo(Foo().__disown()__)
38918 </PRE>
38919 </DIV>
38920 <P> In this example, we are assuming that FooContainer will take care of
38921  deleting all the Foo pointers it contains at some point. Note that no
38922  hard references to the Foo objects remain in Python.</P>
38923 <H3><A name="Python_nn36"></A>31.5.4 Exception unrolling</H3>
38924 <P> With directors routing method calls to Python, and proxies routing
38925  them to C++, the handling of exceptions is an important concern. By
38926  default, the directors ignore exceptions that occur during method calls
38927  that are resolved in Python. To handle such exceptions correctly, it is
38928  necessary to temporarily translate them into C++ exceptions. This can
38929  be done with the %feature(&quot;director:except&quot;) directive. The following
38930  code should suffice in most cases:</P>
38931 <DIV class="code">
38932 <PRE>
38933 %feature(&quot;director:except&quot;) {
38934     if ($error != NULL) {
38935         throw Swig::DirectorMethodException();
38936     }
38937 }
38938 </PRE>
38939 </DIV>
38940 <P> This code will check the Python error state after each method call
38941  from a director into Python, and throw a C++ exception if an error
38942  occurred. This exception can be caught in C++ to implement an error
38943  handler. Currently no information about the Python error is stored in
38944  the Swig::DirectorMethodException object, but this will likely change
38945  in the future.</P>
38946 <P> It may be the case that a method call originates in Python, travels
38947  up to C++ through a proxy class, and then back into Python via a
38948  director method. If an exception occurs in Python at this point, it
38949  would be nice for that exception to find its way back to the original
38950  caller. This can be done by combining a normal %exception directive
38951  with the <TT>director:except</TT> handler shown above. Here is an
38952  example of a suitable exception handler:</P>
38953 <DIV class="code">
38954 <PRE>
38955 %exception {
38956     try { $action }
38957     catch (Swig::DirectorException &amp;e) { SWIG_fail; }
38958 }
38959 </PRE>
38960 </DIV>
38961 <P> The class Swig::DirectorException used in this example is actually a
38962  base class of Swig::DirectorMethodException, so it will trap this
38963  exception. Because the Python error state is still set when
38964  Swig::DirectorMethodException is thrown, Python will register the
38965  exception as soon as the C wrapper function returns.</P>
38966 <H3><A name="Python_nn37"></A>31.5.5 Overhead and code bloat</H3>
38967 <P> Enabling directors for a class will generate a new director method
38968  for every virtual method in the class' inheritance chain. This alone
38969  can generate a lot of code bloat for large hierarchies. Method
38970  arguments that require complex conversions to and from target language
38971  types can result in large director methods. For this reason it is
38972  recommended that you selectively enable directors only for specific
38973  classes that are likely to be extended in Python and used in C++.</P>
38974 <P> Compared to classes that do not use directors, the call routing in
38975  the director methods does add some overhead. In particular, at least
38976  one dynamic cast and one extra function call occurs per method call
38977  from Python. Relative to the speed of Python execution this is probably
38978  completely negligible. For worst case routing, a method call that
38979  ultimately resolves in C++ may take one extra detour through Python in
38980  order to ensure that the method does not have an extended Python
38981  implementation. This could result in a noticeable overhead in some
38982  cases.</P>
38983 <P> Although directors make it natural to mix native C++ objects with
38984  Python objects (as director objects) via a common base class pointer,
38985  one should be aware of the obvious fact that method calls to Python
38986  objects will be much slower than calls to C++ objects. This situation
38987  can be optimized by selectively enabling director methods (using the
38988  %feature directive) for only those methods that are likely to be
38989  extended in Python.</P>
38990 <H3><A name="Python_nn38"></A>31.5.6 Typemaps</H3>
38991 <P> Typemaps for input and output of most of the basic types from
38992  director classes have been written. These are roughly the reverse of
38993  the usual input and output typemaps used by the wrapper code. The
38994  typemap operation names are 'directorin', 'directorout', and
38995  'directorargout'. The director code does not currently use any of the
38996  other kinds of typemaps. It is not clear at this point which kinds are
38997  appropriate and need to be supported.</P>
38998 <H3><A name="Python_nn39"></A>31.5.7 Miscellaneous</H3>
38999 <P> Director typemaps for STL classes are in place, and hence you should
39000  be able to use std::vector, std::string, etc., as you would any other
39001  type.</P>
39002 <P><B> Note:</B> The director typemaps for return types based in const
39003  references, such as<DIV class="code">
39004 <PRE>
39005 class Foo {
39006 &hellip;
39007     virtual const int&amp; bar();
39008 &hellip;
39009 };
39010 </PRE>
39011 </DIV></P>
39012 <P> will work only for simple call scenarios. Usually the resulting code
39013  is neither thread or reentrant safe. Hence, the user is advised to
39014  avoid returning const references in director methods. For example, the
39015  user could modify the method interface to use lvalue return types,
39016  wherever possible, for example</P>
39017 <DIV class="code">
39018 <PRE>
39019 class Foo {
39020 &hellip;
39021     virtual int bar();
39022 &hellip;
39023 };
39024 </PRE>
39025 </DIV>
39026 <P> If that is not possible, the user should avoid enabling the director
39027  feature for reentrant, recursive or threaded member methods that return
39028  const references.</P>
39029 <H2><A name="Python_nn40"></A>31.6 Common customization features</H2>
39030 <P> The last section presented the absolute basics of C/C++ wrapping. If
39031  you do nothing but feed SWIG a header file, you will get an interface
39032  that mimics the behavior described. However, sometimes this isn't
39033  enough to produce a nice module. Certain types of functionality might
39034  be missing or the interface to certain functions might be awkward. This
39035  section describes some common SWIG features that are used to improve
39036  your the interface to an extension module.</P>
39037 <H3><A name="Python_nn41"></A>31.6.1 C/C++ helper functions</H3>
39038 <P> Sometimes when you create a module, it is missing certain bits of
39039  functionality. For example, if you had a function like this</P>
39040 <DIV class="code">
39041 <PRE>
39042 void set_transform(Image *im, double m[4][4]);
39043 </PRE>
39044 </DIV>
39045 <P> it would be accessible from Python, but there may be no easy way to
39046  call it. For example, you might get errors like this:</P>
39047 <DIV class="targetlang">
39048 <PRE>
39049 &gt;&gt;&gt; a = [
39050 ...   [1,0,0,0],
39051 ...   [0,1,0,0],
39052 ...   [0,0,1,0],
39053 ...   [0,0,0,1]]
39054 &gt;&gt;&gt; set_transform(im,a)
39055 Traceback (most recent call last):
39056   File &quot;&lt;stdin&gt;&quot;, line 1, in ?
39057 TypeError: Type error. Expected _p_a_4__double
39058 </PRE>
39059 </DIV>
39060 <P> The problem here is that there is no easy way to construct and
39061  manipulate a suitable <TT>double [4][4]</TT> value to use. To fix this,
39062  you can write some extra C helper functions. Just use the <TT>%inline</TT>
39063  directive. For example:</P>
39064 <DIV class="code">
39065 <PRE>
39066 %inline %{
39067 /* Note: double[4][4] is equivalent to a pointer to an array double (*)[4] */
39068 double (*new_mat44())[4] {
39069    return (double (*)[4]) malloc(16*sizeof(double));
39070 }
39071 void free_mat44(double (*x)[4]) {
39072    free(x);
39073 }
39074 void mat44_set(double x[4][4], int i, int j, double v) {
39075    x[i][j] = v;
39076 }
39077 double mat44_get(double x[4][4], int i, int j) {
39078    return x[i][j];
39079 }
39080 %}
39081 </PRE>
39082 </DIV>
39083 <P> From Python, you could then write code like this:</P>
39084 <DIV class="targetlang">
39085 <PRE>
39086 &gt;&gt;&gt; a = new_mat44()
39087 &gt;&gt;&gt; mat44_set(a,0,0,1.0)
39088 &gt;&gt;&gt; mat44_set(a,1,1,1.0)
39089 &gt;&gt;&gt; mat44_set(a,2,2,1.0)
39090 ...
39091 &gt;&gt;&gt; set_transform(im,a)
39092 &gt;&gt;&gt;
39093 </PRE>
39094 </DIV>
39095 <P> Admittedly, this is not the most elegant looking approach. However,
39096  it works and it wasn't too hard to implement. It is possible to clean
39097  this up using Python code, typemaps, and other customization features
39098  as covered in later sections.</P>
39099 <H3><A name="Python_nn42"></A>31.6.2 Adding additional Python code</H3>
39100 <P> If writing support code in C isn't enough, it is also possible to
39101  write code in Python. This code gets inserted in to the <TT>.py</TT>
39102  file created by SWIG. One use of Python code might be to supply a
39103  high-level interface to certain functions. For example:</P>
39104 <DIV class="code">
39105 <PRE>
39106 void set_transform(Image *im, double x[4][4]);
39107
39108 ...
39109 /* Rewrite the high level interface to set_transform */
39110 %pythoncode %{
39111 def set_transform(im,x):
39112    a = new_mat44()
39113    for i in range(4):
39114        for j in range(4):
39115            mat44_set(a,i,j,x[i][j])
39116    _example.set_transform(im,a)
39117    free_mat44(a)
39118 %}
39119 </PRE>
39120 </DIV>
39121 <P> In this example, <TT>set_transform()</TT> provides a high-level
39122  Python interface built on top of low-level helper functions. For
39123  example, this code now seems to work:</P>
39124 <DIV class="targetlang">
39125 <PRE>
39126 &gt;&gt;&gt; a = [
39127 ...   [1,0,0,0],
39128 ...   [0,1,0,0],
39129 ...   [0,0,1,0],
39130 ...   [0,0,0,1]]
39131 &gt;&gt;&gt; set_transform(im,a)
39132 &gt;&gt;&gt;
39133 </PRE>
39134 </DIV>
39135 <P> Admittedly, this whole scheme for wrapping the two-dimension array
39136  argument is rather ad-hoc. Besides, shouldn't a Python list or a
39137  Numeric Python array just work normally? We'll get to those examples
39138  soon enough. For now, think of this example as an illustration of what
39139  can be done without having to rely on any of the more advanced
39140  customization features.</P>
39141 <P>Sometimes you may want to replace or modify the wrapper function that
39142  SWIG creates in the proxy <TT>.py</TT> file. The Python module in SWIG
39143  provides some features that enable you do do this. First, to entirely
39144  replace a proxy function you can use <TT>%feature(&quot;shadow&quot;)</TT>. For
39145  example:</P>
39146 <DIV class="code">
39147 <PRE>
39148 %module example
39149
39150 // Rewrite bar() python code
39151
39152 %feature(&quot;shadow&quot;) Foo::bar(int) %{
39153 def bar(*args):
39154     #do something before
39155     $action
39156     #do something after
39157 %}
39158     
39159 class Foo {
39160 public:
39161     int bar(int x);
39162 }
39163 </PRE>
39164 </DIV>
39165 <P> where <TT>$action</TT> will be replaced by the call to the C/C++
39166  proper method.</P>
39167 <P> Often the proxy function created by SWIG is fine, but you simply
39168  want to add code to it without touching the rest of the generated
39169  function body. For these cases SWIG provides the <TT>pythonprepend</TT>
39170  and <TT>pythonappend</TT> features which do exactly as their names
39171  suggest. The <TT>pythonprepend</TT> feature will insert its value at
39172  the beginning of the proxy function, and <TT>pythonappend</TT> will
39173  insert code at the end of the proxy, just before the return statement.</P>
39174 <DIV class="code">
39175 <PRE>
39176 %module example
39177
39178 // Add python code to bar() 
39179
39180 %feature(&quot;pythonprepend&quot;) Foo::bar(int) %{
39181    #do something before C++ call
39182 %}
39183
39184 %feature(&quot;pythonappend&quot;) Foo::bar(int) %{
39185    #do something after C++ call
39186 %}
39187
39188     
39189 class Foo {
39190 public:
39191     int bar(int x);
39192 }
39193 </PRE>
39194 </DIV>
39195 <P> Notes: Usually the <TT>pythonappend</TT> and <TT>pythonprepend</TT>
39196  features are safer to use than the <TT>shadow</TT> feature. Also, from
39197  SWIG version 1.3.28 you can use the directive forms <TT>%pythonappend</TT>
39198  and <TT>%pythonprepend</TT> as follows:</P>
39199 <DIV class="code">
39200 <PRE>
39201 %module example
39202
39203 // Add python code to bar() 
39204
39205 %pythonprepend Foo::bar(int) %{
39206    #do something before C++ call
39207 %}
39208
39209 %pythonappend Foo::bar(int) %{
39210    #do something after C++ call
39211 %}
39212
39213     
39214 class Foo {
39215 public:
39216     int bar(int x);
39217 }
39218 </PRE>
39219 </DIV>
39220 <H3><A name="Python_nn43"></A>31.6.3 Class extension with %extend</H3>
39221 <P> One of the more interesting features of SWIG is that it can extend
39222  structures and classes with new methods--at least in the Python
39223  interface. Here is a simple example:</P>
39224 <DIV class="code">
39225 <PRE>
39226 %module example
39227 %{
39228 #include &quot;someheader.h&quot;
39229 %}
39230
39231 struct Vector {
39232    double x,y,z;
39233 };
39234
39235 %extend Vector {
39236    char *__str__() {
39237        static char tmp[1024];
39238        sprintf(tmp,&quot;Vector(%g,%g,%g)&quot;, $self-&gt;x,$self-&gt;y,$self-&gt;z);
39239        return tmp;
39240    }
39241    Vector(double x, double y, double z) {
39242        Vector *v = (Vector *) malloc(sizeof(Vector));
39243        v-&gt;x = x;
39244        v-&gt;y = y;
39245        v-&gt;z = z;
39246        return v;
39247    }
39248 };
39249 </PRE>
39250 </DIV>
39251 <P> Now, in Python</P>
39252 <DIV class="targetlang">
39253 <PRE>
39254 &gt;&gt;&gt; v = example.Vector(2,3,4)
39255 &gt;&gt;&gt; print v
39256 Vector(2,3,4)
39257 &gt;&gt;&gt;
39258 </PRE>
39259 </DIV>
39260 <P> <TT>%extend</TT> can be used for many more tasks than this. For
39261  example, if you wanted to overload a Python operator, you might do
39262  this:</P>
39263 <DIV class="code">
39264 <PRE>
39265 %extend Vector {
39266     Vector __add__(Vector *other) {
39267          Vector v;
39268          v.x = $self-&gt;x + other-&gt;x;
39269          v.y = $self-&gt;y + other-&gt;y;
39270          v.z = $self-&gt;z + other-&gt;z;
39271          return v;
39272     }
39273 };
39274 </PRE>
39275 </DIV>
39276 <P> Use it like this:</P>
39277 <DIV class="targetlang">
39278 <PRE>
39279 &gt;&gt;&gt; import example
39280 &gt;&gt;&gt; v = example.Vector(2,3,4)
39281 &gt;&gt;&gt; w = example.Vector(10,11,12)
39282 &gt;&gt;&gt; print v+w
39283 Vector(12,14,16)
39284 &gt;&gt;&gt; 
39285 </PRE>
39286 </DIV>
39287 <P> <TT>%extend</TT> works with both C and C++ code. It does not modify
39288  the underlying object in any way---the extensions only show up in the
39289  Python interface.</P>
39290 <H3><A name="Python_nn44"></A>31.6.4 Exception handling with %exception</H3>
39291 <P> If a C or C++ function throws an error, you may want to convert that
39292  error into a Python exception. To do this, you can use the <TT>
39293 %exception</TT> directive. <TT>%exception</TT> simply lets you rewrite
39294  part of the generated wrapper code to include an error check.</P>
39295 <P> In C, a function often indicates an error by returning a status code
39296  (a negative number or a NULL pointer perhaps). Here is a simple example
39297  of how you might handle that:</P>
39298 <DIV class="code">
39299 <PRE>
39300 %exception malloc {
39301   $action
39302   if (!result) {
39303      PyErr_SetString(PyExc_MemoryError,&quot;Not enough memory&quot;);
39304      return NULL;
39305   }
39306 }
39307 void *malloc(size_t nbytes);
39308 </PRE>
39309 </DIV>
39310 <P> In Python,</P>
39311 <DIV class="targetlang">
39312 <PRE>
39313 &gt;&gt;&gt; a = example.malloc(2000000000)
39314 Traceback (most recent call last):
39315   File &quot;&lt;stdin&gt;&quot;, line 1, in ?
39316 MemoryError: Not enough memory
39317 &gt;&gt;&gt;
39318 </PRE>
39319 </DIV>
39320 <P> If a library provides some kind of general error handling framework,
39321  you can also use that. For example:</P>
39322 <DIV class="code">
39323 <PRE>
39324 %exception {
39325    $action
39326    if (err_occurred()) {
39327       PyErr_SetString(PyExc_RuntimeError, err_message());
39328       return NULL;
39329    }
39330 }
39331 </PRE>
39332 </DIV>
39333 <P> No declaration name is given to <TT>%exception</TT>, it is applied
39334  to all wrapper functions.</P>
39335 <P> C++ exceptions are also easy to handle. For example, you can write
39336  code like this:</P>
39337 <DIV class="code">
39338 <PRE>
39339 %exception getitem {
39340    try {
39341       $action
39342    } catch (std::out_of_range &amp;e) {
39343       PyErr_SetString(PyExc_IndexError, const_cast&lt;char*&gt;(e.what()));
39344       return NULL;
39345    }
39346 }
39347
39348 class Base {
39349 public:
39350      Foo *getitem(int index);      // Exception handled added
39351      ...
39352 };
39353 </PRE>
39354 </DIV>
39355 <P> When raising a Python exception from C, use the <TT>
39356 PyErr_SetString()</TT> function as shown above. The following exception
39357  types can be used as the first argument.</P>
39358 <DIV class="code">
39359 <PRE>
39360 PyExc_ArithmeticError
39361 PyExc_AssertionError
39362 PyExc_AttributeError
39363 PyExc_EnvironmentError
39364 PyExc_EOFError
39365 PyExc_Exception
39366 PyExc_FloatingPointError
39367 PyExc_ImportError
39368 PyExc_IndexError
39369 PyExc_IOError
39370 PyExc_KeyError
39371 PyExc_KeyboardInterrupt
39372 PyExc_LookupError
39373 PyExc_MemoryError
39374 PyExc_NameError
39375 PyExc_NotImplementedError
39376 PyExc_OSError
39377 PyExc_OverflowError
39378 PyExc_RuntimeError
39379 PyExc_StandardError
39380 PyExc_SyntaxError
39381 PyExc_SystemError
39382 PyExc_TypeError
39383 PyExc_UnicodeError
39384 PyExc_ValueError
39385 PyExc_ZeroDivisionError
39386 </PRE>
39387 </DIV>
39388 <P> The language-independent <TT>exception.i</TT> library file can also
39389  be used to raise exceptions. See the <A href="#Library">SWIG Library</A>
39390  chapter.</P>
39391 <H2><A name="Python_nn45"></A>31.7 Tips and techniques</H2>
39392 <P> Although SWIG is largely automatic, there are certain types of
39393  wrapping problems that require additional user input. Examples include
39394  dealing with output parameters, strings, binary data, and arrays. This
39395  chapter discusses the common techniques for solving these problems.</P>
39396 <H3><A name="Python_nn46"></A>31.7.1 Input and output parameters</H3>
39397 <P> A common problem in some C programs is handling parameters passed as
39398  simple pointers. For example:</P>
39399 <DIV class="code">
39400 <PRE>
39401 void add(int x, int y, int *result) {
39402    *result = x + y;
39403 }
39404 </PRE>
39405 </DIV>
39406 <P> or perhaps</P>
39407 <DIV class="code">
39408 <PRE>
39409 int sub(int *x, int *y) {
39410    return *x-*y;
39411 }
39412 </PRE>
39413 </DIV>
39414 <P> The easiest way to handle these situations is to use the <TT>
39415 typemaps.i</TT> file. For example:</P>
39416 <DIV class="code">
39417 <PRE>
39418 %module example
39419 %include &quot;typemaps.i&quot;
39420
39421 void add(int, int, int *OUTPUT);
39422 int  sub(int *INPUT, int *INPUT);
39423 </PRE>
39424 </DIV>
39425 <P> In Python, this allows you to pass simple values. For example:</P>
39426 <DIV class="targetlang">
39427 <PRE>
39428 &gt;&gt;&gt; a = add(3,4)
39429 &gt;&gt;&gt; print a
39430 7
39431 &gt;&gt;&gt; b = sub(7,4)
39432 &gt;&gt;&gt; print b
39433 3
39434 &gt;&gt;&gt;
39435 </PRE>
39436 </DIV>
39437 <P> Notice how the <TT>INPUT</TT> parameters allow integer values to be
39438  passed instead of pointers and how the <TT>OUTPUT</TT> parameter
39439  creates a return result.</P>
39440 <P> If you don't want to use the names <TT>INPUT</TT> or <TT>OUTPUT</TT>
39441 , use the <TT>%apply</TT> directive. For example:</P>
39442 <DIV class="code">
39443 <PRE>
39444 %module example
39445 %include &quot;typemaps.i&quot;
39446
39447 %apply int *OUTPUT { int *result };
39448 %apply int *INPUT  { int *x, int *y};
39449
39450 void add(int x, int y, int *result);
39451 int  sub(int *x, int *y);
39452 </PRE>
39453 </DIV>
39454 <P> If a function mutates one of its parameters like this,</P>
39455 <DIV class="code">
39456 <PRE>
39457 void negate(int *x) {
39458    *x = -(*x);
39459 }
39460 </PRE>
39461 </DIV>
39462 <P> you can use <TT>INOUT</TT> like this:</P>
39463 <DIV class="code">
39464 <PRE>
39465 %include &quot;typemaps.i&quot;
39466 ...
39467 void negate(int *INOUT);
39468 </PRE>
39469 </DIV>
39470 <P> In Python, a mutated parameter shows up as a return value. For
39471  example:</P>
39472 <DIV class="targetlang">
39473 <PRE>
39474 &gt;&gt;&gt; a = negate(3)
39475 &gt;&gt;&gt; print a
39476 -3
39477 &gt;&gt;&gt;
39478 </PRE>
39479 </DIV>
39480 <P> Note: Since most primitive Python objects are immutable, it is not
39481  possible to perform in-place modification of a Python object passed as
39482  a parameter.</P>
39483 <P> The most common use of these special typemap rules is to handle
39484  functions that return more than one value. For example, sometimes a
39485  function returns a result as well as a special error code:</P>
39486 <DIV class="code">
39487 <PRE>
39488 /* send message, return number of bytes sent, along with success code */
39489 int send_message(char *text, int len, int *success);
39490 </PRE>
39491 </DIV>
39492 <P> To wrap such a function, simply use the <TT>OUTPUT</TT> rule above.
39493  For example:</P>
39494 <DIV class="code">
39495 <PRE>
39496 %module example
39497 %include &quot;typemaps.i&quot;
39498 %apply int *OUTPUT { int *success };
39499 ...
39500 int send_message(char *text, int *success);
39501 </PRE>
39502 </DIV>
39503 <P> When used in Python, the function will return multiple values.</P>
39504 <DIV class="targetlang">
39505 <PRE>
39506 bytes, success = send_message(&quot;Hello World&quot;)
39507 if not success:
39508     print &quot;Whoa!&quot;
39509 else:
39510     print &quot;Sent&quot;, bytes
39511 </PRE>
39512 </DIV>
39513 <P> Another common use of multiple return values are in query functions.
39514  For example:</P>
39515 <DIV class="code">
39516 <PRE>
39517 void get_dimensions(Matrix *m, int *rows, int *columns);
39518 </PRE>
39519 </DIV>
39520 <P> To wrap this, you might use the following:</P>
39521 <DIV class="code">
39522 <PRE>
39523 %module example
39524 %include &quot;typemaps.i&quot;
39525 %apply int *OUTPUT { int *rows, int *columns };
39526 ...
39527 void get_dimensions(Matrix *m, int *rows, *columns);
39528 </PRE>
39529 </DIV>
39530 <P> Now, in Python:</P>
39531 <DIV class="targetlang">
39532 <PRE>
39533 &gt;&gt;&gt; r,c = get_dimensions(m)
39534 </PRE>
39535 </DIV>
39536 <P> Be aware that the primary purpose of the <TT>typemaps.i</TT> file is
39537  to support primitive datatypes. Writing a function like this</P>
39538 <DIV class="code">
39539 <PRE>
39540 void foo(Bar *OUTPUT);
39541 </PRE>
39542 </DIV>
39543 <P> may not have the intended effect since <TT>typemaps.i</TT> does not
39544  define an OUTPUT rule for <TT>Bar</TT>.</P>
39545 <H3><A name="Python_nn47"></A>31.7.2 Simple pointers</H3>
39546 <P> If you must work with simple pointers such as <TT>int *</TT> or <TT>
39547 double *</TT> and you don't want to use <TT>typemaps.i</TT>, consider
39548  using the <TT>cpointer.i</TT> library file. For example:</P>
39549 <DIV class="code">
39550 <PRE>
39551 %module example
39552 %include &quot;cpointer.i&quot;
39553
39554 %inline %{
39555 extern void add(int x, int y, int *result);
39556 %}
39557
39558 %pointer_functions(int, intp);
39559 </PRE>
39560 </DIV>
39561 <P> The <TT>%pointer_functions(type,name)</TT> macro generates five
39562  helper functions that can be used to create, destroy, copy, assign, and
39563  dereference a pointer. In this case, the functions are as follows:</P>
39564 <DIV class="code">
39565 <PRE>
39566 int  *new_intp();
39567 int  *copy_intp(int *x);
39568 void  delete_intp(int *x);
39569 void  intp_assign(int *x, int value);
39570 int   intp_value(int *x);
39571 </PRE>
39572 </DIV>
39573 <P> In Python, you would use the functions like this:</P>
39574 <DIV class="targetlang">
39575 <PRE>
39576 &gt;&gt;&gt; result = new_intp()
39577 &gt;&gt;&gt; print result
39578 _108fea8_p_int
39579 &gt;&gt;&gt; add(3,4,result)
39580 &gt;&gt;&gt; print intp_value(result)
39581 7
39582 &gt;&gt;&gt;
39583 </PRE>
39584 </DIV>
39585 <P> If you replace <TT>%pointer_functions()</TT> by <TT>
39586 %pointer_class(type,name)</TT>, the interface is more class-like.</P>
39587 <DIV class="targetlang">
39588 <PRE>
39589 &gt;&gt;&gt; result = intp()
39590 &gt;&gt;&gt; add(3,4,result)
39591 &gt;&gt;&gt; print result.value()
39592 7
39593 </PRE>
39594 </DIV>
39595 <P> See the <A href="#Library">SWIG Library</A> chapter for further
39596  details.</P>
39597 <H3><A name="Python_nn48"></A>31.7.3 Unbounded C Arrays</H3>
39598 <P> Sometimes a C function expects an array to be passed as a pointer.
39599  For example,</P>
39600 <DIV class="code">
39601 <PRE>
39602 int sumitems(int *first, int nitems) {
39603     int i, sum = 0;
39604     for (i = 0; i &lt; nitems; i++) {
39605         sum += first[i];
39606     }
39607     return sum;
39608 }
39609 </PRE>
39610 </DIV>
39611 <P> To wrap this into Python, you need to pass an array pointer as the
39612  first argument. A simple way to do this is to use the <TT>carrays.i</TT>
39613  library file. For example:</P>
39614 <DIV class="code">
39615 <PRE>
39616 %include &quot;carrays.i&quot;
39617 %array_class(int, intArray);
39618 </PRE>
39619 </DIV>
39620 <P> The <TT>%array_class(type, name)</TT> macro creates wrappers for an
39621  unbounded array object that can be passed around as a simple pointer
39622  like <TT>int *</TT> or <TT>double *</TT>. For instance, you will be
39623  able to do this in Python:</P>
39624 <DIV class="targetlang">
39625 <PRE>
39626 &gt;&gt;&gt; a = intArray(10000000)         # Array of 10-million integers
39627 &gt;&gt;&gt; for i in xrange(10000):        # Set some values
39628 ...     a[i] = i
39629 &gt;&gt;&gt; sumitems(a,10000)
39630 49995000
39631 &gt;&gt;&gt;
39632 </PRE>
39633 </DIV>
39634 <P> The array &quot;object&quot; created by <TT>%array_class()</TT> does not
39635  encapsulate pointers inside a special array object. In fact, there is
39636  no bounds checking or safety of any kind (just like in C). Because of
39637  this, the arrays created by this library are extremely low-level
39638  indeed. You can't iterate over them nor can you even query their
39639  length. In fact, any valid memory address can be accessed if you want
39640  (negative indices, indices beyond the end of the array, etc.). Needless
39641  to say, this approach is not going to suit all applications. On the
39642  other hand, this low-level approach is extremely efficient and well
39643  suited for applications in which you need to create buffers, package
39644  binary data, etc.</P>
39645 <H3><A name="Python_nn49"></A>31.7.4 String handling</H3>
39646 <P> If a C function has an argument of <TT>char *</TT>, then a Python
39647  string can be passed as input. For example:</P>
39648 <DIV class="code">
39649 <PRE>
39650 // C
39651 void foo(char *s);
39652 </PRE>
39653 </DIV><DIV class="targetlang">
39654 <PRE>
39655 # Python
39656 &gt;&gt;&gt; foo(&quot;Hello&quot;)
39657 </PRE>
39658 </DIV>
39659 <P> When a Python string is passed as a parameter, the C function
39660  receives a pointer to the raw data contained in the string. Since
39661  Python strings are immutable, it is illegal for your program to change
39662  the value. In fact, doing so will probably crash the Python
39663  interpreter.</P>
39664 <P> If your program modifies the input parameter or uses it to return
39665  data, consider using the <TT>cstring.i</TT> library file described in
39666  the <A href="#Library">SWIG Library</A> chapter.</P>
39667 <P> When functions return a <TT>char *</TT>, it is assumed to be a
39668  NULL-terminated string. Data is copied into a new Python string and
39669  returned.</P>
39670 <P> If your program needs to work with binary data, you can use a
39671  typemap to expand a Python string into a pointer/length argument pair.
39672  As luck would have it, just such a typemap is already defined. Just do
39673  this:</P>
39674 <DIV class="code">
39675 <PRE>
39676 %apply (char *STRING, int LENGTH) { (char *data, int size) };
39677 ...
39678 int parity(char *data, int size, int initial);
39679 </PRE>
39680 </DIV>
39681 <P> Now in Python:</P>
39682 <DIV class="targetlang">
39683 <PRE>
39684 &gt;&gt;&gt; parity(&quot;e\x09ffss\x00\x00\x01\nx&quot;, 0)
39685 </PRE>
39686 </DIV>
39687 <P> If you need to return binary data, you might use the <TT>cstring.i</TT>
39688  library file. The <TT>cdata.i</TT> library can also be used to extra
39689  binary data from arbitrary pointers.</P>
39690 <H3><A name="Python_nn50"></A>31.7.5 Arrays</H3>
39691 <H3><A name="Python_nn51"></A>31.7.6 String arrays</H3>
39692 <H3><A name="Python_nn52"></A>31.7.7 STL wrappers</H3>
39693 <H2><A name="Python_nn53"></A>31.8 Typemaps</H2>
39694 <P> This section describes how you can modify SWIG's default wrapping
39695  behavior for various C/C++ datatypes using the <TT>%typemap</TT>
39696  directive. This is an advanced topic that assumes familiarity with the
39697  Python C API as well as the material in the &quot;<A href="#Typemaps">
39698 Typemaps</A>&quot; chapter.</P>
39699 <P> Before proceeding, it should be stressed that typemaps are not a
39700  required part of using SWIG---the default wrapping behavior is enough
39701  in most cases. Typemaps are only used if you want to change some aspect
39702  of the primitive C-Python interface or if you want to elevate your guru
39703  status.</P>
39704 <H3><A name="Python_nn54"></A>31.8.1 What is a typemap?</H3>
39705 <P> A typemap is nothing more than a code generation rule that is
39706  attached to a specific C datatype. For example, to convert integers
39707  from Python to C, you might define a typemap like this:</P>
39708 <DIV class="code">
39709 <PRE>
39710 %module example
39711
39712 %typemap(in) int {
39713         $1 = (int) PyLong_AsLong($input);
39714         printf(&quot;Received an integer : %d\n&quot;,$1);
39715 }
39716 %inline %{
39717 extern int fact(int n);
39718 %}
39719 </PRE>
39720 </DIV>
39721 <P> Typemaps are always associated with some specific aspect of code
39722  generation. In this case, the &quot;in&quot; method refers to the conversion of
39723  input arguments to C/C++. The datatype <TT>int</TT> is the datatype to
39724  which the typemap will be applied. The supplied C code is used to
39725  convert values. In this code a number of special variable prefaced by a
39726  <TT>$</TT> are used. The <TT>$1</TT> variable is placeholder for a
39727  local variable of type <TT>int</TT>. The <TT>$input</TT> variable is
39728  the input object of type <TT>PyObject *</TT>.</P>
39729 <P> When this example is compiled into a Python module, it operates as
39730  follows:</P>
39731 <DIV class="targetlang">
39732 <PRE>
39733 &gt;&gt;&gt; from example import *
39734 &gt;&gt;&gt; fact(6)
39735 Received an integer : 6
39736 720
39737 </PRE>
39738 </DIV>
39739 <P> In this example, the typemap is applied to all occurrences of the <TT>
39740 int</TT> datatype. You can refine this by supplying an optional
39741  parameter name. For example:</P>
39742 <DIV class="code">
39743 <PRE>
39744 %module example
39745
39746 %typemap(in) int nonnegative {
39747         $1 = (int) PyLong_AsLong($input);
39748         if ($1 &lt; 0) {
39749            PyErr_SetString(PyExc_ValueError,&quot;Expected a nonnegative value.&quot;);
39750            return NULL;
39751         }
39752 }
39753 %inline %{
39754 extern int fact(int nonnegative);
39755 %}
39756 </PRE>
39757 </DIV>
39758 <P> In this case, the typemap code is only attached to arguments that
39759  exactly match <TT>int nonnegative</TT>.</P>
39760 <P> The application of a typemap to specific datatypes and argument
39761  names involves more than simple text-matching--typemaps are fully
39762  integrated into the SWIG C++ type-system. When you define a typemap for
39763  <TT>int</TT>, that typemap applies to <TT>int</TT> and qualified
39764  variations such as <TT>const int</TT>. In addition, the typemap system
39765  follows <TT>typedef</TT> declarations. For example:</P>
39766 <DIV class="code">
39767 <PRE>
39768 %typemap(in) int n {
39769         $1 = (int) PyLong_AsLong($input);
39770         printf(&quot;n = %d\n&quot;,$1);
39771 }
39772 %inline %{
39773 typedef int Integer;
39774 extern int fact(Integer n);    // Above typemap is applied
39775 %}
39776 </PRE>
39777 </DIV>
39778 <P> Typemaps can also be defined for groups of consecutive arguments.
39779  For example:</P>
39780 <DIV class="code">
39781 <PRE>
39782 %typemap(in) (char *str, int len) {
39783     $1 = PyString_AsString($input);
39784     $2 = PyString_Size($input);
39785 };
39786
39787 int count(char c, char *str, int len);
39788 </PRE>
39789 </DIV>
39790 <P> When a multi-argument typemap is defined, the arguments are always
39791  handled as a single Python object. This allows the function to be used
39792  like this (notice how the length parameter is omitted):</P>
39793 <DIV class="targetlang">
39794 <PRE>
39795 &gt;&gt;&gt; example.count('e','Hello World')
39796 1
39797 &gt;&gt;&gt;
39798 </PRE>
39799 </DIV>
39800 <H3><A name="Python_nn55"></A>31.8.2 Python typemaps</H3>
39801 <P> The previous section illustrated an &quot;in&quot; typemap for converting
39802  Python objects to C. A variety of different typemap methods are defined
39803  by the Python module. For example, to convert a C integer back into a
39804  Python object, you might define an &quot;out&quot; typemap like this:</P>
39805 <DIV class="code">
39806 <PRE>
39807 %typemap(out) int {
39808     $result = PyInt_FromLong((long) $1);
39809 }
39810 </PRE>
39811 </DIV>
39812 <P> A detailed list of available methods can be found in the &quot;<A href="#Typemaps">
39813 Typemaps</A>&quot; chapter.</P>
39814 <P> However, the best source of typemap information (and examples) is
39815  probably the Python module itself. In fact, all of SWIG's default type
39816  handling is defined by typemaps. You can view these typemaps by looking
39817  at the files in the SWIG library. Just take into account that in the
39818  latest versions of swig (1.3.22+), the library files are not very
39819  pristine clear for the casual reader, as they used to be. The extensive
39820  use of macros and other ugly techniques in the latest version produce a
39821  very powerful and consistent python typemap library, but at the cost of
39822  simplicity and pedagogic value.</P>
39823 <P> To learn how to write a simple or your first typemap, you better
39824  take a look at the SWIG library version 1.3.20 or so.</P>
39825 <H3><A name="Python_nn56"></A>31.8.3 Typemap variables</H3>
39826 <P> Within typemap code, a number of special variables prefaced with a <TT>
39827 $</TT> may appear. A full list of variables can be found in the &quot;<A href="#Typemaps">
39828 Typemaps</A>&quot; chapter. This is a list of the most common variables:</P>
39829 <P> <TT>$1</TT></P>
39830 <DIV class="indent"> A C local variable corresponding to the actual type
39831  specified in the <TT>%typemap</TT> directive. For input values, this is
39832  a C local variable that's supposed to hold an argument value. For
39833  output values, this is the raw result that's supposed to be returned to
39834  Python.</DIV>
39835 <P> <TT>$input</TT></P>
39836 <DIV class="indent"> A <TT>PyObject *</TT> holding a raw Python object
39837  with an argument or variable value.</DIV>
39838 <P> <TT>$result</TT></P>
39839 <DIV class="indent"> A <TT>PyObject *</TT> that holds the result to be
39840  returned to Python.</DIV>
39841 <P> <TT>$1_name</TT></P>
39842 <DIV class="indent"> The parameter name that was matched.</DIV>
39843 <P> <TT>$1_type</TT></P>
39844 <DIV class="indent"> The actual C datatype matched by the typemap.</DIV>
39845 <P> <TT>$1_ltype</TT></P>
39846 <DIV class="indent"> An assignable version of the datatype matched by
39847  the typemap (a type that can appear on the left-hand-side of a C
39848  assignment operation). This type is stripped of qualifiers and may be
39849  an altered version of <TT>$1_type</TT>. All arguments and local
39850  variables in wrapper functions are declared using this type so that
39851  their values can be properly assigned.</DIV>
39852 <P> <TT>$symname</TT></P>
39853 <DIV class="indent"> The Python name of the wrapper function being
39854  created.</DIV>
39855 <H3><A name="Python_nn57"></A>31.8.4 Useful Python Functions</H3>
39856 <P> When you write a typemap, you usually have to work directly with
39857  Python objects. The following functions may prove to be useful.</P>
39858 <P><B> Python Integer Functions</B></P>
39859 <DIV class="code">
39860 <PRE>
39861 PyObject *PyInt_FromLong(long l);
39862 long      PyInt_AsLong(PyObject *);
39863 int       PyInt_Check(PyObject *);
39864 </PRE>
39865 </DIV>
39866 <P><B> Python Floating Point Functions</B></P>
39867 <DIV class="code">
39868 <PRE>
39869 PyObject *PyFloat_FromDouble(double);
39870 double    PyFloat_AsDouble(PyObject *);
39871 int       PyFloat_Check(PyObject *);
39872 </PRE>
39873 </DIV>
39874 <P><B> Python String Functions</B></P>
39875 <DIV class="code">
39876 <PRE>
39877 PyObject *PyString_FromString(char *);
39878 PyObject *PyString_FromStringAndSize(char *, lint len);
39879 int       PyString_Size(PyObject *);
39880 char     *PyString_AsString(PyObject *);
39881 int       PyString_Check(PyObject *);
39882 </PRE>
39883 </DIV>
39884 <P><B> Python List Functions</B></P>
39885 <DIV class="code">
39886 <PRE>
39887 PyObject *PyList_New(int size);
39888 int       PyList_Size(PyObject *list);
39889 PyObject *PyList_GetItem(PyObject *list, int i);
39890 int       PyList_SetItem(PyObject *list, int i, PyObject *item);
39891 int       PyList_Insert(PyObject *list, int i, PyObject *item);
39892 int       PyList_Append(PyObject *list, PyObject *item);
39893 PyObject *PyList_GetSlice(PyObject *list, int i, int j);
39894 int       PyList_SetSlice(PyObject *list, int i, int , PyObject *list2);
39895 int       PyList_Sort(PyObject *list);
39896 int       PyList_Reverse(PyObject *list);
39897 PyObject *PyList_AsTuple(PyObject *list);
39898 int       PyList_Check(PyObject *);
39899 </PRE>
39900 </DIV>
39901 <P><B> Python Tuple Functions</B></P>
39902 <DIV class="code">
39903 <PRE>
39904 PyObject *PyTuple_New(int size);
39905 int       PyTuple_Size(PyObject *);
39906 PyObject *PyTuple_GetItem(PyObject *, int i);
39907 int       PyTuple_SetItem(PyObject *, int i, PyObject *item);
39908 PyObject *PyTuple_GetSlice(PyObject *t, int i, int j);
39909 int       PyTuple_Check(PyObject *);
39910 </PRE>
39911 </DIV>
39912 <P><B> Python Dictionary Functions</B></P>
39913 <DIV class="code">
39914 <PRE>
39915 PyObject *PyDict_New();
39916 int       PyDict_Check(PyObject *);
39917 int       PyDict_SetItem(PyObject *p, PyObject *key, PyObject *val);
39918 int       PyDict_SetItemString(PyObject *p, const char *key, PyObject *val);
39919 int       PyDict_DelItem(PyObject *p, PyObject *key);
39920 int       PyDict_DelItemString(PyObject *p, char *key);
39921 PyObject* PyDict_Keys(PyObject *p);
39922 PyObject* PyDict_Values(PyObject *p);
39923 PyObject* PyDict_GetItem(PyObject *p, PyObject *key);
39924 PyObject* PyDict_GetItemString(PyObject *p, const char *key);
39925 int       PyDict_Next(PyObject *p, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue);
39926 Py_ssize_t PyDict_Size(PyObject *p);
39927 int       PyDict_Update(PyObject *a, PyObject *b);
39928 int       PyDict_Merge(PyObject *a, PyObject *b, int override);
39929 PyObject* PyDict_Items(PyObject *p);
39930 </PRE>
39931 </DIV>
39932 <P><B> Python File Conversion Functions</B></P>
39933 <DIV class="code">
39934 <PRE>
39935 PyObject *PyFile_FromFile(FILE *f);
39936 FILE     *PyFile_AsFile(PyObject *);
39937 int       PyFile_Check(PyObject *);
39938 </PRE>
39939 </DIV>
39940 <P><B> Abstract Object Interface</B></P>
39941 <DIV class="code">
39942 <PRE>
39943 write me
39944 </PRE>
39945 </DIV>
39946 <H2><A name="Python_nn58"></A>31.9 Typemap Examples</H2>
39947 <P> This section includes a few examples of typemaps. For more examples,
39948  you might look at the files &quot;<TT>python.swg</TT>&quot; and &quot;<TT>typemaps.i</TT>
39949 &quot; in the SWIG library.</P>
39950 <H3><A name="Python_nn59"></A>31.9.1 Converting Python list to a char **</H3>
39951 <P> A common problem in many C programs is the processing of command
39952  line arguments, which are usually passed in an array of NULL terminated
39953  strings. The following SWIG interface file allows a Python list object
39954  to be used as a <TT>char **</TT> object.</P>
39955 <DIV class="code">
39956 <PRE>
39957 %module argv
39958
39959 // This tells SWIG to treat char ** as a special case
39960 %typemap(in) char ** {
39961   /* Check if is a list */
39962   if (PyList_Check($input)) {
39963     int size = PyList_Size($input);
39964     int i = 0;
39965     $1 = (char **) malloc((size+1)*sizeof(char *));
39966     for (i = 0; i &lt; size; i++) {
39967       PyObject *o = PyList_GetItem($input,i);
39968       if (PyString_Check(o))
39969         $1[i] = PyString_AsString(PyList_GetItem($input,i));
39970       else {
39971         PyErr_SetString(PyExc_TypeError,&quot;list must contain strings&quot;);
39972         free($1);
39973         return NULL;
39974       }
39975     }
39976     $1[i] = 0;
39977   } else {
39978     PyErr_SetString(PyExc_TypeError,&quot;not a list&quot;);
39979     return NULL;
39980   }
39981 }
39982
39983 // This cleans up the char ** array we malloc'd before the function call
39984 %typemap(freearg) char ** {
39985   free((char *) $1);
39986 }
39987
39988 // Now a test function
39989 %inline %{
39990 int print_args(char **argv) {
39991     int i = 0;
39992     while (argv[i]) {
39993          printf(&quot;argv[%d] = %s\n&quot;, i,argv[i]);
39994          i++;
39995     }
39996     return i;
39997 }
39998 %}
39999
40000 </PRE>
40001 </DIV>
40002 <P> When this module is compiled, the wrapped C function now operates as
40003  follows :</P>
40004 <DIV class="targetlang">
40005 <PRE>
40006 &gt;&gt;&gt; from argv import *
40007 &gt;&gt;&gt; print_args([&quot;Dave&quot;,&quot;Mike&quot;,&quot;Mary&quot;,&quot;Jane&quot;,&quot;John&quot;])
40008 argv[0] = Dave
40009 argv[1] = Mike
40010 argv[2] = Mary
40011 argv[3] = Jane
40012 argv[4] = John
40013 5
40014 </PRE>
40015 </DIV>
40016 <P> In the example, two different typemaps are used. The &quot;in&quot; typemap is
40017  used to receive an input argument and convert it to a C array. Since
40018  dynamic memory allocation is used to allocate memory for the array, the
40019  &quot;freearg&quot; typemap is used to later release this memory after the
40020  execution of the C function.</P>
40021 <H3><A name="Python_nn60"></A>31.9.2 Expanding a Python object into
40022  multiple arguments</H3>
40023 <P> Suppose that you had a collection of C functions with arguments such
40024  as the following:</P>
40025 <DIV class="code">
40026 <PRE>
40027 int foo(int argc, char **argv);
40028 </PRE>
40029 </DIV>
40030 <P> In the previous example, a typemap was written to pass a Python list
40031  as the <TT>char **argv</TT>. This allows the function to be used from
40032  Python as follows:</P>
40033 <DIV class="targetlang">
40034 <PRE>
40035 &gt;&gt;&gt; foo(4, [&quot;foo&quot;,&quot;bar&quot;,&quot;spam&quot;,&quot;1&quot;])
40036 </PRE>
40037 </DIV>
40038 <P> Although this works, it's a little awkward to specify the argument
40039  count. To fix this, a multi-argument typemap can be defined. This is
40040  not very difficult--you only have to make slight modifications to the
40041  previous example:</P>
40042 <DIV class="code">
40043 <PRE>
40044 %typemap(in) (int argc, char **argv) {
40045   /* Check if is a list */
40046   if (PyList_Check($input)) {
40047     int i;
40048     $1 = PyList_Size($input);
40049     $2 = (char **) malloc(($1+1)*sizeof(char *));
40050     for (i = 0; i &lt; $1; i++) {
40051       PyObject *o = PyList_GetItem($input,i);
40052       if (PyString_Check(o))
40053         $2[i] = PyString_AsString(PyList_GetItem($input,i));
40054       else {
40055         PyErr_SetString(PyExc_TypeError,&quot;list must contain strings&quot;);
40056         free($2);
40057         return NULL;
40058       }
40059     }
40060     $2[i] = 0;
40061   } else {
40062     PyErr_SetString(PyExc_TypeError,&quot;not a list&quot;);
40063     return NULL;
40064   }
40065 }
40066
40067 %typemap(freearg) (int argc, char **argv) {
40068   free((char *) $2);
40069 }
40070 </PRE>
40071 </DIV>
40072 <P> When writing a multiple-argument typemap, each of the types is
40073  referenced by a variable such as <TT>$1</TT> or <TT>$2</TT>. The
40074  typemap code simply fills in the appropriate values from the supplied
40075  Python object.</P>
40076 <P> With the above typemap in place, you will find it no longer
40077  necessary to supply the argument count. This is automatically set by
40078  the typemap code. For example:</P>
40079 <DIV class="targetlang">
40080 <PRE>
40081 &gt;&gt;&gt; foo([&quot;foo&quot;,&quot;bar&quot;,&quot;spam&quot;,&quot;1&quot;])
40082 </PRE>
40083 </DIV>
40084 <H3><A name="Python_nn61"></A>31.9.3 Using typemaps to return arguments</H3>
40085 <P> A common problem in some C programs is that values may be returned
40086  in arguments rather than in the return value of a function. For
40087  example:</P>
40088 <DIV class="code">
40089 <PRE>
40090 /* Returns a status value and two values in out1 and out2 */
40091 int spam(double a, double b, double *out1, double *out2) {
40092         ... Do a bunch of stuff ...
40093         *out1 = result1;
40094         *out2 = result2;
40095         return status;
40096 };
40097
40098 </PRE>
40099 </DIV>
40100 <P> A typemap can be used to handle this case as follows :</P>
40101 <DIV class="code">
40102 <PRE>
40103 %module outarg
40104
40105 // This tells SWIG to treat an double * argument with name 'OutValue' as
40106 // an output value.  We'll append the value to the current result which 
40107 // is guaranteed to be a List object by SWIG.
40108
40109 %typemap(argout) double *OutValue {
40110     PyObject *o, *o2, *o3;
40111     o = PyFloat_FromDouble(*$1);
40112     if ((!$result) || ($result == Py_None)) {
40113         $result = o;
40114     } else {
40115         if (!PyTuple_Check($result)) {
40116             PyObject *o2 = $result;
40117             $result = PyTuple_New(1);
40118             PyTuple_SetItem(target,0,o2);
40119         }
40120         o3 = PyTuple_New(1);
40121         PyTuple_SetItem(o3,0,o);
40122         o2 = $result;
40123         $result = PySequence_Concat(o2,o3);
40124         Py_DECREF(o2);
40125         Py_DECREF(o3);
40126     }
40127 }
40128
40129 int spam(double a, double b, double *OutValue, double *OutValue);
40130
40131 </PRE>
40132 </DIV>
40133 <P> The typemap works as follows. First, a check is made to see if any
40134  previous result exists. If so, it is turned into a tuple and the new
40135  output value is concatenated to it. Otherwise, the result is returned
40136  normally. For the sample function <TT>spam()</TT>, there are three
40137  output values--meaning that the function will return a 3-tuple of the
40138  results.</P>
40139 <P> As written, the function must accept 4 arguments as input values,
40140  last two being pointers to doubles. If these arguments are only used to
40141  hold output values (and have no meaningful input value), an additional
40142  typemap can be written. For example:</P>
40143 <DIV class="code">
40144 <PRE>
40145 %typemap(in,numinputs=0) double *OutValue(double temp) {
40146     $1 = &amp;temp;
40147 }
40148
40149 </PRE>
40150 </DIV>
40151 <P> By specifying numinputs=0, the input value is ignored. However,
40152  since the argument still has to be set to some meaningful value before
40153  calling C, it is set to point to a local variable <TT>temp</TT>. When
40154  the function stores its output value, it will simply be placed in this
40155  local variable. As a result, the function can now be used as follows:</P>
40156 <DIV class="targetlang">
40157 <PRE>
40158 &gt;&gt;&gt; a = spam(4,5)
40159 &gt;&gt;&gt; print a
40160 (0, 2.45, 5.0)
40161 &gt;&gt;&gt; x,y,z = spam(4,5)
40162 &gt;&gt;&gt;
40163 </PRE>
40164 </DIV>
40165 <H3><A name="Python_nn62"></A>31.9.4 Mapping Python tuples into small
40166  arrays</H3>
40167 <P> In some applications, it is sometimes desirable to pass small arrays
40168  of numbers as arguments. For example :</P>
40169 <DIV class="code">
40170 <PRE>
40171 extern void set_direction(double a[4]);       // Set direction vector
40172 </PRE>
40173 </DIV>
40174 <P> This too, can be handled used typemaps as follows :</P>
40175 <DIV class="code">
40176 <PRE>
40177 // Grab a 4 element array as a Python 4-tuple
40178 %typemap(in) double[4](double temp[4]) {   // temp[4] becomes a local variable
40179   int i;
40180   if (PyTuple_Check($input)) {
40181     if (!PyArg_ParseTuple($input,&quot;dddd&quot;,temp,temp+1,temp+2,temp+3)) {
40182       PyErr_SetString(PyExc_TypeError,&quot;tuple must have 4 elements&quot;);
40183       return NULL;
40184     }
40185     $1 = &amp;temp[0];
40186   } else {
40187     PyErr_SetString(PyExc_TypeError,&quot;expected a tuple.&quot;);
40188     return NULL;
40189   }
40190 }
40191
40192 </PRE>
40193 </DIV>
40194 <P> This allows our <TT>set_direction</TT> function to be called from
40195  Python as follows :</P>
40196 <DIV class="targetlang">
40197 <PRE>
40198 &gt;&gt;&gt; set_direction((0.5,0.0,1.0,-0.25))
40199 </PRE>
40200 </DIV>
40201 <P> Since our mapping copies the contents of a Python tuple into a C
40202  array, such an approach would not be recommended for huge arrays, but
40203  for small structures, this approach works fine.</P>
40204 <H3><A name="Python_nn63"></A>31.9.5 Mapping sequences to C arrays</H3>
40205 <P> Suppose that you wanted to generalize the previous example to handle
40206  C arrays of different sizes. To do this, you might write a typemap as
40207  follows:</P>
40208 <DIV class="code">
40209 <PRE>
40210 // Map a Python sequence into any sized C double array
40211 %typemap(in) double[ANY](double temp[$1_dim0]) {
40212   int i;
40213   if (!PySequence_Check($input)) {
40214       PyErr_SetString(PyExc_TypeError,&quot;Expecting a sequence&quot;);
40215       return NULL;
40216   }
40217   if (PyObject_Length($input) != $1_dim0) {
40218       PyErr_SetString(PyExc_ValueError,&quot;Expecting a sequence with $1_dim0 elements&quot;);
40219       return NULL;
40220   }
40221   for (i =0; i &lt; $1_dim0; i++) {
40222       PyObject *o = PySequence_GetItem($input,i);
40223       if (!PyFloat_Check(o)) {
40224          Py_XDECREF(o);
40225          PyErr_SetString(PyExc_ValueError,&quot;Expecting a sequence of floats&quot;);
40226          return NULL;
40227       }
40228       temp[i] = PyFloat_AsDouble(o);
40229       Py_DECREF(o);
40230   }
40231   $1 = &amp;temp[0];
40232 }
40233 </PRE>
40234 </DIV>
40235 <P> In this case, the variable <TT>$1_dim0</TT> is expanded to match the
40236  array dimensions actually used in the C code. This allows the typemap
40237  to be applied to types such as:</P>
40238 <DIV class="code">
40239 <PRE>
40240 void foo(double x[10]);
40241 void bar(double a[4], double b[8]);
40242 </PRE>
40243 </DIV>
40244 <P> Since the above typemap code gets inserted into every wrapper
40245  function where used, it might make sense to use a helper function
40246  instead. This will greatly reduce the amount of wrapper code. For
40247  example:</P>
40248 <DIV class="code">
40249 <PRE>
40250 %{
40251 static int convert_darray(PyObject *input, double *ptr, int size) {
40252   int i;
40253   if (!PySequence_Check(input)) {
40254       PyErr_SetString(PyExc_TypeError,&quot;Expecting a sequence&quot;);
40255       return 0;
40256   }
40257   if (PyObject_Length(input) != size) {
40258       PyErr_SetString(PyExc_ValueError,&quot;Sequence size mismatch&quot;);
40259       return 0;
40260   }
40261   for (i =0; i &lt; size; i++) {
40262       PyObject *o = PySequence_GetItem(input,i);
40263       if (!PyFloat_Check(o)) {
40264          Py_XDECREF(o);
40265          PyErr_SetString(PyExc_ValueError,&quot;Expecting a sequence of floats&quot;);
40266          return 0;
40267       }
40268       ptr[i] = PyFloat_AsDouble(o);
40269       Py_DECREF(o);
40270   }
40271   return 1;
40272 }
40273 %}
40274
40275 %typemap(in) double [ANY](double temp[$1_dim0]) {
40276    if (!convert_darray($input,temp,$1_dim0))) {
40277       return NULL;
40278    }
40279    $1 = &amp;temp[0];
40280 }
40281 </PRE>
40282 </DIV>
40283 <H3><A name="Python_nn64"></A>31.9.6 Pointer handling</H3>
40284 <P> Occasionally, it might be necessary to convert pointer values that
40285  have been stored using the SWIG typed-pointer representation. Since
40286  there are several ways in which pointers can be represented, the
40287  following two functions are used to safely perform this conversion:</P>
40288 <P> <TT>int SWIG_ConvertPtr(PyObject *obj, void **ptr, swig_type_info
40289  *ty, int flags)</TT></P>
40290 <DIV class="indent"> Converts a Python object <TT>obj</TT> to a C
40291  pointer. The result of the conversion is placed into the pointer
40292  located at <TT>ptr</TT>. <TT>ty</TT> is a SWIG type descriptor
40293  structure. <TT>flags</TT> is used to handle error checking and other
40294  aspects of conversion. It is the bitwise-or of several flag values
40295  including <TT>SWIG_POINTER_EXCEPTION</TT> and <TT>SWIG_POINTER_DISOWN</TT>
40296 . The first flag makes the function raise an exception on type error.
40297  The second flag additionally steals ownership of an object. Returns 0
40298  on success and -1 on error.</DIV>
40299 <P> <TT>PyObject *SWIG_NewPointerObj(void *ptr, swig_type_info *ty, int
40300  own)</TT></P>
40301 <DIV class="indent"> Creates a new Python pointer object. <TT>ptr</TT>
40302  is the pointer to convert, <TT>ty</TT> is the SWIG type descriptor
40303  structure that describes the type, and <TT>own</TT> is a flag that
40304  indicates whether or not Python should take ownership of the pointer.</DIV>
40305 <P> Both of these functions require the use of a special SWIG
40306  type-descriptor structure. This structure contains information about
40307  the mangled name of the datatype, type-equivalence information, as well
40308  as information about converting pointer values under C++ inheritance.
40309  For a type of <TT>Foo *</TT>, the type descriptor structure is usually
40310  accessed as follows:</P>
40311 <DIV class="code">
40312 <PRE>
40313 Foo *f;
40314 if (SWIG_ConvertPtr($input, (void **) &amp;f, SWIGTYPE_p_Foo, SWIG_POINTER_EXCEPTION) == -1)
40315   return NULL;
40316
40317 PyObject *obj;
40318 obj = SWIG_NewPointerObj(f, SWIGTYPE_p_Foo, 0);
40319 </PRE>
40320 </DIV>
40321 <P> In a typemap, the type descriptor should always be accessed using
40322  the special typemap variable <TT>$1_descriptor</TT>. For example:</P>
40323 <DIV class="code">
40324 <PRE>
40325 %typemap(in) Foo * {
40326 if ((SWIG_ConvertPtr($input,(void **) &amp;$1, $1_descriptor,SWIG_POINTER_EXCEPTION)) == -1)
40327   return NULL;
40328 }
40329 </PRE>
40330 </DIV>
40331 <P> If necessary, the descriptor for any type can be obtained using the <TT>
40332 $descriptor()</TT> macro in a typemap. For example:</P>
40333 <DIV class="code">
40334 <PRE>
40335 %typemap(in) Foo * {
40336 if ((SWIG_ConvertPtr($input,(void **) &amp;$1, $descriptor(Foo *), 
40337                                                SWIG_POINTER_EXCEPTION)) == -1)
40338   return NULL;
40339 }
40340 </PRE>
40341 </DIV>
40342 <P> Although the pointer handling functions are primarily intended for
40343  manipulating low-level pointers, both functions are fully aware of
40344  Python proxy classes. Specifically, <TT>SWIG_ConvertPtr()</TT> will
40345  retrieve a pointer from any object that has a <TT>this</TT> attribute.
40346  In addition, <TT>SWIG_NewPointerObj()</TT> can automatically generate a
40347  proxy class object (if applicable).</P>
40348 <H2><A name="Python_nn65"></A>31.10 Docstring Features</H2>
40349 <P> Using docstrings in Python code is becoming more and more important
40350  and more tools are coming on the scene that take advantage of them,
40351  everything from full-blown documentation generators to class browsers
40352  and popup call-tips in Python-aware IDEs. Given the way that SWIG
40353  generates the proxy code by default, your users will normally get
40354  something like <TT>&quot;function_name(*args)&quot;</TT> in the popup calltip of
40355  their IDE which is next to useless when the real function prototype
40356  might be something like this:</P>
40357 <DIV class="code">
40358 <PRE>
40359 bool function_name(int x, int y, Foo* foo=NULL, Bar* bar=NULL);
40360 </PRE>
40361 </DIV>
40362 <P> The features described in this section make it easy for you to add
40363  docstrings to your modules, functions and methods that can then be used
40364  by the various tools out there to make the programming experience of
40365  your users much simpler.</P>
40366 <H3><A name="Python_nn66"></A>31.10.1 Module docstring</H3>
40367 <P> Python allows a docstring at the beginning of the <TT>.py</TT> file
40368  before any other statements, and it is typically used to give a general
40369  description of the entire module. SWIG supports this by setting an
40370  option of the <TT>%module</TT> directive. For example:</P>
40371 <DIV class="code">
40372 <PRE>
40373 %module(docstring=&quot;This is the example module's docstring&quot;) example
40374 </PRE>
40375 </DIV>
40376 <P> When you have more than just a line or so then you can retain the
40377  easy readability of the <TT>%module</TT> directive by using a macro.
40378  For example:</P>
40379 <DIV class="code">
40380 <PRE>
40381 %define DOCSTRING
40382 &quot;The `XmlResource` class allows program resources defining menus, 
40383 layout of controls on a panel, etc. to be loaded from an XML file.&quot;
40384 %enddef
40385
40386 %module(docstring=DOCSTRING) xrc
40387 </PRE>
40388 </DIV>
40389 <H3><A name="Python_nn67"></A>31.10.2 %feature(&quot;autodoc&quot;)</H3>
40390 <P> As alluded to above SWIG will generate all the function and method
40391  proxy wrappers with just &quot;*args&quot; (or &quot;*args, **kwargs&quot; if the -keyword
40392  option is used) for a parameter list and will then sort out the
40393  individual parameters in the C wrapper code. This is nice and simple
40394  for the wrapper code, but makes it difficult to be programmer and tool
40395  friendly as anyone looking at the <TT>.py</TT> file will not be able to
40396  find out anything about the parameters that the functions accept.</P>
40397 <P>But since SWIG does know everything about the function it is possible
40398  to generate a docstring containing the parameter types, names and
40399  default values. Since many of the docstring tools are adopting a
40400  standard of recognizing if the first thing in the docstring is a
40401  function prototype then using that instead of what they found from
40402  introspection, then life is good once more.</P>
40403 <P>SWIG's Python module provides support for the &quot;autodoc&quot; feature,
40404  which when attached to a node in the parse tree will cause a docstring
40405  to be generated that includes the name of the function, parameter
40406  names, default values if any, and return type if any. There are also
40407  three options for autodoc controlled by the value given to the feature,
40408  described below.</P>
40409 <H4><A name="Python_nn68"></A>31.10.2.1 %feature(&quot;autodoc&quot;, &quot;0&quot;)</H4>
40410 <P> When the &quot;0&quot; option is given then the types of the parameters will<EM>
40411  not</EM> be included in the autodoc string. For example, given this
40412  function prototype:</P>
40413 <DIV class="code">
40414 <PRE>
40415 %feature(&quot;autodoc&quot;, &quot;0&quot;);
40416 bool function_name(int x, int y, Foo* foo=NULL, Bar* bar=NULL);
40417 </PRE>
40418 </DIV>
40419 <P> Then Python code like this will be generated:</P>
40420 <DIV class="targetlang">
40421 <PRE>
40422 def function_name(*args, **kwargs):
40423     &quot;&quot;&quot;function_name(x, y, foo=None, bar=None) -&gt; bool&quot;&quot;&quot;
40424     ...
40425 </PRE>
40426 </DIV>
40427 <H4><A name="Python_nn69"></A>31.10.2.2 %feature(&quot;autodoc&quot;, &quot;1&quot;)</H4>
40428 <P> When the &quot;1&quot; option is used then the parameter types<EM> will</EM>
40429  be used in the autodoc string. In addition, an attempt is made to
40430  simplify the type name such that it makes more sense to the Python
40431  user. Pointer, reference and const info is removed, <TT>%rename</TT>'s
40432  are evaluated, etc. (This is not always successful, but works most of
40433  the time. See the next section for what to do when it doesn't.) Given
40434  the example above, then turning on the parameter types with the &quot;1&quot;
40435  option will result in Python code like this:</P>
40436 <DIV class="targetlang">
40437 <PRE>
40438 def function_name(*args, **kwargs):
40439     &quot;&quot;&quot;function_name(int x, int y, Foo foo=None, Bar bar=None) -&gt; bool&quot;&quot;&quot;
40440     ...
40441 </PRE>
40442 </DIV>
40443 <H4><A name="Python_nn70"></A>31.10.2.3 %feature(&quot;autodoc&quot;, &quot;docstring&quot;)</H4>
40444 <P> Finally, there are times when the automatically generated autodoc
40445  string will make no sense for a Python programmer, particularly when a
40446  typemap is involved. So if you give an explicit value for the autodoc
40447  feature then that string will be used in place of the automatically
40448  generated string. For example:</P>
40449 <DIV class="code">
40450 <PRE>
40451 %feature(&quot;autodoc&quot;, &quot;GetPosition() -&gt; (x, y)&quot;) GetPosition;
40452 void GetPosition(int* OUTPUT, int* OUTPUT);
40453 </PRE>
40454 </DIV>
40455 <H3><A name="Python_nn71"></A>31.10.3 %feature(&quot;docstring&quot;)</H3>
40456 <P> In addition to the autodoc strings described above, you can also
40457  attach any arbitrary descriptive text to a node in the parse tree with
40458  the &quot;docstring&quot; feature. When the proxy module is generated then any
40459  docstring associated with classes, function or methods are output. If
40460  an item already has an autodoc string then it is combined with the
40461  docstring and they are output together. If the docstring is all on a
40462  single line then it is output like this::</P>
40463 <DIV class="targetlang">
40464 <PRE>
40465 &quot;&quot;&quot;This is the docstring&quot;&quot;&quot;
40466 </PRE>
40467 </DIV>
40468 <P> Otherwise, to aid readability it is output like this:</P>
40469 <DIV class="targetlang">
40470 <PRE>
40471 &quot;&quot;&quot;
40472 This is a multi-line docstring
40473 with more than one line.
40474 &quot;&quot;&quot;
40475 </PRE>
40476 </DIV>
40477 <H2><A name="Python_nn72"></A>31.11 Python Packages</H2>
40478 <P> Using the <TT>package</TT> option of the <TT>%module</TT> directive
40479  allows you to specify what Python package that the module will be
40480  living in when installed.</P>
40481 <DIV class="code">
40482 <PRE>
40483 %module(package=&quot;wx&quot;) xrc
40484 </PRE>
40485 </DIV>
40486 <P> This is useful when the <TT>.i</TT> file is <TT>%import</TT>ed by
40487  another <TT>.i</TT> file. By default SWIG will assume that the importer
40488  is able to find the importee with just the module name, but if they
40489  live in separate Python packages then that won't work. However if the
40490  importee specifies what its package is with the <TT>%module</TT> option
40491  then the Python code generated for the importer will use that package
40492  name when importing the other module and also in base class
40493  declarations, etc. if the package name is different than its own.</P>
40494 <H2><A name="Python_python3support"></A>31.12 Python 3 Support</H2>
40495 <P> SWIG is able to support Python 3.0. The wrapper code generated by
40496  SWIG can be compiled with both Python 2.x or 3.0. Further more, by
40497  passing the <TT>-py3</TT> command line option to SWIG, wrapper code
40498  with some Python 3 specific features can be generated (see below
40499  subsections for details of these features). The <TT>-py3</TT> option
40500  also disables some incompatible features for Python 3, such as <TT>
40501 -classic</TT>.</P>
40502 <P> There is a list of known-to-be-broken features in Python 3:</P>
40503 <UL>
40504 <LI>No more support for FILE* typemaps, because PyFile_AsFile has been
40505  dropped in Python 3.</LI>
40506 <LI>The <TT>-apply</TT> command line option is removed and generating
40507  code using apply() is no longer supported.</LI>
40508 </UL>
40509 <P> The following are Python 3.0 new features that are currently
40510  supported by SWIG.</P>
40511 <H3><A name="Python_nn74"></A>31.12.1 Function annotation</H3>
40512 <P> The <TT>-py3</TT> option will enable function annotation support.
40513  When used SWIG is able to generate proxy method definitions like this:</P>
40514 <DIV class="code">
40515 <PRE>
40516   def foo(self, bar : &quot;int&quot; = 0) -&gt; &quot;void&quot; : ...
40517 </PRE>
40518 </DIV>
40519 <P> Also, even if without passing SWIG the <TT>-py3</TT> option, the
40520  parameter list still could be generated:</P>
40521 <DIV class="code">
40522 <PRE>
40523   def foo(self, bar = 0): ...
40524 </PRE>
40525 </DIV>
40526 <P> But for overloaded function or method, the parameter list would
40527  fallback to <TT>*args</TT> or <TT>self, *args</TT>, and <TT>**kwargs</TT>
40528  may be append depend on whether you enabled the keyword argument. This
40529  fallback is due to all overloaded functions share the same function in
40530  SWIG generated proxy class.</P>
40531 <P> For detailed usage of function annotation, see PEP 3107.</P>
40532 <H3><A name="Python_nn75"></A>31.12.2 Buffer interface</H3>
40533 <P> Buffer protocols were revised in Python 3. SWIG also gains a series
40534  of new typemaps to support buffer interfaces. These typemap macros are
40535  defined in <TT>pybuffer.i</TT>, which must be included in order to use
40536  them. By using these typemaps, your wrapped function will be able to
40537  accept any Python object that exposes a suitable buffer interface.</P>
40538 <P> For example, the <TT>get_path()</TT> function puts the path string
40539  into the memory pointed to by its argument:</P>
40540 <DIV class="code">
40541 <PRE>
40542 void get_path(char *s);
40543 </PRE>
40544 </DIV>
40545 <P> Then you can write a typemap like this: (the following example is
40546  applied to both Python 3.0 and 2.6, since the <TT>bytearray</TT> type
40547  is backported to 2.6.</P>
40548 <DIV class="code">
40549 <PRE>
40550 %include &lt;pybuffer.i&gt;
40551 %pybuffer_mutable_string(char *str);
40552 void get_path(char *s);
40553 </PRE>
40554 </DIV>
40555 <P> And then on the Python side the wrapped <TT>get_path</TT> could be
40556  used in this way:</P>
40557 <DIV class="targetlang">
40558 <PRE>
40559 &gt;&gt;&gt; p = bytearray(10)
40560 &gt;&gt;&gt; get_path(p)
40561 &gt;&gt;&gt; print(p)
40562 bytearray(b'/Foo/Bar/\x00')
40563 </PRE>
40564 </DIV>
40565 <P> The macros defined in <TT>pybuffer.i</TT> are similar to those in <TT>
40566 cstring.i</TT>:</P>
40567 <P><B> %pybuffer_mutable_binary(parm, size_parm)</B></P>
40568 <DIV class="indent">
40569 <P> The macro can be used to generate a typemap which maps a buffer of
40570  an object to a pointer provided by <TT>parm</TT> and a size argument
40571  provided by <TT>size_parm</TT>. For example:</P>
40572 <DIV class="code">
40573 <PRE>
40574 %pybuffer_mutable_binary(char *str, size_t size);
40575 ...
40576 int snprintf(char *str, size_t size, const char *format, ...);
40577 </PRE>
40578 </DIV>
40579 <P> In Python:</P>
40580 <DIV class="targetlang">
40581 <PRE>
40582 &gt;&gt;&gt; buf = bytearray(6)
40583 &gt;&gt;&gt; snprintf(buf, &quot;Hello world!&quot;)
40584 &gt;&gt;&gt; print(buf)
40585 bytearray(b'Hello\x00')
40586 &gt;&gt;&gt; 
40587 </PRE>
40588 </DIV></DIV>
40589 <P><B> %pybuffer_mutable_string(parm)</B></P>
40590 <DIV class="indent">
40591 <P> This typemap macro requires the buffer to be a zero terminated
40592  string, and maps the pointer of the buffer to <TT>parm</TT>. For
40593  example:</P>
40594 <DIV class="code">
40595 <PRE>
40596 %pybuffer_mutable_string(char *str);
40597 ...
40598 size_t make_upper(char *str);
40599 </PRE>
40600 </DIV>
40601 <P> In Python:</P>
40602 <DIV class="targetlang">
40603 <PRE>
40604 &gt;&gt;&gt; buf = bytearray(b'foo\x00')
40605 &gt;&gt;&gt; make_upper(buf)
40606 &gt;&gt;&gt; print(buf)
40607 bytearray(b'FOO\x00')
40608 &gt;&gt;&gt;
40609 </PRE>
40610 </DIV>
40611 <P> Both <TT>%pybuffer_mutable_binary</TT> and <TT>
40612 %pybuffer_mutable_string</TT> require the provided buffer to be mutable,
40613  eg. they can accept a <TT>bytearray</TT> type but can't accept an
40614  immutable <TT>byte</TT> type.</P>
40615 </DIV>
40616 <P><B> %pybuffer_binary(parm, size_parm)</B></P>
40617 <DIV class="indent">
40618 <P> This macro maps an object's buffer to a pointer <TT>parm</TT> and a
40619  size <TT>size_parm</TT>. It is similar to <TT>%pybuffer_mutable_binary</TT>
40620 , except the <TT>%pybuffer_binary</TT> an accept both mutable and
40621  immutable buffers. As a result, the wrapped function should not modify
40622  the buffer.</P>
40623 </DIV>
40624 <P><B> %pybuffer_string(parm)</B></P>
40625 <DIV class="indent">
40626 <P> This macro maps an object's buffer as a string pointer <TT>parm</TT>
40627 . It is similar to <TT>%pybuffer_mutable_string</TT> but the buffer
40628  could be both mutable and immutable. And your function should not
40629  modify the buffer.</P>
40630 </DIV>
40631 <H3><A name="Python_nn76"></A>31.12.3 Abstract base classes</H3>
40632 <P> By including <TT>pyabc.i</TT> and using the <TT>-py3</TT> command
40633  line option when calling SWIG, the proxy classes of the STL containers
40634  will automatically gain an appropriate abstract base class. For
40635  example, the following SWIG interface:</P>
40636 <DIV class="code">
40637 <PRE>
40638 %include &lt;pyabc.i&gt;
40639 %include &lt;std_map.i&gt;
40640 %include &lt;std_list.i&gt;
40641
40642 namespace std {
40643   %template(Mapii) map&lt;int, int&gt;;
40644   %template(IntList) list&lt;int&gt;;
40645 }
40646 </PRE>
40647 </DIV>
40648 <P> will generate a Python proxy class <TT>Mapii</TT> inheriting from <TT>
40649 collections.MutableMap</TT> and a proxy class <TT>IntList</TT>
40650  inheriting from <TT>collections.MutableSequence</TT>.</P>
40651 <P> <TT>pyabc.i</TT> also provides a macro <TT>%pythonabc</TT> that
40652  could be used to define an abstract base class for your own C++ class:</P>
40653 <DIV class="code">
40654 <PRE>
40655 %pythonabc(MySet, collections.MutableSet);
40656 </PRE>
40657 </DIV>
40658 <P> For details of abstract base class, please see PEP 3119.</P>
40659
40660 <!--  LocalWords:  polymorphism Typemaps STL typemap typemaps Docstring autodoc
40661  -->
40662
40663 <!--  LocalWords:  docstring SWIG's cxx py GCC linux DLL gcc fPIC Wiki Xlinker
40664  -->
40665
40666 <!--  LocalWords:  examplemodule DHAVE CONFIG lpython lm ldl mypython lsocket
40667  -->
40668
40669 <!--  LocalWords:  lnsl lpthread distutils enums namespaces
40670  -->
40671 <HR NOSHADE>
40672 <H1><A name="Ruby"></A>32 SWIG and Ruby</H1>
40673
40674 <!-- INDEX -->
40675 <DIV class="sectiontoc">
40676 <UL>
40677 <LI><A href="#Ruby_nn2">Preliminaries</A>
40678 <UL>
40679 <LI><A href="#Ruby_nn3">Running SWIG</A></LI>
40680 <LI><A href="#Ruby_nn4">Getting the right header files</A></LI>
40681 <LI><A href="#Ruby_nn5">Compiling a dynamic module</A></LI>
40682 <LI><A href="#Ruby_nn6">Using your module</A></LI>
40683 <LI><A href="#Ruby_nn7">Static linking</A></LI>
40684 <LI><A href="#Ruby_nn8">Compilation of C++ extensions</A></LI>
40685 </UL>
40686 </LI>
40687 <LI><A href="#Ruby_nn9">Building Ruby Extensions under Windows 95/NT</A>
40688 <UL>
40689 <LI><A href="#Ruby_nn10">Running SWIG from Developer Studio</A></LI>
40690 </UL>
40691 </LI>
40692 <LI><A href="#Ruby_nn11">The Ruby-to-C/C++ Mapping</A>
40693 <UL>
40694 <LI><A href="#Ruby_nn12">Modules</A></LI>
40695 <LI><A href="#Ruby_nn13">Functions</A></LI>
40696 <LI><A href="#Ruby_nn14">Variable Linking</A></LI>
40697 <LI><A href="#Ruby_nn15">Constants</A></LI>
40698 <LI><A href="#Ruby_nn16">Pointers</A></LI>
40699 <LI><A href="#Ruby_nn17">Structures</A></LI>
40700 <LI><A href="#Ruby_nn18">C++ classes</A></LI>
40701 <LI><A href="#Ruby_nn19">C++ Inheritance</A></LI>
40702 <LI><A href="#Ruby_nn20">C++ Overloaded Functions</A></LI>
40703 <LI><A href="#Ruby_nn21">C++ Operators</A></LI>
40704 <LI><A href="#Ruby_nn22">C++ namespaces</A></LI>
40705 <LI><A href="#Ruby_nn23">C++ templates</A></LI>
40706 <LI><A href="#Ruby_nn23_1">C++ Standard Template Library (STL)</A></LI>
40707 <LI><A href="#C_STL_Functors">C++ STL Functors</A></LI>
40708 <LI><A href="#Ruby_C_Iterators">C++ STL Iterators</A></LI>
40709 <LI><A href="#Ruby_nn24">C++ Smart Pointers</A></LI>
40710 <LI><A href="#Ruby_nn25">Cross-Language Polymorphism</A>
40711 <UL>
40712 <LI><A href="#Ruby_nn26">Exception Unrolling</A></LI>
40713 </UL>
40714 </LI>
40715 </UL>
40716 </LI>
40717 <LI><A href="#Ruby_nn27">Naming</A>
40718 <UL>
40719 <LI><A href="#Ruby_nn28">Defining Aliases</A></LI>
40720 <LI><A href="#Ruby_nn29">Predicate Methods</A></LI>
40721 <LI><A href="#Ruby_nn30">Bang Methods</A></LI>
40722 <LI><A href="#Ruby_nn31">Getters and Setters</A></LI>
40723 </UL>
40724 </LI>
40725 <LI><A href="#Ruby_nn32">Input and output parameters</A></LI>
40726 <LI><A href="#Ruby_nn33">Exception handling</A>
40727 <UL>
40728 <LI><A href="#Ruby_nn34">Using the %exception directive</A></LI>
40729 <LI><A href="#Ruby_nn34_2">Handling Ruby Blocks</A></LI>
40730 <LI><A href="#Ruby_nn35">Raising exceptions</A></LI>
40731 <LI><A href="#Ruby_nn36">Exception classes</A></LI>
40732 </UL>
40733 </LI>
40734 <LI><A href="#Ruby_nn37">Typemaps</A>
40735 <UL>
40736 <LI><A href="#Ruby_nn38">What is a typemap?</A></LI>
40737 <LI><A href="#Ruby_Typemap_scope">Typemap scope</A></LI>
40738 <LI><A href="#Ruby_Copying_a_typemap">Copying a typemap</A></LI>
40739 <LI><A href="#Ruby_Deleting_a_typemap">Deleting a typemap</A></LI>
40740 <LI><A href="#Ruby_Placement_of_typemaps">Placement of typemaps</A></LI>
40741 <LI><A href="#Ruby_nn39">Ruby typemaps</A>
40742 <UL>
40743 <LI><A href="#Ruby_in_typemap">&nbsp;&quot;in&quot; typemap</A></LI>
40744 <LI><A href="#Ruby_typecheck_typemap">&quot;typecheck&quot; typemap</A></LI>
40745 <LI><A href="#Ruby_out_typemap">&nbsp;&quot;out&quot; typemap</A></LI>
40746 <LI><A href="#Ruby_arginit_typemap">&quot;arginit&quot; typemap</A></LI>
40747 <LI><A href="#Ruby_default_typemap">&quot;default&quot; typemap</A></LI>
40748 <LI><A href="#Ruby_check_typemap">&quot;check&quot; typemap</A></LI>
40749 <LI><A href="#Ruby_argout_typemap_">&quot;argout&quot; typemap</A></LI>
40750 <LI><A href="#Ruby_freearg_typemap_">&quot;freearg&quot; typemap</A></LI>
40751 <LI><A href="#Ruby_newfree_typemap">&quot;newfree&quot; typemap</A></LI>
40752 <LI><A href="#Ruby_memberin_typemap">&quot;memberin&quot; typemap</A></LI>
40753 <LI><A href="#Ruby_varin_typemap">&quot;varin&quot; typemap</A></LI>
40754 <LI><A href="#Ruby_varout_typemap_">&quot;varout&quot; typemap</A></LI>
40755 <LI><A href="#Ruby_throws_typemap">&quot;throws&quot; typemap</A></LI>
40756 <LI><A href="#Ruby_directorin_typemap">directorin typemap</A></LI>
40757 <LI><A href="#Ruby_directorout_typemap">directorout typemap</A></LI>
40758 <LI><A href="#Ruby_directorargout_typemap">directorargout typemap</A></LI>
40759 <LI><A href="#Ruby_ret_typemap">ret typemap</A></LI>
40760 <LI><A href="#Ruby_globalin_typemap">globalin typemap</A></LI>
40761 </UL>
40762 </LI>
40763 <LI><A href="#Ruby_nn40">Typemap variables</A></LI>
40764 <LI><A href="#Ruby_nn41">Useful Functions</A>
40765 <UL>
40766 <LI><A href="#Ruby_nn42">C Datatypes to Ruby Objects</A></LI>
40767 <LI><A href="#Ruby_nn43">Ruby Objects to C Datatypes</A></LI>
40768 <LI><A href="#Ruby_nn44">Macros for VALUE</A></LI>
40769 <LI><A href="#Ruby_nn45">Exceptions</A></LI>
40770 <LI><A href="#Ruby_nn46">Iterators</A></LI>
40771 </UL>
40772 </LI>
40773 <LI><A href="#Ruby_nn47">Typemap Examples</A></LI>
40774 <LI><A href="#Ruby_nn48">Converting a Ruby array to a char **</A></LI>
40775 <LI><A href="#Ruby_nn49">Collecting arguments in a hash</A></LI>
40776 <LI><A href="#Ruby_nn50">Pointer handling</A>
40777 <UL>
40778 <LI><A href="#Ruby_nn51">Ruby Datatype Wrapping</A></LI>
40779 </UL>
40780 </LI>
40781 <LI><A href="#Ruby_nn52">Example: STL Vector to Ruby Array</A></LI>
40782 </UL>
40783 </LI>
40784 <LI><A href="#Ruby_nn65">Docstring Features</A>
40785 <UL>
40786 <LI><A href="#Ruby_nn66">Module docstring</A></LI>
40787 <LI><A href="#Ruby_nn67">%feature(&quot;autodoc&quot;)</A>
40788 <UL>
40789 <LI><A href="#Ruby_nn68">%feature(&quot;autodoc&quot;, &quot;0&quot;)</A></LI>
40790 <LI><A href="#Ruby_autodoc1">%feature(&quot;autodoc&quot;, &quot;1&quot;)</A></LI>
40791 <LI><A href="#Ruby_autodoc2">%feature(&quot;autodoc&quot;, &quot;2&quot;)</A></LI>
40792 <LI><A href="#Ruby_feature_autodoc3">%feature(&quot;autodoc&quot;, &quot;3&quot;)</A></LI>
40793 <LI><A href="#Ruby_nn70">%feature(&quot;autodoc&quot;, &quot;docstring&quot;)</A></LI>
40794 </UL>
40795 </LI>
40796 <LI><A href="#Ruby_nn71">%feature(&quot;docstring&quot;)</A></LI>
40797 </UL>
40798 </LI>
40799 <LI><A href="#Ruby_nn53">Advanced Topics</A>
40800 <UL>
40801 <LI><A href="#Ruby_nn54">Operator overloading</A></LI>
40802 <LI><A href="#Ruby_nn55">Creating Multi-Module Packages</A></LI>
40803 <LI><A href="#Ruby_nn56">Specifying Mixin Modules</A></LI>
40804 </UL>
40805 </LI>
40806 <LI><A href="#Ruby_nn57">Memory Management</A>
40807 <UL>
40808 <LI><A href="#Ruby_nn58">Mark and Sweep Garbage Collector</A></LI>
40809 <LI><A href="#Ruby_nn59">Object Ownership</A></LI>
40810 <LI><A href="#Ruby_nn60">Object Tracking</A></LI>
40811 <LI><A href="#Ruby_nn61">Mark Functions</A></LI>
40812 <LI><A href="#Ruby_nn62">Free Functions</A></LI>
40813 <LI><A href="#Ruby_nn63">Embedded Ruby and the C++ Stack</A></LI>
40814 </UL>
40815 </LI>
40816 </UL>
40817 </DIV>
40818 <!-- INDEX -->
40819 <P>This chapter describes SWIG's support of Ruby.</P>
40820 <H2><A name="Ruby_nn2"></A>32.1 Preliminaries</H2>
40821 <P> SWIG 1.3 is known to work with Ruby versions 1.6 and later. Given
40822  the choice, you should use the latest stable version of Ruby. You
40823  should also determine if your system supports shared libraries and
40824  dynamic loading. SWIG will work with or without dynamic loading, but
40825  the compilation process will vary.</P>
40826 <P>This chapter covers most SWIG features, but in less depth than is
40827  found in earlier chapters. At the very least, make sure you also read
40828  the &quot;<A href="#SWIG">SWIG Basics</A>&quot; chapter. It is also assumed that
40829  the reader has a basic understanding of Ruby.</P>
40830 <H3><A name="Ruby_nn3"></A>32.1.1 Running SWIG</H3>
40831 <P> To build a Ruby module, run SWIG using the <TT>-ruby</TT> option:</P>
40832 <DIV class="code shell">
40833 <PRE>$ <B>swig -ruby example.i</B>
40834 </PRE>
40835 </DIV>
40836 <P> If building a C++ extension, add the <TT>-c++</TT> option:</P>
40837 <DIV class="code shell">
40838 <PRE>$ <B>swig -c++ -ruby example.i</B>
40839 </PRE>
40840 </DIV>
40841 <P> This creates a file <TT>example_wrap.c</TT> (<TT>example_wrap.cxx</TT>
40842  if compiling a C++ extension) that contains all of the code needed to
40843  build a Ruby extension module. To finish building the module, you need
40844  to compile this file and link it with the rest of your program.</P>
40845 <H3><A name="Ruby_nn4"></A>32.1.2 Getting the right header files</H3>
40846 <P> In order to compile the wrapper code, the compiler needs the <TT>
40847 ruby.h</TT> header file. This file is usually contained in a directory
40848  such as</P>
40849 <DIV class="code shell diagram">
40850 <PRE>/usr/lib/ruby/1.8/x86_64-linux-gnu/ruby.h
40851 <BR>/usr/local/lib/ruby/1.6/i686-linux/ruby.h
40852 <BR></PRE>
40853 </DIV>
40854 <P> The exact location may vary on your machine, but the above location
40855  is typical. If you are not entirely sure where Ruby is installed, you
40856  can run Ruby to find out. For example:</P>
40857 <DIV class="code shell">
40858 <PRE>$ <B>ruby -e 'puts $:.join(&quot;\n&quot;)'</B>
40859 <BR>/usr/local/lib/ruby/site_ruby/1.6 /usr/local/lib/ruby/site_ruby/1.6/i686-linux
40860 <BR>/usr/local/lib/ruby/site_ruby /usr/local/lib/ruby/1.6 /usr/local/lib/ruby/1.6/i686-linux .
40861 <BR> </PRE>
40862 </DIV>
40863 <H3><A name="Ruby_nn5"></A>32.1.3 Compiling a dynamic module</H3>
40864 <P> Ruby extension modules are typically compiled into shared libraries
40865  that the interpreter loads dynamically at runtime. Since the exact
40866  commands for doing this vary from platform to platform, your best bet
40867  is to follow the steps described in the <TT>README.EXT</TT> file from
40868  the Ruby distribution:</P>
40869 <OL>
40870 <LI>
40871 <P>Create a file called <TT>extconf.rb</TT> that looks like the
40872  following:</P>
40873 <DIV class="code targetlang">
40874 <PRE>require 'mkmf'
40875 <BR>create_makefile('example')
40876 <BR></PRE>
40877 </DIV></LI>
40878 <LI>
40879 <P>Type the following to build the extension:</P>
40880 <DIV class="code shell">
40881 <PRE>$ <B>ruby extconf.rb</B>
40882 <BR>$ <B>make</B>
40883 <BR>$ <B>make install</B>
40884     </PRE>
40885 </DIV></LI>
40886 </OL>
40887 <P> Of course, there is the problem that mkmf does not work correctly on
40888  all platforms, e.g, HPUX. If you need to add your own make rules to the
40889  file that <TT>extconf.rb</TT> produces, you can add this:</P>
40890 <DIV class="code targetlang">
40891 <PRE>open(&quot;Makefile&quot;, &quot;a&quot;) { |mf|
40892 <BR> puts &lt;&lt;EOM
40893 <BR> # Your make rules go here
40894 <BR> EOM
40895 <BR>}
40896 <BR></PRE>
40897 </DIV>
40898 <P> to the end of the <TT>extconf.rb</TT> file. If for some reason you
40899  don't want to use the standard approach, you'll need to determine the
40900  correct compiler and linker flags for your build platform. For example,
40901  a typical sequence of commands for the Linux operating system would
40902  look something like this:</P>
40903 <DIV class="code shell">
40904 <PRE>$ <B>swig -ruby example.i</B>
40905 <BR>$ <B>gcc -c example.c</B>
40906 <BR>$ <B>gcc -c example_wrap.c -I/usr/local/lib/ruby/1.6/i686-linux</B> 
40907 <BR>$ <B>gcc -shared example.o example_wrap.o -o example.so</B>
40908 </PRE>
40909 </DIV>
40910 <P> For other platforms it may be necessary to compile with the <TT>
40911 -fPIC</TT> option to generate position-independent code. If in doubt,
40912  consult the manual pages for your compiler and linker to determine the
40913  correct set of options. You might also check the <A href="http://www.dabeaz.com/cgi-bin/wiki.pl">
40914 SWIG Wiki</A> for additional information.</P>
40915 <H3><A name="Ruby_nn6"></A>32.1.4 Using your module</H3>
40916 <P> Ruby<I> module</I> names must be capitalized, but the convention for
40917  Ruby<I> feature</I> names is to use lowercase names. So, for example,
40918  the<B> Etc</B> extension module is imported by requiring the<B> etc</B>
40919  feature:</P>
40920 <DIV class="code targetlang">
40921 <PRE># The feature name begins with a lowercase letter...
40922 <BR>require 'etc'
40923 <BR>
40924 <BR># ... but the module name begins with an uppercase letter
40925 <BR>puts &quot;Your login name: #{Etc.getlogin}&quot;
40926 <BR></PRE>
40927 </DIV>
40928 <P> To stay consistent with this practice, you should always specify a<B>
40929  lowercase</B> module name with SWIG's <TT>%module</TT> directive. SWIG
40930  will automatically correct the resulting Ruby module name for your
40931  extension. So for example, a SWIG interface file that begins with:</P>
40932 <DIV class="code">
40933 <PRE>%module example
40934 <BR></PRE>
40935 </DIV>
40936 <P> will result in an extension module using the feature name &quot;example&quot;
40937  and Ruby module name &quot;Example&quot;.</P>
40938 <H3><A name="Ruby_nn7"></A>32.1.5 Static linking</H3>
40939 <P> An alternative approach to dynamic linking is to rebuild the Ruby
40940  interpreter with your extension module added to it. In the past, this
40941  approach was sometimes necessary due to limitations in dynamic loading
40942  support on certain machines. However, the situation has improved
40943  greatly over the last few years and you should not consider this
40944  approach unless there is really no other option.</P>
40945 <P>The usual procedure for adding a new module to Ruby involves finding
40946  the Ruby source, adding an entry to the <TT>ext/Setup</TT> file, adding
40947  your directory to the list of extensions in the file, and finally
40948  rebuilding Ruby.</P>
40949 <H3><A name="Ruby_nn8"></A>32.1.6 Compilation of C++ extensions</H3>
40950 <P> On most machines, C++ extension modules should be linked using the
40951  C++ compiler. For example:</P>
40952 <DIV class="code shell">
40953 <PRE>$ <B>swig -c++ -ruby example.i</B>
40954 <BR>$ <B>g++ -c example.cxx</B>
40955 <BR>$ <B>g++ -c example_wrap.cxx -I/usr/local/lib/ruby/1.6/i686-linux</B>
40956 <BR>$ <B>g++ -shared example.o example_wrap.o -o example.so</B>
40957 </PRE>
40958 </DIV>
40959 <P> If you've written an <TT>extconf.rb</TT> script to automatically
40960  generate a <TT>Makefile</TT> for your C++ extension module, keep in
40961  mind that (as of this writing) Ruby still uses <TT>gcc</TT> and not <TT>
40962 g++</TT> as its linker. As a result, the required C++ runtime library
40963  support will not be automatically linked into your extension module and
40964  it may fail to load on some platforms. A workaround for this problem is
40965  use the <TT>mkmf</TT> module's <TT>append_library()</TT> method to add
40966  one of the C++ runtime libraries to the list of libraries linked into
40967  your extension, e.g.</P>
40968 <DIV class="code targetlang">
40969 <PRE>require 'mkmf'
40970 <BR>$libs = append_library($libs, &quot;supc++&quot;)
40971 <BR>create_makefile('example')
40972 <BR></PRE>
40973 </DIV>
40974 <H2><A name="Ruby_nn9"></A>32.2 Building Ruby Extensions under Windows
40975  95/NT</H2>
40976 <P> Building a SWIG extension to Ruby under Windows 95/NT is roughly
40977  similar to the process used with Unix. Normally, you will want to
40978  produce a DLL that can be loaded into the Ruby interpreter. For all
40979  recent versions of Ruby, the procedure described above (i.e. using an <TT>
40980 extconf.rb</TT> script) will work with Windows as well; you should be
40981  able to build your code into a DLL by typing:</P>
40982 <DIV class="code shell">
40983 <PRE>C:\swigtest&gt; <B>ruby extconf.rb</B>
40984 <BR>C:\swigtest&gt; <B>nmake</B>
40985 <BR>C:\swigtest&gt; <B>nmake install</B>
40986 </PRE>
40987 </DIV>
40988 <P> The remainder of this section covers the process of compiling
40989  SWIG-generated Ruby extensions with Microsoft Visual C++ 6 (i.e. within
40990  the Developer Studio IDE, instead of using the command line tools). In
40991  order to build extensions, you may need to download the source
40992  distribution to the Ruby package, as you will need the Ruby header
40993  files.</P>
40994 <H3><A name="Ruby_nn10"></A>32.2.1 Running SWIG from Developer Studio</H3>
40995 <P> If you are developing your application within Microsoft developer
40996  studio, SWIG can be invoked as a custom build option. The process
40997  roughly follows these steps :</P>
40998 <UL>
40999 <LI> Open up a new workspace and use the AppWizard to select a DLL
41000  project.</LI>
41001 <LI> Add both the SWIG interface file (the .i file), any supporting C
41002  files, and the name of the wrapper file that will be created by SWIG
41003  (i.e. <TT>example_wrap.c</TT>). Note : If using C++, choose a different
41004  suffix for the wrapper file such as <TT>example_wrap.cxx</TT>. Don't
41005  worry if the wrapper file doesn't exist yet--Developer Studio will keep
41006  a reference to it around.</LI>
41007 <LI> Select the SWIG interface file and go to the settings menu. Under
41008  settings, select the &quot;Custom Build&quot; option.</LI>
41009 <LI> Enter &quot;SWIG&quot; in the description field.</LI>
41010 <LI> Enter &quot;<TT>swig -ruby -o $(ProjDir)\$(InputName)_wrap.c
41011  $(InputPath)</TT>&quot; in the &quot;Build command(s) field&quot;. You may have to
41012  include the path to swig.exe.</LI>
41013 <LI> Enter &quot;<TT>$(ProjDir)\$(InputName)_wrap.c</TT>&quot; in the &quot;Output
41014  files(s) field&quot;.</LI>
41015 <LI> Next, select the settings for the entire project and go to the
41016  C/C++ tab and select the Preprocessor category. Add NT=1 to the
41017  Preprocessor definitions. This must be set else you will get
41018  compilation errors. Also add IMPORT to the preprocessor definitions,
41019  else you may get runtime errors. Also add the include directories for
41020  your Ruby installation under &quot;Additional include directories&quot;.</LI>
41021 <LI> Next, select the settings for the entire project and go to the Link
41022  tab and select the General category. Set the name of the output file to
41023  match the name of your Ruby module (i.e.. example.dll). Next add the
41024  Ruby library file to your link libraries under Object/Library modules.
41025  For example &quot;mswin32-ruby16.lib. You also need to add the path to the
41026  library under the Input tab - Additional library path.</LI>
41027 <LI> Build your project.</LI>
41028 </UL>
41029 <P> Now, assuming all went well, SWIG will be automatically invoked when
41030  you build your project. Any changes made to the interface file will
41031  result in SWIG being automatically invoked to produce a new version of
41032  the wrapper file. To run your new Ruby extension, simply run Ruby and
41033  use the <TT>require</TT> command as normal. For example if you have
41034  this ruby file run.rb:</P>
41035 <DIV class="code targetlang">
41036 <PRE># file: run.rb
41037 <BR>require 'Example'
41038 <BR>
41039 <BR># Call a c function
41040 <BR>print &quot;Foo = &quot;, Example.Foo, &quot;\n&quot;
41041 <BR></PRE>
41042 </DIV>
41043 <P> Ensure the dll just built is in your path or current directory, then
41044  run the Ruby script from the DOS/Command prompt:</P>
41045 <DIV class="code shell">
41046 <PRE>C:\swigtest&gt; <B>ruby run.rb</B>
41047 <BR>Foo = 3.0
41048 <BR></PRE>
41049 </DIV>
41050 <H2><A name="Ruby_nn11"></A>32.3 The Ruby-to-C/C++ Mapping</H2>
41051 <P> This section describes the basics of how SWIG maps C or C++
41052  declarations in your SWIG interface files to Ruby constructs.</P>
41053 <H3><A name="Ruby_nn12"></A>32.3.1 Modules</H3>
41054 <P> The SWIG <TT>%module</TT> directive specifies the name of the Ruby
41055  module. If you specify:</P>
41056 <DIV class="code">
41057 <PRE>%module example</PRE>
41058 </DIV>
41059 <P> then everything is wrapped into a Ruby module named <TT>Example</TT>
41060  that is nested directly under the global module. You can specify a more
41061  deeply nested module by specifying the fully-qualified module name in
41062  quotes, e.g.</P>
41063 <DIV class="code">
41064 <PRE>%module &quot;foo::bar::spam&quot;</PRE>
41065 </DIV>
41066 <P> An alternate method of specifying a nested module name is to use the
41067 <!--span style=&quot;font-family: monospace;&quot;-->
41068  -prefix option on the SWIG command line. The prefix that you specify
41069  with this option will be prepended to the module name specified with
41070  the
41071 <!--span style=&quot;font-family: monospace;&quot;-->
41072  %module directive in your SWIG interface file. So for example, this
41073  declaration at the top of your SWIG interface file:
41074 <BR></P>
41075 <DIV class="code">
41076 <PRE>%module &quot;foo::bar::spam&quot;</PRE>
41077 </DIV>
41078 <P> will result in a nested module name of
41079 <!--span style=&quot;font-family: monospace;&quot;-->
41080  Foo::Bar::Spam, but you can achieve the
41081 <!--span style=&quot;font-style: italic;&quot;-->
41082  same effect by specifying:
41083 <BR></P>
41084 <DIV class="code">
41085 <PRE>%module spam</PRE>
41086 </DIV>
41087 <P> and then running SWIG with the
41088 <!--span style=&quot;font-family: monospace;&quot;-->
41089  -prefix command line option:
41090 <BR></P>
41091 <DIV class="code shell">
41092 <PRE>$ <B>swig -ruby -prefix &quot;foo::bar::&quot; example.i</B></PRE>
41093 </DIV>
41094 <P> Starting with SWIG 1.3.20, you can also choose to wrap everything
41095  into the global module by specifying the <TT>-globalmodule</TT> option
41096  on the SWIG command line, i.e.</P>
41097 <DIV class="code shell">
41098 <PRE>$ <B>swig -ruby -globalmodule example.i</B></PRE>
41099 </DIV>
41100 <P> Note that this does not relieve you of the requirement of specifying
41101  the SWIG module name with the <TT>%module</TT> directive (or the <TT>
41102 -module</TT> command-line option) as described earlier.</P>
41103 <P>When choosing a module name, do not use the same name as a built-in
41104  Ruby command or standard module name, as the results may be
41105  unpredictable. Similarly, if you're using the <TT>-globalmodule</TT>
41106  option to wrap everything into the global module, take care that the
41107  names of your constants, classes and methods don't conflict with any of
41108  Ruby's built-in names.</P>
41109 <H3><A name="Ruby_nn13"></A>32.3.2 Functions</H3>
41110 <P> Global functions are wrapped as Ruby module methods. For example,
41111  given the SWIG interface file <TT>example.i</TT>:</P>
41112 <DIV class="code">
41113 <PRE>%module example
41114 <BR>
41115 <BR>int fact(int n);
41116 <BR></PRE>
41117 </DIV>
41118 <P> and C source file <TT>example.c</TT>:</P>
41119 <DIV class="code">
41120 <PRE>int fact(int n) {
41121 <BR> if (n == 0)
41122 <BR> return 1;
41123 <BR> return (n * fact(n-1));
41124 <BR>}
41125 <BR></PRE>
41126 </DIV>
41127 <P> SWIG will generate a method<I> fact</I> in the<I> Example</I> module
41128  that can be used like so:</P>
41129 <DIV class="code targetlang">
41130 <PRE>$ <B>irb</B>
41131 <BR>irb(main):001:0&gt; <B>require 'example'</B>
41132 <BR>true
41133 <BR>irb(main):002:0&gt; <B>Example.fact(4)</B>
41134 <BR>24
41135 <BR></PRE>
41136 </DIV>
41137 <H3><A name="Ruby_nn14"></A>32.3.3 Variable Linking</H3>
41138 <P> C/C++ global variables are wrapped as a pair of singleton methods
41139  for the module: one to get the value of the global variable and one to
41140  set it. For example, the following SWIG interface file declares two
41141  global variables:</P>
41142 <DIV class="code">
41143 <PRE>// SWIG interface file with global variables
41144 <BR>%module example
41145 <BR>...
41146 <BR>%inline %{
41147 <BR>extern int variable1;
41148 <BR>extern double Variable2;
41149 <BR>%}
41150 <BR>...
41151 <BR></PRE>
41152 </DIV>
41153 <P> Now look at the Ruby interface:</P>
41154 <DIV class="code targetlang">
41155 <PRE>$ <B>irb</B>
41156 <BR>irb(main):001:0&gt; <B>require 'Example'</B>
41157 <BR>true
41158 <BR>irb(main):002:0&gt; <B>Example.variable1 = 2</B>
41159 <BR>2
41160 <BR>irb(main):003:0&gt; <B>Example.Variable2 = 4 * 10.3</B>
41161 <BR>41.2
41162 <BR>irb(main):004:0&gt; <B>Example.Variable2</B>
41163 <BR>41.2
41164 <BR></PRE>
41165 </DIV>
41166 <P> If you make an error in variable assignment, you will receive an
41167  error message. For example:</P>
41168 <DIV class="code targetlang">
41169 <PRE>irb(main):005:0&gt; <B>Example.Variable2 = &quot;hello&quot;</B>
41170 <BR>TypeError: no implicit conversion to float from string
41171 <BR>from (irb):5:in `Variable2='
41172 <BR>from (irb):5
41173 <BR></PRE>
41174 </DIV>
41175 <P> If a variable is declared as <TT>const</TT>, it is wrapped as a
41176  read-only variable. Attempts to modify its value will result in an
41177  error.</P>
41178 <P>To make ordinary variables read-only, you can also use the <TT>
41179 %immutable</TT> directive. For example:</P>
41180 <DIV class="code">
41181 <PRE>%immutable;
41182 <BR>%inline %{
41183 <BR>extern char *path;
41184 <BR>%}
41185 <BR>%mutable;
41186 <BR></PRE>
41187 </DIV>
41188 <P> The <TT>%immutable</TT> directive stays in effect until it is
41189  explicitly disabled using <TT>%mutable</TT>.</P>
41190 <H3><A name="Ruby_nn15"></A>32.3.4 Constants</H3>
41191 <P> C/C++ constants are wrapped as module constants initialized to the
41192  appropriate value. To create a constant, use <TT>#define</TT> or the <TT>
41193 %constant</TT> directive. For example:</P>
41194 <DIV class="code">
41195 <PRE>#define PI 3.14159
41196 <BR>#define VERSION &quot;1.0&quot;
41197 <BR>
41198 <BR>%constant int FOO = 42;
41199 <BR>%constant const char *path = &quot;/usr/local&quot;;
41200 <BR>
41201 <BR>const int BAR = 32;
41202 <BR></PRE>
41203 </DIV>
41204 <P> Remember to use the :: operator in Ruby to get at these constant
41205  values, e.g.</P>
41206 <DIV class="code targetlang">
41207 <PRE>$ <B>irb</B>
41208 <BR>irb(main):001:0&gt; <B>require 'Example'</B>
41209 <BR>true
41210 <BR>irb(main):002:0&gt; <B>Example::PI</B>
41211 <BR>3.14159
41212 <BR></PRE>
41213 </DIV>
41214 <H3><A name="Ruby_nn16"></A>32.3.5 Pointers</H3>
41215 <P> &quot;Opaque&quot; pointers to arbitrary C/C++ types (i.e. types that aren't
41216  explicitly declared in your SWIG interface file) are wrapped as data
41217  objects. So, for example, consider a SWIG interface file containing
41218  only the declarations:</P>
41219 <DIV class="code">
41220 <PRE>Foo *get_foo();
41221 <BR>void set_foo(Foo *foo);
41222 <BR></PRE>
41223 </DIV>
41224 <P> For this case, the<I> get_foo()</I> method returns an instance of an
41225  internally generated Ruby class:</P>
41226 <DIV class="code targetlang">
41227 <PRE>irb(main):001:0&gt; <B>foo = Example::get_foo()</B>
41228 <BR>#&lt;SWIG::TYPE_p_Foo:0x402b1654&gt;
41229 <BR></PRE>
41230 </DIV>
41231 <P> A <TT>NULL</TT> pointer is always represented by the Ruby <TT>nil</TT>
41232  object.</P>
41233 <H3><A name="Ruby_nn17"></A>32.3.6 Structures</H3>
41234 <P> C/C++ structs are wrapped as Ruby classes, with accessor methods
41235  (i.e. &quot;getters&quot; and &quot;setters&quot;) for all of the struct members. For
41236  example, this struct declaration:</P>
41237 <DIV class="code">
41238 <PRE>struct Vector {
41239 <BR> double x, y;
41240 <BR>};
41241 <BR></PRE>
41242 </DIV>
41243 <P> gets wrapped as a <TT>Vector</TT> class, with Ruby instance methods <TT>
41244 x</TT>, <TT>x=</TT>, <TT>y</TT> and <TT>y=</TT>. These methods can be
41245  used to access structure data from Ruby as follows:</P>
41246 <DIV class="code targetlang">
41247 <PRE>$ <B>irb</B>
41248 <BR>irb(main):001:0&gt; <B>require 'Example'</B>
41249 <BR>true
41250 <BR>irb(main):002:0&gt; <B>f = Example::Vector.new</B>
41251 <BR>#&lt;Example::Vector:0x4020b268&gt;
41252 <BR>irb(main):003:0&gt; <B>f.x = 10</B>
41253 <BR>nil
41254 <BR>irb(main):004:0&gt; <B>f.x</B>
41255 <BR>10.0
41256 <BR></PRE>
41257 </DIV>
41258 <P> Similar access is provided for unions and the public data members of
41259  C++ classes.</P>
41260 <P><TT>const</TT> members of a structure are read-only. Data members can
41261  also be forced to be read-only using the <TT>%immutable</TT> directive
41262  (in C++, <TT>private</TT> may also be used). For example:</P>
41263 <DIV class="code">
41264 <PRE>struct Foo {
41265 <BR> ...
41266 <BR> %immutable;
41267 <BR> int x; /* Read-only members */
41268 <BR> char *name;
41269 <BR> %mutable;
41270 <BR> ...
41271 <BR>};
41272 <BR></PRE>
41273 </DIV>
41274 <P> When <TT>char *</TT> members of a structure are wrapped, the
41275  contents are assumed to be dynamically allocated using <TT>malloc</TT>
41276  or <TT>new</TT> (depending on whether or not SWIG is run with the <TT>
41277 -c++</TT> option). When the structure member is set, the old contents
41278  will be released and a new value created. If this is not the behavior
41279  you want, you will have to use a typemap (described shortly).</P>
41280 <P>Array members are normally wrapped as read-only. For example, this
41281  code:</P>
41282 <DIV class="code">
41283 <PRE>struct Foo {
41284 <BR> int x[50];
41285 <BR>};
41286 <BR></PRE>
41287 </DIV>
41288 <P> produces a single accessor function like this:</P>
41289 <DIV class="code">
41290 <PRE>int *Foo_x_get(Foo *self) {
41291 <BR> return self-&gt;x;
41292 <BR>};
41293 <BR></PRE>
41294 </DIV>
41295 <P> If you want to set an array member, you will need to supply a
41296  &quot;memberin&quot; typemap described in the <A href="#ruby_cpp_smart_pointers">
41297 section on typemaps</A>. As a special case, SWIG does generate code to
41298  set array members of type <TT>char</TT> (allowing you to store a Ruby
41299  string in the structure).</P>
41300 <P>When structure members are wrapped, they are handled as pointers. For
41301  example,</P>
41302 <DIV class="code">
41303 <PRE>struct Foo {
41304 <BR> ...
41305 <BR>};
41306 <BR>
41307 <BR>struct Bar {
41308 <BR> Foo f;
41309 <BR>};
41310 <BR></PRE>
41311 </DIV>
41312 <P> generates accessor functions such as this:</P>
41313 <DIV class="code">
41314 <PRE>Foo *Bar_f_get(Bar *b) {
41315 <BR> return &amp;b-&gt;f;
41316 <BR>}
41317 <BR>
41318 <BR>void Bar_f_set(Bar *b, Foo *val) {
41319 <BR> b-&gt;f = *val;
41320 <BR>}
41321 <BR></PRE>
41322 </DIV>
41323 <H3><A name="Ruby_nn18"></A>32.3.7 C++ classes</H3>
41324 <P> Like structs, C++ classes are wrapped by creating a new Ruby class
41325  of the same name with accessor methods for the public class member
41326  data. Additionally, public member functions for the class are wrapped
41327  as Ruby instance methods, and public static member functions are
41328  wrapped as Ruby singleton methods. So, given the C++ class declaration:</P>
41329 <DIV class="code">
41330 <PRE>class List {
41331 <BR>public:
41332 <BR> List();
41333 <BR> ~List();
41334 <BR> int search(char *item);
41335 <BR> void insert(char *item);
41336 <BR> void remove(char *item);
41337 <BR> char *get(int n);
41338 <BR> int length;
41339 <BR> static void print(List *l);
41340 <BR>};
41341 <BR></PRE>
41342 </DIV>
41343 <P> SWIG would create a <TT>List</TT> class with:</P>
41344 <UL>
41345 <LI> instance methods<I> search</I>,<I> insert</I>,<I> remove</I>, and<I>
41346  get</I>;</LI>
41347 <LI> instance methods<I> length</I> and<I> length=</I> (to get and set
41348  the value of the<I> length</I> data member); and,</LI>
41349 <LI> a<I> print</I> singleton method for the class.</LI>
41350 </UL>
41351 <P> In Ruby, these functions are used as follows:</P>
41352 <DIV class="code targetlang">
41353 <PRE>require 'Example'
41354 <BR>
41355 <BR>l = Example::List.new
41356 <BR>
41357 <BR>l.insert(&quot;Ale&quot;)
41358 <BR>l.insert(&quot;Stout&quot;)
41359 <BR>l.insert(&quot;Lager&quot;)
41360 <BR>Example.print(l)
41361 <BR>l.length()
41362 <BR>----- produces the following output 
41363 <BR>Lager
41364 <BR>Stout
41365 <BR>Ale
41366 <BR>3
41367 <BR></PRE>
41368 </DIV>
41369 <H3><A name="Ruby_nn19"></A>32.3.8 C++ Inheritance</H3>
41370 <P> The SWIG type-checker is fully aware of C++ inheritance. Therefore,
41371  if you have classes like this:</P>
41372 <DIV class="code">
41373 <PRE>class Parent {
41374 <BR> ...
41375 <BR>};
41376 <BR>
41377 <BR>class Child : public Parent {
41378 <BR> ...
41379 <BR>};
41380 <BR></PRE>
41381 </DIV>
41382 <P> those classes are wrapped into a hierarchy of Ruby classes that
41383  reflect the same inheritance structure. All of the usual Ruby utility
41384  methods work normally:</P>
41385 <DIV class="code">
41386 <PRE>irb(main):001:0&gt; <B>c = Child.new</B>
41387 <BR>#&lt;Bar:0x4016efd4&gt;
41388 <BR>irb(main):002:0&gt; <B>c.instance_of? Child</B>
41389 <BR>true
41390 <BR>irb(main):003:0&gt; <B>b.instance_of? Parent</B>
41391 <BR>false
41392 <BR>irb(main):004:0&gt; <B>b.is_a? Child</B>
41393 <BR>true
41394 <BR>irb(main):005:0&gt; <B>b.is_a? Parent</B>
41395 <BR>true
41396 <BR>irb(main):006:0&gt; <B>Child &lt; Parent</B>
41397 <BR>true
41398 <BR>irb(main):007:0&gt; <B>Child &gt; Parent</B>
41399 <BR>false
41400 <BR></PRE>
41401 </DIV>
41402 <P> Furthermore, if you have a function like this:</P>
41403 <DIV class="code">
41404 <PRE>void spam(Parent *f);
41405 <BR></PRE>
41406 </DIV>
41407 <P> then the function <TT>spam()</TT> accepts <TT>Parent</TT>* or a
41408  pointer to any class derived from <TT>Parent</TT>.</P>
41409 <P>Until recently, the Ruby module for SWIG didn't support multiple
41410  inheritance, and this is still the default behavior. This doesn't mean
41411  that you can't wrap C++ classes which inherit from multiple base
41412  classes; it simply means that only the<B> first</B> base class listed
41413  in the class declaration is considered, and any additional base classes
41414  are ignored. As an example, consider a SWIG interface file with a
41415  declaration like this:</P>
41416 <DIV class="code">
41417 <PRE>class Derived : public Base1, public Base2
41418 <BR>{
41419 <BR> ...
41420 <BR>};
41421 <BR></PRE>
41422 </DIV>
41423 <P> For this case, the resulting Ruby class (<TT>Derived</TT>) will only
41424  consider <TT>Base1</TT> as its superclass. It won't inherit any of <TT>
41425 Base2</TT>'s member functions or data and it won't recognize <TT>Base2</TT>
41426  as an &quot;ancestor&quot; of <TT>Derived</TT> (i.e. the<EM> is_a?</EM>
41427  relationship would fail). When SWIG processes this interface file,
41428  you'll see a warning message like:</P>
41429 <DIV class="code shell">
41430 <PRE>example.i:5: Warning(802): Warning for Derived: Base Base2 ignored.
41431 <BR>Multiple inheritance is not supported in Ruby.
41432 <BR></PRE>
41433 </DIV>
41434 <P> Starting with SWIG 1.3.20, the Ruby module for SWIG provides limited
41435  support for multiple inheritance. Because the approach for dealing with
41436  multiple inheritance introduces some limitations, this is an optional
41437  feature that you can activate with the <TT>-minherit</TT> command-line
41438  option:</P>
41439 <DIV class="code shell">
41440 <PRE>$ <B>swig -c++ -ruby -minherit example.i</B></PRE>
41441 </DIV>
41442 <P> Using our previous example, if your SWIG interface file contains a
41443  declaration like this:</P>
41444 <DIV class="code">
41445 <PRE>class Derived : public Base1, public Base2
41446 <BR>{
41447 <BR> ...
41448 <BR>};
41449 <BR></PRE>
41450 </DIV>
41451 <P> and you run SWIG with the <TT>-minherit</TT> command-line option,
41452  then you will end up with a Ruby class <TT>Derived</TT> that appears to
41453  &quot;inherit&quot; the member data and functions from both <TT>Base1</TT> and <TT>
41454 Base2</TT>. What actually happens is that three different top-level
41455  classes are created, with Ruby's <TT>Object</TT> class as their
41456  superclass. Each of these classes defines a nested module named <TT>
41457 Impl</TT>, and it's in these nested <TT>Impl</TT> modules that the
41458  actual instance methods for the classes are defined, i.e.</P>
41459 <DIV class="code targetlang">
41460 <PRE>class Base1
41461 <BR> module Impl
41462 <BR> # Define Base1 methods here
41463 <BR> end
41464 <BR> include Impl
41465 <BR>end
41466 <BR>
41467 <BR>class Base2
41468 <BR> module Impl
41469 <BR> # Define Base2 methods here
41470 <BR> end
41471 <BR> include Impl
41472 <BR>end
41473 <BR>
41474 <BR>class Derived
41475 <BR> module Impl
41476 <BR> include Base1::Impl
41477 <BR> include Base2::Impl
41478 <BR> # Define Derived methods here
41479 <BR> end
41480 <BR> include Impl
41481 <BR>end
41482 <BR></PRE>
41483 </DIV>
41484 <P> Observe that after the nested <TT>Impl</TT> module for a class is
41485  defined, it is mixed-in to the class itself. Also observe that the <TT>
41486 Derived::Impl</TT> module first mixes-in its base classes' <TT>Impl</TT>
41487  modules, thus &quot;inheriting&quot; all of their behavior.</P>
41488 <P>The primary drawback is that, unlike the default mode of operation,
41489  neither <TT>Base1</TT> nor <TT>Base2</TT> is a true superclass of <TT>
41490 Derived</TT> anymore:</P>
41491 <DIV class="code targetlang">
41492 <PRE>obj = Derived.new
41493 <BR>obj.is_a? Base1 # this will return false...
41494 <BR>obj.is_a? Base2 # ... and so will this
41495 <BR></PRE>
41496 </DIV>
41497 <P> In most cases, this is not a serious problem since objects of type <TT>
41498 Derived</TT> will otherwise behave as though they inherit from both <TT>
41499 Base1</TT> and <TT>Base2</TT> (i.e. they exhibit <A href="http://c2.com/cgi/wiki?DuckTyping">
41500 &quot;Duck Typing&quot;</A>).</P>
41501 <H3><A name="Ruby_nn20"></A>32.3.9 C++ Overloaded Functions</H3>
41502 <P> C++ overloaded functions, methods, and constructors are mostly
41503  supported by SWIG. For example, if you have two functions like this:</P>
41504 <DIV class="code">
41505 <PRE>void foo(int);
41506 <BR>void foo(char *c);
41507 <BR></PRE>
41508 </DIV>
41509 <P> You can use them in Ruby in a straightforward manner:</P>
41510 <DIV class="code targetlang">
41511 <PRE>irb(main):001:0&gt; <B>foo(3)</B> # foo(int)
41512 <BR>irb(main):002:0&gt; <B>foo(&quot;Hello&quot;)</B> # foo(char *c)
41513 <BR></PRE>
41514 </DIV>
41515 <P>Similarly, if you have a class like this,</P>
41516 <DIV class="code">
41517 <PRE>class Foo {
41518 <BR>public:
41519 <BR> Foo();
41520 <BR> Foo(const Foo &amp;);
41521 <BR> ...
41522 <BR>};
41523 <BR></PRE>
41524 </DIV>
41525 <P>you can write Ruby code like this:</P>
41526 <DIV class="code targetlang">
41527 <PRE>irb(main):001:0&gt; <B>f = Foo.new</B> # Create a Foo
41528 <BR>irb(main):002:0&gt; <B>g = Foo.new(f)</B> # Copy f
41529 <BR></PRE>
41530 </DIV>
41531 <P> Overloading support is not quite as flexible as in C++. Sometimes
41532  there are methods that SWIG can't disambiguate. For example:</P>
41533 <DIV class="code">
41534 <PRE>void spam(int);
41535 <BR>void spam(short);
41536 <BR></PRE>
41537 </DIV>
41538 <P>or</P>
41539 <DIV class="code">
41540 <PRE>void foo(Bar *b);
41541 <BR>void foo(Bar &amp;b);
41542 <BR></PRE>
41543 </DIV>
41544 <P> If declarations such as these appear, you will get a warning message
41545  like this:</P>
41546 <DIV class="code shell">
41547 <PRE>example.i:12: Warning(509): Overloaded spam(short) is shadowed by spam(int)
41548 <BR>at example.i:11.
41549 <BR> </PRE>
41550 </DIV>
41551 <P> To fix this, you either need to ignore or rename one of the methods.
41552  For example:</P>
41553 <DIV class="code">
41554 <PRE>%rename(spam_short) spam(short);
41555 <BR>...
41556 <BR>void spam(int); 
41557 <BR>void spam(short); // Accessed as spam_short
41558 <BR></PRE>
41559 </DIV>
41560 <P>or</P>
41561 <DIV class="code">
41562 <PRE>%ignore spam(short);
41563 <BR>...
41564 <BR>void spam(int); 
41565 <BR>void spam(short); // Ignored
41566 <BR></PRE>
41567 </DIV>
41568 <P> SWIG resolves overloaded functions and methods using a
41569  disambiguation scheme that ranks and sorts declarations according to a
41570  set of type-precedence rules. The order in which declarations appear in
41571  the input does not matter except in situations where ambiguity
41572  arises--in this case, the first declaration takes precedence.</P>
41573 <P>Please refer to the <A href="#SWIGPlus">&quot;SWIG and C++&quot;</A> chapter
41574  for more information about overloading.</P>
41575 <H3><A name="Ruby_nn21"></A>32.3.10 C++ Operators</H3>
41576 <P> For the most part, overloaded operators are handled automatically by
41577  SWIG and do not require any special treatment on your part. So if your
41578  class declares an overloaded addition operator, e.g.</P>
41579 <DIV class="code">
41580 <PRE>class Complex {
41581 <BR> ...
41582 <BR> Complex operator+(Complex &amp;);
41583 <BR> ...
41584 <BR>};
41585 <BR></PRE>
41586 </DIV>
41587 <P> the resulting Ruby class will also support the addition (+) method
41588  correctly.</P>
41589 <P>For cases where SWIG's built-in support is not sufficient, C++
41590  operators can be wrapped using the <TT>%rename</TT> directive
41591  (available on SWIG 1.3.10 and later releases). All you need to do is
41592  give the operator the name of a valid Ruby identifier. For example:</P>
41593 <DIV class="code">
41594 <PRE>%rename(add_complex) operator+(Complex &amp;, Complex &amp;);
41595 <BR>...
41596 <BR>Complex operator+(Complex &amp;, Complex &amp;);
41597 <BR></PRE>
41598 </DIV>
41599 <P>Now, in Ruby, you can do this:</P>
41600 <DIV class="code targetlang">
41601 <PRE>a = Example::Complex.new(2, 3)
41602 <BR>b = Example::Complex.new(4, -1)
41603 <BR>c = Example.add_complex(a, b)
41604 <BR></PRE>
41605 </DIV>
41606 <P> More details about wrapping C++ operators into Ruby operators is
41607  discussed in the <A href="#ruby_operator_overloading">section on
41608  operator overloading</A>.</P>
41609 <H3><A name="Ruby_nn22"></A>32.3.11 C++ namespaces</H3>
41610 <P> SWIG is aware of C++ namespaces, but namespace names do not appear
41611  in the module nor do namespaces result in a module that is broken up
41612  into submodules or packages. For example, if you have a file like this,</P>
41613 <DIV class="code">
41614 <PRE>%module example
41615 <BR>
41616 <BR>namespace foo {
41617 <BR> int fact(int n);
41618 <BR> struct Vector {
41619 <BR> double x,y,z;
41620 <BR> };
41621 <BR>};
41622 <BR></PRE>
41623 </DIV>
41624 <P>it works in Ruby as follows:</P>
41625 <DIV class="code targetlang">
41626 <PRE>irb(main):001:0&gt; <B>require 'example'</B>
41627 <BR>true
41628 <BR>irb(main):002:0&gt; <B>Example.fact(3)</B>
41629 <BR>6
41630 <BR>irb(main):003:0&gt; <B>v = Example::Vector.new</B>
41631 <BR>#&lt;Example::Vector:0x4016f4d4&gt;
41632 <BR>irb(main):004:0&gt; <B>v.x = 3.4</B>
41633 <BR>3.4
41634 <BR>irb(main):004:0&gt; <B>v.y</B>
41635 <BR>0.0
41636 <BR></PRE>
41637 </DIV>
41638 <P> If your program has more than one namespace, name conflicts (if any)
41639  can be resolved using <TT>%rename</TT> For example:</P>
41640 <DIV class="code">
41641 <PRE>%rename(Bar_spam) Bar::spam;
41642 <BR>
41643 <BR>namespace Foo {
41644 <BR> int spam();
41645 <BR>}
41646 <BR>
41647 <BR>namespace Bar {
41648 <BR> int spam();
41649 <BR>}
41650 <BR></PRE>
41651 </DIV>
41652 <P> If you have more than one namespace and your want to keep their
41653  symbols separate, consider wrapping them as separate SWIG modules. For
41654  example, make the module name the same as the namespace and create
41655  extension modules for each namespace separately. If your program
41656  utilizes thousands of small deeply nested namespaces each with
41657  identical symbol names, well, then you get what you deserve.</P>
41658 <H3><A name="Ruby_nn23"></A>32.3.12 C++ templates</H3>
41659 <P> C++ templates don't present a huge problem for SWIG. However, in
41660  order to create wrappers, you have to tell SWIG to create wrappers for
41661  a particular template instantiation. To do this, you use the <TT>
41662 %template</TT> directive. For example:</P>
41663 <DIV class="code">
41664 <PRE>%module example
41665 <BR>
41666 <BR>%{
41667 <BR>#include &quot;pair.h&quot;
41668 <BR>%}
41669 <BR>
41670 <BR>template&lt;class T1, class T2&gt;
41671 <BR>struct pair {
41672 <BR> typedef T1 first_type;
41673 <BR> typedef T2 second_type;
41674 <BR> T1 first;
41675 <BR> T2 second;
41676 <BR> pair();
41677 <BR> pair(const T1&amp;, const T2&amp;);
41678 <BR> ~pair();
41679 <BR>};
41680 <BR>
41681 <BR>%template(Pairii) pair&lt;int,int&gt;;
41682 <BR></PRE>
41683 </DIV>
41684 <P>In Ruby:</P>
41685 <DIV class="code targetlang">
41686 <PRE>irb(main):001:0&gt; <B>require 'example'</B>
41687 <BR>true
41688 <BR>irb(main):002:0&gt; <B>p = Example::Pairii.new(3, 4)</B>
41689 <BR>#&lt;Example:Pairii:0x4016f4df&gt;
41690 <BR>irb(main):003:0&gt; <B>p.first</B>
41691 <BR>3
41692 <BR>irb(main):004:0&gt; <B>p.second</B>
41693 <BR>4
41694 <BR></PRE>
41695 </DIV>
41696 <H3><A name="Ruby_nn23_1"></A>32.3.13 C++ Standard Template Library
41697  (STL)</H3>
41698 <P> On a related note, the standard SWIG library contains a number of
41699  modules that provide typemaps for standard C++ library classes (such as
41700  <TT>std::pair</TT>, <TT>std::string</TT> and <TT>std::vector</TT>).
41701  These library modules don't provide wrappers around the templates
41702  themselves, but they do make it convenient for users of your extension
41703  module to pass Ruby objects (such as arrays and strings) to wrapped C++
41704  code that expects instances of standard C++ templates. For example,
41705  suppose the C++ library you're wrapping has a function that expects a
41706  vector of floats:</P>
41707 <DIV class="code">
41708 <PRE>%module example
41709 <BR>
41710 <BR>float sum(const std::vector&lt;float&gt;&amp; values);
41711 <BR></PRE>
41712 </DIV>
41713 <P> Rather than go through the hassle of writing an &quot;in&quot; typemap to
41714  convert an array of Ruby numbers into a std::vector&lt;float&gt;, you can
41715  just use the <TT>std_vector.i</TT> module from the standard SWIG
41716  library:</P>
41717 <DIV class="code">
41718 <PRE>%module example
41719 <BR>
41720 <BR><B>%include std_vector.i</B>
41721 <BR>float sum(const std::vector&lt;float&gt;&amp; values);
41722 <BR></PRE>
41723 </DIV>
41724 <P>Ruby's STL wrappings provide additional methods to make them behave
41725  more similarly to Ruby's native classes.</P>
41726 <P>Thus, you can do, for example:</P>
41727 <DIV class="targetlang">
41728 <PRE>v = IntVector.new
41729 <!--span class=&quot;targetlang&quot;-->
41730 <BR>v &lt;&lt; 2
41731 <!--span class=&quot;targetlang&quot;-->
41732 <BR>v &lt;&lt; 3
41733 <BR>v &lt;&lt; 4
41734 <BR>v.each { |x| puts x }
41735 <BR>
41736 <!--span style=&quot;font-weight: bold;&quot;-->
41737 <BR>=&gt; 2
41738 <BR style="font-weight: bold;">
41739 <!--span style=&quot;font-weight: bold;&quot;-->
41740 3
41741 <BR style="font-weight: bold;">
41742 <!--span style=&quot;font-weight: bold;&quot;-->
41743 4
41744 <BR>v.delete_if { |x| x == 3 }
41745 <BR>
41746 <!--span style=&quot;font-weight: bold;&quot;-->
41747 =&gt; [2,4]</PRE>
41748 </DIV>
41749 <P>The SWIG Ruby module provides also the ability for all the STL
41750  containers to carry around Ruby native objects (Fixnum, Classes, etc)
41751  making them act almost like Ruby's own Array, Hash, etc. &nbsp; To do that,
41752  you need to define a container that contains a swig::GC_VALUE, like:</P>
41753 <DIV class="code" style="font-family: monospace;">%module nativevector
41754 <BR>
41755 <BR> %{
41756 <BR> std::vector&lt; swig::GC_VALUE &gt; NativeVector;
41757 <BR> %}
41758 <BR>
41759 <BR> %template(NativeVector) std::vector&lt; swig::GC_VALUE &gt;;
41760 <BR></DIV>
41761 <BR>
41762 <P>This vector can then contain any Ruby object, making them almost
41763  identical to Ruby's own Array class.</P>
41764 <DIV class="targetlang">
41765 <!--span style=&quot;font-family: monospace;&quot;-->
41766 require 'nativevector'
41767 <BR style="font-family: monospace;">
41768 <!--span style=&quot;font-family: monospace;&quot;-->
41769  include NativeVector
41770 <BR style="font-family: monospace;">
41771 <BR style="font-family: monospace;">
41772 <!--span style=&quot;font-family: monospace;&quot;-->
41773  v = NativeVector.new
41774 <BR style="font-family: monospace;">
41775 <!--span style=&quot;font-family: monospace;&quot;-->
41776  v &lt;&lt; 1
41777 <BR style="font-family: monospace;">
41778 <!--span style=&quot;font-family: monospace;&quot;-->
41779  v &lt;&lt; [1,2]
41780 <BR style="font-family: monospace;">
41781 <!--span style=&quot;font-family: monospace;&quot;-->
41782  v &lt;&lt; 'hello'
41783 <BR style="font-family: monospace;">
41784 <BR style="font-family: monospace;">
41785 <!--span style=&quot;font-family: monospace;&quot;-->
41786  class A; end
41787 <BR style="font-family: monospace;">
41788 <BR style="font-family: monospace;">
41789 <!--span style=&quot;font-family: monospace;&quot;-->
41790  v &lt;&lt; A.new
41791 <BR style="font-family: monospace;">
41792 <BR style="font-family: monospace;">
41793 <!--span style=&quot;font-family: monospace;&quot;-->
41794  puts v
41795 <BR style="font-family: monospace;">
41796 <!--span style=&quot;font-weight: bold; font-family: monospace;&quot;-->
41797  =&gt; [1, [1,2], 'hello',&nbsp;#&lt;A:0x245325&gt;]</DIV>
41798 <BR>
41799 <P>Obviously, there is a lot more to template wrapping than shown in
41800  these examples. More details can be found in the <A href="#SWIGPlus">
41801 SWIG and C++</A> chapter.</P>
41802 <H3><A name="C_STL_Functors"></A>32.3.14 C++ STL Functors</H3>
41803 <P>Some containers in the STL allow you to modify their default behavior
41804  by using so called functors or function objects. &nbsp;Functors are often
41805  just a very simple struct with
41806 <!--span style=&quot;font-family: monospace;&quot;-->
41807  operator() redefined or an actual C/C++ function. &nbsp;This allows you, for
41808  example, to always keep the sort order of a STL container to your
41809  liking.</P>
41810 <P>The Ruby STL mappings allows you to modify those containers that
41811  support functors using Ruby procs or methods, instead. &nbsp;Currently, this
41812  includes
41813 <!--span style=&quot;font-family: monospace;&quot;-->
41814  std::set,
41815 <!--span style=&quot;font-family: monospace;&quot;-->
41816  set::map,
41817 <!--span style=&quot;font-family: monospace;&quot;-->
41818  std::multiset and
41819 <!--span style=&quot;font-family: monospace;&quot;-->
41820  std::multimap.</P>
41821 <P>The functors in swig are called
41822 <!--span style=&quot;font-family: monospace;&quot;-->
41823  swig::UnaryFunction and
41824 <!--span style=&quot;font-family: monospace;&quot;-->
41825  swig::BinaryFunction.
41826 <BR> For C++ predicates (ie. functors that must return bool as a result)
41827 <!--span style=&quot;font-family: monospace;&quot;-->
41828  swig::UnaryPredicate and
41829 <!--span style=&quot;font-family: monospace;&quot;-->
41830  swig::BinaryPredicate are provided.</P>
41831 <P>As an example, if given this swig file:</P>
41832 <DIV class="code" style="font-family: monospace;">%module intset;
41833 <BR>
41834 <BR> %include &lt;std_set.i&gt;
41835 <BR>
41836 <BR> %typemap(IntSet)&nbsp; std::set&lt; int, swig::BinaryPredicate &gt;;</DIV>
41837 <P>You can then use the set from Ruby with or without a proc object as a
41838  predicate:</P>
41839 <DIV class="targetlang" style="font-family: monospace;">require 'intset'
41840 <BR> include Intset
41841 <BR>
41842 <BR> # Default sorting behavior defined in C++
41843 <BR> a = IntSet.new
41844 <BR> a &lt;&lt; 1
41845 <BR> a &lt;&lt; 2
41846 <BR> a &lt;&lt; 3
41847 <BR> a
41848 <BR>
41849 <!--span style=&quot;font-weight: bold;&quot;-->
41850  =&gt; &nbsp;[1,2,3]
41851 <BR>
41852 <BR> # Custom sorting behavior defined by a Ruby proc<DIV>
41853 <!--span class=&quot;targetlang&quot;-->
41854 b = IntSet.new( proc { |a,b| a &gt; b } )
41855 <BR> b&nbsp;&lt;&lt; 1
41856 <BR> b&nbsp;&lt;&lt; 2
41857 <BR> b&nbsp;&lt;&lt; 3
41858 <BR> b
41859 <BR style="font-weight: bold;">
41860 <!--span style=&quot;font-weight: bold;&quot;-->
41861  =&gt; &nbsp;[3,2,1]</DIV></DIV>
41862 <H3><A name="Ruby_C_Iterators"></A>32.3.15 C++ STL Iterators</H3>
41863 <P>The STL is well known for the use of iterators. &nbsp;There are a number
41864  of iterators possible with different properties, but in general there
41865  are two main categories: const iterators and non-const iterators. &nbsp;The
41866  const iterators can access and not modify the values they point at,
41867  while the non-const iterators can both read and modify the values.</P>
41868 <P>The Ruby STL wrappings support both type of iterators by using a
41869  proxy class in-between. &nbsp;This proxy class is
41870 <!--span style=&quot;font-family: monospace;&quot;-->
41871  swig::Iterator or swig::ConstIterator. &nbsp;Derived from them are template
41872  classes that need to be initialized with the actual iterator for the
41873  container you are wrapping and often times with the beginning and
41874  ending points of the iteration range.&nbsp;</P>
41875 <P>The SWIG STL library already provides typemaps to all the standard
41876  containers to do this wrapping automatically for you, but if you have
41877  your own STL-like iterator, you will need to write your own typemap for
41878  them.&nbsp;&nbsp;For out typemaps, the special functions
41879 <!--span style=&quot;font-family: monospace;&quot;-->
41880  make_const_iterator and
41881 <!--span style=&quot;font-family: monospace;&quot;-->
41882  make_nonconst_iterator are provided.</P>
41883 <P>These can be used either like:</P>
41884 <DIV class="code" style="font-family: monospace;">make_const_iterator(
41885  iterator, rubyclass );
41886 <BR> make_const_iterator( iterator, iterator_begin, iterator_end,
41887  rubyclass );</DIV>
41888 <P>The iterators support a
41889 <!--span style=&quot;font-family: monospace;&quot;-->
41890  next() and
41891 <!--span style=&quot;font-family: monospace;&quot;-->
41892  previous()&nbsp;member function to just change the iterator without
41893  returning anything. &nbsp;
41894 <!--span style=&quot;font-family: monospace;&quot;-->
41895 previous() should obviously only be used for bidirectional iterators.
41896  &nbsp;You can also advance the iterator multiple steps by using standard
41897  math operations like
41898 <!--span style=&quot;font-family: monospace;&quot;-->
41899  +=.</P>
41900 <P>The value&nbsp;the iterator points at can be accessed with
41901 <!--span style=&quot;font-family: monospace;&quot;-->
41902  value() -- this is equivalent to dereferencing it with
41903 <!--span style=&quot;font-family: monospace;&quot;-->
41904  *i. &nbsp; For non-const iterators, a
41905 <!--span style=&quot;font-family: monospace;&quot;-->
41906  value=() function is also provided which allows you to change the value
41907  pointed by the iterator. &nbsp;This is equivalent to the C++ construct of
41908  dereferencing and assignment, like
41909 <!--span style=&quot;font-family: monospace;&quot;-->
41910  *i = something.&nbsp;</P>
41911 <P>Thus, given say a vector class of doubles defined as:</P>
41912 <DIV class="code" style="font-family: monospace;">
41913 <!--span class=&quot;code&quot;-->
41914 %module doublevector
41915 <BR class="code">
41916 <!--span class=&quot;code&quot;-->
41917 <BR> %include std_vector.i
41918 <BR class="code">
41919 <!--span class=&quot;code&quot;-->
41920 <BR> %template(DoubleVector) std::vector&lt;double&gt;;</DIV>
41921 <P>Its iterator can then be used from Ruby like:</P>
41922 <DIV class="targetlang" style="font-family: monospace;">require
41923  'doublevector'
41924 <BR> include Doublevector
41925 <BR>
41926 <BR> v = DoubleVector.new
41927 <BR> v &lt;&lt; 1
41928 <BR> v &lt;&lt; 2
41929 <BR> v &lt;&lt; 3
41930 <BR>
41931 <BR> #
41932 <BR> # an elaborate and less efficient way of doing v.map! { |x| x+2 }
41933 <BR> #
41934 <BR> i = v.begin
41935 <BR> e = v.end
41936 <BR> while i != e
41937 <BR> &nbsp; val = i.value
41938 <BR> &nbsp; val += 2
41939 <BR> &nbsp; i.value = val
41940 <BR> &nbsp; i.next
41941 <BR> end
41942 <BR> i
41943 <BR>
41944 <!--span style=&quot;font-weight: bold;&quot;-->
41945  &gt;&gt; [3, 4, 5 ]</DIV>
41946 <BR>
41947 <P>If you'd rather have STL classes without any iterators, you should
41948  define
41949 <!--span style=&quot;font-family: monospace;&quot;-->
41950  -DSWIG_NO_EXPORT_ITERATOR_METHODS when running swig.</P>
41951 <H3><A name="Ruby_nn24"></A>32.3.16 C++ Smart Pointers</H3>
41952 <P> In certain C++ programs, it is common to use classes that have been
41953  wrapped by so-called &quot;smart pointers.&quot; Generally, this involves the use
41954  of a template class that implements <TT>operator-&gt;()</TT> like this:</P>
41955 <DIV class="code">
41956 <PRE>template&lt;class T&gt; class SmartPtr {
41957 <BR> ...
41958 <BR> T *operator-&gt;();
41959 <BR> ...
41960 <BR>}
41961 <BR></PRE>
41962 </DIV>
41963 <P>Then, if you have a class like this,</P>
41964 <DIV class="code">
41965 <PRE>class Foo {
41966 <BR>public:
41967 <BR> int x;
41968 <BR> int bar();
41969 <BR>};
41970 <BR></PRE>
41971 </DIV>
41972 <P>A smart pointer would be used in C++ as follows:</P>
41973 <DIV class="code">
41974 <PRE>SmartPtr&lt;Foo&gt; p = CreateFoo(); // Created somehow (not shown)
41975 <BR>...
41976 <BR>p-&gt;x = 3; // Foo::x
41977 <BR>int y = p-&gt;bar(); // Foo::bar
41978 <BR></PRE>
41979 </DIV>
41980 <P> To wrap this in Ruby, simply tell SWIG about the <TT>SmartPtr</TT>
41981  class and the low-level <TT>Foo</TT> object. Make sure you instantiate <TT>
41982 SmartPtr</TT> using <TT>%template</TT> if necessary. For example:</P>
41983 <DIV class="code">
41984 <PRE>%module example
41985 <BR>...
41986 <BR>%template(SmartPtrFoo) SmartPtr&lt;Foo&gt;;
41987 <BR>...
41988 <BR></PRE>
41989 </DIV>
41990 <P>Now, in Ruby, everything should just &quot;work&quot;:</P>
41991 <DIV class="code targetlang">
41992 <PRE>irb(main):001:0&gt; <B>p = Example::CreateFoo()</B> # Create a smart-pointer somehow
41993 <BR>#&lt;Example::SmartPtrFoo:0x4016f4df&gt;
41994 <BR>irb(main):002:0&gt; <B>p.x = 3</B> # Foo::x
41995 <BR>3
41996 <BR>irb(main):003:0&gt; <B>p.bar()</B> # Foo::bar
41997 <BR></PRE>
41998 </DIV>
41999 <P> If you ever need to access the underlying pointer returned by <TT>
42000 operator-&gt;()</TT> itself, simply use the <TT>__deref__()</TT> method.
42001  For example:</P>
42002 <DIV class="code targetlang">
42003 <PRE>irb(main):004:0&gt; <B>f = p.__deref__()</B> # Returns underlying Foo *
42004 <BR></PRE>
42005 </DIV>
42006 <H3><A name="Ruby_nn25"></A>32.3.17 Cross-Language Polymorphism</H3>
42007 <P> SWIG's Ruby module supports cross-language polymorphism (a.k.a. the
42008  &quot;directors&quot; feature) similar to that for SWIG's Python module. Rather
42009  than duplicate the information presented in the <A href="Ruby">Python</A>
42010  chapter, this section just notes the differences that you need to be
42011  aware of when using this feature with Ruby.</P>
42012 <H4><A name="Ruby_nn26"></A>32.3.17.1 Exception Unrolling</H4>
42013 <P> Whenever a C++ director class routes one of its virtual member
42014  function calls to a Ruby instance method, there's always the
42015  possibility that an exception will be raised in the Ruby code. By
42016  default, those exceptions are ignored, which simply means that the
42017  exception will be exposed to the Ruby interpreter. If you would like to
42018  change this behavior, you can use the <TT>%feature(&quot;director:except&quot;)</TT>
42019  directive to indicate what action should be taken when a Ruby exception
42020  is raised. The following code should suffice in most cases:</P>
42021 <DIV class="code">
42022 <PRE>%feature(&quot;director:except&quot;) {
42023 <BR> throw Swig::DirectorMethodException($error);
42024 <BR>}
42025 <BR></PRE>
42026 </DIV>
42027 <P> When this feature is activated, the call to the Ruby instance method
42028  is &quot;wrapped&quot; using the <TT>rb_rescue2()</TT> function from Ruby's C
42029  API. If any Ruby exception is raised, it will be caught here and a C++
42030  exception is raised in its place.</P>
42031 <H2><A name="Ruby_nn27"></A>32.4 Naming</H2>
42032 <P>Ruby has several common naming conventions. Constants are generally
42033  in upper case, module and class names are in camel case and methods are
42034  in lower case with underscores. For example:</P>
42035 <DIV class="code">
42036 <UL>
42037 <LI><STRONG>MATH::PI</STRONG> is a constant name</LI>
42038 <LI><STRONG>MyClass</STRONG> is a class name</LI>
42039 <LI><STRONG>my_method</STRONG> is a method name</LI>
42040 </UL>
42041 </DIV>
42042 <P>Prior to version 1.3.28, SWIG did not support these Ruby conventions.
42043  The only modifications it made to names was to capitalize the first
42044  letter of constants (which includes module and class names).</P>
42045 <P>SWIG 1.3.28 introduces the new -autorename command line parameter.
42046  When this parameter is specified, SWIG will automatically change
42047  constant, class and method names to conform with the standard Ruby
42048  naming conventions. For example:</P>
42049 <DIV class="code shell">
42050 <PRE>$ <B>swig -ruby -autorename example.i</B>
42051 </PRE>
42052 </DIV>
42053 <P>To disable renaming use the -noautorename command line option.</P>
42054 <P>Since this change significantly changes the wrapper code generated by
42055  SWIG, it is turned off by default in SWIG 1.3.28. However, it is
42056  planned to become the default option in future releases.</P>
42057 <H3><A name="Ruby_nn28"></A>32.4.1 Defining Aliases</H3>
42058 <P> It's a fairly common practice in the Ruby built-ins and standard
42059  library to provide aliases for method names. For example,<EM>
42060  Array#size</EM> is an alias for<EM> Array#length</EM>. If you would
42061  like to provide an alias for one of your class' instance methods, one
42062  approach is to use SWIG's <TT>%extend</TT> directive to add a new
42063  method of the aliased name that calls the original function. For
42064  example:</P>
42065 <DIV class="code">
42066 <PRE>class MyArray {
42067 <BR>public:
42068 <BR> // Construct an empty array
42069 <BR> MyArray();
42070 <BR> 
42071 <BR> // Return the size of this array
42072 <BR> size_t length() const;
42073 <BR>};
42074 <BR>
42075 <BR>%extend MyArray {
42076 <BR> // MyArray#size is an alias for MyArray#length
42077 <BR> size_t size() const {
42078 <BR> return $self-&gt;length();
42079 <BR> }
42080 <BR>}
42081 <BR> </PRE>
42082 </DIV>
42083 <P> A better solution is to use the <TT>%alias</TT> directive (unique to
42084  SWIG's Ruby module). The previous example could then be rewritten as:</P>
42085 <DIV class="code">
42086 <PRE>// MyArray#size is an alias for MyArray#length
42087 <BR>%alias MyArray::length &quot;size&quot;;
42088 <BR>
42089 <BR>class MyArray {
42090 <BR>public:
42091 <BR> // Construct an empty array
42092 <BR> MyArray();
42093 <BR> 
42094 <BR> // Return the size of this array
42095 <BR> size_t length() const;
42096 <BR>};
42097 <BR>
42098 <BR></PRE>
42099 </DIV>
42100 <P> Multiple aliases can be associated with a method by providing a
42101  comma-separated list of aliases to the <TT>%alias</TT> directive, e.g.</P>
42102 <DIV class="code">
42103 <PRE>%alias MyArray::length &quot;amount,quantity,size&quot;;</PRE>
42104 </DIV>
42105 <P> From an end-user's standpoint, there's no functional difference
42106  between these two approaches; i.e. they should get the same result from
42107  calling either<EM> MyArray#size</EM> or<EM> MyArray#length</EM>.
42108  However, when the <TT>%alias</TT> directive is used, SWIG doesn't need
42109  to generate all of the wrapper code that's usually associated with
42110  added methods like our<EM> MyArray::size()</EM> example.</P>
42111 <P>Note that the <TT>%alias</TT> directive is implemented using SWIG's
42112  &quot;features&quot; mechanism and so the same name matching rules used for other
42113  kinds of features apply (see the chapter on <A href="#Customization">
42114 &quot;Customization Features&quot;</A>) for more details).</P>
42115 <H3><A name="Ruby_nn29"></A>32.4.2 Predicate Methods</H3>
42116 <P> Ruby methods that return a boolean value and end in a question mark
42117  are known as predicate methods. Examples of predicate methods in
42118  standard Ruby classes include<EM> Array#empty?</EM> (which returns <TT>
42119 true</TT> for an array containing no elements) and<EM>
42120  Object#instance_of?</EM> (which returns <TT>true</TT> if the object is
42121  an instance of the specified class). For consistency with Ruby
42122  conventions, methods that return boolean values should be marked as
42123  predicate methods.</P>
42124 <P>One cumbersome solution to this problem is to rename the method
42125  (using SWIG's <TT>%rename</TT> directive) and provide a custom typemap
42126  that converts the function's actual return type to Ruby's <TT>true</TT>
42127  or <TT>false</TT>. For example:</P>
42128 <DIV class="code">
42129 <PRE>%rename(&quot;is_it_safe?&quot;) is_it_safe();
42130 <BR>
42131 <BR>%typemap(out) int is_it_safe 
42132 <BR> &quot;$result = ($1 != 0) ? Qtrue : Qfalse;&quot;;
42133 <BR>
42134 <BR>int is_it_safe();
42135 <BR>
42136 <BR></PRE>
42137 </DIV>
42138 <P> A better solution is to use the <TT>%predicate</TT> directive
42139  (unique to SWIG's Ruby module) to designate a method as a predicate
42140  method. For the previous example, this would look like:</P>
42141 <DIV class="code">
42142 <PRE>%predicate is_it_safe();
42143 <BR>
42144 <BR>int is_it_safe();
42145 <BR>
42146 <BR></PRE>
42147 </DIV>
42148 <P>This method would be invoked from Ruby code like this:</P>
42149 <DIV class="code targetlang">
42150 <PRE>irb(main):001:0&gt; <B>Example::is_it_safe?</B>
42151 <BR>true
42152 <BR>
42153 <BR></PRE>
42154 </DIV>
42155 <P> The <TT>%predicate</TT> directive is implemented using SWIG's
42156  &quot;features&quot; mechanism and so the same name matching rules used for other
42157  kinds of features apply (see the chapter on <A href="#Customization">
42158 &quot;Customization Features&quot;</A>) for more details).</P>
42159 <H3><A name="Ruby_nn30"></A>32.4.3 Bang Methods</H3>
42160 <P> Ruby methods that modify an object in-place and end in an
42161  exclamation mark are known as bang methods. An example of a bang method
42162  is<EM> Array#sort!</EM> which changes the ordering of items in an
42163  array. Contrast this with<EM> Array#sort</EM>, which returns a copy of
42164  the array with the items sorted instead of modifying the original
42165  array. For consistency with Ruby conventions, methods that modify
42166  objects in place should be marked as bang methods.</P>
42167 <P>Bang methods can be marked using the <TT>%bang</TT> directive which
42168  is unique to the Ruby module and was introduced in SWIG 1.3.28. For
42169  example:</P>
42170 <DIV class="code">
42171 <PRE>%bang sort!(arr);
42172 <BR>
42173 <BR>int sort(int arr[]); </PRE>
42174 </DIV>
42175 <P>This method would be invoked from Ruby code like this:</P>
42176 <DIV class="code">
42177 <PRE>irb(main):001:0&gt; <B>Example::sort!(arr)</B></PRE>
42178 </DIV>
42179 <P> The <TT>%bang</TT> directive is implemented using SWIG's &quot;features&quot;
42180  mechanism and so the same name matching rules used for other kinds of
42181  features apply (see the chapter on <A href="#Customization">
42182 &quot;Customization Features&quot;</A>) for more details).</P>
42183 <H3><A name="Ruby_nn31"></A>32.4.4 Getters and Setters</H3>
42184 <P> Often times a C++ library will expose properties through getter and
42185  setter methods. For example:</P>
42186 <DIV class="code">
42187 <PRE>class Foo {
42188 <BR>    Foo() {}
42189 <BR>
42190 <BR> int getValue() { return value_; }
42191 <BR>
42192 <BR> void setValue(int value) { value_ = value; }
42193 <BR>
42194 <BR>private:
42195 <BR> int value_;
42196 <BR>};</PRE>
42197 </DIV>
42198 <P>By default, SWIG will expose these methods to Ruby as <TT>get_value</TT>
42199  and <TT>set_value.</TT> However, it more natural for these methods to
42200  be exposed in Ruby as <TT>value</TT> and <TT>value=.</TT> That allows
42201  the methods to be used like this:</P>
42202 <DIV class="code">
42203 <PRE>irb(main):001:0&gt; <B>foo = Foo.new()</B>
42204 <BR>irb(main):002:0&gt; <B>foo.value = 5</B>
42205 <BR>irb(main):003:0&gt; <B>puts foo.value</B></PRE>
42206 </DIV>
42207 <P> This can be done by using the %rename directive:</P>
42208 <DIV class="code">
42209 <PRE>%rename(&quot;value&quot;) Foo::getValue();
42210 <BR>%rename(&quot;value=&quot;) Foo::setValue(int value);
42211 <BR></PRE>
42212 </DIV>
42213 <P>&nbsp;</P>
42214 <H2><A name="Ruby_nn32"></A>32.5 Input and output parameters</H2>
42215 <P> A common problem in some C programs is handling parameters passed as
42216  simple pointers. For example:</P>
42217 <DIV class="code">
42218 <PRE>void add(int x, int y, int *result) {
42219 <BR> *result = x + y;
42220 <BR>}
42221 <BR>or
42222 <BR>int sub(int *x, int *y) {
42223 <BR> return *x-*y;
42224 <BR>}
42225 <BR></PRE>
42226 </DIV>
42227 <P> The easiest way to handle these situations is to use the <TT>
42228 typemaps.i</TT> file. For example:</P>
42229 <DIV class="code">
42230 <PRE>%module Example
42231 <BR>%include &quot;typemaps.i&quot;
42232 <BR>
42233 <BR>void add(int, int, int *OUTPUT);
42234 <BR>int sub(int *INPUT, int *INPUT);
42235 <BR></PRE>
42236 </DIV>
42237 <P>In Ruby, this allows you to pass simple values. For example:</P>
42238 <DIV class="code targetlang">
42239 <PRE>a = Example.add(3,4)
42240 <BR>puts a
42241 <BR>7
42242 <BR>b = Example.sub(7,4)
42243 <BR>puts b
42244 <BR>3
42245 <BR></PRE>
42246 </DIV>
42247 <P> Notice how the <TT>INPUT</TT> parameters allow integer values to be
42248  passed instead of pointers and how the <TT>OUTPUT</TT> parameter
42249  creates a return result.</P>
42250 <P>If you don't want to use the names <TT>INPUT</TT> or <TT>OUTPUT</TT>,
42251  use the <TT>%apply</TT> directive. For example:</P>
42252 <DIV class="code">
42253 <PRE>%module Example
42254 <BR>%include &quot;typemaps.i&quot;
42255 <BR>
42256 <BR>%apply int *OUTPUT { int *result };
42257 <BR>%apply int *INPUT { int *x, int *y};
42258 <BR>
42259 <BR>void add(int x, int y, int *result);
42260 <BR>int sub(int *x, int *y);
42261 <BR></PRE>
42262 </DIV>
42263 <P> If a function mutates one of its parameters like this,</P>
42264 <DIV class="code">
42265 <PRE>void negate(int *x) {
42266 <BR> *x = -(*x);
42267 <BR>}
42268 <BR></PRE>
42269 </DIV>
42270 <P>you can use <TT>INOUT</TT> like this:</P>
42271 <DIV class="code">
42272 <PRE>%include &quot;typemaps.i&quot;
42273 <BR>...
42274 <BR>void negate(int *INOUT);
42275 <BR></PRE>
42276 </DIV>
42277 <P>In Ruby, a mutated parameter shows up as a return value. For example:</P>
42278 <DIV class="code targetlang">
42279 <PRE>a = Example.negate(3)
42280 <BR>print a
42281 <BR>-3
42282 <BR>
42283 <BR></PRE>
42284 </DIV>
42285 <P> The most common use of these special typemap rules is to handle
42286  functions that return more than one value. For example, sometimes a
42287  function returns a result as well as a special error code:</P>
42288 <DIV class="code">
42289 <PRE>/* send message, return number of bytes sent, success code, and error_code */
42290 <BR>int send_message(char *text, int *success, int *error_code);
42291 <BR></PRE>
42292 </DIV>
42293 <P> To wrap such a function, simply use the <TT>OUTPUT</TT> rule above.
42294  For example:</P>
42295 <DIV class="code">
42296 <PRE>%module example
42297 <BR>%include &quot;typemaps.i&quot;
42298 <BR>...
42299 <BR>int send_message(char *, int *OUTPUT, int *OUTPUT);
42300 <BR></PRE>
42301 </DIV>
42302 <P> When used in Ruby, the function will return an array of multiple
42303  values.</P>
42304 <DIV class="code targetlang">
42305 <PRE>bytes, success, error_code = send_message(&quot;Hello World&quot;)
42306 <BR>if not success
42307 <BR> print &quot;error #{error_code} : in send_message&quot;
42308 <BR>else
42309 <BR> print &quot;Sent&quot;, bytes
42310 <BR>end
42311 <BR></PRE>
42312 </DIV>
42313 <P> Another way to access multiple return values is to use the <TT>
42314 %apply</TT> rule. In the following example, the parameters rows and
42315  columns are related to SWIG as <TT>OUTPUT</TT> values through the use
42316  of <TT>%apply</TT></P>
42317 <DIV class="code">
42318 <PRE>%module Example
42319 <BR>%include &quot;typemaps.i&quot;
42320 <BR>%apply int *OUTPUT { int *rows, int *columns };
42321 <BR>...
42322 <BR>void get_dimensions(Matrix *m, int *rows, int*columns);
42323 <BR></PRE>
42324 </DIV>
42325 <P>In Ruby:</P>
42326 <DIV class="code targetlang">
42327 <PRE>r, c = Example.get_dimensions(m)
42328 <BR></PRE>
42329 </DIV>
42330 <H2><A name="Ruby_nn33"></A>32.6 Exception handling</H2>
42331 <H3><A name="Ruby_nn34"></A>32.6.1 Using the %exception directive</H3>
42332 <P>The SWIG <TT>%exception</TT> directive can be used to define a
42333  user-definable exception handler that can convert C/C++ errors into
42334  Ruby exceptions. The chapter on <A href="#Customization">Customization
42335  Features</A> contains more details, but suppose you have a C++ class
42336  like the following :</P>
42337 <DIV class="code">
42338 <PRE>class DoubleArray {
42339 <BR> private:
42340 <BR> int n;
42341 <BR> double *ptr;
42342 <BR> public:
42343 <BR> // Create a new array of fixed size
42344 <BR> DoubleArray(int size) {
42345 <BR> ptr = new double[size];
42346 <BR> n = size;
42347 <BR> }
42348 <BR>
42349 <BR> // Destroy an array
42350 <BR> ~DoubleArray() {
42351 <BR> delete ptr;
42352 <BR> } 
42353 <BR>
42354 <BR> // Return the length of the array
42355 <BR> int length() {
42356 <BR> return n;
42357 <BR> }
42358 <BR>
42359 <BR> // Get an array item and perform bounds checking.
42360 <BR> double getitem(int i) {
42361 <BR> if ((i &gt;= 0) &amp;&amp; (i &lt; n))
42362 <BR> return ptr[i];
42363 <BR> else
42364 <BR> throw RangeError();
42365 <BR> }
42366 <BR>
42367 <BR> // Set an array item and perform bounds checking.
42368 <BR> void setitem(int i, double val) {
42369 <BR> if ((i &gt;= 0) &amp;&amp; (i &lt; n))
42370 <BR> ptr[i] = val;
42371 <BR> else {
42372 <BR> throw RangeError();
42373 <BR> }
42374 <BR> }
42375 <BR> };
42376 <BR></PRE>
42377 </DIV>
42378 <P> Since several methods in this class can throw an exception for an
42379  out-of-bounds access, you might want to catch this in the Ruby
42380  extension by writing the following in an interface file:</P>
42381 <DIV class="code">
42382 <PRE>%exception {
42383 <BR> try {
42384 <BR> $action
42385 <BR> }
42386 <BR> catch (const RangeError&amp;) {
42387 <BR> static VALUE cpperror = rb_define_class(&quot;CPPError&quot;, rb_eStandardError);
42388 <BR> rb_raise(cpperror, &quot;Range error.&quot;);
42389 <BR> }
42390 <BR>}
42391 <BR>
42392 <BR>class DoubleArray {
42393 <BR> ...
42394 <BR>};
42395 <BR></PRE>
42396 </DIV>
42397 <P> The exception handling code is inserted directly into generated
42398  wrapper functions. When an exception handler is defined, errors can be
42399  caught and used to gracefully raise a Ruby exception instead of forcing
42400  the entire program to terminate with an uncaught error.</P>
42401 <P>As shown, the exception handling code will be added to every wrapper
42402  function. Because this is somewhat inefficient, you might consider
42403  refining the exception handler to only apply to specific methods like
42404  this:</P>
42405 <DIV class="code">
42406 <PRE>%exception getitem {
42407 <BR> try {
42408 <BR> $action
42409 <BR> }
42410 <BR> catch (const RangeError&amp;) {
42411 <BR> static VALUE cpperror = rb_define_class(&quot;CPPError&quot;, rb_eStandardError);
42412 <BR> rb_raise(cpperror, &quot;Range error in getitem.&quot;);
42413 <BR> }
42414 <BR>}
42415 <BR>
42416 <BR>%exception setitem {
42417 <BR> try {
42418 <BR> $action
42419 <BR> }
42420 <BR> catch (const RangeError&amp;) {
42421 <BR> static VALUE cpperror = rb_define_class(&quot;CPPError&quot;, rb_eStandardError);
42422 <BR> rb_raise(cpperror, &quot;Range error in setitem.&quot;);
42423 <BR> }
42424 <BR>}
42425 <BR></PRE>
42426 </DIV>
42427 <P> In this case, the exception handler is only attached to methods and
42428  functions named <TT>getitem</TT> and <TT>setitem</TT>.</P>
42429 <P>Since SWIG's exception handling is user-definable, you are not
42430  limited to C++ exception handling. See the chapter on <A href="#Customization">
42431 Customization Features</A> for more examples.</P>
42432 <H3><A name="Ruby_nn34_2"></A>32.6.2 Handling Ruby Blocks</H3>
42433 <P>One of the highlights of Ruby and most of its standard library is the
42434  use of blocks, which allow the easy creation of continuations and other
42435  niceties. &nbsp;Blocks in ruby are also often used to simplify the passing
42436  of many arguments to a class.</P>
42437 <P>In order to make your class constructor support blocks, you can take
42438  advantage of the %exception directive, which will get run after the C++
42439  class' constructor was called.&nbsp;</P>
42440 <P>For example, this yields the class over after its construction:
42441 <BR></P>
42442 <DIV class="code">
42443 <PRE>class Window
42444 <BR>{
42445 <BR>public:
42446 <BR> Window(int x, int y, int w, int h);
42447 <BR>// .... other methods here ....
42448 <BR>};
42449 <BR>
42450 <BR>// Add support for yielding self in the Class' constructor.
42451 <BR>%exception Window::Window {
42452 <BR> $action
42453 <BR> if (rb_block_given_p()) {
42454 <BR> rb_yield(self);
42455 <BR> }
42456 <BR>}</PRE>
42457 </DIV>
42458 <P> Then, in ruby, it can be used like:</P>
42459 <DIV class="targetlang" style="font-family: monospace;">
42460 Window.new(0,0,360,480) { |w|
42461 <BR> &nbsp;&nbsp;&nbsp; w.color = Fltk::RED
42462 <BR> &nbsp;&nbsp;&nbsp; w.border = false
42463 <BR>
42464 <!--span class=&quot;targetlang&quot;-->
42465  }</DIV>
42466 <BR>
42467 <P>For other methods, you can usually use a dummy parameter with a
42468  special in typemap, like:</P>
42469 <DIV class="code" style="font-family: monospace;">//
42470 <BR> // original function was:
42471 <BR> //
42472 <BR> // void func(int x);
42473 <BR>
42474 <BR> %typemap(in,numinputs=0) int RUBY_YIELD_SELF {
42475 <BR> &nbsp; &nbsp; &nbsp;if ( !rb_block_given_p() )
42476 <BR> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; rb_raise(&quot;No block given&quot;);
42477 <BR> &nbsp; &nbsp; &nbsp;return rb_yield(self);
42478 <BR> }
42479 <BR>
42480 <BR> %extend {
42481 <BR> &nbsp; &nbsp; &nbsp; &nbsp; void func(int x, int RUBY_YIELD_SELF );
42482 <BR> }</DIV>
42483 <P>For more information on typemaps, see <A href="#Ruby_nn37">Typemaps</A>
42484 .</P>
42485 <H3><A name="Ruby_nn35"></A>32.6.3 Raising exceptions</H3>
42486 <P>There are three ways to raise exceptions from C++ code to Ruby.</P>
42487 <P>The first way is to use <TT>SWIG_exception(int code, const char *msg)</TT>
42488 . The following table shows the mappings from SWIG error codes to Ruby
42489  exceptions:</P>
42490 <DIV class="diagram">
42491 <TABLE border="1" class="diagram" summary="Mapping between SWIG error codes and Ruby exceptions."
42492 width="80%"><TBODY></TBODY>
42493 <TR><TD class="diagram" style="font-family: monospace;"><DIV>
42494 SWIG_MemoryError</DIV></TD><TD style="font-family: monospace;"><DIV>
42495 rb_eNoMemError</DIV></TD></TR>
42496 <TR><TD class="diagram" style="font-family: monospace;"><DIV>
42497 SWIG_IOError</DIV></TD><TD style="font-family: monospace;"><DIV>
42498 rb_eIOError</DIV></TD></TR>
42499 <TR><TD class="diagram" style="font-family: monospace;"><DIV>
42500 SWIG_RuntimeError</DIV></TD><TD style="font-family: monospace;"><DIV>
42501 rb_eRuntimeError</DIV></TD></TR>
42502 <TR><TD class="diagram" style="font-family: monospace;"><DIV>
42503 SWIG_IndexError</DIV></TD><TD style="font-family: monospace;"><DIV>
42504 rb_eIndexError</DIV></TD></TR>
42505 <TR><TD class="diagram" style="font-family: monospace;"><DIV>
42506 SWIG_TypeError</DIV></TD><TD style="font-family: monospace;"><DIV>
42507 rb_eTypeError</DIV></TD></TR>
42508 <TR><TD class="diagram" style="font-family: monospace;"><DIV>
42509 SWIG_DivisionByZero</DIV></TD><TD style="font-family: monospace;"><DIV>
42510 rb_eZeroDivError</DIV></TD></TR>
42511 <TR><TD class="diagram" style="font-family: monospace;"><DIV>
42512 SWIG_OverflowError</DIV></TD><TD style="font-family: monospace;"><DIV>
42513 rb_eRangeError</DIV></TD></TR>
42514 <TR><TD class="diagram" style="font-family: monospace;"><DIV>
42515 SWIG_SyntaxError</DIV></TD><TD style="font-family: monospace;"><DIV>
42516 rb_eSyntaxError</DIV></TD></TR>
42517 <TR><TD class="diagram" style="font-family: monospace;"><DIV>
42518 SWIG_ValueError</DIV></TD><TD style="font-family: monospace;"><DIV>
42519 rb_eArgError</DIV></TD></TR>
42520 <TR><TD class="diagram" style="font-family: monospace;"><DIV>
42521 SWIG_SystemError</DIV></TD><TD style="font-family: monospace;"><DIV>
42522 rb_eFatal</DIV></TD></TR>
42523 <TR><TD class="diagram" style="font-family: monospace;"><DIV>
42524 SWIG_AttributeError</DIV></TD><TD style="font-family: monospace;"><DIV>
42525 rb_eRuntimeError</DIV></TD></TR>
42526 <TR><TD class="diagram" style="font-family: monospace;"><DIV>
42527 SWIG_NullReferenceError</DIV></TD><TD style="font-family: monospace;"><DIV>
42528 rb_eNullReferenceError*</DIV></TD></TR>
42529 <TR><TD class="diagram" style="font-family: monospace;"><DIV>
42530 SWIG_ObjectPreviouslyDeletedError</DIV></TD><TD style="font-family: monospace;">
42531 <DIV>rb_eObjectPreviouslyDeleted*</DIV></TD></TR>
42532 <TR><TD class="diagram" style="font-family: monospace;"><DIV>
42533 SWIG_UnknownError</DIV></TD><TD style="font-family: monospace;"><DIV>
42534 rb_eRuntimeError</DIV></TD></TR>
42535 <TR class="diagram" style="font-family: monospace;"><TD colspan="2"><DIV>
42536 * These error classes are created by SWIG and are not built-in Ruby
42537  exception classes</DIV></TD></TR>
42538 </TABLE>
42539 </DIV>
42540 <P>The second way to raise errors is to use <TT>SWIG_Raise(obj, type,
42541  desc)</TT>. Obj is a C++ instance of an exception class, type is a
42542  string specifying the type of exception (for example, &quot;MyError&quot;) and
42543  desc is the SWIG description of the exception class. For example:</P>
42544 <DIV class="code" style="font-family: monospace;">
42545  %raise(SWIG_NewPointerObj(e, SWIGTYPE_p_AssertionFailedException, 0),
42546  &quot;:AssertionFailedException&quot;, SWIGTYPE_p_AssertionFailedException);</DIV>
42547 <P>This is useful when you want to pass the current exception object
42548  directly to Ruby, particularly when the object is an instance of class
42549  marked as an <TT>%exceptionclass</TT> (see the next section for more
42550  information).</P>
42551 <P>Last, you can raise an exception by directly calling Ruby's C api.
42552  This is done by invoking the <TT>rb_raise()</TT> function. The first
42553  argument passed to <TT>rb_raise()</TT> is the exception type. You can
42554  raise a custom exception type or one of the built-in Ruby exception
42555  types.</P>
42556 <H3><A name="Ruby_nn36"></A>32.6.4 Exception classes</H3>
42557 <P>Starting with SWIG 1.3.28, the Ruby module supports the <TT>
42558 %exceptionclass</TT> directive, which is used to identify C++ classes
42559  that are used as exceptions. Classes that are marked with the <TT>
42560 %exceptionclass</TT> directive are exposed in Ruby as child classes of <TT>
42561 rb_eRuntimeError</TT>. This allows C++ exceptions to be directly mapped
42562  to Ruby exceptions, providing for a more natural integration between
42563  C++ code and Ruby code.</P>
42564 <DIV class="code">
42565 <PRE>   %exceptionclass CustomError;
42566 <BR>    
42567 <BR>    %inline %{
42568 <BR>    class CustomError { };
42569 <BR>    
42570 <BR>    class Foo { 
42571 <BR>    public:
42572 <BR>    void test() { throw CustomError; }
42573 <BR>    };
42574 <BR>    }
42575 <BR></PRE>
42576 </DIV>
42577 <P>From Ruby you can now call this method like this:</P>
42578 <DIV class="code targetlang">
42579 <PRE>foo = Foo.new
42580 <BR>begin
42581 <BR> foo.test()
42582 <BR>rescue CustomError =&gt; e
42583 <BR> puts &quot;Caught custom error&quot;
42584 <BR>end </PRE>
42585 </DIV>
42586 <P>For another example look at swig/Examples/ruby/exception_class.
42587 <BR></P>
42588 <H2><A name="Ruby_nn37"></A>32.7 Typemaps</H2>
42589 <P> This section describes how you can modify SWIG's default wrapping
42590  behavior for various C/C++ datatypes using the <TT>%typemap</TT>
42591  directive. This is an advanced topic that assumes familiarity with the
42592  Ruby C API as well as the material in the &quot;<A href="#Typemaps">Typemaps</A>
42593 &quot; chapter.&nbsp;</P>
42594 <P>Before proceeding, it should be stressed that typemaps are not a
42595  required part of using SWIG---the default wrapping behavior is enough
42596  in most cases. Typemaps are only used if you want to change some aspect
42597  of the primitive C-Ruby interface.</P>
42598 <H3><A name="Ruby_nn38"></A>32.7.1 What is a typemap?</H3>
42599 <P> A typemap is nothing more than a code generation rule that is
42600  attached to a specific C datatype. The general form of this declaration
42601  is as follows ( parts enclosed in [...] are optional ):&nbsp;&nbsp; &nbsp;</P>
42602 <DIV class="code">
42603 <!--span style=&quot;font-family: monospace;&quot; class=&quot;code&quot;-->
42604 %typemap( method [, modifiers...] ) typelist code;</DIV>
42605 <P><EM> method</EM> is a simply a name that specifies what kind of
42606  typemap is being defined. It is usually a name like <TT>&quot;in&quot;</TT>, <TT>
42607 &quot;out&quot;</TT>, or <TT>&quot;argout&quot;</TT> (or its director variations). The
42608  purpose of these methods is described later.</P>
42609 <P><EM> modifiers</EM> is an optional comma separated list of <TT>
42610 name=&quot;value&quot;</TT> values. These are sometimes to attach extra
42611  information to a typemap and is often target-language dependent.</P>
42612 <P><EM> typelist</EM> is a list of the C++ type patterns that the
42613  typemap will match. The general form of this list is as follows:</P>
42614 <DIV class="diagram">
42615 <PRE>typelist : typepattern [, typepattern, typepattern, ... ] ;
42616 <BR>
42617 <BR>typepattern : type [ (parms) ]
42618 <BR> | type name [ (parms) ]
42619 <BR> | ( typelist ) [ (parms) ]
42620 <BR></PRE>
42621 </DIV>
42622 <P> Each type pattern is either a simple type, a simple type and
42623  argument name, or a list of types in the case of multi-argument
42624  typemaps. In addition, each type pattern can be parameterized with a
42625  list of temporary variables (parms). The purpose of these variables
42626  will be explained shortly.</P>
42627 <P><EM>code</EM> specifies the C code used in the typemap. It can take
42628  any one of the following forms:</P>
42629 <DIV class="diagram">
42630 <PRE>code : { ... }
42631 <BR> | &quot; ... &quot;
42632 <BR> | %{ ... %}
42633 <BR></PRE>
42634 </DIV>
42635 <P>For example, to convert integers from Ruby to C, you might define a
42636  typemap like this:</P>
42637 <DIV class="code">
42638 <PRE>%module example
42639 <BR>
42640 <BR>%typemap(in) int {
42641 <BR> $1 = (int) NUM2INT($input);
42642 <BR> printf(&quot;Received an integer : %d\n&quot;,$1);
42643 <BR>}
42644 <BR>
42645 <BR>%inline %{
42646 <BR>extern int fact(int n);
42647 <BR>%}
42648 <BR></PRE>
42649 </DIV>
42650 <P> Typemaps are always associated with some specific aspect of code
42651  generation. In this case, the &quot;in&quot; method refers to the conversion of
42652  input arguments to C/C++. The datatype <TT>int</TT> is the datatype to
42653  which the typemap will be applied. The supplied C code is used to
42654  convert values. In this code a number of special variables prefaced by
42655  a <TT>$</TT> are used. The <TT>$1</TT> variable is placeholder for a
42656  local variable of type <TT>int</TT>. The <TT>$input</TT> variable is
42657  the input Ruby object.</P>
42658 <P>When this example is compiled into a Ruby module, the following
42659  sample code:</P>
42660 <DIV class="code targetlang">
42661 <PRE>require 'example'
42662 <BR>
42663 <BR>puts Example.fact(6)
42664 <BR></PRE>
42665 </DIV>
42666 <P>prints the result:</P>
42667 <DIV class="code shell">
42668 <PRE>Received an integer : 6
42669 <BR>720
42670 <BR></PRE>
42671 </DIV>
42672 <P> In this example, the typemap is applied to all occurrences of the <TT>
42673 int</TT> datatype. You can refine this by supplying an optional
42674  parameter name. For example:</P>
42675 <DIV class="code">
42676 <PRE>%module example
42677 <BR>
42678 <BR>%typemap(in) int n {
42679 <BR> $1 = (int) NUM2INT($input);
42680 <BR> printf(&quot;n = %d\n&quot;,$1);
42681 <BR>}
42682 <BR>
42683 <BR>%inline %{
42684 <BR>extern int fact(int n);
42685 <BR>%}
42686 <BR></PRE>
42687 </DIV>
42688 <P> In this case, the typemap code is only attached to arguments that
42689  exactly match &quot;<TT>int n</TT>&quot;.</P>
42690 <P>The application of a typemap to specific datatypes and argument names
42691  involves more than simple text-matching--typemaps are fully integrated
42692  into the SWIG type-system. When you define a typemap for <TT>int</TT>,
42693  that typemap applies to <TT>int</TT> and qualified variations such as <TT>
42694 const int</TT>. In addition, the typemap system follows <TT>typedef</TT>
42695  declarations. For example:</P>
42696 <DIV class="code">
42697 <PRE>%typemap(in) int n {
42698 <BR> $1 = (int) NUM2INT($input);
42699 <BR> printf(&quot;n = %d\n&quot;,$1);
42700 <BR>}
42701 <BR>
42702 <BR>typedef int Integer;
42703 <BR>extern int fact(Integer n); // Above typemap is applied
42704 <BR></PRE>
42705 </DIV>
42706 <P> However, the matching of <TT>typedef</TT> only occurs in one
42707  direction. If you defined a typemap for <TT>Integer</TT>, it is not
42708  applied to arguments of type <TT>int</TT>.</P>
42709 <P>Typemaps can also be defined for groups of consecutive arguments. For
42710  example:</P>
42711 <DIV class="code">
42712 <PRE>%typemap(in) (char *str, int len) {
42713 <BR> $1 = STR2CSTR($input);
42714 <BR> $2 = (int) RSTRING($input)-&gt;len;
42715 <BR>};
42716 <BR>
42717 <BR>int count(char c, char *str, int len);
42718 <BR></PRE>
42719 </DIV>
42720 <P> When a multi-argument typemap is defined, the arguments are always
42721  handled as a single Ruby object. This allows the function <TT>count</TT>
42722  to be used as follows (notice how the length parameter is omitted):</P>
42723 <DIV class="code targetlang">
42724 <PRE>puts Example.count('o','Hello World')
42725 <BR>2
42726 <BR></PRE>
42727 </DIV>
42728 <H3><A name="Ruby_Typemap_scope"></A>32.7.2 Typemap scope</H3>
42729 <P> Once defined, a typemap remains in effect for all of the
42730  declarations that follow. A typemap may be redefined for different
42731  sections of an input file. For example:</P>
42732 <DIV class="code">
42733 <PRE>// typemap1
42734 <BR>%typemap(in) int {
42735 <BR>...
42736 <BR>}
42737 <BR>
42738 <BR>int fact(int); // typemap1
42739 <BR>int gcd(int x, int y); // typemap1
42740 <BR>
42741 <BR>// typemap2
42742 <BR>%typemap(in) int {
42743 <BR>...
42744 <BR>}
42745 <BR>
42746 <BR>int isprime(int); // typemap2
42747 <BR></PRE>
42748 </DIV>
42749 <P> One exception to the typemap scoping rules pertains to the <TT>
42750 %extend</TT> declaration. <TT>%extend</TT> is used to attach new
42751  declarations to a class or structure definition. Because of this, all
42752  of the declarations in an <TT>%extend</TT> block are subject to the
42753  typemap rules that are in effect at the point where the class itself is
42754  defined. For example:</P>
42755 <DIV class="code">
42756 <PRE>class Foo {
42757 <BR> ...
42758 <BR>};
42759 <BR>
42760 <BR>%typemap(in) int {
42761 <BR> ...
42762 <BR>}
42763 <BR>
42764 <BR>%extend Foo {
42765 <BR> int blah(int x); // typemap has no effect. Declaration is attached to Foo which 
42766 <BR> // appears before the %typemap declaration.
42767 <BR>};
42768 <BR></PRE>
42769 </DIV>
42770 <H3><A name="Ruby_Copying_a_typemap"></A>32.7.3 Copying a typemap</H3>
42771 <P> A typemap is copied by using assignment. For example:</P>
42772 <DIV class="code">
42773 <PRE>%typemap(in) Integer = int;
42774 <BR></PRE>
42775 </DIV>
42776 <P> or this:</P>
42777 <DIV class="code">
42778 <PRE>%typemap(in) Integer, Number, int32_t = int;
42779 <BR></PRE>
42780 </DIV>
42781 <P> Types are often managed by a collection of different typemaps. For
42782  example:</P>
42783 <DIV class="code">
42784 <PRE>%typemap(in) int { ... }
42785 <BR>%typemap(out) int { ... }
42786 <BR>%typemap(varin) int { ... }
42787 <BR>%typemap(varout) int { ... }
42788 <BR></PRE>
42789 </DIV>
42790 <P> To copy all of these typemaps to a new type, use <TT>%apply</TT>.
42791  For example:</P>
42792 <DIV class="code">
42793 <PRE>%apply int { Integer }; // Copy all int typemaps to Integer
42794 <BR>%apply int { Integer, Number }; // Copy all int typemaps to both Integer and Number
42795 <BR></PRE>
42796 </DIV>
42797 <P> The patterns for <TT>%apply</TT> follow the same rules as for <TT>
42798 %typemap</TT>. For example:</P>
42799 <DIV class="code">
42800 <PRE>%apply int *output { Integer *output }; // Typemap with name
42801 <BR>%apply (char *buf, int len) { (char *buffer, int size) }; // Multiple arguments
42802 <BR></PRE>
42803 </DIV>
42804 <H3><A name="Ruby_Deleting_a_typemap"></A>32.7.4 Deleting a typemap</H3>
42805 <P> A typemap can be deleted by simply defining no code. For example:</P>
42806 <DIV class="code">
42807 <PRE>%typemap(in) int; // Clears typemap for int
42808 <BR>%typemap(in) int, long, short; // Clears typemap for int, long, short
42809 <BR>%typemap(in) int *output; 
42810 <BR></PRE>
42811 </DIV>
42812 <P> The <TT>%clear</TT> directive clears all typemaps for a given type.
42813  For example:</P>
42814 <DIV class="code">
42815 <PRE>%clear int; // Removes all types for int
42816 <BR>%clear int *output, long *output;
42817 <BR></PRE>
42818 </DIV>
42819 <P><B> Note:</B> Since SWIG's default behavior is defined by typemaps,
42820  clearing a fundamental type like <TT>int</TT> will make that type
42821  unusable unless you also define a new set of typemaps immediately after
42822  the clear operation.</P>
42823 <H3><A name="Ruby_Placement_of_typemaps"></A>32.7.5 Placement of
42824  typemaps</H3>
42825 <P> Typemap declarations can be declared in the global scope, within a
42826  C++ namespace, and within a C++ class. For example:</P>
42827 <DIV class="code">
42828 <PRE>%typemap(in) int {
42829 <BR> ...
42830 <BR>}
42831 <BR>
42832 <BR>namespace std {
42833 <BR> class string;
42834 <BR> %typemap(in) string {
42835 <BR> ...
42836 <BR> }
42837 <BR>}
42838 <BR>
42839 <BR>class Bar {
42840 <BR>public:
42841 <BR> typedef const int &amp; const_reference;
42842 <BR> %typemap(out) const_reference {
42843 <BR> ...
42844 <BR> }
42845 <BR>};
42846 <BR></PRE>
42847 </DIV>
42848 <P> When a typemap appears inside a namespace or class, it stays in
42849  effect until the end of the SWIG input (just like before). However, the
42850  typemap takes the local scope into account. Therefore, this code</P>
42851 <DIV class="code">
42852 <PRE>namespace std {
42853 <BR> class string;
42854 <BR> %typemap(in) string {
42855 <BR> ...
42856 <BR> }
42857 <BR>}
42858 <BR></PRE>
42859 </DIV>
42860 <P> is really defining a typemap for the type <TT>std::string</TT>. You
42861  could have code like this:</P>
42862 <DIV class="code">
42863 <PRE>namespace std {
42864 <BR> class string;
42865 <BR> %typemap(in) string { /* std::string */
42866 <BR> ...
42867 <BR> }
42868 <BR>}
42869 <BR>
42870 <BR>namespace Foo {
42871 <BR> class string;
42872 <BR> %typemap(in) string { /* Foo::string */
42873 <BR> ...
42874 <BR> }
42875 <BR>}
42876 <BR></PRE>
42877 </DIV>
42878 <P> In this case, there are two completely distinct typemaps that apply
42879  to two completely different types (<TT>std::string</TT> and <TT>
42880 Foo::string</TT>).</P>
42881 <P> It should be noted that for scoping to work, SWIG has to know that <TT>
42882 string</TT> is a typename defined within a particular namespace. In this
42883  example, this is done using the class declaration <TT>class string</TT>
42884  .</P>
42885 <H3><A name="Ruby_nn39"></A>32.7.6 Ruby typemaps</H3>
42886 <P>The following list details all of the typemap methods that can be
42887  used by the Ruby module:</P>
42888 <H4><A name="Ruby_in_typemap"></A>32.7.6.1 &nbsp;&quot;in&quot; typemap</H4>
42889 <P>Converts Ruby objects to input function arguments. For example:</P>
42890 <DIV class="code">
42891 <PRE>%typemap(in) int {
42892 <BR> $1 = NUM2INT($input);
42893 <BR>}
42894 <BR></PRE>
42895 </DIV>
42896 <P> The following special variables are available:</P>
42897 <DIV class="diagram">
42898 <TABLE border="1" cellpadding="2" cellspacing="2" summary="Special variables - in typemap"
42899 width="100%"><TBODY></TBODY>
42900 <TR><TD style="font-family: monospace;">$input</TD><TD style="font-family: monospace;">
42901  Input object holding value to be converted.</TD></TR>
42902 <TR><TD style="font-family: monospace;">$symname</TD><TD style="font-family: monospace;">
42903  Name of function/method being wrapped</TD></TR>
42904 <TR><TD style="font-family: monospace;">$1...n</TD><TD style="font-family: monospace;">
42905  Argument being sent to the function</TD></TR>
42906 <TR><TD style="font-family: monospace;">$1_name</TD><TD style="font-family: monospace;">
42907  Name of the argument (if provided)</TD></TR>
42908 <TR><TD style="font-family: monospace;">$1_type</TD><TD style="font-family: monospace;">
42909  The actual C datatype matched by the typemap.</TD></TR>
42910 <TR><TD style="font-family: monospace;">$1_ltype</TD><TD style="font-family: monospace;">
42911  The assignable version of the C datatype matched by the typemap.</TD></TR>
42912 </TABLE>
42913 </DIV>
42914 <P> This is probably the most commonly redefined typemap because it can
42915  be used to implement customized conversions.</P>
42916 <P> In addition, the &quot;in&quot; typemap allows the number of converted
42917  arguments to be specified. For example:</P>
42918 <DIV class="code">
42919 <PRE>// Ignored argument.
42920 <BR>%typemap(in, numinputs=0) int *out (int temp) {
42921 <BR> $1 = &amp;temp;
42922 <BR>}
42923 <BR></PRE>
42924 </DIV>
42925 <P> At this time, only zero or one arguments may be converted.</P>
42926 <H4><A name="Ruby_typecheck_typemap"></A>32.7.6.2 &quot;typecheck&quot; typemap</H4>
42927 <P> The &quot;typecheck&quot; typemap is used to support overloaded functions and
42928  methods. It merely checks an argument to see whether or not it matches
42929  a specific type. For example:</P>
42930 <DIV class="code">
42931 <PRE>%typemap(typecheck,precedence=SWIG_TYPECHECK_INTEGER) int {
42932 <BR> $1 = FIXNUM_P($input) ? 1 : 0;
42933 <BR>}
42934 <BR></PRE>
42935 </DIV>
42936 <P> For typechecking, the $1 variable is always a simple integer that is
42937  set to 1 or 0 depending on whether or not the input argument is the
42938  correct type.</P>
42939 <P> If you define new &quot;in&quot; typemaps<EM> and</EM> your program uses
42940  overloaded methods, you should also define a collection of &quot;typecheck&quot;
42941  typemaps. More details about this follow in a later section on
42942  &quot;Typemaps and Overloading.&quot;</P>
42943 <H4><A name="Ruby_out_typemap"></A>32.7.6.3 &nbsp;&quot;out&quot; typemap</H4>
42944 <P>Converts return value of a C function to a Ruby object.</P>
42945 <DIV class="code"><TT>
42946 <BR> %typemap(out) int {
42947 <BR> &nbsp; &nbsp;$result = INT2NUM( $1 );
42948 <BR> }
42949 <BR></TT></DIV>
42950 <P> The following special variables are available.</P>
42951 <DIV class="diagram">
42952 <TABLE border="1" cellpadding="2" cellspacing="2" summary="Special variables - out typemap"
42953 width="100%"><TBODY></TBODY>
42954 <TR><TD style="font-family: monospace;">$result</TD><TD style="font-family: monospace;">
42955  Result object returned to target language.</TD></TR>
42956 <TR><TD style="font-family: monospace;">$symname</TD><TD style="font-family: monospace;">
42957  Name of function/method being wrapped</TD></TR>
42958 <TR><TD style="font-family: monospace;">$1...n</TD><TD style="font-family: monospace;">
42959  Argument being wrapped</TD></TR>
42960 <TR><TD style="font-family: monospace;">$1_name</TD><TD style="font-family: monospace;">
42961  Name of the argument (if provided)</TD></TR>
42962 <TR><TD style="font-family: monospace;">$1_type</TD><TD style="font-family: monospace;">
42963  The actual C datatype matched by the typemap.</TD></TR>
42964 <TR><TD style="font-family: monospace;">$1_ltype</TD><TD style="font-family: monospace;">
42965  The assignable version of the C datatype matched by the typemap.</TD></TR>
42966 </TABLE>
42967 </DIV>
42968 <BR>
42969 <H4><A name="Ruby_arginit_typemap"></A>32.7.6.4 &quot;arginit&quot; typemap</H4>
42970 <P> The &quot;arginit&quot; typemap is used to set the initial value of a function
42971  argument--before any conversion has occurred. This is not normally
42972  necessary, but might be useful in highly specialized applications. For
42973  example:</P>
42974 <DIV class="code">
42975 <PRE>// Set argument to NULL before any conversion occurs
42976 <BR>%typemap(arginit) int *data {
42977 <BR> $1 = NULL;
42978 <BR>}
42979 <BR></PRE>
42980 </DIV>
42981 <H4><A name="Ruby_default_typemap"></A>32.7.6.5 &quot;default&quot; typemap</H4>
42982 <P> The &quot;default&quot; typemap is used to turn an argument into a default
42983  argument. For example:</P>
42984 <DIV class="code">
42985 <PRE>%typemap(default) int flags {
42986 <BR> $1 = DEFAULT_FLAGS;
42987 <BR>}
42988 <BR>...
42989 <BR>int foo(int x, int y, int flags);
42990 <BR></PRE>
42991 </DIV>
42992 <P> The primary use of this typemap is to either change the wrapping of
42993  default arguments or specify a default argument in a language where
42994  they aren't supported (like C). Target languages that do not support
42995  optional arguments, such as Java and C#, effectively ignore the value
42996  specified by this typemap as all arguments must be given.</P>
42997 <P> Once a default typemap has been applied to an argument, all
42998  arguments that follow must have default values. See the <A href="http://www.swig.org/Doc1.3/SWIGDocumentation.html#SWIG_default_args">
42999  Default/optional arguments</A> section for further information on
43000  default argument wrapping.</P>
43001 <H4><A name="Ruby_check_typemap"></A>32.7.6.6 &quot;check&quot; typemap</H4>
43002 <P> The &quot;check&quot; typemap is used to supply value checking code during
43003  argument conversion. The typemap is applied<EM> after</EM> arguments
43004  have been converted. For example:</P>
43005 <DIV class="code">
43006 <PRE>%typemap(check) int positive {
43007 <BR> if ($1 &lt;= 0) {
43008 <BR> SWIG_exception(SWIG_ValueError,&quot;Expected positive value.&quot;);
43009 <BR> }
43010 <BR>}
43011 <BR></PRE>
43012 </DIV>
43013 <H4><A name="Ruby_argout_typemap_"></A>32.7.6.7 &quot;argout&quot; typemap</H4>
43014 <P> The &quot;argout&quot; typemap is used to return values from arguments. This
43015  is most commonly used to write wrappers for C/C++ functions that need
43016  to return multiple values. The &quot;argout&quot; typemap is almost always
43017  combined with an &quot;in&quot; typemap---possibly to ignore the input value. For
43018  example:</P>
43019 <DIV class="code">
43020 <PRE>/* Set the input argument to point to a temporary variable */
43021 <BR>%typemap(in, numinputs=0) int *out (int temp) {
43022 <BR> $1 = &amp;temp;
43023 <BR>}
43024 <BR>
43025 <BR>%typemap(argout, fragment=&quot;output_helper&quot;) int *out {
43026 <BR> // Append output value $1 to $result (assuming a single integer in this case)
43027 <BR> $result = output_helper( $result, INT2NUM(*$1) );
43028 <BR>}
43029 <BR></PRE>
43030 </DIV>
43031 <P> The following special variables are available.</P>
43032 <DIV class="diagram">
43033 <TABLE border="1" cellpadding="2" cellspacing="2" summary="Special variables - argout typemap"
43034 width="100%"><TBODY></TBODY>
43035 <TR><TD style="font-family: monospace;">$result</TD><TD style="font-family: monospace;">
43036  Result object returned to target language.</TD></TR>
43037 <TR><TD style="font-family: monospace;">$input</TD><TD style="font-family: monospace;">
43038  The original input object passed.</TD></TR>
43039 <TR><TD style="font-family: monospace;">$symname</TD><TD style="font-family: monospace;">
43040  Name of function/method being wrapped.</TD></TR>
43041 </TABLE>
43042 </DIV>
43043 <P> The code supplied to the &quot;argout&quot; typemap is always placed after the
43044  &quot;out&quot; typemap. If multiple return values are used, the extra return
43045  values are often appended to return value of the function.</P>
43046 <P>Output helper is a fragment that usually defines a macro to some
43047  function like SWIG_Ruby_AppendOutput.</P>
43048 <P> See the <TT>typemaps.i</TT> library for examples.</P>
43049 <H4><A name="Ruby_freearg_typemap_"></A>32.7.6.8 &quot;freearg&quot; typemap</H4>
43050 <P> The &quot;freearg&quot; typemap is used to cleanup argument data. It is only
43051  used when an argument might have allocated resources that need to be
43052  cleaned up when the wrapper function exits. The &quot;freearg&quot; typemap
43053  usually cleans up argument resources allocated by the &quot;in&quot; typemap. For
43054  example:</P>
43055 <DIV class="code">
43056 <PRE>// Get a list of integers
43057 <BR>%typemap(in) int *items {
43058 <BR> int nitems = Length($input); 
43059 <BR> $1 = (int *) malloc(sizeof(int)*nitems);
43060 <BR>}
43061 <BR>// Free the list 
43062 <BR>%typemap(freearg) int *items {
43063 <BR> free($1);
43064 <BR>}
43065 <BR></PRE>
43066 </DIV>
43067 <P> The &quot;freearg&quot; typemap inserted at the end of the wrapper function,
43068  just before control is returned back to the target language. This code
43069  is also placed into a special variable <TT>$cleanup</TT> that may be
43070  used in other typemaps whenever a wrapper function needs to abort
43071  prematurely.</P>
43072 <H4><A name="Ruby_newfree_typemap"></A>32.7.6.9 &quot;newfree&quot; typemap</H4>
43073 <P> The &quot;newfree&quot; typemap is used in conjunction with the <TT>%newobject</TT>
43074  directive and is used to deallocate memory used by the return result of
43075  a function. For example:</P>
43076 <DIV class="code">
43077 <PRE>%typemap(newfree) string * {
43078 <BR> delete $1;
43079 <BR>}
43080 <BR>%typemap(out) string * {
43081 <BR> $result = PyString_FromString($1-&gt;c_str());
43082 <BR>}
43083 <BR>...
43084 <BR>
43085 <BR>%newobject foo;
43086 <BR>...
43087 <BR>string *foo();
43088 <BR></PRE>
43089 </DIV>
43090 <P> See <A href="http://www.swig.org/Doc1.3/SWIGDocumentation.html#ownership">
43091 Object ownership and %newobject</A> for further details.</P>
43092 <H4><A name="Ruby_memberin_typemap"></A>32.7.6.10 &quot;memberin&quot; typemap</H4>
43093 <P> The &quot;memberin&quot; typemap is used to copy data from<EM> an already
43094  converted input value</EM> into a structure member. It is typically
43095  used to handle array members and other special cases. For example:</P>
43096 <DIV class="code">
43097 <PRE>%typemap(memberin) int [4] {
43098 <BR> memmove($1, $input, 4*sizeof(int));
43099 <BR>}
43100 <BR></PRE>
43101 </DIV>
43102 <P> It is rarely necessary to write &quot;memberin&quot; typemaps---SWIG already
43103  provides a default implementation for arrays, strings, and other
43104  objects.</P>
43105 <H4><A name="Ruby_varin_typemap"></A>32.7.6.11 &quot;varin&quot; typemap</H4>
43106 <P> The &quot;varin&quot; typemap is used to convert objects in the target
43107  language to C for the purposes of assigning to a C/C++ global variable.
43108  This is implementation specific.</P>
43109 <H4><A name="Ruby_varout_typemap_"></A>32.7.6.12 &quot;varout&quot; typemap</H4>
43110 <P> The &quot;varout&quot; typemap is used to convert a C/C++ object to an object
43111  in the target language when reading a C/C++ global variable. This is
43112  implementation specific.</P>
43113 <H4><A name="Ruby_throws_typemap"></A>32.7.6.13 &quot;throws&quot; typemap</H4>
43114 <P> The &quot;throws&quot; typemap is only used when SWIG parses a C++ method with
43115  an exception specification or has the <TT>%catches</TT> feature
43116  attached to the method. It provides a default mechanism for handling
43117  C++ methods that have declared the exceptions they will throw. The
43118  purpose of this typemap is to convert a C++ exception into an error or
43119  exception in the target language. It is slightly different to the other
43120  typemaps as it is based around the exception type rather than the type
43121  of a parameter or variable. For example:</P>
43122 <DIV class="code">
43123 <PRE>%typemap(throws) const char * %{
43124 <BR> rb_raise(rb_eRuntimeError, $1);
43125 <BR> SWIG_fail;
43126 <BR>%}
43127 <BR>void bar() throw (const char *);
43128 <BR></PRE>
43129 </DIV>
43130 <P> As can be seen from the generated code below, SWIG generates an
43131  exception handler with the catch block comprising the &quot;throws&quot; typemap
43132  content.</P>
43133 <DIV class="code">
43134 <PRE>...
43135 <BR>try {
43136 <BR> bar();
43137 <BR>}
43138 <BR>catch(char const *_e) {
43139 <BR> rb_raise(rb_eRuntimeError, _e);
43140 <BR> SWIG_fail;
43141 <BR>}
43142 <BR>...
43143 <BR></PRE>
43144 </DIV>
43145 <P> Note that if your methods do not have an exception specification yet
43146  they do throw exceptions, SWIG cannot know how to deal with them. For a
43147  neat way to handle these, see the <A href="http://www.swig.org/Doc1.3/SWIGDocumentation.html#exception">
43148 Exception handling with %exception</A> section.</P>
43149 <H4><A name="Ruby_directorin_typemap"></A>32.7.6.14 directorin typemap</H4>
43150 <P>Converts C++ objects in director member functions to ruby objects.&nbsp;It
43151  is roughly the opposite of the &quot;in&quot; typemap, making its typemap rule
43152  often similar to the &quot;out&quot; typemap.</P>
43153 <DIV class="code"><TT>
43154 <BR> %typemap(directorin) int {
43155 <BR> &nbsp; &nbsp; &nbsp;$result = INT2NUM($1);
43156 <BR> }
43157 <BR></TT></DIV>
43158 <P> The following special variables are available.</P>
43159 <DIV class="diagram">
43160 <TABLE border="1" cellpadding="2" cellspacing="2" summary="Special variables - directorin typemap"
43161 width="100%"><TBODY></TBODY>
43162 <TR><TD style="font-family: monospace;">$result</TD><TD style="font-family: monospace;">
43163  Result object returned to target language.</TD></TR>
43164 <TR><TD style="font-family: monospace;">$symname</TD><TD style="font-family: monospace;">
43165  Name of function/method being wrapped</TD></TR>
43166 <TR><TD style="font-family: monospace;">$1...n</TD><TD style="font-family: monospace;">
43167  Argument being wrapped</TD></TR>
43168 <TR><TD style="font-family: monospace;">$1_name</TD><TD style="font-family: monospace;">
43169  Name of the argument (if provided)</TD></TR>
43170 <TR><TD style="font-family: monospace;">$1_type</TD><TD style="font-family: monospace;">
43171  The actual C datatype matched by the typemap.</TD></TR>
43172 <TR><TD style="font-family: monospace;">$1_ltype</TD><TD style="font-family: monospace;">
43173  The assignable version of the C datatype matched by the typemap.</TD></TR>
43174 <TR><TD style="font-family: monospace;">this</TD><TD style="font-family: monospace;">
43175  C++ this, referring to the class itself.</TD></TR>
43176 </TABLE>
43177 </DIV>
43178 <H4><A name="Ruby_directorout_typemap"></A>32.7.6.15 directorout typemap</H4>
43179 <P>Converts Ruby objects in director member functions to C++ objects.
43180  &nbsp;It is roughly the opposite of the &quot;out&quot; typemap, making its rule often
43181  similar to the &quot;in&quot; typemap.</P>
43182 <DIV class="code"><TT style="font-family: monospace;">
43183 <BR> %typemap(directorout) int {</TT><TT>
43184 <BR> &nbsp; &nbsp;$result =&nbsp;NUM2INT($1);</TT>
43185 <BR> <TT style="font-family: monospace;">}
43186 <BR></TT></DIV>
43187 <P> The following special variables are available:</P>
43188 <DIV class="diagram">
43189 <TABLE border="1" cellpadding="2" cellspacing="2" summary="Special variables - directorout typemap"
43190 width="100%"><TBODY></TBODY>
43191 <TR><TD style="font-family: monospace;">$symname</TD><TD style="font-family: monospace;">
43192  Name of function/method being wrapped</TD></TR>
43193 <TR><TD style="font-family: monospace;">$1...n</TD><TD style="font-family: monospace;">
43194  Argument being sent to the function</TD></TR>
43195 <TR><TD style="font-family: monospace;">$1_name</TD><TD style="font-family: monospace;">
43196  Name of the argument (if provided)</TD></TR>
43197 <TR><TD style="font-family: monospace;">$1_type</TD><TD style="font-family: monospace;">
43198  The actual C datatype matched by the typemap.</TD></TR>
43199 <TR><TD style="font-family: monospace;">$1_ltype</TD><TD style="font-family: monospace;">
43200  The assignable version of the C datatype matched by the typemap.</TD></TR>
43201 <TR><TD style="font-family: monospace;">this</TD><TD style="font-family: monospace;">
43202  C++ this, referring to the class itself.</TD></TR>
43203 </TABLE>
43204 </DIV>
43205 <P>Currently, the directorout nor the out typemap support the option&nbsp;
43206 <!--span style=&quot;font-family: monospace;&quot;-->
43207 numoutputs, but the Ruby module provides that functionality through a
43208  %feature directive. &nbsp;Thus, a function can be made to return &quot;nothing&quot;
43209  if you do:</P>
43210 <DIV class="code" style="font-family: monospace;">
43211 %feature(&quot;numoutputs&quot;,&quot;0&quot;) MyClass::function;</DIV>
43212 <P>This feature can be useful if a function returns a status code, which
43213  you want to discard but still use the typemap to raise an exception.
43214 <BR></P>
43215 <H4><A name="Ruby_directorargout_typemap"></A>32.7.6.16 directorargout
43216  typemap</H4>
43217 <P>Output argument processing in director member functions.</P>
43218 <DIV class="code"><TT style="font-family: monospace;">
43219 %typemap(directorargout, fragment=&quot;output_helper&quot;) int {</TT><TT>
43220 <BR> $result = output_helper( $result, NUM2INT($1) );</TT>
43221 <BR> <TT style="font-family: monospace;">}</TT></DIV>
43222 <P> The following special variables are available:</P>
43223 <DIV class="diagram">
43224 <TABLE border="1" cellpadding="2" cellspacing="2" style="text-align: left; width: 100%;"
43225 summary="Special variables - directorargout typemap"><TBODY></TBODY>
43226 <TR><TD style="font-family: monospace;">$result</TD><TD style="font-family: monospace;">
43227 Result that the director function returns</TD></TR>
43228 <TR><TD style="font-family: monospace;">$symname</TD><TD style="font-family: monospace;">
43229 name of the function/method being wrapped</TD></TR>
43230 <TR><TD style="font-family: monospace;">$1...n</TD><TD style="font-family: monospace;">
43231 Argument being sent to the function</TD></TR>
43232 <TR><TD style="font-family: monospace;">$1_name</TD><TD style="font-family: monospace;">
43233 Name of the argument (if provided)</TD></TR>
43234 <TR><TD style="font-family: monospace;">$1_type</TD><TD style="font-family: monospace;">
43235 The actual C datatype matched by the typemap</TD></TR>
43236 <TR><TD style="font-family: monospace;">$1_ltype</TD><TD style="font-family: monospace;">
43237 The assignable version of the C datatype matched by the typemap</TD></TR>
43238 <TR><TD style="font-family: monospace;">this</TD><TD style="font-family: monospace;">
43239 C++ this, referring to the instance of the class itself</TD></TR>
43240 </TABLE>
43241 </DIV>
43242 <H4><A name="Ruby_ret_typemap"></A>32.7.6.17 ret typemap</H4>
43243 <P>Cleanup of function return values</P>
43244 <H4><A name="Ruby_globalin_typemap"></A>32.7.6.18 globalin typemap</H4>
43245 <P>Setting of C global variables</P>
43246 <H3><A name="Ruby_nn40"></A>32.7.7 Typemap variables</H3>
43247 <P> Within a typemap, a number of special variables prefaced with a <TT>
43248 $</TT> may appear. A full list of variables can be found in the &quot;<A href="#Typemaps">
43249 Typemaps</A>&quot; chapter. This is a list of the most common variables:</P>
43250 <P><TT>$1</TT></P>
43251 <DIV class="indent">A C local variable corresponding to the actual type
43252  specified in the <TT>%typemap</TT> directive. For input values, this is
43253  a C local variable that is supposed to hold an argument value. For
43254  output values, this is the raw result that is supposed to be returned
43255  to Ruby.</DIV>
43256 <P><TT>$input</TT></P>
43257 <DIV class="indent">A <TT>VALUE</TT> holding a raw Ruby object with an
43258  argument or variable value.</DIV>
43259 <P><TT>$result</TT></P>
43260 <DIV class="indent">A <TT>VALUE</TT> that holds the result to be
43261  returned to Ruby.</DIV>
43262 <P><TT>$1_name</TT></P>
43263 <DIV class="indent">The parameter name that was matched.</DIV>
43264 <P><TT>$1_type</TT></P>
43265 <DIV class="indent">The actual C datatype matched by the typemap.</DIV>
43266 <P><TT>$1_ltype</TT></P>
43267 <DIV class="indent">An assignable version of the datatype matched by the
43268  typemap (a type that can appear on the left-hand-side of a C assignment
43269  operation). This type is stripped of qualifiers and may be an altered
43270  version of <TT>$1_type</TT>. All arguments and local variables in
43271  wrapper functions are declared using this type so that their values can
43272  be properly assigned.</DIV>
43273 <P><TT>$symname</TT></P>
43274 <DIV class="indent">The Ruby name of the wrapper function being created.</DIV>
43275 <H3><A name="Ruby_nn41"></A>32.7.8 Useful Functions</H3>
43276 <P> When you write a typemap, you usually have to work directly with
43277  Ruby objects. The following functions may prove to be useful. (These
43278  functions plus many more can be found in <A href="http://www.rubycentral.com/book">
43279 <EM>Programming Ruby</EM></A>, by David Thomas and Andrew Hunt.)&nbsp;</P>
43280 <P>In addition, we list equivalent functions that Swig defines, which
43281  provide a language neutral conversion (these functions are defined for
43282  each swig language supported). &nbsp;If you are trying to create a swig file
43283  that will work under multiple languages, it is recommended you stick to
43284  the swig functions instead of the native Ruby functions. &nbsp;That should
43285  help you avoid having to rewrite a lot of typemaps across multiple
43286  languages.</P>
43287 <H4><A name="Ruby_nn42"></A>32.7.8.1 C Datatypes to Ruby Objects</H4>
43288 <DIV class="diagram">
43289 <TABLE border="1" cellpadding="2" cellspacing="2" style="width: 100%;" summary="Datatypes">
43290 <TBODY></TBODY>
43291 <TR><TH style="font-weight: bold;">RUBY</TH><TH style="font-weight: bold;">
43292 Swig</TH><TD></TD></TR>
43293 <TR><TD style="font-family: monospace;">INT2NUM(long or int)</TD><TD style="font-family: monospace;">
43294 SWIG_From_int(int x)</TD><TD> int to Fixnum or Bignum</TD></TR>
43295 <TR><TD style="font-family: monospace;">INT2FIX(long or int)</TD><TD style="font-family: monospace;">
43296 </TD><TD> int to Fixnum (faster than INT2NUM)</TD></TR>
43297 <TR><TD style="font-family: monospace;">CHR2FIX(char)</TD><TD style="font-family: monospace;">
43298 SWIG_From_char(char x)</TD><TD> char to Fixnum</TD></TR>
43299 <TR><TD style="font-family: monospace;">rb_str_new2(char*)</TD><TD style="font-family: monospace;">
43300 SWIG_FromCharPtrAndSize(char*, size_t)</TD><TD> char* to String</TD></TR>
43301 <TR><TD style="font-family: monospace;">rb_float_new(double)</TD><TD style="font-family: monospace;">
43302 SWIG_From_double(double),
43303 <BR> SWIG_From_float(float)</TD><TD>float/double to Float</TD></TR>
43304 </TABLE>
43305 </DIV>
43306 <H4><A name="Ruby_nn43"></A>32.7.8.2 Ruby Objects to C Datatypes</H4>
43307 <P>Here, while the Ruby versions return the value directly, the SWIG
43308  versions do not, but return a status value to indicate success (
43309 <!--span style=&quot;font-family: monospace;&quot;-->
43310 SWIG_OK). While more akward to use, this allows you to write typemaps
43311  that report more helpful error messages, like:</P>
43312 <DIV class="code" style="font-family: monospace;">
43313 <BR> %typemap(in) size_t (int ok)
43314 <BR> &nbsp;
43315 <BR> &nbsp; ok = SWIG_AsVal_size_t($input, &amp;$1);
43316 <BR> &nbsp; if (!SWIG_IsOK(ok)) {
43317 <BR> &nbsp;&nbsp;&nbsp; SWIG_exception_fail(SWIG_ArgError(ok), Ruby_Format_TypeError(
43318  &quot;$1_name&quot;, &quot;$1_type&quot;,&quot;$symname&quot;, $argnum, $input ));
43319 <BR> &nbsp; &nbsp;}
43320 <BR>
43321 <BR> }</DIV><DIV style="font-family: monospace;">&nbsp;&nbsp;</DIV><DIV class="diagram">
43322 <TABLE border="1" cellpadding="2" cellspacing="2" summary="Ruby objects" width="100%">
43323 <TBODY></TBODY>
43324 <TR><TD style="font-family: monospace;">int NUM2INT(Numeric)</TD><TD style="font-family: monospace;">
43325 SWIG_AsVal_int(VALUE, int*)</TD></TR>
43326 <TR><TD style="font-family: monospace;">int FIX2INT(Numeric)</TD><TD style="font-family: monospace;">
43327 SWIG_AsVal_int(VALUE, int*)</TD></TR>
43328 <TR><TD style="font-family: monospace;">unsigned int NUM2UINT(Numeric)</TD><TD
43329 style="font-family: monospace;">SWIG_AsVal_unsigned_SS_int(VALUE, int*)</TD>
43330 </TR>
43331 <TR><TD style="font-family: monospace;">unsigned int FIX2UINT(Numeric)</TD><TD
43332 style="font-family: monospace;">SWIG_AsVal_unsigned_SS_int(VALUE, int*)</TD>
43333 </TR>
43334 <TR><TD style="font-family: monospace;">long NUM2LONG(Numeric)</TD><TD style="font-family: monospace;">
43335 SWIG_AsVal_long(VALUE, long*)</TD></TR>
43336 <TR><TD style="font-family: monospace;">long FIX2LONG(Numeric)</TD><TD style="font-family: monospace;">
43337 SWIG_AsVal_long(VALUE, long*)</TD></TR>
43338 <TR><TD style="font-family: monospace;">unsigned long FIX2ULONG(Numeric)</TD><TD
43339 style="font-family: monospace;">SWIG_AsVal_unsigned_SS_long(VALUE,
43340  unsigned long*)</TD></TR>
43341 <TR><TD style="font-family: monospace;">char NUM2CHR(Numeric or String)</TD><TD
43342 style="font-family: monospace;">SWIG_AsVal_char(VALUE, int*)</TD></TR>
43343 <TR><TD style="font-family: monospace;">char * STR2CSTR(String)</TD><TD style="font-family: monospace;">
43344 SWIG_AsCharPtrAndSize(VALUE, char*, size_t, int* alloc)</TD></TR>
43345 <TR><TD style="font-family: monospace;">char * rb_str2cstr(String,
43346  int*length)</TD><TD style="font-family: monospace;"></TD></TR>
43347 <TR><TD style="font-family: monospace;">double NUM2DBL(Numeric)</TD><TD style="font-family: monospace;">
43348 (double) SWIG_AsVal_int(VALUE) or similar</TD></TR>
43349 </TABLE>
43350 </DIV>
43351 <H4><A name="Ruby_nn44"></A>32.7.8.3 Macros for VALUE</H4>
43352 <P> <TT>RSTRING_LEN(str)</TT></P>
43353 <DIV class="indent">length of the Ruby string</DIV>
43354 <P><TT>RSTRING_PTR(str)</TT></P>
43355 <DIV class="indent">pointer to string storage</DIV>
43356 <P><TT>RARRAY_LEN(arr)</TT></P>
43357 <DIV class="indent">length of the Ruby array</DIV>
43358 <P><TT>RARRAY(arr)-&gt;capa</TT></P>
43359 <DIV class="indent">capacity of the Ruby array</DIV>
43360 <P><TT>RARRAY_PTR(arr)</TT></P>
43361 <DIV class="indent">pointer to array storage</DIV>
43362 <H4><A name="Ruby_nn45"></A>32.7.8.4 Exceptions</H4>
43363 <P> <TT>void rb_raise(VALUE exception, const char *fmt, ...)</TT></P>
43364 <DIV class="indent"> Raises an exception. The given format string<I> fmt</I>
43365  and remaining arguments are interpreted as with <TT>printf()</TT>.</DIV>
43366 <P><TT>void rb_fatal(const char *fmt, ...)</TT></P>
43367 <DIV class="indent"> Raises a fatal exception, terminating the process.
43368  No rescue blocks are called, but ensure blocks will be called. The
43369  given format string<I> fmt</I> and remaining arguments are interpreted
43370  as with <TT>printf()</TT>.</DIV>
43371 <P><TT>void rb_bug(const char *fmt, ...)</TT></P>
43372 <DIV class="indent"> Terminates the process immediately -- no handlers
43373  of any sort will be called. The given format string<I> fmt</I> and
43374  remaining arguments are interpreted as with <TT>printf()</TT>. You
43375  should call this function only if a fatal bug has been exposed.</DIV>
43376 <P><TT>void rb_sys_fail(const char *msg)</TT></P>
43377 <DIV class="indent"> Raises a platform-specific exception corresponding
43378  to the last known system error, with the given string<I> msg</I>.</DIV>
43379 <P><TT>VALUE rb_rescue(VALUE (*body)(VALUE), VALUE args,
43380  VALUE(*rescue)(VALUE, VALUE), VALUE rargs)</TT></P>
43381 <DIV class="indent"> Executes<I> body</I> with the given<I> args</I>. If
43382  a <TT>StandardError</TT> exception is raised, then execute<I> rescue</I>
43383  with the given<I> rargs</I>.</DIV>
43384 <P><TT>VALUE rb_ensure(VALUE(*body)(VALUE), VALUE args,
43385  VALUE(*ensure)(VALUE), VALUE eargs)</TT></P>
43386 <DIV class="indent"> Executes<I> body</I> with the given<I> args</I>.
43387  Whether or not an exception is raised, execute<I> ensure</I> with the
43388  given<I> rargs</I> after<I> body</I> has completed.</DIV>
43389 <P><TT>VALUE rb_protect(VALUE (*body)(VALUE), VALUE args, int *result)</TT>
43390 </P>
43391 <DIV class="indent"> Executes<I> body</I> with the given<I> args</I> and
43392  returns nonzero in result if any exception was raised.</DIV>
43393 <P><TT>void rb_notimplement()</TT></P>
43394 <DIV class="indent"> Raises a <TT>NotImpError</TT> exception to indicate
43395  that the enclosed function is not implemented yet, or not available on
43396  this platform.</DIV>
43397 <P><TT>void rb_exit(int status)</TT></P>
43398 <DIV class="indent"> Exits Ruby with the given<I> status</I>. Raises a <TT>
43399 SystemExit</TT> exception and calls registered exit functions and
43400  finalizers.</DIV>
43401 <P><TT>void rb_warn(const char *fmt, ...)</TT></P>
43402 <DIV class="indent"> Unconditionally issues a warning message to
43403  standard error. The given format string<I> fmt</I> and remaining
43404  arguments are interpreted as with <TT>printf()</TT>.</DIV>
43405 <P><TT>void rb_warning(const char *fmt, ...)</TT></P>
43406 <DIV class="indent"> Conditionally issues a warning message to standard
43407  error if Ruby was invoked with the <TT>-w</TT> flag. The given format
43408  string<I> fmt</I> and remaining arguments are interpreted as with <TT>
43409 printf()</TT>.</DIV>
43410 <H4><A name="Ruby_nn46"></A>32.7.8.5 Iterators</H4>
43411 <P> <TT>void rb_iter_break()</TT></P>
43412 <DIV class="indent"> Breaks out of the enclosing iterator block.</DIV>
43413 <P><TT>VALUE rb_each(VALUE obj)</TT></P>
43414 <DIV class="indent"> Invokes the <TT>each</TT> method of the given<I>
43415  obj</I>.</DIV>
43416 <P><TT>VALUE rb_yield(VALUE arg)</TT></P>
43417 <DIV class="indent"> Transfers execution to the iterator block in the
43418  current context, passing<I> arg</I> as an argument. Multiple values may
43419  be passed in an array.</DIV>
43420 <P><TT>int rb_block_given_p()</TT></P>
43421 <DIV class="indent"> Returns <TT>true</TT> if <TT>yield</TT> would
43422  execute a block in the current context; that is, if a code block was
43423  passed to the current method and is available to be called.</DIV>
43424 <P><TT>VALUE rb_iterate(VALUE (*method)(VALUE), VALUE args, VALUE
43425  (*block)(VALUE, VALUE), VALUE arg2)</TT></P>
43426 <DIV class="indent"> Invokes<I> method</I> with argument<I> args</I> and
43427  block<I> block</I>. A <TT>yield</TT> from that method will invoke<I>
43428  block</I> with the argument given to <TT>yield</TT>, and a second
43429  argument<I> arg2</I>.</DIV>
43430 <P><TT>VALUE rb_catch(const char *tag, VALUE (*proc)(VALUE, VALUE),
43431  VALUE value)</TT></P>
43432 <DIV class="indent"> Equivalent to Ruby's <TT>catch</TT>.</DIV>
43433 <P><TT>void rb_throw(const char *tag, VALUE value)</TT></P>
43434 <DIV class="indent"> Equivalent to Ruby's <TT>throw</TT>.</DIV>
43435 <H3><A name="Ruby_nn47"></A>32.7.9 Typemap Examples</H3>
43436 <P> This section includes a few examples of typemaps. For more examples,
43437  you might look at the examples in the <TT>Example/ruby</TT> directory.</P>
43438 <H3><A name="Ruby_nn48"></A>32.7.10 Converting a Ruby array to a char **</H3>
43439 <P> A common problem in many C programs is the processing of command
43440  line arguments, which are usually passed in an array of <TT>NULL</TT>
43441  terminated strings. The following SWIG interface file allows a Ruby
43442  Array instance to be used as a <TT>char **</TT> object.</P>
43443 <DIV class="code">
43444 <PRE>%module argv
43445 <BR>
43446 <BR>// This tells SWIG to treat char ** as a special case
43447 <BR>%typemap(in) char ** {
43448 <BR> /* Get the length of the array */
43449 <BR> int size = RARRAY($input)-&gt;len; 
43450 <BR> int i;
43451 <BR> $1 = (char **) malloc((size+1)*sizeof(char *));
43452 <BR> /* Get the first element in memory */
43453 <BR> VALUE *ptr = RARRAY($input)-&gt;ptr; 
43454 <BR> for (i=0; i &lt; size; i++, ptr++)
43455 <BR> /* Convert Ruby Object String to char* */
43456 <BR> $1[i]= STR2CSTR(*ptr); 
43457 <BR> $1[i]=NULL; /* End of list */
43458 <BR>}
43459 <BR>
43460 <BR>// This cleans up the char ** array created before 
43461 <BR>// the function call
43462 <BR>
43463 <BR>%typemap(freearg) char ** {
43464 <BR> free((char *) $1);
43465 <BR>}
43466 <BR>
43467 <BR>// Now a test function
43468 <BR>%inline %{
43469 <BR>int print_args(char **argv) {
43470 <BR> int i = 0;
43471 <BR> while (argv[i]) {
43472 <BR> printf(&quot;argv[%d] = %s\n&quot;, i,argv[i]);
43473 <BR> i++;
43474 <BR> }
43475 <BR> return i;
43476 <BR>}
43477 <BR>%}
43478 <BR>
43479 <BR></PRE>
43480 </DIV>
43481 <P> When this module is compiled, the wrapped C function now operates as
43482  follows :</P>
43483 <DIV class="code targetlang">
43484 <PRE>require 'Argv'
43485 <BR>Argv.print_args([&quot;Dave&quot;,&quot;Mike&quot;,&quot;Mary&quot;,&quot;Jane&quot;,&quot;John&quot;])
43486 <BR>argv[0] = Dave
43487 <BR>argv[1] = Mike
43488 <BR>argv[2] = Mary
43489 <BR>argv[3] = Jane
43490 <BR>argv[4] = John
43491 <BR></PRE>
43492 </DIV>
43493 <P> In the example, two different typemaps are used. The &quot;in&quot; typemap is
43494  used to receive an input argument and convert it to a C array. Since
43495  dynamic memory allocation is used to allocate memory for the array, the
43496  &quot;freearg&quot; typemap is used to later release this memory after the
43497  execution of the C function.</P>
43498 <H3><A name="Ruby_nn49"></A>32.7.11 Collecting arguments in a hash</H3>
43499 <P> Ruby's solution to the &quot;keyword arguments&quot; capability of some other
43500  languages is to allow the programmer to pass in one or more key-value
43501  pairs as arguments to a function. All of those key-value pairs are
43502  collected in a single <TT>Hash</TT> argument that's presented to the
43503  function. If it makes sense, you might want to provide similar
43504  functionality for your Ruby interface. For example, suppose you'd like
43505  to wrap this C function that collects information about people's vital
43506  statistics:</P>
43507 <DIV class="code">
43508 <PRE>void setVitalStats(const char *person, int nattributes, const char **names, int *values);
43509 <BR></PRE>
43510 </DIV>
43511 <P> and you'd like to be able to call it from Ruby by passing in an
43512  arbitrary number of key-value pairs as inputs, e.g.</P>
43513 <DIV class="code targetlang">
43514 <PRE>setVitalStats(&quot;Fred&quot;,
43515 <BR> 'weight' =&gt; 270,
43516 <BR>    'age' =&gt; 42
43517 <BR>    )
43518 <BR></PRE>
43519 </DIV>
43520 <P> To make this work, you need to write a typemap that expects a Ruby <TT>
43521 Hash</TT> as its input and somehow extracts the last three arguments (<I>
43522 nattributes</I>,<I> names</I> and<I> values</I>) needed by your C
43523  function. Let's start with the basics:</P>
43524 <DIV class="code">
43525 <PRE>%typemap(in) (int nattributes, const char **names, const int *values)
43526 <BR> (VALUE keys_arr, int i, VALUE key, VALUE val) {
43527 <BR>}
43528 <BR> </PRE>
43529 </DIV>
43530 <P> This <TT>%typemap</TT> directive tells SWIG that we want to match
43531  any function declaration that has the specified types and names of
43532  arguments somewhere in the argument list. The fact that we specified
43533  the argument names (<I>nattributes</I>,<I> names</I> and<I> values</I>)
43534  in our typemap is significant; this ensures that SWIG won't try to
43535  apply this typemap to<I> other</I> functions it sees that happen to
43536  have a similar declaration with different argument names. The arguments
43537  that appear in the second set of parentheses (<I>keys_arr</I>,<I> i</I>
43538 ,<I> key</I> and<I> val</I>) define local variables that our typemap
43539  will need.</P>
43540 <P>Since we expect the input argument to be a <TT>Hash</TT>, let's next
43541  add a check for that:</P>
43542 <DIV class="code">
43543 <PRE>%typemap(in) (int nattributes, const char **names, const int *values)
43544 <BR> (VALUE keys_arr, int i, VALUE key, VALUE val) {
43545 <BR> <B>Check_Type($input, T_HASH);</B>
43546 <BR>}
43547 <BR></PRE>
43548 </DIV>
43549 <P> <TT>Check_Type()</TT> is just a macro (defined in the Ruby header
43550  files) that confirms that the input argument is of the correct type; if
43551  it isn't, an exception will be raised.</P>
43552 <P>The next task is to determine how many key-value pairs are present in
43553  the hash; we'll assign this number to the first typemap argument (<TT>
43554 $1</TT>). This is a little tricky since the Ruby/C API doesn't provide a
43555  public function for querying the size of a hash, but we can get around
43556  that by calling the hash's<I> size</I> method directly and converting
43557  its result to a C <TT>int</TT> value:</P>
43558 <DIV class="code">
43559 <PRE>%typemap(in) (int nattributes, const char **names, const int *values)
43560 <BR> (VALUE keys_arr, int i, VALUE key, VALUE val) {
43561 <BR> Check_Type($input, T_HASH);
43562 <BR> <B>$1 = NUM2INT(rb_funcall($input, rb_intern(&quot;size&quot;), 0, NULL));</B>
43563 <BR>}
43564 <BR></PRE>
43565 </DIV>
43566 <P> So now we know the number of attributes. Next we need to initialize
43567  the second and third typemap arguments (i.e. the two C arrays) to <TT>
43568 NULL</TT> and set the stage for extracting the keys and values from the
43569  hash:</P>
43570 <DIV class="code">
43571 <PRE>%typemap(in) (int nattributes, const char **names, const int *values)
43572 <BR> (VALUE keys_arr, int i, VALUE key, VALUE val) {
43573 <BR> Check_Type($input, T_HASH);
43574 <BR> $1 = NUM2INT(rb_funcall($input, rb_intern(&quot;size&quot;), 0, NULL));
43575 <BR> <B>$2 = NULL;
43576 <BR> $3 = NULL;
43577 <BR> if ($1 &gt; 0) {
43578 <BR> $2 = (char **) malloc($1*sizeof(char *));
43579 <BR> $3 = (int *) malloc($1*sizeof(int));
43580 <BR> }</B>
43581 <BR>}
43582 <BR></PRE>
43583 </DIV>
43584 <P> There are a number of ways we could extract the keys and values from
43585  the input hash, but the simplest approach is to first call the hash's<I>
43586  keys</I> method (which returns a Ruby array of the keys) and then start
43587  looping over the elements in that array:</P>
43588 <DIV class="code">
43589 <PRE>%typemap(in) (int nattributes, const char **names, const int *values)
43590 <BR> (VALUE keys_arr, int i, VALUE key, VALUE val) {
43591 <BR> Check_Type($input, T_HASH);
43592 <BR> $1 = NUM2INT(rb_funcall($input, rb_intern(&quot;size&quot;), 0, NULL));
43593 <BR> $2 = NULL;
43594 <BR> $3 = NULL;
43595 <BR> if ($1 &gt; 0) {
43596 <BR> $2 = (char **) malloc($1*sizeof(char *));
43597 <BR> $3 = (int *) malloc($1*sizeof(int));
43598 <BR> <B>keys_arr = rb_funcall($input, rb_intern(&quot;keys&quot;), 0, NULL);
43599 <BR> for (i = 0; i &lt; $1; i++) {
43600 <BR> }</B>
43601 <BR>}
43602 <BR>}
43603 <BR></PRE>
43604 </DIV>
43605 <P> Recall that<I> keys_arr</I> and<I> i</I> are local variables for
43606  this typemap. For each element in the<I> keys_arr</I> array, we want to
43607  get the key itself, as well as the value corresponding to that key in
43608  the hash:</P>
43609 <DIV class="code">
43610 <PRE>%typemap(in) (int nattributes, const char **names, const int *values)
43611 <BR> (VALUE keys_arr, int i, VALUE key, VALUE val) {
43612 <BR> Check_Type($input, T_HASH);
43613 <BR> $1 = NUM2INT(rb_funcall($input, rb_intern(&quot;size&quot;), 0, NULL));
43614 <BR> $2 = NULL;
43615 <BR> $3 = NULL;
43616 <BR> if ($1 &gt; 0) {
43617 <BR> $2 = (char **) malloc($1*sizeof(char *));
43618 <BR> $3 = (int *) malloc($1*sizeof(int));
43619 <BR> keys_arr = rb_funcall($input, rb_intern(&quot;keys&quot;), 0, NULL);
43620 <BR> for (i = 0; i &lt; $1; i++) {
43621 <BR> <B>key = rb_ary_entry(keys_arr, i);
43622 <BR> val = rb_hash_aref($input, key);</B>
43623 <BR>}
43624 <BR>}
43625 <BR>}
43626 <BR></PRE>
43627 </DIV>
43628 <P> To be safe, we should again use the <TT>Check_Type()</TT> macro to
43629  confirm that the key is a <TT>String</TT> and the value is a <TT>Fixnum</TT>
43630 :</P>
43631 <DIV class="code">
43632 <PRE>%typemap(in) (int nattributes, const char **names, const int *values)
43633 <BR> (VALUE keys_arr, int i, VALUE key, VALUE val) {
43634 <BR> Check_Type($input, T_HASH);
43635 <BR> $1 = NUM2INT(rb_funcall($input, rb_intern(&quot;size&quot;), 0, NULL));
43636 <BR> $2 = NULL;
43637 <BR> $3 = NULL;
43638 <BR> if ($1 &gt; 0) {
43639 <BR> $2 = (char **) malloc($1*sizeof(char *));
43640 <BR> $3 = (int *) malloc($1*sizeof(int));
43641 <BR> keys_arr = rb_funcall($input, rb_intern(&quot;keys&quot;), 0, NULL);
43642 <BR> for (i = 0; i &lt; $1; i++) {
43643 <BR> key = rb_ary_entry(keys_arr, i);
43644 <BR> val = rb_hash_aref($input, key);
43645 <BR> <B>Check_Type(key, T_STRING);
43646 <BR> Check_Type(val, T_FIXNUM);</B>
43647 <BR>}
43648 <BR>}
43649 <BR>}
43650 <BR></PRE>
43651 </DIV>
43652 <P> Finally, we can convert these Ruby objects into their C equivalents
43653  and store them in our local C arrays:</P>
43654 <DIV class="code">
43655 <PRE>%typemap(in) (int nattributes, const char **names, const int *values)
43656 <BR> (VALUE keys_arr, int i, VALUE key, VALUE val) {
43657 <BR> Check_Type($input, T_HASH);
43658 <BR> $1 = NUM2INT(rb_funcall($input, rb_intern(&quot;size&quot;), 0, NULL));
43659 <BR> $2 = NULL;
43660 <BR> $3 = NULL;
43661 <BR> if ($1 &gt; 0) {
43662 <BR> $2 = (char **) malloc($1*sizeof(char *));
43663 <BR> $3 = (int *) malloc($1*sizeof(int));
43664 <BR> keys_arr = rb_funcall($input, rb_intern(&quot;keys&quot;), 0, NULL);
43665 <BR> for (i = 0; i &lt; $1; i++) {
43666 <BR> key = rb_ary_entry(keys_arr, i);
43667 <BR> val = rb_hash_aref($input, key);
43668 <BR> Check_Type(key, T_STRING);
43669 <BR> Check_Type(val, T_FIXNUM);
43670 <BR> <B>$2[i] = STR2CSTR(key);
43671 <BR> $3[i] = NUM2INT(val);</B>
43672 <BR>}
43673 <BR>}
43674 <BR>}
43675 <BR></PRE>
43676 </DIV>
43677 <P> We're not done yet. Since we used <TT>malloc()</TT> to dynamically
43678  allocate the memory used for the<I> names</I> and<I> values</I>
43679  arguments, we need to provide a corresponding &quot;freearg&quot; typemap to free
43680  that memory so that there is no memory leak. Fortunately, this typemap
43681  is a lot easier to write:</P>
43682 <DIV class="code">
43683 <PRE>%typemap(freearg) (int nattributes, const char **names, const int *values) {
43684 <BR> free((void *) $2);
43685 <BR> free((void *) $3);
43686 <BR>}
43687 <BR></PRE>
43688 </DIV>
43689 <P> All of the code for this example, as well as a sample Ruby program
43690  that uses the extension, can be found in the <TT>Examples/ruby/hashargs</TT>
43691  directory of the SWIG distribution.</P>
43692 <H3><A name="Ruby_nn50"></A>32.7.12 Pointer handling</H3>
43693 <P> Occasionally, it might be necessary to convert pointer values that
43694  have been stored using the SWIG typed-pointer representation. Since
43695  there are several ways in which pointers can be represented, the
43696  following two functions are used to safely perform this conversion:</P>
43697 <P><TT>int SWIG_ConvertPtr(VALUE obj, void **ptr, swig_type_info *ty,
43698  int flags)</TT></P>
43699 <DIV class="indent">Converts a Ruby object<I> obj</I> to a C pointer
43700  whose address is<I> ptr</I> (i.e.<I> ptr</I> is a pointer to a
43701  pointer). The third argument,<I> ty</I>, is a pointer to a SWIG type
43702  descriptor structure. If<I> ty</I> is not <TT>NULL</TT>, that type
43703  information is used to validate type compatibility and other aspects of
43704  the type conversion. If<I> flags</I> is non-zero, any type errors
43705  encountered during this validation result in a Ruby <TT>TypeError</TT>
43706  exception being raised; if<I> flags</I> is zero, such type errors will
43707  cause <TT>SWIG_ConvertPtr()</TT> to return -1 but not raise an
43708  exception. If<I> ty</I> is <TT>NULL</TT>, no type-checking is
43709  performed.</DIV>
43710 <P> <TT>VALUE SWIG_NewPointerObj(void *ptr, swig_type_info *ty, int own)</TT>
43711 </P>
43712 <DIV class="indent">Creates a new Ruby pointer object. Here,<I> ptr</I>
43713  is the pointer to convert,<I> ty</I> is the SWIG type descriptor
43714  structure that describes the type, and<I> own</I> is a flag that
43715  indicates whether or not Ruby should take ownership of the pointer
43716  (i.e. whether Ruby should free this data when the corresponding Ruby
43717  instance is garbage-collected).</DIV>
43718 <P> Both of these functions require the use of a special SWIG
43719  type-descriptor structure. This structure contains information about
43720  the mangled name of the datatype, type-equivalence information, as well
43721  as information about converting pointer values under C++ inheritance.
43722  For a type of <TT>Foo *</TT>, the type descriptor structure is usually
43723  accessed as follows:</P>
43724 <DIV class="indent code">
43725 <PRE>Foo *foo;
43726 <BR>SWIG_ConvertPtr($input, (void **) &amp;foo, SWIGTYPE_p_Foo, 1);
43727 <BR>
43728 <BR>VALUE obj;
43729 <BR>obj = SWIG_NewPointerObj(f, SWIGTYPE_p_Foo, 0);
43730 <BR></PRE>
43731 </DIV>
43732 <P> In a typemap, the type descriptor should always be accessed using
43733  the special typemap variable <TT>$1_descriptor</TT>. For example:</P>
43734 <DIV class="indent code">
43735 <PRE>%typemap(in) Foo * {
43736 <BR> SWIG_ConvertPtr($input, (void **) &amp;$1, $1_descriptor, 1);
43737 <BR>}
43738 <BR></PRE>
43739 </DIV>
43740 <H4><A name="Ruby_nn51"></A>32.7.12.1 Ruby Datatype Wrapping</H4>
43741 <P> <TT>VALUE Data_Wrap_Struct(VALUE class, void (*mark)(void *), void
43742  (*free)(void *), void *ptr)</TT></P>
43743 <DIV class="indent">Given a pointer<I> ptr</I> to some C data, and the
43744  two garbage collection routines for this data (<I>mark</I> and<I> free</I>
43745 ), return a <TT>VALUE</TT> for the Ruby object.</DIV>
43746 <P><TT>VALUE Data_Make_Struct(VALUE class,<I> c-type</I>, void
43747  (*mark)(void *), void (*free)(void *),<I> c-type</I> *ptr)</TT></P>
43748 <DIV class="indent">Allocates a new instance of a C data type<I> c-type</I>
43749 , assigns it to the pointer<I> ptr</I>, then wraps that pointer with <TT>
43750 Data_Wrap_Struct()</TT> as above.</DIV>
43751 <P><TT>Data_Get_Struct(VALUE obj,<I> c-type</I>,<I> c-type</I> *ptr)</TT>
43752 </P>
43753 <DIV class="indent">Retrieves the original C pointer of type<I> c-type</I>
43754  from the data object<I> obj</I> and assigns that pointer to<I> ptr</I>.</DIV>
43755 <H3><A name="Ruby_nn52"></A>32.7.13 Example: STL Vector to Ruby Array</H3>
43756 <P>Another use for macros and type maps is to create a Ruby array from a
43757  STL vector of pointers. In essence, copy of all the pointers in the
43758  vector into a Ruby array. The use of the macro is to make the typemap
43759  so generic that any vector with pointers can use the type map. The
43760  following is an example of how to construct this type of macro/typemap
43761  and should give insight into constructing similar typemaps for other
43762  STL structures:</P>
43763 <DIV class="code">
43764 <PRE>%define PTR_VECTOR_TO_RUBY_ARRAY(vectorclassname, classname)
43765 <BR>%typemap(out) vectorclassname &amp;, const vectorclassname &amp; {
43766 <BR> VALUE arr = rb_ary_new2($1-&gt;size());
43767 <BR> vectorclassname::iterator i = $1-&gt;begin(), iend = $1-&gt;end();
43768 <BR> for ( ; i!=iend; i++ )
43769 <BR> rb_ary_push(arr, Data_Wrap_Struct(c ## classname.klass, 0, 0, *i));
43770 <BR> $result = arr;
43771 <BR>}
43772 <BR>%typemap(out) vectorclassname, const vectorclassname {
43773 <BR> VALUE arr = rb_ary_new2($1.size());
43774 <BR> vectorclassname::iterator i = $1.begin(), iend = $1.end();
43775 <BR> for ( ; i!=iend; i++ )
43776 <BR> rb_ary_push(arr, Data_Wrap_Struct(c ## classname.klass, 0, 0, *i));
43777 <BR> $result = arr;
43778 <BR>}
43779 <BR>%enddef
43780 <BR></PRE>
43781 </DIV>
43782 <P> Note, that the &quot;<TT>c ## classname.klass&quot;</TT> is used in the
43783  preprocessor step to determine the actual object from the class name.</P>
43784 <P>To use the macro with a class Foo, the following is used:</P>
43785 <DIV class="code">
43786 <PRE>PTR_VECTOR_TO_RUBY_ARRAY(vector&lt;foo *=&quot;&quot;&gt;, Foo)
43787 <BR></PRE>
43788 </DIV>
43789 <P> It is also possible to create a STL vector of Ruby objects:</P>
43790 <DIV class="code">
43791 <PRE>%define RUBY_ARRAY_TO_PTR_VECTOR(vectorclassname, classname)
43792 <BR>%typemap(in) vectorclassname &amp;, const vectorclassname &amp; {
43793 <BR> Check_Type($input, T_ARRAY);
43794 <BR> vectorclassname *vec = new vectorclassname;
43795 <BR> int len = RARRAY($input)-&gt;len;
43796 <BR> for (int i=0; i!=len; i++) {
43797 <BR> VALUE inst = rb_ary_entry($input, i);
43798 <BR> //The following _should_ work but doesn't on HPUX
43799 <BR> // Check_Type(inst, T_DATA);
43800 <BR> classname *element = NULL;
43801 <BR> Data_Get_Struct(inst, classname, element);
43802 <BR> vec-&gt;push_back(element);
43803 <BR> }
43804 <BR> $1 = vec;
43805 <BR>}
43806 <BR>
43807 <BR>%typemap(freearg) vectorclassname &amp;, const vectorclassname &amp; {
43808 <BR> delete $1;
43809 <BR>}
43810 <BR>%enddef
43811 <BR></PRE>
43812 </DIV>
43813 <P> It is also possible to create a Ruby array from a vector of static
43814  data types:</P>
43815 <DIV class="code">
43816 <PRE>%define VECTOR_TO_RUBY_ARRAY(vectorclassname, classname)
43817 <BR>%typemap(out) vectorclassname &amp;, const vectorclassname &amp; {
43818 <BR> VALUE arr = rb_ary_new2($1-&gt;size()); 
43819 <BR> vectorclassname::iterator i = $1-&gt;begin(), iend = $1-&gt;end();
43820 <BR> for ( ; i!=iend; i++ )
43821 <BR> rb_ary_push(arr, Data_Wrap_Struct(c ## classname.klass, 0, 0, &amp;(*i)));
43822 <BR> $result = arr;
43823 <BR>}
43824 <BR>%typemap(out) vectorclassname, const vectorclassname {
43825 <BR> VALUE arr = rb_ary_new2($1.size()); 
43826 <BR> vectorclassname::iterator i = $1.begin(), iend = $1.end();
43827 <BR> for ( ; i!=iend; i++ )
43828 <BR> rb_ary_push(arr, Data_Wrap_Struct(c ## classname.klass, 0, 0, &amp;(*i)));
43829 <BR> $result = arr;
43830 <BR>}
43831 <BR>%enddef
43832 <BR></PRE>
43833 </DIV>
43834 <BR> Note that this is mostly an example of typemaps. If you want to use
43835  the STL with ruby, you are advised to use the standard swig STL
43836  library, which does much more than this. &nbsp;Refer to the section called
43837  the<A href="#Ruby_nn23_1"> C++ Standard Template Library</A>.
43838 <BR>
43839 <H2><A name="Ruby_nn65"></A>32.8 Docstring Features</H2>
43840 <P> Using ri and rdoc web pages in Ruby libraries is a common practice.
43841  Given the way that SWIG generates the extensions by default, your users
43842  will normally not get any documentation for it, even if they run 'rdoc'
43843  on the resulting .c or .cxx file.</P>
43844 <P>The features described in this section make it easy for you to add
43845  rdoc strings to your modules, functions and methods that can then be
43846  read by Ruby's rdoc tool to generate html web pages, ri documentation,
43847  Windows chm file and an .xml description.</P>
43848 <P>rdoc can then be run from a console or shell window on a swig
43849  generated file.&nbsp;</P>
43850 <P>For example, to generate html web pages from a C++ file, you'd do:&nbsp;</P>
43851 <DIV class="code shell">
43852 <!--span style=&quot;font-family: monospace; font-weight: bold;&quot;-->
43853  $ rdoc&nbsp;-E cxx=c -f html file_wrap.cxx</DIV>
43854 <P>To generate ri documentation from a c wrap file, you could do:</P>
43855 <DIV class="code shell">
43856 <!--span style=&quot;font-family: monospace; font-weight: bold;&quot;-->
43857 $ rdoc -r&nbsp;file_wrap.c</DIV>
43858 <H3><A name="Ruby_nn66"></A>32.8.1 Module docstring</H3>
43859 <P> Ruby allows a docstring at the beginning of the&nbsp;file before any
43860  other statements, and it is typically used to give a general
43861  description of the entire module. SWIG supports this by setting an
43862  option of the <TT>%module</TT> directive. For example:</P>
43863 <DIV class="code">
43864 <PRE>%module(docstring=&quot;This is the example module's docstring&quot;) example
43865 <BR></PRE>
43866 </DIV>
43867 <P> When you have more than just a line or so then you can retain the
43868  easy readability of the <TT>%module</TT> directive by using a macro.
43869  For example:</P>
43870 <DIV class="code">
43871 <PRE>%define DOCSTRING
43872 <BR>&quot;The `XmlResource` class allows program resources defining menus, 
43873 <BR>layout of controls on a panel, etc. to be loaded from an XML file.&quot;
43874 <BR>%enddef
43875 <BR>
43876 <BR>%module(docstring=DOCSTRING) xrc
43877 <BR></PRE>
43878 </DIV>
43879 <H3><A name="Ruby_nn67"></A>32.8.2 %feature(&quot;autodoc&quot;)</H3>
43880 <P>Since SWIG does know everything about the function it wraps, it is
43881  possible to generate an rdoc containing the parameter types, names and
43882  default values. Since Ruby ships with one of the best documentation
43883  systems of any language, it makes sense to take advantage of it.</P>
43884 <P>SWIG's Ruby module provides support for the &quot;autodoc&quot; feature, which
43885  when attached to a node in the parse tree will cause an rdoc comment to
43886  be generated in the wrapper file that includes the name of the
43887  function, parameter names, default values if any, and return type if
43888  any. There are also several options for autodoc controlled by the value
43889  given to the feature, described below.</P>
43890 <H4><A name="Ruby_nn68"></A>32.8.2.1 %feature(&quot;autodoc&quot;, &quot;0&quot;)</H4>
43891 <P> When the &quot;0&quot; option is given then the types of the parameters will<EM>
43892  not</EM> be included in the autodoc string. For example, given this
43893  function prototype:</P>
43894 <DIV class="code">
43895 <PRE>%feature(&quot;autodoc&quot;, &quot;0&quot;);
43896 <BR>bool function_name(int x, int y, Foo* foo=NULL, Bar* bar=NULL);
43897 <BR></PRE>
43898 </DIV>
43899 <P> Then Ruby code like this will be generated:</P>
43900 <DIV class="targetlang">
43901 <PRE>function_name(x, y, foo=nil, bar=nil) -&gt; bool
43902 <BR> ...
43903 <BR></PRE>
43904 </DIV>
43905 <H4><A name="Ruby_autodoc1"></A>32.8.2.2 %feature(&quot;autodoc&quot;, &quot;1&quot;)</H4>
43906 <P> When the &quot;1&quot; option is used then the parameter types<EM> will</EM>
43907  be used in the rdoc string. In addition, an attempt is made to simplify
43908  the type name such that it makes more sense to the Ruby user. Pointer,
43909  reference and const info is removed, <TT>%rename</TT>'s are evaluated,
43910  etc. (This is not always successful, but works most of the time. See
43911  the next section for what to do when it doesn't.) Given the example
43912  above, then turning on the parameter types with the &quot;1&quot; option will
43913  result in rdoc code like this:</P>
43914 <DIV class="targetlang">
43915 <PRE>function_name(int x, int y, Foo foo=nil, Bar bar=nil) -&gt; bool
43916 <BR> ...
43917 <BR></PRE>
43918 </DIV>
43919 <H4><A name="Ruby_autodoc2"></A>32.8.2.3 %feature(&quot;autodoc&quot;, &quot;2&quot;)</H4>
43920 <P> When the &quot;2&quot; option is used then the parameter types will not be
43921  used in the rdoc string. However, they will be listed in full after the
43922  function. &nbsp;Given the example above, then turning on the parameter types
43923  with the &quot;2&quot; option will result in Ruby code like this:</P>
43924 <H4><A name="Ruby_feature_autodoc3"></A>32.8.2.4 %feature(&quot;autodoc&quot;,
43925  &quot;3&quot;)</H4>
43926 <P> When the &quot;3&quot; option is used then the function will be documented
43927  using a combination of &quot;1&quot; and &quot;2&quot; above. &nbsp;Given the example above,
43928  then turning on the parameter types with the &quot;2&quot; option will result in
43929  Ruby code like this:</P>
43930 <DIV class="targetlang">
43931 <PRE>function_name(int x, int y, Foo foo=nil, Bar bar=nil) -&gt; bool
43932 <BR>
43933 <BR>Parameters:
43934 <BR>    x - int
43935 <BR>    y - int
43936 <BR>    foo - Foo
43937 <BR>    bar - Bar
43938 <BR></PRE>
43939 </DIV>
43940 <H4><A name="Ruby_nn70"></A>32.8.2.5 %feature(&quot;autodoc&quot;, &quot;docstring&quot;)</H4>
43941 <P> Finally, there are times when the automatically generated autodoc
43942  string will make no sense for a Ruby programmer, particularly when a
43943  typemap is involved. So if you give an explicit value for the autodoc
43944  feature then that string will be used in place of the automatically
43945  generated string. For example:</P>
43946 <DIV class="code">
43947 <PRE>%feature(&quot;autodoc&quot;, &quot;GetPosition() -&gt; (x, y)&quot;) GetPosition;
43948 <BR>void GetPosition(int* OUTPUT, int* OUTPUT);
43949 <BR></PRE>
43950 </DIV>
43951 <H3><A name="Ruby_nn71"></A>32.8.3 %feature(&quot;docstring&quot;)</H3>
43952 <P> In addition to the autodoc strings described above, you can also
43953  attach any arbitrary descriptive text to a node in the parse tree with
43954  the &quot;docstring&quot; feature. When the proxy module is generated then any
43955  docstring associated with classes, function or methods are output. If
43956  an item already has an autodoc string then it is combined with the
43957  docstring and they are output together.</P>
43958 <H2><A name="Ruby_nn53"></A>32.9 Advanced Topics</H2>
43959 <H3><A name="Ruby_nn54"></A>32.9.1 Operator overloading</H3>
43960 <P> SWIG allows operator overloading with, by using the <TT>%extend</TT>
43961  or <TT>%rename</TT> commands in SWIG and the following operator names
43962  (derived from Python):</P>
43963 <DIV class="code diagram">
43964 <TABLE border="1" cellpadding="2" cellspacing="2" style="width: 100%; font-family: monospace;"
43965 summary="operator names"><TBODY></TBODY>
43966 <TR><TD><B> General</B></TD></TR>
43967 <TR><TD>__repr__</TD><TD> inspect</TD></TR>
43968 <TR><TD>__str__</TD><TD> to_s</TD></TR>
43969 <TR><TD>__cmp__</TD><TD> &lt;=&gt;</TD></TR>
43970 <TR><TD>__hash__</TD><TD> hash</TD></TR>
43971 <TR><TD>__nonzero__</TD><TD> nonzero?</TD></TR>
43972 <TR><TD></TD></TR>
43973 <TR><TD><B> Callable</B></TD></TR>
43974 <TR><TD>__call__</TD><TD> call</TD></TR>
43975 <TR><TD></TD></TR>
43976 <TR><TD><B> Collection</B></TD></TR>
43977 <TR><TD>__len__</TD><TD> length</TD></TR>
43978 <TR><TD>__getitem__</TD><TD> []</TD></TR>
43979 <TR><TD>__setitem__</TD><TD> []=</TD></TR>
43980 <TR><TD></TD></TR>
43981 <TR><TD><B> Numeric</B></TD></TR>
43982 <TR><TD>__add__</TD><TD> +</TD></TR>
43983 <TR><TD>__sub__</TD><TD> -</TD><TD></TD></TR>
43984 <TR><TD>__mul__</TD><TD> *</TD></TR>
43985 <TR><TD>__div__</TD><TD> /</TD></TR>
43986 <TR><TD>__mod__</TD><TD> %</TD></TR>
43987 <TR><TD>__divmod__</TD><TD> divmod</TD></TR>
43988 <TR><TD>__pow__</TD><TD> **</TD></TR>
43989 <TR><TD>__lshift__</TD><TD> &lt;&lt;</TD></TR>
43990 <TR><TD>__rshift__</TD><TD> &gt;&gt;</TD></TR>
43991 <TR><TD>__and__</TD><TD> &amp;</TD></TR>
43992 <TR><TD>__xor__</TD><TD> ^</TD></TR>
43993 <TR><TD>__or__</TD><TD> |</TD></TR>
43994 <TR><TD>__neg__</TD><TD> -@</TD><TD></TD></TR>
43995 <TR><TD>__pos__</TD><TD> +@</TD></TR>
43996 <TR><TD>__abs__</TD><TD> abs</TD></TR>
43997 <TR><TD>__invert__</TD><TD> ~</TD></TR>
43998 <TR><TD>__int__</TD><TD> to_i</TD></TR>
43999 <TR><TD>__float__</TD><TD> to_f</TD></TR>
44000 <TR><TD>__coerce__</TD><TD> coerce</TD></TR>
44001 <TR><TD></TD></TR>
44002 <TR><TD><B>Additions in 1.3.13</B></TD></TR>
44003 <TR><TD>__lt__</TD><TD> &lt;</TD></TR>
44004 <TR><TD>__le__</TD><TD> &lt;=</TD></TR>
44005 <TR><TD>__eq__</TD><TD> ==</TD></TR>
44006 <TR><TD>__gt__</TD><TD> &gt;</TD></TR>
44007 <TR><TD>__ge__</TD><TD> &gt;=</TD></TR>
44008 </TABLE>
44009 </DIV>
44010 <P> Note that although SWIG supports the <TT>__eq__</TT> magic method
44011  name for defining an equivalence operator, there is no separate method
44012  for handling<I> inequality</I> since Ruby parses the expression<I> a !=
44013  b</I> as<I> !(a == b)</I>.</P>
44014 <H3><A name="Ruby_nn55"></A>32.9.2 Creating Multi-Module Packages</H3>
44015 <P> The chapter on <A href="Modules.html">Working with Modules</A>
44016  discusses the basics of creating multi-module extensions with SWIG, and
44017  in particular the considerations for sharing runtime type information
44018  among the different modules.</P>
44019 <P>As an example, consider one module's interface file (<TT>shape.i</TT>
44020 ) that defines our base class:</P>
44021 <DIV class="code">
44022 <PRE>%module shape
44023 <BR>
44024 <BR>%{
44025 <BR>#include &quot;Shape.h&quot;
44026 <BR>%}
44027 <BR>
44028 <BR>class Shape {
44029 <BR>protected:
44030 <BR> double xpos;
44031 <BR> double ypos;
44032 <BR>protected:
44033 <BR> Shape(double x, double y);
44034 <BR>public:
44035 <BR> double getX() const;
44036 <BR> double getY() const;
44037 <BR>};
44038 <BR></PRE>
44039 </DIV>
44040 <P> We also have a separate interface file (<TT>circle.i</TT>) that
44041  defines a derived class:</P>
44042 <DIV class="code">
44043 <PRE>%module circle
44044 <BR>
44045 <BR>%{
44046 <BR>#include &quot;Shape.h&quot;
44047 <BR>#include &quot;Circle.h&quot;
44048 <BR>%}
44049 <BR>
44050 <BR>// Import the base class definition from Shape module
44051 <BR>%import shape.i
44052 <BR>
44053 <BR>class Circle : public Shape {
44054 <BR>protected:
44055 <BR> double radius;
44056 <BR>public:
44057 <BR> Circle(double x, double y, double r);
44058 <BR> double getRadius() const;
44059 <BR>};
44060 <BR></PRE>
44061 </DIV>
44062 <P> We'll start by building the<B> Shape</B> extension module:</P>
44063 <DIV class="code shell">
44064 <PRE>$ <B>swig -c++ -ruby shape.i</B>
44065 </PRE>
44066 </DIV>
44067 <P> SWIG generates a wrapper file named <TT>shape_wrap.cxx</TT>. To
44068  compile this into a dynamically loadable extension for Ruby, prepare an
44069  <TT>extconf.rb</TT> script using this template:</P>
44070 <DIV class="code targetlang">
44071 <PRE>require 'mkmf'
44072 <BR>
44073 <BR># Since the SWIG runtime support library for Ruby
44074 <BR># depends on the Ruby library, make sure it's in the list
44075 <BR># of libraries.
44076 <BR>$libs = append_library($libs, Config::CONFIG['RUBY_INSTALL_NAME'])
44077 <BR>
44078 <BR># Create the makefile
44079 <BR>create_makefile('shape')
44080 <BR></PRE>
44081 </DIV>
44082 <P> Run this script to create a <TT>Makefile</TT> and then type <TT>make</TT>
44083  to build the shared library:</P>
44084 <DIV class="code targetlang">
44085 <PRE>$ <B>ruby extconf.rb</B>
44086 <BR>creating Makefile
44087 <BR>$ <B>make</B>
44088 <BR>g++ -fPIC -g -O2 -I. -I/usr/local/lib/ruby/1.7/i686-linux \
44089 <BR>-I. -c shape_wrap.cxx
44090 <BR>gcc -shared -L/usr/local/lib -o shape.so shape_wrap.o -L. \
44091 <BR>-lruby -lruby -lc
44092 <BR></PRE>
44093 </DIV>
44094 <P> Note that depending on your installation, the outputs may be
44095  slightly different; these outputs are those for a Linux-based
44096  development environment. The end result should be a shared library
44097  (here, <TT>shape.so</TT>) containing the extension module code. Now
44098  repeat this process in a separate directory for the<B> Circle</B>
44099  module:</P>
44100 <OL>
44101 <LI> Run SWIG to generate the wrapper code (<TT>circle_wrap.cxx</TT>);</LI>
44102 <LI> Write an <TT>extconf.rb</TT> script that your end-users can use to
44103  create a platform-specific <TT>Makefile</TT> for the extension;</LI>
44104 <LI> Build the shared library for this extension by typing <TT>make</TT>
44105 .</LI>
44106 </OL>
44107 <P> Once you've built both of these extension modules, you can test them
44108  interactively in IRB to confirm that the <TT>Shape</TT> and <TT>Circle</TT>
44109  modules are properly loaded and initialized:</P>
44110 <DIV class="code targetlang">
44111 <PRE>$ <B>irb</B>
44112 <BR>irb(main):001:0&gt; <B>require 'shape'</B>
44113 <BR>true
44114 <BR>irb(main):002:0&gt; <B>require 'circle'</B>
44115 <BR>true
44116 <BR>irb(main):003:0&gt; <B>c = Circle::Circle.new(5, 5, 20)</B>
44117 <BR>#&lt;Circle::Circle:0xa097208&gt;
44118 <BR>irb(main):004:0&gt; <B>c.kind_of? Shape::Shape</B>
44119 <BR>true
44120 <BR>irb(main):005:0&gt; <B>c.getX()</B>
44121 <BR>5.0
44122 <BR></PRE>
44123 </DIV>
44124 <H3><A name="Ruby_nn56"></A>32.9.3 Specifying Mixin Modules</H3>
44125 <P> The Ruby language doesn't support multiple inheritance, but it does
44126  allow you to mix one or more modules into a class using Ruby's <TT>
44127 include</TT> method. For example, if you have a Ruby class that defines
44128  an<EM> each</EM> instance method, e.g.</P>
44129 <DIV class="code targetlang">
44130 <PRE>class Set
44131 <BR> def initialize
44132 <BR> @members = []
44133 <BR> end
44134 <BR> 
44135 <BR> def each
44136 <BR> @members.each { |m| yield m }
44137 <BR> end
44138 <BR>end
44139 <BR></PRE>
44140 </DIV>
44141 <P> then you can mix-in Ruby's <TT>Enumerable</TT> module to easily add
44142  a lot of functionality to your class:</P>
44143 <DIV class="code targetlang">
44144 <PRE>class Set
44145 <BR> <B>include Enumerable</B>
44146 <BR>def initialize
44147 <BR>@members = []
44148 <BR>end
44149 <BR>def each
44150 <BR>@members.each { |m| yield m }
44151 <BR>end
44152 <BR>end
44153 <BR></PRE>
44154 </DIV>
44155 <P> To get the same benefit for your SWIG-wrapped classes, you can use
44156  the <TT>%mixin</TT> directive to specify the names of one or more
44157  modules that should be mixed-in to a class. For the above example, the
44158  SWIG interface specification might look like this:</P>
44159 <DIV class="code">
44160 <PRE>%mixin Set &quot;Enumerable&quot;;
44161 <BR>
44162 <BR>class Set {
44163 <BR>public:
44164 <BR> // Constructor
44165 <BR> Set();
44166 <BR> 
44167 <BR> // Iterates through set members
44168 <BR> void each();
44169 <BR>};
44170 <BR></PRE>
44171 </DIV>
44172 <P> Multiple modules can be mixed into a class by providing a
44173  comma-separated list of module names to the <TT>%mixin</TT> directive,
44174  e.g.</P>
44175 <DIV class="code">
44176 <PRE>%mixin Set &quot;Fee,Fi,Fo,Fum&quot;;</PRE>
44177 </DIV>
44178 <P> Note that the <TT>%mixin</TT> directive is implemented using SWIG's
44179  &quot;features&quot; mechanism and so the same name matching rules used for other
44180  kinds of features apply (see the chapter on <A href="#Customization">
44181 &quot;Customization Features&quot;</A>) for more details).</P>
44182 <H2><A name="Ruby_nn57"></A>32.10 Memory Management</H2>
44183 <P>One of the most common issues in generating SWIG bindings for Ruby is
44184  proper memory management. The key to proper memory management is
44185  clearly defining whether a wrapper Ruby object owns the underlying C
44186  struct or C++ class. There are two possibilities:</P>
44187 <UL>
44188 <LI> The Ruby object is responsible for freeing the C struct or C++
44189  object</LI>
44190 <LI> The Ruby object should not free the C struct or C++ object because
44191  it will be freed by the underlying C or C++ code</LI>
44192 </UL>
44193 <P>To complicate matters, object ownership may transfer from Ruby to C++
44194  (or vice versa) depending on what function or methods are invoked.
44195  Clearly, developing a SWIG wrapper requires a thorough understanding of
44196  how the underlying library manages memory.</P>
44197 <H3><A name="Ruby_nn58"></A>32.10.1 Mark and Sweep Garbage Collector</H3>
44198 <P>Ruby uses a mark and sweep garbage collector. When the garbage
44199  collector runs, it finds all the &quot;root&quot; objects, including local
44200  variables, global variables, global constants, hardware registers and
44201  the C stack. For each root object, the garbage collector sets its mark
44202  flag to true and calls <TT>rb_gc_mark</TT> on the object. The job of <TT>
44203 rb_gc_mark</TT> is to recursively mark all the objects that a Ruby
44204  object has a reference to (ignoring those objects that have already
44205  been marked). Those objects, in turn, may reference other objects. This
44206  process will continue until all active objects have been &quot;marked.&quot;
44207  After the mark phase comes the sweep phase. In the sweep phase, all
44208  objects that have not been marked will be garbage collected. For more
44209  information about the Ruby garbage collector please refer to <A href="http://rubygarden.org/ruby/ruby?GCAndExtensions">
44210
44211 <!--span style=&quot;text-decoration: underline;&quot;-->
44212  http://rubygarden.org/ruby/ruby?GCAndExtensions</A>.</P>
44213 <P>The Ruby C/API provides extension developers two hooks into the
44214  garbage collector - a &quot;mark&quot; function and a &quot;sweep&quot; function. By
44215  default these functions are set to NULL.</P>
44216 <P>If a C struct or C++ class references any other Ruby objects, then it
44217  must provide a &quot;mark&quot; function. The &quot;mark&quot; function should identify any
44218  referenced Ruby objects by calling the rb_gc_mark function for each
44219  one. Unsurprisingly, this function will be called by the Ruby garbage
44220  during the &quot;mark&quot; phase.</P>
44221 <P>During the sweep phase, Ruby destroys any unused objects. If any
44222  memory has been allocated in creating the underlying C struct or C++
44223  struct, then a &quot;free&quot; function must be defined that deallocates this
44224  memory.</P>
44225 <H3><A name="Ruby_nn59"></A>32.10.2 Object Ownership</H3>
44226 <P>As described above, memory management depends on clearly defining who
44227  is responsible for freeing the underlying C struct or C++ class. If the
44228  Ruby object is responsible for freeing the C++ object, then a &quot;free&quot;
44229  function must be registered for the object. If the Ruby object is not
44230  responsible for freeing the underlying memory, then a &quot;free&quot; function
44231  must not be registered for the object.</P>
44232 <P>For the most part, SWIG takes care of memory management issues. The
44233  rules it uses are:</P>
44234 <UL>
44235 <LI> When calling a C++ object's constructor from Ruby, SWIG will assign
44236  a &quot;free&quot; function thereby making the Ruby object responsible for
44237  freeing the C++ object</LI>
44238 <LI> When calling a C++ member function that returns a pointer, SWIG
44239  will not assign a &quot;free&quot; function thereby making the underlying library
44240  responsible for freeing the object.</LI>
44241 </UL>
44242 <P>To make this clearer, let's look at an example. Assume we have a Foo
44243  and a Bar class.</P>
44244 <DIV class="code">
44245 <PRE>/* File &quot;RubyOwernshipExample.h&quot; */
44246 <BR>
44247 <BR>class Foo
44248 <BR>{
44249 <BR>public:
44250 <BR> Foo() {}
44251 <BR> ~Foo() {}
44252 <BR>};
44253 <BR>
44254 <BR>class Bar
44255 <BR>{
44256 <BR> Foo *foo_;
44257 <BR>public:
44258 <BR> Bar(): foo_(new Foo) {}
44259 <BR> ~Bar() { delete foo_; }
44260 <BR> Foo* get_foo() { return foo_; }
44261 <BR> Foo* get_new_foo() { return new Foo; }
44262 <BR> void set_foo(Foo *foo) { delete foo_; foo_ = foo; }
44263 <BR>};
44264 <BR>
44265 <BR></PRE>
44266 </DIV>
44267 <P>First, consider this Ruby code:</P>
44268 <DIV class="code targetlang">
44269 <PRE>foo = Foo.new</PRE>
44270 </DIV>
44271 <P>In this case, the Ruby code calls the underlying <TT>Foo</TT> C++
44272  constructor, thus creating a new <TT>foo</TT> object. By default, SWIG
44273  will assign the new Ruby object a &quot;free&quot; function. When the Ruby object
44274  is garbage collected, the &quot;free&quot; function will be called. It in turn
44275  will call <TT>Foo's</TT> destructor.</P>
44276 <P>Next, consider this code:</P>
44277 <DIV class="code targetlang">
44278 <PRE>bar = Bar.new
44279 <BR>foo = bar.get_foo()</PRE>
44280 </DIV>
44281 <P>In this case, the Ruby code calls a C++ member function, <TT>get_foo</TT>
44282 . By default, SWIG will not assign the Ruby object a &quot;free&quot; function.
44283  Thus, when the Ruby object is garbage collected the underlying C++ <TT>
44284 foo</TT> object is not affected.</P>
44285 <P>Unfortunately, the real world is not as simple as the examples above.
44286  For example:</P>
44287 <DIV class="code targetlang">
44288 <PRE>bar = Bar.new
44289 <BR>foo = bar.get_new_foo()</PRE>
44290 </DIV>
44291 <P>In this case, the default SWIG behavior for calling member functions
44292  is incorrect. The Ruby object should assume ownership of the returned
44293  object. This can be done by using the %newobject directive. See <A href="#ownership">
44294  Object ownership and %newobject</A> for more information.</P>
44295 <P>The SWIG default mappings are also incorrect in this case:</P>
44296 <DIV class="code targetlang">
44297 <PRE>foo = Foo.new
44298 <BR>bar = Bar.new
44299 <BR>bar.set_foo(foo)</PRE>
44300 </DIV>
44301 <P>Without modification, this code will cause a segmentation fault. When
44302  the Ruby <TT>foo</TT> object goes out of scope, it will free the
44303  underlying C++ <TT>foo</TT> object. However, when the Ruby bar object
44304  goes out of scope, it will call the C++ bar destructor which will also
44305  free the C++ <TT>foo</TT> object. The problem is that object ownership
44306  is transferred from the Ruby object to the C++ object when the <TT>
44307 set_foo</TT> method is called. This can be done by using the special
44308  DISOWN type map, which was added to the Ruby bindings in SWIG-1.3.26.</P>
44309 <P>Thus, a correct SWIG interface file correct mapping for these classes
44310  is:</P>
44311 <DIV class="code">
44312 <PRE>/* File RubyOwnershipExample.i */
44313 <BR>
44314 <BR>%module RubyOwnershipExample
44315 <BR>
44316 <BR>%{
44317 <BR>#include &quot;RubyOwnershipExample.h&quot;
44318 <BR>%}
44319 <BR>
44320 <BR>class Foo
44321 <BR>{
44322 <BR>public:
44323 <BR> Foo();
44324 <BR> ~Foo();
44325 <BR>};
44326 <BR>
44327 <BR>class Bar
44328 <BR>{
44329 <BR> Foo *foo_;
44330 <BR>public:
44331 <BR> Bar();
44332 <BR> ~Bar();
44333 <BR> Foo* get_foo();
44334 <BR>
44335 <BR>
44336 <!--span style=&quot;font-weight: bold;&quot;-->
44337  %newobject get_new_foo;
44338 <BR> Foo* get_new_foo();
44339 <BR>
44340 <BR>
44341 <!--span style=&quot;font-weight: bold;&quot;-->
44342  %apply SWIGTYPE *DISOWN {Foo *foo};
44343 <BR> void set_foo(Foo *foo);
44344 <BR>
44345 <!--span style=&quot;font-weight: bold;&quot;-->
44346  %clear Foo *foo;
44347 <BR>};
44348 <BR>
44349 <BR></PRE>
44350 </DIV>
44351 <BR>
44352 <P> This code can be seen in swig/examples/ruby/tracking.</P>
44353 <BR>
44354 <H3><A name="Ruby_nn60"></A>32.10.3 Object Tracking</H3>
44355 <P>The remaining parts of this section will use the class library shown
44356  below to illustrate different memory management techniques. The class
44357  library models a zoo and the animals it contains.</P>
44358 <DIV class="code">
44359 <PRE>%module zoo
44360 <BR>
44361 <BR>%{
44362 <BR>#include &lt;string&gt;
44363 <BR>#include &lt;vector&gt;
44364 <BR>
44365 <BR>#include &quot;zoo.h&quot;
44366 <BR>%}
44367 <BR>
44368 <BR>class Animal
44369 <BR>{
44370 <BR>private:
44371 <BR> typedef std::vector&lt;Animal*&gt; AnimalsType;
44372 <BR> typedef AnimalsType::iterator IterType;
44373 <BR>protected:
44374 <BR> AnimalsType animals;
44375 <BR>protected:
44376 <BR> std::string name_;
44377 <BR>public:
44378 <BR> // Construct an animal with this name
44379 <BR> Animal(const char* name) : name_(name) {}
44380 <BR> 
44381 <BR> // Return the animal's name
44382 <BR> const char* get_name() const { return name.c_str(); }
44383 <BR>};
44384 <BR>
44385 <BR>class Zoo
44386 <BR>{
44387 <BR>protected:
44388 <BR> std::vector&lt;animal *=&quot;&quot;&gt; animals;
44389 <BR> 
44390 <BR>public:
44391 <BR> // Construct an empty zoo
44392 <BR> Zoo() {}
44393 <BR> 
44394 <BR> /* Create a new animal. */
44395 <BR> static Animal* Zoo::create_animal(const char* name)
44396 <BR> {
44397 <BR> return new Animal(name);
44398 <BR> }
44399 <BR>
44400 <BR> // Add a new animal to the zoo
44401 <BR> void add_animal(Animal* animal) {
44402 <BR> animals.push_back(animal); 
44403 <BR> }
44404 <BR>
44405 <BR> Animal* remove_animal(size_t i) {
44406 <BR> Animal* result = this-&gt;animals[i];
44407 <BR> IterType iter = this-&gt;animals.begin();
44408 <BR> std::advance(iter, i);
44409 <BR> this-&gt;animals.erase(iter);
44410 <BR>
44411 <BR> return result;
44412 <BR> }
44413 <BR> 
44414 <BR> // Return the number of animals in the zoo
44415 <BR> size_t get_num_animals() const {
44416 <BR> return animals.size(); 
44417 <BR> }
44418 <BR> 
44419 <BR> // Return a pointer to the ith animal
44420 <BR> Animal* get_animal(size_t i) const {
44421 <BR> return animals[i]; 
44422 <BR> }
44423 <BR>};
44424 <BR>
44425 <BR></PRE>
44426 </DIV>
44427 <P>Let's say you SWIG this code and then run IRB:
44428 <BR></P>
44429 <DIV class="code targetlang">
44430 <PRE>$ 
44431 <!--span style=&quot;font-weight: bold;&quot;-->
44432 irb
44433 <BR>irb(main):001:0&gt; 
44434 <!--span style=&quot;font-weight: bold;&quot;-->
44435 require 'example'
44436 <BR>=&gt; true
44437 <BR>
44438 <BR>irb(main):002:0&gt; 
44439 <!--span style=&quot;font-weight: bold;&quot;-->
44440 tiger1 = Example::Animal.new(&quot;tiger1&quot;)
44441 <BR>=&gt; #&lt;Example::Animal:0x2be3820&gt;
44442 <BR>
44443 <BR>irb(main):004:0&gt; 
44444 <!--span style=&quot;font-weight: bold;&quot;-->
44445 tiger1.get_name()
44446 <BR>=&gt; &quot;tiger1&quot;
44447 <BR>
44448 <BR>irb(main):003:0&gt; 
44449 <!--span style=&quot;font-weight: bold;&quot;-->
44450 zoo = Example::Zoo.new()
44451 <BR>=&gt; #&lt;Example::Zoo:0x2be0a60&gt;
44452 <BR>
44453 <BR>irb(main):006:0&gt; 
44454 <!--span style=&quot;font-weight: bold;&quot;-->
44455 zoo.add_animal(tiger)
44456 <BR>=&gt; nil
44457 <BR>
44458 <BR>irb(main):007:0&gt; 
44459 <!--span style=&quot;font-weight: bold;&quot;-->
44460 zoo.get_num_animals()
44461 <BR>=&gt; 1
44462 <BR>
44463 <BR>irb(main):007:0&gt; 
44464 <!--span style=&quot;font-weight: bold;&quot;-->
44465 tiger2 = zoo.remove_animal(0)
44466 <BR>=&gt; #&lt;Example::Animal:0x2bd4a18&gt;
44467 <BR>
44468 <BR>irb(main):008:0&gt; 
44469 <!--span style=&quot;font-weight: bold;&quot;-->
44470 tiger2.get_name()
44471 <BR>=&gt; &quot;tiger1&quot;
44472 <BR>
44473 <BR>irb(main):009:0&gt; 
44474 <!--span style=&quot;font-weight: bold;&quot;-->
44475 tiger1.equal?(tiger2)
44476 <BR>=&gt; false
44477 <BR>
44478 <BR></PRE>
44479 </DIV>
44480 <P>Pay particular attention to the code <TT>tiger1.equal?(tiger2)</TT>.
44481  Note that the two Ruby objects are not the same - but they reference
44482  the same underlying C++ object. This can cause problems. For example:
44483 <BR></P>
44484 <DIV class="code targetlang">
44485 <PRE>irb(main):010:0&gt; 
44486 <!--span style=&quot;font-weight: bold;&quot;-->
44487 tiger1 = nil
44488 <BR>=&gt; nil
44489 <BR>
44490 <BR>irb(main):011:0&gt; 
44491 <!--span style=&quot;font-weight: bold;&quot;-->
44492 GC.start
44493 <BR>=&gt; nil
44494 <BR>
44495 <BR>irb(main):012:0&gt; 
44496 <!--span style=&quot;font-weight: bold;&quot;-->
44497 tiger2.get_name()
44498 <BR>(irb):12: [BUG] Segmentation fault
44499 <BR>
44500 <BR></PRE>
44501 </DIV>
44502 <P>After the the garbage collector runs, as a result of our call to <TT>
44503 GC.start</TT>, calling<TT>tiger2.get_name()</TT> causes a segmentation
44504  fault. The problem is that when <TT>tiger1</TT> is garbage collected,
44505  it frees the underlying C++ object. Thus, when <TT>tiger2</TT> calls
44506  the <TT>get_name()</TT> method it invokes it on a destroyed object.</P>
44507 <P>This problem can be avoided if SWIG enforces a one-to-one mapping
44508  between Ruby objects and C++ classes. This can be done via the use of
44509  the <TT>%trackobjects</TT> functionality available in SWIG-1.3.26. and
44510  later.</P>
44511 <P>When the <TT>%trackobjects</TT> is turned on, SWIG automatically
44512  keeps track of mappings between C++ objects and Ruby objects. Note that
44513  enabling object tracking causes a slight performance degradation. Test
44514  results show this degradation to be about 3% to 5% when creating and
44515  destroying 100,000 animals in a row.</P>
44516 <P>Since <TT>%trackobjects</TT> is implemented as a <TT>%feature</TT>,
44517  it uses the same name matching rules as other kinds of features (see
44518  the chapter on <A href="#Customization"> &quot;Customization Features&quot;</A>)
44519  . Thus it can be applied on a class-by-class basis if needed. To fix
44520  the example above:</P>
44521 <BR><DIV class="code">
44522 <PRE>%module example
44523 <BR>
44524 <BR>%{
44525 <BR>#include &quot;example.h&quot;
44526 <BR>%}
44527 <BR>
44528 <BR>
44529 <!--span style=&quot;font-weight: bold;&quot;-->
44530 /* Tell SWIG that create_animal creates a new object */
44531 <BR>
44532 <!--span style=&quot;font-weight: bold;&quot;-->
44533 %newobject Zoo::create_animal;
44534 <BR>
44535 <BR>
44536 <!--span style=&quot;font-weight: bold;&quot;-->
44537 /* Tell SWIG to keep track of mappings between C/C++ structs/classes. */
44538 <BR style="font-weight: bold;">
44539 <!--span style=&quot;font-weight: bold;&quot;-->
44540 %trackobjects;
44541 <BR>
44542 <BR>%include &quot;example.h&quot;</PRE>
44543 </DIV>
44544 <P>When this code runs we see:
44545 <BR>
44546 <BR></P>
44547 <DIV class="code targetlang">
44548 <PRE>$ 
44549 <!--span style=&quot;font-weight: bold;&quot;-->
44550 irb
44551 <BR>irb(main):001:0&gt; 
44552 <!--span style=&quot;font-weight: bold;&quot;-->
44553 require 'example'
44554 <BR>=&gt; true
44555 <BR>
44556 <BR>irb(main):002:0&gt; 
44557 <!--span style=&quot;font-weight: bold;&quot;-->
44558 tiger1 = Example::Animal.new(&quot;tiger1&quot;)
44559 <BR>=&gt; #&lt;Example::Animal:0x2be37d8&gt;
44560 <BR>
44561 <BR>irb(main):003:0&gt; 
44562 <!--span style=&quot;font-weight: bold;&quot;-->
44563 zoo = Example::Zoo.new()
44564 <BR>=&gt; #&lt;Example::Zoo:0x2be0a18&gt;
44565 <BR>
44566 <BR>irb(main):004:0&gt; 
44567 <!--span style=&quot;font-weight: bold;&quot;-->
44568 zoo.add_animal(tiger1)
44569 <BR>=&gt; nil
44570 <BR>
44571 <BR>irb(main):006:0&gt; 
44572 <!--span style=&quot;font-weight: bold;&quot;-->
44573 tiger2 = zoo.remove_animal(0)
44574 <BR>=&gt; #&lt;Example::Animal:0x2be37d8&gt;
44575 <BR>
44576 <BR>irb(main):007:0&gt; 
44577 <!--span style=&quot;font-weight: bold;&quot;-->
44578 tiger1.equal?(tiger2)
44579 <BR>=&gt; true
44580 <BR>
44581 <BR>irb(main):008:0&gt; 
44582 <!--span style=&quot;font-weight: bold;&quot;-->
44583 tiger1 = nil
44584 <BR>=&gt; nil
44585 <BR>
44586 <BR>irb(main):009:0&gt; 
44587 <!--span style=&quot;font-weight: bold;&quot;-->
44588 GC.start
44589 <BR>=&gt; nil
44590 <BR>
44591 <BR>irb(main):010:0&gt; 
44592 <!--span style=&quot;font-weight: bold;&quot;-->
44593 tiger.get_name()
44594 <BR>=&gt; &quot;tiger1&quot;
44595 <BR>irb(main):011:0&gt;
44596 <BR>
44597 <BR></PRE>
44598 </DIV>
44599 <P>For those who are interested, object tracking is implemented by
44600  storing Ruby objects in a hash table and keying them on C++ pointers.
44601  The underlying API is:
44602 <BR></P>
44603 <DIV class="code">
44604 <PRE>static void SWIG_RubyAddTracking(void* ptr, VALUE object);
44605 <BR>static VALUE SWIG_RubyInstanceFor(void* ptr) ;
44606 <BR>static void SWIG_RubyRemoveTracking(void* ptr);
44607 <BR>static void SWIG_RubyUnlinkObjects(void* ptr);</PRE>
44608 </DIV>
44609 <P>When an object is created, SWIG will automatically call the <TT>
44610 SWIG_RubyAddTracking</TT> method. Similarly, when an object is deleted,
44611  SWIG will call the <TT>SWIG_RubyRemoveTracking</TT>. When an object is
44612  returned to Ruby from C++, SWIG will use the <TT>SWIG_RubyInstanceFor</TT>
44613  method to ensure a one-to-one mapping from Ruby to C++ objects. Last,
44614  the <TT>RubyUnlinkObjects</TT> method unlinks a Ruby object from its
44615  underlying C++ object.</P>
44616 <P>In general, you will only need to use the <TT>SWIG_RubyInstanceFor</TT>
44617 , which is required for implementing mark functions as shown below.
44618  However, if you implement your own free functions (see below) you may
44619  also have to call the <TT>SWIG_RubyRemoveTracking</TT> and <TT>
44620 RubyUnlinkObjects</TT> methods.</P>
44621 <H3><A name="Ruby_nn61"></A>32.10.4 Mark Functions</H3>
44622 <P>With a bit more testing, we see that our class library still has
44623  problems. For example:
44624 <BR></P>
44625 <DIV class="targetlang">
44626 <PRE>$ <B>irb</B>
44627 <BR>irb(main):001:0&gt; 
44628 <!--span style=&quot;font-weight: bold;&quot;-->
44629 require 'example'
44630 <BR>=&gt; true
44631 <BR>
44632 <BR>irb(main):002:0&gt; tiger1 = 
44633 <!--span style=&quot;font-weight: bold;&quot;-->
44634 Example::Animal.new(&quot;tiger1&quot;)
44635 <BR>=&gt; #&lt;Example::Animal:0x2bea6a8&gt;
44636 <BR>
44637 <BR>irb(main):003:0&gt; zoo = 
44638 <!--span style=&quot;font-weight: bold;&quot;-->
44639 Example::Zoo.new()
44640 <BR>=&gt; #&lt;Example::Zoo:0x2be7960&gt;
44641 <BR>
44642 <BR>irb(main):004:0&gt; 
44643 <!--span style=&quot;font-weight: bold;&quot;-->
44644 zoo.add_animal(tiger1)
44645 <BR>=&gt; nil
44646 <BR>
44647 <BR>irb(main):007:0&gt; 
44648 <!--span style=&quot;font-weight: bold;&quot;-->
44649 tiger1 = nil
44650 <BR>=&gt; nil
44651 <BR>
44652 <BR>irb(main):007:0&gt; 
44653 <!--span style=&quot;font-weight: bold;&quot;-->
44654 GC.start
44655 <BR>=&gt; nil
44656 <BR>
44657 <BR>irb(main):005:0&gt; 
44658 <!--span style=&quot;font-weight: bold;&quot;-->
44659 tiger2 = zoo.get_animal(0)
44660 <BR>(irb):12: [BUG] Segmentation fault</PRE>
44661 </DIV>
44662 <P>The problem is that Ruby does not know that the <TT>zoo</TT> object
44663  contains a reference to a Ruby object. Thus, when Ruby garbage collects
44664 <!--span style=&quot;font-family: monospace;&quot;-->
44665  tiger1 it frees the underlying C++ object.</P>
44666 <P>This can be fixed by implementing a <TT>mark</TT> function as
44667  described above in the <A href="#Ruby_nn52">Mark and Sweep Garbage
44668  Collector</A> section. You can specify a mark function by using the <TT>
44669 %markfunc</TT> directive. Since the <TT>%markfunc</TT> directive is
44670  implemented using SWIG's' &quot;features&quot; mechanism it uses the same name
44671  matching rules as other kinds of features (see the chapter on <A href="#Customization">
44672 &quot;Customization Features&quot;</A> for more details).</P>
44673 <P>A <TT>mark</TT> function takes a single argument, which is a pointer
44674  to the C++ object being marked; it should, in turn, call <TT>
44675 rb_gc_mark()</TT> for any instances that are reachable from the current
44676  object. The mark function for our <TT>Zoo</TT> class should therefore
44677  loop over all of the C++ animal objects in the zoo object, look up
44678  their Ruby object equivalent, and then call <TT>rb_gc_mark()</TT>. One
44679  possible implementation is:</P>
44680 <DIV class="code">
44681 <PRE>%module example
44682 <BR>
44683 <BR>%{
44684 <BR>#include &quot;example.h&quot;
44685 <BR>%}
44686 <BR>
44687 <BR>/* Keep track of mappings between C/C++ structs/classes
44688 <BR> and Ruby objects so we can implement a mark function. */
44689 <BR>
44690 <!--span style=&quot;font-weight: bold;&quot;-->
44691 %trackobjects;
44692 <BR>
44693 <BR>/* Specify the mark function */
44694 <BR>
44695 <!--span style=&quot;font-weight: bold;&quot;-->
44696 %markfunc Zoo &quot;mark_Zoo&quot;;
44697 <BR>
44698 <BR>%include &quot;example.h&quot;
44699 <BR>
44700 <BR>%header %{
44701 <BR>
44702 <BR>static void mark_Zoo(void* ptr) {
44703 <BR> Zoo* zoo = (Zoo*) ptr;
44704 <BR>
44705 <BR> /* Loop over each object and tell the garbage collector
44706 <BR> that we are holding a reference to them. */
44707 <BR> int count = zoo-&gt;get_num_animals();
44708 <BR>
44709 <BR> for(int i = 0; i &lt; count; ++i) {
44710 <BR> Animal* animal = zoo-&gt;get_animal(i);
44711 <BR> VALUE object = SWIG_RubyInstanceFor(animal);
44712 <BR>
44713 <BR> if (object != Qnil) {
44714 <BR> rb_gc_mark(object);
44715 <BR> }
44716 <BR> }
44717 <BR>}
44718 <BR>%}
44719 <BR>
44720 <BR></PRE>
44721 </DIV>
44722 <P> Note the <TT>mark</TT> function is dependent on the <TT>
44723 SWIG_RUBY_InstanceFor</TT> method, and thus requires that <TT>
44724 %trackobjects</TT> is enabled. For more information, please refer to the
44725  track_object.i test case in the SWIG test suite.</P>
44726 <P>When this code is compiled we now see:</P>
44727 <DIV class="targetlang">
44728 <PRE>$ <B>irb
44729 <BR></B>irb(main):002:0&gt; 
44730 <!--span style=&quot;font-weight: bold;&quot;-->
44731 tiger1=Example::Animal.new(&quot;tiger1&quot;)
44732 <BR>=&gt; #&lt;Example::Animal:0x2be3bf8&gt;
44733 <BR>
44734 <BR>irb(main):003:0&gt; 
44735 <!--span style=&quot;font-weight: bold;&quot;-->
44736 Example::Zoo.new()
44737 <BR>=&gt; #&lt;Example::Zoo:0x2be1780&gt;
44738 <BR>
44739 <BR>irb(main):004:0&gt; 
44740 <!--span style=&quot;font-weight: bold;&quot;-->
44741 zoo = Example::Zoo.new()
44742 <BR>=&gt; #&lt;Example::Zoo:0x2bde9c0&gt;
44743 <BR>
44744 <BR>irb(main):005:0&gt; 
44745 <!--span style=&quot;font-weight: bold;&quot;-->
44746 zoo.add_animal(tiger1)
44747 <BR>=&gt; nil
44748 <BR>
44749 <BR>irb(main):009:0&gt; 
44750 <!--span style=&quot;font-weight: bold;&quot;-->
44751 tiger1 = nil
44752 <BR>=&gt; nil
44753 <BR>
44754 <BR>irb(main):010:0&gt; 
44755 <!--span style=&quot;font-weight: bold;&quot;-->
44756 GC.start
44757 <BR>=&gt; nil
44758 <BR>irb(main):014:0&gt; 
44759 <!--span style=&quot;font-weight: bold;&quot;-->
44760 tiger2 = zoo.get_animal(0)
44761 <BR>=&gt; #&lt;Example::Animal:0x2be3bf8&gt;
44762 <BR>
44763 <BR>irb(main):015:0&gt; 
44764 <!--span style=&quot;font-weight: bold;&quot;-->
44765 tiger2.get_name()
44766 <BR>=&gt; &quot;tiger1&quot;
44767 <BR>irb(main):016:0&gt;
44768 <BR>
44769 <BR></PRE>
44770 </DIV>
44771 <BR>
44772 <P>This code can be seen in swig/examples/ruby/mark_function.</P>
44773 <H3><A name="Ruby_nn62"></A>32.10.5 Free Functions</H3>
44774 <P>By default, SWIG creates a &quot;free&quot; function that is called when a Ruby
44775  object is garbage collected. The free function simply calls the C++
44776  object's destructor.</P>
44777 <P>However, sometimes an appropriate destructor does not exist or
44778  special processing needs to be performed before the destructor is
44779  called. Therefore, SWIG allows you to manually specify a &quot;free&quot;
44780  function via the use of the <TT>%freefunc</TT> directive. The <TT>
44781 %freefunc</TT> directive is implemented using SWIG's' &quot;features&quot;
44782  mechanism and so the same name matching rules used for other kinds of
44783  features apply (see the chapter on <A href="#Customization">
44784 &quot;Customization Features&quot;</A>) for more details).</P>
44785 <P>IMPORTANT ! - If you define your own free function, then you must
44786  ensure that you call the underlying C++ object's destructor. In
44787  addition, if object tracking is activated for the object's class, you
44788  must also call the <TT>SWIG_RubyRemoveTracking</TT> function (of course
44789  call this before you destroy the C++ object). Note that it is harmless
44790  to call this method if object tracking if off so it is advised to
44791  always call it.</P>
44792 <P>Note there is a subtle interaction between object ownership and free
44793  functions. A custom defined free function will only be called if the
44794  Ruby object owns the underlying C++ object. This also to Ruby objects
44795  which are created, but then transfer ownership to C++ objects via the
44796  use of the <TT>disown</TT> typemap described above.</P>
44797 <P>To show how to use the <TT>%freefunc</TT> directive, let's slightly
44798  change our example. Assume that the zoo object is responsible for
44799  freeing animal that it contains. This means that the
44800 <!--span style=&quot;font-family: monospace;&quot;-->
44801  Zoo::add_animal function should be marked with a
44802 <!--span style=&quot;font-family: monospace;&quot;-->
44803  DISOWN typemap and the destructor should be updated as below::</P>
44804 <DIV class="code">
44805 <PRE>Zoo::~Zoo() {
44806 <BR> IterType iter = this-&gt;animals.begin();
44807 <BR> IterType end = this-&gt;animals.end();
44808 <BR>
44809 <BR> for(iter; iter != end; ++iter) {
44810 <BR> Animal* animal = *iter;
44811 <BR> delete animal;
44812 <BR> }
44813 <BR>}</PRE>
44814 </DIV>
44815 <P>When we use these objects in IRB we see:</P>
44816 <DIV class="code targetlang">
44817 <PRE class="targetlang">
44818 <!--span style=&quot;font-weight: bold;&quot;-->
44819 $irb
44820 <BR>irb(main):002:0&gt; 
44821 <!--span style=&quot;font-weight: bold;&quot;-->
44822 require 'example'
44823 <BR>=&gt; true
44824 <BR>
44825 <BR>irb(main):003:0&gt; 
44826 <!--span style=&quot;font-weight: bold;&quot;-->
44827 zoo = Example::Zoo.new()
44828 <BR>=&gt; #&lt;Example::Zoo:0x2be0fe8&gt;
44829 <BR>
44830 <BR>irb(main):005:0&gt; 
44831 <!--span style=&quot;font-weight: bold;&quot;-->
44832 tiger1 = Example::Animal.new(&quot;tiger1&quot;)
44833 <BR>=&gt; #&lt;Example::Animal:0x2bda760&gt;
44834 <BR>
44835 <BR>irb(main):006:0&gt; 
44836 <!--span style=&quot;font-weight: bold;&quot;-->
44837 zoo.add_animal(tiger1)
44838 <BR>=&gt; nil
44839 <BR>
44840 <BR>irb(main):007:0&gt; 
44841 <!--span style=&quot;font-weight: bold;&quot;-->
44842 zoo = nil
44843 <BR>=&gt; nil
44844 <BR>
44845 <BR>irb(main):008:0&gt; 
44846 <!--span style=&quot;font-weight: bold;&quot;-->
44847 GC.start
44848 <BR>=&gt; nil
44849 <BR>
44850 <BR>irb(main):009:0&gt; 
44851 <!--span style=&quot;font-weight: bold;&quot;-->
44852 tiger1.get_name()
44853 <BR>(irb):12: [BUG] Segmentation fault
44854 <BR>
44855 <BR></PRE>
44856 </DIV>
44857 <P>The error happens because the C++ <TT>animal</TT> object is freed
44858  when the <TT>zoo</TT> object is freed. Although this error is
44859  unavoidable, we can at least prevent the segmentation fault. To do this
44860  requires enabling object tracking and implementing a custom free
44861  function that calls the <TT>SWIG_RubyUnlinkObjects</TT> function for
44862  each animal object that is destroyed. The <TT>SWIG_RubyUnlinkObjects</TT>
44863  function notifies SWIG that a Ruby object's underlying C++ object is no
44864  longer valid. Once notified, SWIG will intercept any calls from the
44865  existing Ruby object to the destroyed C++ object and raise an
44866  exception.
44867 <BR></P>
44868 <DIV class="code">
44869 <PRE>%module example
44870 <BR>
44871 <BR>%{
44872 <BR>#include &quot;example.h&quot;
44873 <BR>%}
44874 <BR>
44875 <BR>/* Specify that ownership is transferred to the zoo
44876 <BR>    when calling add_animal */
44877 <BR>%apply SWIGTYPE *DISOWN { Animal* animal };
44878 <BR>
44879 <BR>/* Track objects */
44880 <BR>%trackobjects;
44881 <BR>
44882 <BR>/* Specify the mark function */
44883 <BR>%freefunc Zoo &quot;free_Zoo&quot;;
44884 <BR>
44885 <BR>%include &quot;example.h&quot;
44886 <BR>
44887 <BR>%header %{
44888 <BR> static void free_Zoo(void* ptr) {
44889 <BR> Zoo* zoo = (Zoo*) ptr;
44890 <BR>
44891 <BR> /* Loop over each animal */
44892 <BR> int count = zoo-&gt;get_num_animals();
44893 <BR>
44894 <BR> for(int i = 0; i &lt; count; ++i) {
44895 <BR> /* Get an animal */
44896 <BR> Animal* animal = zoo-&gt;get_animal(i);
44897 <BR>
44898 <BR> /* Unlink the Ruby object from the C++ object */
44899 <BR> SWIG_RubyUnlinkObjects(animal);
44900 <BR>
44901 <BR> /* Now remove the tracking for this animal */
44902 <BR> SWIG_RubyRemoveTracking(animal);
44903 <BR> }
44904 <BR>
44905 <BR> /* Now call SWIG_RubyRemoveTracking for the zoo */
44906 <BR> SWIG_RubyRemoveTracking(ptr);
44907 <BR> 
44908 <BR> /* Now free the zoo which will free the animals it contains */
44909 <BR> delete zoo;
44910 <BR> }
44911 <BR>%} </PRE>
44912 </DIV>
44913 <P>Now when we use these objects in IRB we see:</P>
44914 <DIV class="code targetlang">
44915 <PRE>
44916 <!--span style=&quot;font-weight: bold;&quot;-->
44917 $irb
44918 <BR>irb(main):002:0&gt; 
44919 <!--span style=&quot;font-weight: bold;&quot;-->
44920 require 'example'
44921 <BR>=&gt; true
44922 <BR>
44923 <BR>irb(main):003:0&gt; 
44924 <!--span style=&quot;font-weight: bold;&quot;-->
44925 zoo = Example::Zoo.new()
44926 <BR>=&gt; #&lt;Example::Zoo:0x2be0fe8&gt;
44927 <BR>
44928 <BR>irb(main):005:0&gt; 
44929 <!--span style=&quot;font-weight: bold;&quot;-->
44930 tiger1 = Example::Animal.new(&quot;tiger1&quot;)
44931 <BR>=&gt; #&lt;Example::Animal:0x2bda760&gt;
44932 <BR>
44933 <BR>irb(main):006:0&gt; 
44934 <!--span style=&quot;font-weight: bold;&quot;-->
44935 zoo.add_animal(tiger1)
44936 <BR>=&gt; nil
44937 <BR>
44938 <BR>irb(main):007:0&gt; 
44939 <!--span style=&quot;font-weight: bold;&quot;-->
44940 zoo = nil
44941 <BR>=&gt; nil
44942 <BR>
44943 <BR>irb(main):008:0&gt; 
44944 <!--span style=&quot;font-weight: bold;&quot;-->
44945 GC.start
44946 <BR>=&gt; nil
44947 <BR>
44948 <BR>irb(main):009:0&gt; 
44949 <!--span style=&quot;font-weight: bold;&quot;-->
44950 tiger1.get_name()
44951 <BR>RuntimeError: This Animal * already released
44952 <BR> from (irb):10:in `get_name'
44953 <BR> from (irb):10
44954 <BR>irb(main):011:0&gt;</PRE>
44955 </DIV>
44956 <P>Notice that SWIG can now detect the underlying C++ object has been
44957  freed, and thus raises a runtime exception.</P>
44958 <P>This code can be seen in swig/examples/ruby/free_function.</P>
44959 <H3><A name="Ruby_nn63"></A>32.10.6 Embedded Ruby and the C++ Stack</H3>
44960 <P>As has been said, the Ruby GC runs and marks objects before its sweep
44961  phase. &nbsp;When the garbage collector is called, it will also try to mark
44962  any Ruby objects (VALUE) it finds in the machine registers and in the
44963  C++ stack.</P>
44964 <P>The stack is basically the history of the functions that have been
44965  called and also contains local variables, such as the ones you define
44966  whenever you do inside a function:</P>
44967 <DIV class="diagram">VALUE obj;</DIV>
44968 <P>For ruby to determine where its stack space begins, during
44969  initialization a normal Ruby interpreter will call the ruby_init()
44970  function which in turn will call a function called Init_stack or
44971  similar. &nbsp;This function will store a pointer to the location where the
44972  stack points at at that point in time.</P>
44973 <P>ruby_init() is presumed to always be called within the main()
44974  function of your program and whenever the GC is called, ruby will
44975  assume that the memory between the current location in memory and the
44976  pointer that was stored previously represents the stack, which may
44977  contain local (and temporary) VALUE ruby objects. &nbsp; Ruby will then be
44978  careful not to remove any of those objects in that location.</P>
44979 <P>So far so good. &nbsp;For a normal Ruby session, all the above is
44980  completely transparent and magic to the extensions developer. &nbsp;&nbsp;</P>
44981 <P>However, with an embedded Ruby, it may not always be possible to
44982  modify main() to make sure ruby_init() is called there. &nbsp; As such,
44983  ruby_init() will likely end up being called from within some other
44984  function. &nbsp;This can lead Ruby to measure incorrectly where the stack
44985  begins and&nbsp;can result in Ruby incorrectly collecting those temporary
44986  VALUE objects that are created once another&nbsp;function is called. &nbsp;The
44987  end result: random crashes and segmentation faults.</P>
44988 <P>This problem will often be seen in director functions that are used
44989  for callbacks, for example. &nbsp;</P>
44990 <P>To solve the problem, SWIG can now generate code with director
44991  functions&nbsp;containing the optional macros SWIG_INIT_STACK and
44992  SWIG_RELEASE_STACK. &nbsp; These macros will try to force Ruby to
44993  reinitiliaze the beginning of the stack&nbsp;the first time a director
44994  function is called. &nbsp;This will lead Ruby to measure and not collect any
44995  VALUE objects defined from that point on. &nbsp;</P>
44996 <P>To mark functions to either reset the ruby stack or not, you can use:</P>
44997 <DIV class="indent code" style="font-family: monospace;">%initstack &nbsp;
44998  Class::memberfunction; &nbsp;// only re-init the stack in this director
44999  method
45000 <BR> %ignorestack Class::memberfunction; &nbsp;// do not re-init the stack in
45001  this director method
45002 <BR> %initstack &nbsp; Class; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // init the stack on all the
45003  methods of this class
45004 <BR> %initstack; &nbsp; // all director functions will re-init the stack</DIV>
45005 <HR NOSHADE>
45006 <H1><A name="Tcl"></A>33 SWIG and Tcl</H1>
45007
45008 <!-- INDEX -->
45009 <DIV class="sectiontoc">
45010 <UL>
45011 <LI><A href="#Tcl_nn2">Preliminaries</A>
45012 <UL>
45013 <LI><A href="#Tcl_nn3">Getting the right header files</A></LI>
45014 <LI><A href="#Tcl_nn4">Compiling a dynamic module</A></LI>
45015 <LI><A href="#Tcl_nn5">Static linking</A></LI>
45016 <LI><A href="#Tcl_nn6">Using your module</A></LI>
45017 <LI><A href="#Tcl_nn7">Compilation of C++ extensions</A></LI>
45018 <LI><A href="#Tcl_nn8">Compiling for 64-bit platforms</A></LI>
45019 <LI><A href="#Tcl_nn9">Setting a package prefix</A></LI>
45020 <LI><A href="#Tcl_nn10">Using namespaces</A></LI>
45021 </UL>
45022 </LI>
45023 <LI><A href="#Tcl_nn11">Building Tcl/Tk Extensions under Windows 95/NT</A>
45024 <UL>
45025 <LI><A href="#Tcl_nn12">Running SWIG from Developer Studio</A></LI>
45026 <LI><A href="#Tcl_nn13">Using NMAKE</A></LI>
45027 </UL>
45028 </LI>
45029 <LI><A href="#Tcl_nn14">A tour of basic C/C++ wrapping</A>
45030 <UL>
45031 <LI><A href="#Tcl_nn15">Modules</A></LI>
45032 <LI><A href="#Tcl_nn16">Functions</A></LI>
45033 <LI><A href="#Tcl_nn17">Global variables</A></LI>
45034 <LI><A href="#Tcl_nn18">Constants and enums</A></LI>
45035 <LI><A href="#Tcl_nn19">Pointers</A></LI>
45036 <LI><A href="#Tcl_nn20">Structures</A></LI>
45037 <LI><A href="#Tcl_nn21">C++ classes</A></LI>
45038 <LI><A href="#Tcl_nn22">C++ inheritance</A></LI>
45039 <LI><A href="#Tcl_nn23">Pointers, references, values, and arrays</A></LI>
45040 <LI><A href="#Tcl_nn24">C++ overloaded functions</A></LI>
45041 <LI><A href="#Tcl_nn25">C++ operators</A></LI>
45042 <LI><A href="#Tcl_nn26">C++ namespaces</A></LI>
45043 <LI><A href="#Tcl_nn27">C++ templates</A></LI>
45044 <LI><A href="#Tcl_nn28">C++ Smart Pointers</A></LI>
45045 </UL>
45046 </LI>
45047 <LI><A href="#Tcl_nn29">Further details on the Tcl class interface</A>
45048 <UL>
45049 <LI><A href="#Tcl_nn30">Proxy classes</A></LI>
45050 <LI><A href="#Tcl_nn31">Memory management</A></LI>
45051 </UL>
45052 </LI>
45053 <LI><A href="#Tcl_nn32">Input and output parameters</A></LI>
45054 <LI><A href="#Tcl_nn33">Exception handling</A></LI>
45055 <LI><A href="#Tcl_nn34">Typemaps</A>
45056 <UL>
45057 <LI><A href="#Tcl_nn35">What is a typemap?</A></LI>
45058 <LI><A href="#Tcl_nn36">Tcl typemaps</A></LI>
45059 <LI><A href="#Tcl_nn37">Typemap variables</A></LI>
45060 <LI><A href="#Tcl_nn38">Converting a Tcl list to a char **</A></LI>
45061 <LI><A href="#Tcl_nn39">Returning values in arguments</A></LI>
45062 <LI><A href="#Tcl_nn40">Useful functions</A></LI>
45063 <LI><A href="#Tcl_nn41">Standard typemaps</A></LI>
45064 <LI><A href="#Tcl_nn42">Pointer handling</A></LI>
45065 </UL>
45066 </LI>
45067 <LI><A href="#Tcl_nn43">Turning a SWIG module into a Tcl Package.</A></LI>
45068 <LI><A href="#Tcl_nn44">Building new kinds of Tcl interfaces (in Tcl)</A>
45069 <UL>
45070 <LI><A href="#Tcl_nn45">Proxy classes</A></LI>
45071 </UL>
45072 </LI>
45073 <LI><A href="#Tcl_nn46">Tcl/Tk Stubs</A></LI>
45074 </UL>
45075 </DIV>
45076 <!-- INDEX -->
45077 <P><B> Caution: This chapter is under repair!</B></P>
45078 <P> This chapter discusses SWIG's support of Tcl. SWIG currently
45079  requires Tcl 8.0 or a later release. Earlier releases of SWIG supported
45080  Tcl 7.x, but this is no longer supported.</P>
45081 <H2><A name="Tcl_nn2"></A>33.1 Preliminaries</H2>
45082 <P> To build a Tcl module, run SWIG using the <TT>-tcl</TT> option :</P>
45083 <DIV class="code">
45084 <PRE>
45085 $ swig -tcl example.i
45086 </PRE>
45087 </DIV>
45088 <P> If building a C++ extension, add the <TT>-c++</TT> option:</P>
45089 <DIV class="code">
45090 <PRE>
45091 $ swig -c++ -tcl example.i
45092 </PRE>
45093 </DIV>
45094 <P> This creates a file <TT>example_wrap.c</TT> or <TT>example_wrap.cxx</TT>
45095  that contains all of the code needed to build a Tcl extension module.
45096  To finish building the module, you need to compile this file and link
45097  it with the rest of your program.</P>
45098 <H3><A name="Tcl_nn3"></A>33.1.1 Getting the right header files</H3>
45099 <P> In order to compile the wrapper code, the compiler needs the <TT>
45100 tcl.h</TT> header file. This file is usually contained in the directory</P>
45101 <DIV class="code">
45102 <PRE>
45103 /usr/local/include
45104 </PRE>
45105 </DIV>
45106 <P> Be aware that some Tcl versions install this header file with a
45107  version number attached to it. If this is the case, you should probably
45108  make a symbolic link so that <TT>tcl.h</TT> points to the correct
45109  header file.</P>
45110 <H3><A name="Tcl_nn4"></A>33.1.2 Compiling a dynamic module</H3>
45111 <P> The preferred approach to building an extension module is to compile
45112  it into a shared object file or DLL. To do this, you will need to
45113  compile your program using commands like this (shown for Linux):</P>
45114 <DIV class="code">
45115 <PRE>
45116 $ swig -tcl example.i
45117 $ gcc -c example.c
45118 $ gcc -c example_wrap.c -I/usr/local/include
45119 $ gcc -shared example.o example_wrap.o -o example.so
45120 </PRE>
45121 </DIV>
45122 <P> The exact commands for doing this vary from platform to platform.
45123  SWIG tries to guess the right options when it is installed. Therefore,
45124  you may want to start with one of the examples in the <TT>
45125 SWIG/Examples/tcl</TT> directory. If that doesn't work, you will need to
45126  read the man-pages for your compiler and linker to get the right set of
45127  options. You might also check the <A href="http://www.dabeaz.com/cgi-bin/wiki.pl">
45128 SWIG Wiki</A> for additional information.</P>
45129 <P> When linking the module, the name of the output file has to match
45130  the name of the module. If the name of your SWIG module is &quot;<TT>example</TT>
45131 &quot;, the name of the corresponding object file should be &quot;<TT>example.so</TT>
45132 &quot;. The name of the module is specified using the <TT>%module</TT>
45133  directive or the <TT>-module</TT> command line option.</P>
45134 <H3><A name="Tcl_nn5"></A>33.1.3 Static linking</H3>
45135 <P> An alternative approach to dynamic linking is to rebuild the Tcl
45136  interpreter with your extension module added to it. In the past, this
45137  approach was sometimes necessary due to limitations in dynamic loading
45138  support on certain machines. However, the situation has improved
45139  greatly over the last few years and you should not consider this
45140  approach unless there is really no other option.</P>
45141 <P> The usual procedure for adding a new module to Tcl involves writing
45142  a special function <TT>Tcl_AppInit()</TT> and using it to initialize
45143  the interpreter and your module. With SWIG, the <TT>tclsh.i</TT> and <TT>
45144 wish.i</TT> library files can be used to rebuild the <TT>tclsh</TT> and <TT>
45145 wish</TT> interpreters respectively. For example:</P>
45146 <DIV class="code">
45147 <PRE>
45148 %module example
45149
45150 %inline %{
45151 extern int fact(int);
45152 extern int mod(int, int);
45153 extern double My_variable;
45154 %}
45155
45156 %include &quot;tclsh.i&quot;       // Include code for rebuilding tclsh
45157
45158 </PRE>
45159 </DIV>
45160 <P> The <TT>tclsh.i</TT> library file includes supporting code that
45161  contains everything needed to rebuild tclsh. To rebuild the
45162  interpreter, you simply do something like this:</P>
45163 <DIV class="code">
45164 <PRE>
45165 $ swig -tcl example.i
45166 $ gcc example.c example_wrap.c \
45167         -Xlinker -export-dynamic \
45168         -DHAVE_CONFIG_H -I/usr/local/include/ \
45169         -L/usr/local/lib -ltcl -lm -ldl \
45170         -o mytclsh
45171
45172 </PRE>
45173 </DIV>
45174 <P> You will need to supply the same libraries that were used to build
45175  Tcl the first time. This may include system libraries such as <TT>
45176 -lsocket</TT>, <TT>-lnsl</TT>, and <TT>-lpthread</TT>. If this actually
45177  works, the new version of Tcl should be identical to the default
45178  version except that your extension module will be a built-in part of
45179  the interpreter.</P>
45180 <P><B> Comment:</B> In practice, you should probably try to avoid static
45181  linking if possible. Some programmers may be inclined to use static
45182  linking in the interest of getting better performance. However, the
45183  performance gained by static linking tends to be rather minimal in most
45184  situations (and quite frankly not worth the extra hassle in the opinion
45185  of this author).</P>
45186 <H3><A name="Tcl_nn6"></A>33.1.4 Using your module</H3>
45187 <P> To use your module, simply use the Tcl <TT>load</TT> command. If all
45188  goes well, you will be able to this:</P>
45189 <DIV class="code">
45190 <PRE>
45191 $ tclsh
45192 % load ./example.so
45193 % fact 4
45194 24
45195 %
45196 </PRE>
45197 </DIV>
45198 <P> A common error received by first-time users is the following:</P>
45199 <DIV class="code">
45200 <PRE>
45201 % load ./example.so
45202 couldn't find procedure Example_Init
45203
45204 </PRE>
45205 </DIV>
45206 <P> This error is almost always caused when the name of the shared
45207  object file doesn't match the name of the module supplied using the
45208  SWIG <TT>%module</TT> directive. Double-check the interface to make
45209  sure the module name and the shared object file match. Another possible
45210  cause of this error is forgetting to link the SWIG-generated wrapper
45211  code with the rest of your application when creating the extension
45212  module.</P>
45213 <P> Another common error is something similar to the following:</P>
45214 <DIV class="code">
45215 <PRE>
45216 % load ./example.so
45217 couldn't load file &quot;./example.so&quot;: ./example.so: undefined symbol: fact
45218
45219 </PRE>
45220 </DIV>
45221 <P> This error usually indicates that you forgot to include some object
45222  files or libraries in the linking of the shared library file. Make sure
45223  you compile both the SWIG wrapper file and your original program into a
45224  shared library file. Make sure you pass all of the required libraries
45225  to the linker.</P>
45226 <P> Sometimes unresolved symbols occur because a wrapper has been
45227  created for a function that doesn't actually exist in a library. This
45228  usually occurs when a header file includes a declaration for a function
45229  that was never actually implemented or it was removed from a library
45230  without updating the header file. To fix this, you can either edit the
45231  SWIG input file to remove the offending declaration or you can use the <TT>
45232 %ignore</TT> directive to ignore the declaration.</P>
45233 <P> Finally, suppose that your extension module is linked with another
45234  library like this:</P>
45235 <DIV class="code">
45236 <PRE>
45237 $ gcc -shared example.o example_wrap.o -L/home/beazley/projects/lib -lfoo \
45238       -o example.so
45239 </PRE>
45240 </DIV>
45241 <P> If the <TT>foo</TT> library is compiled as a shared library, you
45242  might get the following problem when you try to use your module:</P>
45243 <DIV class="code">
45244 <PRE>
45245 % load ./example.so
45246 couldn't load file &quot;./example.so&quot;: libfoo.so: cannot open shared object file:
45247 No such file or directory
45248 %        
45249 </PRE>
45250 </DIV>
45251 <P> This error is generated because the dynamic linker can't locate the <TT>
45252 libfoo.so</TT> library. When shared libraries are loaded, the system
45253  normally only checks a few standard locations such as <TT>/usr/lib</TT>
45254  and <TT>/usr/local/lib</TT>. To fix this problem, there are several
45255  things you can do. First, you can recompile your extension module with
45256  extra path information. For example, on Linux you can do this:</P>
45257 <DIV class="code">
45258 <PRE>
45259 $ gcc -shared example.o example_wrap.o -L/home/beazley/projects/lib -lfoo \
45260       -Xlinker -rpath /home/beazley/projects/lib \
45261       -o example.so
45262 </PRE>
45263 </DIV>
45264 <P> Alternatively, you can set the <TT>LD_LIBRARY_PATH</TT> environment
45265  variable to include the directory with your shared libraries. If
45266  setting <TT>LD_LIBRARY_PATH</TT>, be aware that setting this variable
45267  can introduce a noticeable performance impact on all other applications
45268  that you run. To set it only for Tcl, you might want to do this
45269  instead:</P>
45270 <DIV class="code">
45271 <PRE>
45272 $ env LD_LIBRARY_PATH=/home/beazley/projects/lib tclsh
45273 </PRE>
45274 </DIV>
45275 <P> Finally, you can use a command such as <TT>ldconfig</TT> to add
45276  additional search paths to the default system configuration (this
45277  requires root access and you will need to read the man pages).</P>
45278 <H3><A name="Tcl_nn7"></A>33.1.5 Compilation of C++ extensions</H3>
45279 <P> Compilation of C++ extensions has traditionally been a tricky
45280  problem. Since the Tcl interpreter is written in C, you need to take
45281  steps to make sure C++ is properly initialized and that modules are
45282  compiled correctly.</P>
45283 <P> On most machines, C++ extension modules should be linked using the
45284  C++ compiler. For example:</P>
45285 <DIV class="code">
45286 <PRE>
45287 % swig -c++ -tcl example.i
45288 % g++ -c example.cxx
45289 % g++ -c example_wrap.cxx -I/usr/local/include
45290 % g++ -shared example.o example_wrap.o -o example.so
45291 </PRE>
45292 </DIV>
45293 <P> In addition to this, you may need to include additional library
45294  files to make it work. For example, if you are using the Sun C++
45295  compiler on Solaris, you often need to add an extra library <TT>-lCrun</TT>
45296  like this:</P>
45297 <DIV class="code">
45298 <PRE>
45299 % swig -c++ -tcl example.i
45300 % CC -c example.cxx
45301 % CC -c example_wrap.cxx -I/usr/local/include
45302 % CC -G example.o example_wrap.o -L/opt/SUNWspro/lib -o example.so -lCrun
45303 </PRE>
45304 </DIV>
45305 <P> Of course, the extra libraries to use are completely
45306  non-portable---you will probably need to do some experimentation.</P>
45307 <P> Sometimes people have suggested that it is necessary to relink the
45308  Tcl interpreter using the C++ compiler to make C++ extension modules
45309  work. In the experience of this author, this has never actually
45310  appeared to be necessary. Relinking the interpreter with C++ really
45311  only includes the special run-time libraries described above---as long
45312  as you link your extension modules with these libraries, it should not
45313  be necessary to rebuild Tcl.</P>
45314 <P> If you aren't entirely sure about the linking of a C++ extension,
45315  you might look at an existing C++ program. On many Unix machines, the <TT>
45316 ldd</TT> command will list library dependencies. This should give you
45317  some clues about what you might have to include when you link your
45318  extension module. For example:</P>
45319 <DIV class="code">
45320 <PRE>
45321 $ ldd swig
45322         libstdc++-libc6.1-1.so.2 =&gt; /usr/lib/libstdc++-libc6.1-1.so.2 (0x40019000)
45323         libm.so.6 =&gt; /lib/libm.so.6 (0x4005b000)
45324         libc.so.6 =&gt; /lib/libc.so.6 (0x40077000)
45325         /lib/ld-linux.so.2 =&gt; /lib/ld-linux.so.2 (0x40000000)
45326 $
45327 </PRE>
45328 </DIV>
45329 <P> As a final complication, a major weakness of C++ is that it does not
45330  define any sort of standard for binary linking of libraries. This means
45331  that C++ code compiled by different compilers will not link together
45332  properly as libraries nor is the memory layout of classes and data
45333  structures implemented in any kind of portable manner. In a monolithic
45334  C++ program, this problem may be unnoticed. However, in Tcl, it is
45335  possible for different extension modules to be compiled with different
45336  C++ compilers. As long as these modules are self-contained, this
45337  probably won't matter. However, if these modules start sharing data,
45338  you will need to take steps to avoid segmentation faults and other
45339  erratic program behavior. If working with lots of software components,
45340  you might want to investigate using a more formal standard such as COM.</P>
45341 <H3><A name="Tcl_nn8"></A>33.1.6 Compiling for 64-bit platforms</H3>
45342 <P> On platforms that support 64-bit applications (Solaris, Irix, etc.),
45343  special care is required when building extension modules. On these
45344  machines, 64-bit applications are compiled and linked using a different
45345  set of compiler/linker options. In addition, it is not generally
45346  possible to mix 32-bit and 64-bit code together in the same
45347  application.</P>
45348 <P> To utilize 64-bits, the Tcl executable will need to be recompiled as
45349  a 64-bit application. In addition, all libraries, wrapper code, and
45350  every other part of your application will need to be compiled for
45351  64-bits. If you plan to use other third-party extension modules, they
45352  will also have to be recompiled as 64-bit extensions.</P>
45353 <P> If you are wrapping commercial software for which you have no source
45354  code, you will be forced to use the same linking standard as used by
45355  that software. This may prevent the use of 64-bit extensions. It may
45356  also introduce problems on platforms that support more than one linking
45357  standard (e.g., -o32 and -n32 on Irix).</P>
45358 <H3><A name="Tcl_nn9"></A>33.1.7 Setting a package prefix</H3>
45359 <P> To avoid namespace problems, you can instruct SWIG to append a
45360  package prefix to all of your functions and variables. This is done
45361  using the -prefix option as follows :</P>
45362 <DIV class="code">
45363 <PRE>
45364 swig -tcl -prefix Foo example.i
45365 </PRE>
45366 </DIV>
45367 <P> If you have a function &quot;<TT>bar</TT>&quot; in the SWIG file, the prefix
45368  option will append the prefix to the name when creating a command and
45369  call it &quot;<TT>Foo_bar</TT>&quot;.</P>
45370 <H3><A name="Tcl_nn10"></A>33.1.8 Using namespaces</H3>
45371 <P> Alternatively, you can have SWIG install your module into a Tcl
45372  namespace by specifying the <TT>-namespace</TT> option :</P>
45373 <DIV class="code">
45374 <PRE>
45375 swig -tcl -namespace example.i
45376 </PRE>
45377 </DIV>
45378 <P> By default, the name of the namespace will be the same as the module
45379  name, but you can override it using the <TT>-prefix</TT> option.</P>
45380 <P> When the <TT>-namespace</TT> option is used, objects in the module
45381  are always accessed with the namespace name such as <TT>Foo::bar</TT>.</P>
45382 <H2><A name="Tcl_nn11"></A>33.2 Building Tcl/Tk Extensions under Windows
45383  95/NT</H2>
45384 <P> Building a SWIG extension to Tcl/Tk under Windows 95/NT is roughly
45385  similar to the process used with Unix. Normally, you will want to
45386  produce a DLL that can be loaded into tclsh or wish. This section
45387  covers the process of using SWIG with Microsoft Visual C++. although
45388  the procedure may be similar with other compilers.</P>
45389 <H3><A name="Tcl_nn12"></A>33.2.1 Running SWIG from Developer Studio</H3>
45390 <P> If you are developing your application within Microsoft developer
45391  studio, SWIG can be invoked as a custom build option. The process
45392  roughly follows these steps :</P>
45393 <UL>
45394 <LI>Open up a new workspace and use the AppWizard to select a DLL
45395  project.</LI>
45396 <LI>Add both the SWIG interface file (the .i file), any supporting C
45397  files, and the name of the wrapper file that will be created by SWIG
45398  (ie. <TT>example_wrap.c</TT>). Note : If using C++, choose a different
45399  suffix for the wrapper file such as <TT>example_wrap.cxx</TT>. Don't
45400  worry if the wrapper file doesn't exist yet--Developer studio will keep
45401  a reference to it around.</LI>
45402 <LI>Select the SWIG interface file and go to the settings menu. Under
45403  settings, select the &quot;Custom Build&quot; option.</LI>
45404 <LI>Enter &quot;SWIG&quot; in the description field.</LI>
45405 <LI>Enter &quot;<TT>swig -tcl -o $(ProjDir)\$(InputName)_wrap.c $(InputPath)</TT>
45406 &quot; in the &quot;Build command(s) field&quot;</LI>
45407 <LI>Enter &quot;<TT>$(ProjDir)\$(InputName)_wrap.c</TT>&quot; in the &quot;Output
45408  files(s) field&quot;.</LI>
45409 <LI>Next, select the settings for the entire project and go to
45410  &quot;C++:Preprocessor&quot;. Add the include directories for your Tcl
45411  installation under &quot;Additional include directories&quot;.</LI>
45412 <LI>Finally, select the settings for the entire project and go to &quot;Link
45413  Options&quot;. Add the Tcl library file to your link libraries. For example
45414  &quot;<TT>tcl80.lib</TT>&quot;. Also, set the name of the output file to match
45415  the name of your Tcl module (ie. example.dll).</LI>
45416 <LI>Build your project.</LI>
45417 </UL>
45418 <P> Now, assuming all went well, SWIG will be automatically invoked when
45419  you build your project. Any changes made to the interface file will
45420  result in SWIG being automatically invoked to produce a new version of
45421  the wrapper file. To run your new Tcl extension, simply run <TT>tclsh</TT>
45422  or <TT>wish</TT> and use the <TT>load</TT> command. For example :</P>
45423 <DIV class="code">
45424 <PRE>
45425 MSDOS &gt; tclsh80
45426 % load example.dll
45427 % fact 4
45428 24
45429 %
45430 </PRE>
45431 </DIV>
45432 <H3><A name="Tcl_nn13"></A>33.2.2 Using NMAKE</H3>
45433 <P> Alternatively, SWIG extensions can be built by writing a Makefile
45434  for NMAKE. To do this, make sure the environment variables for MSVC++
45435  are available and the MSVC++ tools are in your path. Now, just write a
45436  short Makefile like this :</P>
45437 <DIV class="code">
45438 <PRE>
45439 # Makefile for building various SWIG generated extensions
45440
45441 SRCS          = example.c
45442 IFILE         = example
45443 INTERFACE     = $(IFILE).i
45444 WRAPFILE      = $(IFILE)_wrap.c
45445
45446 # Location of the Visual C++ tools (32 bit assumed)
45447
45448 TOOLS         = c:\msdev
45449 TARGET        = example.dll
45450 CC            = $(TOOLS)\bin\cl.exe
45451 LINK          = $(TOOLS)\bin\link.exe
45452 INCLUDE32     = -I$(TOOLS)\include
45453 MACHINE       = IX86
45454
45455 # C Library needed to build a DLL
45456
45457 DLLIBC        = msvcrt.lib oldnames.lib  
45458
45459 # Windows libraries that are apparently needed
45460 WINLIB        = kernel32.lib advapi32.lib user32.lib gdi32.lib comdlg32.lib 
45461 winspool.lib
45462
45463 # Libraries common to all DLLs
45464 LIBS          = $(DLLIBC) $(WINLIB) 
45465
45466 # Linker options
45467 LOPT      = -debug:full -debugtype:cv /NODEFAULTLIB /RELEASE /NOLOGO /
45468 MACHINE:$(MACHINE) -entry:_DllMainCRTStartup@12 -dll
45469
45470 # C compiler flags
45471
45472 CFLAGS    = /Z7 /Od /c /nologo
45473 TCL_INCLUDES  = -Id:\tcl8.0a2\generic -Id:\tcl8.0a2\win
45474 TCLLIB        = d:\tcl8.0a2\win\tcl80.lib
45475
45476 tcl::
45477         ..\..\swig -tcl -o $(WRAPFILE) $(INTERFACE)
45478         $(CC) $(CFLAGS) $(TCL_INCLUDES) $(SRCS) $(WRAPFILE)
45479         set LIB=$(TOOLS)\lib
45480         $(LINK) $(LOPT) -out:example.dll $(LIBS) $(TCLLIB) example.obj example_wrap.obj
45481
45482 </PRE>
45483 </DIV>
45484 <P> To build the extension, run NMAKE (you may need to run vcvars32
45485  first). This is a pretty minimal Makefile, but hopefully its enough to
45486  get you started. With a little practice, you'll be making lots of Tcl
45487  extensions.</P>
45488 <H2><A name="Tcl_nn14"></A>33.3 A tour of basic C/C++ wrapping</H2>
45489 <P> By default, SWIG tries to build a very natural Tcl interface to your
45490  C/C++ code. Functions are wrapped as functions, classes are wrapped in
45491  an interface that mimics the style of Tk widgets and [incr Tcl]
45492  classes. This section briefly covers the essential aspects of this
45493  wrapping.</P>
45494 <H3><A name="Tcl_nn15"></A>33.3.1 Modules</H3>
45495 <P> The SWIG <TT>%module</TT> directive specifies the name of the Tcl
45496  module. If you specify `<TT>%module example</TT>', then everything is
45497  compiled into an extension module <TT>example.so</TT>. When choosing a
45498  module name, make sure you don't use the same name as a built-in Tcl
45499  command.</P>
45500 <P> One pitfall to watch out for is module names involving numbers. If
45501  you specify a module name like <TT>%module md5</TT>, you'll find that
45502  the load command no longer seems to work:</P>
45503 <DIV class="code">
45504 <PRE>
45505 % load ./md5.so
45506 couldn't find procedure Md_Init
45507 </PRE>
45508 </DIV>
45509 <P> To fix this, supply an extra argument to <TT>load</TT> like this:</P>
45510 <DIV class="code">
45511 <PRE>
45512 % load ./md5.so md5
45513 </PRE>
45514 </DIV>
45515 <H3><A name="Tcl_nn16"></A>33.3.2 Functions</H3>
45516 <P> Global functions are wrapped as new Tcl built-in commands. For
45517  example,</P>
45518 <DIV class="code">
45519 <PRE>
45520 %module example
45521 int fact(int n);
45522 </PRE>
45523 </DIV>
45524 <P> creates a built-in function <TT>fact</TT> that works exactly like
45525  you think it does:</P>
45526 <DIV class="code">
45527 <PRE>
45528 % load ./example.so
45529 % fact 4
45530 24
45531 % set x [fact 6]
45532 %
45533 </PRE>
45534 </DIV>
45535 <H3><A name="Tcl_nn17"></A>33.3.3 Global variables</H3>
45536 <P> C/C++ global variables are wrapped by Tcl global variables. For
45537  example:</P>
45538 <DIV class="code">
45539 <PRE>
45540 // SWIG interface file with global variables
45541 %module example
45542 ...
45543 %inline %{
45544 extern double density;
45545 %}
45546 ...
45547 </PRE>
45548 </DIV>
45549 <P> Now look at the Tcl interface:</P>
45550 <DIV class="code">
45551 <PRE>
45552 % puts $density          # Output value of C global variable
45553 1.0
45554 % set density 0.95       # Change value
45555 </PRE>
45556 </DIV>
45557 <P> If you make an error in variable assignment, you will get an error
45558  message. For example:</P>
45559 <DIV class="code">
45560 <PRE>
45561 % set density &quot;hello&quot;
45562 can't set &quot;density&quot;: Type error. expected a double.
45563 %
45564 </PRE>
45565 </DIV>
45566 <P> If a variable is declared as <TT>const</TT>, it is wrapped as a
45567  read-only variable. Attempts to modify its value will result in an
45568  error.</P>
45569 <P> To make ordinary variables read-only, you can use the <TT>%immutable</TT>
45570  directive. For example:</P>
45571 <DIV class="code">
45572 <PRE>
45573 %{
45574 extern char *path;
45575 %}
45576 %immutable;
45577 extern char *path;
45578 %mutable;
45579 </PRE>
45580 </DIV>
45581 <P> The <TT>%immutable</TT> directive stays in effect until it is
45582  explicitly disabled or cleared using <TT>%mutable</TT>. See the <A href="#SWIG_readonly_variables">
45583 Creating read-only variables</A> section for further details.</P>
45584 <P> If you just want to make a specific variable immutable, supply a
45585  declaration name. For example:</P>
45586 <DIV class="code">
45587 <PRE>
45588 %{
45589 extern char *path;
45590 %}
45591 %immutable path;
45592 ...
45593 extern char *path;      // Read-only (due to %immutable)
45594 </PRE>
45595 </DIV>
45596 <H3><A name="Tcl_nn18"></A>33.3.4 Constants and enums</H3>
45597 <P> C/C++ constants are installed as global Tcl variables containing the
45598  appropriate value. To create a constant, use <TT>#define</TT>, <TT>enum</TT>
45599 , or the <TT>%constant</TT> directive. For example:</P>
45600 <DIV class="code">
45601 <PRE>
45602 #define PI 3.14159
45603 #define VERSION &quot;1.0&quot;
45604
45605 enum Beverage { ALE, LAGER, STOUT, PILSNER };
45606
45607 %constant int FOO = 42;
45608 %constant const char *path = &quot;/usr/local&quot;;
45609 </PRE>
45610 </DIV>
45611 <P> For enums, make sure that the definition of the enumeration actually
45612  appears in a header file or in the wrapper file somehow---if you just
45613  stick an enum in a SWIG interface without also telling the C compiler
45614  about it, the wrapper code won't compile.</P>
45615 <P> Note: declarations declared as <TT>const</TT> are wrapped as
45616  read-only variables and will be accessed using the <TT>cvar</TT> object
45617  described in the previous section. They are not wrapped as constants.
45618  For further discussion about this, see the <A href="#SWIG">SWIG Basics</A>
45619  chapter.</P>
45620 <P> Constants are not guaranteed to remain constant in Tcl---the value
45621  of the constant could be accidentally reassigned.You will just have to
45622  be careful.</P>
45623 <P> A peculiarity of installing constants as variables is that it is
45624  necessary to use the Tcl <TT>global</TT> statement to access constants
45625  in procedure bodies. For example:</P>
45626 <DIV class="code">
45627 <PRE>
45628 proc blah {} {
45629    global FOO
45630    bar $FOO
45631 }
45632 </PRE>
45633 </DIV>
45634 <P> If a program relies on a lot of constants, this can be extremely
45635  annoying. To fix the problem, consider using the following typemap
45636  rule:</P>
45637 <DIV class="code">
45638 <PRE>
45639 %apply int CONSTANT { int x };
45640 #define FOO 42
45641 ...
45642 void bar(int x);
45643 </PRE>
45644 </DIV>
45645 <P> When applied to an input argument, the <TT>CONSTANT</TT> rule allows
45646  a constant to be passed to a function using its actual value or a
45647  symbolic identifier name. For example:</P>
45648 <DIV class="code">
45649 <PRE>
45650 proc blah {} {
45651    bar FOO
45652 }
45653 </PRE>
45654 </DIV>
45655 <P> When an identifier name is given, it is used to perform an implicit
45656  hash-table lookup of the value during argument conversion. This allows
45657  the <TT>global</TT> statement to be omitted.</P>
45658 <H3><A name="Tcl_nn19"></A>33.3.5 Pointers</H3>
45659 <P> C/C++ pointers are fully supported by SWIG. Furthermore, SWIG has no
45660  problem working with incomplete type information. Here is a rather
45661  simple interface:</P>
45662 <DIV class="code">
45663 <PRE>
45664 %module example
45665
45666 FILE *fopen(const char *filename, const char *mode);
45667 int fputs(const char *, FILE *);
45668 int fclose(FILE *);
45669 </PRE>
45670 </DIV>
45671 <P> When wrapped, you will be able to use the functions in a natural way
45672  from Tcl. For example:</P>
45673 <DIV class="code">
45674 <PRE>
45675 % load ./example.so
45676 % set f [fopen junk w]
45677 % fputs &quot;Hello World\n&quot; $f
45678 % fclose $f
45679 </PRE>
45680 </DIV>
45681 <P> If this makes you uneasy, rest assured that there is no deep magic
45682  involved. Underneath the covers, pointers to C/C++ objects are simply
45683  represented as opaque values--normally an encoded character string like
45684  this:</P>
45685 <DIV class="code">
45686 <PRE>
45687 % puts $f
45688 _c0671108_p_FILE
45689
45690 </PRE>
45691 </DIV>
45692 <P> This pointer value can be freely passed around to different C
45693  functions that expect to receive an object of type <TT>FILE *</TT>. The
45694  only thing you can't do is dereference the pointer from Tcl.</P>
45695 <P> The NULL pointer is represented by the string <TT>NULL</TT>.</P>
45696 <P> As much as you might be inclined to modify a pointer value directly
45697  from Tcl, don't. The hexadecimal encoding is not necessarily the same
45698  as the logical memory address of the underlying object. Instead it is
45699  the raw byte encoding of the pointer value. The encoding will vary
45700  depending on the native byte-ordering of the platform (i.e., big-endian
45701  vs. little-endian). Similarly, don't try to manually cast a pointer to
45702  a new type by simply replacing the type-string. This may not work like
45703  you expect and it is particularly dangerous when casting C++ objects.
45704  If you need to cast a pointer or change its value, consider writing
45705  some helper functions instead. For example:</P>
45706 <DIV class="code">
45707 <PRE>
45708 %inline %{
45709 /* C-style cast */
45710 Bar *FooToBar(Foo *f) {
45711    return (Bar *) f;
45712 }
45713
45714 /* C++-style cast */
45715 Foo *BarToFoo(Bar *b) {
45716    return dynamic_cast&lt;Foo*&gt;(b);
45717 }
45718
45719 Foo *IncrFoo(Foo *f, int i) {
45720     return f+i;
45721 }
45722 %}
45723 </PRE>
45724 </DIV>
45725 <P> Also, if working with C++, you should always try to use the new C++
45726  style casts. For example, in the above code, the C-style cast may
45727  return a bogus result whereas as the C++-style cast will return <TT>
45728 None</TT> if the conversion can't be performed.</P>
45729 <H3><A name="Tcl_nn20"></A>33.3.6 Structures</H3>
45730 <P> If you wrap a C structure, it is wrapped by a Tcl interface that
45731  somewhat resembles a Tk widget. This provides a very natural interface.
45732  For example,</P>
45733 <DIV class="code">
45734 <PRE>
45735 struct Vector {
45736         double x,y,z;
45737 };
45738
45739 </PRE>
45740 </DIV>
45741 <P> is used as follows:</P>
45742 <DIV class="code">
45743 <PRE>
45744 % Vector v
45745 % v configure -x 3.5 -y 7.2
45746 % puts &quot;[v cget -x] [v cget -y] [v cget -z]&quot;
45747 3.5 7.2 0.0
45748
45749 </PRE>
45750 </DIV>
45751 <P> Similar access is provided for unions and the data members of C++
45752  classes.</P>
45753 <P> In the above example, <TT>v</TT> is a name that's used for the
45754  object. However, underneath the covers, there's a pointer to a raw C
45755  structure. This can be obtained by looking at the <TT>-this</TT>
45756  attribute. For example:</P>
45757 <DIV class="code">
45758 <PRE>
45759 % puts [v cget -this]
45760 _88e31408_p_Vector
45761 </PRE>
45762 </DIV>
45763 <P> Further details about the relationship between the Tcl and the
45764  underlying C structure are covered a little later.</P>
45765 <P> <TT>const</TT> members of a structure are read-only. Data members
45766  can also be forced to be read-only using the <TT>%immutable</TT>
45767  directive. For example:</P>
45768 <DIV class="code">
45769 <PRE>
45770 struct Foo {
45771    ...
45772    %immutable;
45773    int x;        /* Read-only members */
45774    char *name;
45775    %mutable;
45776    ...
45777 };
45778 </PRE>
45779 </DIV>
45780 <P> When <TT>char *</TT> members of a structure are wrapped, the
45781  contents are assumed to be dynamically allocated using <TT>malloc</TT>
45782  or <TT>new</TT> (depending on whether or not SWIG is run with the -c++
45783  option). When the structure member is set, the old contents will be
45784  released and a new value created. If this is not the behavior you want,
45785  you will have to use a typemap (described later).</P>
45786 <P> If a structure contains arrays, access to those arrays is managed
45787  through pointers. For example, consider this:</P>
45788 <DIV class="code">
45789 <PRE>
45790 struct Bar {
45791     int  x[16];
45792 };
45793 </PRE>
45794 </DIV>
45795 <P> If accessed in Tcl, you will see behavior like this:</P>
45796 <DIV class="code">
45797 <PRE>
45798 % Bar b
45799 % puts [b cget -x]
45800 _801861a4_p_int
45801
45802 </PRE>
45803 </DIV>
45804 <P> This pointer can be passed around to functions that expect to
45805  receive an <TT>int *</TT> (just like C). You can also set the value of
45806  an array member using another pointer. For example:</P>
45807 <DIV class="code">
45808 <PRE>
45809 % Bar c
45810 % c configure -x [b cget -x]   # Copy contents of b.x to c.x
45811 </PRE>
45812 </DIV>
45813 <P> For array assignment, SWIG copies the entire contents of the array
45814  starting with the data pointed to by <TT>b.x</TT>. In this example, 16
45815  integers would be copied. Like C, SWIG makes no assumptions about
45816  bounds checking---if you pass a bad pointer, you may get a segmentation
45817  fault or access violation.</P>
45818 <P> When a member of a structure is itself a structure, it is handled as
45819  a pointer. For example, suppose you have two structures like this:</P>
45820 <DIV class="code">
45821 <PRE>
45822 struct Foo {
45823    int a;
45824 };
45825
45826 struct Bar {
45827    Foo f;
45828 };
45829 </PRE>
45830 </DIV>
45831 <P> Now, suppose that you access the <TT>f</TT> attribute of <TT>Bar</TT>
45832  like this:</P>
45833 <DIV class="code">
45834 <PRE>
45835 % Bar b
45836 % set x [b cget -f]
45837 </PRE>
45838 </DIV>
45839 <P> In this case, <TT>x</TT> is a pointer that points to the <TT>Foo</TT>
45840  that is inside <TT>b</TT>. This is the same value as generated by this
45841  C code:</P>
45842 <DIV class="code">
45843 <PRE>
45844 Bar b;
45845 Foo *x = &amp;b-&gt;f;       /* Points inside b */
45846 </PRE>
45847 </DIV>
45848 <P> However, one peculiarity of accessing a substructure like this is
45849  that the returned value does work quite like you might expect. For
45850  example:</P>
45851 <DIV class="code">
45852 <PRE>
45853 % Bar b
45854 % set x [b cget -f]
45855 % x cget -a
45856 invalid command name &quot;x&quot;
45857 </PRE>
45858 </DIV>
45859 <P> This is because the returned value was not created in a normal way
45860  from the interpreter (x is not a command object). To make it function
45861  normally, just evaluate the variable like this:</P>
45862 <DIV class="code">
45863 <PRE>
45864 % Bar b
45865 % set x [b cget -f]
45866 % $x cget -a
45867 0
45868 %
45869 </PRE>
45870 </DIV>
45871 <P> In this example, <TT>x</TT> points inside the original structure.
45872  This means that modifications work just like you would expect. For
45873  example:</P>
45874 <DIV class="code">
45875 <PRE>
45876
45877 % Bar b
45878 % set x [b cget -f]
45879 % $x configure -a 3            # Modifies contents of f (inside b)
45880 % [b cget -f] -configure -a 3  # Same thing
45881 </PRE>
45882 </DIV>
45883 <P> In many of these structure examples, a simple name like &quot;v&quot; or &quot;b&quot;
45884  has been given to wrapped structures. If necessary, this name can be
45885  passed to functions that expect to receive an object. For example, if
45886  you have a function like this,</P>
45887 <DIV class="code">
45888 <PRE>
45889 void blah(Foo *f);
45890 </PRE>
45891 </DIV>
45892 <P> you can call the function in Tcl as follows:</P>
45893 <DIV class="code">
45894 <PRE>
45895 % Foo x            # Create a Foo object 
45896 % blah x           # Pass the object to a function
45897 </PRE>
45898 </DIV>
45899 <P> It is also possible to call the function using the raw pointer
45900  value. For instance:</P>
45901 <DIV class="code">
45902 <PRE>
45903 % blah [x cget -this]   # Pass object to a function
45904 </PRE>
45905 </DIV>
45906 <P> It is also possible to create and use objects using variables. For
45907  example:</P>
45908 <DIV class="code">
45909 <PRE>
45910 % set b [Bar]            # Create a Bar
45911 % $b cget -f             # Member access
45912 % puts $b
45913 _108fea88_p_Bar
45914 %
45915 </PRE>
45916 </DIV>
45917 <P> Finally, to destroy objects created from Tcl, you can either let the
45918  object name go out of scope or you can explicitly delete the object.
45919  For example:</P>
45920 <DIV class="code">
45921 <PRE>
45922 % Foo f                 # Create object f
45923 % rename f &quot;&quot;
45924 </PRE>
45925 </DIV>
45926 <P> or</P>
45927 <DIV class="code">
45928 <PRE>
45929 % Foo f                 # Create object f
45930 % f -delete
45931 </PRE>
45932 </DIV>
45933 <P> Note: Tcl only destroys the underlying object if it has ownership.
45934  See the memory management section that appears shortly.</P>
45935 <H3><A name="Tcl_nn21"></A>33.3.7 C++ classes</H3>
45936 <P> C++ classes are wrapped as an extension of structure wrapping. For
45937  example, if you have this class,</P>
45938 <DIV class="code">
45939 <PRE>
45940 class List {
45941 public:
45942   List();
45943   ~List();
45944   int  search(char *item);
45945   void insert(char *item);
45946   void remove(char *item);
45947   char *get(int n);
45948   int  length;
45949 };
45950 </PRE>
45951 </DIV>
45952 <P> you can use it in Tcl like this:</P>
45953 <DIV class="code">
45954 <PRE>
45955 % List x
45956 % x insert Ale
45957 % x insert Stout
45958 % x insert Lager
45959 % x get 1
45960 Stout
45961 % puts [l cget -length]
45962 3
45963 %
45964 </PRE>
45965 </DIV>
45966 <P> Class data members are accessed in the same manner as C structures.</P>
45967 <P> Static class members are accessed as global functions or variables.
45968  To illustrate, suppose you have a class like this:</P>
45969 <DIV class="code">
45970 <PRE>
45971 class Spam {
45972 public:
45973    static void foo();
45974    static int bar;
45975
45976 };
45977 </PRE>
45978 </DIV>
45979 <P> In Tcl, the static member is accessed as follows:</P>
45980 <DIV class="code">
45981 <PRE>
45982 % Spam_foo        # Spam::foo()
45983 % puts $Spam_bar  # Spam::bar
45984 </PRE>
45985 </DIV>
45986 <H3><A name="Tcl_nn22"></A>33.3.8 C++ inheritance</H3>
45987 <P> SWIG is fully aware of issues related to C++ inheritance. Therefore,
45988  if you have classes like this</P>
45989 <DIV class="code">
45990 <PRE>
45991 class Foo {
45992 ...
45993 };
45994
45995 class Bar : public Foo {
45996 ...
45997 };
45998 </PRE>
45999 </DIV>
46000 <P> An object of type <TT>Bar</TT> can be used where a <TT>Foo</TT> is
46001  expected. For example, if you have this function:</P>
46002 <DIV class="code">
46003 <PRE>
46004 void spam(Foo *f);
46005 </PRE>
46006 </DIV>
46007 <P> then the function <TT>spam()</TT> accepts a <TT>Foo *</TT> or a
46008  pointer to any class derived from <TT>Foo</TT>. For instance:</P>
46009 <DIV class="code">
46010 <PRE>
46011 % Foo f      # Create a Foo
46012 % Bar b      # Create a Bar
46013 % spam f     # OK
46014 % spam b     # OK
46015 </PRE>
46016 </DIV>
46017 <P> It is safe to use multiple inheritance with SWIG.</P>
46018 <H3><A name="Tcl_nn23"></A>33.3.9 Pointers, references, values, and
46019  arrays</H3>
46020 <P> In C++, there are many different ways a function might receive and
46021  manipulate objects. For example:</P>
46022 <DIV class="code">
46023 <PRE>
46024 void spam1(Foo *x);      // Pass by pointer
46025 void spam2(Foo &amp;x);      // Pass by reference
46026 void spam3(Foo x);       // Pass by value
46027 void spam4(Foo x[]);     // Array of objects
46028 </PRE>
46029 </DIV>
46030 <P> In Tcl, there is no detailed distinction like this. Because of this,
46031  SWIG unifies all of these types together in the wrapper code. For
46032  instance, if you actually had the above functions, it is perfectly
46033  legal to do this:</P>
46034 <DIV class="code">
46035 <PRE>
46036 % Foo f             # Create a Foo
46037 % spam1 f           # Ok. Pointer
46038 % spam2 f           # Ok. Reference
46039 % spam3 f           # Ok. Value.
46040 % spam4 f           # Ok. Array (1 element)
46041 </PRE>
46042 </DIV>
46043 <P> Similar behavior occurs for return values. For example, if you had
46044  functions like this,</P>
46045 <DIV class="code">
46046 <PRE>
46047 Foo *spam5();
46048 Foo &amp;spam6();
46049 Foo  spam7();
46050 </PRE>
46051 </DIV>
46052 <P> then all three functions will return a pointer to some <TT>Foo</TT>
46053  object. Since the third function (spam7) returns a value, newly
46054  allocated memory is used to hold the result and a pointer is returned
46055  (Tcl will release this memory when the return value is garbage
46056  collected).</P>
46057 <H3><A name="Tcl_nn24"></A>33.3.10 C++ overloaded functions</H3>
46058 <P> C++ overloaded functions, methods, and constructors are mostly
46059  supported by SWIG. For example, if you have two functions like this:</P>
46060 <DIV class="code">
46061 <PRE>
46062 void foo(int);
46063 void foo(char *c);
46064 </PRE>
46065 </DIV>
46066 <P> You can use them in Tcl in a straightforward manner:</P>
46067 <DIV class="code">
46068 <PRE>
46069 % foo 3            # foo(int)
46070 % foo Hello        # foo(char *c)
46071 </PRE>
46072 </DIV>
46073 <P> Similarly, if you have a class like this,</P>
46074 <DIV class="code">
46075 <PRE>
46076 class Foo {
46077 public:
46078     Foo();
46079     Foo(const Foo &amp;);
46080     ...
46081 };
46082 </PRE>
46083 </DIV>
46084 <P> you can write Tcl code like this:</P>
46085 <DIV class="code">
46086 <PRE>
46087 % Foo f                # Create a Foo
46088 % Foo g f              # Copy f
46089 </PRE>
46090 </DIV>
46091 <P> Overloading support is not quite as flexible as in C++. Sometimes
46092  there are methods that SWIG can't disambiguate. For example:</P>
46093 <DIV class="code">
46094 <PRE>
46095 void spam(int);
46096 void spam(short);
46097 </PRE>
46098 </DIV>
46099 <P> or</P>
46100 <DIV class="code">
46101 <PRE>
46102 void foo(Bar *b);
46103 void foo(Bar &amp;b);
46104 </PRE>
46105 </DIV>
46106 <P> If declarations such as these appear, you will get a warning message
46107  like this:</P>
46108 <DIV class="code">
46109 <PRE>
46110 example.i:12: Warning(509): Overloaded spam(short) is shadowed by spam(int)
46111 at example.i:11.
46112 </PRE>
46113 </DIV>
46114 <P> To fix this, you either need to ignore or rename one of the methods.
46115  For example:</P>
46116 <DIV class="code">
46117 <PRE>
46118 %rename(spam_short) spam(short);
46119 ...
46120 void spam(int);    
46121 void spam(short);   // Accessed as spam_short
46122 </PRE>
46123 </DIV>
46124 <P> or</P>
46125 <DIV class="code">
46126 <PRE>
46127 %ignore spam(short);
46128 ...
46129 void spam(int);    
46130 void spam(short);   // Ignored
46131 </PRE>
46132 </DIV>
46133 <P> SWIG resolves overloaded functions and methods using a
46134  disambiguation scheme that ranks and sorts declarations according to a
46135  set of type-precedence rules. The order in which declarations appear in
46136  the input does not matter except in situations where ambiguity
46137  arises--in this case, the first declaration takes precedence.</P>
46138 <P> Please refer to the &quot;SWIG and C++&quot; chapter for more information
46139  about overloading.</P>
46140 <H3><A name="Tcl_nn25"></A>33.3.11 C++ operators</H3>
46141 <P> Certain C++ overloaded operators can be handled automatically by
46142  SWIG. For example, consider a class like this:</P>
46143 <DIV class="code">
46144 <PRE>
46145 class Complex {
46146 private:
46147   double rpart, ipart;
46148 public:
46149   Complex(double r = 0, double i = 0) : rpart(r), ipart(i) { }
46150   Complex(const Complex &amp;c) : rpart(c.rpart), ipart(c.ipart) { }
46151   Complex &amp;operator=(const Complex &amp;c);
46152   Complex operator+(const Complex &amp;c) const;
46153   Complex operator-(const Complex &amp;c) const;
46154   Complex operator*(const Complex &amp;c) const;
46155   Complex operator-() const;
46156   
46157   double re() const { return rpart; }
46158   double im() const { return ipart; }
46159 };
46160 </PRE>
46161 </DIV>
46162 <P> When wrapped, it works like this:</P>
46163 <DIV class="code">
46164 <PRE>
46165 % Complex c 3 4
46166 % Complex d 7 8
46167 % set e [c + d]
46168 % $e re
46169 10.0
46170 % $e im
46171 12.0
46172 </PRE>
46173 </DIV>
46174 <P> It should be stressed that operators in SWIG have no relationship to
46175  operators in Tcl. In fact, the only thing that's happening here is that
46176  an operator like <TT>operator +</TT> has been renamed to a method <TT>+</TT>
46177 . Therefore, the statement <TT>[c + d]</TT> is really just invoking the <TT>
46178 +</TT> method on <TT>c</TT>. When more than operator is defined (with
46179  different arguments), the standard method overloading facilities are
46180  used. Here is a rather odd looking example:</P>
46181 <DIV class="code">
46182 <PRE>
46183 % Complex c 3 4
46184 % Complex d 7 8
46185 % set e [c - d]       # operator-(const Complex &amp;)
46186 % puts &quot;[$e re] [$e im]&quot;
46187 10.0 12.0
46188 % set f [c -]         # operator-()
46189 % puts &quot;[$f re] [$f im]&quot;
46190 -3.0 -4.0
46191 %
46192 </PRE>
46193 </DIV>
46194 <P> One restriction with operator overloading support is that SWIG is
46195  not able to fully handle operators that aren't defined as part of the
46196  class. For example, if you had code like this</P>
46197 <DIV class="code">
46198 <PRE>
46199 class Complex {
46200 ...
46201 friend Complex operator+(double, const Complex &amp;c);
46202 ...
46203 };
46204 </PRE>
46205 </DIV>
46206 <P> then SWIG doesn't know what to do with the friend function--in fact,
46207  it simply ignores it and issues a warning. You can still wrap the
46208  operator, but you may have to encapsulate it in a special function. For
46209  example:</P>
46210 <DIV class="code">
46211 <PRE>
46212 %rename(Complex_add_dc) operator+(double, const Complex &amp;);
46213 ...
46214 Complex operator+(double, const Complex &amp;c);
46215 </PRE>
46216 </DIV>
46217 <P> There are ways to make this operator appear as part of the class
46218  using the <TT>%extend</TT> directive. Keep reading.</P>
46219 <H3><A name="Tcl_nn26"></A>33.3.12 C++ namespaces</H3>
46220 <P> SWIG is aware of C++ namespaces, but namespace names do not appear
46221  in the module nor do namespaces result in a module that is broken up
46222  into submodules or packages. For example, if you have a file like this,</P>
46223 <DIV class="code">
46224 <PRE>
46225 %module example
46226
46227 namespace foo {
46228    int fact(int n);
46229    struct Vector {
46230        double x,y,z;
46231    };
46232 };
46233 </PRE>
46234 </DIV>
46235 <P> it works in Tcl as follows:</P>
46236 <DIV class="code">
46237 <PRE>
46238 % load ./example.so
46239 % fact 3
46240 6
46241 % Vector v
46242 % v configure -x 3.4
46243 </PRE>
46244 </DIV>
46245 <P> If your program has more than one namespace, name conflicts (if any)
46246  can be resolved using <TT>%rename</TT> For example:</P>
46247 <DIV class="code">
46248 <PRE>
46249 %rename(Bar_spam) Bar::spam;
46250
46251 namespace Foo {
46252     int spam();
46253 }
46254
46255 namespace Bar {
46256     int spam();
46257 }
46258 </PRE>
46259 </DIV>
46260 <P> If you have more than one namespace and your want to keep their
46261  symbols separate, consider wrapping them as separate SWIG modules. For
46262  example, make the module name the same as the namespace and create
46263  extension modules for each namespace separately. If your program
46264  utilizes thousands of small deeply nested namespaces each with
46265  identical symbol names, well, then you get what you deserve.</P>
46266 <H3><A name="Tcl_nn27"></A>33.3.13 C++ templates</H3>
46267 <P> C++ templates don't present a huge problem for SWIG. However, in
46268  order to create wrappers, you have to tell SWIG to create wrappers for
46269  a particular template instantiation. To do this, you use the <TT>
46270 %template</TT> directive. For example:</P>
46271 <DIV class="code">
46272 <PRE>
46273 %module example
46274 %{
46275 #include &quot;pair.h&quot;
46276 %}
46277
46278 template&lt;class T1, class T2&gt;
46279 struct pair {
46280    typedef T1 first_type;
46281    typedef T2 second_type;
46282    T1 first;
46283    T2 second;
46284    pair();
46285    pair(const T1&amp;, const T2&amp;);
46286   ~pair();
46287 };
46288
46289 %template(pairii) pair&lt;int,int&gt;;
46290 </PRE>
46291 </DIV>
46292 <P> In Tcl:</P>
46293 <DIV class="code">
46294 <PRE>
46295 % pairii p 3 4
46296 % p cget -first
46297 3
46298 % p cget -second
46299 4
46300 </PRE>
46301 </DIV>
46302 <P> Obviously, there is more to template wrapping than shown in this
46303  example. More details can be found in the <A href="#SWIGPlus">SWIG and
46304  C++</A> chapter. Some more complicated examples will appear later.</P>
46305 <H3><A name="Tcl_nn28"></A>33.3.14 C++ Smart Pointers</H3>
46306 <P> In certain C++ programs, it is common to use classes that have been
46307  wrapped by so-called &quot;smart pointers.&quot; Generally, this involves the use
46308  of a template class that implements <TT>operator-&gt;()</TT> like this:</P>
46309 <DIV class="code">
46310 <PRE>
46311 template&lt;class T&gt; class SmartPtr {
46312    ...
46313    T *operator-&gt;();
46314    ...
46315 }
46316 </PRE>
46317 </DIV>
46318 <P> Then, if you have a class like this,</P>
46319 <DIV class="code">
46320 <PRE>
46321 class Foo {
46322 public:
46323      int x;
46324      int bar();
46325 };
46326 </PRE>
46327 </DIV>
46328 <P> A smart pointer would be used in C++ as follows:</P>
46329 <DIV class="code">
46330 <PRE>
46331 SmartPtr&lt;Foo&gt; p = CreateFoo();   // Created somehow (not shown)
46332 ...
46333 p-&gt;x = 3;                        // Foo::x
46334 int y = p-&gt;bar();                // Foo::bar
46335 </PRE>
46336 </DIV>
46337 <P> To wrap this in Tcl, simply tell SWIG about the <TT>SmartPtr</TT>
46338  class and the low-level <TT>Foo</TT> object. Make sure you instantiate <TT>
46339 SmartPtr</TT> using <TT>%template</TT> if necessary. For example:</P>
46340 <DIV class="code">
46341 <PRE>
46342 %module example
46343 ...
46344 %template(SmartPtrFoo) SmartPtr&lt;Foo&gt;;
46345 ...
46346 </PRE>
46347 </DIV>
46348 <P> Now, in Tcl, everything should just &quot;work&quot;:</P>
46349 <DIV class="code">
46350 <PRE>
46351 % set p [CreateFoo]                  # Create a smart-pointer somehow
46352 % $p configure -x 3                  # Foo::x
46353 % $p bar                             # Foo::bar
46354 </PRE>
46355 </DIV>
46356 <P> If you ever need to access the underlying pointer returned by <TT>
46357 operator-&gt;()</TT> itself, simply use the <TT>__deref__()</TT> method.
46358  For example:</P>
46359 <DIV class="code">
46360 <PRE>
46361 % set f [$p __deref__]    # Returns underlying Foo *
46362 </PRE>
46363 </DIV>
46364 <H2><A name="Tcl_nn29"></A>33.4 Further details on the Tcl class
46365  interface</H2>
46366 <P> In the previous section, a high-level view of Tcl wrapping was
46367  presented. A key component of this wrapping is that structures and
46368  classes are wrapped by Tcl class-like objects. This provides a very
46369  natural Tcl interface and allows SWIG to support a number of advanced
46370  features such as operator overloading. However, a number of low-level
46371  details were omitted. This section provides a brief overview of how the
46372  proxy classes work.</P>
46373 <H3><A name="Tcl_nn30"></A>33.4.1 Proxy classes</H3>
46374 <P> In the <A href="#SWIG">&quot;SWIG basics&quot;</A> and <A href="#SWIGPlus">
46375 &quot;SWIG and C++&quot;</A> chapters, details of low-level structure and class
46376  wrapping are described. To summarize those chapters, if you have a
46377  class like this</P>
46378 <DIV class="code">
46379 <PRE>
46380 class Foo {
46381 public:
46382      int x;
46383      int spam(int);
46384      ...
46385 </PRE>
46386 </DIV>
46387 <P> then SWIG transforms it into a set of low-level procedural wrappers.
46388  For example:</P>
46389 <DIV class="code">
46390 <PRE>
46391 Foo *new_Foo() {
46392     return new Foo();
46393 }
46394 void delete_Foo(Foo *f) {
46395     delete f;
46396 }
46397 int Foo_x_get(Foo *f) {
46398     return f-&gt;x;
46399 }
46400 void Foo_x_set(Foo *f, int value) {
46401     f-&gt;x = value;
46402 }
46403 int Foo_spam(Foo *f, int arg1) {
46404     return f-&gt;spam(arg1);
46405 }
46406 </PRE>
46407 </DIV>
46408 <P> These wrappers are actually found in the Tcl extension module. For
46409  example, you can certainly do this:</P>
46410 <DIV class="code">
46411 <PRE>
46412 % load ./example.so
46413 % set f [new_Foo]
46414 % Foo_x_get $f
46415 0
46416 % Foo_spam $f 3
46417 1
46418 %
46419 </PRE>
46420 </DIV>
46421 <P> However, in addition to this, the classname <TT>Foo</TT> is used as
46422  an object constructor function. This allows objects to be encapsulated
46423  objects that look a lot like Tk widgets as shown in the last section.</P>
46424 <H3><A name="Tcl_nn31"></A>33.4.2 Memory management</H3>
46425 <P> Associated with each wrapped object, is an ownership flag <TT>
46426 thisown</TT> The value of this flag determines who is responsible for
46427  deleting the underlying C++ object. If set to 1, the Tcl interpreter
46428  destroys the C++ object when the proxy class is garbage collected. If
46429  set to 0 (or if the attribute is missing), then the destruction of the
46430  proxy class has no effect on the C++ object.</P>
46431 <P> When an object is created by a constructor or returned by value, Tcl
46432  automatically takes ownership of the result. For example:</P>
46433 <DIV class="code">
46434 <PRE>
46435 class Foo {
46436 public:
46437     Foo();
46438     Foo bar();
46439 };
46440 </PRE>
46441 </DIV>
46442 <P> In Tcl:</P>
46443 <DIV class="code">
46444 <PRE>
46445 % Foo f
46446 % f cget -thisown
46447 1
46448 % set g [f bar]
46449 % $g cget -thisown
46450 1
46451 </PRE>
46452 </DIV>
46453 <P> On the other hand, when pointers are returned to Tcl, there is often
46454  no way to know where they came from. Therefore, the ownership is set to
46455  zero. For example:</P>
46456 <DIV class="code">
46457 <PRE>
46458 class Foo {
46459 public:
46460     ...
46461     Foo *spam();
46462     ...
46463 };
46464 </PRE>
46465 </DIV>
46466 <BR><DIV class="code">
46467 <PRE>
46468 % Foo f
46469 % set s [f spam]
46470 % $s cget -thisown
46471 0
46472
46473 </PRE>
46474 </DIV>
46475 <P> This behavior is especially important for classes that act as
46476  containers. For example, if a method returns a pointer to an object
46477  that is contained inside another object, you definitely don't want Tcl
46478  to assume ownership and destroy it!</P>
46479 <P> Related to containers, ownership issues can arise whenever an object
46480  is assigned to a member or global variable. For example, consider this
46481  interface:</P>
46482 <DIV class="code">
46483 <PRE>
46484 %module example
46485
46486 struct Foo {
46487     int  value;
46488     Foo  *next;
46489 };
46490
46491 Foo *head = 0;
46492 </PRE>
46493 </DIV>
46494 <P> When wrapped in Tcl, careful observation will reveal that ownership
46495  changes whenever an object is assigned to a global variable. For
46496  example:</P>
46497 <DIV class="code">
46498 <PRE>
46499 % Foo f
46500 % f cget -thisown
46501 1
46502 % set head f
46503 % f cget -thisown
46504 0
46505 </PRE>
46506 </DIV>
46507 <P> In this case, C is now holding a reference to the object---you
46508  probably don't want Tcl to destroy it. Similarly, this occurs for
46509  members. For example:</P>
46510 <DIV class="code">
46511 <PRE>
46512 % Foo f
46513 % Foo g
46514 % f cget -thisown
46515 1
46516 % g cget -thisown
46517 1
46518 % f configure -next g
46519 % g cget -thisown 
46520 0
46521 %
46522 </PRE>
46523 </DIV>
46524 <P> For the most part, memory management issues remain hidden. However,
46525  there are occasionally situations where you might have to manually
46526  change the ownership of an object. For instance, consider code like
46527  this:</P>
46528 <DIV class="code">
46529 <PRE>
46530 class Node {
46531    Object *value;
46532 public:
46533    void set_value(Object *v) { value = v; }
46534    ...
46535 };
46536 </PRE>
46537 </DIV>
46538 <P> Now, consider the following Tcl code:</P>
46539 <DIV class="code">
46540 <PRE>
46541 % Object v                 # Create an object
46542 % Node n                   # Create a node
46543 % n setvalue v             # Set value
46544 % v cget -thisown
46545 1
46546
46547 </PRE>
46548 </DIV>
46549 <P> In this case, the object <TT>n</TT> is holding a reference to <TT>v</TT>
46550  internally. However, SWIG has no way to know that this has occurred.
46551  Therefore, Tcl still thinks that it has ownership of the object. Should
46552  the proxy object be destroyed, then the C++ destructor will be invoked
46553  and <TT>n</TT> will be holding a stale-pointer. If you're lucky, you
46554  will only get a segmentation fault.</P>
46555 <P> To work around this, it is always possible to flip the ownership
46556  flag. For example,</P>
46557 <DIV class="code">
46558 <PRE>
46559 % v -disown              # Give ownership to C/C++
46560 % v -acquire             # Acquire ownership
46561 </PRE>
46562 </DIV>
46563 <P> It is also possible to deal with situations like this using
46564  typemaps--an advanced topic discussed later.</P>
46565 <H2><A name="Tcl_nn32"></A>33.5 Input and output parameters</H2>
46566 <P> A common problem in some C programs is handling parameters passed as
46567  simple pointers. For example:</P>
46568 <DIV class="code">
46569 <PRE>
46570 void add(int x, int y, int *result) {
46571    *result = x + y;
46572 }
46573 </PRE>
46574 </DIV>
46575 <P> or perhaps</P>
46576 <DIV class="code">
46577 <PRE>
46578 int sub(int *x, int *y) {
46579    return *x+*y;
46580 }
46581 </PRE>
46582 </DIV>
46583 <P> The easiest way to handle these situations is to use the <TT>
46584 typemaps.i</TT> file. For example:</P>
46585 <DIV class="code">
46586 <PRE>
46587 %module example
46588 %include &quot;typemaps.i&quot;
46589
46590 void add(int, int, int *OUTPUT);
46591 int  sub(int *INPUT, int *INPUT);
46592 </PRE>
46593 </DIV>
46594 <P> In Tcl, this allows you to pass simple values instead of pointer.
46595  For example:</P>
46596 <DIV class="code">
46597 <PRE>
46598 set a [add 3 4]
46599 puts $a
46600 7
46601 </PRE>
46602 </DIV>
46603 <P> Notice how the <TT>INPUT</TT> parameters allow integer values to be
46604  passed instead of pointers and how the <TT>OUTPUT</TT> parameter
46605  creates a return result.</P>
46606 <P> If you don't want to use the names <TT>INPUT</TT> or <TT>OUTPUT</TT>
46607 , use the <TT>%apply</TT> directive. For example:</P>
46608 <DIV class="code">
46609 <PRE>
46610 %module example
46611 %include &quot;typemaps.i&quot;
46612
46613 %apply int *OUTPUT { int *result };
46614 %apply int *INPUT  { int *x, int *y};
46615
46616 void add(int x, int y, int *result);
46617 int  sub(int *x, int *y);
46618 </PRE>
46619 </DIV>
46620 <P> If a function mutates one of its parameters like this,</P>
46621 <DIV class="code">
46622 <PRE>
46623 void negate(int *x) {
46624    *x = -(*x);
46625 }
46626 </PRE>
46627 </DIV>
46628 <P> you can use <TT>INOUT</TT> like this:</P>
46629 <DIV class="code">
46630 <PRE>
46631 %include &quot;typemaps.i&quot;
46632 ...
46633 void negate(int *INOUT);
46634 </PRE>
46635 </DIV>
46636 <P> In Tcl, a mutated parameter shows up as a return value. For example:</P>
46637 <DIV class="code">
46638 <PRE>
46639 set a [negate 3]
46640 puts $a
46641 -3
46642 </PRE>
46643 </DIV>
46644 <P> The most common use of these special typemap rules is to handle
46645  functions that return more than one value. For example, sometimes a
46646  function returns a result as well as a special error code:</P>
46647 <DIV class="code">
46648 <PRE>
46649 /* send message, return number of bytes sent, along with success code */
46650 int send_message(char *text, int len, int *success);
46651 </PRE>
46652 </DIV>
46653 <P> To wrap such a function, simply use the <TT>OUTPUT</TT> rule above.
46654  For example:</P>
46655 <DIV class="code">
46656 <PRE>
46657 %module example
46658 %include &quot;typemaps.i&quot;
46659 %apply int *OUTPUT { int *success };
46660 ...
46661 int send_message(char *text, int *success);
46662 </PRE>
46663 </DIV>
46664 <P> When used in Tcl, the function will return multiple values as a
46665  list.</P>
46666 <DIV class="code">
46667 <PRE>
46668 set r [send_message &quot;Hello World&quot;]
46669 set bytes [lindex $r 0]
46670 set success [lindex $r 1]
46671 </PRE>
46672 </DIV>
46673 <P> Another common use of multiple return values are in query functions.
46674  For example:</P>
46675 <DIV class="code">
46676 <PRE>
46677 void get_dimensions(Matrix *m, int *rows, int *columns);
46678 </PRE>
46679 </DIV>
46680 <P> To wrap this, you might use the following:</P>
46681 <DIV class="code">
46682 <PRE>
46683 %module example
46684 %include &quot;typemaps.i&quot;
46685 %apply int *OUTPUT { int *rows, int *columns };
46686 ...
46687 void get_dimensions(Matrix *m, int *rows, *columns);
46688 </PRE>
46689 </DIV>
46690 <P> Now, in Perl:</P>
46691 <DIV class="code">
46692 <PRE>
46693 set dim [get_dimensions $m]
46694 set r  [lindex $dim 0]
46695 set c  [lindex $dim 1]
46696 </PRE>
46697 </DIV>
46698 <H2><A name="Tcl_nn33"></A>33.6 Exception handling</H2>
46699 <P> The <TT>%exception</TT> directive can be used to create a
46700  user-definable exception handler in charge of converting exceptions in
46701  your C/C++ program into Tcl exceptions. The chapter on customization
46702  features contains more details, but suppose you extended the array
46703  example into a C++ class like the following :</P>
46704 <DIV class="code">
46705 <PRE>
46706 class RangeError {};   // Used for an exception
46707
46708 class DoubleArray {
46709   private:
46710     int n;
46711     double *ptr;
46712   public:
46713     // Create a new array of fixed size
46714     DoubleArray(int size) {
46715       ptr = new double[size];
46716       n = size;
46717     }
46718     // Destroy an array
46719     ~DoubleArray() {
46720        delete ptr;
46721     }
46722     // Return the length of the array
46723     int   length() {
46724       return n;
46725     }
46726
46727     // Get an item from the array and perform bounds checking.
46728     double getitem(int i) {
46729       if ((i &gt;= 0) &amp;&amp; (i &lt; n))
46730         return ptr[i];
46731       else
46732         throw RangeError();
46733     }
46734
46735     // Set an item in the array and perform bounds checking.
46736     void setitem(int i, double val) {
46737       if ((i &gt;= 0) &amp;&amp; (i &lt; n))
46738         ptr[i] = val;
46739       else {
46740         throw RangeError();
46741       }
46742     }
46743   };
46744 </PRE>
46745 </DIV>
46746 <P> The functions associated with this class can throw a C++ range
46747  exception for an out-of-bounds array access. We can catch this in our
46748  Tcl extension by specifying the following in an interface file :</P>
46749 <DIV class="code">
46750 <PRE>
46751 %exception {
46752   try {
46753     $action                // Gets substituted by actual function call
46754   }
46755   catch (RangeError) {
46756     Tcl_SetStringObj(tcl_result,&quot;Array index out-of-bounds&quot;);
46757     return TCL_ERROR;
46758   }
46759 }
46760 </PRE>
46761 </DIV>
46762 <P> As shown, the exception handling code will be added to every wrapper
46763  function. Since this is somewhat inefficient. You might consider
46764  refining the exception handler to only apply to specific methods like
46765  this:</P>
46766 <DIV class="code">
46767 <PRE>
46768 %exception getitem {
46769   try {
46770     $action
46771   }
46772   catch (RangeError) {
46773     Tcl_SetStringObj(tcl_result,&quot;Array index out-of-bounds&quot;);
46774     return TCL_ERROR;
46775   }
46776 }
46777
46778 %exception setitem {
46779   try {
46780     $action
46781   }
46782   catch (RangeError) {
46783     Tcl_SetStringObj(tcl_result,&quot;Array index out-of-bounds&quot;);
46784     return TCL_ERROR;
46785   }
46786 }
46787 </PRE>
46788 </DIV>
46789 <P> In this case, the exception handler is only attached to methods and
46790  functions named <TT>getitem</TT> and <TT>setitem</TT>.</P>
46791 <P> If you had a lot of different methods, you can avoid extra typing by
46792  using a macro. For example:</P>
46793 <DIV class="code">
46794 <PRE>
46795 %define RANGE_ERROR
46796 {
46797   try {
46798     $action
46799   }
46800   catch (RangeError) {
46801     Tcl_SetStringObj(tcl_result,&quot;Array index out-of-bounds&quot;);
46802     return TCL_ERROR;
46803   }
46804 }
46805 %enddef
46806
46807 %exception getitem RANGE_ERROR;
46808 %exception setitem RANGE_ERROR;
46809 </PRE>
46810 </DIV>
46811 <P> Since SWIG's exception handling is user-definable, you are not
46812  limited to C++ exception handling. See the chapter on &quot;<A href="#Customization">
46813 Customization Features</A>&quot; for more examples.</P>
46814 <H2><A name="Tcl_nn34"></A>33.7 Typemaps</H2>
46815 <P> This section describes how you can modify SWIG's default wrapping
46816  behavior for various C/C++ datatypes using the <TT>%typemap</TT>
46817  directive. This is an advanced topic that assumes familiarity with the
46818  Tcl C API as well as the material in the &quot;<A href="#Typemaps">Typemaps</A>
46819 &quot; chapter.</P>
46820 <P> Before proceeding, it should be stressed that typemaps are not a
46821  required part of using SWIG---the default wrapping behavior is enough
46822  in most cases. Typemaps are only used if you want to change some aspect
46823  of the primitive C-Tcl interface.</P>
46824 <H3><A name="Tcl_nn35"></A>33.7.1 What is a typemap?</H3>
46825 <P> A typemap is nothing more than a code generation rule that is
46826  attached to a specific C datatype. For example, to convert integers
46827  from Tcl to C, you might define a typemap like this:</P>
46828 <DIV class="code">
46829 <PRE>
46830 %module example
46831
46832 %typemap(in) int {
46833         if (Tcl_GetIntFromObj(interp,$input,&amp;$1) == TCL_ERROR) return TCL_ERROR;
46834         printf(&quot;Received an integer : %d\n&quot;,$1);
46835 }
46836 %inline %{
46837 extern int fact(int n);
46838 %}
46839 </PRE>
46840 </DIV>
46841 <P> Typemaps are always associated with some specific aspect of code
46842  generation. In this case, the &quot;in&quot; method refers to the conversion of
46843  input arguments to C/C++. The datatype <TT>int</TT> is the datatype to
46844  which the typemap will be applied. The supplied C code is used to
46845  convert values. In this code a number of special variable prefaced by a
46846  <TT>$</TT> are used. The <TT>$1</TT> variable is placeholder for a
46847  local variable of type <TT>int</TT>. The <TT>$input</TT> variable is
46848  the input object of type <TT>Tcl_Obj *</TT>.</P>
46849 <P> When this example is compiled into a Tcl module, it operates as
46850  follows:</P>
46851 <DIV class="code">
46852 <PRE>
46853 % load ./example.so
46854 % fact 6
46855 Received an integer : 6
46856 720
46857 </PRE>
46858 </DIV>
46859 <P> In this example, the typemap is applied to all occurrences of the <TT>
46860 int</TT> datatype. You can refine this by supplying an optional
46861  parameter name. For example:</P>
46862 <DIV class="code">
46863 <PRE>
46864 %module example
46865
46866 %typemap(in) int n {
46867         if (Tcl_GetIntFromObj(interp,$input,&amp;$1) == TCL_ERROR) return TCL_ERROR;
46868         printf(&quot;n = %d\n&quot;,$1);
46869 }
46870 %inline %{
46871 extern int fact(int n);
46872 %}
46873 </PRE>
46874 </DIV>
46875 <P> In this case, the typemap code is only attached to arguments that
46876  exactly match <TT>int n</TT>.</P>
46877 <P> The application of a typemap to specific datatypes and argument
46878  names involves more than simple text-matching--typemaps are fully
46879  integrated into the SWIG type-system. When you define a typemap for <TT>
46880 int</TT>, that typemap applies to <TT>int</TT> and qualified variations
46881  such as <TT>const int</TT>. In addition, the typemap system follows <TT>
46882 typedef</TT> declarations. For example:</P>
46883 <DIV class="code">
46884 <PRE>
46885 %typemap(in) int n {
46886         if (Tcl_GetIntFromObj(interp,$input,&amp;$1) == TCL_ERROR) return TCL_ERROR;
46887         printf(&quot;n = %d\n&quot;,$1);
46888 }
46889 %inline %{
46890 typedef int Integer;
46891 extern int fact(Integer n);    // Above typemap is applied
46892 %}
46893 </PRE>
46894 </DIV>
46895 <P> However, the matching of <TT>typedef</TT> only occurs in one
46896  direction. If you defined a typemap for <TT>Integer</TT>, it is not
46897  applied to arguments of type <TT>int</TT>.</P>
46898 <P> Typemaps can also be defined for groups of consecutive arguments.
46899  For example:</P>
46900 <DIV class="code">
46901 <PRE>
46902 %typemap(in) (char *str, int len) {
46903     $1 = Tcl_GetStringFromObj($input,&amp;$2);
46904 };
46905
46906 int count(char c, char *str, int len);
46907 </PRE>
46908 </DIV>
46909 <P> When a multi-argument typemap is defined, the arguments are always
46910  handled as a single Tcl object. This allows the function to be used
46911  like this (notice how the length parameter is omitted):</P>
46912 <DIV class="code">
46913 <PRE>
46914 % count e &quot;Hello World&quot;
46915 1
46916 </PRE>
46917 </DIV>
46918 <H3><A name="Tcl_nn36"></A>33.7.2 Tcl typemaps</H3>
46919 <P> The previous section illustrated an &quot;in&quot; typemap for converting Tcl
46920  objects to C. A variety of different typemap methods are defined by the
46921  Tcl module. For example, to convert a C integer back into a Tcl object,
46922  you might define an &quot;out&quot; typemap like this:</P>
46923 <DIV class="code">
46924 <PRE>
46925 %typemap(out) int {
46926     Tcl_SetObjResult(interp,Tcl_NewIntObj($1));
46927 }
46928 </PRE>
46929 </DIV>
46930 <P> The following list details all of the typemap methods that can be
46931  used by the Tcl module:</P>
46932 <P> <TT>%typemap(in)</TT></P>
46933 <DIV class="indent"> Converts Tcl objects to input function arguments</DIV>
46934 <P> <TT>%typemap(out)</TT></P>
46935 <DIV class="indent"> Converts return value of a C function to a Tcl
46936  object</DIV>
46937 <P> <TT>%typemap(varin)</TT></P>
46938 <DIV class="indent"> Assigns a C global variable from a Tcl object</DIV>
46939 <P> <TT>%typemap(varout)</TT></P>
46940 <DIV class="indent"> Returns a C global variable as a Tcl object</DIV>
46941 <P> <TT>%typemap(freearg)</TT></P>
46942 <DIV class="indent"> Cleans up a function argument (if necessary)</DIV>
46943 <P> <TT>%typemap(argout)</TT></P>
46944 <DIV class="indent"> Output argument processing</DIV>
46945 <P> <TT>%typemap(ret)</TT></P>
46946 <DIV class="indent"> Cleanup of function return values</DIV>
46947 <P> <TT>%typemap(consttab)</TT></P>
46948 <DIV class="indent"> Creation of Tcl constants (constant table)</DIV>
46949 <P> <TT>%typemap(constcode)</TT></P>
46950 <DIV class="indent"> Creation of Tcl constants (init function)</DIV>
46951 <P> <TT>%typemap(memberin)</TT></P>
46952 <DIV class="indent"> Setting of structure/class member data</DIV>
46953 <P> <TT>%typemap(globalin)</TT></P>
46954 <DIV class="indent"> Setting of C global variables</DIV>
46955 <P> <TT>%typemap(check)</TT></P>
46956 <DIV class="indent"> Checks function input values.</DIV>
46957 <P> <TT>%typemap(default)</TT></P>
46958 <DIV class="indent"> Set a default value for an argument (making it
46959  optional).</DIV>
46960 <P> <TT>%typemap(arginit)</TT></P>
46961 <DIV class="indent"> Initialize an argument to a value before any
46962  conversions occur.</DIV>
46963 <P> Examples of these methods will appear shortly.</P>
46964 <H3><A name="Tcl_nn37"></A>33.7.3 Typemap variables</H3>
46965 <P> Within typemap code, a number of special variables prefaced with a <TT>
46966 $</TT> may appear. A full list of variables can be found in the &quot;<A href="#Typemaps">
46967 Typemaps</A>&quot; chapter. This is a list of the most common variables:</P>
46968 <P> <TT>$1</TT></P>
46969 <DIV class="indent"> A C local variable corresponding to the actual type
46970  specified in the <TT>%typemap</TT> directive. For input values, this is
46971  a C local variable that's supposed to hold an argument value. For
46972  output values, this is the raw result that's supposed to be returned to
46973  Tcl.</DIV>
46974 <P> <TT>$input</TT></P>
46975 <DIV class="indent"> A <TT>Tcl_Obj *</TT> holding a raw Tcl object with
46976  an argument or variable value.</DIV>
46977 <P> <TT>$result</TT></P>
46978 <DIV class="indent"> A <TT>Tcl_Obj *</TT> that holds the result to be
46979  returned to Tcl.</DIV>
46980 <P> <TT>$1_name</TT></P>
46981 <DIV class="indent"> The parameter name that was matched.</DIV>
46982 <P> <TT>$1_type</TT></P>
46983 <DIV class="indent"> The actual C datatype matched by the typemap.</DIV>
46984 <P> <TT>$1_ltype</TT></P>
46985 <DIV class="indent"> An assignable version of the datatype matched by
46986  the typemap (a type that can appear on the left-hand-side of a C
46987  assignment operation). This type is stripped of qualifiers and may be
46988  an altered version of <TT>$1_type</TT>. All arguments and local
46989  variables in wrapper functions are declared using this type so that
46990  their values can be properly assigned.</DIV>
46991 <P> <TT>$symname</TT></P>
46992 <DIV class="indent"> The Tcl name of the wrapper function being created.</DIV>
46993 <H3><A name="Tcl_nn38"></A>33.7.4 Converting a Tcl list to a char **</H3>
46994 <P> A common problem in many C programs is the processing of command
46995  line arguments, which are usually passed in an array of NULL terminated
46996  strings. The following SWIG interface file allows a Tcl list to be used
46997  as a <TT>char **</TT> object.</P>
46998 <DIV class="code">
46999 <PRE>
47000 %module argv
47001
47002 // This tells SWIG to treat char ** as a special case
47003 %typemap(in) char ** {
47004      Tcl_Obj **listobjv;
47005      int       nitems;
47006      int       i;
47007      if (Tcl_ListObjGetElements(interp, $input, &amp;nitems, &amp;listobjv) == TCL_ERROR) {
47008         return TCL_ERROR;
47009      }
47010      $1 = (char **) malloc((nitems+1)*sizeof(char *));
47011      for (i = 0; i &lt; nitems; i++) {
47012         $1[i] = Tcl_GetStringFromObj(listobjv[i],0);
47013      }
47014      $1[i] = 0;
47015 }
47016
47017 // This gives SWIG some cleanup code that will get called after the function call
47018 %typemap(freearg) char ** {
47019      if ($1) {
47020         free($1);
47021      }
47022 }
47023
47024 // Now a test functions
47025 %inline %{
47026 int print_args(char **argv) {
47027     int i = 0;
47028     while (argv[i]) {
47029          printf(&quot;argv[%d] = %s\n&quot;, i,argv[i]);
47030          i++;
47031     }
47032     return i;
47033 }
47034 %}
47035 %include &quot;tclsh.i&quot;
47036
47037 </PRE>
47038 </DIV>
47039 <P> In Tcl:</P>
47040 <DIV class="code">
47041 <PRE>
47042 % print_args {John Guido Larry}
47043 argv[0] = John
47044 argv[1] = Guido
47045 argv[2] = Larry
47046 3
47047 </PRE>
47048 </DIV>
47049 <H3><A name="Tcl_nn39"></A>33.7.5 Returning values in arguments</H3>
47050 <P> The &quot;argout&quot; typemap can be used to return a value originating from
47051  a function argument. For example :</P>
47052 <DIV class="code">
47053 <PRE>
47054 // A typemap defining how to return an argument by appending it to the result
47055 %typemap(argout) double *outvalue {
47056      Tcl_Obj *o = Tcl_NewDoubleObj($1);
47057      Tcl_ListObjAppendElement(interp,$result,o);
47058 }
47059
47060 // A typemap telling SWIG to ignore an argument for input
47061 // However, we still need to pass a pointer to the C function
47062 %typemap(in,numinputs=0) double *outvalue (double temp) {
47063      $1 = &amp;temp;
47064 }
47065
47066 // Now a function returning two values
47067 int mypow(double a, double b, double *outvalue) {
47068         if ((a &lt; 0) || (b &lt; 0)) return -1;
47069         *outvalue = pow(a,b);
47070         return 0;
47071 };
47072 </PRE>
47073 </DIV>
47074 <P> When wrapped, SWIG matches the <TT>argout</TT> typemap to the &quot;<TT>
47075 double *outvalue</TT>&quot; argument. The numinputs=0 specification tells
47076  SWIG to simply ignore this argument when generating wrapper code. As a
47077  result, a Tcl function using these typemaps will work like this :</P>
47078 <DIV class="code">
47079 <PRE>
47080 % mypow 2 3     # Returns two values, a status value and the result
47081 0 8
47082 %
47083 </PRE>
47084 </DIV>
47085 <H3><A name="Tcl_nn40"></A>33.7.6 Useful functions</H3>
47086 <P> The following tables provide some functions that may be useful in
47087  writing Tcl typemaps.</P>
47088 <P><B> Integers</B></P>
47089 <DIV class="code">
47090 <PRE>
47091 Tcl_Obj   *Tcl_NewIntObj(int Value);
47092 void       Tcl_SetIntObj(Tcl_Obj *obj, int Value);
47093 int        Tcl_GetIntFromObj(Tcl_Interp *, Tcl_Obj *obj, int *ip);
47094 </PRE>
47095 </DIV>
47096 <P><B> Floating Point</B></P>
47097 <DIV class="code">
47098 <PRE>
47099 Tcl_Obj  *Tcl_NewDoubleObj(double Value);
47100 void      Tcl_SetDoubleObj(Tcl_Obj *obj, double value);
47101 int       Tcl_GetDoubleFromObj(Tcl_Interp *, Tcl_Obj *o, double *dp);
47102 </PRE>
47103 </DIV>
47104 <P><B> Strings</B></P>
47105 <DIV class="code">
47106 <PRE>
47107 Tcl_Obj  *Tcl_NewStringObj(char *str, int len);
47108 void      Tcl_SetStringObj(Tcl_Obj *obj, char *str, int len);
47109 char     *Tcl_GetStringFromObj(Tcl_Obj *obj, int *len);
47110 void      Tcl_AppendToObj(Tcl_Obj *obj, char *str, int len);
47111 </PRE>
47112 </DIV>
47113 <P><B> Lists</B></P>
47114 <DIV class="code">
47115 <PRE>
47116 Tcl_Obj  *Tcl_NewListObj(int objc, Tcl_Obj *objv);
47117 int       Tcl_ListObjAppendList(Tcl_Interp *, Tcl_Obj *listPtr, Tcl_Obj *elemListPtr);
47118 int       Tcl_ListObjAppendElement(Tcl_Interp *, Tcl_Obj *listPtr, Tcl_Obj *element);
47119 int       Tcl_ListObjGetElements(Tcl_Interp *, Tcl_Obj *listPtr, int *objcPtr,
47120                                  Tcl_Obj ***objvPtr);
47121 int       Tcl_ListObjLength(Tcl_Interp *, Tcl_Obj *listPtr, int *intPtr);
47122 int       Tcl_ListObjIndex(Tcl_Interp *, Tcl_Obj *listPtr, int index,
47123                            Tcl_Obj_Obj **objptr);
47124 int       Tcl_ListObjReplace(Tcl_Interp *, Tcl_Obj *listPtr, int first, int count,
47125                              int objc, Tcl_Obj *objv);
47126 </PRE>
47127 </DIV>
47128 <P><B> Objects</B></P>
47129 <DIV class="code">
47130 <PRE>
47131 Tcl_Obj *Tcl_DuplicateObj(Tcl_Obj *obj);
47132 void     Tcl_IncrRefCount(Tcl_Obj *obj);
47133 void     Tcl_DecrRefCount(Tcl_Obj *obj);
47134 int      Tcl_IsShared(Tcl_Obj *obj);
47135 </PRE>
47136 </DIV>
47137 <H3><A name="Tcl_nn41"></A>33.7.7 Standard typemaps</H3>
47138 <P> The following typemaps show how to convert a few common kinds of
47139  objects between Tcl and C (and to give a better idea of how typemaps
47140  work)</P>
47141 <P><B> Integer conversion</B></P>
47142 <DIV class="code">
47143 <PRE>
47144 %typemap(in) int, short, long {
47145    int temp;
47146    if (Tcl_GetIntFromObj(interp, $input, &amp;temp) == TCL_ERROR)
47147       return TCL_ERROR;
47148    $1 = ($1_ltype) temp;
47149 }
47150 </PRE>
47151 </DIV>
47152 <BR><DIV class="code">
47153 <PRE>
47154 %typemap(out) int, short, long {
47155    Tcl_SetIntObj($result,(int) $1);
47156 }
47157 </PRE>
47158 </DIV>
47159 <P><B> Floating point conversion</B></P>
47160 <DIV class="code">
47161 <PRE>
47162 %typemap(in) float, double {
47163    double temp;
47164    if (Tcl_GetDoubleFromObj(interp, $input, &amp;temp) == TCL_ERROR)
47165        return TCL_ERROR;
47166    $1 = ($1_ltype) temp;
47167 }
47168 </PRE>
47169 </DIV>
47170 <BR><DIV class="code">
47171 <PRE>
47172 %typemap(out) float, double {
47173    Tcl_SetDoubleObj($result, $1);
47174 }
47175 </PRE>
47176 </DIV>
47177 <P><B> String Conversion</B></P>
47178 <DIV class="code">
47179 <PRE>
47180 %typemap(in) char * {
47181    int len;
47182    $1 = Tcl_GetStringFromObj(interp, &amp;len);
47183    }
47184 }
47185 </PRE>
47186 </DIV>
47187 <BR><DIV class="code">
47188 <PRE>
47189 %typemap(out) char * {
47190    Tcl_SetStringObj($result,$1);
47191 }
47192 </PRE>
47193 </DIV>
47194 <H3><A name="Tcl_nn42"></A>33.7.8 Pointer handling</H3>
47195 <P> SWIG pointers are mapped into Tcl strings containing the hexadecimal
47196  value and type. The following functions can be used to create and read
47197  pointer values.</P>
47198 <P> <TT>int SWIG_ConvertPtr(Tcl_Obj *obj, void **ptr, swig_type_info
47199  *ty, int flags)</TT></P>
47200 <DIV class="indent"> Converts a Tcl object <TT>obj</TT> to a C pointer.
47201  The result of the conversion is placed into the pointer located at <TT>
47202 ptr</TT>. <TT>ty</TT> is a SWIG type descriptor structure. <TT>flags</TT>
47203  is used to handle error checking and other aspects of conversion. It is
47204  currently reserved for future expansion. Returns 0 on success and -1 on
47205  error.</DIV>
47206 <P> <TT>Tcl_Obj *SWIG_NewPointerObj(void *ptr, swig_type_info *ty, int
47207  flags)</TT></P>
47208 <DIV class="indent"> Creates a new Tcl pointer object. <TT>ptr</TT> is
47209  the pointer to convert, <TT>ty</TT> is the SWIG type descriptor
47210  structure that describes the type, and <TT>own</TT> is a flag reserved
47211  for future expansion.</DIV>
47212 <P> Both of these functions require the use of a special SWIG
47213  type-descriptor structure. This structure contains information about
47214  the mangled name of the datatype, type-equivalence information, as well
47215  as information about converting pointer values under C++ inheritance.
47216  For a type of <TT>Foo *</TT>, the type descriptor structure is usually
47217  accessed as follows:</P>
47218 <DIV class="indent">
47219 <PRE>
47220 Foo *f;
47221 if (SWIG_ConvertPtr($input, (void **) &amp;f, SWIGTYPE_p_Foo, 0) == -1) return NULL;
47222
47223 Tcl_Obj *;
47224 obj = SWIG_NewPointerObj(f, SWIGTYPE_p_Foo, 0);
47225 </PRE>
47226 </DIV>
47227 <P> In a typemap, the type descriptor should always be accessed using
47228  the special typemap variable <TT>$1_descriptor</TT>. For example:</P>
47229 <DIV class="indent">
47230 <PRE>
47231 %typemap(in) Foo * {
47232    if ((SWIG_ConvertPtr($input,(void **) &amp;$1, $1_descriptor,0)) == -1) return NULL;
47233 }
47234 </PRE>
47235 </DIV>
47236 <P> If necessary, the descriptor for any type can be obtained using the <TT>
47237 $descriptor()</TT> macro in a typemap. For example:</P>
47238 <DIV class="indent">
47239 <PRE>
47240 %typemap(in) Foo * {
47241    if ((SWIG_ConvertPtr($input,(void **) &amp;$1, $descriptor(Foo *), 0)) == -1) return NULL;
47242 }
47243 </PRE>
47244 </DIV>
47245 <H2><A name="Tcl_nn43"></A>33.8 Turning a SWIG module into a Tcl
47246  Package.</H2>
47247 <P> Tcl 7.4 introduced the idea of an extension package. By default,
47248  SWIG generates all of the code necessary to create a package. To set
47249  the package version, simply use the <TT>-pkgversion</TT> option. For
47250  example:</P>
47251 <DIV class="code">
47252 <PRE>
47253 % swig -tcl -pkgversion 2.3 example.i
47254 </PRE>
47255 </DIV>
47256 <P> After building the SWIG generated module, you need to execute the &quot;<TT>
47257 pkg_mkIndex</TT>&quot; command inside tclsh. For example :</P>
47258 <DIV class="code">
47259 <PRE>
47260 unix &gt; tclsh
47261 % pkg_mkIndex . example.so
47262 % exit
47263 </PRE>
47264 </DIV>
47265 <P> This creates a file &quot;<TT>pkgIndex.tcl</TT>&quot; with information about
47266  the package. To use your package, you now need to move it to its own
47267  subdirectory which has the same name as the package. For example :</P>
47268 <DIV class="code">
47269 <PRE>
47270 ./example/
47271            pkgIndex.tcl           # The file created by pkg_mkIndex
47272            example.so             # The SWIG generated module
47273 </PRE>
47274 </DIV>
47275 <P> Finally, assuming that you're not entirely confused at this point,
47276  make sure that the example subdirectory is visible from the directories
47277  contained in either the <TT>tcl_library</TT> or <TT>auto_path</TT>
47278  variables. At this point you're ready to use the package as follows :</P>
47279 <DIV class="code">
47280 <PRE>
47281 unix &gt; tclsh
47282 % package require example
47283 % fact 4
47284 24
47285 %
47286 </PRE>
47287 </DIV>
47288 <P> If you're working with an example in the current directory and this
47289  doesn't work, do this instead :</P>
47290 <DIV class="code">
47291 <PRE>
47292 unix &gt; tclsh
47293 % lappend auto_path .
47294 % package require example
47295 % fact 4
47296 24
47297 </PRE>
47298 </DIV>
47299 <P> As a final note, most SWIG examples do not yet use the <TT>package</TT>
47300  commands. For simple extensions it may be easier just to use the <TT>
47301 load</TT> command instead.</P>
47302 <H2><A name="Tcl_nn44"></A>33.9 Building new kinds of Tcl interfaces (in
47303  Tcl)</H2>
47304 <P> One of the most interesting aspects of Tcl and SWIG is that you can
47305  create entirely new kinds of Tcl interfaces in Tcl using the low-level
47306  SWIG accessor functions. For example, suppose you had a library of
47307  helper functions to access arrays :</P>
47308 <DIV class="code">
47309 <PRE>
47310 /* File : array.i */
47311 %module array
47312
47313 %inline %{
47314 double *new_double(int size) {
47315         return (double *) malloc(size*sizeof(double));
47316 }
47317 void delete_double(double *a) {
47318         free(a);
47319 }
47320 double get_double(double *a, int index) {
47321         return a[index];
47322 }
47323 void set_double(double *a, int index, double val) {
47324         a[index] = val;
47325 }
47326 int *new_int(int size) {
47327         return (int *) malloc(size*sizeof(int));
47328 }
47329 void delete_int(int *a) {
47330         free(a);
47331 }
47332 int get_int(int *a, int index) {
47333         return a[index];
47334 }
47335 int set_int(int *a, int index, int val) {
47336         a[index] = val;
47337 }
47338 %}
47339
47340 </PRE>
47341 </DIV>
47342 <P> While these could be called directly, we could also write a Tcl
47343  script like this :</P>
47344 <DIV class="code">
47345 <PRE>
47346 proc Array {type size} {
47347     set ptr [new_$type $size]
47348     set code {
47349         set method [lindex $args 0]
47350         set parms [concat $ptr [lrange $args 1 end]]
47351         switch $method {
47352             get {return [eval &quot;get_$type $parms&quot;]}
47353             set {return [eval &quot;set_$type $parms&quot;]}
47354             delete {eval &quot;delete_$type $ptr; rename $ptr {}&quot;}
47355         }
47356     }
47357     # Create a procedure
47358     uplevel &quot;proc $ptr args {set ptr $ptr; set type $type;$code}&quot;
47359     return $ptr
47360 }
47361 </PRE>
47362 </DIV>
47363 <P> Our script allows easy array access as follows :</P>
47364 <DIV class="code">
47365 <PRE>
47366 set a [Array double 100]                   ;# Create a double [100]
47367 for {set i 0} {$i &lt; 100} {incr i 1} {      ;# Clear the array
47368         $a set $i 0.0
47369 }
47370 $a set 3 3.1455                            ;# Set an individual element
47371 set b [$a get 10]                          ;# Retrieve an element
47372
47373 set ia [Array int 50]                      ;# Create an int[50]
47374 for {set i 0} {$i &lt; 50} {incr i 1} {       ;# Clear it
47375         $ia set $i 0
47376 }
47377 $ia set 3 7                                ;# Set an individual element
47378 set ib [$ia get 10]                        ;# Get an individual element
47379
47380 $a delete                                  ;# Destroy a
47381 $ia delete                                 ;# Destroy ia
47382 </PRE>
47383 </DIV>
47384 <P> The cool thing about this approach is that it makes a common
47385  interface for two different types of arrays. In fact, if we were to add
47386  more C datatypes to our wrapper file, the Tcl code would work with
47387  those as well--without modification. If an unsupported datatype was
47388  requested, the Tcl code would simply return with an error so there is
47389  very little danger of blowing something up (although it is easily
47390  accomplished with an out of bounds array access).</P>
47391 <H3><A name="Tcl_nn45"></A>33.9.1 Proxy classes</H3>
47392 <P> A similar approach can be applied to proxy classes (also known as
47393  shadow classes). The following example is provided by Erik Bierwagen
47394  and Paul Saxe. To use it, run SWIG with the <TT>-noobject</TT> option
47395  (which disables the builtin object oriented interface). When running
47396  Tcl, simply source this file. Now, objects can be used in a more or
47397  less natural fashion.</P>
47398 <DIV class="code">
47399 <PRE>
47400 # swig_c++.tcl
47401 # Provides a simple object oriented interface using
47402 # SWIG's low level interface.
47403 #
47404
47405 proc new {objectType handle_r args} {
47406     # Creates a new SWIG object of the given type,
47407     # returning a handle in the variable &quot;handle_r&quot;.
47408     #
47409     # Also creates a procedure for the object and a trace on
47410     # the handle variable that deletes the object when the
47411     # handle variable is overwritten or unset
47412     upvar $handle_r handle
47413     #
47414     # Create the new object
47415     #
47416     eval set handle \[new_$objectType $args\]
47417     #
47418     # Set up the object procedure
47419     #
47420     proc $handle {cmd args} &quot;eval ${objectType}_\$cmd $handle \$args&quot;
47421     #
47422     # And the trace ...
47423     #
47424     uplevel trace variable $handle_r uw &quot;{deleteObject $objectType $handle}&quot;
47425     #
47426     # Return the handle so that 'new' can be used as an argument to a procedure
47427     #
47428     return $handle
47429 }
47430
47431 proc deleteObject {objectType handle name element op} {
47432     #
47433     # Check that the object handle has a reasonable form
47434     #
47435     if {![regexp {_[0-9a-f]*_(.+)_p} $handle]} {
47436         error &quot;deleteObject: not a valid object handle: $handle&quot;
47437     }
47438     #
47439     # Remove the object procedure
47440     #
47441     catch {rename $handle {}}
47442     #
47443     # Delete the object
47444     #
47445     delete_$objectType $handle
47446 }
47447
47448 proc delete {handle_r} {
47449     #
47450     # A synonym for unset that is more familiar to C++ programmers
47451     #
47452     uplevel unset $handle_r
47453 }
47454 </PRE>
47455 </DIV>
47456 <P> To use this file, we simply source it and execute commands such as
47457  &quot;new&quot; and &quot;delete&quot; to manipulate objects. For example :</P>
47458 <DIV class="code">
47459 <PRE>
47460 // list.i
47461 %module List
47462 %{
47463 #include &quot;list.h&quot;
47464 %}
47465
47466 // Very simple C++ example
47467
47468 class List {
47469 public:
47470   List();  // Create a new list
47471   ~List(); // Destroy a list
47472   int  search(char *value);
47473   void insert(char *);  // Insert a new item into the list
47474   void remove(char *);  // Remove item from list
47475   char *get(int n);     // Get the nth item in the list
47476   int  length;          // The current length of the list
47477 static void print(List *l);  // Print out the contents of the list
47478 };
47479 </PRE>
47480 </DIV>
47481 <P> Now a Tcl script using the interface...</P>
47482 <DIV class="code">
47483 <PRE>
47484 load ./list.so list       ; # Load the module
47485 source swig_c++.tcl       ; # Source the object file
47486
47487 new List l
47488 $l insert Dave
47489 $l insert John
47490 $l insert Guido
47491 $l remove Dave
47492 puts $l length_get
47493
47494 delete l
47495 </PRE>
47496 </DIV>
47497 <P> The cool thing about this example is that it works with any C++
47498  object wrapped by SWIG and requires no special compilation. Proof that
47499  a short, but clever Tcl script can be combined with SWIG to do many
47500  interesting things.</P>
47501 <H2><A name="Tcl_nn46"></A>33.10 Tcl/Tk Stubs</H2>
47502 <P> For background information about the Tcl Stubs feature, see <A href="http://www.tcl.tk/doc/howto/stubs.html">
47503 http://www.tcl.tk/doc/howto/stubs.html</A>.</P>
47504 <P> As of SWIG 1.3.10, the generated C/C++ wrapper will use the Tcl
47505  Stubs feature if compiled with <TT>-DUSE_TCL_STUBS</TT>.</P>
47506 <P> As of SWIG 1.3.40, the generated C/C++ wrapper will use the Tk Stubs
47507  feature if compiled with <TT>-DUSE_TK_STUBS</TT>. Also, you can
47508  override the minimum version to support which is passed to <TT>
47509 Tcl_InitStubs()</TT> and <TT>Tk_InitStubs()</TT> with <TT>
47510 -DSWIG_TCL_STUBS_VERSION=&quot;8.3&quot;</TT> or the version being compiled with
47511  using <TT>-DSWIG_TCL_STUBS_VERSION=TCL_VERSION</TT>.</P>
47512 <HR NOSHADE>
47513 <H1><A name="R"></A>34 SWIG and R</H1>
47514
47515 <!-- INDEX -->
47516 <DIV class="sectiontoc">
47517 <UL>
47518 <LI><A href="#R_nn2">Bugs</A></LI>
47519 <LI><A href="#R_nn3">Using R and SWIG</A></LI>
47520 <LI><A href="#R_nn4">Precompiling large R files</A></LI>
47521 <LI><A href="#R_nn5">General policy</A></LI>
47522 <LI><A href="#R_language_conventions">Language conventions</A></LI>
47523 <LI><A href="#R_nn6">C++ classes</A></LI>
47524 <LI><A href="#R_nn7">Enumerations</A></LI>
47525 </UL>
47526 </DIV>
47527 <!-- INDEX -->
47528 <P> R is a GPL'ed open source statistical and plotting environment.
47529  Information about R can be found at <A href="http://www.r-project.org/">
47530 www.r-project.org</A>. The R bindings are under active development. They
47531  have been used to compile and run an R interface to QuantLib running on
47532  Mandriva Linux with gcc. The R bindings also work on Microsoft Windows
47533  using Visual C++.</P>
47534 <H2><A name="R_nn2"></A>34.1 Bugs</H2>
47535 <P> Currently the following features are not implemented or broken:</P>
47536 <UL>
47537 <LI>Garbage collection of created objects</LI>
47538 <LI>C Array wrappings</LI>
47539 </UL>
47540 <H2><A name="R_nn3"></A>34.2 Using R and SWIG</H2>
47541 <P> To use R and SWIG in C mode, execute the following commands where
47542  example.c is the name of the file with the functions in them</P>
47543 <DIV class="shell">
47544 <PRE>
47545 swig -r example.i
47546 PKG_LIBS=&quot;example.c&quot; R CMD SHLIB example_wrap.c
47547 </PRE>
47548 </DIV>
47549 <P> The corresponding comments for C++ mode are</P>
47550 <DIV class="shell">
47551 <PRE>
47552 swig -c++ -r -o example_wrap.cpp example.i
47553 PKG_LIBS=&quot;example.cxx&quot; R CMD SHLIB example_wrap.cpp
47554 </PRE>
47555 </DIV>
47556 <P> Note that R is sensitive to the name of the file and to the file
47557  extension in C and C++ mode. The name of the wrapper file must be the
47558  name of the library. Also in C++ mode, the file extension must be .cpp
47559  rather than .cxx for the R compile command to recognize it.</P>
47560 <P> The commands produces two files. A dynamic shared object file called
47561  example.so, or example.dll, and an R wrapper file called example.R. To
47562  load these files, start up R and type in the following commands</P>
47563 <DIV class="shell">
47564 <PRE>
47565 dyn.load(paste(&quot;example&quot;, .Platform$dynlib.ext, sep=&quot;&quot;))
47566 source(&quot;example.R&quot;)
47567 cacheMetaData(1)
47568 </PRE>
47569 </DIV> The cacheMetaData(1) will cause R to refresh its object tables.
47570  Without it, inheritance of wrapped objects may fail.
47571 <P> These two files can be loaded in any order</P>
47572 <H2><A name="R_nn4"></A>34.3 Precompiling large R files</H2>
47573  In cases where the R file is large, one make save a lot of loading time
47574  by precompiling the R wrapper. This can be done by creating the file
47575  makeRData.R which contains the following
47576 <PRE>
47577 source('BigFile.R')
47578 save(list=ls(all=TRUE),file=&quot;BigFile.RData&quot;, compress=TRUE)
47579 q(save=&quot;no&quot;)
47580 </PRE>
47581  This will generate a compiled R file called BigFile.RData that will
47582  save a large amount of loading time.
47583 <H2><A name="R_nn5"></A>34.4 General policy</H2>
47584 <P> The general policy of the module is to treat the C/C++ as a basic
47585  wrapping over the underlying functions and rely on the R type system to
47586  provide R syntax.</P>
47587 <H2><A name="R_language_conventions"></A>34.5 Language conventions</H2>
47588 <P> getitem and setitem use C++ conventions (i.e. zero based indices). [
47589 <!---
47590 and [ are overloaded to allow for R syntax (one based indices and
47591 slices)
47592 &lt;/p-->
47593 </P>
47594 <H2><A name="R_nn6"></A>34.6 C++ classes</H2>
47595 <P> C++ objects are implemented as external pointer objects with the
47596  class being the mangled name of the class. The C++ classes are
47597  encapsulated as an SEXP with an external pointer type. The class is the
47598  mangled name of the class. The nice thing about R is that is allows you
47599  to keep track of the pointer object which removes the necessity for a
47600  lot of the proxy class baggage you see in other languages.</P>
47601 <H2><A name="R_nn7"></A>34.7 Enumerations</H2>
47602 <P> enumerations are characters which are then converted back and forth
47603  to ints before calling the C routines. All of the enumeration code is
47604  done in R.</P>
47605 <HR NOSHADE>
47606 <H1><A name="Extending"></A>35 Extending SWIG to support new languages</H1>
47607
47608 <!-- INDEX -->
47609 <DIV class="sectiontoc">
47610 <UL>
47611 <LI><A href="#Extending_nn2">Introduction</A></LI>
47612 <LI><A href="#Extending_nn3">Prerequisites</A></LI>
47613 <LI><A href="#Extending_nn4">The Big Picture</A></LI>
47614 <LI><A href="#Extending_nn5">Execution Model</A>
47615 <UL>
47616 <LI><A href="#Extending_nn6">Preprocessing</A></LI>
47617 <LI><A href="#Extending_nn7">Parsing</A></LI>
47618 <LI><A href="#Extending_nn8">Parse Trees</A></LI>
47619 <LI><A href="#Extending_nn9">Attribute namespaces</A></LI>
47620 <LI><A href="#Extending_nn10">Symbol Tables</A></LI>
47621 <LI><A href="#Extending_nn11">The %feature directive</A></LI>
47622 <LI><A href="#Extending_nn12">Code Generation</A></LI>
47623 <LI><A href="#Extending_nn13">SWIG and XML</A></LI>
47624 </UL>
47625 </LI>
47626 <LI><A href="#Extending_nn14">Primitive Data Structures</A>
47627 <UL>
47628 <LI><A href="#Extending_nn15">Strings</A></LI>
47629 <LI><A href="#Extending_nn16">Hashes</A></LI>
47630 <LI><A href="#Extending_nn17">Lists</A></LI>
47631 <LI><A href="#Extending_nn18">Common operations</A></LI>
47632 <LI><A href="#Extending_nn19">Iterating over Lists and Hashes</A></LI>
47633 <LI><A href="#Extending_nn20">I/O</A></LI>
47634 </UL>
47635 </LI>
47636 <LI><A href="#Extending_nn21">Navigating and manipulating parse trees</A>
47637 </LI>
47638 <LI><A href="#Extending_nn22">Working with attributes</A></LI>
47639 <LI><A href="#Extending_nn23">Type system</A>
47640 <UL>
47641 <LI><A href="#Extending_nn24">String encoding of types</A></LI>
47642 <LI><A href="#Extending_nn25">Type construction</A></LI>
47643 <LI><A href="#Extending_nn26">Type tests</A></LI>
47644 <LI><A href="#Extending_nn27">Typedef and inheritance</A></LI>
47645 <LI><A href="#Extending_nn28">Lvalues</A></LI>
47646 <LI><A href="#Extending_nn29">Output functions</A></LI>
47647 </UL>
47648 </LI>
47649 <LI><A href="#Extending_nn30">Parameters</A></LI>
47650 <LI><A href="#Extending_nn31">Writing a Language Module</A>
47651 <UL>
47652 <LI><A href="#Extending_nn32">Execution model</A></LI>
47653 <LI><A href="#Extending_nn33">Starting out</A></LI>
47654 <LI><A href="#Extending_nn34">Command line options</A></LI>
47655 <LI><A href="#Extending_nn35">Configuration and preprocessing</A></LI>
47656 <LI><A href="#Extending_nn36">Entry point to code generation</A></LI>
47657 <LI><A href="#Extending_nn37">Module I/O and wrapper skeleton</A></LI>
47658 <LI><A href="#Extending_nn38">Low-level code generators</A></LI>
47659 <LI><A href="#Extending_nn39">Configuration files</A></LI>
47660 <LI><A href="#Extending_nn40">Runtime support</A></LI>
47661 <LI><A href="#Extending_nn41">Standard library files</A></LI>
47662 <LI><A href="#Extending_nn42">Examples and test cases</A></LI>
47663 <LI><A href="#Extending_nn43">Documentation</A></LI>
47664 <LI><A href="#Extending_prerequisites">Prerequisites for adding a new
47665  language module to the SWIG distribution</A></LI>
47666 <LI><A href="#Extending_coding_style_guidelines">Coding style guidelines</A>
47667 </LI>
47668 </UL>
47669 </LI>
47670 <LI><A href="#Extending_nn44">Typemaps</A>
47671 <UL>
47672 <LI><A href="#Extending_nn45">Proxy classes</A></LI>
47673 </UL>
47674 </LI>
47675 <LI><A href="#Extending_nn46">Guide to parse tree nodes</A></LI>
47676 </UL>
47677 </DIV>
47678 <!-- INDEX -->
47679 <H2><A name="Extending_nn2"></A>35.1 Introduction</H2>
47680 <P> This chapter describes SWIG's internal organization and the process
47681  by which new target languages can be developed. First, a brief word of
47682  warning---SWIG is continually evolving. The information in this chapter
47683  is mostly up to date, but changes are ongoing. Expect a few
47684  inconsistencies.</P>
47685 <P> Also, this chapter is not meant to be a hand-holding tutorial. As a
47686  starting point, you should probably look at one of SWIG's existing
47687  modules.</P>
47688 <H2><A name="Extending_nn3"></A>35.2 Prerequisites</H2>
47689 <P> In order to extend SWIG, it is useful to have the following
47690  background:</P>
47691 <UL>
47692 <LI>An understanding of the C API for the target language.</LI>
47693 <LI>A good grasp of the C++ type system.</LI>
47694 <LI>An understanding of typemaps and some of SWIG's advanced features.</LI>
47695 <LI>Some familiarity with writing C++ (language modules are currently
47696  written in C++).</LI>
47697 </UL>
47698 <P> Since SWIG is essentially a specialized C++ compiler, it may be
47699  useful to have some prior experience with compiler design (perhaps even
47700  a compilers course) to better understand certain parts of the system. A
47701  number of books will also be useful. For example, &quot;The C Programming
47702  Language&quot; by Kernighan and Ritchie (a.k.a, &quot;K&amp;R&quot;) and the C++ standard,
47703  &quot;ISO/IEC 14882 Programming Languages - C++&quot; will be of great use.</P>
47704 <P> Also, it is useful to keep in mind that SWIG primarily operates as
47705  an extension of the C++<EM> type</EM> system. At first glance, this
47706  might not be obvious, but almost all SWIG directives as well as the
47707  low-level generation of wrapper code are driven by C++ datatypes.</P>
47708 <H2><A name="Extending_nn4"></A>35.3 The Big Picture</H2>
47709 <P> SWIG is a special purpose compiler that parses C++ declarations to
47710  generate wrapper code. To make this conversion possible, SWIG makes
47711  three fundamental extensions to the C++ language:</P>
47712 <UL>
47713 <LI><B>Typemaps</B>. Typemaps are used to define the
47714  conversion/marshalling behavior of specific C++ datatypes. All type
47715  conversion in SWIG is based on typemaps. Furthermore, the association
47716  of typemaps to datatypes utilizes an advanced pattern matching
47717  mechanism that is fully integrated with the C++ type system.</LI>
47718 <LI><B>Declaration Annotation</B>. To customize wrapper code generation,
47719  most declarations can be annotated with special features. For example,
47720  you can make a variable read-only, you can ignore a declaration, you
47721  can rename a member function, you can add exception handling, and so
47722  forth. Virtually all of these customizations are built on top of a
47723  low-level declaration annotator that can attach arbitrary attributes to
47724  any declaration. Code generation modules can look for these attributes
47725  to guide the wrapping process.</LI>
47726 <LI><B>Class extension</B>. SWIG allows classes and structures to be
47727  extended with new methods and attributes (the <TT>%extend</TT>
47728  directive). This has the effect of altering the API in the target
47729  language and can be used to generate OO interfaces to C libraries.</LI>
47730 </UL>
47731 <P> It is important to emphasize that virtually all SWIG features reduce
47732  to one of these three fundamental concepts. The type system and pattern
47733  matching rules also play a critical role in making the system work. For
47734  example, both typemaps and declaration annotation are based on pattern
47735  matching and interact heavily with the underlying type system.</P>
47736 <H2><A name="Extending_nn5"></A>35.4 Execution Model</H2>
47737 <P> When you run SWIG on an interface, processing is handled in stages
47738  by a series of system components:</P>
47739 <UL>
47740 <LI>An integrated C preprocessor reads a collection of configuration
47741  files and the specified interface file into memory. The preprocessor
47742  performs the usual functions including macro expansion and file
47743  inclusion. However, the preprocessor also performs some transformations
47744  of the interface. For instance, <TT>#define</TT> statements are
47745  sometimes transformed into <TT>%constant</TT> declarations. In
47746  addition, information related to file/line number tracking is inserted.</LI>
47747 <LI>A C/C++ parser reads the preprocessed input and generates a full
47748  parse tree of all of the SWIG directives and C declarations found. The
47749  parser is responsible for many aspects of the system including
47750  renaming, declaration annotation, and template expansion. However, the
47751  parser does not produce any output nor does it interact with the target
47752  language module as it runs. SWIG is not a one-pass compiler.</LI>
47753 <LI>A type-checking pass is made. This adjusts all of the C++ typenames
47754  to properly handle namespaces, typedefs, nested classes, and other
47755  issues related to type scoping.</LI>
47756 <LI>A semantic pass is made on the parse tree to collect information
47757  related to properties of the C++ interface. For example, this pass
47758  would determine whether or not a class allows a default constructor.</LI>
47759 <LI>A code generation pass is made using a specific target language
47760  module. This phase is responsible for generating the actual wrapper
47761  code. All of SWIG's user-defined modules are invoked during this latter
47762  stage of compilation.</LI>
47763 </UL>
47764 <P> The next few sections briefly describe some of these stages.</P>
47765 <H3><A name="Extending_nn6"></A>35.4.1 Preprocessing</H3>
47766 <P> The preprocessor plays a critical role in the SWIG implementation.
47767  This is because a lot of SWIG's processing and internal configuration
47768  is managed not by code written in C, but by configuration files in the
47769  SWIG library. In fact, when you run SWIG, parsing starts with a small
47770  interface file like this (note: this explains the cryptic error
47771  messages that new users sometimes get when SWIG is misconfigured or
47772  installed incorrectly):</P>
47773 <DIV class="code">
47774 <PRE>
47775 %include &quot;swig.swg&quot;             // Global SWIG configuration
47776 %include &quot;<EM>langconfig.swg</EM>&quot;       // Language specific configuration
47777 %include &quot;yourinterface.i&quot;      // Your interface file
47778 </PRE>
47779 </DIV>
47780 <P> The <TT>swig.swg</TT> file contains global configuration
47781  information. In addition, this file defines many of SWIG's standard
47782  directives as macros. For instance, part of of <TT>swig.swg</TT> looks
47783  like this:</P>
47784 <DIV class="code">
47785 <PRE>
47786 ...
47787 /* Code insertion directives such as %wrapper %{ ... %} */
47788
47789 #define %begin       %insert(&quot;begin&quot;)
47790 #define %runtime     %insert(&quot;runtime&quot;)
47791 #define %header      %insert(&quot;header&quot;)
47792 #define %wrapper     %insert(&quot;wrapper&quot;)
47793 #define %init        %insert(&quot;init&quot;)
47794
47795 /* Access control directives */
47796
47797 #define %immutable   %feature(&quot;immutable&quot;,&quot;1&quot;)
47798 #define %mutable     %feature(&quot;immutable&quot;)
47799
47800 /* Directives for callback functions */
47801
47802 #define %callback(x) %feature(&quot;callback&quot;) `x`;
47803 #define %nocallback  %feature(&quot;callback&quot;);
47804
47805 /* %ignore directive */
47806
47807 #define %ignore         %rename($ignore)
47808 #define %ignorewarn(x)  %rename(&quot;$ignore:&quot; x)
47809 ...
47810 </PRE>
47811 </DIV>
47812 <P> The fact that most of the standard SWIG directives are macros is
47813  intended to simplify the implementation of the internals. For instance,
47814  rather than having to support dozens of special directives, it is
47815  easier to have a few basic primitives such as <TT>%feature</TT> or <TT>
47816 %insert</TT>.</P>
47817 <P> The<EM> <TT>langconfig.swg</TT></EM> file is supplied by the target
47818  language. This file contains language-specific configuration
47819  information. More often than not, this file provides run-time wrapper
47820  support code (e.g., the type-checker) as well as a collection of
47821  typemaps that define the default wrapping behavior. Note: the name of
47822  this file depends on the target language and is usually something like <TT>
47823 python.swg</TT> or <TT>perl5.swg</TT>.</P>
47824 <P> As a debugging aide, the text that SWIG feeds to its C++ parser can
47825  be obtained by running <TT>swig -E interface.i</TT>. This output
47826  probably isn't too useful in general, but it will show how macros have
47827  been expanded as well as everything else that goes into the low-level
47828  construction of the wrapper code.</P>
47829 <H3><A name="Extending_nn7"></A>35.4.2 Parsing</H3>
47830 <P> The current C++ parser handles a subset of C++. Most
47831  incompatibilities with C are due to subtle aspects of how SWIG parses
47832  declarations. Specifically, SWIG expects all C/C++ declarations to
47833  follow this general form:</P>
47834 <DIV class="diagram">
47835 <PRE>
47836 <EM>storage</EM> <EM>type</EM> <EM>declarator</EM> <EM>initializer</EM>;
47837 </PRE>
47838 </DIV>
47839 <P> <TT><EM>storage</EM></TT> is a keyword such as <TT>extern</TT>, <TT>
47840 static</TT>, <TT>typedef</TT>, or <TT>virtual</TT>. <TT><EM>type</EM></TT>
47841  is a primitive datatype such as <TT>int</TT> or <TT>void</TT>. <TT><EM>
47842 type</EM></TT> may be optionally qualified with a qualifier such as <TT>
47843 const</TT> or <TT>volatile</TT>. <TT><EM>declarator</EM></TT> is a name
47844  with additional type-construction modifiers attached to it (pointers,
47845  arrays, references, functions, etc.). Examples of declarators include <TT>
47846 *x</TT>, <TT>**x</TT>, <TT>x[20]</TT>, and <TT>(*x)(int,double)</TT>.
47847  The <TT><EM>initializer</EM></TT> may be a value assigned using <TT>=</TT>
47848  or body of code enclosed in braces <TT>{ ... }</TT>.</P>
47849 <P> This declaration format covers most common C++ declarations.
47850  However, the C++ standard is somewhat more flexible in the placement of
47851  the parts. For example, it is technically legal, although uncommon to
47852  write something like <TT>int typedef const a</TT> in your program. SWIG
47853  simply doesn't bother to deal with this case.</P>
47854 <P> The other significant difference between C++ and SWIG is in the
47855  treatment of typenames. In C++, if you have a declaration like this,</P>
47856 <DIV class="code">
47857 <PRE>
47858 int blah(Foo *x, Bar *y);
47859 </PRE>
47860 </DIV>
47861 <P> it won't parse correctly unless <TT>Foo</TT> and <TT>Bar</TT> have
47862  been previously defined as types either using a <TT>class</TT>
47863  definition or a <TT>typedef</TT>. The reasons for this are subtle, but
47864  this treatment of typenames is normally integrated at the level of the
47865  C tokenizer---when a typename appears, a different token is returned to
47866  the parser instead of an identifier.</P>
47867 <P> SWIG does not operate in this manner--any legal identifier can be
47868  used as a type name. The reason for this is primarily motivated by the
47869  use of SWIG with partially defined data. Specifically, SWIG is supposed
47870  to be easy to use on interfaces with missing type information.</P>
47871 <P> Because of the different treatment of typenames, the most serious
47872  limitation of the SWIG parser is that it can't process type
47873  declarations where an extra (and unnecessary) grouping operator is
47874  used. For example:</P>
47875 <DIV class="code">
47876 <PRE>
47877 int (x);         /* A variable x */
47878 int (y)(int);    /* A function y */
47879 </PRE>
47880 </DIV>
47881 <P> The placing of extra parentheses in type declarations like this is
47882  already recognized by the C++ community as a potential source of
47883  strange programming errors. For example, Scott Meyers &quot;Effective STL&quot;
47884  discusses this problem in a section on avoiding C++'s &quot;most vexing
47885  parse.&quot;</P>
47886 <P> The parser is also unable to handle declarations with no return type
47887  or bare argument names. For example, in an old C program, you might see
47888  things like this:</P>
47889 <DIV class="code">
47890 <PRE>
47891 foo(a,b) {
47892 ...
47893 }
47894 </PRE>
47895 </DIV>
47896 <P> In this case, the return type as well as the types of the arguments
47897  are taken by the C compiler to be an <TT>int</TT>. However, SWIG
47898  interprets the above code as an abstract declarator for a function
47899  returning a <TT>foo</TT> and taking types <TT>a</TT> and <TT>b</TT> as
47900  arguments).</P>
47901 <H3><A name="Extending_nn8"></A>35.4.3 Parse Trees</H3>
47902 <P> The SWIG parser produces a complete parse tree of the input file
47903  before any wrapper code is actually generated. Each item in the tree is
47904  known as a &quot;Node&quot;. Each node is identified by a symbolic tag.
47905  Furthermore, a node may have an arbitrary number of children. The parse
47906  tree structure and tag names of an interface can be displayed using <TT>
47907 swig -debug-tags</TT>. For example:</P>
47908 <DIV class="shell">
47909 <PRE>
47910 $ <B>swig -c++ -python -debug-tags example.i</B>
47911  . top (example.i:1)
47912  . top . include (example.i:1)
47913  . top . include . typemap (/r0/beazley/Projects/lib/swig1.3/swig.swg:71)
47914  . top . include . typemap . typemapitem (/r0/beazley/Projects/lib/swig1.3/swig.swg:71)
47915  . top . include . typemap (/r0/beazley/Projects/lib/swig1.3/swig.swg:83)
47916  . top . include . typemap . typemapitem (/r0/beazley/Projects/lib/swig1.3/swig.swg:83)
47917  . top . include (example.i:4)
47918  . top . include . insert (/r0/beazley/Projects/lib/swig1.3/python/python.swg:7)
47919  . top . include . insert (/r0/beazley/Projects/lib/swig1.3/python/python.swg:8)
47920  . top . include . typemap (/r0/beazley/Projects/lib/swig1.3/python/python.swg:19)
47921 ...
47922  . top . include (example.i:6)
47923  . top . include . module (example.i:2)
47924  . top . include . insert (example.i:6)
47925  . top . include . include (example.i:9)
47926  . top . include . include . class (example.h:3)
47927  . top . include . include . class . access (example.h:4)
47928  . top . include . include . class . constructor (example.h:7)
47929  . top . include . include . class . destructor (example.h:10)
47930  . top . include . include . class . cdecl (example.h:11)
47931  . top . include . include . class . cdecl (example.h:11)
47932  . top . include . include . class . cdecl (example.h:12)
47933  . top . include . include . class . cdecl (example.h:13)
47934  . top . include . include . class . cdecl (example.h:14)
47935  . top . include . include . class . cdecl (example.h:15)
47936  . top . include . include . class (example.h:18)
47937  . top . include . include . class . access (example.h:19)
47938  . top . include . include . class . cdecl (example.h:20)
47939  . top . include . include . class . access (example.h:21)
47940  . top . include . include . class . constructor (example.h:22)
47941  . top . include . include . class . cdecl (example.h:23)
47942  . top . include . include . class . cdecl (example.h:24)
47943  . top . include . include . class (example.h:27)
47944  . top . include . include . class . access (example.h:28)
47945  . top . include . include . class . cdecl (example.h:29)
47946  . top . include . include . class . access (example.h:30)
47947  . top . include . include . class . constructor (example.h:31)
47948  . top . include . include . class . cdecl (example.h:32)
47949  . top . include . include . class . cdecl (example.h:33)
47950 </PRE>
47951 </DIV>
47952 <P> Even for the most simple interface, the parse tree structure is
47953  larger than you might expect. For example, in the above output, a
47954  substantial number of nodes are actually generated by the <TT>
47955 python.swg</TT> configuration file which defines typemaps and other
47956  directives. The contents of the user-supplied input file don't appear
47957  until the end of the output.</P>
47958 <P> The contents of each parse tree node consist of a collection of
47959  attribute/value pairs. Internally, the nodes are simply represented by
47960  hash tables. A display of the entire parse-tree structure can be
47961  obtained using <TT>swig -debug-top &lt;n&gt;</TT>, where <TT>n</TT> is the
47962  stage being processed. There are a number of other parse tree display
47963  options, for example, <TT>swig -debug-module &lt;n&gt;</TT> will avoid
47964  displaying system parse information and only display the parse tree
47965  pertaining to the user's module at stage <TT>n</TT> of processing.</P>
47966 <DIV class="shell">
47967 <PRE>
47968 $ swig -c++ -python -debug-module 4 example.i
47969       +++ include ----------------------------------------
47970       | name         - &quot;example.i&quot;
47971
47972             +++ module ----------------------------------------
47973             | name         - &quot;example&quot;
47974             |
47975             +++ insert ----------------------------------------
47976             | code         - &quot;\n#include \&quot;example.h\&quot;\n&quot;
47977             |
47978             +++ include ----------------------------------------
47979             | name         - &quot;example.h&quot;
47980
47981                   +++ class ----------------------------------------
47982                   | abstract     - &quot;1&quot;
47983                   | sym:name     - &quot;Shape&quot;
47984                   | name         - &quot;Shape&quot;
47985                   | kind         - &quot;class&quot;
47986                   | symtab       - 0x40194140
47987                   | sym:symtab   - 0x40191078
47988
47989                         +++ access ----------------------------------------
47990                         | kind         - &quot;public&quot;
47991                         |
47992                         +++ constructor ----------------------------------------
47993                         | sym:name     - &quot;Shape&quot;
47994                         | name         - &quot;Shape&quot;
47995                         | decl         - &quot;f().&quot;
47996                         | code         - &quot;{\n    nshapes++;\n  }&quot;
47997                         | sym:symtab   - 0x40194140
47998                         |
47999                         +++ destructor ----------------------------------------
48000                         | sym:name     - &quot;~Shape&quot;
48001                         | name         - &quot;~Shape&quot;
48002                         | storage      - &quot;virtual&quot;
48003                         | code         - &quot;{\n    nshapes--;\n  }&quot;
48004                         | sym:symtab   - 0x40194140
48005                         |
48006                         +++ cdecl ----------------------------------------
48007                         | sym:name     - &quot;x&quot;
48008                         | name         - &quot;x&quot;
48009                         | decl         - &quot;&quot;
48010                         | type         - &quot;double&quot;
48011                         | sym:symtab   - 0x40194140
48012                         |
48013                         +++ cdecl ----------------------------------------
48014                         | sym:name     - &quot;y&quot;
48015                         | name         - &quot;y&quot;
48016                         | decl         - &quot;&quot;
48017                         | type         - &quot;double&quot;
48018                         | sym:symtab   - 0x40194140
48019                         |
48020                         +++ cdecl ----------------------------------------
48021                         | sym:name     - &quot;move&quot;
48022                         | name         - &quot;move&quot;
48023                         | decl         - &quot;f(double,double).&quot;
48024                         | parms        - double ,double
48025                         | type         - &quot;void&quot;
48026                         | sym:symtab   - 0x40194140
48027                         |
48028                         +++ cdecl ----------------------------------------
48029                         | sym:name     - &quot;area&quot;
48030                         | name         - &quot;area&quot;
48031                         | decl         - &quot;f(void).&quot;
48032                         | parms        - void
48033                         | storage      - &quot;virtual&quot;
48034                         | value        - &quot;0&quot;
48035                         | type         - &quot;double&quot;
48036                         | sym:symtab   - 0x40194140
48037                         |
48038                         +++ cdecl ----------------------------------------
48039                         | sym:name     - &quot;perimeter&quot;
48040                         | name         - &quot;perimeter&quot;
48041                         | decl         - &quot;f(void).&quot;
48042                         | parms        - void
48043                         | storage      - &quot;virtual&quot;
48044                         | value        - &quot;0&quot;
48045                         | type         - &quot;double&quot;
48046                         | sym:symtab   - 0x40194140
48047                         |
48048                         +++ cdecl ----------------------------------------
48049                         | sym:name     - &quot;nshapes&quot;
48050                         | name         - &quot;nshapes&quot;
48051                         | decl         - &quot;&quot;
48052                         | storage      - &quot;static&quot;
48053                         | type         - &quot;int&quot;
48054                         | sym:symtab   - 0x40194140
48055                         |
48056                   +++ class ----------------------------------------
48057                   | sym:name     - &quot;Circle&quot;
48058                   | name         - &quot;Circle&quot;
48059                   | kind         - &quot;class&quot;
48060                   | bases        - 0x40194510
48061                   | symtab       - 0x40194538
48062                   | sym:symtab   - 0x40191078
48063
48064                         +++ access ----------------------------------------
48065                         | kind         - &quot;private&quot;
48066                         |
48067                         +++ cdecl ----------------------------------------
48068                         | name         - &quot;radius&quot;
48069                         | decl         - &quot;&quot;
48070                         | type         - &quot;double&quot;
48071                         |
48072                         +++ access ----------------------------------------
48073                         | kind         - &quot;public&quot;
48074                         |
48075                         +++ constructor ----------------------------------------
48076                         | sym:name     - &quot;Circle&quot;
48077                         | name         - &quot;Circle&quot;
48078                         | parms        - double
48079                         | decl         - &quot;f(double).&quot;
48080                         | code         - &quot;{ }&quot;
48081                         | sym:symtab   - 0x40194538
48082                         |
48083                         +++ cdecl ----------------------------------------
48084                         | sym:name     - &quot;area&quot;
48085                         | name         - &quot;area&quot;
48086                         | decl         - &quot;f(void).&quot;
48087                         | parms        - void
48088                         | storage      - &quot;virtual&quot;
48089                         | type         - &quot;double&quot;
48090                         | sym:symtab   - 0x40194538
48091                         |
48092                         +++ cdecl ----------------------------------------
48093                         | sym:name     - &quot;perimeter&quot;
48094                         | name         - &quot;perimeter&quot;
48095                         | decl         - &quot;f(void).&quot;
48096                         | parms        - void
48097                         | storage      - &quot;virtual&quot;
48098                         | type         - &quot;double&quot;
48099                         | sym:symtab   - 0x40194538
48100                         |
48101                   +++ class ----------------------------------------
48102                   | sym:name     - &quot;Square&quot;
48103                   | name         - &quot;Square&quot;
48104                   | kind         - &quot;class&quot;
48105                   | bases        - 0x40194760
48106                   | symtab       - 0x40194788
48107                   | sym:symtab   - 0x40191078
48108
48109                         +++ access ----------------------------------------
48110                         | kind         - &quot;private&quot;
48111                         |
48112                         +++ cdecl ----------------------------------------
48113                         | name         - &quot;width&quot;
48114                         | decl         - &quot;&quot;
48115                         | type         - &quot;double&quot;
48116                         |
48117                         +++ access ----------------------------------------
48118                         | kind         - &quot;public&quot;
48119                         |
48120                         +++ constructor ----------------------------------------
48121                         | sym:name     - &quot;Square&quot;
48122                         | name         - &quot;Square&quot;
48123                         | parms        - double
48124                         | decl         - &quot;f(double).&quot;
48125                         | code         - &quot;{ }&quot;
48126                         | sym:symtab   - 0x40194788
48127                         |
48128                         +++ cdecl ----------------------------------------
48129                         | sym:name     - &quot;area&quot;
48130                         | name         - &quot;area&quot;
48131                         | decl         - &quot;f(void).&quot;
48132                         | parms        - void
48133                         | storage      - &quot;virtual&quot;
48134                         | type         - &quot;double&quot;
48135                         | sym:symtab   - 0x40194788
48136                         |
48137                         +++ cdecl ----------------------------------------
48138                         | sym:name     - &quot;perimeter&quot;
48139                         | name         - &quot;perimeter&quot;
48140                         | decl         - &quot;f(void).&quot;
48141                         | parms        - void
48142                         | storage      - &quot;virtual&quot;
48143                         | type         - &quot;double&quot;
48144                         | sym:symtab   - 0x40194788
48145 </PRE>
48146 </DIV>
48147 <H3><A name="Extending_nn9"></A>35.4.4 Attribute namespaces</H3>
48148 <P> Attributes of parse tree nodes are often prepended with a namespace
48149  qualifier. For example, the attributes <TT>sym:name</TT> and <TT>
48150 sym:symtab</TT> are attributes related to symbol table management and
48151  are prefixed with <TT>sym:</TT>. As a general rule, only those
48152  attributes which are directly related to the raw declaration appear
48153  without a prefix (type, name, declarator, etc.).</P>
48154 <P> Target language modules may add additional attributes to nodes to
48155  assist the generation of wrapper code. The convention for doing this is
48156  to place these attributes in a namespace that matches the name of the
48157  target language. For example, <TT>python:foo</TT> or <TT>perl:foo</TT>.</P>
48158 <H3><A name="Extending_nn10"></A>35.4.5 Symbol Tables</H3>
48159 <P> During parsing, all symbols are managed in the space of the target
48160  language. The <TT>sym:name</TT> attribute of each node contains the
48161  symbol name selected by the parser. Normally, <TT>sym:name</TT> and <TT>
48162 name</TT> are the same. However, the <TT>%rename</TT> directive can be
48163  used to change the value of <TT>sym:name</TT>. You can see the effect
48164  of <TT>%rename</TT> by trying it on a simple interface and dumping the
48165  parse tree. For example:</P>
48166 <DIV class="code">
48167 <PRE>
48168 %rename(foo_i) foo(int);
48169 %rename(foo_d) foo(double);
48170
48171 void foo(int);
48172 void foo(double);
48173 void foo(Bar *b);
48174 </PRE>
48175 </DIV>
48176 <P> There are various <TT>debug-</TT> options that can be useful for
48177  debugging and analysing the parse tree. For example, the <TT>debug-top
48178  &lt;n&gt;</TT> or <TT>debug-module &lt;n&gt;</TT> options will dump the entire/top
48179  of the parse tree or the module subtree at one of the four <TT>n</TT>
48180  stages of processing. The parse tree can be viewed after the final
48181  stage of processing by running SWIG:</P>
48182 <DIV class="shell">
48183 <PRE>
48184 $ swig -debug-top 4 example.i
48185 ...
48186             +++ cdecl ----------------------------------------
48187             | sym:name     - &quot;foo_i&quot;
48188             | name         - &quot;foo&quot;
48189             | decl         - &quot;f(int).&quot;
48190             | parms        - int
48191             | type         - &quot;void&quot;
48192             | sym:symtab   - 0x40165078
48193             |
48194             +++ cdecl ----------------------------------------
48195             | sym:name     - &quot;foo_d&quot;
48196             | name         - &quot;foo&quot;
48197             | decl         - &quot;f(double).&quot;
48198             | parms        - double
48199             | type         - &quot;void&quot;
48200             | sym:symtab   - 0x40165078
48201             |
48202             +++ cdecl ----------------------------------------
48203             | sym:name     - &quot;foo&quot;
48204             | name         - &quot;foo&quot;
48205             | decl         - &quot;f(p.Bar).&quot;
48206             | parms        - Bar *
48207             | type         - &quot;void&quot;
48208             | sym:symtab   - 0x40165078
48209 </PRE>
48210 </DIV>
48211 <P> All symbol-related conflicts and complaints about overloading are
48212  based on <TT>sym:name</TT> values. For instance, the following example
48213  uses <TT>%rename</TT> in reverse to generate a name clash.</P>
48214 <DIV class="code">
48215 <PRE>
48216 %rename(foo) foo_i(int);
48217 %rename(foo) foo_d(double;
48218
48219 void foo_i(int);
48220 void foo_d(double);
48221 void foo(Bar *b);
48222 </PRE>
48223 </DIV>
48224 <P> When you run SWIG on this you now get:</P>
48225 <DIV class="shell">
48226 <PRE>
48227 $ ./swig example.i
48228 example.i:6. Overloaded declaration ignored.  foo_d(double )
48229 example.i:5. Previous declaration is foo_i(int )
48230 example.i:7. Overloaded declaration ignored.  foo(Bar *)
48231 example.i:5. Previous declaration is foo_i(int )
48232 </PRE>
48233 </DIV>
48234 <H3><A name="Extending_nn11"></A>35.4.6 The %feature directive</H3>
48235 <P> A number of SWIG directives such as <TT>%exception</TT> are
48236  implemented using the low-level <TT>%feature</TT> directive. For
48237  example:</P>
48238 <DIV class="code">
48239 <PRE>
48240 %feature(&quot;except&quot;) getitem(int) {
48241   try {
48242      $action
48243   } catch (badindex) {
48244      ...
48245   }
48246 }
48247
48248 ...
48249 class Foo {
48250 public:
48251     Object *getitem(int index) throws(badindex);
48252     ...
48253 };
48254 </PRE>
48255 </DIV>
48256 <P> The behavior of <TT>%feature</TT> is very easy to describe--it
48257  simply attaches a new attribute to any parse tree node that matches the
48258  given prototype. When a feature is added, it shows up as an attribute
48259  in the <TT>feature:</TT> namespace. You can see this when running with
48260  the <TT>-debug-top 4</TT> option. For example:</P>
48261 <DIV class="shell">
48262 <PRE>
48263  +++ cdecl ----------------------------------------
48264  | sym:name     - &quot;getitem&quot;
48265  | name         - &quot;getitem&quot;
48266  | decl         - &quot;f(int).p.&quot;
48267  | parms        - int
48268  | type         - &quot;Object&quot;
48269  | feature:except - &quot;{\n    try {\n       $action\n    } catc...&quot;
48270  | sym:symtab   - 0x40168ac8
48271  |
48272 </PRE>
48273 </DIV>
48274 <P> Feature names are completely arbitrary and a target language module
48275  can be programmed to respond to any feature name that it wants to
48276  recognize. The data stored in a feature attribute is usually just a raw
48277  unparsed string. For example, the exception code above is simply stored
48278  without any modifications.</P>
48279 <H3><A name="Extending_nn12"></A>35.4.7 Code Generation</H3>
48280 <P> Language modules work by defining handler functions that know how to
48281  respond to different types of parse-tree nodes. These handlers simply
48282  look at the attributes of each node in order to produce low-level code.</P>
48283 <P> In reality, the generation of code is somewhat more subtle than
48284  simply invoking handler functions. This is because parse-tree nodes
48285  might be transformed. For example, suppose you are wrapping a class
48286  like this:</P>
48287 <DIV class="code">
48288 <PRE>
48289 class Foo {
48290 public:
48291     virtual int *bar(int x);
48292 };
48293 </PRE>
48294 </DIV>
48295 <P> When the parser constructs a node for the member <TT>bar</TT>, it
48296  creates a raw &quot;cdecl&quot; node with the following attributes:</P>
48297 <DIV class="diagram">
48298 <PRE>
48299 nodeType    : cdecl
48300 name        : bar
48301 type        : int
48302 decl        : f(int).p
48303 parms       : int x
48304 storage     : virtual
48305 sym:name    : bar
48306 </PRE>
48307 </DIV>
48308 <P> To produce wrapper code, this &quot;cdecl&quot; node undergoes a number of
48309  transformations. First, the node is recognized as a function
48310  declaration. This adjusts some of the type information--specifically,
48311  the declarator is joined with the base datatype to produce this:</P>
48312 <DIV class="diagram">
48313 <PRE>
48314 nodeType    : cdecl
48315 name        : bar
48316 type        : p.int        &lt;-- Notice change in return type
48317 decl        : f(int).p
48318 parms       : int x
48319 storage     : virtual
48320 sym:name    : bar
48321 </PRE>
48322 </DIV>
48323 <P> Next, the context of the node indicates that the node is really a
48324  member function. This produces a transformation to a low-level accessor
48325  function like this:</P>
48326 <DIV class="diagram">
48327 <PRE>
48328 nodeType    : cdecl
48329 name        : bar
48330 type        : int.p
48331 decl        : f(int).p
48332 parms       : Foo *self, int x            &lt;-- Added parameter
48333 storage     : virtual
48334 wrap:action : result = (arg1)-&gt;bar(arg2)  &lt;-- Action code added
48335 sym:name    : Foo_bar                     &lt;-- Symbol name changed
48336 </PRE>
48337 </DIV>
48338 <P> In this transformation, notice how an additional parameter was added
48339  to the parameter list and how the symbol name of the node has suddenly
48340  changed into an accessor using the naming scheme described in the &quot;SWIG
48341  Basics&quot; chapter. A small fragment of &quot;action&quot; code has also been
48342  generated--notice how the <TT>wrap:action</TT> attribute defines the
48343  access to the underlying method. The data in this transformed node is
48344  then used to generate a wrapper.</P>
48345 <P> Language modules work by registering handler functions for dealing
48346  with various types of nodes at different stages of transformation. This
48347  is done by inheriting from a special <TT>Language</TT> class and
48348  defining a collection of virtual methods. For example, the Python
48349  module defines a class as follows:</P>
48350 <DIV class="code">
48351 <PRE>
48352 class PYTHON : public Language {
48353 protected:
48354 public :
48355   virtual void main(int, char *argv[]);
48356   virtual int  top(Node *);
48357   virtual int  functionWrapper(Node *);
48358   virtual int  constantWrapper(Node *);
48359   virtual int  variableWrapper(Node *);
48360   virtual int  nativeWrapper(Node *);
48361   virtual int  membervariableHandler(Node *);
48362   virtual int  memberconstantHandler(Node *);
48363   virtual int  memberfunctionHandler(Node *);
48364   virtual int  constructorHandler(Node *);
48365   virtual int  destructorHandler(Node *);
48366   virtual int  classHandler(Node *);
48367   virtual int  classforwardDeclaration(Node *);
48368   virtual int  insertDirective(Node *);
48369   virtual int  importDirective(Node *);
48370 };
48371 </PRE>
48372 </DIV>
48373 <P> The role of these functions is described shortly.</P>
48374 <H3><A name="Extending_nn13"></A>35.4.8 SWIG and XML</H3>
48375 <P> Much of SWIG's current parser design was originally motivated by
48376  interest in using XML to represent SWIG parse trees. Although XML is
48377  not currently used in any direct manner, the parse tree structure, use
48378  of node tags, attributes, and attribute namespaces are all influenced
48379  by aspects of XML parsing. Therefore, in trying to understand SWIG's
48380  internal data structures, it may be useful to keep XML in the back of
48381  your mind as a model.</P>
48382 <H2><A name="Extending_nn14"></A>35.5 Primitive Data Structures</H2>
48383 <P> Most of SWIG is constructed using three basic data structures:
48384  strings, hashes, and lists. These data structures are dynamic in same
48385  way as similar structures found in many scripting languages. For
48386  instance, you can have containers (lists and hash tables) of mixed
48387  types and certain operations are polymorphic.</P>
48388 <P> This section briefly describes the basic structures so that later
48389  sections of this chapter make more sense.</P>
48390 <P> When describing the low-level API, the following type name
48391  conventions are used:</P>
48392 <UL>
48393 <LI><TT>String</TT>. A string object.</LI>
48394 <LI><TT>Hash</TT>. A hash object.</LI>
48395 <LI><TT>List</TT>. A list object.</LI>
48396 <LI><TT>String_or_char</TT>. A string object or a <TT>char *</TT>.</LI>
48397 <LI><TT>Object_or_char</TT>. An object or a <TT>char *</TT>.</LI>
48398 <LI><TT>Object</TT>. Any object (string, hash, list, etc.)</LI>
48399 </UL>
48400 <P> In most cases, other typenames in the source are aliases for one of
48401  these primitive types. Specifically:</P>
48402 <DIV class="code">
48403 <PRE>
48404 typedef String SwigType;
48405 typedef Hash   Parm;
48406 typedef Hash   ParmList;
48407 typedef Hash   Node;
48408 typedef Hash   Symtab;
48409 typedef Hash   Typetab;
48410 </PRE>
48411 </DIV>
48412 <H3><A name="Extending_nn15"></A>35.5.1 Strings</H3>
48413 <P><B> <TT>String *NewString(const String_or_char *val)</TT></B></P>
48414 <DIV class="indent"> Creates a new string with initial value <TT>val</TT>
48415 . <TT>val</TT> may be a <TT>char *</TT> or another <TT>String</TT>
48416  object. If you want to create an empty string, use &quot;&quot; for val.</DIV>
48417 <P><B> <TT>String *NewStringf(const char *fmt, ...)</TT></B></P>
48418 <DIV class="indent"> Creates a new string whose initial value is set
48419  according to a C <TT>printf</TT> style format string in <TT>fmt</TT>.
48420  Additional arguments follow depending on <TT>fmt</TT>.</DIV>
48421 <P><B> <TT>String *Copy(String *s)</TT></B></P>
48422 <DIV class="indent"> Make a copy of the string <TT>s</TT>.</DIV>
48423 <P><B> <TT>void Delete(String *s)</TT></B></P>
48424 <DIV class="indent"> Deletes <TT>s</TT>.</DIV>
48425 <P><B> <TT>int Len(const String_or_char *s)</TT></B></P>
48426 <DIV class="indent"> Returns the length of the string.</DIV>
48427 <P><B> <TT>char *Char(const String_or_char *s)</TT></B></P>
48428 <DIV class="indent"> Returns a pointer to the first character in a
48429  string.</DIV>
48430 <P><B> <TT>void Append(String *s, const String_or_char *t)</TT></B></P>
48431 <DIV class="indent"> Appends <TT>t</TT> to the end of string <TT>s</TT>.</DIV>
48432 <P><B> <TT>void Insert(String *s, int pos, const String_or_char *t)</TT></B>
48433 </P>
48434 <DIV class="indent"> Inserts <TT>t</TT> into <TT>s</TT> at position <TT>
48435 pos</TT>. The contents of <TT>s</TT> are shifted accordingly. The
48436  special value <TT>DOH_END</TT> can be used for <TT>pos</TT> to indicate
48437  insertion at the end of the string (appending).</DIV>
48438 <P><B> <TT>int Strcmp(const String_or_char *s, const String_or_char *t)</TT>
48439 </B></P>
48440 <DIV class="indent"> Compare strings <TT>s</TT> and <TT>t</TT>. Same as
48441  the C <TT>strcmp()</TT> function.</DIV>
48442 <P><B> <TT>int Strncmp(const String_or_char *s, const String_or_char *t,
48443  int len)</TT></B></P>
48444 <DIV class="indent"> Compare the first <TT>len</TT> characters of
48445  strings <TT>s</TT> and <TT>t</TT>. Same as the C <TT>strncmp()</TT>
48446  function.</DIV>
48447 <P><B> <TT>char *Strstr(const String_or_char *s, const String_or_char
48448  *pat)</TT></B></P>
48449 <DIV class="indent"> Returns a pointer to the first occurrence of <TT>
48450 pat</TT> in <TT>s</TT>. Same as the C <TT>strstr()</TT> function.</DIV>
48451 <P><B> <TT>char *Strchr(const String_or_char *s, char ch)</TT></B></P>
48452 <DIV class="indent"> Returns a pointer to the first occurrence of
48453  character <TT>ch</TT> in <TT>s</TT>. Same as the C <TT>strchr()</TT>
48454  function.</DIV>
48455 <P><B> <TT>void Chop(String *s)</TT></B></P>
48456 <DIV class="indent"> Chops trailing whitespace off the end of <TT>s</TT>
48457 .</DIV>
48458 <P><B> <TT>int Replace(String *s, const String_or_char *pat, const
48459  String_or_char *rep, int flags)</TT></B></P>
48460 <DIV class="indent">
48461 <P> Replaces the pattern <TT>pat</TT> with <TT>rep</TT> in string <TT>s</TT>
48462 . <TT>flags</TT> is a combination of the following flags:</P>
48463 <DIV class="code">
48464 <PRE>
48465 DOH_REPLACE_ANY       - Replace all occurrences
48466 DOH_REPLACE_ID        - Valid C identifiers only
48467 DOH_REPLACE_NOQUOTE   - Don't replace in quoted strings
48468 DOH_REPLACE_FIRST     - Replace first occurrence only.
48469 </PRE>
48470 </DIV>
48471 <P> Returns the number of replacements made (if any).</P>
48472 </DIV>
48473 <H3><A name="Extending_nn16"></A>35.5.2 Hashes</H3>
48474 <P><B> <TT>Hash *NewHash()</TT></B></P>
48475 <DIV class="indent"> Creates a new empty hash table.</DIV>
48476 <P><B> <TT>Hash *Copy(Hash *h)</TT></B></P>
48477 <DIV class="indent"> Make a shallow copy of the hash <TT>h</TT>.</DIV>
48478 <P><B> <TT>void Delete(Hash *h)</TT></B></P>
48479 <DIV class="indent"> Deletes <TT>h</TT>.</DIV>
48480 <P><B> <TT>int Len(Hash *h)</TT></B></P>
48481 <DIV class="indent"> Returns the number of items in <TT>h</TT>.</DIV>
48482 <P><B> <TT>Object *Getattr(Hash *h, const String_or_char *key)</TT></B></P>
48483 <DIV class="indent"> Gets an object from <TT>h</TT>. <TT>key</TT> may be
48484  a string or a simple <TT>char *</TT> string. Returns NULL if not found.</DIV>
48485 <P><B> <TT>int Setattr(Hash *h, const String_or_char *key, const
48486  Object_or_char *val)</TT></B></P>
48487 <DIV class="indent"> Stores <TT>val</TT> in <TT>h</TT>. <TT>key</TT> may
48488  be a string or a simple <TT>char *</TT>. If <TT>val</TT> is not a
48489  standard object (String, Hash, or List) it is assumed to be a <TT>char
48490  *</TT> in which case it is used to construct a <TT>String</TT> that is
48491  stored in the hash. If <TT>val</TT> is NULL, the object is deleted.
48492  Increases the reference count of <TT>val</TT>. Returns 1 if this
48493  operation replaced an existing hash entry, 0 otherwise.</DIV>
48494 <P><B> <TT>int Delattr(Hash *h, const String_or_char *key)</TT></B></P>
48495 <DIV class="indent"> Deletes the hash item referenced by <TT>key</TT>.
48496  Decreases the reference count on the corresponding object (if any).
48497  Returns 1 if an object was removed, 0 otherwise.</DIV>
48498 <P><B> <TT>List *Keys(Hash *h)</TT></B></P>
48499 <DIV class="indent"> Returns the list of hash table keys.</DIV>
48500 <H3><A name="Extending_nn17"></A>35.5.3 Lists</H3>
48501 <P><B> <TT>List *NewList()</TT></B></P>
48502 <DIV class="indent"> Creates a new empty list.</DIV>
48503 <P><B> <TT>List *Copy(List *x)</TT></B></P>
48504 <DIV class="indent"> Make a shallow copy of the List <TT>x</TT>.</DIV>
48505 <P><B> <TT>void Delete(List *x)</TT></B></P>
48506 <DIV class="indent"> Deletes <TT>x</TT>.</DIV>
48507 <P><B> <TT>int Len(List *x)</TT></B></P>
48508 <DIV class="indent"> Returns the number of items in <TT>x</TT>.</DIV>
48509 <P><B> <TT>Object *Getitem(List *x, int n)</TT></B></P>
48510 <DIV class="indent"> Returns an object from <TT>x</TT> with index <TT>n</TT>
48511 . If <TT>n</TT> is beyond the end of the list, the last item is
48512  returned. If <TT>n</TT> is negative, the first item is returned.</DIV>
48513 <P><B> <TT>int *Setitem(List *x, int n, const Object_or_char *val)</TT></B>
48514 </P>
48515 <DIV class="indent"> Stores <TT>val</TT> in <TT>x</TT>. If <TT>val</TT>
48516  is not a standard object (String, Hash, or List) it is assumed to be a <TT>
48517 char *</TT> in which case it is used to construct a <TT>String</TT> that
48518  is stored in the list. <TT>n</TT> must be in range. Otherwise, an
48519  assertion will be raised.</DIV>
48520 <P><B> <TT>int *Delitem(List *x, int n)</TT></B></P>
48521 <DIV class="indent"> Deletes item <TT>n</TT> from the list, shifting
48522  items down if necessary. To delete the last item in the list, use the
48523  special value <TT>DOH_END</TT> for <TT>n</TT>.</DIV>
48524 <P><B> <TT>void Append(List *x, const Object_or_char *t)</TT></B></P>
48525 <DIV class="indent"> Appends <TT>t</TT> to the end of <TT>x</TT>. If <TT>
48526 t</TT> is not a standard object, it is assumed to be a <TT>char *</TT>
48527  and is used to create a String object.</DIV>
48528 <P><B> <TT>void Insert(String *s, int pos, const Object_or_char *t)</TT></B>
48529 </P>
48530 <DIV class="indent"> Inserts <TT>t</TT> into <TT>s</TT> at position <TT>
48531 pos</TT>. The contents of <TT>s</TT> are shifted accordingly. The
48532  special value <TT>DOH_END</TT> can be used for <TT>pos</TT> to indicate
48533  insertion at the end of the list (appending). If <TT>t</TT> is not a
48534  standard object, it is assumed to be a <TT>char *</TT> and is used to
48535  create a String object.</DIV>
48536 <H3><A name="Extending_nn18"></A>35.5.4 Common operations</H3>
48537  The following operations are applicable to all datatypes.
48538 <P><B> <TT>Object *Copy(Object *x)</TT></B></P>
48539 <DIV class="indent"> Make a copy of the object <TT>x</TT>.</DIV>
48540 <P><B> <TT>void Delete(Object *x)</TT></B></P>
48541 <DIV class="indent"> Deletes <TT>x</TT>.</DIV>
48542 <P><B> <TT>void Setfile(Object *x, String_or_char *f)</TT></B></P>
48543 <DIV class="indent"> Sets the filename associated with <TT>x</TT>. Used
48544  to track objects and report errors.</DIV>
48545 <P><B> <TT>String *Getfile(Object *x)</TT></B></P>
48546 <DIV class="indent"> Gets the filename associated with <TT>x</TT>.</DIV>
48547 <P><B> <TT>void Setline(Object *x, int n)</TT></B></P>
48548 <DIV class="indent"> Sets the line number associated with <TT>x</TT>.
48549  Used to track objects and report errors.</DIV>
48550 <P><B> <TT>int Getline(Object *x)</TT></B></P>
48551 <DIV class="indent"> Gets the line number associated with <TT>x</TT>.</DIV>
48552 <H3><A name="Extending_nn19"></A>35.5.5 Iterating over Lists and Hashes</H3>
48553  To iterate over the elements of a list or a hash table, the following
48554  functions are used:
48555 <P><B> <TT>Iterator First(Object *x)</TT></B></P>
48556 <DIV class="indent"> Returns an iterator object that points to the first
48557  item in a list or hash table. The <TT>item</TT> attribute of the
48558  Iterator object is a pointer to the item. For hash tables, the <TT>key</TT>
48559  attribute of the Iterator object additionally points to the
48560  corresponding Hash table key. The <TT>item</TT> and <TT>key</TT>
48561  attributes are NULL if the object contains no items or if there are no
48562  more items.</DIV>
48563 <P><B> <TT>Iterator Next(Iterator i)</TT></B></P>
48564 <DIV class="indent">
48565 <P>Returns an iterator that points to the next item in a list or hash
48566  table. Here are two examples of iteration:</P>
48567 <DIV class="code">
48568 <PRE>
48569 List *l = (some list);
48570 Iterator i;
48571
48572 for (i = First(l); i.item; i = Next(i)) {
48573     Printf(stdout,&quot;%s\n&quot;, i.item);
48574 }
48575
48576 Hash *h = (some hash);
48577 Iterator j;
48578
48579 for (j = First(j); j.item; j= Next(j)) {
48580     Printf(stdout,&quot;%s : %s\n&quot;, j.key, j.item);
48581 }
48582 </PRE>
48583 </DIV></DIV>
48584 <H3><A name="Extending_nn20"></A>35.5.6 I/O</H3>
48585  Special I/O functions are used for all internal I/O. These operations
48586  work on C <TT>FILE *</TT> objects, String objects, and special <TT>File</TT>
48587  objects (which are merely a wrapper around <TT>FILE *</TT>).
48588 <P><B> <TT>int Printf(String_or_FILE *f, const char *fmt, ...)</TT></B></P>
48589 <DIV class="indent"> Formatted I/O. Same as the C <TT>fprintf()</TT>
48590  function except that output can also be directed to a string object.
48591  Note: the <TT>%s</TT> format specifier works with both strings and <TT>
48592 char *</TT>. All other format operators have the same meaning.</DIV>
48593 <P><B> <TT>int Printv(String_or_FILE *f, String_or_char *arg1,..., NULL)</TT>
48594 </B></P>
48595 <DIV class="indent"> Prints a variable number of strings arguments to
48596  the output. The last argument to this function must be NULL. The other
48597  arguments can either be <TT>char *</TT> or string objects.</DIV>
48598 <P><B> <TT>int Putc(int ch, String_or_FILE *f)</TT></B></P>
48599 <DIV class="indent"> Same as the C <TT>fputc()</TT> function.</DIV>
48600 <P><B> <TT>int Write(String_or_FILE *f, void *buf, int len)</TT></B></P>
48601 <DIV class="indent"> Same as the C <TT>write()</TT> function.</DIV>
48602 <P><B> <TT>int Read(String_or_FILE *f, void *buf, int maxlen)</TT></B></P>
48603 <DIV class="indent"> Same as the C <TT>read()</TT> function.</DIV>
48604 <P><B> <TT>int Getc(String_or_FILE *f)</TT></B></P>
48605 <DIV class="indent"> Same as the C <TT>fgetc()</TT> function.</DIV>
48606 <P><B> <TT>int Ungetc(int ch, String_or_FILE *f)</TT></B></P>
48607 <DIV class="indent"> Same as the C <TT>ungetc()</TT> function.</DIV>
48608 <P><B> <TT>int Seek(String_or_FILE *f, int offset, int whence)</TT></B></P>
48609 <DIV class="indent"> Same as the C <TT>seek()</TT> function. <TT>offset</TT>
48610  is the number of bytes. <TT>whence</TT> is one of <TT>SEEK_SET</TT>,<TT>
48611 SEEK_CUR</TT>, or <TT>SEEK_END</TT>..</DIV>
48612 <P><B> <TT>long Tell(String_or_FILE *f)</TT></B></P>
48613 <DIV class="indent"> Same as the C <TT>tell()</TT> function.</DIV>
48614 <P><B> <TT>File *NewFile(const char *filename, const char *mode, List
48615  *newfiles)</TT></B></P>
48616 <DIV class="indent"> Create a File object using the <TT>fopen()</TT>
48617  library call. This file differs from <TT>FILE *</TT> in that it can be
48618  placed in the standard SWIG containers (lists, hashes, etc.). The <TT>
48619 filename</TT> is added to the <TT>newfiles</TT> list if <TT>newfiles</TT>
48620  is non-zero and the file was created successfully.</DIV>
48621 <P><B> <TT>File *NewFileFromFile(FILE *f)</TT></B></P>
48622 <DIV class="indent"> Create a File object wrapper around an existing <TT>
48623 FILE *</TT> object.</DIV>
48624 <P><B> <TT>int Close(String_or_FILE *f)</TT></B></P>
48625 <DIV class="indent">
48626 <P>Closes a file. Has no effect on strings.</P>
48627 <P> The use of the above I/O functions and strings play a critical role
48628  in SWIG. It is common to see small code fragments of code generated
48629  using code like this:</P>
48630 <DIV class="code">
48631 <PRE>
48632 /* Print into a string */
48633 String *s = NewString(&quot;&quot;);
48634 Printf(s,&quot;Hello\n&quot;);
48635 for (i = 0; i &lt; 10; i++) {
48636     Printf(s,&quot;%d\n&quot;, i);
48637 }
48638 ...
48639 /* Print string into a file */
48640 Printf(f, &quot;%s\n&quot;, s);
48641 </PRE>
48642 </DIV>
48643 <P> Similarly, the preprocessor and parser all operate on string-files.</P>
48644 </DIV>
48645 <H2><A name="Extending_nn21"></A>35.6 Navigating and manipulating parse
48646  trees</H2>
48647  Parse trees are built as collections of hash tables. Each node is a
48648  hash table in which arbitrary attributes can be stored. Certain
48649  attributes in the hash table provide links to other parse tree nodes.
48650  The following macros can be used to move around the parse tree.
48651 <P><B> <TT>String *nodeType(Node *n)</TT></B></P>
48652 <DIV class="indent"> Returns the node type tag as a string. The returned
48653  string indicates the type of parse tree node.</DIV>
48654 <P><B> <TT>Node *nextSibling(Node *n)</TT></B></P>
48655 <DIV class="indent"> Returns the next node in the parse tree. For
48656  example, the next C declaration.</DIV>
48657 <P><B> <TT>Node *previousSibling(Node *n)</TT></B></P>
48658 <DIV class="indent"> Returns the previous node in the parse tree. For
48659  example, the previous C declaration.</DIV>
48660 <P><B> <TT>Node *firstChild(Node *n)</TT></B></P>
48661 <DIV class="indent"> Returns the first child node. For example, if <TT>n</TT>
48662  was a C++ class node, this would return the node for the first class
48663  member.</DIV>
48664 <P><B> <TT>Node *lastChild(Node *n)</TT></B></P>
48665 <DIV class="indent"> Returns the last child node. You might use this if
48666  you wanted to append a new node to the of a class.</DIV>
48667 <P><B> <TT>Node *parentNode(Node *n)</TT></B></P>
48668 <DIV class="indent"> Returns the parent of node <TT>n</TT>. Use this to
48669  move up the pass tree.</DIV>
48670 <P> The following macros can be used to change all of the above
48671  attributes. Normally, these functions are only used by the parser.
48672  Changing them without knowing what you are doing is likely to be
48673  dangerous.</P>
48674 <P><B> <TT>void set_nodeType(Node *n, const String_or_char)</TT></B></P>
48675 <DIV class="indent"> Change the node type. tree node.</DIV>
48676 <P><B> <TT>void set_nextSibling(Node *n, Node *s)</TT></B></P>
48677 <DIV class="indent"> Set the next sibling.</DIV>
48678 <P><B> <TT>void set_previousSibling(Node *n, Node *s)</TT></B></P>
48679 <DIV class="indent"> Set the previous sibling.</DIV>
48680 <P><B> <TT>void set_firstChild(Node *n, Node *c)</TT></B></P>
48681 <DIV class="indent"> Set the first child node.</DIV>
48682 <P><B> <TT>void set_lastChild(Node *n, Node *c)</TT></B></P>
48683 <DIV class="indent"> Set the last child node.</DIV>
48684 <P><B> <TT>void set_parentNode(Node *n, Node *p)</TT></B></P>
48685 <DIV class="indent"> Set the parent node.</DIV>
48686 <P> The following utility functions are used to alter the parse tree (at
48687  your own risk)</P>
48688 <P><B> <TT>void appendChild(Node *parent, Node *child)</TT></B></P>
48689 <DIV class="indent"> Append a child to <TT>parent</TT>. The appended
48690  node becomes the last child.</DIV>
48691 <P><B> <TT>void deleteNode(Node *node)</TT></B></P>
48692 <DIV class="indent"> Deletes a node from the parse tree. Deletion
48693  reconnects siblings and properly updates the parent so that sibling
48694  nodes are unaffected.</DIV>
48695 <H2><A name="Extending_nn22"></A>35.7 Working with attributes</H2>
48696 <P> Since parse tree nodes are just hash tables, attributes are accessed
48697  using the <TT>Getattr()</TT>, <TT>Setattr()</TT>, and <TT>Delattr()</TT>
48698  operations. For example:</P>
48699 <DIV class="code">
48700 <PRE>
48701 int functionHandler(Node *n) {
48702     String *name    = Getattr(n,&quot;name&quot;);
48703     String *symname = Getattr(n,&quot;sym:name&quot;);
48704     SwigType *type  = Getattr(n,&quot;type&quot;);
48705     ...
48706 }
48707 </PRE>
48708 </DIV>
48709 <P> New attributes can be freely attached to a node as needed. However,
48710  when new attributes are attached during code generation, they should be
48711  prepended with a namespace prefix. For example:</P>
48712 <DIV class="code">
48713 <PRE>
48714 ...
48715 Setattr(n,&quot;python:docstring&quot;, doc);     /* Store docstring */
48716 ...
48717 </PRE>
48718 </DIV>
48719 <P> A quick way to check the value of an attribute is to use the <TT>
48720 checkAttribute()</TT> function like this:</P>
48721 <DIV class="code">
48722 <PRE>
48723 if (checkAttribute(n,&quot;storage&quot;,&quot;virtual&quot;)) {
48724    /* n is virtual */
48725    ...
48726 }
48727 </PRE>
48728 </DIV>
48729 <P> Changing the values of existing attributes is allowed and is
48730  sometimes done to implement node transformations. However, if a
48731  function/method modifies a node, it is required to restore modified
48732  attributes to their original values. To simplify the task of
48733  saving/restoring attributes, the following functions are used:</P>
48734 <P><B> <TT>int Swig_save(const char *ns, Node *n, const char *name1,
48735  const char *name2, ..., NIL)</TT></B></P>
48736 <DIV class="indent"> Saves a copy of attributes <TT>name1</TT>, <TT>
48737 name2</TT>, etc. from node <TT>n</TT>. Copies of the attributes are
48738  actually resaved in the node in a different namespace which is set by
48739  the <TT>ns</TT> argument. For example, if you call <TT>
48740 Swig_save(&quot;foo&quot;,n,&quot;type&quot;,NIL)</TT>, then the &quot;type&quot; attribute will be
48741  copied and saved as &quot;foo:type&quot;. The namespace name itself is stored in
48742  the &quot;view&quot; attribute of the node. If necessary, this can be examined to
48743  find out where previous values of attributes might have been saved.</DIV>
48744 <P><B> <TT>int Swig_restore(Node *n)</TT></B></P>
48745 <DIV class="indent">
48746 <P> Restores the attributes saved by the previous call to <TT>
48747 Swig_save()</TT>. Those attributes that were supplied to <TT>Swig_save()</TT>
48748  will be restored to their original values.</P>
48749 <P> The <TT>Swig_save()</TT> and <TT>Swig_restore()</TT> functions must
48750  always be used as a pair. That is, every call to <TT>Swig_save()</TT>
48751  must have a matching call to <TT>Swig_restore()</TT>. Calls can be
48752  nested if necessary. Here is an example that shows how the functions
48753  might be used:</P>
48754 <DIV class="code">
48755 <PRE>
48756 int variableHandler(Node *n) {
48757     Swig_save(&quot;variableHandler&quot;,n,&quot;type&quot;,&quot;sym:name&quot;,NIL);
48758     String *symname = Getattr(n,&quot;sym:name&quot;);
48759     SwigType *type  = Getattr(n,&quot;type&quot;);
48760     ...
48761     Append(symname,&quot;_global&quot;);         // Change symbol name
48762     SwigType_add_pointer(type);        // Add pointer
48763     ...
48764     generate wrappers
48765     ...
48766     Swig_restore(n);                  // Restore original values
48767     return SWIG_OK;
48768 }
48769 </PRE>
48770 </DIV></DIV>
48771 <P><B> <TT>int Swig_require(const char *ns, Node *n, const char *name1,
48772  const char *name2, ..., NIL)</TT></B></P>
48773 <DIV class="indent"> This is an enhanced version of <TT>Swig_save()</TT>
48774  that adds error checking. If an attribute name is not present in <TT>n</TT>
48775 , a failed assertion results and SWIG terminates with a fatal error.
48776  Optionally, if an attribute name is specified as &quot;*<EM>name</EM>&quot;, a
48777  copy of the attribute is saved as with <TT>Swig_save()</TT>. If an
48778  attribute is specified as &quot;?<EM>name</EM>&quot;, the attribute is optional. <TT>
48779 Swig_restore()</TT> must always be called after using this function.</DIV>
48780 <H2><A name="Extending_nn23"></A>35.8 Type system</H2>
48781 <P> SWIG implements the complete C++ type system including typedef,
48782  inheritance, pointers, references, and pointers to members. A detailed
48783  discussion of type theory is impossible here. However, let's cover the
48784  highlights.</P>
48785 <H3><A name="Extending_nn24"></A>35.8.1 String encoding of types</H3>
48786 <P> All types in SWIG consist of a base datatype and a collection of
48787  type operators that are applied to the base. A base datatype is almost
48788  always some kind of primitive type such as <TT>int</TT> or <TT>double</TT>
48789 . The operators consist of things like pointers, references, arrays, and
48790  so forth. Internally, types are represented as strings that are
48791  constructed in a very precise manner. Here are some examples:</P>
48792 <DIV class="diagram">
48793 <PRE>
48794 C datatype                     SWIG encoding (strings)
48795 -----------------------------  --------------------------
48796 int                            &quot;int&quot;
48797 int *                          &quot;p.int&quot;
48798 const int *                    &quot;p.q(const).int&quot;
48799 int (*x)(int,double)           &quot;p.f(int,double).int&quot;
48800 int [20][30]                   &quot;a(20).a(30).int&quot;
48801 int (F::*)(int)                &quot;m(F).f(int).int&quot;
48802 vector&lt;int&gt; *                  &quot;p.vector&lt;(int)&gt;&quot;
48803 </PRE>
48804 </DIV>
48805 <P> Reading the SWIG encoding is often easier than figuring out the C
48806  code---just read it from left to right. For a type of
48807  &quot;p.f(int,double).int&quot; is a &quot;pointer to a function(int,double) that
48808  returns int&quot;.</P>
48809 <P> The following operator encodings are used in type strings:</P>
48810 <DIV class="diagram">
48811 <PRE>
48812 Operator              Meaning
48813 -------------------   -------------------------------
48814 p.                    Pointer to
48815 a(n).                 Array of dimension n
48816 r.                    C++ reference
48817 m(class).             Member pointer to class
48818 f(args).              Function.
48819 q(qlist).             Qualifiers
48820 </PRE>
48821 </DIV>
48822 <P> In addition, type names may be parameterized by templates. This is
48823  represented by enclosing the template parameters in <TT>&lt;( ... )&gt;</TT>.
48824  Variable length arguments are represented by the special base type of <TT>
48825 v(...)</TT>.</P>
48826 <P> If you want to experiment with type encodings, the raw type strings
48827  can be inserted into an interface file using backticks `` wherever a
48828  type is expected. For instance, here is an extremely perverted example:</P>
48829 <DIV class="diagram">
48830 <PRE>
48831 `p.a(10).p.f(int,p.f(int).int)` foo(int, int (*x)(int));
48832 </PRE>
48833 </DIV>
48834 <P> This corresponds to the immediately obvious C declaration:</P>
48835 <DIV class="diagram">
48836 <PRE>
48837 (*(*foo(int,int (*)(int)))[10])(int,int (*)(int));
48838 </PRE>
48839 </DIV>
48840 <P> Aside from the potential use of this declaration on a C programming
48841  quiz, it motivates the use of the special SWIG encoding of types. The
48842  SWIG encoding is much easier to work with because types can be easily
48843  examined, modified, and constructed using simple string operations
48844  (comparison, substrings, concatenation, etc.). For example, in the
48845  parser, a declaration like this</P>
48846 <DIV class="code">
48847 <PRE>
48848 int *a[30];
48849 </PRE>
48850 </DIV>
48851 <P> is processed in a few pieces. In this case, you have the base type &quot;<TT>
48852 int</TT>&quot; and the declarator of type &quot;<TT>a(30).p.</TT>&quot;. To make the
48853  final type, the two parts are just joined together using string
48854  concatenation.</P>
48855 <H3><A name="Extending_nn25"></A>35.8.2 Type construction</H3>
48856 <P> The following functions are used to construct types. You should use
48857  these functions instead of trying to build the type strings yourself.</P>
48858 <P><B> <TT>void SwigType_add_pointer(SwigType *ty)</TT></B></P>
48859 <DIV class="indent"> Adds a pointer to <TT>ty</TT>.</DIV>
48860 <P><B> <TT>void SwigType_del_pointer(SwigType *ty)</TT></B></P>
48861 <DIV class="indent"> Removes a single pointer from <TT>ty</TT>.</DIV>
48862 <P><B> <TT>void SwigType_add_reference(SwigType *ty)</TT></B></P>
48863 <DIV class="indent"> Adds a reference to <TT>ty</TT>.</DIV>
48864 <P><B> <TT>void SwigType_add_array(SwigType *ty, const String_or_char
48865  *size)</TT></B></P>
48866 <DIV class="indent"> Adds an array with dimension <TT>dim</TT> to <TT>ty</TT>
48867 .</DIV>
48868 <P><B> <TT>void SwigType_del_array(SwigType *ty)</TT></B></P>
48869 <DIV class="indent"> Removes a single array dimension from <TT>ty</TT>.</DIV>
48870 <P><B> <TT>int SwigType_array_ndim(SwigType *ty)</TT></B></P>
48871 <DIV class="indent"> Returns number of array dimensions of <TT>ty</TT>.</DIV>
48872 <P><B> <TT>String* SwigType_array_getdim(SwigType *ty,int n)</TT></B></P>
48873 <DIV class="indent"> Returns <TT>n</TT>th array dimension of <TT>ty</TT>
48874 .</DIV>
48875 <P><B> <TT>void SwigType_array_setdim(SwigType *ty, int n, const
48876  String_or_char *rep)</TT></B></P>
48877 <DIV class="indent"> Sets <TT>n</TT>th array dimensions of <TT>ty</TT>
48878  to <TT>rep</TT>.</DIV>
48879 <P><B> <TT>void SwigType_add_qualifier(SwigType *ty, const
48880  String_or_char *q)</TT></B></P>
48881 <DIV class="indent"> Adds a type qualifier <TT>q</TT> to <TT>ty</TT>. <TT>
48882 q</TT> is typically <TT>&quot;const&quot;</TT> or <TT>&quot;volatile&quot;</TT>.</DIV>
48883 <P><B> <TT>void SwigType_add_memberpointer(SwigType *ty, const
48884  String_or_char *cls)</TT></B></P>
48885 <DIV class="indent"> Adds a pointer to a member of class <TT>cls</TT> to
48886  <TT>ty</TT>.</DIV>
48887 <P><B> <TT>void SwigType_add_function(SwigType *ty, ParmList *p)</TT></B>
48888 </P>
48889 <DIV class="indent"> Adds a function to <TT>ty</TT>. <TT>p</TT> is a
48890  linked-list of parameter nodes as generated by the parser. See the
48891  section on parameter lists for details about the representation.</DIV>
48892 <P><B> <TT>void SwigType_add_template(SwigType *ty, ParmList *p)</TT></B>
48893 </P>
48894 <DIV class="indent"> Adds a template to <TT>ty</TT>. <TT>p</TT> is a
48895  linked-list of parameter nodes as generated by the parser. See the
48896  section on parameter lists for details about the representation.</DIV>
48897 <P><B> <TT>SwigType *SwigType_pop(SwigType *ty)</TT></B></P>
48898 <DIV class="indent"> Removes the last type constructor from <TT>ty</TT>
48899  and returns it. <TT>ty</TT> is modified.</DIV>
48900 <P><B> <TT>void SwigType_push(SwigType *ty, SwigType *op)</TT></B></P>
48901 <DIV class="indent"> Pushes the type operators in <TT>op</TT> onto type <TT>
48902 ty</TT>. The opposite of <TT>SwigType_pop()</TT>.</DIV>
48903 <P><B> <TT>SwigType *SwigType_pop_arrays(SwigType *ty)</TT></B></P>
48904 <DIV class="indent"> Removes all leading array operators from <TT>ty</TT>
48905  and returns them. <TT>ty</TT> is modified. For example, if <TT>ty</TT>
48906  is <TT>&quot;a(20).a(10).p.int&quot;</TT>, then this function would return <TT>
48907 &quot;a(20).a(10).&quot;</TT> and modify <TT>ty</TT> so that it has the value <TT>
48908 &quot;p.int&quot;</TT>.</DIV>
48909 <P><B> <TT>SwigType *SwigType_pop_function(SwigType *ty)</TT></B></P>
48910 <DIV class="indent"> Removes a function operator from <TT>ty</TT>
48911  including any qualification. <TT>ty</TT> is modified. For example, if <TT>
48912 ty</TT> is <TT>&quot;f(int).int&quot;</TT>, then this function would return <TT>
48913 &quot;f(int).&quot;</TT> and modify <TT>ty</TT> so that it has the value <TT>&quot;int&quot;</TT>
48914 .</DIV>
48915 <P><B> <TT>SwigType *SwigType_base(SwigType *ty)</TT></B></P>
48916 <DIV class="indent"> Returns the base type of a type. For example, if <TT>
48917 ty</TT> is <TT>&quot;p.a(20).int&quot;</TT>, this function would return <TT>&quot;int&quot;</TT>
48918 . <TT>ty</TT> is unmodified.</DIV>
48919 <P><B> <TT>SwigType *SwigType_prefix(SwigType *ty)</TT></B></P>
48920 <DIV class="indent"> Returns the prefix of a type. For example, if <TT>
48921 ty</TT> is <TT>&quot;p.a(20).int&quot;</TT>, this function would return <TT>
48922 &quot;p.a(20).&quot;</TT>. <TT>ty</TT> is unmodified.</DIV>
48923 <H3><A name="Extending_nn26"></A>35.8.3 Type tests</H3>
48924 <P> The following functions can be used to test properties of a
48925  datatype.</P>
48926 <P><B> <TT>int SwigType_ispointer(SwigType *ty)</TT></B></P>
48927 <DIV class="indent"> Checks if <TT>ty</TT> is a standard pointer.</DIV>
48928 <P><B> <TT>int SwigType_ismemberpointer(SwigType *ty)</TT></B></P>
48929 <DIV class="indent"> Checks if <TT>ty</TT> is a member pointer.</DIV>
48930 <P><B> <TT>int SwigType_isreference(SwigType *ty)</TT></B></P>
48931 <DIV class="indent"> Checks if <TT>ty</TT> is a C++ reference.</DIV>
48932 <P><B> <TT>int SwigType_isarray(SwigType *ty)</TT></B></P>
48933 <DIV class="indent"> Checks if <TT>ty</TT> is an array.</DIV>
48934 <P><B> <TT>int SwigType_isfunction(SwigType *ty)</TT></B></P>
48935 <DIV class="indent"> Checks if <TT>ty</TT> is a function.</DIV>
48936 <P><B> <TT>int SwigType_isqualifier(SwigType *ty)</TT></B></P>
48937 <DIV class="indent"> Checks if <TT>ty</TT> is a qualifier.</DIV>
48938 <P><B> <TT>int SwigType_issimple(SwigType *ty)</TT></B></P>
48939 <DIV class="indent"> Checks if <TT>ty</TT> is a simple type. No
48940  operators applied.</DIV>
48941 <P><B> <TT>int SwigType_isconst(SwigType *ty)</TT></B></P>
48942 <DIV class="indent"> Checks if <TT>ty</TT> is a const type.</DIV>
48943 <P><B> <TT>int SwigType_isvarargs(SwigType *ty)</TT></B></P>
48944 <DIV class="indent"> Checks if <TT>ty</TT> is a varargs type.</DIV>
48945 <P><B> <TT>int SwigType_istemplate(SwigType *ty)</TT></B></P>
48946 <DIV class="indent"> Checks if <TT>ty</TT> is a templatized type.</DIV>
48947 <H3><A name="Extending_nn27"></A>35.8.4 Typedef and inheritance</H3>
48948 <P> The behavior of <TT>typedef</TT> declaration is to introduce a type
48949  alias. For instance, <TT>typedef int Integer</TT> makes the identifier <TT>
48950 Integer</TT> an alias for <TT>int</TT>. The treatment of typedef in SWIG
48951  is somewhat complicated due to the pattern matching rules that get
48952  applied in typemaps and the fact that SWIG prefers to generate wrapper
48953  code that closely matches the input to simplify debugging (a user will
48954  see the typedef names used in their program instead of the low-level
48955  primitive C datatypes).</P>
48956 <P> To handle <TT>typedef</TT>, SWIG builds a collection of trees
48957  containing typedef relations. For example,</P>
48958 <DIV class="code">
48959 <PRE>
48960 typedef int Integer;
48961 typedef Integer *IntegerPtr;
48962 typedef int Number;
48963 typedef int Size;
48964 </PRE>
48965 </DIV>
48966 <P> produces two trees like this:</P>
48967 <DIV class="diagram">
48968 <PRE>
48969                  int               p.Integer
48970                ^  ^  ^                 ^
48971               /   |   \                |
48972              /    |    \               |
48973         Integer  Size   Number    IntegerPtr
48974 </PRE>
48975 </DIV>
48976 <P> To resolve a single typedef relationship, the following function is
48977  used:</P>
48978 <P><B> <TT>SwigType *SwigType_typedef_resolve(SwigType *ty)</TT></B></P>
48979 <DIV class="indent"> Checks if <TT>ty</TT> can be reduced to a new type
48980  via typedef. If so, returns the new type. If not, returns NULL.</DIV>
48981 <P> Typedefs are only resolved in simple typenames that appear in a
48982  type. For example, the type base name and in function parameters. When
48983  resolving types, the process starts in the leaf nodes and moves up the
48984  tree towards the root. Here are a few examples that show how it works:</P>
48985 <DIV class="diagram">
48986 <PRE>
48987 Original type            After typedef_resolve()
48988 ------------------------ -----------------------
48989 Integer                  int
48990 a(30).Integer            int
48991 p.IntegerPtr             p.p.Integer
48992 p.p.Integer              p.p.int
48993 </PRE>
48994 </DIV>
48995 <P> For complicated types, the process can be quite involved. Here is
48996  the reduction of a function pointer:</P>
48997 <DIV class="diagram">
48998 <PRE>
48999 p.f(Integer, p.IntegerPtr, Size).Integer          : Start
49000 p.f(Integer, p.IntegerPtr, Size).int
49001 p.f(int, p.IntegerPtr, Size).int
49002 p.f(int, p.p.Integer, Size).int
49003 p.f(int, p.p.int, Size).int
49004 p.f(int, p.p.int, int).int                        : End
49005 </PRE>
49006 </DIV>
49007 <P> Two types are equivalent if their full type reductions are the same.
49008  The following function will fully reduce a datatype:</P>
49009 <P><B> <TT>SwigType *SwigType_typedef_resolve_all(SwigType *ty)</TT></B></P>
49010 <DIV class="indent"> Fully reduces <TT>ty</TT> according to typedef
49011  rules. Resulting datatype will consist only of primitive typenames.</DIV>
49012 <H3><A name="Extending_nn28"></A>35.8.5 Lvalues</H3>
49013 <P> When generating wrapper code, it is necessary to emit datatypes that
49014  can be used on the left-hand side of an assignment operator (an
49015  lvalue). However, not all C datatypes can be used in this
49016  way---especially arrays and const-qualified types. To generate a type
49017  that can be used as an lvalue, use the following function:</P>
49018 <P><B> <TT>SwigType *SwigType_ltype(SwigType *ty)</TT></B></P>
49019 <DIV class="indent"> Converts type <TT>ty</TT> to a type that can be
49020  used as an lvalue in assignment. The resulting type is stripped of
49021  qualifiers and arrays are converted to a pointers.</DIV>
49022 <P> The creation of lvalues is fully aware of typedef and other aspects
49023  of the type system. Therefore, the creation of an lvalue may result in
49024  unexpected results. Here are a few examples:</P>
49025 <DIV class="code">
49026 <PRE>
49027 typedef double Matrix4[4][4];
49028 Matrix4 x;    // type = 'Matrix4', ltype='p.a(4).double'
49029
49030 typedef const char * Literal;
49031 Literal y;    // type = 'Literal', ltype='p.char'
49032 </PRE>
49033 </DIV>
49034 <H3><A name="Extending_nn29"></A>35.8.6 Output functions</H3>
49035 <P> The following functions produce strings that are suitable for
49036  output.</P>
49037 <P><B> <TT>String *SwigType_str(SwigType *ty, const String_or_char *id =
49038  0)</TT></B></P>
49039 <DIV class="indent"> Generates a C string for a datatype. <TT>id</TT> is
49040  an optional declarator. For example, if <TT>ty</TT> is &quot;p.f(int).int&quot;
49041  and <TT>id</TT> is &quot;foo&quot;, then this function produces &quot;<TT>int
49042  (*foo)(int)</TT>&quot;. This function is used to convert string-encoded
49043  types back into a form that is valid C syntax.</DIV>
49044 <P><B> <TT>String *SwigType_lstr(SwigType *ty, const String_or_char *id
49045  = 0)</TT></B></P>
49046 <DIV class="indent"> This is the same as <TT>SwigType_str()</TT> except
49047  that the result is generated from the type's lvalue (as generated from
49048  SwigType_ltype).</DIV>
49049 <P><B> <TT>String *SwigType_lcaststr(SwigType *ty, const String_or_char
49050  *id = 0)</TT></B></P>
49051 <DIV class="indent"> Generates a casting operation that converts from
49052  type <TT>ty</TT> to its lvalue. <TT>id</TT> is an optional name to
49053  include in the cast. For example, if <TT>ty</TT> is &quot;<TT>
49054 q(const).p.char</TT>&quot; and <TT>id</TT> is &quot;<TT>foo</TT>&quot;, this function
49055  produces the string &quot;<TT>(char *) foo</TT>&quot;.</DIV>
49056 <P><B> <TT>String *SwigType_rcaststr(SwigType *ty, const String_or_char
49057  *id = 0)</TT></B></P>
49058 <DIV class="indent"> Generates a casting operation that converts from a
49059  type's lvalue to a type equivalent to <TT>ty</TT>. <TT>id</TT> is an
49060  optional name to include in the cast. For example, if <TT>ty</TT> is &quot;<TT>
49061 q(const).p.char</TT>&quot; and <TT>id</TT> is &quot;<TT>foo</TT>&quot;, this function
49062  produces the string &quot;<TT>(const char *) foo</TT>&quot;.</DIV>
49063 <P><B> <TT>String *SwigType_manglestr(SwigType *ty)</TT></B></P>
49064 <DIV class="indent"> Generates a mangled string encoding of type <TT>ty</TT>
49065 . The mangled string only contains characters that are part of a valid C
49066  identifier. The resulting string is used in various parts of SWIG, but
49067  is most commonly associated with type-descriptor objects that appear in
49068  wrappers (e.g., <TT>SWIGTYPE_p_double</TT>).</DIV>
49069 <H2><A name="Extending_nn30"></A>35.9 Parameters</H2>
49070 <P> Several type-related functions involve parameter lists. These
49071  include functions and templates. Parameter list are represented as a
49072  list of nodes with the following attributes:</P>
49073 <DIV class="diagram">
49074 <PRE>
49075 &quot;type&quot;        -  Parameter type  (required)
49076 &quot;name&quot;        -  Parameter name  (optional)
49077 &quot;value&quot;       -  Initializer     (optional)
49078 </PRE>
49079 </DIV>
49080 <P> Typically parameters are denoted in the source by using a typename
49081  of <TT>Parm *</TT> or <TT>ParmList *</TT>. To walk a parameter list,
49082  simply use code like this:</P>
49083 <DIV class="diagram">
49084 <PRE>
49085 Parm *parms;
49086 Parm *p;
49087 for (p = parms; p; p = nextSibling(p)) {
49088     SwigType *type  = Getattr(p,&quot;type&quot;);
49089     String   *name  = Getattr(p,&quot;name&quot;);
49090     String   *value = Getattr(p,&quot;value&quot;);
49091     ...
49092 }
49093 </PRE>
49094 </DIV>
49095 <P> Note: this code is exactly the same as what you would use to walk
49096  parse tree nodes.</P>
49097 <P> An empty list of parameters is denoted by a NULL pointer.</P>
49098 <P> Since parameter lists are fairly common, the following utility
49099  functions are provided to manipulate them:</P>
49100 <P><B> <TT>Parm *CopyParm(Parm *p);</TT></B></P>
49101 <DIV class="indent"> Copies a single parameter.</DIV>
49102 <P><B> <TT>ParmList *CopyParmList(ParmList *p);</TT></B></P>
49103 <DIV class="indent"> Copies an entire list of parameters.</DIV>
49104 <P><B> <TT>int ParmList_len(ParmList *p);</TT></B></P>
49105 <DIV class="indent"> Returns the number of parameters in a parameter
49106  list.</DIV>
49107 <P><B> <TT>String *ParmList_str(ParmList *p);</TT></B></P>
49108 <DIV class="indent"> Converts a parameter list into a C string. For
49109  example, produces a string like &quot;<TT>(int *p, int n, double x);</TT>&quot;.</DIV>
49110 <P><B> <TT>String *ParmList_protostr(ParmList *p);</TT></B></P>
49111 <DIV class="indent"> The same as <TT>ParmList_str()</TT> except that
49112  parameter names are not included. Used to emit prototypes.</DIV>
49113 <P><B> <TT>int ParmList_numrequired(ParmList *p);</TT></B></P>
49114 <DIV class="indent"> Returns the number of required (non-optional)
49115  arguments in <TT>p</TT>.</DIV>
49116 <H2><A name="Extending_nn31"></A>35.10 Writing a Language Module</H2>
49117 <P> One of the easiest routes to supporting a new language module is to
49118  copy an already supported language module implementation and modify it.
49119  Be sure to choose a language that is similar in nature to the new
49120  language. All language modules follow a similar structure and this
49121  section briefly outlines the steps needed to create a bare-bones
49122  language module from scratch. Since the code is relatively easy to
49123  read, this section describes the creation of a minimal Python module.
49124  You should be able to extrapolate this to other languages.</P>
49125 <H3><A name="Extending_nn32"></A>35.10.1 Execution model</H3>
49126 <P> Code generation modules are defined by inheriting from the <TT>
49127 Language</TT> class, currently defined in the <TT>Source/Modules</TT>
49128  directory of SWIG. Starting from the parsing of command line options,
49129  all aspects of code generation are controlled by different methods of
49130  the <TT>Language</TT> that must be defined by your module.</P>
49131 <H3><A name="Extending_nn33"></A>35.10.2 Starting out</H3>
49132 <P> To define a new language module, first create a minimal
49133  implementation using this example as a guide:</P>
49134 <DIV class="code">
49135 <PRE>
49136 #include &quot;swigmod.h&quot;
49137
49138 class PYTHON : public Language {
49139 public:
49140
49141   virtual void main(int argc, char *argv[]) {
49142     printf(&quot;I'm the Python module.\n&quot;);
49143   }
49144
49145   virtual int top(Node *n) {
49146     printf(&quot;Generating code.\n&quot;);
49147     return SWIG_OK;
49148   }
49149
49150 };
49151
49152 extern &quot;C&quot; Language *
49153 swig_python(void) {
49154   return new PYTHON();
49155 }
49156 </PRE>
49157 </DIV>
49158 <P> The &quot;swigmod.h&quot; header file contains, among other things, the
49159  declaration of the <TT>Language</TT> base class and so you should
49160  include it at the top of your language module's source file. Similarly,
49161  the &quot;swigconfig.h&quot; header file contains some other useful definitions
49162  that you may need. Note that you should<EM> not</EM> include any header
49163  files that are installed with the target language. That is to say, the
49164  implementation of the SWIG Python module shouldn't have any
49165  dependencies on the Python header files. The wrapper code generated by
49166  SWIG will almost always depend on some language-specific C/C++ header
49167  files, but SWIG itself does not.</P>
49168 <P> Give your language class a reasonable name, usually the same as the
49169  target language. By convention, these class names are all uppercase
49170  (e.g. &quot;PYTHON&quot; for the Python language module) but this is not a
49171  requirement. This class will ultimately consist of a number of
49172  overrides of the virtual functions declared in the <TT>Language</TT>
49173  base class, in addition to any language-specific member functions and
49174  data you need. For now, just use the dummy implementations shown above.</P>
49175 <P> The language module ends with a factory function, <TT>swig_python()</TT>
49176 , that simply returns a new instance of the language class. As shown, it
49177  should be declared with the <TT>extern &quot;C&quot;</TT> storage qualifier so
49178  that it can be called from C code. It should also return a pointer to
49179  the base class (<TT>Language</TT>) so that only the interface (and not
49180  the implementation) of your language module is exposed to the rest of
49181  SWIG.</P>
49182 <P> Save the code for your language module in a file named &quot;<TT>
49183 python.cxx</TT>&quot; and. place this file in the <TT>Source/Modules</TT>
49184  directory of the SWIG distribution. To ensure that your module is
49185  compiled into SWIG along with the other language modules, modify the
49186  file <TT>Source/Modules/Makefile.am</TT> to include the additional
49187  source files. In addition, modify the file <TT>
49188 Source/Modules/swigmain.cxx</TT> with an additional command line option
49189  that activates the module. Read the source---it's straightforward.</P>
49190 <P> Next, at the top level of the SWIG distribution, re-run the <TT>
49191 autogen.sh</TT> script to regenerate the various build files:</P>
49192 <DIV class="shell">
49193 <PRE>
49194 $ <B>./autogen.sh</B>
49195 </PRE>
49196 </DIV>
49197 <P> Next re-run <TT>configure</TT> to regenerate all of the Makefiles:</P>
49198 <DIV class="shell">
49199 <PRE>
49200 $ <B>./configure</B>
49201 </PRE>
49202 </DIV>
49203 <P> Finally, rebuild SWIG with your module added:</P>
49204 <DIV class="shell">
49205 <PRE>
49206 $ <B>make</B>
49207 </PRE>
49208 </DIV>
49209 <P> Once it finishes compiling, try running SWIG with the command-line
49210  option that activates your module. For example, <TT>swig -python foo.i</TT>
49211 . The messages from your new module should appear.</P>
49212 <H3><A name="Extending_nn34"></A>35.10.3 Command line options</H3>
49213 <P> When SWIG starts, the command line options are passed to your
49214  language module. This occurs before any other processing occurs
49215  (preprocessing, parsing, etc.). To capture the command line options,
49216  simply use code similar to this:</P>
49217 <DIV class="code">
49218 <PRE>
49219 void Language::main(int argc, char *argv[]) {
49220   for (int i = 1; i &lt; argc; i++) {
49221       if (argv[i]) {
49222           if(strcmp(argv[i],&quot;-interface&quot;) == 0) {
49223             if (argv[i+1]) {
49224               interface = NewString(argv[i+1]);
49225               Swig_mark_arg(i);
49226               Swig_mark_arg(i+1);
49227               i++;
49228             } else {
49229               Swig_arg_error();
49230             }
49231           } else if (strcmp(argv[i],&quot;-globals&quot;) == 0) {
49232             if (argv[i+1]) {
49233               global_name = NewString(argv[i+1]);
49234               Swig_mark_arg(i);
49235               Swig_mark_arg(i+1);
49236               i++;
49237             } else {
49238               Swig_arg_error();
49239             }
49240           } else if ( (strcmp(argv[i],&quot;-proxy&quot;) == 0)) {
49241             proxy_flag = 1;
49242             Swig_mark_arg(i);
49243           } else if (strcmp(argv[i],&quot;-keyword&quot;) == 0) {
49244             use_kw = 1;
49245             Swig_mark_arg(i);
49246           } else if (strcmp(argv[i],&quot;-help&quot;) == 0) {
49247             fputs(usage,stderr);
49248           }
49249           ...
49250       }
49251   }
49252 }
49253 </PRE>
49254 </DIV>
49255 <P> The exact set of options depends on what you want to do in your
49256  module. Generally, you would use the options to change code generation
49257  modes or to print diagnostic information.</P>
49258 <P> If a module recognizes an option, it should always call <TT>
49259 Swig_mark_arg()</TT> to mark the option as valid. If you forget to do
49260  this, SWIG will terminate with an unrecognized command line option
49261  error.</P>
49262 <H3><A name="Extending_nn35"></A>35.10.4 Configuration and preprocessing</H3>
49263 <P> In addition to looking at command line options, the <TT>main()</TT>
49264  method is responsible for some initial configuration of the SWIG
49265  library and preprocessor. To do this, insert some code like this:</P>
49266 <DIV class="code">
49267 <PRE>
49268 void main(int argc, char *argv[]) {
49269    ... command line options ...
49270
49271    /* Set language-specific subdirectory in SWIG library */
49272    SWIG_library_directory(&quot;python&quot;);
49273
49274    /* Set language-specific preprocessing symbol */
49275    Preprocessor_define(&quot;SWIGPYTHON 1&quot;, 0);
49276
49277    /* Set language-specific configuration file */
49278    SWIG_config_file(&quot;python.swg&quot;);
49279
49280    /* Set typemap language (historical) */
49281    SWIG_typemap_lang(&quot;python&quot;);
49282 }
49283 </PRE>
49284 </DIV>
49285 <P> The above code does several things--it registers the name of the
49286  language module with the core, it supplies some preprocessor macro
49287  definitions for use in input files (so that they can determine the
49288  target language), and it registers a start-up file. In this case, the
49289  file <TT>python.swg</TT> will be parsed before any part of the
49290  user-supplied input file.</P>
49291 <P> Before proceeding any further, create a directory for your module in
49292  the SWIG library (The <TT>Lib</TT> directory). Now, create a
49293  configuration file in the directory. For example, <TT>python.swg</TT>.</P>
49294 <P> Just to review, your language module should now consist of two
49295  files-- an implementation file <TT>python.cxx</TT> and a configuration
49296  file <TT>python.swg</TT>.</P>
49297 <H3><A name="Extending_nn36"></A>35.10.5 Entry point to code generation</H3>
49298 <P> SWIG is a multi-pass compiler. Once the <TT>main()</TT> method has
49299  been invoked, the language module does not execute again until
49300  preprocessing, parsing, and a variety of semantic analysis passes have
49301  been performed. When the core is ready to start generating wrappers, it
49302  invokes the <TT>top()</TT> method of your language class. The argument
49303  to <TT>top</TT> is a single parse tree node that corresponds to the top
49304  of the entire parse tree.</P>
49305 <P> To get the code generation process started, the <TT>top()</TT>
49306  procedure needs to do several things:</P>
49307 <UL>
49308 <LI>Initialize the wrapper code output.</LI>
49309 <LI>Set the module name.</LI>
49310 <LI>Emit common initialization code.</LI>
49311 <LI>Emit code for all of the child nodes.</LI>
49312 <LI>Finalize the wrapper module and cleanup.</LI>
49313 </UL>
49314 <P> An outline of <TT>top()</TT> might be as follows:</P>
49315 <DIV class="code">
49316 <PRE>
49317 int Python::top(Node *n) {
49318
49319    /* Get the module name */
49320    String *module = Getattr(n,&quot;name&quot;);
49321
49322    /* Get the output file name */
49323    String *outfile = Getattr(n,&quot;outfile&quot;);
49324
49325    /* Initialize I/O (see next section) */
49326    ...
49327
49328    /* Output module initialization code */
49329    ...
49330
49331    /* Emit code for children */
49332    Language::top(n);
49333
49334    ...
49335    /* Cleanup files */
49336    ...
49337
49338    return SWIG_OK;
49339 }
49340 </PRE>
49341 </DIV>
49342 <H3><A name="Extending_nn37"></A>35.10.6 Module I/O and wrapper skeleton</H3>
49343
49344 <!-- please report bugs in this section to mgossage -->
49345 <P> Within SWIG wrappers, there are four main sections. These are (in
49346  order)</P>
49347 <UL>
49348 <LI>runtime: This section has most of the common SWIG runtime code</LI>
49349 <LI>header: This section holds declarations and inclusions from the .i
49350  file</LI>
49351 <LI>wrapper: This section holds all the wrappering code</LI>
49352 <LI>init: This section holds the module initalisation function (the
49353  entry point for the interpreter)</LI>
49354 </UL>
49355 <P> Different parts of the SWIG code will fill different sections, then
49356  upon completion of the wrappering all the sections will be saved to the
49357  wrapper file.</P>
49358 <P> To perform this will require several additions to the code in
49359  various places, such as:</P>
49360 <DIV class="code">
49361 <PRE>
49362 class PYTHON : public Language {
49363 protected:
49364    /* General DOH objects used for holding the strings */
49365    File *f_begin;
49366    File *f_runtime;
49367    File *f_header;
49368    File *f_wrappers;
49369    File *f_init;
49370
49371 public:
49372    ...
49373
49374 };
49375
49376 int Python::top(Node *n) {
49377
49378    ...
49379
49380    /* Initialize I/O */
49381    f_begin = NewFile(outfile, &quot;w&quot;, SWIG_output_files());
49382    if (!f_begin) {
49383       FileErrorDisplay(outfile);
49384       SWIG_exit(EXIT_FAILURE);
49385    }
49386    f_runtime = NewString(&quot;&quot;);
49387    f_init = NewString(&quot;&quot;);
49388    f_header = NewString(&quot;&quot;);
49389    f_wrappers = NewString(&quot;&quot;);
49390
49391    /* Register file targets with the SWIG file handler */
49392    Swig_register_filebyname(&quot;begin&quot;, f_begin);
49393    Swig_register_filebyname(&quot;header&quot;, f_header);
49394    Swig_register_filebyname(&quot;wrapper&quot;, f_wrappers);
49395    Swig_register_filebyname(&quot;runtime&quot;, f_runtime);
49396    Swig_register_filebyname(&quot;init&quot;, f_init);
49397
49398    /* Output module initialization code */
49399    Swig_banner(f_begin);
49400    ...
49401
49402    /* Emit code for children */
49403    Language::top(n);
49404
49405    ...
49406    /* Write all to the file */
49407    Dump(f_runtime, f_begin);
49408    Dump(f_header, f_begin);
49409    Dump(f_wrappers, f_begin);
49410    Wrapper_pretty_print(f_init, f_begin);
49411
49412    /* Cleanup files */
49413    Delete(f_runtime);
49414    Delete(f_header);
49415    Delete(f_wrappers);
49416    Delete(f_init);
49417    Close(f_begin);
49418    Delete(f_begin);
49419
49420    return SWIG_OK;
49421 }
49422 </PRE>
49423 </DIV>
49424 <P> Using this to process a file will generate a wrapper file, however
49425  the wrapper will only consist of the common SWIG code as well as any
49426  inline code which was written in the .i file. It does not contain any
49427  wrappers for any of the functions or classes.</P>
49428 <P> The code to generate the wrappers are the various member functions,
49429  which currently have not been touched. We will look at <TT>
49430 functionWrapper()</TT> as this is the most commonly used function. In
49431  fact many of the other wrapper routines will call this to do their
49432  work.</P>
49433 <P> A simple modification to write some basic details to the wrapper
49434  looks like this:</P>
49435 <DIV class="code">
49436 <PRE>
49437 int Python::functionWrapper(Node *n) {
49438   /* Get some useful attributes of this function */
49439   String   *name   = Getattr(n,&quot;sym:name&quot;);
49440   SwigType *type   = Getattr(n,&quot;type&quot;);
49441   ParmList *parms  = Getattr(n,&quot;parms&quot;);
49442   String   *parmstr= ParmList_str_defaultargs(parms); // to string
49443   String   *func   = SwigType_str(type, NewStringf(&quot;%s(%s)&quot;, name, parmstr));
49444   String   *action = Getattr(n,&quot;wrap:action&quot;);
49445
49446   Printf(f_wrappers,&quot;functionWrapper   : %s\n&quot;, func);
49447   Printf(f_wrappers,&quot;           action : %s\n&quot;, action);
49448   return SWIG_OK;
49449 }
49450 </PRE>
49451 </DIV>
49452 <P> This will now produce some useful information within your wrapper
49453  file.</P>
49454 <DIV class="shell">
49455 <PRE>
49456 functionWrapper   : void delete_Shape(Shape *self)
49457            action : delete arg1;
49458
49459 functionWrapper   : void Shape_x_set(Shape *self,double x)
49460            action : if (arg1) (arg1)-&gt;x = arg2;
49461
49462 functionWrapper   : double Shape_x_get(Shape *self)
49463            action : result = (double) ((arg1)-&gt;x);
49464
49465 functionWrapper   : void Shape_y_set(Shape *self,double y)
49466            action : if (arg1) (arg1)-&gt;y = arg2;
49467 ...
49468 </PRE>
49469 </DIV>
49470 <H3><A name="Extending_nn38"></A>35.10.7 Low-level code generators</H3>
49471
49472 <!-- please report bugs in this section to mgossage -->
49473 <P> As ingenious as SWIG is, and despite all its capabilities and the
49474  power of its parser, the Low-level code generation takes a lot of work
49475  to write properly. Mainly because every language insists on its own
49476  manner of interfacing to C/C++. To write the code generators you will
49477  need a good understanding of how to manually write an interface to your
49478  chosen language, so make sure you have your documentation handy.</P>
49479 <P> At this point it is also probably a good idea to take a very simple
49480  file (just one function), and try letting SWIG generate wrappers for
49481  many different languages. Take a look at all of the wrappers generated,
49482  and decide which one looks closest to the language you are trying to
49483  wrap. This may help you to decide which code to look at.</P>
49484 <P> In general most language wrappers look a little like this:</P>
49485 <DIV class="code">
49486 <PRE>
49487 /* wrapper for TYPE3 some_function(TYPE1,TYPE2); */
49488 RETURN_TYPE _wrap_some_function(ARGS){
49489   TYPE1 arg1;
49490   TYPE2 arg2;
49491   TYPE3 result;
49492
49493   if(ARG1 is not of TYPE1) goto fail;
49494   arg1=(convert ARG1);
49495   if(ARG2 is not of TYPE2) goto fail;
49496   arg2=(convert ARG2);
49497
49498   result=some_function(arg1,arg2);
49499
49500   convert 'result' to whatever the language wants;
49501
49502   do any tidy up;
49503
49504   return ALL_OK;
49505
49506   fail:
49507   do any tidy up;
49508   return ERROR;
49509 }
49510 </PRE>
49511 </DIV>
49512 <P> Yes, it is rather vague and not very clear. But each language works
49513  differently so this will have to do for now.</P>
49514 <P> Tackling this problem will be done in two stages:</P>
49515 <UL>
49516 <LI>The skeleton: the function wrapper, and call, but without the
49517  conversion</LI>
49518 <LI>The conversion: converting the arguments to-from what the language
49519  wants</LI>
49520 </UL>
49521 <P> The first step will be done in the code, the second will be done in
49522  typemaps.</P>
49523 <P> Our first step will be to write the code for <TT>functionWrapper()</TT>
49524 . What is shown below is<B> NOT</B> the solution, merely a step in the
49525  right direction. There are a lot of issues to address.</P>
49526 <UL>
49527 <LI>Variable length and default parameters</LI>
49528 <LI>Typechecking and number of argument checks</LI>
49529 <LI>Overloaded functions</LI>
49530 <LI>Inout and Output only arguments</LI>
49531 </UL>
49532 <DIV class="code">
49533 <PRE>
49534 virtual int functionWrapper(Node *n) {
49535   /* get useful atributes */
49536   String   *name   = Getattr(n,&quot;sym:name&quot;);
49537   SwigType *type   = Getattr(n,&quot;type&quot;);
49538   ParmList *parms  = Getattr(n,&quot;parms&quot;);
49539   ...
49540
49541   /* create the wrapper object */
49542   Wrapper *wrapper = NewWrapper();
49543
49544   /* create the functions wrappered name */
49545   String *wname = Swig_name_wrapper(iname);
49546
49547   /* deal with overloading */
49548   ....
49549
49550   /* write the wrapper function definition */
49551   Printv(wrapper-&gt;def,&quot;RETURN_TYPE &quot;, wname, &quot;(ARGS) {&quot;,NIL);
49552
49553   /* if any additional local variable needed, add them now */
49554   ...
49555
49556   /* write the list of locals/arguments required */
49557   emit_args(type, parms, wrapper);
49558
49559   /* check arguments */
49560   ...
49561
49562   /* write typemaps(in) */
49563   ....
49564
49565   /* write constriants */
49566   ....
49567
49568   /* Emit the function call */
49569   emit_action(n,wrapper);
49570
49571   /* return value if necessary  */
49572   ....
49573
49574   /* write typemaps(out) */
49575   ....
49576
49577   /* add cleanup code */
49578   ....
49579
49580   /* Close the function(ok) */
49581   Printv(wrapper-&gt;code, &quot;return ALL_OK;\n&quot;, NIL);
49582
49583   /* add the failure cleanup code */
49584   ...
49585
49586   /* Close the function(error) */
49587   Printv(wrapper-&gt;code, &quot;return ERROR;\n&quot;, &quot;}\n&quot;, NIL);
49588
49589   /* final substititions if applicable */
49590   ...
49591
49592   /* Dump the function out */
49593   Wrapper_print(wrapper,f_wrappers);
49594
49595   /* tidy up */
49596   Delete(wname);
49597   DelWrapper(wrapper);
49598
49599   return SWIG_OK;
49600 }
49601 </PRE>
49602 </DIV>
49603 <P> Executing this code will produce wrappers which have our basic
49604  skeleton but without the typemaps, there is still work to do.</P>
49605 <H3><A name="Extending_nn39"></A>35.10.8 Configuration files</H3>
49606
49607 <!-- please report bugs in this section to ttn -->
49608 <P> At the time of this writing, SWIG supports nearly a dozen languages,
49609  which means that for continued sanity in maintaining the configuration
49610  files, the language modules need to follow some conventions. These are
49611  outlined here along with the admission that, yes it is ok to violate
49612  these conventions in minor ways, as long as you know where to apply the
49613  proper kludge to keep the overall system regular and running.
49614  Engineering is the art of compromise, see...</P>
49615 <P> Much of the maintenance regularity depends on choosing a suitable
49616  nickname for your language module (and then using it in a controlled
49617  way). Nicknames should be all lower case letters with an optional
49618  numeric suffix (no underscores, no dashes, no spaces). Some examples
49619  are: <TT>foo</TT>, <TT>bar</TT>, <TT>qux99</TT>.</P>
49620 <P> The numeric suffix variant, as in the last example, is somewhat
49621  tricky to work with because sometimes people expect to refer to the
49622  language without this number but sometimes that number is extremely
49623  relevant (especially when it corresponds to language implementation
49624  versions with incompatible interfaces). New language modules that
49625  unavoidably require a numeric suffix in their nickname should include
49626  that number in all uses, or be prepared to kludge.</P>
49627 <P> The nickname is used in four places:</P>
49628 <TABLE summary="nickname table">
49629 <TR><TD><B>usage</B></TD><TD><B>transform</B></TD></TR>
49630 <TR><TD>&quot;skip&quot; tag</TD><TD>(none)</TD></TR>
49631 <TR><TD>Examples/ subdir name</TD><TD>(none)</TD></TR>
49632 <TR><TD>Examples/GIFPlot/ subdir name</TD><TD>capitalize (upcase first
49633  letter)</TD></TR>
49634 <TR><TD>Examples/test-suite/ subdir name</TD><TD>(none)</TD></TR>
49635
49636 <!-- add more uses here (remember to adjust header) -->
49637 </TABLE>
49638 <P> As you can see, most usages are direct.</P>
49639 <DL>
49640 <DT><B> configure.in</B></DT>
49641 <DD> This file is processed by
49642 <P> <A HREF="http://www.gnu.org/software/autoconf/">autoconf</A> to
49643  generate the <TT>configure</TT> script. This is where you need to add
49644  shell script fragments and autoconf macros to detect the presence of
49645  whatever development support your language module requires, typically
49646  directories where headers and libraries can be found, and/or utility
49647  programs useful for integrating the generated wrapper code.</P>
49648 <P> Use the <TT>AC_ARG_WITH</TT>, <TT>AC_MSG_CHECKING</TT>, <TT>AC_SUBST</TT>
49649  macros and so forth (see other languages for examples). Avoid using the
49650  <TT>[</TT> and <TT>]</TT> character in shell script fragments. The
49651  variable names passed to <TT>AC_SUBST</TT> should begin with the
49652  nickname, entirely upcased.</P>
49653 <P> At the end of the new section is the place to put the aforementioned
49654  nickname kludges (should they be needed). See Perl5 for examples of
49655  what to do. [If this is still unclear after you've read the code, ping
49656  me and I'll expand on this further. --ttn]</P>
49657 </DD>
49658 <DT><B> Makefile.in</B></DT>
49659 <DD>
49660 <P> Some of the variables AC_SUBSTituted are essential to the support of
49661  your language module. Fashion these into a shell script &quot;test&quot; clause
49662  and assign that to a skip tag using &quot;-z&quot; and &quot;-o&quot;:</P>
49663 <DIV class="code"> <TT>skip-qux99 = [ -z &quot;@QUX99INCLUDE@&quot; -o -z
49664  &quot;@QUX99LIBS&quot; ]</TT></DIV>
49665 <P> This means if those vars should ever be empty, qux99 support should
49666  be considered absent and so it would be a good idea to skip actions
49667  that might rely on it.</P>
49668 <P> Here is where you may also define an alias (but then you'll need to
49669  kludge --- don't do this):</P>
49670 <DIV class="code"> <TT>skip-qux = $(skip-qux99)</TT></DIV>
49671 <P> Lastly, you need to modify each of <TT>check-aliveness</TT>, <TT>
49672 check-examples</TT>, <TT>check-test-suite</TT>, <TT>check-gifplot</TT>
49673  (all targets) and <TT>lib-languages</TT> (var). Use the nickname for
49674  these, not the alias. Note that you can do this even before you have
49675  any tests or examples set up; the Makefile rules do some sanity
49676  checking and skip around these kinds of problems.</P>
49677 </DD>
49678 <DT><B> Examples/Makefile.in</B></DT>
49679 <DD> Nothing special here; see comments at top the of this file and look
49680  to the existing languages for examples.</DD>
49681 <DT><B> Examples/qux99/check.list</B></DT>
49682 <DD> Do <TT>cp ../python/check.list .</TT> and modify to taste. One
49683  subdir per line.</DD>
49684 <DT><B> Examples/GIFPlot/Qux99/check.list</B></DT>
49685 <DD> Do <TT>cp ../Python/check.list .</TT> and modify to taste. One
49686  subdir per line.</DD>
49687 <DT><B> Lib/qux99/extra-install.list</B></DT>
49688 <DD> If you add your language to the top-level Makefile.in var <TT>
49689 lib-languages</TT>, then <TT>make install</TT> will install all <TT>*.i</TT>
49690  and <TT>*.swg</TT> files from the language-specific subdirectory of <TT>
49691 Lib</TT>. Use (optional) file <TT>extra-install.list</TT> in that
49692  directory to name additional files to install (see ruby for example).</DD>
49693 <DT><B> Source/Modules/Makefile.am</B></DT>
49694 <DD> Add appropriate files to this Automake file. That's it!
49695 <P> When you have modified these files, please make sure that the new
49696  language module is completely ignored if it is not installed and
49697  detected on a box, that is, <TT>make check-examples</TT> and <TT>make
49698  check-test-suite</TT> politely displays the ignoring language message.</P>
49699 </DD>
49700 </DL>
49701 <H3><A name="Extending_nn40"></A>35.10.9 Runtime support</H3>
49702 <P> Discuss the kinds of functions typically needed for SWIG runtime
49703  support (e.g. <TT>SWIG_ConvertPtr()</TT> and <TT>SWIG_NewPointerObj()</TT>
49704 ) and the names of the SWIG files that implement those functions.</P>
49705 <H3><A name="Extending_nn41"></A>35.10.10 Standard library files</H3>
49706 <P> The standard library files that most languages supply keeps growing
49707  as SWIG matures. The following are the minimum that are usually
49708  supported:</P>
49709 <UL>
49710 <LI> typemaps.i</LI>
49711 <LI> std_string.i</LI>
49712 <LI> std_vector.i</LI>
49713 <LI> stl.i</LI>
49714 </UL>
49715 <P> Please copy these and modify for any new language.</P>
49716 <H3><A name="Extending_nn42"></A>35.10.11 Examples and test cases</H3>
49717 <P> Each of the language modules provides one or more examples. These
49718  examples are used to demonstrate different features of the language
49719  module to SWIG end-users, but you'll find that they're useful during
49720  development and testing of your language module as well. You can use
49721  examples from the existing SWIG language modules for inspiration.</P>
49722 <P> Each example is self-contained and consists of (at least) a <TT>
49723 Makefile</TT>, a SWIG interface file for the example module, and a
49724  'runme' script that demonstrates the functionality for that module. All
49725  of these files are stored in the same subdirectory under the <TT>
49726 Examples/[lang]</TT> directory. There are two classic examples which
49727  should be the first to convert to a new language module. These are the
49728  &quot;simple&quot; C example and the &quot;class&quot; C++ example. These can be found, for
49729  example for Python, in <TT>Examples/python/simple</TT> and <TT>
49730 Examples/python/class</TT>.</P>
49731 <P> By default, all of the examples are built and run when the user
49732  types <TT>make check</TT>. To ensure that your examples are
49733  automatically run during this process, see the section on <A href="#n37a">
49734 configuration files</A>.</P>
49735 <H3><A name="Extending_nn43"></A>35.10.12 Documentation</H3>
49736 <P> Don't forget to write end-user documentation for your language
49737  module. Currently, each language module has a dedicated chapter You
49738  shouldn't rehash things that are already covered in sufficient detail
49739  in the <A href="#SWIG">SWIG Basics</A> and <A href="#SWIGPlus">SWIG and
49740  C++</A> chapters. There is no fixed format for<EM> what</EM>, exactly,
49741  you should document about your language module, but you'll obviously
49742  want to cover issues that are unique to your language.</P>
49743 <P> Some topics that you'll want to be sure to address include:</P>
49744 <UL>
49745 <LI> Command line options unique to your language module.</LI>
49746 <LI> Non-obvious mappings between C/C++ and target language concepts.
49747  For example, if your target language provides a single floating point
49748  type, it should be no big surprise to find that C/C++ <TT>float</TT>
49749  and <TT>double</TT> types are mapped to it. On the other hand, if your
49750  target language doesn't provide support for &quot;classes&quot; or something
49751  similar, you'd want to discuss how C++ classes are handled.</LI>
49752 <LI> How to compile the SWIG-generated wrapper code into shared
49753  libraries that can actually be used. For some languages, there are
49754  well-defined procedures for doing this, but for others it's an ad hoc
49755  process. Provide as much detail as appropriate, and links to other
49756  resources if available.</LI>
49757 </UL>
49758 <H3><A name="Extending_prerequisites"></A>35.10.13 Prerequisites for
49759  adding a new language module to the SWIG distribution</H3>
49760 <P> If you wish for a new language module to be distributed with SWIG,
49761  which we encourage for all popular languages, there are a few
49762  requirements. While we appreciate that getting all aspects of a new
49763  language working won't happen at the outset, there are a set of minimum
49764  requirements before a module can be committed into the SVN repository
49765  for distribution with future versions of SWIG. The following are really
49766  a summary of this whole section with details being outlined earlier on.</P>
49767 <OL>
49768 <LI> Demonstrate basic C code working by porting the &quot;simple&quot; example
49769  including a runtime test, see for example <TT>Examples/python/simple</TT>
49770 .</LI>
49771 <LI> Demonstrate basic C++ code working by porting the &quot;class&quot; example
49772  including a runtime test, see for example <TT>Examples/python/class</TT>
49773 .</LI>
49774 <LI> Modify <TT>configure.in</TT>, <TT>Makefile.in</TT> and <TT>
49775 Examples/Makefile.in</TT> to run these examples. Please make sure that
49776  if the new language is not installed properly on a box, <TT>make -k
49777  check</TT> should still work by skipping the tests and examples for the
49778  new language module.</LI>
49779 <LI> Get the test-suite running for the new language (<TT>make
49780  check-[lang]-test-suite</TT>). While the test-suite tests many corner
49781  cases, we'd expect the majority of it to work by compiling the
49782  generated code correctly as most of the corner cases are covered in the
49783  SWIG core. Get at least one C and one C++ runtime test running in the
49784  test-suite.</LI>
49785 <LI> Provide a chapter in the html documentation on the basics of using
49786  the language module.</LI>
49787 <LI> Ensure your source code is formatted according to the <A href="#Extending_coding_style_guidelines">
49788 coding style guidelines</A>.</LI>
49789 <LI> Finally, email the SWIG developers with a patch and a demonstration
49790  of commitment to maintaining the language module, certainly in the
49791  short term and ideally long term.</LI>
49792 </OL>
49793 <P> Once accepted into SVN, development efforts should concentrate on
49794  getting the entire test-suite to work with plenty of runtime tests.
49795  Runtime tests should be for existing testcases and new test cases
49796  should be added should there be an area not already covered by the
49797  existing tests.</P>
49798 <H3><A name="Extending_coding_style_guidelines"></A>35.10.14 Coding
49799  style guidelines</H3>
49800 <P> The coding guidelines for the C/C++ source code are pretty much K&amp;R
49801  C style. The style can be inferred from the existing code base and is
49802  largely dictated by the <TT>indent</TT> code beautifier tool set to K&amp;R
49803  style. The code can formatted using the make targets in the Source
49804  directory. Below is an example of how to format the emit.cxx file:</P>
49805 <BLOCKQUOTE>
49806 <PRE>
49807 $ cd Source
49808 $ make beautify-file INDENTFILE=Modules/emit.cxx
49809 </PRE>
49810 </BLOCKQUOTE>
49811 <P> Of particular note is indentation is set to 2 spaces and a tab is
49812  used instead of 8 spaces. The generated C/C++ code should also follow
49813  this style as close as possible. However, tabs should be avoided as
49814  unlike the SWIG developers, users will never have consistent tab
49815  settings.</P>
49816 <H2><A name="Extending_nn44"></A>35.11 Typemaps</H2>
49817 <H3><A name="Extending_nn45"></A>35.11.1 Proxy classes</H3>
49818 <H2><A name="Extending_nn46"></A>35.12 Guide to parse tree nodes</H2>
49819 <P> This section describes the different parse tree nodes and their
49820  attributes.</P>
49821 <P><B> cdecl</B></P>
49822 <P> Describes general C declarations including variables, functions, and
49823  typedefs. A declaration is parsed as &quot;storage T D&quot; where storage is a
49824  storage class, T is a base type, and D is a declarator.</P>
49825 <DIV class="diagram">
49826 <PRE>
49827 &quot;name&quot;          - Declarator name
49828 &quot;type&quot;          - Base type T
49829 &quot;decl&quot;          - Declarator type (abstract)
49830 &quot;storage&quot;       - Storage class (static, extern, typedef, etc.)
49831 &quot;parms&quot;         - Function parameters (if a function)
49832 &quot;code&quot;          - Function body code (if supplied)
49833 &quot;value&quot;         - Default value (if supplied)
49834 </PRE>
49835 </DIV>
49836 <P><B> constructor</B></P>
49837 <P> C++ constructor declaration.</P>
49838 <DIV class="diagram">
49839 <PRE>
49840 &quot;name&quot;          - Name of constructor
49841 &quot;parms&quot;         - Parameters
49842 &quot;decl&quot;          - Declarator (function with parameters)
49843 &quot;code&quot;          - Function body code (if any)
49844 &quot;feature:new&quot;   - Set to indicate return of new object.
49845 </PRE>
49846 </DIV>
49847 <P><B> destructor</B></P>
49848 <P> C++ destructor declaration.</P>
49849 <DIV class="diagram">
49850 <PRE>
49851 &quot;name&quot;          - Name of destructor
49852 &quot;code&quot;          - Function body code (if any)
49853 &quot;storage&quot;       - Storage class (set if virtual)
49854 &quot;value&quot;         - Default value (set if pure virtual).
49855 </PRE>
49856 </DIV>
49857 <P><B> access</B></P>
49858 <P> C++ access change.</P>
49859 <DIV class="diagram">
49860 <PRE>
49861 &quot;kind&quot;          - public, protected, private
49862 </PRE>
49863 </DIV>
49864 <P><B> constant</B></P>
49865 <P> Constant created by %constant or #define.</P>
49866 <DIV class="diagram">
49867 <PRE>
49868 &quot;name&quot;          - Name of constant.
49869 &quot;type&quot;          - Base type.
49870 &quot;value&quot;         - Value.
49871 &quot;storage&quot;       - Set to %constant
49872 &quot;feature:immutable&quot; - Set to indicate read-only
49873 </PRE>
49874 </DIV>
49875 <P><B> class</B></P>
49876 <P> C++ class definition or C structure definition.</P>
49877 <DIV class="diagram">
49878 <PRE>
49879 &quot;name&quot;          - Name of the class.
49880 &quot;kind&quot;          - Class kind (&quot;struct&quot;, &quot;union&quot;, &quot;class&quot;)
49881 &quot;symtab&quot;        - Enclosing symbol table.
49882 &quot;tdname&quot;        - Typedef name. Use for typedef struct { ... } A.
49883 &quot;abstract&quot;      - Set if class has pure virtual methods.
49884 &quot;baselist&quot;      - List of base class names.
49885 &quot;storage&quot;       - Storage class (if any)
49886 &quot;unnamed&quot;       - Set if class is unnamed.
49887 </PRE>
49888 </DIV>
49889 <P><B> enum</B></P>
49890 <P> Enumeration.</P>
49891 <DIV class="diagram">
49892 <PRE>
49893 &quot;name&quot;          - Name of the enum (if supplied).
49894 &quot;storage&quot;       - Storage class (if any)
49895 &quot;tdname&quot;        - Typedef name (typedef enum { ... } name).
49896 &quot;unnamed&quot;       - Set if enum is unnamed.
49897 </PRE>
49898 </DIV>
49899 <P><B> enumitem</B></P>
49900 <P> Enumeration value.</P>
49901 <DIV class="diagram">
49902 <PRE>
49903 &quot;name&quot;          - Name of the enum value.
49904 &quot;type&quot;          - Type (integer or char)
49905 &quot;value&quot;         - Enum value (if given)
49906 &quot;feature:immutable&quot; - Set to indicate read-only
49907 </PRE>
49908 </DIV>
49909 <P><B> namespace</B></P>
49910 <P> C++ namespace.</P>
49911 <DIV class="diagram">
49912 <PRE>
49913 &quot;name&quot;          - Name of the namespace.
49914 &quot;symtab&quot;        - Symbol table for enclosed scope.
49915 &quot;unnamed&quot;       - Set if unnamed namespace
49916 &quot;alias&quot;         - Alias name. Set for namespace A = B;
49917 </PRE>
49918 </DIV>
49919 <P><B> using</B></P>
49920 <P> C++ using directive.</P>
49921 <DIV class="diagram">
49922 <PRE>
49923 &quot;name&quot;          - Name of the object being referred to.
49924 &quot;uname&quot;         - Qualified name actually given to using.
49925 &quot;node&quot;          - Node being referenced.
49926 &quot;namespace&quot;     - Namespace name being reference (using namespace name)
49927 </PRE>
49928 </DIV>
49929 <P><B> classforward</B></P>
49930 <P> A forward C++ class declaration.</P>
49931 <DIV class="diagram">
49932 <PRE>
49933 &quot;name&quot;          - Name of the class.
49934 &quot;kind&quot;          - Class kind (&quot;union&quot;, &quot;struct&quot;, &quot;class&quot;)
49935 </PRE>
49936 </DIV>
49937 <P><B> insert</B></P>
49938 <P> Code insertion directive. For example, %{ ... %} or
49939  %insert(section).</P>
49940 <DIV class="diagram">
49941 <PRE>
49942 &quot;code&quot;          - Inserted code
49943 &quot;section&quot;       - Section name (&quot;header&quot;, &quot;wrapper&quot;, etc.)
49944 </PRE>
49945 </DIV>
49946 <P><B> top</B></P>
49947 <P> Top of the parse tree.</P>
49948 <DIV class="diagram">
49949 <PRE>
49950 &quot;module&quot;        - Module name
49951 </PRE>
49952 </DIV>
49953 <P><B> extend</B></P>
49954 <P> %extend directive.</P>
49955 <DIV class="diagram">
49956 <PRE>
49957 &quot;name&quot;          - Module name
49958 &quot;symtab&quot;        - Symbol table of enclosed scope.
49959 </PRE>
49960 </DIV>
49961 <P><B> apply</B></P>
49962 <P> %apply pattern { patternlist }.</P>
49963 <DIV class="diagram">
49964 <PRE>
49965 &quot;pattern&quot;       - Source pattern.
49966 &quot;symtab&quot;        - Symbol table of enclosed scope.
49967 </PRE>
49968 </DIV>
49969 <P><B> clear</B></P>
49970 <P> %clear patternlist;</P>
49971 <DIV class="diagram">
49972 <PRE>
49973 &quot;firstChild&quot;    - Patterns to clear
49974 </PRE>
49975 </DIV>
49976 <P><B> include</B></P>
49977 <P> %include directive.</P>
49978 <DIV class="diagram">
49979 <PRE>
49980 &quot;name&quot;         - Filename
49981 &quot;firstChild&quot;   - Children
49982 </PRE>
49983 </DIV>
49984 <P><B> import</B></P>
49985 <P> %import directive.</P>
49986 <DIV class="diagram">
49987 <PRE>
49988 &quot;name&quot;         - Filename
49989 &quot;firstChild&quot;   - Children
49990 </PRE>
49991 </DIV>
49992 <P><B> module</B></P>
49993 <P> %module directive.</P>
49994 <DIV class="diagram">
49995 <PRE>
49996 &quot;name&quot;         - Name of the module
49997 </PRE>
49998 </DIV>
49999 <P><B> typemap</B></P>
50000 <P> %typemap directive.</P>
50001 <DIV class="diagram">
50002 <PRE>
50003 &quot;method&quot;       - Typemap method name.
50004 &quot;code&quot;         - Typemap code.
50005 &quot;kwargs&quot;       - Keyword arguments (if any)
50006 &quot;firstChild&quot;   - Typemap patterns
50007 </PRE>
50008 </DIV>
50009 <P><B> typemapcopy</B></P>
50010 <P> %typemap directive with copy.</P>
50011 <DIV class="diagram">
50012 <PRE>
50013 &quot;method&quot;       - Typemap method name.
50014 &quot;pattern&quot;      - Typemap source pattern.
50015 &quot;firstChild&quot;   - Typemap patterns
50016 </PRE>
50017 </DIV>
50018 <P><B> typemapitem</B></P>
50019 <P> %typemap pattern. Used with %apply, %clear, %typemap.</P>
50020 <DIV class="diagram">
50021 <PRE>
50022 &quot;pattern&quot;      - Typemap pattern (a parameter list)
50023 &quot;parms&quot;        - Typemap parameters.
50024 </PRE>
50025 </DIV>
50026 <P><B> types</B></P>
50027 <P> %types directive.</P>
50028 <DIV class="diagram">
50029 <PRE>
50030 &quot;parms&quot;        - List of parameter types.
50031 &quot;convcode&quot;     - Code which replaces the default casting / conversion code
50032 </PRE>
50033 </DIV>
50034 <P><B> extern</B></P>
50035 <P> extern &quot;X&quot; { ... } declaration.</P>
50036 <DIV class="diagram">
50037 <PRE>
50038 &quot;name&quot;       - Name &quot;C&quot;, &quot;Fortran&quot;, etc.
50039 </PRE>
50040 </DIV></BODY>
50041 </HTML>