1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
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"><!--
40 background-color: #F0FFFF;
49 background-color: #d7f6bb;
59 background-color: #DCDCDC;
68 background-color: #FFEBCD;
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 }
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>
109 <H1 ALIGN="CENTER"><A NAME="CONTENTS">Table of Contents</A></H1>
111 <BR><B><A HREF="#Sections">SWIG-1.3 Development Documentation</A></B>
113 <LI><A HREF="#1_1">Sections</A>
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>
122 <B><A HREF="#Preface">1 Preface</A></B>
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>
135 <B><A HREF="#Introduction">2 Introduction</A></B>
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>
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>
148 <LI><A HREF="#Introduction_nn10">2.4 Supported C/C++ language features</A>
150 <LI><A HREF="#Introduction_nn11">2.5 Non-intrusive interface building</A>
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>
157 <B><A HREF="#Windows">3 Getting started on Windows</A></B>
159 <LI><A HREF="#Windows_installation">3.1 Installation on Windows</A>
161 <LI><A HREF="#Windows_executable">3.1.1 Windows Executable</A></LI>
164 <LI><A HREF="#Windows_examples">3.2 SWIG Windows Examples</A>
166 <LI><A HREF="#Windows_visual_studio">3.2.1 Instructions for using the
167 Examples with Visual Studio</A>
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>
178 <LI><A HREF="#Windows_other_compilers">3.2.2 Instructions for using the
179 Examples with other compilers</A></LI>
182 <LI><A HREF="#Windows_cygwin_mingw">3.3 SWIG on Cygwin and MinGW</A>
184 <LI><A HREF="#Windows_swig_exe">3.3.1 Building swig.exe on Windows</A>
186 <LI><A HREF="#Windows_mingw_msys">3.3.1.1 Building swig.exe using MinGW
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>
193 <LI><A HREF="#Windows_examples_cygwin">3.3.2 Running the examples on
194 Windows using Cygwin</A></LI>
197 <LI><A HREF="#Windows_interface_file">3.4 Microsoft extensions and other
198 Windows quirks</A></LI>
200 <B><A HREF="#Scripting">4 Scripting Languages</A></B>
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
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>
213 <LI><A HREF="#Scripting_nn9">4.3 Building scripting language extensions</A>
215 <LI><A HREF="#Scripting_nn10">4.3.1 Shared libraries and dynamic loading</A>
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>
222 <B><A HREF="#SWIG">5 SWIG Basics</A></B>
224 <LI><A HREF="#SWIG_nn2">5.1 Running SWIG</A>
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>
234 <LI><A HREF="#SWIG_nn9">5.2 Wrapping Simple C Declarations</A>
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>
243 <LI><A HREF="#SWIG_nn15">5.3 Pointers and complex objects</A>
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>
252 <LI><A HREF="#SWIG_nn21">5.4 Other Practicalities</A>
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
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>
267 <LI><A HREF="#SWIG_nn31">5.5 Structures and unions</A>
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>
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
282 <LI><A HREF="#SWIG_nn40">5.6 Code Insertion</A>
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>
290 <LI><A HREF="#SWIG_nn45">5.7 An Interface Building Strategy</A>
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>
300 <B><A HREF="#SWIGPlus">6 SWIG and C++</A></B>
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>
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>
313 <LI><A HREF="#SWIGPlus_nn6">6.6 Simple C++ wrapping</A>
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
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>
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>
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>
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>
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->()</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>
361 <LI><A HREF="#SWIGPlus_nn42">6.28 Where to go for more information</A></LI>
363 <B><A HREF="#Preprocessor">7 Preprocessing</A></B>
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
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 %{ ... %} & " ...
373 " delimiters</A></LI>
374 <LI><A HREF="#Preprocessor_nn9">7.8 Preprocessing and { ... } delimiters</A>
376 <LI><A HREF="#Preprocessor_typemap_delimiters">7.9 Preprocessor and
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
382 <B><A HREF="#Library">8 SWIG library</A></B>
384 <LI><A HREF="#Library_nn2">8.1 The %include directive and library search
386 <LI><A HREF="#Library_nn3">8.2 C Arrays and Pointers</A>
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>
394 <LI><A HREF="#Library_nn8">8.3 C String Handling</A>
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>
402 <LI><A HREF="#Library_stl_cpp_library">8.4 STL/C++ Library</A>
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>
409 <LI><A HREF="#Library_nn16">8.5 Utility Libraries</A>
411 <LI><A HREF="#Library_nn17">8.5.1 exception.i</A></LI>
415 <B><A HREF="#Arguments">9 Argument Handling</A></B>
417 <LI><A HREF="#Arguments_nn2">9.1 The typemaps.i library</A>
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>
426 <LI><A HREF="#Arguments_nn8">9.2 Applying constraints to input values</A>
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
435 <B><A HREF="#Typemaps">10 Typemaps</A></B>
437 <LI><A HREF="#Typemaps_nn2">10.1 Introduction</A>
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>
448 <LI><A HREF="#Typemaps_nn10">10.2 Typemap specifications</A>
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>
457 <LI><A HREF="#Typemaps_pattern_matching">10.3 Pattern matching rules</A>
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>
466 <LI><A HREF="#Typemaps_nn21">10.4 Code generation rules</A>
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
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>
482 <LI><A HREF="#Typemaps_nn25">10.5 Common typemap methods</A>
484 <LI><A HREF="#Typemaps_nn26">10.5.1 "in" typemap</A></LI>
485 <LI><A HREF="#Typemaps_nn27">10.5.2 "typecheck" typemap</A></LI>
486 <LI><A HREF="#Typemaps_nn28">10.5.3 "out" typemap</A></LI>
487 <LI><A HREF="#Typemaps_nn29">10.5.4 "arginit" typemap</A></LI>
488 <LI><A HREF="#Typemaps_nn30">10.5.5 "default" typemap</A></LI>
489 <LI><A HREF="#Typemaps_nn31">10.5.6 "check" typemap</A></LI>
490 <LI><A HREF="#Typemaps_nn32">10.5.7 "argout" typemap</A></LI>
491 <LI><A HREF="#Typemaps_nn33">10.5.8 "freearg" typemap</A></LI>
492 <LI><A HREF="#Typemaps_nn34">10.5.9 "newfree" typemap</A></LI>
493 <LI><A HREF="#Typemaps_nn35">10.5.10 "memberin" typemap</A></LI>
494 <LI><A HREF="#Typemaps_nn36">10.5.11 "varin" typemap</A></LI>
495 <LI><A HREF="#Typemaps_nn37">10.5.12 "varout" typemap</A></LI>
496 <LI><A HREF="#throws_typemap">10.5.13 "throws" typemap</A></LI>
499 <LI><A HREF="#Typemaps_nn39">10.6 Some typemap examples</A>
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
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
511 <LI><A HREF="#runtime_type_checker">10.10 The run-time type checker</A>
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>
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++ "this" pointer</A></LI>
522 <LI><A HREF="#Typemaps_nn51">10.16 Where to go for more information?</A></LI>
524 <B><A HREF="#Customization">11 Customization Features</A></B>
526 <LI><A HREF="#exception">11.1 Exception handling with %exception</A>
528 <LI><A HREF="#Customization_nn3">11.1.1 Handling exceptions in C code</A>
530 <LI><A HREF="#Customization_nn4">11.1.2 Exception handling with
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
535 <LI><A HREF="#Customization_nn6">11.1.5 Defining different exception
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>
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>
546 <LI><A HREF="#Customization_feature_attributes">11.3.1 Feature
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>
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>
557 <B><A HREF="#Contract">12 Contracts</A></B>
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>
565 <B><A HREF="#Varargs">13 Variable Length Arguments</A></B>
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>
577 <B><A HREF="#Warnings">14 Warning Messages</A></B>
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>
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>
596 <LI><A HREF="#Warnings_nn16">14.9.7 User defined (900-999)</A></LI>
599 <LI><A HREF="#Warnings_nn17">14.10 History</A></LI>
601 <B><A HREF="#Modules">15 Working with Modules</A></B>
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>
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>
612 <B><A HREF="#CCache">16 Using SWIG with ccache - ccache-swig(1) manpage</A>
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>
633 <B><A HREF="#Allegrocl_nn1">17 SWIG and Allegro Common Lisp</A></B>
635 <LI><A HREF="#Allegrocl_nn2">17.1 Basics</A>
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
643 <LI><A HREF="#Allegrocl_nn6">17.2 Wrapping Overview</A>
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
652 <LI><A HREF="#Allegrocl_nn13">17.2.7 Object Wrapping</A></LI>
655 <LI><A HREF="#Allegrocl_nn14">17.3 Wrapping Details</A>
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
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>
672 <LI><A HREF="#Allegrocl_nn25">17.3.7 Templates</A>
674 <LI><A HREF="#Allegrocl_nn26">17.3.7.1 Generating wrapper code for
676 <LI><A HREF="#Allegrocl_nn27">17.3.7.2 Implicit Template instantiation</A>
680 <LI><A HREF="#Allegrocl_nn28">17.3.8 Typedef, Templates, and Synonym
683 <LI><A HREF="#Allegrocl_nn29">17.3.8.1 Choosing a primary type</A></LI>
686 <LI><A HREF="#Allegrocl_nn30">17.3.9 Function overloading/Parameter
688 <LI><A HREF="#Allegrocl_nn31">17.3.10 Operator wrapping and Operator
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>
696 <LI><A HREF="#Allegrocl_nn35">17.4 Typemaps</A>
698 <LI><A HREF="#Allegrocl_nn36">17.4.1 Code Generation in the C++ Wrapper</A>
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>
705 <LI><A HREF="#Allegrocl_nn40">17.4.2 Code generation in Lisp wrappers</A>
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>
714 <LI><A HREF="#Allegrocl_nn46">17.4.3 Modifying SWIG behavior using
718 <LI><A HREF="#Allegrocl_nn47">17.5 Identifier Converter functions</A>
720 <LI><A HREF="#Allegrocl_nn48">17.5.1 Creating symbols in the lisp
722 <LI><A HREF="#Allegrocl_nn49">17.5.2 Existing identifier-converter
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
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>
738 <B><A HREF="#CSharp">18 SWIG and C#</A></B>
740 <LI><A HREF="#csharp_introduction">18.1 Introduction</A></LI>
741 <LI><A HREF="#csharp_differences_java">18.2 Differences to the Java
743 <LI><A HREF="#CSharp_arrays">18.3 C# Arrays</A>
745 <LI><A HREF="#CSharp_arrays_swig_library">18.3.1 The SWIG C arrays
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>
753 <LI><A HREF="#csharp_exceptions">18.4 C# Exceptions</A>
755 <LI><A HREF="#csharp_exception_example_check_typemap">18.4.1 C#
756 exception example using "check" 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>
765 <LI><A HREF="#csharp_directors">18.5 C# Directors</A>
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>
773 <LI><A HREF="#csharp_typemap_examples">18.6 C# Typemap examples</A>
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>
790 <B><A HREF="#Chicken">19 SWIG and Chicken</A></B>
792 <LI><A HREF="#Chicken_nn2">19.1 Preliminaries</A>
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>
798 <LI><A HREF="#Chicken_nn5">19.2 Code Generation</A>
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>
807 <LI><A HREF="#Chicken_nn11">19.3 TinyCLOS</A></LI>
808 <LI><A HREF="#Chicken_nn12">19.4 Linkage</A>
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>
814 <LI><A HREF="#Chicken_nn15">19.4.3 Linking multiple SWIG modules with
818 <LI><A HREF="#Chicken_nn16">19.5 Typemaps</A></LI>
819 <LI><A HREF="#Chicken_nn17">19.6 Pointers</A>
821 <LI><A HREF="#collection">19.6.1 Garbage collection</A></LI>
824 <LI><A HREF="#Chicken_nn18">19.7 Unsupported features and known problems</A>
826 <LI><A HREF="#Chicken_nn19">19.7.1 TinyCLOS problems with Chicken
827 version <= 1.92</A></LI>
831 <B><A HREF="#Guile">20 SWIG and Guile</A></B>
833 <LI><A HREF="#Guile_nn2">20.1 Meaning of "Module"</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>
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>
842 <LI><A HREF="#Guile_nn9">20.3.5 Hobbit4D Linkage</A></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>
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>
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>
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>
864 <B><A HREF="#Java">21 SWIG and Java</A></B>
866 <LI><A HREF="#java_overview">21.1 Overview</A></LI>
867 <LI><A HREF="#java_preliminaries">21.2 Preliminaries</A>
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>
872 <LI><A HREF="#getting_right_headers">21.2.3 Getting the right header
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>
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>
882 <LI><A HREF="#visual_studio">21.2.8.1 Running SWIG from Visual Studio</A>
884 <LI><A HREF="#nmake">21.2.8.2 Using NMAKE</A></LI>
889 <LI><A HREF="#java_basic_tour">21.3 A tour of basic C/C++ wrapping</A>
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>
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>
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>
912 <LI><A HREF="#null_pointers">21.3.10.1 Null pointers</A></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>
922 <LI><A HREF="#further_details">21.4 Further details on the generated
925 <LI><A HREF="#imclass">21.4.1 The intermediary JNI class</A>
927 <LI><A HREF="#imclass_pragmas">21.4.1.1 The intermediary JNI class
931 <LI><A HREF="#java_module_class">21.4.2 The Java module class</A>
933 <LI><A HREF="#module_class_pragmas">21.4.2.1 The Java module class
937 <LI><A HREF="#java_proxy_classes">21.4.3 Java proxy classes</A>
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
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>
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>
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>
955 <LI><A HREF="#typeunsafe_enums_classes">21.4.5.3 Type unsafe enum
961 <LI><A HREF="#java_directors">21.5 Cross language polymorphism using
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>
968 <LI><A HREF="#java_directors_example">21.5.4 Simple directors example</A>
970 <LI><A HREF="#java_directors_threading">21.5.5 Director threading issues</A>
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>
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>
985 <LI><A HREF="#tips_techniques">21.8 Tips and techniques</A>
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>
996 <LI><A HREF="#java_typemaps">21.9 Java typemaps</A>
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
1015 <LI><A HREF="#typemap_examples">21.10 Typemap Examples</A>
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
1035 <LI><A HREF="#struct_pointer_pointer">21.10.10 Struct pointer to pointer</A>
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>
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>
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
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>
1057 <LI><A HREF="#java_examples">21.13 Examples</A></LI>
1059 <B><A HREF="#Lisp_nn1">22 SWIG and Common Lisp</A></B>
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>
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>
1071 <LI><A HREF="#Lisp_nn8">22.3 CLISP</A>
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>
1077 <LI><A HREF="#Lisp_nn11">22.4 UFFI</A></LI>
1079 <B><A HREF="#Lua_nn1">23 SWIG and Lua</A></B>
1081 <LI><A HREF="#Lua_nn2">23.1 Preliminaries</A></LI>
1082 <LI><A HREF="#Lua_nn3">23.2 Running SWIG</A>
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>
1089 <LI><A HREF="#Lua_nn7">23.3 A tour of basic C/C++ wrapping</A>
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>
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>
1109 <LI><A HREF="#Lua_nn23">23.4 Typemaps</A>
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>
1118 <LI><A HREF="#Lua_nn28">23.5 Writing typemaps</A>
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>
1124 <LI><A HREF="#Lua_nn31">23.6 Customization of your Bindings</A>
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>
1130 <LI><A HREF="#Lua_nn34">23.7 Details on the Lua binding</A>
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>
1138 <B><A HREF="#Modula3">24 SWIG and Modula-3</A></B>
1140 <LI><A HREF="#modula3_overview">24.1 Overview</A>
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>
1148 <LI><A HREF="#conception">24.2 Conception</A>
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>
1154 <LI><A HREF="#preliminaries">24.3 Preliminaries</A>
1156 <LI><A HREF="#compilers">24.3.1 Compilers</A></LI>
1157 <LI><A HREF="#commandline">24.3.2 Additional Commandline Options</A></LI>
1160 <LI><A HREF="#modula3_typemaps">24.4 Modula-3 typemaps</A>
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>
1170 <LI><A HREF="#hints">24.5 More hints to the generator</A>
1172 <LI><A HREF="#features">24.5.1 Features</A></LI>
1173 <LI><A HREF="#pragmas">24.5.2 Pragmas</A></LI>
1176 <LI><A HREF="#remarks">24.6 Remarks</A></LI>
1178 <B><A HREF="#MzScheme">25 SWIG and MzScheme</A></B>
1180 <LI><A HREF="#MzScheme_nn2">25.1 Creating native MzScheme structures</A></LI>
1182 <B><A HREF="#Ocaml">26 SWIG and Ocaml</A></B>
1184 <LI><A HREF="#Ocaml_nn2">26.1 Preliminaries</A>
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
1194 <LI><A HREF="#Ocaml_nn8">26.2 The low-level Ocaml/C interface</A>
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>
1199 <LI><A HREF="#Ocaml_nn11">26.2.2.1 Enum typing in Ocaml</A></LI>
1202 <LI><A HREF="#Ocaml_nn12">26.2.3 Arrays</A>
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>
1211 <LI><A HREF="#Ocaml_nn17">26.2.4 C++ Classes</A>
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>
1219 <LI><A HREF="#Ocaml_nn22">26.2.5 Director Classes</A>
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>
1232 <LI><A HREF="#Ocaml_nn31">26.2.6 Exceptions</A></LI>
1236 <B><A HREF="#Octave">27 SWIG and Octave</A></B>
1238 <LI><A HREF="#Octave_nn2">27.1 Preliminaries</A></LI>
1239 <LI><A HREF="#Octave_nn3">27.2 Running SWIG</A>
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>
1245 <LI><A HREF="#Octave_nn7">27.3 A tour of basic C/C++ wrapping</A>
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++
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>
1268 <B><A HREF="#Perl5">28 SWIG and Perl5</A></B>
1270 <LI><A HREF="#Perl5_nn2">28.1 Overview</A></LI>
1271 <LI><A HREF="#Perl5_nn3">28.2 Preliminaries</A>
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>
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
1281 <LI><A HREF="#Perl5_nn10">28.2.7 Compiling for 64-bit platforms</A></LI>
1284 <LI><A HREF="#Perl5_nn11">28.3 Building Perl Extensions under Windows</A>
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>
1290 <LI><A HREF="#Perl5_nn14">28.4 The low-level interface</A>
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>
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>
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>
1314 <LI><A HREF="#Perl5_nn32">28.8 Typemap Examples</A>
1316 <LI><A HREF="#Perl5_nn33">28.8.1 Converting a Perl5 array to a char **</A>
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>
1323 <LI><A HREF="#Perl5_nn38">28.8.6 Pointer handling</A></LI>
1326 <LI><A HREF="#Perl5_nn39">28.9 Proxy classes</A>
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>
1337 <LI><A HREF="#Perl5_nn47">28.10 Adding additional Perl code</A></LI>
1339 <B><A HREF="#Php">29 SWIG and PHP</A></B>
1341 <LI><A HREF="#Php_nn1">29.1 Generating PHP Extensions</A>
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>
1347 <LI><A HREF="#Php_nn2">29.2 Basic PHP interface</A>
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>
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>
1362 <LI><A HREF="#Php_nn2_7">29.2.7 PHP Pragmas, Startup and Shutdown code</A>
1366 <LI><A HREF="#Php_nn3">29.3 Cross language polymorphism</A>
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>
1378 <B><A HREF="#Pike">30 SWIG and Pike</A></B>
1380 <LI><A HREF="#Pike_nn2">30.1 Preliminaries</A>
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>
1387 <LI><A HREF="#Pike_nn6">30.2 Basic C/C++ Mapping</A>
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>
1398 <B><A HREF="#Python">31 SWIG and Python</A></B>
1400 <LI><A HREF="#Python_nn2">31.1 Overview</A></LI>
1401 <LI><A HREF="#Python_nn3">31.2 Preliminaries</A>
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
1414 <LI><A HREF="#Python_nn13">31.3 A tour of basic C/C++ wrapping</A>
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
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>
1435 <LI><A HREF="#Python_nn28">31.4 Further details on the Python class
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>
1443 <LI><A HREF="#Python_directors">31.5 Cross language polymorphism</A>
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>
1454 <LI><A HREF="#Python_nn40">31.6 Common customization features</A>
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>
1462 <LI><A HREF="#Python_nn45">31.7 Tips and techniques</A>
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>
1473 <LI><A HREF="#Python_nn53">31.8 Typemaps</A>
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>
1481 <LI><A HREF="#Python_nn58">31.9 Typemap Examples</A>
1483 <LI><A HREF="#Python_nn59">31.9.1 Converting Python list to a char **</A>
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
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>
1494 <LI><A HREF="#Python_nn65">31.10 Docstring Features</A>
1496 <LI><A HREF="#Python_nn66">31.10.1 Module docstring</A></LI>
1497 <LI><A HREF="#Python_nn67">31.10.2 %feature("autodoc")</A>
1499 <LI><A HREF="#Python_nn68">31.10.2.1 %feature("autodoc", "0")</A></LI>
1500 <LI><A HREF="#Python_nn69">31.10.2.2 %feature("autodoc", "1")</A></LI>
1501 <LI><A HREF="#Python_nn70">31.10.2.3 %feature("autodoc", "docstring")</A>
1505 <LI><A HREF="#Python_nn71">31.10.3 %feature("docstring")</A></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>
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>
1517 <B><A HREF="#Ruby">32 SWIG and Ruby</A></B>
1519 <LI><A HREF="#Ruby_nn2">32.1 Preliminaries</A>
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>
1529 <LI><A HREF="#Ruby_nn9">32.2 Building Ruby Extensions under Windows
1532 <LI><A HREF="#Ruby_nn10">32.2.1 Running SWIG from Developer Studio</A></LI>
1535 <LI><A HREF="#Ruby_nn11">32.3 The Ruby-to-C/C++ Mapping</A>
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>
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>
1556 <LI><A HREF="#Ruby_nn26">32.3.17.1 Exception Unrolling</A></LI>
1561 <LI><A HREF="#Ruby_nn27">32.4 Naming</A>
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>
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>
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>
1578 <LI><A HREF="#Ruby_nn37">32.7 Typemaps</A>
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>
1586 <LI><A HREF="#Ruby_nn39">32.7.6 Ruby typemaps</A>
1588 <LI><A HREF="#Ruby_in_typemap">32.7.6.1 "in" typemap</A></LI>
1589 <LI><A HREF="#Ruby_typecheck_typemap">32.7.6.2 "typecheck" typemap</A></LI>
1590 <LI><A HREF="#Ruby_out_typemap">32.7.6.3 "out" typemap</A></LI>
1591 <LI><A HREF="#Ruby_arginit_typemap">32.7.6.4 "arginit" typemap</A></LI>
1592 <LI><A HREF="#Ruby_default_typemap">32.7.6.5 "default" typemap</A></LI>
1593 <LI><A HREF="#Ruby_check_typemap">32.7.6.6 "check" typemap</A></LI>
1594 <LI><A HREF="#Ruby_argout_typemap_">32.7.6.7 "argout" typemap</A></LI>
1595 <LI><A HREF="#Ruby_freearg_typemap_">32.7.6.8 "freearg" typemap</A></LI>
1596 <LI><A HREF="#Ruby_newfree_typemap">32.7.6.9 "newfree" typemap</A></LI>
1597 <LI><A HREF="#Ruby_memberin_typemap">32.7.6.10 "memberin" typemap</A></LI>
1598 <LI><A HREF="#Ruby_varin_typemap">32.7.6.11 "varin" typemap</A></LI>
1599 <LI><A HREF="#Ruby_varout_typemap_">32.7.6.12 "varout" typemap</A></LI>
1600 <LI><A HREF="#Ruby_throws_typemap">32.7.6.13 "throws" 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>
1604 <LI><A HREF="#Ruby_directorargout_typemap">32.7.6.16 directorargout
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>
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>
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>
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>
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>
1626 <LI><A HREF="#Ruby_nn51">32.7.12.1 Ruby Datatype Wrapping</A></LI>
1629 <LI><A HREF="#Ruby_nn52">32.7.13 Example: STL Vector to Ruby Array</A></LI>
1632 <LI><A HREF="#Ruby_nn65">32.8 Docstring Features</A>
1634 <LI><A HREF="#Ruby_nn66">32.8.1 Module docstring</A></LI>
1635 <LI><A HREF="#Ruby_nn67">32.8.2 %feature("autodoc")</A>
1637 <LI><A HREF="#Ruby_nn68">32.8.2.1 %feature("autodoc", "0")</A></LI>
1638 <LI><A HREF="#Ruby_autodoc1">32.8.2.2 %feature("autodoc", "1")</A></LI>
1639 <LI><A HREF="#Ruby_autodoc2">32.8.2.3 %feature("autodoc", "2")</A></LI>
1640 <LI><A HREF="#Ruby_feature_autodoc3">32.8.2.4 %feature("autodoc", "3")</A>
1642 <LI><A HREF="#Ruby_nn70">32.8.2.5 %feature("autodoc", "docstring")</A></LI>
1645 <LI><A HREF="#Ruby_nn71">32.8.3 %feature("docstring")</A></LI>
1648 <LI><A HREF="#Ruby_nn53">32.9 Advanced Topics</A>
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>
1655 <LI><A HREF="#Ruby_nn57">32.10 Memory Management</A>
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>
1666 <B><A HREF="#Tcl">33 SWIG and Tcl</A></B>
1668 <LI><A HREF="#Tcl_nn2">33.1 Preliminaries</A>
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>
1680 <LI><A HREF="#Tcl_nn11">33.2 Building Tcl/Tk Extensions under Windows
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>
1687 <LI><A HREF="#Tcl_nn14">33.3 A tour of basic C/C++ wrapping</A>
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>
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>
1706 <LI><A HREF="#Tcl_nn29">33.4 Further details on the Tcl class interface</A>
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>
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>
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>
1726 <LI><A HREF="#Tcl_nn43">33.8 Turning a SWIG module into a Tcl Package.</A>
1728 <LI><A HREF="#Tcl_nn44">33.9 Building new kinds of Tcl interfaces (in
1731 <LI><A HREF="#Tcl_nn45">33.9.1 Proxy classes</A></LI>
1734 <LI><A HREF="#Tcl_nn46">33.10 Tcl/Tk Stubs</A></LI>
1736 <B><A HREF="#R">34 SWIG and R</A></B>
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>
1746 <B><A HREF="#Extending">35 Extending SWIG to support new languages</A></B>
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>
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>
1763 <LI><A HREF="#Extending_nn14">35.5 Primitive Data Structures</A>
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>
1773 <LI><A HREF="#Extending_nn21">35.6 Navigating and manipulating parse
1775 <LI><A HREF="#Extending_nn22">35.7 Working with attributes</A></LI>
1776 <LI><A HREF="#Extending_nn23">35.8 Type system</A>
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>
1786 <LI><A HREF="#Extending_nn30">35.9 Parameters</A></LI>
1787 <LI><A HREF="#Extending_nn31">35.10 Writing a Language Module</A>
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>
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>
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
1809 <LI><A HREF="#Extending_nn44">35.11 Typemaps</A>
1811 <LI><A HREF="#Extending_nn45">35.11.1 Proxy classes</A></LI>
1814 <LI><A HREF="#Extending_nn46">35.12 Guide to parse tree nodes</A></LI>
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
1825 <H3><A NAME="1_1_1">SWIG Core Documentation</A></H3>
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>
1844 <H3><A NAME="1_1_2">Language Module Documentation</A></H3>
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>
1865 <H3><A NAME="1_1_3">Developer Documentation</A></H3>
1867 <LI><A href="#Extending">Extending SWIG</A></LI>
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>
1877 <LI><A href="Advanced.html#Advanced">Advanced topics</A> (see <A href="#Modules">
1878 Modules</A> for updated information).</LI>
1881 <H1><A name="Preface"></A>1 Preface</H1>
1884 <DIV class="sectiontoc">
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>
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,
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>
1937 <A href="http://www.swig.org">http://www.swig.org</A>
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
1947 <A href="http://www.swig.org/mail.html">http://www.swig.org/mail.html</A>
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>
1956 <A href="http://www.swig.org/svn.html">http://www.swig.org/svn.html</A>
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 "Introduction" 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
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>
2011 #if SWIG_VERSION >= 0x010311
2012 /* Use some fancy new feature */
2016 <P> Note: The version symbol is not defined in the generated SWIG
2017 wrapper file. The SWIG preprocessor has defined SWIG_VERSION since
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ö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>
2048 <H1><A name="Introduction"></A>2 Introduction</H1>
2051 <DIV class="sectiontoc">
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>
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>
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
2068 <LI><A href="#Introduction_nn12">Hands off code generation</A></LI>
2069 <LI><A href="#Introduction_nn13">SWIG and freedom</A></LI>
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>
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>
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>
2113 <LI>Excellent support for writing programming libraries.</LI>
2114 <LI>High performance (number crunching, data processing, graphics,
2116 <LI>Systems programming and systems integration.</LI>
2117 <LI>Large user community and software base.</LI>
2119 <P> Next, let's list a few problems with C/C++ programming</P>
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>
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>
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>
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>
2167 /* File : example.c */
2169 double My_variable = 3.0;
2171 /* Compute factorial of n */
2173 if (n <= 1) return 1;
2174 else return n*fact(n-1);
2177 /* Compute n mod m */
2178 int my_mod(int n, int m) {
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
2187 <H3><A name="Introduction_nn5"></A>2.3.1 SWIG interface file</H3>
2190 /* File : example.i */
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);
2199 extern double My_variable;
2200 extern int fact(int);
2201 extern int my_mod(int n, int m);
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>
2214 unix > <B>swig -tcl example.i</B>
2215 unix > <B>gcc -c -fpic example.c example_wrap.c -I/usr/local/include</B>
2216 unix > <B>gcc -shared example.o example_wrap.o -o example.so</B>
2217 unix > <B>tclsh</B>
2218 % <B>load ./example.so</B>
2221 % <B>my_mod 23 7</B>
2223 % <B>expr $My_variable + 4.5</B>
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>
2241 unix > <B>swig -perl5 example.i</B>
2242 unix > <B>gcc -c example.c example_wrap.c \
2243 -I/usr/local/lib/perl5/sun4-solaris/5.003/CORE</B>
2244 unix > <B>ld -G example.o example_wrap.o -o example.so</B> # This is for Solaris
2245 unix > <B>perl5.003
2247 print example::fact(4), "\n";
2248 print example::my_mod(23,7), "\n";
2249 print $example::My_variable + 4.5, "\n";
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>
2261 unix > <B>swig -python example.i</B>
2262 unix > <B>gcc -c -fpic example.c example_wrap.c -I/usr/local/include/python2.0</B>
2263 unix > <B>gcc -shared example.o example_wrap.o -o _example.so</B>
2264 unix > <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 "copyright", "credits" or "license" for more information.
2268 >>> <B>import example</B>
2269 >>> <B>example.fact(4)</B>
2271 >>> <B>example.my_mod(23,7)</B>
2273 >>> <B>example.cvar.My_variable + 4.5</B>
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>
2284 unix > <B>swig -perl5 -module example example.h</B>
2285 unix > <B>gcc -c example.c example_wrap.c \
2286 -I/usr/local/lib/perl5/sun4-solaris/5.003/CORE</B>
2287 unix > <B>ld -G example.o example_wrap.o -o example.so</B>
2288 unix > <B>perl5.003
2290 print example::fact(4), "\n";
2291 print example::my_mod(23,7), "\n";
2292 print $example::My_variable + 4.5, "\n";
2299 <H2><A name="Introduction_nn10"></A>2.4 Supported C/C++ language
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>
2306 <LI>Full C99 preprocessing.</LI>
2307 <LI>All ANSI C and C++ datatypes.</LI>
2308 <LI>Functions, variables, and constants.</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>
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
2337 <H2><A name="Introduction_build_system"></A>2.6 Incorporating SWIG into
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,
2367 # This is a CMake example for Python
2369 FIND_PACKAGE(SWIG REQUIRED)
2370 INCLUDE(${SWIG_USE_FILE})
2372 FIND_PACKAGE(PythonLibs)
2373 INCLUDE_DIRECTORIES(${PYTHON_INCLUDE_PATH})
2375 INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR})
2377 SET(CMAKE_SWIG_FLAGS "")
2379 SET_SOURCE_FILES_PROPERTIES(example.i PROPERTIES CPLUSPLUS ON)
2380 SET_SOURCE_FILES_PROPERTIES(example.i PROPERTIES SWIG_FLAGS "-includeall")
2381 SWIG_ADD_MODULE(example python example.i example.cxx)
2382 SWIG_LINK_LIBRARIES(example ${PYTHON_LIBRARIES})
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 "philosophy" 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 "shooting yourself in the foot" 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>
2420 <H1><A name="Windows"></A>3 Getting started on Windows</H1>
2423 <DIV class="sectiontoc">
2425 <LI><A href="#Windows_installation">Installation on Windows</A>
2427 <LI><A href="#Windows_executable">Windows Executable</A></LI>
2430 <LI><A href="#Windows_examples">SWIG Windows Examples</A>
2432 <LI><A href="#Windows_visual_studio">Instructions for using the Examples
2433 with Visual Studio</A>
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>
2444 <LI><A href="#Windows_other_compilers">Instructions for using the
2445 Examples with other compilers</A></LI>
2448 <LI><A href="#Windows_cygwin_mingw">SWIG on Cygwin and MinGW</A>
2450 <LI><A href="#Windows_swig_exe">Building swig.exe on Windows</A>
2452 <LI><A href="#Windows_mingw_msys">Building swig.exe using MinGW and MSYS</A>
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>
2459 <LI><A href="#Windows_examples_cygwin">Running the examples on Windows
2460 using Cygwin</A></LI>
2463 <LI><A href="#Windows_interface_file">Microsoft extensions and other
2464 Windows quirks</A></LI>
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
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>
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
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
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
2528 <BR><B> <TT>JAVA_BIN</TT></B> : Set this to the bin directory containing
2530 <P> Example using JDK1.3:
2531 <BR> <TT>JAVA_INCLUDE: D:\jdk1.3\include
2532 <BR> JAVA_BIN: D:\jdk1.3\bin
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
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
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
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
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
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
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
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
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
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
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
2601 <P> The short abbreviated instructions follow...</P>
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>
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>
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.
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>
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,
2635 <LI>Answer y to the "do you wish to continue with the post install?"</LI>
2636 <LI>Answer y to the "do you have MinGW installed?"</LI>
2637 <LI>Type in the the folder in which you installed MinGW (C:/MinGW is
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
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>
2651 <LI> Start the MSYS command prompt and execute:<DIV class="shell">
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
2659 <LI> To get the latest SWIG SVN (version from Subversion source
2660 control), type in the following:<DIV class="shell">
2664 svn co https://swig.svn.sourceforge.net/svnroot/swig/trunk swig
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">
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
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>
2712 %include <windows.i>
2714 __declspec(dllexport) ULONG __stdcall foo(DWORD, __int32);
2717 <H1><A name="Scripting"></A>4 Scripting Languages</H1>
2720 <DIV class="sectiontoc">
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>
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>
2732 <LI><A href="#Scripting_nn9">Building scripting language extensions</A>
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>
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 "commands." 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
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
2766 <H2><A name="Scripting_nn3"></A>4.2 How does a scripting language talk
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
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 "wrapper"
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
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>
2789 if (n <= 1) return 1;
2790 else return n*fact(n-1);
2794 <P> In order to access this function from a scripting language, it is
2795 necessary to write a special "wrapper" 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>
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
2804 <P> As an example, the Tcl wrapper function for the <TT>fact()</TT>
2805 function above example might look like the following :</P>
2808 int wrap_fact(ClientData clientData, Tcl_Interp *interp,
2809 int argc, char *argv[]) {
2813 interp->result = "wrong # args";
2816 arg0 = atoi(argv[1]);
2817 result = fact(arg0);
2818 sprintf(interp->result,"%d", result);
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>
2831 int Wrap_Init(Tcl_Interp *interp) {
2832 Tcl_CreateCommand(interp, "fact", wrap_fact, (ClientData) NULL,
2833 (Tcl_CmdDeleteProc *) NULL);
2838 <P> When executed, Tcl will now have a new command called "<TT>fact</TT>
2839 " 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>
2853 <P> It might be nice to access it from a script as follows (shown for
2855 <DIV class="targetlang">
2857 $a = $Foo * 2.3; # Evaluation
2858 $Foo = $a + 2.0; # Assignment
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 "get" function is invoked. Similarly, whenever the
2864 value of a variable is changed, a "set" 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>
2875 #define RED 0xff0000
2876 #define BLUE 0x0000ff
2877 #define GREEN 0x00ff00
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
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
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>
2906 <P> can be transformed into the following set of functions :</P>
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);
2920 <P> Now, from an interpreter these function might be used as follows:</P>
2921 <DIV class="targetlang">
2923 % set v [new_Vector]
2924 % Vector_x_set $v 3.5
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>
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">
2955 >>> v = Vector()
2956 >>> v.x = 3
2957 >>> v.y = 4
2958 >>> v.z = -13
2963 <P> Similarly, in Perl5 you may want the interface to work like this:</P>
2964 <DIV class="targetlang">
2973 <P> Finally, in Tcl :</P>
2974 <DIV class="targetlang">
2977 v configure -x 3 -y 4 -z 13
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
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
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>
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
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
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
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">
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>
3032 c++ -shared example.o example_wrap.o -o example.so
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
3041 <DIV class="targetlang">
3043 >>> import graph
3044 Traceback (innermost last):
3045 File "<stdin>", line 1, in ?
3046 File "/home/sci/data1/beazley/graph/graph.py", line 2, in ?
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:
3054 <P> What this error means is that the extension module created by SWIG
3055 depends upon a shared library called "<TT>libgraph.so</TT>" that the
3056 system was unable to locate. To fix this problem, there are a few
3057 approaches you can take.</P>
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
3065 <LI>Put shared libraries in the same directory as the executable. This
3066 technique is sometimes required for correct operation on non-Unix
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>
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>
3084 <H1><A name="SWIG"></A>5 SWIG Basics</H1>
3087 <DIV class="sectiontoc">
3089 <LI><A href="#SWIG_nn2">Running SWIG</A>
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>
3099 <LI><A href="#SWIG_nn9">Wrapping Simple C Declarations</A>
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>
3108 <LI><A href="#SWIG_nn15">Pointers and complex objects</A>
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>
3117 <LI><A href="#SWIG_nn21">Other Practicalities</A>
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>
3130 <LI><A href="#SWIG_nn31">Structures and unions</A>
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
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>
3144 <LI><A href="#SWIG_nn40">Code Insertion</A>
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>
3152 <LI><A href="#SWIG_nn45">An Interface Building Strategy</A>
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>
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>
3174 swig [ <EM>options</EM> ] filename
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>
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
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
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>
3235 #include "myheader.h"
3237 // Now list ANSI C/C++ declarations
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>
3272 $ swig -c++ -python -o example_wrap.cpp example.i
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
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>
3288 $ swig -c++ -python -outdir pyfiles -o cppfiles/example_wrap.cpp example.i
3291 <P> If the directories <TT>cppfiles</TT> and <TT>pyfiles</TT> exist, the
3292 following will be generated:</P>
3295 cppfiles/example_wrap.cpp
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 "<A href="#Preprocessor">Preprocessor</A>" 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 "<TT>%</TT>" 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>
3338 /* header.h --- Some header file */
3340 /* SWIG directives -- only seen if SWIG is running */
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
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">
3359 /* Non-conventional placement of storage specifier (extern) */
3360 const int extern Number;
3362 /* Extra declarator grouping */
3363 Matrix (foo); // A global variable
3365 /* Extra declarator grouping in parameters */
3366 void bar(Spam (Grok)(Doh));
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>
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">
3381 /* Not supported by SWIG */
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
3391 <P> In the event of a parsing error, conditional compilation can be used
3392 to skip offending code. For example:</P>
3396 ... some bad declarations ...
3400 <P> Alternatively, you can just delete the offending code from the
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&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>
3422 extern double sin(double x);
3423 extern int strcmp(const char *, const char *);
3427 #define VERSION "1.1"
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">
3449 <P> Or in Python:</P>
3450 <DIV class="targetlang">
3452 >>> example.sin(3)
3454 >>> example.strcmp('Dave','Mike')
3456 >>> print example.cvar.Foo
3458 >>> print example.STATUS
3460 >>> print example.VERSION
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
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
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>
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
3499 <!-- Dave: Maybe we should fix this -->
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
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
3526 <P> SWIG recognizes the following floating point types :</P>
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 "foo" 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>
3576 <P> results in a scripting language variable like this:</P>
3580 set foo [3.5] ;# Set foo to 3.5
3581 puts $foo ;# Print the value of foo
3584 cvar.foo = 3.5 # Set foo to 3.5
3585 print cvar.foo # Print value of foo
3588 $foo = 3.5; # Set foo to 3.5
3589 print $foo,"\n"; # Print value of foo
3592 Module.foo = 3.5 # Set foo to 3.5
3593 print Module.foo, "\n" # Print value of foo
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>
3616 #define I_CONST 5 // An integer constant
3617 #define PI 3.14159 // A Floating point constant
3618 #define S_CONST "hello world" // A string constant
3619 #define NEWLINE '\n' // Character constant
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;
3626 #define FLAGS 0x04 | 0x08 | 0x40
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>
3639 #define EXTERN extern
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>
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>
3658 #define F_CONST (double) 5 // A floating pointer constant with cast
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
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>
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
3701 <P> Here is an example of a declaration that is not <TT>const</TT>:</P>
3704 const char *e; // A pointer to a constant character. The pointer
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 "read-only" 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
3730 %constant double PI = 3.14159;
3737 #define const %constant
3739 const double foo = 3.4;
3740 const double bar = 23.4;
3741 const int spam = 42;
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>
3762 char *strcat(char *s, const char *t)
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>
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">
3793 _1008e124_ppp_double
3797 <P> A NULL pointer is represented by the string "NULL" 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>
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>
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
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>
3852 FILE *fopen(char *, char *);
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);
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
3865 <DIV class="targetlang">
3868 def filecopy(source,target):
3869 f1 = fopen(source,"r")
3870 f2 = fopen(target,"w")
3871 buffer = malloc(8192)
3872 nbytes = fread(buffer,8192,1,f1)
3873 while (nbytes > 0):
3874 fwrite(buffer,8192,1,f2)
3875 nbytes = fread(buffer,8192,1,f1)
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>
3889 void matrix_multiply(Matrix *a, Matrix *b, Matrix *c);
3892 <P> SWIG has no idea what a "<TT>Matrix</TT>" 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
3908 void foo(size_t num);
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>
3918 TypeError: expected a _p_size_t.
3921 <P> The only way to fix this problem is to make sure you properly
3922 declare type names using <TT>typedef</TT>.</P>
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>
3930 typedef unsigned int size_t;
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>
3940 /* Include in the generated wrapper file */
3941 typedef unsigned int size_t;
3943 /* Tell SWIG about it */
3944 typedef unsigned int size_t;
3951 typedef unsigned int size_t;
3955 <P> In certain cases, you might be able to include other header files to
3956 collect type information. For example:</P>
3960 %import "sys/types.h"
3963 <P> In this case, you might run SWIG as follows:</P>
3966 $ swig -I/usr/include -includeall example.i
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
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>
3980 void foo(unsigned int *ptr);
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>
3995 double dot_product(Vector a, Vector b);
3998 <P> To deal with this, SWIG transforms the function to use pointers by
3999 creating a wrapper equivalent to the following:</P>
4002 double wrap_dot_product(Vector *a, Vector *b) {
4005 return dot_product(x,y);
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>
4017 Vector cross_product(Vector v1, Vector v2);
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>
4024 Vector *wrap_cross_product(Vector *v1, Vector *v2) {
4028 result = (Vector *) malloc(sizeof(Vector));
4029 *(result) = cross(x,y);
4034 <P> or if SWIG was run with the <TT>-c++</TT> option:</P>
4037 Vector *wrap_cross(Vector *v1, Vector *v2) {
4040 Vector *result = new Vector(cross(x,y)); // Uses default copy constructor
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>
4065 <P> gets mapped to an underlying pair of set/get functions like this :</P>
4068 Vector *unit_i_get() {
4071 void unit_i_set(Vector *value) {
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>
4090 <P> SWIG generates the following code:</P>
4094 void foo_set(char *value) {
4096 foo = (char *) malloc(strlen(value)+1);
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];
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>
4115 void set_foo(char *value) {
4116 strncpy(foo,value, 50);
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">
4126 >>> set_foo("Hello World")
4129 <P> A common mistake with <TT>char *</TT> variables is to link to a
4130 variable declared like this:</P>
4133 char *VERSION = "1.0";
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>
4147 char VERSION[64] = "1.0";
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>
4157 example.i:20. Typemap warning. Setting const char * variable may leak memory
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>
4164 const char *foo = "Hello World\n";
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
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>
4180 int foobar(int a[40]);
4181 void grok(char *argv[]);
4182 void transpose(double a[20][20]);
4185 <P> are processed as if they were really declared like this:</P>
4189 void grok(char **argv);
4190 void transpose(double (*a)[20]);
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
4196 <P> Multi-dimensional arrays are transformed into a pointer to an array
4197 of one less dimension. For example:</P>
4200 int [10]; // Maps to int *
4201 int [10][20]; // Maps to int (*)[20]
4202 int [10][20][30]; // Maps to int (*)[20][30]
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
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 &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>
4228 void a_set(int i, int j, int val) {
4231 int a_get(int i, int j) {
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>
4241 // Some array helpers
4243 /* Create any sort of [size] array */
4244 int *int_array(int size) {
4245 return (int *) malloc(size*sizeof(int));
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));
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>
4262 <P> SWIG generates functions for both getting and setting the value that
4263 are equivalent to the following code:</P>
4266 char *pathname_get() {
4269 void pathname_set(char *value) {
4270 strncpy(pathname,value,256);
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
4277 <P> A read-only variable can be created by using the <TT>%immutable</TT>
4278 directive as shown :</P>
4281 // File : interface.i
4283 int a; // Can read/write
4285 int b,c,d // Read only variables
4287 double x,y // read/write
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>
4296 %immutable x; // Make x read-only
4298 double x; // Read-only (from earlier %immutable directive)
4299 double y; // Read-write
4303 <P> The <TT>%mutable</TT> and <TT>%immutable</TT> directives are
4304 actually <A href="#features">%feature directives</A> defined like this:</P>
4307 #define %immutable %feature("immutable")
4308 #define %mutable %feature("immutable","")
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>
4315 %immutable; // Make all variables read-only
4316 %feature("immutable","0") x; // except, make x read/write
4324 <P> Read-only variables are also created when declarations are declared
4325 as <TT>const</TT>. For example:</P>
4328 const int foo; /* Read only variable */
4329 char * const version="1.0"; /* Read only variable */
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
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>
4348 %rename(my_print) print;
4349 extern void print(char *);
4351 %rename(foo) a_really_long_and_annoying_name;
4352 extern int a_really_long_and_annoying_name;
4356 <P> SWIG still calls the correct C function, but in this case the
4357 function <TT>print()</TT> will really be called "<TT>my_print()</TT>"
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>
4366 %rename(my_print) print;
4367 %rename(foo) a_really_long_and_annoying_name;
4369 %include "header.h"
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>
4380 %rename(output) print; // Rename all `print' functions to `output'
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>
4392 %ignore print; // Ignore all declarations named print
4393 %ignore _HAVE_FOO_H; // Ignore an include guard constant
4395 %include "foo.h" // Grab a header file
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
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>
4416 %name(output) extern void print(char *);
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>
4426 int plot(double x, double y, int color=WHITE);
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">
4434 % plot -3.4 7.5 # Use default value
4435 % plot -3.4 7.5 10 # set color to 10 instead
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
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>
4458 int binary_op(int a, int b, int (*op)(int,int));
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
4464 <DIV class="targetlang">
4466 >>> def add(x,y):
4469 >>> binary_op(3,4,add)
4470 Traceback (most recent call last):
4471 File "<stdin>", line 1, in ?
4472 TypeError: Type error. Expected _p_f_int_int__int
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>
4483 /* Function with a callback */
4484 int binary_op(int a, int b, int (*op)(int,int));
4486 /* Some callback functions */
4487 %constant int add(int,int);
4488 %constant int sub(int,int);
4489 %constant int mul(int,int);
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">
4497 >>> binary_op(3,4,add)
4499 >>> binary_op(3,4,mul)
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">
4508 >>> add(3,4)
4509 Traceback (most recent call last):
4510 File "<stdin>", line 1, in ?
4511 TypeError: object is not callable: '_ff020efc_p_f_int_int__int'
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>
4520 /* Function with a callback */
4521 int binary_op(int a, int b, int (*op)(int,int));
4523 /* Some callback functions */
4524 %callback("%s_cb");
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">
4538 >>> binary_op(3,4,add_cb)
4540 >>> binary_op(3,4,mul_cb)
4542 >>> add(3,4)
4544 >>> mul(3,4)
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>
4557 /* Some callback functions */
4558 %callback("%(upper)s");
4565 <P> A format string of <TT>"%(lower)s"</TT> converts all characters to
4566 lower-case. A string of <TT>"%(title)s"</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>
4590 <P> gets transformed into the following set of accessor functions :</P>
4593 double Vector_x_get(struct Vector *obj) {
4596 double Vector_y_get(struct Vector *obj) {
4599 double Vector_z_get(struct Vector *obj) {
4602 void Vector_x_set(struct Vector *obj, double value) {
4605 void Vector_y_set(struct Vector *obj, double value) {
4608 void Vector_z_set(struct Vector *obj, double value) {
4613 <P> In addition, SWIG creates default constructor and destructor
4614 functions if none are defined in the interface. For example:</P>
4617 struct Vector *new_Vector() {
4618 return (Vector *) calloc(1,sizeof(struct Vector));
4620 void delete_Vector(struct Vector *obj) {
4625 <P> Using these low-level accessor functions, an object can be minimally
4626 manipulated from the target language using code like this:</P>
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
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>
4656 double Vector_x_get(Vector *obj) {
4661 <P> If two different names are used like this :</P>
4664 typedef struct vector_struct {
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>
4692 <P> This results in the following accessor functions :</P>
4695 char *Foo_name_get(Foo *obj) {
4696 return Foo->name;
4699 char *Foo_name_set(Foo *obj, char *c) {
4700 if (obj->name) free(obj->name);
4701 obj->name = (char *) malloc(strlen(c)+1);
4702 strcpy(obj->name,c);
4703 return obj->name;
4707 <P> If this behavior differs from what you need in your applications,
4708 the SWIG "memberin" 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
4721 interface.i:116. Warning. Array member will be read-only
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
4727 <H3><A name="SWIG_structure_data_members"></A>5.5.4 Structure data
4729 <P> Occasionally, a structure will contain data members that are
4730 themselves structures. For example:</P>
4733 typedef struct Foo {
4737 typedef struct Bar {
4739 Foo f; /* struct member */
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>
4750 Foo *Bar_f_get(Bar *b) {
4751 return &b->f;
4753 void Bar_f_set(Bar *b, Foo *value) {
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>
4768 <P> Translating this assignment to function calls (as would be used
4769 inside the scripting language interface) results in the following code:</P>
4773 Foo_x_set(Bar_f_get(b),37);
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>
4790 <P> and nothing was known about <TT>WORD</TT>, then SWIG will generate
4791 more normal accessor functions like this:</P>
4794 WORD Foo_w_get(Foo *f) {
4797 void Foo_w_set(FOO *f, WORD value) {
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>"struct Foo;"</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>
4822 swig -nodefaultctor example.i
4830 %nodefaultctor; // Don't create default constructors
4831 ... declarations ...
4832 %clearnodefaultctor; // Re-enable default constructors
4835 <P> If you need more precise control, <TT>%nodefaultctor</TT> can
4836 selectively target individual structure definitions. For example:</P>
4839 %nodefaultctor Foo; // No default constructor for Foo
4841 struct Foo { // No default constructor generated.
4844 struct Bar { // Default constructor generated.
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>
4854 %nodefaultdtor Foo; // No default/implicit destructor for Foo
4856 struct Foo { // No default destructor is generated.
4859 struct Bar { // Default destructor generated.
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>
4886 /* file : vector.h */
4894 <P> You can make a <TT>Vector</TT> look a lot like a class by writing a
4895 SWIG interface like this:</P>
4901 #include "vector.h"
4904 %include "vector.h" // Just grab original C header file
4905 %extend Vector { // Attach these functions to struct Vector
4906 Vector(double x, double y, double z) {
4908 v = (Vector *) malloc(sizeof(Vector));
4917 double magnitude() {
4918 return sqrt($self->x*$self->x+$self->y*$self->y+$self->z*$self->z);
4921 printf("Vector [%g, %g, %g]\n", $self->x,$self->y,$self->z);
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
4938 <DIV class="targetlang">
4940 >>> v = Vector(3,4,0) # Create a new vector
4941 >>> print v.magnitude() # Print magnitude
4943 >>> v.print() # Print it out
4945 >>> del v # Destroy it
4948 <P> The <TT>%extend</TT> directive can also be used inside the
4949 definition of the Vector structure. For example:</P>
4955 #include "vector.h"
4961 Vector(double x, double y, double z) { ... }
4968 <P> Finally, <TT>%extend</TT> can be used to access externally written
4969 functions provided they follow the naming convention used in this
4973 /* File : vector.c */
4974 /* Vector methods */
4975 #include "vector.h"
4976 Vector *new_Vector(double x, double y, double z) {
4978 v = (Vector *) malloc(sizeof(Vector));
4984 void delete_Vector(Vector *v) {
4988 double Vector_magnitude(Vector *v) {
4989 return sqrt(v->x*v->x+v->y*v->y+v->z*v->z);
4996 #include "vector.h"
5002 Vector(int,int,int); // This calls new_Vector()
5003 ~Vector(); // This calls delete_Vector()
5004 double magnitude(); // This will call Vector_magnitude()
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>
5017 // Add a new attribute to Vector
5019 const double magnitude;
5021 // Now supply the implementation of the Vector_magnitude_get function
5023 const double Vector_magnitude_get(Vector *v) {
5024 return (const double) return sqrt(v->x*v->x+v->y*v->y+v->z*v->z);
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>
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>
5054 // Specific implementation of set/get functions
5056 char *Person_name_get(Person *p) {
5059 void Person_name_set(Person *p, char *val) {
5060 strncpy(p->name,val,50);
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>
5077 typedef struct Object {
5089 <P> When SWIG encounters this, it performs a structure splitting
5090 operation that transforms the declaration into the equivalent of the
5101 typedef struct Object {
5103 Object_intRep intRep;
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>
5113 Object_intRep *Object_intRep_get(Object *o) {
5114 return (Object_intRep *) &o->intRep;
5116 int Object_intRep_ivalue_get(Object_intRep *o) {
5117 return o->ivalue;
5119 int Object_intRep_ivalue_set(Object_intRep *o, int value) {
5120 return (o->ivalue = value);
5122 double Object_intRep_dvalue_get(Object_intRep *o) {
5123 return o->dvalue;
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">
5134 # Perl5 script for accessing nested member
5135 $o = CreateObject(); # Create an object somehow
5136 $o->{intRep}->{ivalue} = 7 # Change value of o.intRep.ivalue
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
5143 <H3><A name="SWIG_nn39"></A>5.5.8 Other things to note about structure
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>
5156 double Vector_x_get(Vector *v) {
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>
5168 _wrap_Vector_x_get(ClientData clientData, Tcl_Interp *interp,
5169 int objc, Tcl_Obj *CONST objv[]) {
5170 struct Vector *arg1 ;
5173 if (SWIG_GetArgs(interp, objc, objv,"p:Vector_x_get self ",&arg0,
5174 SWIGTYPE_p_Vector) == TCL_ERROR)
5176 result = (double ) (arg1->x);
5177 Tcl_SetObjResult(interp,Tcl_NewDoubleObj((double) result));
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>
5199 <LI><B>Begin section</B>.
5200 <BR> A placeholder to put code at the beginning of the C/C++ wrapper
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
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>
5222 ... code in begin section ...
5226 ... code in runtime section ...
5230 ... code in header section ...
5234 ... code in wrapper section ...
5238 ... code in init section ...
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>
5255 #include "my_header.h"
5257 ... Declare functions here
5260 void some_extra_function() {
5266 <P> A common use for code blocks is to write "helper" 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.
5273 /* Create a new vector */
5274 static Vector *new_Vector() {
5275 return (Vector *) malloc(sizeof(Vector));
5280 Vector *new_Vector();
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>
5289 /* Create a new vector */
5290 Vector *new_Vector() {
5291 return (Vector *) malloc(sizeof(Vector));
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>
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>
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
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
5348 <LI>Run SWIG and compile.</LI>
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>
5364 /* File : header.h */
5366 #include <stdio.h>
5367 #include <math.h>
5369 extern int foo(double);
5370 extern double bar(int, int);
5371 extern void dump(FILE *f);
5375 <P> A typical SWIG interface file for this header file would look like
5379 /* File : interface.i */
5382 #include "header.h"
5384 extern int foo(double);
5385 extern double bar(int, int);
5386 extern void dump(FILE *f);
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>
5394 /* File : interface.i */
5397 #include "header.h"
5399 %include "header.h"
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>
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
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>
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>
5434 #include <GL/gl.h>
5435 #include <GL/glu.h>
5438 // Put rest of declarations here
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>
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>
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>
5476 <H1><A name="SWIGPlus"></A>6 SWIG and C++</H1>
5479 <DIV class="sectiontoc">
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>
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>
5492 <LI><A href="#SWIGPlus_nn6">Simple C++ wrapping</A>
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>
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
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
5520 <LI><A href="#SWIGPlus_nn27">Comments on overloading</A></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->()</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>
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
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
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 "component" 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 "magic" 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
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++
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>
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>
5620 <LI>Templates (including specialization and member templates)</LI>
5621 <LI>Pointers to members</LI>
5623 <LI>Default parameters</LI>
5624 <LI>Smart pointers</LI>
5626 <P> The following C++ features are not currently supported:</P>
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>
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>
5649 $ swig -c++ -tcl example.i
5650 $ c++ -c example_wrap.cxx
5651 $ c++ example_wrap.o $(OBJS) -o example.so
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
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>
5684 <P> Using C++ as pseudocode, a proxy class looks something like this:</P>
5698 return Foo_bar(self,x);
5701 return Foo_x_get(self);
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">
5716 self.this = new_Foo()
5718 delete_Foo(self.this)
5720 return Foo_bar(self.this,x)
5721 def __getattr__(self,name):
5723 return Foo_x_get(self.this)
5725 def __setattr__(self,name,value):
5727 Foo_x_set(self.this,value)
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
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>
5756 <P> Consider some script code that uses these classes:</P>
5757 <DIV class="targetlang">
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
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>
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>
5804 thisown = 1; // Newly created object
5807 if (thisown) delete_Foo(self);
5810 // Ownership control API
5819 class FooPtrProxy: public FooProxy {
5821 FooPtrProxy(Foo *s) {
5829 FooProxy *value_get() {
5830 return FooPtrProxy(Spam_value_get(self));
5832 void value_set(FooProxy *v) {
5833 Spam_value_set(self,v->self);
5840 <P> Looking at this code, there are a few central features:</P>
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
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>
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++
5869 #include "list.h"
5872 // Very simple C++ example for linked list
5878 int search(char *value);
5879 void insert(char *);
5880 void remove(char *);
5883 static void print(List *l);
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>
5895 List * new_List(void) {
5898 void delete_List(List *l) {
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>
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>
5916 <LI> If a C++ class does not declare an explicit destructor, SWIG will
5917 automatically generate a wrapper for one.</LI>
5919 <P> And as in C++, a few rules that alters the previous behavior:</P>
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>
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
5945 <P> For example:</P>
5948 %nodefaultctor Foo; // Disable the default constructor for class Foo.
5949 class Foo { // No default constructor is generated, unless one is declared
5952 class Bar { // A default constructor is generated, if possible
5957 <P> The directive <TT>%nodefaultctor</TT> can also be applied
5958 "globally", as in:</P>
5961 %nodefaultctor; // Disable creation of default constructors
5962 class Foo { // No default constructor is generated, unless one is declared
5967 Bar(); // The default constructor is generated, since one is declared
5969 %clearnodefaultctor; // Enable the creation of default constructors again
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>
5979 %nodefaultdtor Foo; // Disable the implicit/default destructor for class Foo.
5980 class Foo { // No destructor is generated, unless one is declared
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
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
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>
6016 Foo(); // Not wrapped.
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
6029 Bar(); // Not wrapped. Bar is abstract.
6030 virtual void spam(void) = 0;
6033 class Grok : public Bar {
6035 Grok(); // Not wrapped. No implementation of abstract spam().
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>
6045 % swig -Wall -python module.i
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>
6052 %feature("notabstract") Foo;
6054 class Foo : public Bar {
6056 Foo(); // Generated no matter what---not abstract.
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>
6073 List(const List &); // Copy constructor
6078 <P> then the copy constructor can be used as follows:</P>
6079 <DIV class="targetlang">
6081 x = List() # Create a list
6082 y = List(x) # Copy list x
6085 <P> If the target language does not support overloading, then the copy
6086 constructor is available through a special function like this:</P>
6089 List *copy_List(List *f) {
6090 return new List(*f);
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 &)</TT>, <TT>X(X &)</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>
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>
6125 %name(CopyFoo) Foo(const Foo &);
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
6139 int List_search(List *obj, char *value) {
6140 return obj->search(value);
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->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
6164 int List_length_get(List *obj) {
6165 return obj->length;
6167 int List_length_set(List *obj, int value) {
6168 obj->length = value;
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>
6191 <P> Alternatively, you can specify an immutable member in advance like
6195 %immutable List::length;
6199 int length; // Immutable by above directive
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>
6216 <P> then the low-level accessor to the <TT>items</TT> member actually
6217 uses pointers. For example:</P>
6220 List *Foo_items_get(Foo *self) {
6221 return &self->items;
6223 void Foo_items_set(Foo *self, List *value) {
6224 self->items = *value;
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>
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>
6241 // All List variables will use const List& typemaps
6244 // Only Foo::myList will use const List& typemaps
6245 %naturalvar Foo::myList;
6250 // All variables will use const reference typemaps
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>
6262 const List &Foo_items_get(Foo *self) {
6263 return self->items;
6265 void Foo_items_set(Foo *self, const List &value) {
6266 self->items = value;
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 & {
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>
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>
6316 void bar(int x, int y = 3, int z = 4);
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>
6329 void bar(int x, int y, int z);
6330 void bar(int x, int y);
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>
6361 %feature("compactdefaultargs") Foo::bar;
6364 void bar(int x, int y = 3, int z = 4);
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>
6377 static const int spam;
6379 void bar(int x, int y = spam); // Won't work with %feature("compactdefaultargs") -
6380 // private default value
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
6416 enum {ALE, LAGER, PORTER, STOUT};
6421 <P> Generates the following set of constants in the target scripting
6423 <DIV class="targetlang">
6425 Swig_ALE = Swig::ALE
6426 Swig_LAGER = Swig::LAGER
6427 Swig_PORTER = Swig::PORTER
6428 Swig_STOUT = Swig::STOUT
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
6442 friend void blah(Foo *f);
6447 <P> then the <TT>friend</TT> declaration does result in a wrapper code
6448 equivalent to one generated for the following declaration</P>
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>
6464 %ignore bar::blah(Foo *f);
6471 friend void blah(Foo *f);
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>
6485 double bar(double &a);
6489 <P> has a low-level accessor</P>
6492 double Foo_bar(Foo *obj, double *a) {
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>
6503 void foo(const int &x);
6506 <P> it is called from a script as follows:</P>
6507 <DIV class="targetlang">
6509 foo(3) # Notice pass by value
6512 <P> Functions that return a reference are remapped to return a pointer
6513 instead. For example:</P>
6522 <P> Generates an accessor like this:</P>
6525 Foo *Bar_spam(Bar *obj) {
6526 Foo &result = obj->spam();
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>
6537 const int &bar();
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>
6554 Vector cross_product(Vector a, Vector b);
6557 <P> If no information is supplied about <TT>Vector</TT>, SWIG creates a
6558 wrapper function similar to the following:</P>
6561 Vector *wrap_cross_product(Vector *a, Vector *b) {
6564 Vector r = cross_product(x,y);
6565 return new Vector(r);
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 "Fulton Transform". This produces a
6574 wrapper that looks like this:</P>
6577 Vector cross_product(Vector *a, Vector *b) {
6578 SwigValueWrapper<Vector> x = *a;
6579 SwigValueWrapper<Vector> y = *b;
6580 SwigValueWrapper<Vector> r = cross_product(x,y);
6581 return new Vector(r);
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("valuewrapper")</TT> to
6594 ensure it is used and <TT>%feature("novaluewrapper")</TT> to ensure it
6598 %feature("novaluewrapper") A;
6601 %feature("valuewrapper") B;
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
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
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>
6643 #include "shapes.h"
6649 virtual double area() = 0;
6650 virtual double perimeter() = 0;
6651 void set_location(double x, double y);
6653 class Circle : public Shape {
6655 Circle(double radius);
6660 class Square : public Shape {
6662 Square(double size);
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">
6674 >>> import shapes
6675 >>> circle = shapes.new_Circle(7)
6676 >>> square = shapes.new_Square(10)
6677 >>> print shapes.Circle_area(circle)
6678 153.93804004599999757
6679 >>> print shapes.Shape_area(circle)
6680 153.93804004599999757
6681 >>> print shapes.Shape_area(square)
6682 100.00000000000000000
6683 >>> shapes.Shape_set_location(square,2,-3)
6684 >>> print shapes.Shape_perimeter(square)
6685 40.00000000000000000
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
6714 example.i:18: Warning(401): Nothing known about base class 'Foo'. Ignored.
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>
6728 <P><B> Note:</B> <TT>typedef</TT>-names<EM> can</EM> be used as base
6729 classes. For example:</P>
6737 class Bar : public FooObj { // Ok. Base class is Foo
6742 <P> Similarly, <TT>typedef</TT> allows unnamed structures to be used as
6743 base classes. For example:</P>
6750 class Bar : public Foo { // Ok.
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
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">
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
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>
6805 class C : public A, public B {
6808 int A_function(A *a) {
6812 int B_function(B *b) {
6817 <P> Now, consider the following code that uses <TT>void *</TT>.</P>
6821 void *p = (void *) c;
6823 int x = A_function((A *) p);
6824 int y = B_function((B *) p);
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">
6837 ------------ <--- (C *), (A *)
6839 |------------| <--- (B *)
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>
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>
6861 void *p = (void *) c;
6862 void *pA = (void *) c;
6863 void *pB = (void *) c;
6865 int x = A_function((A *) pA);
6866 int y = B_function((B *) pB);
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>
6879 printf("x is %d\n", x);
6882 printf("x is '%s'\n", x);
6886 <P> The function is used in a completely natural way. For example:</P>
6887 <DIV class="targetlang">
6891 >>> foo("hello")
6896 <P> Overloading works in a similar manner for methods and constructors.
6897 For example if you have this code,</P>
6903 Foo(const Foo &); // Copy constructor
6905 void bar(char *s, int y);
6909 <P> it might be used like this</P>
6910 <DIV class="targetlang">
6912 >>> f = Foo() # Create a Foo
6913 >>> f.bar(3)
6914 >>> g = Foo(f) # Copy Foo
6915 >>> f.bar("hello",2)
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>
6932 <P> the order in which the arguments are checked plays a rather critical
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>
6941 <LI><B>Number of required arguments.</B> Methods are sorted by
6942 increasing number of required arguments.</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
6947 <DIV class="diagram">
6950 ---------------- ----------
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>
6964 <P> This may sound very confusing, but an example will help. Consider
6965 the following collection of overloaded methods:</P>
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);
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">
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);
6994 <P> The second rule, simply refines the ranking by looking at argument
6995 type precedence values.</P>
6996 <DIV class="diagram">
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);
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>
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>
7033 example.i:4: Warning(509): Overloaded foo(long) is shadowed by foo(int) at example.i:3.
7036 <P> or for statically typed languages like Java:</P>
7039 example.i:4: Warning(516): Overloaded method foo(long) ignored. Method foo(int)
7040 at example.i:3 used.
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
7047 <P> Ambiguity problems are known to arise in the following situations:</P>
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
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 &</TT>
7056 <LI>Pointers and arrays. For example, <TT>Foo *</TT> and <TT>Foo [4]</TT>
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>
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>
7071 example.i:3: Warning(467): Overloaded foo(int) not supported (no type checking
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>
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 )
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>
7103 void foo(long); // Ignored. Oh well.
7106 <P> The other alternative is to rename one of the methods. This can be
7107 done using <TT>%rename</TT>. For example:</P>
7110 %rename("foo_short") foo(short);
7111 %rename(foo_long) foo(long);
7114 void foo(short); // Accessed as foo_short()
7115 void foo(long); // Accessed as foo_long()
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>
7126 /* Forward renaming declarations */
7127 %rename(foo_i) foo(int);
7128 %rename(foo_d) foo(double);
7130 void foo(int); // Becomes 'foo_i'
7131 void foo(char *c); // Stays 'foo' (not renamed)
7135 void foo(int); // Becomes 'foo_i'
7136 void foo(double); // Becomes 'foo_d'
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>
7145 %rename(foo_i) ::foo(int); // Only rename foo(int) in the global scope.
7146 // (will not rename class members)
7148 %rename(foo_i) Spam::foo(int); // Only rename foo(int) in class Spam
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>
7157 %rename(foo_i) Spam::foo(int);
7158 %rename(foo_d) Spam::foo(double);
7162 virtual void foo(int); // Renamed to foo_i
7163 virtual void foo(double); // Renamed to foo_d
7167 class Bar : public Spam {
7169 virtual void foo(int); // Renamed to foo_i
7170 virtual void foo(double); // Renamed to foo_d
7174 class Grok : public Bar {
7176 virtual void foo(int); // Renamed to foo_i
7177 virtual void foo(double); // Renamed to foo_d
7182 <P> It is also possible to include <TT>%rename</TT> specifications in
7183 the class definition itself. For example:</P>
7187 %rename(foo_i) foo(int);
7188 %rename(foo_d) foo(double);
7190 virtual void foo(int); // Renamed to foo_i
7191 virtual void foo(double); // Renamed to foo_d
7195 class Bar : public Spam {
7197 virtual void foo(int); // Renamed to foo_i
7198 virtual void foo(double); // Renamed to foo_d
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>
7210 %rename(foo_i) *::foo(int); // Only rename foo(int) if it appears in a class.
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>
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
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>
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>
7242 /* Rename these overloaded functions */
7243 %rename(foo_i) foo(int);
7244 %rename(foo_d) foo(double);
7246 %include "header.h"
7250 <P>The scope qualifier (::) can also be used on simple names. For
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
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>
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>
7278 %rename(foo_i) Spam::foo(int);
7279 %rename(Foo) Spam::foo;
7285 %rename(Foo) Spam::foo;
7287 %rename(foo_i) Spam::foo(int);
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>
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>
7299 <P>The name matching rules strictly follow member qualification rules.
7300 For example, if you have a class like this:</P>
7311 <P> the declaration</P>
7314 %rename(name) Spam::bar();
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>
7321 %rename(name) Spam::bar() const;
7324 <P> An often overlooked C++ feature is that classes can define two
7325 different overloaded members that differ only in their qualifiers, like
7332 void bar(); // Unqualified member
7333 void bar() const; // Qualified member
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
7343 %rename(name1) Spam::bar();
7344 %rename(name2) Spam::bar() const;
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>
7353 %ignore Spam::bar() const; // Ignore bar() const, but leave other bar() alone
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">
7362 typedef int Integer;
7364 %rename(foo_i) foo(int);
7368 void foo(Integer); // Stays 'foo' (not renamed)
7372 void foo(int); // Renamed to foo_i
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>
7388 void bar(int i=-1, double d=0.0);
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>
7398 %rename(newbar) Spam::bar(int i=-1, double d=0.0);
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>
7409 %rename(newbar) Spam::bar(int i, double d);
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
7420 %rename(bar_2args) Spam::bar(int i, double d);
7421 %rename(bar_1arg) Spam::bar(int i);
7422 %rename(bar_default) Spam::bar();
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>
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>
7450 double rpart, ipart;
7452 Complex(double r = 0, double i = 0) : rpart(r), ipart(i) { }
7453 Complex(const Complex &c) : rpart(c.rpart), ipart(c.ipart) { }
7454 Complex &operator=(const Complex &c) {
7459 Complex operator+(const Complex &c) const {
7460 return Complex(rpart+c.rpart, ipart+c.ipart);
7462 Complex operator-(const Complex &c) const {
7463 return Complex(rpart-c.rpart, ipart-c.ipart);
7465 Complex operator*(const Complex &c) const {
7466 return Complex(rpart*c.rpart - ipart*c.ipart,
7467 rpart*c.ipart + c.rpart*ipart);
7469 Complex operator-() const {
7470 return Complex(-rpart, -ipart);
7472 double re() const { return rpart; }
7473 double im() const { return ipart; }
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 "<TT>operator +</TT>" or "<TT>operator -</TT>".
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 "<TT>operator +</TT>" in Python--there won't be any way to call
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>
7491 %rename(__add__) Complex::operator+;
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>
7500 _wrap_Complex___add__(args) {
7502 obj->operator+(args);
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">
7511 >>> a = Complex(3,4)
7512 >>> b = Complex(5,2)
7513 >>> c = a + b # Invokes __add__ method
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>
7521 %rename(add) operator+;
7524 <P> The resulting scripting interface might work like this:</P>
7525 <DIV class="targetlang">
7529 c = a.add(b) # Call a.operator+(b)
7532 <P> All of the techniques described to deal with overloaded functions
7533 also apply to operators. For example:</P>
7536 %ignore Complex::operator=; // Ignore = in class Complex
7537 %ignore *::operator=; // Ignore = in all classes
7538 %ignore operator=; // Ignore = everywhere.
7540 %rename(__sub__) Complex::operator-;
7541 %rename(__neg__) Complex::operator-(); // Unary -
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>
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>
7557 friend Complex operator+(Complex &, double);
7559 Complex operator+(Complex &, double);
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>
7569 %rename(add_complex_double) operator+(Complex &, double);
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
7577 <LI>The semantics of certain C++ operators may not match those in the
7578 target language.</LI>
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
7589 #include "vector.h"
7597 ... bunch of C++ methods ...
7600 static char temp[256];
7601 sprintf(temp,"[ %g, %g, %g ]", $self->x,$self->y,$self->z);
7602 return &temp[0];
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>
7612 <DIV class="targetlang">
7615 >>> v = Vector();
7616 >>> v.x = 3
7617 >>> v.y = 4
7618 >>> v.z = 0
7619 >>> print(v)
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>
7638 virtual void method(int v) {
7643 struct Derived : Base {
7646 virtual void method(int v) {
7647 $self->Base::method(v); // akin to this->Base::method(v);
7648 $self->value = v; // akin to this->value = v;
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>
7666 void foo(vector<int> *a, int n);
7667 void bar(list<int,100> *x);
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 '<' and '>' within a constant expressions currently is not
7673 supported by SWIG ('<=' and '>=' are though). For example:</P>
7676 void bar(list<int,100> *x); // OK
7677 void bar(list<int,2*50> *x); // OK
7678 void bar(list<int,(2>1 ? 100 : 50)> *x) // Not supported
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>
7685 typedef int Integer;
7686 void foo(vector<int> *x, vector<Integer> *y);
7689 <P> In this case, <TT>vector<Integer></TT> is exactly the same type as <TT>
7690 vector<int></TT>. The wrapper for <TT>foo()</TT> will accept either
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<int></TT>, <TT>array<double></TT>,
7700 etc.). Second, an instantiation name such as <TT>vector<int></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>
7707 template<class T> class List {
7721 void append(T obj) {
7722 if (nitems < maxitems) {
7723 data[nitems++] = obj;
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>
7742 %rename(intList) List<int>; // Rename to a suitable identifier
7743 class List<int> {
7751 void append(int obj);
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
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>
7769 /* Instantiate a few different versions of the template */
7770 %template(intList) List<int>;
7771 %template(doubleList) List<double>;
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>
7781 %template(intList) List<int>;
7783 typedef List<int> intList; // OK
7786 <P> SWIG can also generate wrappers for function templates using a
7787 similar technique. For example:</P>
7790 // Function template
7791 template<class T> T max(T a, T b) { return a > b ? a : b; }
7793 // Make some different versions of this function
7794 %template(maxint) max<int>;
7795 %template(maxdouble) max<double>;
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>
7805 template vector<typename T, int max=100> class vector {
7809 %template(intvec) vector<int>; // OK
7810 %template(vec1000) vector<int,1000>; // OK
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>
7818 %template(intList) List<int>;
7819 %template(Listint) List<int>; // Error. Template already wrapped.
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
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>
7832 %template(intList) vector<int>;
7833 typedef int Integer;
7835 void foo(vector<Integer> *x);
7838 <P> In this case, <TT>vector<Integer></TT> is exactly the same type as <TT>
7839 vector<int></TT>. Any use of <TT>Vector<Integer></TT> is mapped back to
7840 the instantiation of <TT>vector<int></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>
7849 %template(intList) List<int>;
7851 class UltraList : public List<int> {
7856 <P> then SWIG knows that <TT>List<int></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<int></TT>
7859 , you will get a warning message similar to this:</P>
7862 example.h:42. Nothing known about class 'List<int >' (ignored).
7863 example.h:42. Maybe you forgot to instantiate 'List<int >' using %template.
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.
7871 template<class T> class Foo {
7875 template<class T> class Bar : public Foo<T> {
7879 // Instantiate base classes first
7880 %template(intFoo) Foo<int>;
7881 %template(doubleFoo) Foo<double>;
7883 // Now instantiate derived classes
7884 %template(intBar) Bar<int>;
7885 %template(doubleBar) Bar<double>;
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
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>
7900 // Instantiate traits<double,double>, but don't wrap it.
7901 %template() traits<double,double>;
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>
7908 %define TEMPLATE_WRAP(prefix, T...)
7909 %template(prefix ## Foo) Foo<T >;
7910 %template(prefix ## Bar) Bar<T >;
7914 TEMPLATE_WRAP(int, int)
7915 TEMPLATE_WRAP(double, double)
7916 TEMPLATE_WRAP(String, char *)
7917 TEMPLATE_WRAP(PairStringInt, std::pair<string, int>)
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
7924 <P> The SWIG template mechanism<EM> does</EM> support specialization.
7925 For instance, if you define a class like this,</P>
7928 template<> class List<int> {
7936 void append(int obj);
7942 <P> then SWIG will use this code whenever the user expands <TT>List<int></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
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>
7954 template<class T> class List<T*> {
7962 void append(int obj);
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>
7973 template<class T1, class T2> class Foo<T1, T2 *> { };
7976 <P> SWIG isn't able to match it properly for instantiations like <TT>
7977 Foo<int *, int *></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>
7988 template<class T> void bar(T x, T y) { ... };
7993 <P> To expand the template, simply use <TT>%template</TT> inside the
7999 template<class T> void bar(T x, T y) { ... };
8001 %template(barint) bar<int>;
8002 %template(bardouble) bar<double>;
8006 <P> Or, if you want to leave the original class definition alone, just
8012 template<class T> void bar(T x, T y) { ... };
8017 %template(barint) bar<int>;
8018 %template(bardouble) bar<double>;
8027 template<class T> void bar(T x, T y) { ... };
8032 %template(bari) Foo::bar<int>;
8033 %template(bard) Foo::bar<double>;
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>
8045 %template(bar) Foo::bar<int>;
8046 %template(bar) Foo::bar<double>;
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>
8057 template<class T> class Foo {
8059 // A member template
8060 template<class S> T bar(S x, S y) { ... };
8064 // Expand a few member templates
8066 %template(bari) bar<int>;
8067 %template(bard) bar<double>;
8070 // Create some wrappers for the template
8071 %template(Fooi) Foo<int>;
8072 %template(Food) Foo<double>;
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>
8081 template<class T1, class T2> struct pair {
8084 pair() : first(T1()), second(T2()) { }
8085 pair(const T1 &x, const T2 &y) : first(x), second(y) { }
8086 template<class U1, class U2> pair(const pair<U1,U2> &x)
8087 : first(x.first),second(x.second) { }
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>
8098 %template(pair) pair<T1,T2>; // Generate default copy constructor
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>
8108 // Instantiate a few versions
8109 %template(pairii) pair<int,int>;
8110 %template(pairdd) pair<double,double>;
8112 // Create a default constructor only
8113 %extend pair<int,int> {
8114 %template(paird) pair<int,int>; // Default constructor
8117 // Create default and conversion constructors
8118 %extend pair<double,double> {
8119 %template(paird) pair<double,dobule>; // Default constructor
8120 %template(pairc) pair<int,int>; // Conversion constructor
8124 <P>And if your target language supports overloading, then you can try
8128 // Create default and conversion constructors
8129 %extend pair<double,double> {
8130 %template(pair) pair<double,dobule>; // Default constructor
8131 %template(pair) pair<int,int>; // Conversion constructor
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
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>
8146 template<class T> class List {
8149 %rename(__getitem__) get(int);
8156 /* Make a string representation */
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>
8169 %rename(__getitem__) List::get;
8172 /* Make a string representation */
8177 return new List<T>(*$self);
8182 template<class T> class List {
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>
8198 %template(intList) List<int>;
8200 %extend List<int> {
8202 printf("Hey, I'm an List<int>!\n");
8207 <P> SWIG even supports overloaded templated functions. As usual the <TT>
8208 %template</TT> directive is used to wrap templated functions. For
8212 template<class T> void foo(T x) { };
8213 template<class T> void foo(T x, T y) { };
8215 %template(foo) foo<int>;
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>
8242 %template(vectori) vector<int>;
8244 void somemethod() { }
8248 <P> This behavior is no longer supported. Instead, you should use the
8249 original template name as the class name. For example:</P>
8252 %template(vectori) vector<int>;
8253 %extend vector<int> {
8254 void somemethod() { }
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>
8281 <P> Members of the namespace are accessed in C++ by prepending the
8282 namespace prefix to names. For example:</P>
8285 double x = math::sin(1.0);
8286 double magnitude(math::Complex *c);
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>
8297 using math::Complex;
8298 double magnitude(Complex *c); // Namespace prefix stripped
8301 <P> Similarly, the contents of an entire namespace can be made available
8305 using namespace math;
8306 double x = sin(1.0);
8307 double magnitude(Complex *c);
8310 <P> Alternatively, a namespace can be aliased:</P>
8314 double x = M::sin(1.0);
8315 double magnitude(M::Complex *c);
8318 <P> Using combinations of these features, it is possible to write
8319 head-exploding code like this:</P>
8331 typedef C::Foo FooClass;
8337 using BIGB::FooClass;
8338 class Bar : public FooClass {
8342 class Spam : public D::Bar {
8345 void evil(A::Foo *a, B::FooClass *b, B::C::Foo *c, BIGB::FooClass *d,
8346 BIGB::C::Foo *e, D::FooClass *f);
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
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>
8403 <P> When this conflict occurs, you will get an error message that
8407 example.i:26. Error. 'foo' is multiply defined in the generated module.
8408 example.i:23. Previous declaration of 'foo'
8411 <P> To resolve this error, simply use <TT>%rename</TT> to disambiguate
8412 the declarations. For example:</P>
8415 %rename(B_foo) B::foo;
8421 void foo(double); // Gets renamed to B_foo
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
8434 typedef int Integer;
8437 void foo(Integer x);
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>
8448 template<typename T> T max(T a, T b) { return a > b ? a : b; }
8453 %template(maxint) max<int>; // Okay.
8454 %template(maxfloat) foo::max<float>; // Okay (qualified name).
8457 using namespace foo;
8458 %template(maxdouble) max<double>; // Okay.
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>
8475 typedef int Integer;
8483 Integer add(Integer x, Integer y) {
8484 Integer r = x + y; // Error. Integer not defined in this scope
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>
8498 Integer add(Integer x, Integer y) {
8499 foo::Integer r = x + y; // Ok.
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>
8521 void bar(int) { ... }
8526 // Bad version. Emitted code not placed in namespace.
8529 void bar(int) { ... } /* I'm bad */
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>
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
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>
8569 operator bar(); // Conversion of spam -> bar
8575 <P> The following is how the feature is expected to be written for a
8576 successful match:</P>
8579 %rename(tofoo) foo::spam::operator bar();
8582 <P> The following does not work as no namespace resolution is performed
8583 in the matching of conversion operator names:</P>
8586 %rename(tofoo) foo::spam::operator <B>foo::</B>bar();
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>
8593 %rename(tofoo) foo::spam::operator bar(); // will not match
8594 %rename(tofoo) foo::spam::operator foo::bar(); // will match
8600 operator foo::bar();
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
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>
8627 %rename(bbb) Space::ABC::aaa(T t); // will match but with lower precedence than ccc
8628 %rename(ccc) Space::ABC<Space::XYZ>::aaa(Space::XYZ t); // will match but with higher precedence than bbb
8632 template<typename T> struct ABC {
8636 %template(ABCXYZ) Space::ABC<Space::XYZ>;
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>
8646 %rename(bbb) ABC::aaa(T t); // will match but with lower precedence than ccc
8647 %rename(ccc) ABC<Space::XYZ>::aaa(Space::XYZ t); // will match but with higher precedence than bbb
8648 %rename(ddd) ABC<Space::XYZ>::aaa(XYZ t); // will not match
8653 template<typename T> struct ABC {
8657 %template(ABCXYZ) Space::ABC<Space::XYZ>;
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>
8668 %rename(bbb) aaa(T t); // will match but with lower precedence than ccc
8670 %extend ABC<Space::XYZ> {
8671 %rename(ccc) aaa(Space::XYZ t); // will match but with higher precedence than bbb
8672 %rename(ddd) aaa(XYZ t); // will not match
8678 template<typename T> struct ABC {
8682 %template(ABCXYZ) Space::ABC<Space::XYZ>;
8685 <H2><A name="SWIGPlus_exception_specifications"></A>6.21 Exception
8687 <P> When C++ programs utilize exceptions, exceptional behavior is
8688 sometimes specified as part of a function or method declaration. For
8697 void blah() throw(Error);
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
8707 <DIV class="targetlang">
8713 # e is a wrapped instance of "Error"
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">"throws" typemap</A>
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 "<A href="#exception">Exception handling with %exception</A>" 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 "throws" 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 "...". For example,</P>
8740 struct EBase { virtual ~EBase(); };
8741 struct Error1 : EBase { };
8742 struct Error2 : EBase { };
8743 struct Error3 : EBase { };
8744 struct Error4 : EBase { };
8746 %catches(Error1,Error2,...) Foo::bar();
8747 %catches(EBase) Foo::blah();
8753 void blah() throw(Error1,Error2,Error3,Error4);
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>
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) = &Object::foo;
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 "The
8785 Annotated C++ Manual" 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">
8790 >>> print example.FOO
8791 _ff0d54a800000000_m_Object__f_double_double__double
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
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->()</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 -></TT> operator has been overloaded. This class is then wrapped around
8808 some other class. For example:</P>
8811 // Smart-pointer class
8812 template<class T> class SmartPtr {
8816 T *operator->() {
8830 // Smart-pointer wrapper
8831 typedef SmartPtr<Foo_Impl> Foo;
8833 // Create smart pointer Foo
8835 return SmartPtr(new Foo_Impl());
8838 // Do something with smart pointer Foo
8839 void do_something(Foo f) {
8840 printf("x = %d\n", f->x);
8845 <P> A key feature of this approach is that by defining <TT>operator-></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>
8855 <P> are transparently mapped to the following</P>
8858 (f.operator->())->x;
8859 (f.operator->())->bar();
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->()</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>
8870 int Foo_x_get(Foo *f) {
8873 void Foo_x_set(Foo *f, int value) {
8876 void Foo_bar(Foo *f) {
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->()</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">
8889 >>> f = make_Foo()
8890 >>> print f.x
8892 >>> f.bar()
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->()</TT>. This includes any methods
8899 that might be accessible through inheritance. However, there are a
8900 number of restrictions:</P>
8902 <LI>Member variables and methods are wrapped through a smart pointer.
8903 Enumerations, constructors, and destructors are not wrapped.</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>
8918 Foo *operator->();
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>
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>
8935 class Foo { // Ignored
8940 Foo *operator->();
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->()</TT>, the
8948 operator itself is wrapped as a method <TT>__deref__()</TT>. For
8950 <DIV class="targetlang">
8952 f = Foo() # Smart-pointer
8953 p = f.__deref__() # Raw pointer from operator->
8956 <P><B> Note:</B> To disable the smart-pointer behavior, use <TT>%ignore</TT>
8957 to ignore <TT>operator->()</TT>. For example:</P>
8960 %ignore Bar::operator->;
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>
8976 double blah(double x);
8979 class FooBar : public Foo, public Bar {
8983 char *blah(const char *x);
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>
8993 f->blah(3); // Ok. Invokes Foo::blah(int)
8994 f->blah(3.5); // Ok. Invokes Bar::blah(double)
8995 f->blah("hello"); // Ok. Invokes FooBar::blah(const char *);
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">
9003 >>> import example
9004 >>> f = example.FooBar()
9005 >>> f.blah(3)
9006 >>> f.blah(3.5)
9007 >>> f.blah("hello")
9010 <P> <TT>using</TT> declarations can also be used to change access when
9011 applicable. For example:</P>
9020 class Bar : public Foo {
9022 using Foo::x; // Make x public
9023 using Foo::blah; // Make blah public
9027 <P> This also works in SWIG---the exposed declarations will be wrapped
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>
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>
9044 class FooBar : public Foo, public Bar {
9050 int blah(int x); // explicitly tell SWIG about other declarations
9051 double blah(double x);
9054 char *blah(const char *x);
9058 <P><B> Notes:</B></P>
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>
9068 double blah(double);
9071 class Bar : public Foo {
9073 using Foo::blah; // Only imports blah(double);
9079 <P>Resolving ambiguity in overloading may prevent declarations from
9080 being imported by <TT>using</TT>. For example:</P>
9083 %rename(blah_long) Foo::blah(long);
9087 long blah(long); // Renamed to blah_long
9090 class Bar : public Foo {
9092 using Foo::blah; // Only imports blah(int)
9093 double blah(double x);
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>
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>
9137 Inner(int v = 0) : var(v) {}
9139 void method(Inner inner);
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
9152 // Suppress SWIG warning
9153 #pragma SWIG nowarn=SWIGWARN_PARSE_NESTED_CLASS
9155 // Redefine nested class in global scope in order for SWIG to generate
9156 // a proxy class. Only SWIG parses this definition.
9160 Inner(int v = 0) : var(v) {}
9164 #include "outer.h"
9166 %include "outer.h"
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;
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
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>
9193 const Object * foo();
9199 bar(foo()); // Error: bar discards const
9203 <P> Now, consider the behavior when wrapped into a Python module:</P>
9204 <DIV class="targetlang">
9206 >>> bar(foo()) # Okay
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 "The Annotated C++ Reference Manual" by Ellis and Stroustrup.
9222 This is the reference document we use to guide a lot of SWIG's C++
9225 <!-- LocalWords: destructors Enums Namespaces const SWIG's STL OO adaptor tcl
9228 <!-- LocalWords: debuggable cxx OBJS Wiki accessor nodefault makedefault
9231 <!-- LocalWords: notabstract CopyFoo
9234 <H1><A name="Preprocessor"></A>7 Preprocessing</H1>
9237 <DIV class="sectiontoc">
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 %{ ... %} & " ... "
9248 <LI><A href="#Preprocessor_nn9">Preprocessing and { ... } delimiters</A></LI>
9249 <LI><A href="#Preprocessor_typemap_delimiters">Preprocessor and Typemaps</A>
9251 <LI><A href="#Preprocessor_nn10">Viewing preprocessor output</A></LI>
9252 <LI><A href="#Preprocessor_warning_error">The #error and #warning
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>
9266 %include "pointer.i"
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
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>
9283 %import "foo.i"
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
9299 <H2><A name="Preprocessor_condition_compilation"></A>7.3 Conditional
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>
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).
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
9337 <P> In addition, SWIG defines the following set of standard C/C++
9341 __LINE__ Current line number
9342 __FILE__ Current file name
9343 __STDC__ Defined to indicate ANSI C
9344 __cplusplus Defined when -c++ option used
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
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>
9370 #define EXTERN extern
9372 #define _ANSI(args) (args)
9374 #define _ANSI(args) ()
9378 <P> The following operators can appear in macro definitions:</P>
9381 <BR> Converts macro argument <TT>x</TT> to a string surrounded by double
9382 quotes ("x").</LI>
9384 <BR> Concatenates x and y together to form <TT>xy</TT>.</LI>
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>
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>
9395 %define ARRAYHELPER(type,name)
9397 type *new_ ## name (int nitems) {
9398 return (type *) malloc(sizeof(type)*nitems);
9400 void delete_ ## name(type *t) {
9403 type name ## _get(type *t, int index) {
9406 void name ## _set(type *t, int index, type val) {
9412 ARRAYHELPER(int, IntArray)
9413 ARRAYHELPER(double, DoubleArray)
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
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.
9432 #define DEBUGF(fmt,...) fprintf(stderr,fmt,__VA_ARGS__)
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>
9443 DEBUGF("hello"); --> fprintf(stderr,"hello",);
9446 <P> To get rid of the extra comma, use <TT>##</TT> like this:</P>
9449 #define DEBUGF(fmt,...) fprintf(stderr,fmt, ##__VA_ARGS__)
9452 <P> SWIG also supports GNU-style variadic macros. For example:</P>
9455 #define DEBUGF(fmt, args...) fprintf(stdout,fmt,args)
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 %{ ... %} & "
9463 ... " 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>
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 { ... }
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>
9489 printf("I'm in bar\n");
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>
9503 printf("I'm in bar\n");
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
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 "" or %{ %} delimiters but the code<B> is</B> run
9517 through the preprocessor. For example:</P>
9520 #define SWIG_macro(CAST) (CAST)$input
9521 %typemap(in) Int {$1= SWIG_macro(int);}
9524 <P> might generate</P>
9535 #define SWIG_macro(CAST) (CAST)$input
9536 %typemap(in,noblock=1) Int {$1= SWIG_macro(int);}
9539 <P> might generate</P>
9548 #define SWIG_macro(CAST) (CAST)$input
9549 %typemap(in) Int %{$1=SWIG_macro(int);%}
9552 <P> would generate</P>
9555 arg1=SWIG_macro(int);
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
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>
9573 #error "This is a fatal error message"
9574 #warning "This is a warning message"
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>
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
9589 <H1><A name="Library"></A>8 SWIG library</H1>
9592 <DIV class="sectiontoc">
9594 <LI><A href="#Library_nn2">The %include directive and library search
9596 <LI><A href="#Library_nn3">C Arrays and Pointers</A>
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>
9604 <LI><A href="#Library_nn8">C String Handling</A>
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>
9612 <LI><A href="#Library_stl_cpp_library">STL/C++ Library</A>
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>
9619 <LI><A href="#Library_nn16">Utility Libraries</A>
9621 <LI><A href="#Library_nn17">exception.i</A></LI>
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
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
9639 <H2><A name="Library_nn2"></A>8.1 The %include directive and library
9641 <P> Library files are included using the <TT>%include</TT> directive.
9642 When searching for files, directories are searched in the following
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>
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
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
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>
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>
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
9694 <P> <TT>type *delete_name(type *obj)</TT></P>
9695 <DIV class="indent">
9696 <P> Deletes an object type <TT>type</TT>.</P>
9698 <P> <TT>void name_assign(type *obj, type value)</TT></P>
9699 <DIV class="indent">
9700 <P> Assigns <TT>*obj = value</TT>.</P>
9702 <P> <TT>type name_value(type *obj)</TT></P>
9703 <DIV class="indent">
9704 <P> Returns the value of <TT>*obj</TT>.</P>
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>
9713 %include "cpointer.i"
9715 /* Create some functions for working with "int *" */
9716 %pointer_functions(int, intp);
9718 /* A function that uses an "int *" */
9719 void add(int x, int y, int *result);
9722 <P> Now, in Python:</P>
9723 <DIV class="targetlang">
9725 >>> import example
9726 >>> c = example.new_intp() # Create an "int" for storing result
9727 >>> example.add(3,4,c) # Call function
9728 >>> example.intp_value(c) # Dereference
9730 >>> example.delete_intp(c) # Delete
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>
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
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 "class" may be transparently passed to any function that expects
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>
9766 %include "cpointer.i"
9768 /* Wrap a class interface around an "int *" */
9769 %pointer_class(int, intp);
9771 /* A function that uses an "int *" */
9772 void add(int x, int y, int *result);
9775 <P> Now, in Python (using proxy classes)</P>
9776 <DIV class="targetlang">
9778 >>> import example
9779 >>> c = example.intp() # Create an "int" for storing result
9780 >>> example.add(3,4,c) # Call function
9781 >>> c.value() # Dereference
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
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>
9797 %pointer_cast(int *, unsigned int *, int_to_uint);
9800 <P> In this example, the function <TT>int_to_uint()</TT> would be used
9801 to cast types in the target language.</P>
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
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>
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>
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>
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>
9841 void print_array(double x[10]) {
9843 for (i = 0; i < 10; i++) {
9844 printf("[%d] = %g\n", i, x[i]);
9849 <P> To wrap it, you might write this:</P>
9854 %include "carrays.i"
9855 %array_functions(double, doubleArray);
9857 void print_array(double x[10]);
9860 <P> Now, in a scripting language, you might write this:</P>
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
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>
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
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>
9897 %include "carrays.i"
9898 %array_class(double, doubleArray);
9900 void print_array(double x[10]);
9903 <P> Allows you to do this:</P>
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
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
9929 <EM>type</EM> *malloc_<EM>name</EM>(int nbytes = sizeof(<EM>type</EM>));
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., "<TT>
9935 int *</TT>", "<TT>double **</TT>", etc.).</P>
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
9943 <EM>type</EM> *calloc_<EM>name</EM>(int nobj =1, int sz = sizeof(<EM>type</EM>));
9946 <P> If <TT>type</TT> is <TT>void</TT>, then the size parameter <TT>sz</TT>
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
9955 <EM>type</EM> *realloc_<EM>name</EM>(<EM>type</EM> *ptr, int nitems);
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>
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
9969 void free_<EM>name</EM>(<EM>type</EM> *ptr);
9972 <P><B> <TT>%sizeof(type [,name=type])</TT></B></P>
9973 <DIV class="indent">
9974 <P> Creates the constant:</P>
9977 %constant int sizeof_<EM>name</EM> = sizeof(<EM>type</EM>);
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>
9984 <P> Here is a simple example that illustrates the use of these macros:</P>
9989 %include "cmalloc.i"
9994 %malloc(int *, intp);
9997 %allocators(double);
10000 <P> Now, in a script:</P>
10001 <DIV class="targetlang">
10003 >>> from example import *
10004 >>> a = malloc_int()
10007 >>> free_int(a)
10008 >>> b = malloc_intp()
10010 '_000efb20_p_p_int'
10011 >>> free_intp(b)
10012 >>> c = calloc_double(50)
10014 '_000fab98_p_double'
10015 >>> c = realloc_double(100000)
10016 >>> free_double(c)
10017 >>> print sizeof_double
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>
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
10041 <P> One use of these functions is packing and unpacking data from
10042 memory. Here is a short example:</P>
10047 %include "carrays.i"
10048 %include "cdata.i"
10050 %array_class(int, intArray);
10053 <P> Python example:</P>
10054 <DIV class="targetlang">
10056 >>> a = intArray(10)
10057 >>> for i in range(0,10):
10059 >>> b = cdata(a,40)
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 >>> c = intArray(10)
10064 >>> memmove(c,b)
10065 >>> print c[4]
10070 <P> Since the size of data is not always known, the following macro is
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
10078 char *cdata_<EM>name</EM>(type* ptr, int nitems)
10081 <P> <TT>nitems</TT> is the number of items of the given type to extract.</P>
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
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
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>
10101 char *foo(char *s);
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>
10113 <P> then <TT>s</TT> would point to the representation of "Hello" 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>
10127 int parity(char *str, int len, int initial);
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>
10134 %apply (char *STRING, int LENGTH) { (char *str, int len) };
10136 int parity(char *str, int len, int initial);
10139 <P> Now, in the target language, you can use binary string data like
10143 >>> s = "H\x00\x15eg\x09\x20"
10144 >>> parity(s,0)
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>
10154 char *result = (char *) malloc(...);
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
10163 <P> To fix the memory leak, use the <TT>%newobject</TT> directive.</P>
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>
10179 void get_path(char *s) {
10180 // Potential buffer overflow---uh, oh.
10181 sprintf(s,"%s/%s", base_directory, sub_directory);
10184 // Somewhere else in the C program
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
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>
10206 %cstring_bounded_output(char *path, 1024);
10208 void get_path(char *path);
10211 <P> In the target language:</P>
10212 <DIV class="targetlang">
10214 >>> get_path()
10215 /home/beazley/packages/Foo/Bar
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>
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>
10234 %cstring_chunk_output(char *packet, PACKETSIZE);
10236 void get_packet(char *packet);
10239 <P> In the target language:</P>
10240 <DIV class="targetlang">
10242 >>> get_packet()
10243 '\xa9Y:\xf6\xd7\xe1\x87\xdbH;y\x97\x7f\xd3\x99\x14V\xec\x06\xea\xa2\x88'
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>
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>
10262 %cstring_bounded_mutable(char *ustr, 1024);
10264 void make_upper(char *ustr);
10267 <P> In the target language:</P>
10268 <DIV class="targetlang">
10270 >>> make_upper("hello world")
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>
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>
10294 %cstring_mutable(char *ustr);
10296 void make_upper(char *ustr);
10298 %cstring_mutable(char *hstr, HEADER_SIZE);
10300 void attach_header(char *hstr);
10303 <P> In the target language:</P>
10304 <DIV class="targetlang">
10306 >>> make_upper("hello world")
10308 >>> attach_header("Hello world")
10309 'header: Hello world'
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>
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>
10331 %cstring_output_maxsize(char *path, int maxpath);
10333 void get_path(char *path, int maxpath);
10336 <P> In the target language:</P>
10337 <DIV class="targetlang">
10339 >>> get_path(1024)
10340 '/home/beazley/Packages/Foo/Bar'
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>
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>
10359 %cstring_output_withsize(char *data, int *maxdata);
10361 void get_data(char *data, int *maxdata);
10364 <P> In the target language:</P>
10365 <DIV class="targetlang">
10367 >>> get_data(1024)
10369 >>> get_data(1024)
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>
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
10387 void foo(char **s) {
10388 *s = (char *) malloc(64);
10389 sprintf(*s, "Hello world\n");
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>
10398 %cstring_output_allocate(char **s, free(*$1));
10400 void foo(char **s);
10403 <P> In the target language:</P>
10404 <DIV class="targetlang">
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>
10418 void foo(char **s, int *sz) {
10419 *s = (char *) malloc(64);
10421 // Write some binary data
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>
10431 %cstring_output_allocate_size(char **s, int *slen, free(*$1));
10433 void foo(char **s, int *slen);
10436 <P> In the target language:</P>
10437 <DIV class="targetlang">
10440 '\xa9Y:\xf6\xd7\xe1\x87\xdbH;y\x97\x7f\xd3\x99\x14V\xec\x06\xea\xa2\x88'
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>
10450 char *get_data(int *len);
10453 <P> You could wrap it with a function like this:</P>
10456 void my_get_data(char **result, int *len) {
10457 *result = get_data(len);
10461 <P><B> Comments:</B></P>
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>
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>
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
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>
10504 %include "std_string.i"
10507 void bar(const std::string &x);
10510 <P> In the target language:</P>
10511 <DIV class="targetlang">
10513 x = foo(); # Returns a string object
10514 bar("Hello World"); # Pass string as std::string
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>
10523 %include "std_string.i"
10525 %apply const std::string& {std::string* foo};
10533 <P> In the target language:</P>
10534 <DIV class="targetlang">
10537 x.foo="Hello World"; # assign with string
10538 print x.foo; # print as string
10541 <P> This module only supports types <TT>std::string</TT> and <TT>const
10542 std::string &</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>
10550 %include "std_string.i"
10552 using namespace std;
10553 typedef std::string String;
10555 void foo(string s, const String &t); // std_string typemaps still applied
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>
10569 %include "std_vector.i"
10572 %template(vectori) vector<int>;
10573 %template(vectord) vector<double>;
10577 <P> When a template <TT>vector<X></TT> is instantiated a number of
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<X></TT>, <TT>const
10584 vector<X> &</TT>, and <TT>const vector<X> *</TT>. For each of these, a
10585 pointer <TT>vector<X> *</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<X></TT>. In this case,
10588 the values in the vector are expanded into a list object in the target
10590 <LI>For all other variations of the type, the wrappers expect to receive
10591 a <TT>vector<X> *</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
10597 <P> To illustrate the use of this library, consider the following
10601 /* File : example.h */
10603 #include <vector>
10604 #include <algorithm>
10605 #include <functional>
10606 #include <numeric>
10608 double average(std::vector<int> v) {
10609 return std::accumulate(v.begin(),v.end(),0.0)/v.size();
10612 std::vector<double> half(const std::vector<double>& v) {
10613 std::vector<double> w(v);
10614 for (unsigned int i=0; i<w.size(); i++)
10619 void halve_in_place(std::vector<double>& v) {
10620 std::transform(v.begin(),v.end(),v.begin(),
10621 std::bind2nd(std::divides<double>(),2.0));
10625 <P> To wrap with SWIG, you might write the following:</P>
10630 #include "example.h"
10633 %include "std_vector.i"
10634 // Instantiate templates used by example
10636 %template(IntVector) vector<int>;
10637 %template(DoubleVector) vector<double>;
10640 // Include the header file with above prototypes
10641 %include "example.h"
10644 <P> Now, to illustrate the behavior in the scripting interpreter,
10645 consider this Python example:</P>
10646 <DIV class="targetlang">
10648 >>> from example import *
10649 >>> iv = IntVector(4) # Create an vector<int>
10650 >>> for i in range(0,4):
10652 >>> average(iv) # Call method
10654 >>> average([0,1,2,3]) # Call with list
10656 >>> half([1,2,3]) # Half a list
10658 >>> halve_in_place([1,2,3]) # Oops
10659 Traceback (most recent call last):
10660 File "<stdin>", line 1, in ?
10661 TypeError: Type error. Expected _p_std__vectorTdouble_t
10662 >>> dv = DoubleVector(4)
10663 >>> for i in range(0,4):
10665 >>> halve_in_place(dv) # Ok
10666 >>> for i in dv:
10673 >>> dv[20] = 4.5
10674 Traceback (most recent call last):
10675 File "<stdin>", line 1, in ?
10676 File "example.py", line 81, in __setitem__
10677 def __setitem__(*args): return apply(examplec.DoubleVector___setitem__,args)
10678 IndexError: vector index out of range
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>
10687 %include "std_vector.i"
10690 %template(IntVector) vector<int>;
10693 using namespace std;
10694 typedef std::vector Vector;
10696 void foo(vector<int> *x, const Vector &x);
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 "The
10708 Amazing" 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 "throws" typemaps. For example:</P>
10721 %include "std_vector.i"
10722 %typemap(throws) std::out_of_range {
10723 // custom exception handler
10725 %template(VectInt) std::vector<int>;
10728 <P> The custom exception handler might, for example, log the exception
10729 then convert it into a specific error/exception for the target
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
10737 %include "exception.i"
10742 } catch (const std::exception& e) {
10743 SWIG_exception(SWIG_RuntimeError, e.what());
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>
10768 SWIG_DivisionByZero
10775 <P> <TT>message</TT> is a string indicating more information about the
10778 <P> The primary use of this module is in writing language-independent
10779 exception handlers. For example:</P>
10782 %include "exception.i"
10783 %exception std::vector::getitem {
10786 } catch (std::out_of_range& e) {
10787 SWIG_exception(SWIG_IndexError,const_cast<char*>(e.what()));
10792 <H1><A name="Arguments"></A>9 Argument Handling</H1>
10795 <DIV class="sectiontoc">
10797 <LI><A href="#Arguments_nn2">The typemaps.i library</A>
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>
10806 <LI><A href="#Arguments_nn8">Applying constraints to input values</A>
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>
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
10829 <H3><A name="Arguments_nn3"></A>9.1.1 Introduction</H3>
10830 <P> Suppose you had a C function like this:</P>
10833 void add(double a, double b, double *result) {
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>
10846 // Simple example using typemaps
10848 %include "typemaps.i"
10850 %apply double *OUTPUT { double *result };
10852 extern void add(double a, double b, double *result);
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 "<TT>double *OUTPUT</TT>"
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 "<TT>
10861 double *result</TT>".</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">
10866 >>> a = add(3,4)
10867 >>> print a
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>
10883 %include "typemaps.i"
10885 %apply double *OUTPUT { double *result };
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);
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>
10902 %include "typemaps.i"
10903 %apply int *OUTPUT { int *width, int *height };
10905 // Returns a pair (width,height)
10906 void getwinsize(int winid, int *width, int *height);
10909 <P> In this case, the function returns multiple values, allowing it to
10910 be used like this:</P>
10911 <DIV class="targetlang">
10913 >>> w,h = genwinsize(wid)
10914 >>> print w
10916 >>> print h
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>
10926 // Simple example using typemaps
10928 %include "typemaps.i"
10931 extern void add(double a, double b, double *OUTPUT);
10933 extern void add(double a, double b, double *OUTPUT);
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>
10941 %clear double *result; // Remove all typemaps for double *result
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>
10952 unsigned int *INPUT
10953 unsigned short *INPUT
10954 unsigned long *INPUT
10959 <P> When used, it allows values to be passed instead of pointers. For
10960 example, consider this function:</P>
10963 double add(double *a, double *b) {
10968 <P> Now, consider this SWIG interface:</P>
10972 %include "typemaps.i"
10975 extern double add(double *, double *);
10977 extern double add(double *INPUT, double *INPUT);
10981 <P> When the function is used in the scripting language interpreter, it
10982 will work like this:</P>
10983 <DIV class="targetlang">
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
10998 unsigned int *OUTPUT
10999 unsigned short *OUTPUT
11000 unsigned long *OUTPUT
11006 <P> These methods can be used as shown in an earlier example. For
11007 example, if you have this C function :</P>
11010 void add(double a, double b, double *c) {
11015 <P> A SWIG interface file might look like this :</P>
11019 %include "typemaps.i"
11022 extern void add(double a, double b, double *OUTPUT);
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
11031 <P> If the function also returns a value, it is returned along with the
11032 argument. For example, if you had this:</P>
11035 extern int foo(double a, double b, double *OUTPUT);
11038 <P> The function will return two values like this:</P>
11039 <DIV class="targetlang">
11041 iresult, dresult = foo(3.5, 2)
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>
11052 unsigned int *INOUT
11053 unsigned short *INOUT
11054 unsigned long *INOUT
11060 <P> A C function that uses this might be something like this:</P>
11063 void negate(double *x) {
11069 <P> To make x function as both and input and output value, declare the
11070 function like this in an interface file :</P>
11074 %include "typemaps.i"
11077 extern void negate(double *);
11079 extern void negate(double *INOUT);
11083 <P> Now within a script, you can simply call the function normally :</P>
11084 <DIV class="targetlang">
11086 a = negate(3); # a = -3 after calling this
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>
11105 // Make double *result an output value
11106 %apply double *OUTPUT { double *result };
11108 // Make Int32 *in an input value
11109 %apply int *INPUT { Int32 *in };
11111 // Make long *x inout
11112 %apply long *INOUT {long *x};
11116 <P> To clear a rule, the <TT>%clear</TT> directive is used:</P>
11119 %clear double *result;
11120 %clear Int32 *in, long *x;
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>
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>
11137 // Interface file with constraints
11139 %include "constraints.i"
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
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>
11157 POSITIVE Any number > 0 (not zero)
11158 NEGATIVE Any number < 0 (not zero)
11159 NONNEGATIVE Any number >= 0
11160 NONPOSITIVE Any number <= 0
11161 NONZERO Nonzero number
11162 NONNULL Non-NULL pointer (pointers only).
11166 <H3><A name="Arguments_nn11"></A>9.2.3 Applying constraints to new
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
11173 // Apply a constraint to a Real variable
11174 %apply Number POSITIVE { Real in };
11176 // Apply a constraint to a pointer type
11177 %apply Pointer NONNULL { Vector * };
11181 <P> The special types of "Number" and "Pointer" 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>
11190 <H1><A name="Typemaps"></A>10 Typemaps</H1>
11193 <DIV class="sectiontoc">
11195 <LI><A href="#Typemaps_nn2">Introduction</A>
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>
11206 <LI><A href="#Typemaps_nn10">Typemap specifications</A>
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>
11215 <LI><A href="#Typemaps_pattern_matching">Pattern matching rules</A>
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>
11224 <LI><A href="#Typemaps_nn21">Code generation rules</A>
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>
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>
11238 <LI><A href="#Typemaps_nn25">Common typemap methods</A>
11240 <LI><A href="#Typemaps_nn26">"in" typemap</A></LI>
11241 <LI><A href="#Typemaps_nn27">"typecheck" typemap</A></LI>
11242 <LI><A href="#Typemaps_nn28">"out" typemap</A></LI>
11243 <LI><A href="#Typemaps_nn29">"arginit" typemap</A></LI>
11244 <LI><A href="#Typemaps_nn30">"default" typemap</A></LI>
11245 <LI><A href="#Typemaps_nn31">"check" typemap</A></LI>
11246 <LI><A href="#Typemaps_nn32">"argout" typemap</A></LI>
11247 <LI><A href="#Typemaps_nn33">"freearg" typemap</A></LI>
11248 <LI><A href="#Typemaps_nn34">"newfree" typemap</A></LI>
11249 <LI><A href="#Typemaps_nn35">"memberin" typemap</A></LI>
11250 <LI><A href="#Typemaps_nn36">"varin" typemap</A></LI>
11251 <LI><A href="#Typemaps_nn37">"varout" typemap</A></LI>
11252 <LI><A href="#throws_typemap">"throws" typemap</A></LI>
11255 <LI><A href="#Typemaps_nn39">Some typemap examples</A>
11257 <LI><A href="#Typemaps_nn40">Typemaps for arrays</A></LI>
11258 <LI><A href="#Typemaps_nn41">Implementing constraints with typemaps</A></LI>
11261 <LI><A href="#Typemaps_nn43">Typemaps for multiple languages</A></LI>
11262 <LI><A href="#Typemaps_optimal">Optimal code generation when returning
11264 <LI><A href="#Typemaps_multi_argument_typemaps">Multi-argument typemaps</A>
11266 <LI><A href="#runtime_type_checker">The run-time type checker</A>
11268 <LI><A href="#Typemaps_nn45">Implementation</A></LI>
11269 <LI><A href="#Typemaps_runtime_type_checker_usage">Usage</A></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>
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++ "this" pointer</A></LI>
11278 <LI><A href="#Typemaps_nn51">Where to go for more information?</A></LI>
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 "typemaps" and you asked
11286 yourself "typemaps, what are those?" That said, let's start with a
11287 short disclaimer that "typemaps" 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>
11306 int factorial(int n);
11309 <P> To access this function from Python, a pair of Python API functions
11310 are used to convert integer values. For example:</P>
11313 long PyInt_AsLong(PyObject *obj); /* Python --> C */
11314 PyObject *PyInt_FromLong(long x); /* C --> Python */
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
11324 PyObject *wrap_factorial(PyObject *self, PyObject *args) {
11328 PyObject *resultobj;
11330 if (!PyArg_ParseTuple("O:factorial", &obj1)) return NULL;
11331 <B>arg1 = PyInt_AsLong(obj1);</B>
11332 result = factorial(arg1);
11333 <B>resultobj = PyInt_FromLong(result);</B>
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>
11342 IV SvIV(SV *sv); /* Perl --> C */
11343 void sv_setiv(SV *sv, IV val); /* C --> Perl */
11349 int Tcl_GetLongFromObj(Tcl_Interp *interp, Tcl_Obj *obj, long *value);
11350 Tcl_Obj *Tcl_NewIntObj(long value);
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>
11364 /* Convert from Python --> C */
11366 $1 = PyInt_AsLong($input);
11369 /* Convert from C --> Python */
11370 %typemap(out) int {
11371 $result = PyInt_FromLong($1);
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 "in" typemap) is
11377 used to convert a value from the target language to C. The second
11378 typemap (the "out" 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
11393 <P> A short example might make this a little more clear. If you were
11394 wrapping a function like this:</P>
11397 int gcd(int x, int y);
11400 <P> A wrapper function would look approximately like this:</P>
11403 PyObject *wrap_gcd(PyObject *self, PyObject *args) {
11409 PyObject *resultobj;
11411 if (!PyArg_ParseTuple("OO:gcd", &obj1, &obj2)) return NULL;
11413 /* "in" typemap, argument 1 */<B>
11415 arg1 = PyInt_AsLong(obj1);
11418 /* "in" typemap, argument 2 */<B>
11420 arg2 = PyInt_AsLong(obj2);
11423 result = gcd(arg1,arg2);
11425 /* "out" typemap, return value */<B>
11427 resultobj = PyInt_FromLong(result);
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 "map" 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>
11448 /* Convert from Perl --> C */
11449 %typemap(in) <B>int</B> {
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);
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>
11466 /* Convert from Ruby--> C */
11467 %typemap(in) <B>int</B> {
11468 $1 = NUM2INT($input);
11471 typedef int Integer;
11473 typedef Integer Number;
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);
11481 <P> In this case, the typemap is still applied to the proper arguments
11482 even though typenames don't always match the text "int". 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>
11492 %typemap(in) <B>double nonnegative</B> {
11493 $1 = PyFloat_AsDouble($input);
11495 PyErr_SetString(PyExc_ValueError,"argument must be nonnegative.");
11501 double sin(double x);
11502 double cos(double x);
11503 double sqrt(<B>double nonnegative</B>);
11505 typedef double Real;
11506 double log(<B>Real nonnegative</B>);
11510 <P> For certain tasks such as input argument conversion, typemaps can be
11511 defined for sequences of consecutive arguments. For example:</P>
11514 %typemap(in) (<B>char *str, int len</B>) {
11515 $1 = PyString_AsString($input); /* char *str */
11516 $2 = PyString_Size($input); /* int len */
11519 int count(<B>char *str, int len</B>, char c);
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>
11531 %typemap(in) Integer = int;
11532 %typemap(in) (char *buffer, int size) = (char *str, int len);
11535 <P> A more general form of copying is found in the <TT>%apply</TT>
11536 directive like this:</P>
11540 /* Convert an integer argument */
11543 %typemap(out) int {
11544 /* Return an integer value */
11548 /* Apply all of the integer typemaps to size_t */
11549 %apply int { size_t };
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>
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
11561 typedef int size_t;
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>
11573 int foo(<B>int x, double y, char *s</B>);
11577 <LI>Input argument conversion ("in" typemap).</LI>
11578 <LI>Input argument type checking ("typecheck" typemap).</LI>
11579 <LI>Output argument handling ("argout" typemap).</LI>
11580 <LI>Input argument value checking ("check" typemap).</LI>
11581 <LI>Input argument initialization ("arginit" typemap).</LI>
11582 <LI>Default arguments ("default" typemap).</LI>
11583 <LI>Input argument resource management ("freearg" typemap).</LI>
11585 <P><B> Return value handling</B></P>
11588 <B>int</B> foo(int x, double y, char *s);
11592 <LI>Function return value conversion ("out" typemap).</LI>
11593 <LI>Return value resource management ("ret" typemap).</LI>
11594 <LI>Resource management for newly allocated objects ("newfree" typemap).</LI>
11596 <P><B> Exception handling</B></P>
11599 <B>int</B> foo(int x, double y, char *s) throw(<B>MemoryError, IndexError</B>);
11603 <LI>Handling of C++ exception specifications. ("throw" typemap).</LI>
11605 <P><B> Global variables</B></P>
11612 <LI>Assignment of a global variable. ("varin" typemap).</LI>
11613 <LI>Reading a global variable. ("varout" typemap).</LI>
11615 <P><B> Member variables</B></P>
11624 <LI>Assignment of data to a class/structure member. ("memberin"
11627 <P><B> Constant creation</B></P>
11631 %constant int BAR = 42;
11632 enum { ALE, LAGER, STOUT };
11636 <LI>Creation of constant values. ("consttab" or "constcode" typemap).</LI>
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
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>
11663 void foo(int, char *);
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">
11670 foo("hello",3) # Reversed arguments
11673 <P> If you want to change the calling conventions of a function, write a
11674 helper function instead. For example:</P>
11677 %rename(foo) wrap_foo;
11679 void wrap_foo(char *s, int x) {
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 "The C Programming Language" by Kernighan and Ritchie or "The
11697 C++ Programming Language" 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>
11707 %typemap(<EM>method</EM> [, <EM>modifiers</EM>]) <EM>typelist</EM> <EM>code</EM> ;
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>"in"</TT>, <TT>
11712 "out"</TT>, or <TT>"argout"</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="value"</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">
11721 typelist : typepattern [, typepattern, typepattern, ... ] ;
11723 typepattern : type [ (parms) ]
11724 | type name [ (parms) ]
11725 | ( typelist ) [ (parms) ]
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">
11741 | " ... "
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>
11751 /* Simple typemap declarations */
11753 $1 = PyInt_AsLong($input);
11755 %typemap(in) int "$1 = PyInt_AsLong($input);";
11756 %typemap(in) int %{
11757 $1 = PyInt_AsLong($input);
11760 /* Typemap with extra argument name */
11761 %typemap(in) int nonnegative {
11765 /* Multiple types in one typemap */
11766 %typemap(in) int, short, long {
11770 /* Typemap with modifiers */
11771 %typemap(in,doc="integer") int "$1 = gh_scm2int($input);";
11773 /* Typemap applied to patterns of multiple arguments */
11774 %typemap(in) (char *str, int len),
11775 (char *buffer, int size)
11777 $1 = PyString_AsString($input);
11778 $2 = PyString_Size($input);
11781 /* Typemap with extra pattern parameters */
11782 %typemap(in, numinputs=0) int *output (int temp),
11783 long *output (long temp)
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>
11802 int fact(int); // typemap1
11803 int gcd(int x, int y); // typemap1
11810 int isprime(int); // typemap2
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>
11830 int blah(int x); // typemap has no effect. Declaration is attached to Foo which
11831 // appears before the %typemap declaration.
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>
11839 %typemap(in) Integer = int;
11845 %typemap(in) Integer, Number, int32_t = int;
11848 <P> Types are often managed by a collection of different typemaps. For
11852 %typemap(in) int { ... }
11853 %typemap(out) int { ... }
11854 %typemap(varin) int { ... }
11855 %typemap(varout) int { ... }
11858 <P> To copy all of these typemaps to a new type, use <TT>%apply</TT>.
11862 %apply int { Integer }; // Copy all int typemaps to Integer
11863 %apply int { Integer, Number }; // Copy all int typemaps to both Integer and Number
11866 <P> The patterns for <TT>%apply</TT> follow the same rules as for <TT>
11867 %typemap</TT>. For example:</P>
11870 %apply int *output { Integer *output }; // Typemap with name
11871 %apply (char *buf, int len) { (char *buffer, int size) }; // Multiple arguments
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>
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;
11883 <P> The <TT>%clear</TT> directive clears all typemaps for a given type.
11887 %clear int; // Removes all types for int
11888 %clear int *output, long *output;
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>
11906 %typemap(in) string {
11913 typedef const int & const_reference;
11914 %typemap(out) const_reference {
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>
11927 %typemap(in) string {
11933 <P> is really defining a typemap for the type <TT>std::string</TT>. You
11934 could have code like this:</P>
11939 %typemap(in) string { /* std::string */
11946 %typemap(in) string { /* Foo::string */
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>
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
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>
11971 <P> If <TT>TYPE</TT> includes qualifiers (const, volatile, etc.), they
11972 are stripped and the following checks are made:</P>
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>
11977 <P> If <TT>TYPE</TT> is an array. The following transformation is made:</P>
11979 <LI>Replace all dimensions to <TT>[ANY]</TT> and look for a generic
11980 array typemap.</LI>
11982 <P> To illustrate, suppose that you had a function like this:</P>
11985 int foo(const char *s);
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">
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)
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>
12003 %typemap(in) int *x {
12007 %typemap(in) int * {
12011 %typemap(in) const int *z {
12015 %typemap(in) int [4] {
12019 %typemap(in) int [ANY] {
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)
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>
12041 typedef int Integer;
12042 void blah(Integer x);
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">
12053 <P> Finding no match, it then applies a reduction <TT>Integer -> int</TT>
12054 to the type and repeats the search.</P>
12055 <DIV class="diagram">
12058 int --> match: typemap 1
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>
12067 typedef double pdouble; // Positive double
12070 %typemap(in) double {
12071 ... get a double ...
12074 %typemap(in) pdouble {
12075 ... get a positive double ...
12077 double sin(double x); // typemap 1
12078 pdouble sqrt(pdouble x); // typemap 2
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>
12088 typedef int Integer;
12089 typedef Integer Row4[4];
12090 void foo(Row4 rows[10]);
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>
12102 # Reduce Row4 --> Integer[4]
12103 Integer rows[10][4]
12105 Integer rows[ANY][ANY]
12108 # Reduce Integer --> int
12115 <P> For parameterized types like templates, the situation is even more
12116 complicated. Suppose you had some declarations like this:</P>
12119 typedef int Integer;
12120 typedef foo<Integer,Integer> fooii;
12121 void blah(fooii *x);
12124 <P> In this case, the following typemap patterns are searched for the
12125 argument <TT>fooii *x</TT>:</P>
12131 # Reduce fooii --> foo<Integer,Integer>
12132 foo<Integer,Integer> *x
12133 foo<Integer,Integer> *
12135 # Reduce Integer -> int
12136 foo<int, Integer> *x
12137 foo<int, Integer> *
12139 # Reduce Integer -> int
12140 foo<int, int> *x
12141 foo<int, int> *
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<int,Integer></TT>, but a typemap
12148 for <TT>foo<Integer,int></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>
12158 %typemap(in) int "convert an int";
12159 %typemap(in) short "convert a short";
12160 %typemap(in) float "convert a float";
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>
12172 %typemap(in) SWIGTYPE * { ... default pointer handling ... }
12173 %typemap(in) SWIGTYPE & { ... 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 ... }
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>
12188 %typemap(in) SWIGTYPE { ... handle an unknown type ... }
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>
12196 double dot_product(Vector a, Vector b);
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>
12219 %typemap(in) enum SWIGTYPE & { ... enum references ... }
12220 %typemap(in) const enum SWIGTYPE & { ... const enum references ... }
12221 %typemap(in) SWIGTYPE *& { ... pointers passed by reference ... }
12222 %typemap(in) SWIGTYPE * const & { ... constant pointers passed by reference ... }
12223 %typemap(in) SWIGTYPE[ANY][ANY] { ... 2D arrays ... }
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>
12232 %typemap(in) const Hello & { ... }
12233 %typemap(in) const enum SWIGTYPE & { ... }
12234 %typemap(in) enum SWIGTYPE & { ... }
12235 %typemap(in) SWIGTYPE & { ... }
12236 %typemap(in) SWIGTYPE { ... }
12239 const Hello &hi;
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>
12256 %typemap(in) (char *buffer, int len) {
12260 %typemap(in) char *buffer {
12264 void foo(char *buffer, int len, int count); // (char *buffer, int len)
12265 void bar(char *buffer, int blah); // char *buffer
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>
12280 $1 = PyInt_AsLong($input);
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>
12292 arg1 = PyInt_AsLong(obj1);
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
12303 %typemap(in) short {
12304 long temp; /* Temporary value */
12305 if (Tcl_GetLongFromObj(interp, $input, &temp) != TCL_OK) {
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>
12320 %typemap(in) int "$1 = PyInt_AsLong($input);";
12321 %typemap(in) int %{
12322 $1 = PyInt_AsLong($input);
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>
12336 int foo(std::string *s);
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
12342 <DIV class="targetlang">
12344 $x = foo("Hello World");
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>
12354 %typemap(in) std::string * <B>(std::string temp)</B> {
12357 s = SvPV($input,len); /* Extract string data */
12358 temp.assign(s,len); /* Assign to temp */
12359 $1 = &temp; /* Set argument to point to temp */
12363 <P> In this case, <TT>temp</TT> becomes a local variable in the scope of
12364 the entire wrapper function. For example:</P>
12368 std::string temp; <--- Declaration of temp goes here
12374 temp.assign(s,len);
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
12388 void foo(std::string *x, std::string *y, std::string *z);
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>
12397 int *arg1; /* Actual arguments */
12400 std::string temp1; /* Locals declared in the typemap */
12408 temp1.assign(s,len);
12415 temp2.assign(s,len);
12422 temp3.assign(s,len);
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>
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)
12442 %typemap(in) const std::string * (std::string temp), std::string * (std::string temp) // Correct
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>
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>
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>
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>$&<EM>n</EM>_type</TD><TD>Real C datatype of type<EM> n</EM>
12477 with one pointer added.</TD></TR>
12478 <TR><TD>$&<EM>n</EM>_ltype</TD><TD>ltype of type<EM> n</EM> with one
12479 pointer added.</TD></TR>
12480 <TR><TD>$&<EM>n</EM>_mangle</TD><TD>Mangled form of type<EM> n</EM> with
12481 one pointer added.</TD></TR>
12482 <TR><TD>$&<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>
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>
12492 %typemap(in) int *INPUT {
12497 <P> then $1 refers to <TT>int *INPUT</TT>. If you have a typemap like
12501 %typemap(in) (int argc, char *argv[]) {
12506 <P> then $1 refers to <TT>int argc</TT> and $2 refers to <TT>char
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>
12513 %typemap(in) int, short, long {
12514 $1 = ($1_ltype) PyInt_AsLong($input);
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 "ltype." An "ltype"
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">
12527 ------ ----------------
12532 int [4][5] int (*)[5]
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>$&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
12542 <P> If necessary, type related substitutions can also be used when
12543 declaring locals. For example:</P>
12546 %typemap(in) int * ($*1_type temp) {
12547 temp = PyInt_AsLong($input);
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>
12558 %typemap(in) int [10][20] {
12563 <P> then the declaration of <TT>temp</TT> will be expanded as</P>
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>
12576 %typemap(in) int [10][20] {
12579 (($1_ltype) temp)[i][j] = x; /* set a value */
12584 <P> Another approach, which only works for arrays is to use the <TT>
12585 $1_basetype</TT> substitution. For example:</P>
12588 %typemap(in) int [10][20] {
12589 $1_basetype temp[10][20];
12591 temp[i][j] = x; /* set a value */
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<int> *)</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
12636 %typemap(cstype) unsigned long "uint"
12637 %typemap(cstype) unsigned long bb "bool"
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)
12649 <P> The result is the following expansion</P>
12652 %typemap(cstype) unsigned long "uint"
12653 %typemap(cstype) unsigned long bb "bool"
12654 %typemap(cscode) BarClass %{
12655 void foo(uint var1,
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 "in" typemap</H3>
12669 <P> The "in" typemap is used to convert function arguments from the
12670 target language to C. For example:</P>
12674 $1 = PyInt_AsLong($input);
12678 <P> The following special variables are available:</P>
12681 $input - Input object holding value to be converted.
12682 $symname - Name of function/method being wrapped
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 "in" typemap allows the number of converted
12688 arguments to be specified. The <TT>numinputs</TT> attributes
12689 facilitates this. For example:</P>
12692 // Ignored argument.
12693 %typemap(in, numinputs=0) int *out (int temp) {
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 "ignore" typemap.</P>
12712 <H3><A name="Typemaps_nn27"></A>10.5.2 "typecheck" typemap</H3>
12713 <P> The "typecheck" 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>
12718 %typemap(typecheck,precedence=SWIG_TYPECHECK_INTEGER) int {
12719 $1 = PyInt_Check($input) ? 1 : 0;
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
12726 <P> If you define new "in" typemaps<EM> and</EM> your program uses
12727 overloaded methods, you should also define a collection of "typecheck"
12728 typemaps. More details about this follow in a later section on
12729 "Typemaps and Overloading."</P>
12730 <H3><A name="Typemaps_nn28"></A>10.5.3 "out" typemap</H3>
12731 <P> The "out" typemap is used to convert function/method return values
12732 from C into the target language. For example:</P>
12735 %typemap(out) int {
12736 $result = PyInt_FromLong($1);
12740 <P> The following special variables are available.</P>
12743 $result - Result object returned to target language.
12744 $symname - Name of function/method being wrapped
12747 <P> The "out" typemap supports an optional attribute flag called
12748 "optimal". 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 "arginit" typemap</H3>
12751 <P> The "arginit" 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
12757 // Set argument to NULL before any conversion occurs
12758 %typemap(arginit) int *data {
12763 <H3><A name="Typemaps_nn30"></A>10.5.5 "default" typemap</H3>
12764 <P> The "default" typemap is used to turn an argument into a default
12765 argument. For example:</P>
12768 %typemap(default) int flags {
12769 $1 = DEFAULT_FLAGS;
12772 int foo(int x, int y, int flags);
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 "check" typemap</H3>
12785 <P> The "check" 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>
12790 %typemap(check) int positive {
12792 SWIG_exception(SWIG_ValueError,"Expected positive value.");
12797 <H3><A name="Typemaps_nn32"></A>10.5.7 "argout" typemap</H3>
12798 <P> The "argout" 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 "argout" typemap is almost always
12801 combined with an "in" typemap---possibly to ignore the input value. For
12805 /* Set the input argument to point to a temporary variable */
12806 %typemap(in, numinputs=0) int *out (int temp) {
12810 %typemap(argout) int *out {
12811 // Append output value $1 to $result
12816 <P> The following special variables are available.</P>
12817 <DIV class="diagram">
12819 $result - Result object returned to target language.
12820 $input - The original input object passed.
12821 $symname - Name of function/method being wrapped
12824 <P> The code supplied to the "argout" typemap is always placed after the
12825 "out" 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 "freearg" typemap</H3>
12829 <P> The "freearg" 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 "freearg" typemap
12832 usually cleans up argument resources allocated by the "in" typemap. For
12836 // Get a list of integers
12837 %typemap(in) int *items {
12838 int nitems = Length($input);
12839 $1 = (int *) malloc(sizeof(int)*nitems);
12842 %typemap(freearg) int *items {
12847 <P> The "freearg" 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
12852 <H3><A name="Typemaps_nn34"></A>10.5.9 "newfree" typemap</H3>
12853 <P> The "newfree" 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>
12858 %typemap(newfree) string * {
12861 %typemap(out) string * {
12862 $result = PyString_FromString($1->c_str());
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 "memberin" typemap</H3>
12874 <P> The "memberin" 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>
12879 %typemap(memberin) int [4] {
12880 memmove($1, $input, 4*sizeof(int));
12884 <P> It is rarely necessary to write "memberin" typemaps---SWIG already
12885 provides a default implementation for arrays, strings, and other
12887 <H3><A name="Typemaps_nn36"></A>10.5.11 "varin" typemap</H3>
12888 <P> The "varin" 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 "varout" typemap</H3>
12892 <P> The "varout" 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 "throws" typemap</H3>
12896 <P> The "throws" 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>
12906 %typemap(throws) const char * %{
12907 PyErr_SetString(PyExc_RuntimeError, $1);
12910 void bar() throw (const char *);
12913 <P> As can be seen from the generated code below, SWIG generates an
12914 exception handler with the catch block comprising the "throws" typemap
12922 catch(char const *_e) {
12923 PyErr_SetString(PyExc_RuntimeError, _e);
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>
12943 void set_vector(int type, float value[4]);
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>
12951 %typemap(in) float value[4] (float temp[4]) {
12953 if (!PySequence_Check($input)) {
12954 PyErr_SetString(PyExc_ValueError,"Expected a sequence");
12957 if (PySequence_Length($input) != 4) {
12958 PyErr_SetString(PyExc_ValueError,"Size mismatch. Expected 4 elements");
12961 for (i = 0; i < 4; i++) {
12962 PyObject *o = PySequence_GetItem($input,i);
12963 if (PyNumber_Check(o)) {
12964 temp[i] = (float) PyFloat_AsDouble(o);
12966 PyErr_SetString(PyExc_ValueError,"Sequence elements must be numbers");
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
12979 <DIV class="targetlang">
12981 >>> set_vector(type, [ 1, 2.5, 5, 20 ])
12984 <P> If you wanted to generalize the typemap to apply to arrays of all
12985 dimensions you might write this:</P>
12988 %typemap(in) float value[ANY] (float temp[$1_dim0]) {
12990 if (!PySequence_Check($input)) {
12991 PyErr_SetString(PyExc_ValueError,"Expected a sequence");
12994 if (PySequence_Length($input) != $1_dim0) {
12995 PyErr_SetString(PyExc_ValueError,"Size mismatch. Expected $1_dim0 elements");
12998 for (i = 0; i < $1_dim0; i++) {
12999 PyObject *o = PySequence_GetItem($input,i);
13000 if (PyNumber_Check(o)) {
13001 temp[i] = (float) PyFloat_AsDouble(o);
13003 PyErr_SetString(PyExc_ValueError,"Sequence elements must be numbers");
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>
13016 %typemap(in) float matrix[ANY][ANY] (float temp[$1_dim0][$1_dim1]) {
13017 ... convert a 2d array ...
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>
13026 %typemap(in) float value[ANY] {
13028 if (!PySequence_Check($input)) {
13029 PyErr_SetString(PyExc_ValueError,"Expected a sequence");
13032 if (PySequence_Length($input) != $1_dim0) {
13033 PyErr_SetString(PyExc_ValueError,"Size mismatch. Expected $1_dim0 elements");
13036 $1 = (float *) malloc($1_dim0*sizeof(float));
13037 for (i = 0; i < $1_dim0; i++) {
13038 PyObject *o = PySequence_GetItem($input,i);
13039 if (PyNumber_Check(o)) {
13040 $1[i] = (float) PyFloat_AsDouble(o);
13042 PyErr_SetString(PyExc_ValueError,"Sequence elements must be numbers");
13048 %typemap(freearg) float value[ANY] {
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 "assign" 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>
13063 struct SomeObject {
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">
13073 swig -python example.i
13074 Generating wrappers for Python
13075 example.i:10. Warning. Array member value will be read-only.
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 "memberin" typemap like this:</P>
13083 %typemap(memberin) float [ANY] {
13085 for (i = 0; i < $1_dim0; i++) {
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 "in" and "memberin" typemap allows the following usage:</P>
13097 <DIV class="targetlang">
13099 >>> s = SomeObject()
13100 >>> s.x = [1, 2.5, 5, 10]
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
13108 <DIV class="targetlang">
13110 >>> s = SomeObject()
13111 >>> s.x = [1, 2.5, 5, 10]
13112 >>> print s.x
13117 <P> To fix this, you can write an "out" typemap. For example:</P>
13120 %typemap(out) float [ANY] {
13122 $result = PyList_New($1_dim0);
13123 for (i = 0; i < $1_dim0; i++) {
13124 PyObject *o = PyFloat_FromDouble((double) $1[i]);
13125 PyList_SetItem($result,i,o);
13130 <P> Now, you will find that member access is quite nice:</P>
13131 <DIV class="targetlang">
13133 >>> s = SomeObject()
13134 >>> s.x = [1, 2.5, 5, 10]
13135 >>> print s.x
13139 <P><B> Compatibility Note:</B> SWIG1.1 used to provide a special
13140 "memberout" typemap. However, it was mostly useless and has since been
13141 eliminated. To return structure members, simply use the "out" typemap.</P>
13142 <H3><A name="Typemaps_nn41"></A>10.6.2 Implementing constraints with
13144 <P> One particularly interesting application of typemaps is the
13145 implementation of argument constraints. This can be done with the
13146 "check" typemap. When used, this allows you to provide code for
13147 checking the values of function arguments. For example :</P>
13152 %typemap(check) double posdouble {
13154 croak("Expecting a positive number");
13159 double sqrt(double posdouble);
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>
13170 %typemap(check) Vector * {
13172 PyErr_SetString(PyExc_TypeError,"NULL Pointer not allowed");
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++
13184 <P> Note: A more advanced constraint checking system is in development.
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 "in" typemap for Perl and Ruby could be written as:</P>
13193 #if defined(SWIGPERL)
13194 %typemap(in) int "$1 = ($1_ltype) SvIV($input);"
13195 #elif defined(SWIGRUBY)
13196 %typemap(in) int "$1 = NUM2INT($input);"
13198 #warning no "in" typemap defined
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
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 "$1 = NUM2INT($input);"</TT>.</P>
13210 <H2><A name="Typemaps_optimal"></A>10.8 Optimal code generation when
13211 returning by value</H2>
13212 <P> The "out" typemap is the main typemap for return types. This typemap
13213 supports an optional attribute flag called "optimal", 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>
13227 %typemap(out) SWIGTYPE %{
13228 $result = new $1_ltype((const $1_ltype &)$1);
13232 #include <iostream>
13233 using namespace std;
13236 XX() { cout << "XX()" << endl; }
13237 XX(int i) { cout << "XX(" << i << ")" << endl; }
13238 XX(const XX &other) { cout << "XX(const XX &)" << endl; }
13239 XX & operator =(const XX &other) { cout << "operator=(const XX &)" << endl; return *this; }
13240 ~XX() { cout << "~XX()" << endl; }
13241 static XX create() {
13248 <P> The "out" 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">
13255 operator=(const XX &)
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 "optimal" attribute in the "out" typemap
13268 can help out. If the typemap code is kept the same and just the
13269 "optimal" attribute specified like this:</P>
13272 %typemap(out, optimal="1") SWIGTYPE %{
13273 $result = new $1_ltype((const $1_ltype &)$1);
13277 <P> then when the code is run again, the output is simply:</P>
13278 <DIV class="targetlang">
13284 <P> How the "optimal" attribute works is best explained using the
13285 generated code. Without "optimal", the generated code is:</P>
13288 SWIGEXPORT void * SWIGSTDCALL CSharp_XX_create() {
13291 result = XX::create();
13292 jresult = new XX((const XX &)result);
13298 <P> With the "optimal" attribute, the code is:</P>
13301 SWIGEXPORT void * SWIGSTDCALL CSharp_XX_create() {
13303 jresult = new XX((const XX &)XX::create());
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 "optimal" attribute is telling SWIG to
13319 <P> The "optimal" 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>
13326 %exception XX::create() %{
13329 } catch(const std::exception &e) {
13330 cout << e.what() << endl;
13335 <P> SWIG can detect when the "optimal" attribute cannot be used and will
13336 ignore it and in this case will issue the following warning:</P>
13337 <DIV class="targetlang">
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:
13342 result = XX::create();
13343 } catch(const std::exception &e) {
13344 cout << e.what() << endl;
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>
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">
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.
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
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>
13372 int foo(int argc, char *argv[]);
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">
13379 >>> foo(["ale","lager","stout"])
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
13394 %typemap(in) (int argc, char *argv[]) {
13396 if (!PyList_Check($input)) {
13397 PyErr_SetString(PyExc_ValueError, "Expecting a list");
13400 $1 = PyList_Size($input);
13401 $2 = (char **) malloc(($1+1)*sizeof(char *));
13402 for (i = 0; i < $1; i++) {
13403 PyObject *s = PyList_GetItem($input,i);
13404 if (!PyString_Check(s)) {
13406 PyErr_SetString(PyExc_ValueError, "List items must be strings");
13409 $2[i] = PyString_AsString(s);
13414 %typemap(freearg) (int argc, char *argv[]) {
13419 <P> A multi-argument map is always specified by surrounding the
13420 arguments with parentheses as shown. For example:</P>
13423 %typemap(in) (int argc, char *argv[]) { ... }
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>
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 ... }
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
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>
13449 %typemap(in) (int scount, char *swords[]) { ... }
13450 %typemap(in) (int wcount, char *words[]) { ... }
13452 void search_words(int scount, char *swords[], int wcount, char *words[], int maxcount);
13455 <P> Other directives such as <TT>%apply</TT> and <TT>%clear</TT> also
13456 work with multi-argument maps. For example:</P>
13459 %apply (int argc, char *argv[]) {
13460 (int scount, char *swords[]),
13461 (int wcount, char *words[])
13464 %clear (int scount, char *swords[]), (int wcount, char *words[]);
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>
13474 typedef unsigned int size_t;
13476 int read(int fd, void *rbuffer, size_t len);
13477 int write(int fd, void *wbuffer, size_t len);
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>
13487 // typemap for an outgoing buffer
13488 %typemap(in) (void *wbuffer, size_t len) {
13489 if (!PyString_Check($input)) {
13490 PyErr_SetString(PyExc_ValueError, "Expecting a string");
13493 $1 = (void *) PyString_AsString($input);
13494 $2 = PyString_Size($input);
13497 // typemap for an incoming buffer
13498 %typemap(in) (void *rbuffer, size_t len) {
13499 if (!PyInt_Check($input)) {
13500 PyErr_SetString(PyExc_ValueError, "Expecting an integer");
13503 $2 = PyInt_AsLong($input);
13505 PyErr_SetString(PyExc_ValueError, "Positive integer expected");
13508 $1 = (void *) malloc($2);
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 < 0) { /* Check for I/O error */
13516 PyErr_SetFromErrno(PyExc_IOError);
13519 $result = PyString_FromStringAndSize($1,result);
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">
13532 >>> f = example.open("Makefile")
13533 >>> example.read(f,40)
13534 'TOP = ../..\nSWIG = $(TOP)/.'
13535 >>> example.read(f,40)
13536 './swig\nSRCS = example.c\nTARGET '
13537 >>> example.close(f)
13539 >>> g = example.open("foo", example.O_WRONLY | example.O_CREAT, 0644)
13540 >>> example.write(g,"Hello world\n")
13542 >>> example.write(g,"This is a test\n")
13544 >>> example.close(g)
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
13555 int is_symmetric(double *mat, int rows, int columns);
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>
13563 %typemap(in) (double *mat, int rows, int columns) {
13565 a = GetMatrixFromObject($input); /* Get matrix somehow */
13567 /* Get matrix properties */
13568 $1 = GetPointer(a);
13570 $3 = GetColumns(a);
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>
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
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>
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">
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>
13628 class FooBar : public Foo, public Bar {
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">
13638 FooBar --> | -----------| <-- Foo
13640 |------------| <-- Bar
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>
13659 if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_Foo,1)) == -1) return NULL;
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 "a type X that can
13675 cast into a type Y" 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>
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 */
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 */
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
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
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;
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>
13759 %typemap(in) Foo * {
13760 if ((SWIG_ConvertPtr($input, (void **) &$1, $1_descriptor)) == -1) return NULL;
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 "in use." 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>
13782 %typemap(in) Foo * {
13783 if ((SWIG_ConvertPtr($input, (void **) &$1, $1_descriptor)) == -1) {
13785 if ((SWIG_ConvertPtr($input, (void **) &temp, <B>$descriptor(Bar *)</B>) == -1) {
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>
13805 %types(int *, short *, long *, float *, double *);
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
13825 int foo(char *s, int y);
13828 <P> You can access the functions in a normal way from the scripting
13830 <DIV class="targetlang">
13834 foo(3.5) # foo(double)
13835 foo("hello",5) # foo(char *, int)
13839 foo 3.5 # foo(double)
13840 foo hello 5 # foo(char *, int)
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>
13848 // wrapper pseudocode
13849 _wrap_foo_0(argc, args[]) { // foo(int)
13853 arg1 = FromInteger(args[0]);
13854 result = foo(arg1);
13855 return ToInteger(result);
13858 _wrap_foo_1(argc, args[]) { // foo(double)
13862 arg1 = FromDouble(args[0]);
13863 result = foo(arg1);
13864 return ToInteger(result);
13867 _wrap_foo_2(argc, args[]) { // foo(char *, int)
13872 arg1 = FromString(args[0]);
13873 arg2 = FromInteger(args[1]);
13874 result = foo(arg1,arg2);
13875 return ToInteger(result);
13880 <P> Next, a dynamic dispatch function is generated:</P>
13883 _wrap_foo(argc, args[]) {
13885 if (IsInteger(args[0])) {
13886 return _wrap_foo_0(argc,args);
13888 if (IsDouble(args[0])) {
13889 return _wrap_foo_1(argc,args);
13893 if (IsString(args[0]) && IsInteger(args[1])) {
13894 return _wrap_foo_2(argc,args);
13897 error("No matching function!\n");
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 "<A href="#SWIGPlus">SWIG and C++</A>
13910 " 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">
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
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 "typecheck" typemaps. The follow excerpt from the Python
13959 module illustrates this:</P>
13962 /* Python type checking rules */
13963 /* Note: %typecheck(X) is a macro for %typemap(typecheck,precedence=X) */
13965 %typecheck(SWIG_TYPECHECK_INTEGER)
13967 unsigned int, unsigned short, unsigned long,
13968 signed char, unsigned char,
13969 long long, unsigned long long,
13970 const int &, const short &, const long &,
13971 const unsigned int &, const unsigned short &, const unsigned long &,
13972 const long long &, const unsigned long long &,
13974 bool, const bool &
13976 $1 = (PyInt_Check($input) || PyLong_Check($input)) ? 1 : 0;
13979 %typecheck(SWIG_TYPECHECK_DOUBLE)
13981 const float &, const double &
13983 $1 = (PyFloat_Check($input) || PyInt_Check($input) || PyLong_Check($input)) ? 1 : 0;
13986 %typecheck(SWIG_TYPECHECK_CHAR) char {
13987 $1 = (PyString_Check($input) && (PyString_Size($input) == 1)) ? 1 : 0;
13990 %typecheck(SWIG_TYPECHECK_STRING) char * {
13991 $1 = PyString_Check($input) ? 1 : 0;
13994 %typecheck(SWIG_TYPECHECK_POINTER) SWIGTYPE *, SWIGTYPE &, SWIGTYPE [] {
13996 if (SWIG_ConvertPtr($input, (void **) &ptr, $1_descriptor, 0) == -1) {
14004 %typecheck(SWIG_TYPECHECK_POINTER) SWIGTYPE {
14006 if (SWIG_ConvertPtr($input, (void **) &ptr, $&1_descriptor, 0) == -1) {
14014 %typecheck(SWIG_TYPECHECK_VOIDPTR) void * {
14016 if (SWIG_ConvertPtr($input, (void **) &ptr, 0, 0) == -1) {
14024 %typecheck(SWIG_TYPECHECK_POINTER) PyObject *
14026 $1 = ($input != 0);
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>
14036 <LI>Overloaded methods are first sorted by the number of required
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>
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>
14050 // Typemap for a C++ string
14051 %typemap(in) std::string {
14052 if (PyString_Check($input)) {
14053 $1 = std::string(PyString_AsString($input));
14055 SWIG_exception(SWIG_TypeError, "string expected");
14058 // Copy the typecheck code for "char *".
14059 %typemap(typecheck) std::string = char *;
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>
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 "in"
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 "in" typemaps would then perform more extensive type-checking.</LI>
14081 <LI>Make sure you read the section on overloading in the "<A href="#SWIGPlus">
14082 SWIG and C++</A>" chapter.</LI>
14084 <H2><A name="Typemaps_nn48"></A>10.12 More about <TT>%apply</TT> and <TT>
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>
14091 %typemap(in,numinputs=0) int *OUTPUT (int temp) {
14094 %typemap(argout) int *OUTPUT {
14095 // return value somehow
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>
14104 %apply int *OUTPUT { int *retvalue, int32 *output };
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>
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>
14120 <P> For example:</P>
14123 %typemap(in) int *INPUT (int temp) {
14124 temp = ... get value from $input ...;
14128 %typemap(check) int *POSITIVE {
14130 SWIG_exception(SWIG_ValueError,"Expected a positive number!\n");
14136 %apply int *INPUT { int *invalue };
14137 %apply int *POSITIVE { int *invalue };
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>
14146 %clear int *invalue;
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>
14155 %typemap(in) float [ANY] {
14157 if (!PySequence_Check($input)) {
14158 PyErr_SetString(PyExc_ValueError,"Expected a sequence");
14161 if (PySequence_Length($input) != $1_dim0) {
14162 PyErr_SetString(PyExc_ValueError,"Size mismatch. Expected $1_dim0 elements");
14165 $1 = (float) malloc($1_dim0*sizeof(float));
14166 for (i = 0; i < $1_dim0; i++) {
14167 PyObject *o = PySequence_GetItem($input,i);
14168 if (PyNumber_Check(o)) {
14169 $1[i] = (float) PyFloat_AsDouble(o);
14171 PyErr_SetString(PyExc_ValueError,"Sequence elements must be numbers");
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>
14186 /* Define a helper function */
14188 convert_float_array(PyObject *input, int size) {
14191 if (!PySequence_Check(input)) {
14192 PyErr_SetString(PyExc_ValueError,"Expected a sequence");
14195 if (PySequence_Length(input) != size) {
14196 PyErr_SetString(PyExc_ValueError,"Size mismatch. ");
14199 result = (float) malloc(size*sizeof(float));
14200 for (i = 0; i < size; i++) {
14201 PyObject *o = PySequence_GetItem(input,i);
14202 if (PyNumber_Check(o)) {
14203 result[i] = (float) PyFloat_AsDouble(o);
14205 PyErr_SetString(PyExc_ValueError,"Sequence elements must be numbers");
14214 %typemap(in) float [ANY] {
14215 $1 = convert_float_array($input, $1_dim0);
14216 if (!$1) return NULL;
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>
14231 %typemap(in) int *(int temp) {
14232 temp = (int) PyInt_AsLong($input);
14236 %typemap(argout) int * {
14237 PyObject *o = PyInt_FromLong(temp$argnum);
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++ "this" 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>
14263 %typemap(check) SWIGTYPE *self %{
14265 SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "swigCPtr null");
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>
14279 SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException,
14280 "invalid native object; delete() likely already called");
14283 (arg1)->wrappedFunction(...);
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>
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>
14302 <H1><A name="Customization"></A>11 Customization Features</H1>
14305 <DIV class="sectiontoc">
14307 <LI><A href="#exception">Exception handling with %exception</A>
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
14314 <LI><A href="#Customization_nn6">Defining different exception handlers</A>
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>
14321 <LI><A href="#ownership">Object ownership and %newobject</A></LI>
14322 <LI><A href="#features">Features and the %feature directive</A>
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
14329 <LI><A href="#features_example">Feature example</A></LI>
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 "features" 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>
14351 catch (RangeError) {
14352 PyErr_SetString(PyExc_IndexError,"index out-of-bounds");
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>
14368 %exception; // Deletes any previously defined handler
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>
14381 /* File : except.c */
14383 static char error_message[256];
14384 static int error_status = 0;
14386 void throw_exception(char *msg) {
14387 strncpy(error_message,msg,256);
14391 void clear_exception() {
14394 char *check_exception() {
14395 if (error_status) return error_message;
14401 <P> To use these functions, functions simply call <TT>throw_exception()</TT>
14402 to indicate an error occurred. For example :</P>
14405 double inv(double x) {
14406 if (x != 0) return 1.0/x;
14408 throw_exception("Division by zero");
14415 <P> To catch the exception, you can write a simple exception handler
14416 such as the following (shown for Perl5) :</P>
14423 if ((err = check_exception())) {
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
14433 <H3><A name="Customization_nn4"></A>11.1.2 Exception handling with
14435 <P> Exception handling can also be added to C code using the <TT>
14436 <setjmp.h></TT> library. Here is a minimalistic implementation that
14437 relies on the C preprocessor :</P>
14441 Just the declaration of a few global variables we're going to use */
14443 #include <setjmp.h>
14444 jmp_buf exception_buffer;
14445 int exception_status;
14447 /* File : except.h */
14448 #include <setjmp.h>
14449 extern jmp_buf exception_buffer;
14450 extern int exception_status;
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
14457 /* Exception codes */
14459 #define RangeError 1
14460 #define DivisionByZero 2
14461 #define OutOfMemory 3
14465 <P> Now, within a C program, you can do the following :</P>
14468 double inv(double x) {
14469 if (x) return 1.0/x;
14470 else throw(DivisionByZero);
14475 <P> Finally, to create a SWIG exception handler, write the following :</P>
14479 #include "except.h"
14485 } catch(RangeError) {
14486 croak("Range Error");
14487 } catch(DivisionByZero) {
14488 croak("Division by zero");
14489 } catch(OutOfMemory) {
14490 croak("Out of memory");
14492 croak("Unknown exception");
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>
14507 } catch(RangeError) {
14508 croak("Range Error");
14509 } catch(DivisionByZero) {
14510 croak("Division by zero");
14511 } catch(OutOfMemory) {
14512 croak("Out of memory");
14514 croak("Unknown exception");
14520 <P> The exception types need to be declared as classes elsewhere,
14521 possibly in a header file :</P>
14524 class RangeError {};
14525 class DivisionByZero {};
14526 class OutOfMemory {};
14529 <H3><A name="Customization_allowexcept"></A>11.1.4 Exception handlers
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("allowexcept")</TT>, that is, it is a feature
14540 called "allowexcept". 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>
14547 %allowexception; // turn on globally
14548 %allowexception Klass::MyVar; // turn on for a specific variable
14550 %noallowexception Klass::MyVar; // turn off for a specific variable
14551 %noallowexception; // turn off globally
14554 <H3><A name="Customization_nn6"></A>11.1.5 Defining different exception
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
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>
14568 ... your exception handler ...
14570 /* Define critical operations that can throw exceptions here */
14574 /* Define non-critical operations that don't throw exceptions */
14577 <P> More precise control over exception handling can be obtained by
14578 attaching an exception handler to specific declaration name. For
14582 %exception allocate {
14586 catch (MemoryError) {
14587 croak("Out of memory");
14592 <P> In this case, the exception handler is only attached to declarations
14593 named "allocate". 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>
14600 %exception Object::allocate {
14604 catch (MemoryError) {
14605 croak("Out of memory");
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>
14617 %exception Object::allocate(int) {
14621 catch (MemoryError) {
14622 croak("Out of memory");
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>
14634 #include "someheader.h"
14637 // Define a few exception handlers for specific declarations
14638 %exception Object::allocate(int) {
14642 catch (MemoryError) {
14643 croak("Out of memory");
14647 %exception Object::getitem {
14651 catch (RangeError) {
14652 croak("Index out of range");
14656 // Read a raw header file
14657 %include "someheader.h"
14660 <P><B> Compatibility note:</B> The <TT>%exception</TT> directive
14661 replaces the functionality provided by the deprecated "except" 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
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
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>
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>
14694 %exception Special::something {
14695 log("symname: $symname");
14696 log("overname: $overname");
14697 log("wrapname: $wrapname");
14698 log("decl: $decl");
14699 log("fulldecl: $fulldecl");
14703 catch (MemoryError) {
14704 croak("Out of memory in $decl");
14707 void log(const char *message);
14709 void something(const char *c);
14710 void something(int i);
14714 <P> Below shows the expansions for the 1st of the overloaded <TT>
14715 something</TT> wrapper methods for Perl:</P>
14718 log("symname: Special_something");
14719 log("overname: __SWIG_0");
14720 log("wrapname: _wrap_Special_something__SWIG_0");
14721 log("decl: Special::something(char const *)");
14722 log("fulldecl: void Special::something(char const *)");
14724 (arg1)->something((char const *)arg2);
14726 catch (MemoryError) {
14727 croak("Out of memory in Special::something(char const *)");
14731 <H3><A name="Customization_nn7"></A>11.1.7 Using The SWIG exception
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 "<TT>%include exception.i</TT>" 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
14741 // Language independent exception handler
14742 %include exception.i
14747 } catch(RangeError) {
14748 SWIG_exception(SWIG_ValueError, "Range Error");
14749 } catch(DivisionByZero) {
14750 SWIG_exception(SWIG_DivisionByZero, "Division by zero");
14751 } catch(OutOfMemory) {
14752 SWIG_exception(SWIG_MemoryError, "Out of memory");
14754 SWIG_exception(SWIG_RuntimeError,"Unknown exception");
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
14763 <DIV class="diagram">
14770 SWIG_DivisionByZero
14775 SWIG_AttributeError
14777 SWIG_NullReferenceError
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>
14789 Foo *f = new Foo();
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>
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>
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
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 "newfree" 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
14830 %typemap(newfree) char * "free($1);";
14834 char *strdup(const char *s);
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 "newfree"
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>
14846 %newobject create_foo;
14847 %delobject destroy_foo;
14850 void destroy_foo(Foo *foo);
14853 <P> or in a member method as:</P>
14856 %delobject Foo::destroy;
14860 void destroy() { delete this;}
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>
14877 %new char *strdup(const char *s);
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>
14887 char *strdup(const char *s);
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 "features." 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>
14899 %feature("except") Object::allocate {
14903 catch (MemoryError) {
14904 croak("Out of memory");
14908 %feature("new","1") *::copy;
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>
14915 #define %exception %feature("except")
14916 #define %newobject %feature("new","1")
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>
14930 /* Define a global exception handler */
14931 %feature("except") {
14938 ... bunch of declarations ...
14941 <P> The <TT>%feature</TT> directive can be used with different syntax.
14942 The following are all equivalent:</P>
14945 %feature("except") Object::method { $action };
14946 %feature("except") Object::method %{ $action %};
14947 %feature("except") Object::method " $action ";
14948 %feature("except","$action") Object::method;
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
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>
14960 %feature("name","value", attribute1="AttributeValue1") symbol;
14961 %feature("name", attribute1="AttributeValue1") symbol {value};
14962 %feature("name", attribute1="AttributeValue1") symbol %{value%};
14963 %feature("name", attribute1="AttributeValue1") symbol "value";
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("except")</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>
14974 %feature("except", throws="MyExceptionClass") Object::method {
14978 ... code to throw a MyExceptionClass Java exception ...
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>
14992 %feature("featurename") // enables feature
14993 %feature("featurename", "1") // enables feature
14994 %feature("featurename", "x") // enables feature
14995 %feature("featurename", "0") // disables feature
14996 %feature("featurename", "") // clears feature
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("immutable")</TT>, and can be used to demonstrates feature
15009 // features are disabled by default
15010 int red; // mutable
15012 %feature("immutable"); // global enable
15013 int orange; // immutable
15015 %feature("immutable","0"); // global disable
15016 int yellow; // mutable
15018 %feature("immutable","1"); // another form of global enable
15019 int green; // immutable
15021 %feature("immutable",""); // clears the global feature
15022 int blue; // mutable
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>
15031 %feature("immutable","1") orange;
15032 %feature("immutable","1") green;
15033 int red; // mutable
15034 int orange; // immutable
15035 int yellow; // mutable
15036 int green; // immutable
15037 int blue; // mutable
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
15046 %feature("immutable","1");
15047 %feature("immutable","0") red;
15048 %feature("immutable","0") yellow;
15049 %feature("immutable","0") blue;
15050 int red; // mutable
15051 int orange; // immutable
15052 int yellow; // mutable
15053 int green; // immutable
15054 int blue; // mutable
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>
15063 %featurename // equivalent to %feature("featurename", "1") ie enables feature
15064 %nofeaturename // equivalent to %feature("featurename", "0") ie disables feature
15065 %clearfeaturename // equivalent to %feature("featurename", "") ie clears feature
15068 <P> The concept of clearing features is discussed next.</P>
15069 <H3><A name="Customization_clearing_features"></A>11.3.3 Clearing
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("name","")</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>
15080 // Define global exception handler
15081 %feature("except") {
15085 croak("Unknown C++ exception");
15089 // Define exception handler for all clone methods to log the method calls
15090 %feature("except") *::clone() {
15092 logger.info("$action");
15095 croak("Unknown C++ exception");
15099 ... initial set of class declarations with clone methods ...
15101 // clear the previously defined feature
15102 %feature("except","") *::clone();
15104 ... final set of class declarations with clone methods ...
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("except","") *::clone()</TT>
15114 is not the same as specifying <TT>%feature("except","0") *::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
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>
15125 %feature("except") clone() { logger.info("$action"); $action }
15126 %feature("except","") *::clone();
15129 <P> but this will:</P>
15132 %feature("except") clone() { logger.info("$action"); $action }
15133 %feature("except","") clone();
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 "except" feature:</P>
15143 #define %exception %feature("except")
15144 #define %noexception %feature("except","0")
15145 #define %clearexception %feature("except","")
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>
15160 %feature("except") void hello(int i=0, double d=0.0) { ... }
15161 void hello(int i=0, double d=0.0);
15164 <P> will apply the feature to all three wrapper methods, that is:</P>
15167 void hello(int i, double d);
15172 <P> If the default arguments are not specified in the feature:</P>
15175 %feature("except") void hello(int i, double d) { ... }
15176 void hello(int i=0, double d=0.0);
15179 <P> then the feature will only apply to this wrapper method:</P>
15182 void hello(int i, double d);
15185 <P> and not these wrapper methods:</P>
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
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>
15210 %rename(bar_id) bar(int,double);
15212 // Rewrite bar() to allow some nice overloading
15214 %feature("shadow") Foo::bar(int) %{
15217 return apply(examplec.Foo_bar_id,args)
15218 return apply(examplec.Foo_bar,args)
15224 int bar(int x, double y);
15228 <P> Further details of <TT>%feature</TT> usage is described in the
15229 documentation for specific language modules.</P>
15231 <H1><A name="Contract"></A>12 Contracts</H1>
15234 <DIV class="sectiontoc">
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>
15240 <LI><A href="#Contract_nn5">Notes</A></LI>
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
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>
15262 %contract sqrt(double x) {
15270 double sqrt(double);
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
15286 <P> Once a contract has been specified, it modifies the behavior of the
15287 resulting module. For example:</P>
15288 <DIV class="shell">
15290 >>> example.sqrt(2)
15292 >>> example.sqrt(-2)
15293 Traceback (most recent call last):
15294 File "<stdin>", line 1, in ?
15295 RuntimeError: Contract violation: require: (arg1>=0)
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>
15304 %contract Foo::bar(int x, int y) {
15311 %contract Foo::Foo(int a) {
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.
15329 class Spam : public Foo {
15331 int bar(int,int); // Gets contract defined for Foo::bar(int,int)
15335 <P> In addition to this, separate contracts can be applied to both the
15336 base class and a derived class. For example:</P>
15339 %contract Foo::bar(int x, int) {
15344 %contract Spam::bar(int, int y) {
15351 int bar(int,int); // Gets Foo::bar contract.
15354 class Spam : public Foo {
15356 int bar(int,int); // Gets Foo::bar and Spam::bar contract
15360 <P> When more than one contract is applied, the conditions specified in
15361 a "require:" 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
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>
15376 void move(SomeObject *, int direction, int distance);
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>
15385 %aggregate_check(int, check_direction, UP, DOWN, LEFT, RIGHT);
15388 <P> This merely defines a utility function of the form</P>
15391 int check_direction(int x);
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>
15398 %aggregate_check(int, check_direction, UP, DOWN, RIGHT, LEFT);
15400 %contract move(SomeObject *, int direction, in) {
15402 check_direction(direction);
15410 void move(SomeObject *, int direction, int distance);
15413 <P> Alternatively, it can be used in typemaps and other directives. For
15417 %aggregate_check(int, check_direction, UP, DOWN, RIGHT, LEFT);
15419 %typemap(check) int direction {
15420 if (!check_direction($1)) SWIG_exception(SWIG_ValueError, "Bad direction");
15428 void move(SomeObject *, int direction, int distance);
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>
15437 <H1><A name="Varargs"></A>13 Variable Length Arguments</H1>
15440 <DIV class="sectiontoc">
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>
15454 <P><B> (a.k.a, "The horror. The horror.")</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>
15468 int printf(const char *fmt, ...)
15469 int fprintf(FILE *, const char *fmt, ...);
15470 int sprintf(char *s, const char *fmt, ...);
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>
15479 int traceprintf(const char *fmt, ...);
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>
15495 int execlp(const char *path, const char *arg1, ...);
15499 execlp("ls","ls","-l",NULL);
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>
15508 int open(const char *path, int oflag, ...);
15512 f = open("foo", O_RDONLY);
15513 g = open("bar", O_WRONLY | O_CREAT, 0644);
15516 <P> Finally, to implement a varargs function, recall that you have to
15517 use the C library functions defined in <TT><stdarg.h></TT>. For
15521 List make_list(const char *s, ...) {
15528 s = va_arg(ap, const char *);
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>
15551 printf("Hello %s. Your number is %d\n", name, num);
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>
15564 int wrap_printf(const char *fmt, ...) {
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
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.
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>
15606 void traceprintf(const char *fmt, ...);
15609 <P> it would be wrapped as if it had been declared as follows:</P>
15612 void traceprintf(const char *fmt);
15615 <P> When the function is called inside the wrappers, it is called as
15619 traceprintf(arg1, NULL);
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">
15628 >>> traceprintf("Hello World")
15629 >>> traceprintf("Hello %s. Your number is %d\n" % (name, num))
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>
15640 %varargs(int mode = 0) open;
15642 int open(const char *path, int oflags, ...);
15645 <P> is equivalent to this:</P>
15648 int open(const char *path, int oflags, int mode = 0);
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>
15657 %varargs(10,char *arg = NULL) execlp;
15659 int execlp(const char *path, const char *arg1, ...);
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
15681 %typemap(in) (...) {
15682 // Get variable length arguments (somehow)
15686 %typemap(in) (const char *fmt, ...) {
15687 // Multi-argument typemap
15691 <P> However, this immediately raises the question of what "type" 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>
15705 %typemap(in) (const char *fmt, ...) {
15706 $1 = "%s"; /* Fix format string to %s */
15707 $2 = (void *) PyString_AsString($input); /* Get string argument */
15710 int printf(const char *fmt, ...);
15713 <P> In this example, the format string is implicitly set to <TT>"%s"</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>
15726 arg1 = "%s";
15727 arg2 = (void *) PyString_AsString(arg2obj);
15729 result = printf(arg1,arg2);
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>
15751 %typemap(in) (...)(char *args[10]) {
15754 for (i = 0; i < 10; i++) args[i] = 0;
15755 argc = PyTuple_Size(varargs);
15756 if (argc > 10) {
15757 PyErr_SetString(PyExc_ValueError,"Too many arguments");
15760 for (i = 0; i < argc; i++) {
15761 PyObject *o = PyTuple_GetItem(varargs,i);
15762 if (!PyString_Check(o)) {
15763 PyErr_SetString(PyExc_ValueError,"Expected a string");
15766 args[i] = PyString_AsString(o);
15768 $1 = (void *) args;
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>
15783 %feature("action") 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);
15789 int execlp(const char *path, const char *arg, ...);
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>
15817 /* Take an arbitrary number of extra arguments and place into an array
15820 %typemap(in) (...) {
15825 argc = PyTuple_Size(varargs);
15826 argv = (char **) malloc(sizeof(char *)*(argc+1));
15827 for (i = 0; i < argc; i++) {
15828 PyObject *o = PyTuple_GetItem(varargs,i);
15829 if (!PyString_Check(o)) {
15830 PyErr_SetString(PyExc_ValueError,"Expected a string");
15834 argv[i] = PyString_AsString(o);
15837 $1 = (void *) argv;
15840 /* Rewrite the function call, using libffi */
15842 %feature("action") execlp {
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;
15854 /* Set up path parameter */
15855 types[0] = &ffi_type_pointer;
15856 values[0] = &arg1;
15858 /* Set up first argument */
15859 types[1] = &ffi_type_pointer;
15860 values[1] = &arg2;
15862 /* Set up rest of parameters */
15863 for (i = 0; i <= vc; i++) {
15864 types[2+i] = &ffi_type_pointer;
15865 values[2+i] = &args[i];
15867 if (ffi_prep_cif(&cif, FFI_DEFAULT_ABI, vc+3,
15868 &ffi_type_uint, types) == FFI_OK) {
15869 ffi_call(&cif, (void (*)()) execlp, &result, values);
15871 PyErr_SetString(PyExc_RuntimeError, "Whoa!!!!!");
15882 /* Declare the function. Whew! */
15883 int execlp(const char *path, const char *arg1, ...);
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 "why in the hell am I trying to wrap this varargs
15890 function in the first place?!?" 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>
15896 /* A wrapper for printf() using libffi */
15899 /* Structure for holding passed arguments after conversion */
15908 enum { VT_INT, VT_DOUBLE, VT_POINTER };
15911 %typemap(in) (const char *fmt, ...) {
15916 /* Format string */
15917 $1 = PyString_AsString($input);
15919 /* Variable length arguments */
15920 argc = PyTuple_Size(varargs);
15921 argv = (vtype *) malloc(argc*sizeof(vtype));
15922 for (i = 0; i < 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);
15934 PyErr_SetString(PyExc_ValueError,"Unsupported argument type");
15939 $2 = (void *) argv;
15942 /* Rewrite the function call using libffi */
15943 %feature("action") printf {
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;
15955 /* Set up fmt parameter */
15956 types[0] = &ffi_type_pointer;
15957 values[0] = &arg1;
15959 /* Set up rest of parameters */
15960 for (i = 0; i < vc; i++) {
15961 switch(args[i].type) {
15963 types[1+i] = &ffi_type_uint;
15964 values[1+i] = &args[i].val.ivalue;
15967 types[1+i] = &ffi_type_double;
15968 values[1+i] = &args[i].val.dvalue;
15971 types[1+i] = &ffi_type_pointer;
15972 values[1+i] = &args[i].val.pvalue;
15975 abort(); /* Whoa! We're seriously hosed */
15979 if (ffi_prep_cif(&cif, FFI_DEFAULT_ABI, vc+1,
15980 &ffi_type_uint, types) == FFI_OK) {
15981 ffi_call(&cif, (void (*)()) printf, &result, values);
15983 PyErr_SetString(PyExc_RuntimeError, "Whoa!!!!!");
15995 int printf(const char *fmt, ...);
15998 <P> Much to your amazement, it even seems to work if you try it:</P>
15999 <DIV class="targetlang">
16001 >>> import example
16002 >>> example.printf("Grade: %s %d/60 = %0.2f%%\n", "Dave", 47, 47.0*100/60)
16003 Grade: Dave 47/60 = 78.33%
16007 <P> Of course, there are still some limitations to consider:</P>
16008 <DIV class="targetlang">
16010 >>> example.printf("la de da de da %s", 42)
16011 Segmentation fault (core dumped)
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>.
16030 int vfprintf(FILE *f, const char *fmt, va_list ap);
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.
16048 %varargs (10, char * = NULL) Foo::bar;
16052 virtual void bar(char *arg, ...); // gets varargs above
16055 class Spam: public Foo {
16057 virtual void bar(char *arg, ...); // gets varargs above
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
16081 %feature("action") Foo::bar {
16083 result = arg1->bar(arg2, arg3, etc.);
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>
16109 %typemap(const char *fmt, ...) {
16112 %feature("action") traceprintf {
16116 /* Include some header file with traceprintf in it */
16117 %include "someheader.h"
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>
16131 %feature("action") printf {
16135 #ifdef USE_OTHERFFI
16136 %feature("action") printf {
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 "A7.3.2 Function Calls" 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
16159 <H1><A name="Warnings"></A>14 Warning Messages</H1>
16162 <DIV class="sectiontoc">
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>
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>
16183 <LI><A href="#Warnings_nn17">History</A></LI>
16187 <H2><A name="Warnings_nn2"></A>14.1 Introduction</H2>
16188 <P> During compilation, SWIG may generate a variety of warning messages.
16190 <DIV class="shell">
16192 example.i:16: Warning(501): Overloaded declaration ignored. bar(double)
16193 example.i:15: Warning(501): Previous declaration is bar(int)
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">
16206 % swig -python -w501 example.i
16207 % swig -python -w501,505,401 example.i
16210 <P> Alternatively, warnings can be suppressed by inserting a special
16211 preprocessor pragma into the input file:</P>
16215 #pragma SWIG nowarn=501
16216 #pragma SWIG nowarn=501,505,401
16219 <P> Finally, code-generation warnings can be disabled on a declaration
16220 by declaration basis using the <TT>%warnfilter</TT> directive. For
16225 %warnfilter(501) foo;
16228 int foo(double); // Silently ignored.
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>
16238 %warnfilter(501) Object::foo;
16242 int foo(double); // Silently ignored
16246 class Derived : public Object {
16249 int foo(double); // Silently ignored
16254 <P> Warnings can be suppressed for an entire class by supplying a class
16255 name. For example:</P>
16258 %warnfilter(501) Object;
16262 ... // All 501 warnings ignored in class
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">
16276 % swig -Wextra -python example.i
16279 <P> To selectively turn on extra warning messages, you can use the
16280 directives and options in the previous section--simply add a "+" to all
16281 warning numbers. For example:</P>
16282 <DIV class="shell">
16284 % swig -w+309,+452 example.i
16287 <P> or in your interface file use either</P>
16290 #pragma SWIG nowarn=+309,+452
16296 %warnfilter(+309,+452) foo;
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>
16302 <P> You can of course also enable all warnings and suppress a select
16303 few, for example:</P>
16304 <DIV class="shell">
16306 % swig -Wextra -w309,452 example.i
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
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>
16325 %warn "900:This is your last warning!"
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>
16336 %ignorewarn("362:operator= ignored") operator=;
16339 <P> Warning messages can be associated with typemaps using the <TT>
16340 warning</TT> attribute of a typemap declaration. For example:</P>
16343 %typemap(in, warning="901:You are really going to regret this") blah * {
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
16357 %define SWIGWARN_TYPE_UNDEFINED_CLASS 401 %enddef
16360 <P> so <TT>SWIGWARN_TYPE_UNDEFINED_CLASS</TT> could be used instead of
16361 401, for example:</P>
16364 #pragma SWIG nowarn=SWIGWARN_TYPE_UNDEFINED_CLASS
16370 %warnfilter(SWIGWARN_TYPE_UNDEFINED_CLASS) Foo;
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
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,
16394 <DIV class="shell">
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.
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>
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>
16427 <H3><A name="Warnings_nn11"></A>14.9.2 Preprocessor (200-299)</H3>
16429 <LI>201. Unable to find 'filename'.</LI>
16430 <LI>202. Could not evaluate 'expr'.</LI>
16432 <H3><A name="Warnings_nn12"></A>14.9.3 C/C++ Parser (300-399)</H3>
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>
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>
16444 <LI>309. [private | protected] inheritance ignored.</LI>
16445 <LI>310. Template '<EM>name</EM>' was already wrapped as '<EM>name</EM>'
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 "<EM>name</EM>" (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>
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& 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< ignored.</LI>
16475 <LI>364. operator> 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&= ignored.</LI>
16483 <LI>372. operator|= ignored.</LI>
16484 <LI>373. operator<< ignored.</LI>
16485 <LI>374. operator>>ignored.</LI>
16486 <LI>375. operator<<= ignored.</LI>
16487 <LI>376. operator>>= ignored.</LI>
16488 <LI>377. operator== ignored.</LI>
16489 <LI>378. operator!= ignored.</LI>
16490 <LI>379. operator<= ignored.</LI>
16491 <LI>380. operator>= ignored.</LI>
16492 <LI>381. operator&& 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-<* ignored.</LI>
16498 <LI>387. operator-< 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& ignored (unary).</LI>
16505 <LI>394. operator new[] ignored.</LI>
16506 <LI>395. operator delete[] ignored.</LI>
16508 <H3><A name="Warnings_nn13"></A>14.9.4 Types and typemaps (400-499)</H3>
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>
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
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>
16539 <H3><A name="Warnings_nn14"></A>14.9.5 Code generation (500-599)</H3>
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
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->() 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>
16560 <LI>516. Overloaded method<EM> declaration</EM> ignored. Method<EM>
16561 declaration</EM> at<EM> file</EM>:<EM>line</EM> used.</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>
16569 <H3><A name="Warnings_nn15"></A>14.9.6 Language module specific
16572 <LI>801. Wrong name (corrected to '<EM>name</EM>'). (Ruby).</LI>
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>
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>
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>
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>
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>
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>
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>
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
16628 <H1><A name="Modules"></A>15 Working with Modules</H1>
16631 <DIV class="sectiontoc">
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>
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>
16658 <TT>%module(option1="value1",option2="value2",...) modulename</TT>
16661 <P> where the modulename is mandatory and the options add one or more
16662 optional additional features. Typically no options are specified, for
16666 <TT>%module mymodule</TT>
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>
16701 </DIV> <DIV class="code">
16703 // File: base_module.i
16704 %module base_module
16707 #include "base.h"
16709 %include "base.h"
16711 </DIV> <DIV class="code">
16713 // File: derived_module.i
16714 %module derived_module
16716 %import "base_module.i"
16719 class derived : public base {
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 "base_module.i"</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">
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.
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">
16749 // File: derived_module.i
16750 %module derived_module
16752 %import(module="base_module") "base.h"
16755 class derived : public base {
16761 <P> Note that "base_module" 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 "SWIG runtime." 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
16776 <P> The runtime functions are private to each SWIG-generated module.
16777 That is, the runtime functions are declared with "static" 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">
16827 $ swig -python -external-runtime <filename>
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
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 "Linkers and Loaders" 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>
16885 virtual void method();
16889 struct Derived : Base {
16890 virtual void method();
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("compactdefaultargs")</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>
16905 <H1><A name="CCache"></A>16 Using SWIG with ccache - ccache-swig(1)
16909 <DIV class="sectiontoc">
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>
16932 <H2><A name="CCache_nn2"></A>16.1 NAME</H2>
16933 <P> ccache-swig - a fast compiler cache</P>
16935 <H2><A name="CCache_nn3"></A>16.2 SYNOPSIS</H2>
16936 <P> ccache-swig [OPTION]</P>
16937 <P> ccache-swig <compiler> [COMPILER OPTIONS]</P>
16938 <P> <compiler> [COMPILER OPTIONS]</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
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>
16952 -s show statistics summary
16954 -c run a cache cleanup
16955 -C clear the cache completely
16956 -F <n> set maximum files in cache
16957 -M <n> set maximum size of cache (use G, M or K)
16959 -V print version number
16963 <H2><A name="CCache_nn6"></A>16.5 OPTIONS</H2>
16964 <P> These options only apply when you invoke ccache as "ccache-swig".
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>
16971 <DT><STRONG><STRONG>-h</STRONG></STRONG></DT>
16972 <DD> Print a options summary page
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 "ccache-swig -s" adds up the statistics across all subdirectories and
16984 <DT><STRONG><STRONG>-z</STRONG></STRONG></DT>
16985 <DD> Zero the cache statistics.
16989 <DT><STRONG><STRONG>-V</STRONG></STRONG></DT>
16990 <DD> Print the ccache version number
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
17004 <DT><STRONG><STRONG>-C</STRONG></STRONG></DT>
17005 <DD> Clear the entire cache, removing all cached files.
17009 <DT><STRONG><STRONG>-F <maxfiles></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.
17017 <DT><STRONG><STRONG>-M <maxsize></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.
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 "ccache-swig" 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>
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
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 "which gcc" 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 "interesting" problems.</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
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>
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 "$HOME/.ccache".
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
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.
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.
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.
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
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
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.
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.
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.
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.
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.
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.
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.
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
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.
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.
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.
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 "i" if you use the aCC compiler.
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: "-E" redefines product
17238 from "object" to "source (stdout)" when -E and -c is used together.
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
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 "ccache -M" and "ccache -F" options, which set the size and number of
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>
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>
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>
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>
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>
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>
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>
17313 <LI> Use the same<STRONG> CCACHE_DIR</STRONG> environment variable
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
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 "chmod g+s `find $CCACHE_DIR -type d`" 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>
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
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>
17340 <H2><A name="CCache_nn16"></A>16.15 DIFFERENCES FROM COMPILERCACHE</H2>
17341 <P> The biggest differences between Erik's compilercache script and
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>
17355 <H2><A name="CCache_nn17"></A>16.16 CREDITS</H2>
17356 <P> Thanks to the following people for their contributions to ccache</P>
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>
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>
17376 <!-- Hand-written HTML -->
17377 <H1><A name="Allegrocl_nn1"></A>17 SWIG and Allegro Common Lisp</H1>
17380 <DIV class="sectiontoc">
17382 <LI><A href="#Allegrocl_nn2">Basics</A>
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>
17390 <LI><A href="#Allegrocl_nn6">Wrapping Overview</A>
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>
17399 <LI><A href="#Allegrocl_nn13">Object Wrapping</A></LI>
17402 <LI><A href="#Allegrocl_nn14">Wrapping Details</A>
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>
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>
17418 <LI><A href="#Allegrocl_nn25">Templates</A>
17420 <LI><A href="#Allegrocl_nn26">Generating wrapper code for templates</A></LI>
17421 <LI><A href="#Allegrocl_nn27">Implicit Template instantiation</A></LI>
17424 <LI><A href="#Allegrocl_nn28">Typedef, Templates, and Synonym Types</A>
17426 <LI><A href="#Allegrocl_nn29">Choosing a primary type</A></LI>
17429 <LI><A href="#Allegrocl_nn30">Function overloading/Parameter defaulting</A>
17431 <LI><A href="#Allegrocl_nn31">Operator wrapping and Operator overloading</A>
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>
17438 <LI><A href="#Allegrocl_nn35">Typemaps</A>
17440 <LI><A href="#Allegrocl_nn36">Code Generation in the C++ Wrapper</A>
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>
17447 <LI><A href="#Allegrocl_nn40">Code generation in Lisp wrappers</A>
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>
17456 <LI><A href="#Allegrocl_nn46">Modifying SWIG behavior using typemaps</A></LI>
17459 <LI><A href="#Allegrocl_nn47">Identifier Converter functions</A>
17461 <LI><A href="#Allegrocl_nn48">Creating symbols in the lisp environment</A>
17463 <LI><A href="#Allegrocl_nn49">Existing identifier-converter functions</A>
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>
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>
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
17536 %include "header.h"
17541 <P>The contents of header.h are very simple:</P>
17542 <DIV class="code">header.h
17544 int fact(char *statement); // pass it a fact, and it will rate it.
17547 <P>The contents of example.cl will look like this:</P>
17548 <DIV class="targetlang">example.cl
17550 (defpackage :example
17551 (:use :common-lisp :swig :ff :excl))
17553 ... helper routines for defining the interface ...
17555 (swig-in-package ())
17557 (swig-defun ("fact")
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)))
17564 (swig-defun ("fact")
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)))
17571 (swig-dispatcher ("fact" :type :function :arities (1)))
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">
17584 % swig -allegrocl example.i
17587 <P> When building an interface to C++ code, include the <TT>-c++</TT>
17589 <DIV class="shell">
17591 % swig -allegrocl -c++ example.i
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
17613 <DIV class="code">example_wrap.i
17615 ... lots of SWIG internals ...
17617 EXPORT int ACL___fact__SWIG_0 (char *larg1) {
17618 int lresult = (int)0 ;
17619 char *arg1 = (char *) 0 ;
17624 result = (int)fact(arg1);
17634 EXPORT int ACL___fact__SWIG_1 (int larg1) {
17635 int lresult = (int)0 ;
17641 result = (int)fact(arg1);
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">
17657 (swig-in-package ())
17659 (swig-defmethod ("fact" "ACL___fact__SWIG_0" :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)))
17666 (swig-defmethod ("fact" "ACL___fact__SWIG_1" :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)))
17673 (swig-dispatcher ("fact" :type :function :arities (1)))
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
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">
17692 swig -allegrocl [ options ] filename
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.
17699 -cwrap - [default] Generate a .cxx file containing C wrapper function when
17700 wrapping C code. The interface generated is similar to what is
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.
17706 -isolate - With this command-line argument, all lisp helper functions are defined
17707 in a unique package named <TT>swig.<module-name></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.
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 "header.h"</TT> directive. This can be done using the
17721 SWIG <TT>%insert(section) %{ ...code... %}</TT> directive:</P>
17727 #include "header.h"
17730 %include "header.h"
17735 <P> Additional sections have been added for inserting into the generated
17736 lisp interface file</P>
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>
17742 <P> Note that the block <TT>%{ ... %}</TT> is effectively a shortcut for
17743 <TT>%insert("header") %{ ... %}</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">
17763 | Foreign Code | What we're generating an interface to.
17769 | Wrapper code | extern "C" wrappers calling C++
17770 |______________| functions and methods.
17772 . . . - - + - - . . .
17775 | FFI Layer | Low level lisp interface. ff:def-foreign-call,
17776 |______________| ff:def-foreign-variable
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______
17787 | Defuns | dispatch function
17788 |______________| to overloads based
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:
17808 %ffargs(strings_convert="nil",call_direct="t") foo;
17809 %ffargs(strings_convert="nil",release_heap=":never",optimize_for_space="t") bar;
17811 int foo(float f1, float f2);
17812 int foo(float f1, char c2);
17814 void bar(void *lisp_fn);
17820 <DIV class="targetlang">ffargs.cl:
17822 (swig-in-package ())
17824 (swig-defmethod ("foo" "ACL___foo__SWIG_0" :type :function :arity 2)
17825 ((PARM0_f1 cl:single-float :float )
17826 (PARM1_f2 cl:single-float :float ))
17827 (:returning (:int )
17829 :strings-convert nil)
17830 (let ((SWIG_arg0 PARM0_f1))
17831 (let ((SWIG_arg1 PARM1_f2))
17832 (swig-ff-call SWIG_arg0 SWIG_arg1))))
17834 (swig-defmethod ("foo" "ACL___foo__SWIG_1" :type :function :arity 2)
17835 ((PARM0_f1 cl:single-float :float )
17836 (PARM1_c2 cl:character :char character))
17837 (:returning (:int )
17839 :strings-convert nil)
17840 (let ((SWIG_arg0 PARM0_f1))
17841 (let ((SWIG_arg1 PARM1_c2))
17842 (swig-ff-call SWIG_arg0 SWIG_arg1))))
17844 (swig-dispatcher ("foo" :type :function :arities (2)))
17845 (swig-defun ("bar" "ACL___bar__SWIG_0" :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)))
17855 (swig-defun ("xxx" "ACL___xxx__SWIG_0" :type :function)
17857 (:returning ((* :char) )
17858 :strings-convert t)
17861 </DIV><DIV class="code">
17862 <PRE>%ffargs(strings_convert="t");</PRE>
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
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
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:
17923 #include "foo.h"
17926 %include "foo.h"
17931 int do_something(int n);
17936 <P>Generates the following code.</P>
17937 <DIV class="targetlang">foo.cl
17940 (:use :common-lisp :swig :ff :excl))
17944 (swig-defpackage ("car"))
17945 (swig-defpackage ("car" "tires"))
17949 (swig-in-package ("car" "tires"))
17950 (swig-defun ("do_something" "ACL_car_tires__do_something__SWIG_0" :type :function)
17952 (:returning (:int )
17953 :strings-convert t)
17954 (let ((SWIG_arg0 PARM0_n))
17955 (swig-ff-call SWIG_arg0)))
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
17980 <P> Here are examples of simple preprocessor constants when using
17984 #define A 1 => (swig-defconstant "A" 1)
17985 #define B 'c' => (swig-defconstant "B" #\c)
17986 #define C B => (swig-defconstant "C" #\c)
17987 #define D 1.0e2 => (swig-defconstant "D" 1.0d2)
17988 #define E 2222 => (swig-defconstant "E" 2222)
17989 #define F (unsigned int)2222 => no code generated
17990 #define G 1.02e2f => (swig-defconstant "G" 1.02f2)
17991 #define H foo => no code generated
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
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>
18007 #define I A + E => (swig-defconstant "I" (+ 1 2222))
18008 #define J 1|2 => (swig-defconstant "J" (logior 1 2))
18009 #define Y 1 + 2 * 3 + 4 => (swig-defconstant "Y" (* (+ 1 2) (+ 3 4)))
18010 #define Y1 (1 + 2) * (3 + 4) => (swig-defconstant "Y1" (* (+ 1 2) (+ 3 4)))
18011 #define Y2 1 * 2 + 3 * 4 => (swig-defconstant "Y2" (* 1 (+ 2 3) 4)) ;; WRONG
18012 #define Y3 (1 * 2) + (3 * 4) => (swig-defconstant "Y3" (* 1 (+ 2 3) 4)) ;; WRONG
18013 #define Z 1 + 2 - 3 + 4 * 5 => (swig-defconstant "Z" (* (+ 1 (- 2 3) 4) 5)) ;; WRONG
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
18028 int const global_var = 2;
18029 float glob_float = 2.0;
18033 <P> Generated code:</P>
18034 <DIV class="targetlang">vars.cl
18036 (swig-in-package ("nnn"))
18037 (swig-defun ("global_var" "ACL_nnn__global_var_get__SWIG_0" :type :getter)
18039 (:returning (:int )
18040 :strings-convert t)
18044 (swig-defun ("glob_float" "ACL_nnn__glob_float_set__SWIG_0" :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)))
18052 (swig-defun ("glob_float" "ACL_nnn__glob_float_get__SWIG_0" :type :getter)
18054 (:returning (:float )
18055 :strings-convert t)
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
18062 <DIV class="targetlang">
18064 user> (load "globalvar.dll")
18065 ; Foreign loading globalvar.dll.
18067 user> (load "globalvar.cl")
18068 ; Loading c:\mikel\src\swig\test\globalvar.cl
18071 globalvar> (globalvar.nnn::global_var)
18073 globalvar> (globalvar.nnn::glob_float)
18075 globalvar> (setf (globalvar.nnn::glob_float) 3.0)
18077 globalvar> (globalvar.nnn::glob_float)
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>
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
18097 <P>For example, the following header file<DIV class="code">enum.h:
18099 enum COL { RED, GREEN, BLUE };
18100 enum FOO { FOO1 = 10, FOO2, FOO3 };
18103 <P> In -nocwrap mode, generates</P>
18104 <DIV class="targetlang">enum.cl:
18106 (swig-def-foreign-type "COL" :int)
18107 (swig-defconstant "RED" 0)
18108 (swig-defconstant "GREEN" (+ #.(swig-insert-id "RED" () :type :constant) 1))
18109 (swig-defconstant "BLUE" (+ #.(swig-insert-id "GREEN" () :type :constant) 1))
18111 (swig-def-foreign-type "FOO" :int)
18112 (swig-defconstant "FOO1" 10)
18113 (swig-defconstant "FOO2" (+ #.(swig-insert-id "FOO1" () :type :constant) 1))
18114 (swig-defconstant "FOO3" (+ #.(swig-insert-id "FOO2" () :type :constant) 1))
18117 <P>And when generating a .cxx wrapper<DIV class="code">enum_wrap.cxx:
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;
18128 <DIV class="targetlang">enum.cl:
18130 (swig-def-foreign-type "COL" :int)
18131 (swig-defvar "RED" "ACL_ENUM___RED__SWIG_0" :type :constant)
18132 (swig-defvar "GREEN" "ACL_ENUM___GREEN__SWIG_0" :type :constant)
18133 (swig-defvar "BLUE" "ACL_ENUM___BLUE__SWIG_0" :type :constant)
18135 (swig-def-foreign-type "FOO" :int)
18136 (swig-defvar "FOO1" "ACL_ENUM___FOO1__SWIG_0" :type :constant)
18137 (swig-defvar "FOO2" "ACL_ENUM___FOO2__SWIG_0" :type :constant)
18138 (swig-defvar "FOO3" "ACL_ENUM___FOO3__SWIG_0" :type :constant)
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
18156 #define MAX_BUF_SIZE 1024
18159 int global_var1[13];
18160 float global_var2[MAX_BUF_SIZE];
18164 enum COLOR { RED = 10, GREEN = 20, BLUE, PURPLE = 50, CYAN };
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];
18171 int enum_var5[GREEN];
18172 int enum_var6[CYAN];
18174 COLOR enum_var7[CYAN][MAX_BUF_SIZE];
18179 <DIV class="targetlang">array.cl
18181 (in-package #.*swig-module-name*)
18183 (swig-defpackage ("FOO"))
18184 (swig-defpackage ("BAR"))
18186 (swig-in-package ())
18187 (swig-def-foreign-type "COLOR" :int)
18188 (swig-defvar "RED" "ACL_ENUM___RED__SWIG_0" :type :constant)
18189 (swig-defvar "GREEN" "ACL_ENUM___GREEN__SWIG_0" :type :constant)
18190 (swig-defvar "BLUE" "ACL_ENUM___BLUE__SWIG_0" :type :constant)
18191 (swig-defvar "PURPLE" "ACL_ENUM___PURPLE__SWIG_0" :type :constant)
18192 (swig-defvar "CYAN" "ACL_ENUM___CYAN__SWIG_0" :type :constant)
18194 (swig-in-package ())
18196 (swig-defconstant "MAX_BUF_SIZE" 1024)
18197 (swig-in-package ("FOO"))
18199 (swig-defun ("global_var1" "ACL_FOO__global_var1_get__SWIG_0" :type :getter)
18201 (:returning ((* :int) )
18202 :strings-convert t)
18203 (make-instance 'ff:foreign-pointer :foreign-address (swig-ff-call)))
18206 (swig-defun ("global_var2" "ACL_FOO__global_var2_set__SWIG_0" :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)))
18214 (swig-in-package ())
18215 (swig-in-package ("BAR"))
18216 (swig-defun ("global_var3" "ACL_BAR__global_var3_set__SWIG_0" :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)))
18224 (swig-defun ("global_var4" "ACL_BAR__global_var4_set__SWIG_0" :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)))
18232 (swig-defun ("global_var4" "ACL_BAR__global_var4_get__SWIG_0" :type :getter)
18234 (:returning ((* (:array :float 13)) )
18235 :strings-convert t)
18236 (make-instance 'ff:foreign-pointer :foreign-address (swig-ff-call)))
18239 (swig-defun ("global_var5" "ACL_BAR__global_var5_set__SWIG_0" :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)))
18247 (swig-defun ("enum_var5" "ACL_BAR__enum_var5_set__SWIG_0" :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)))
18255 (swig-defun ("enum_var6" "ACL_BAR__enum_var6_set__SWIG_0" :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)))
18263 (swig-defun ("enum_var7" "ACL_BAR__enum_var7_set__SWIG_0" :type :setter)
18264 ((enum_var7 (:array (:array #.(swig-insert-id "COLOR" ()) 1024) #|CYAN|#) ))
18265 (:returning (:void )
18266 :strings-convert t)
18267 (let ((SWIG_arg0 enum_var7))
18268 (swig-ff-call SWIG_arg0)))
18271 (swig-defun ("enum_var7" "ACL_BAR__enum_var7_get__SWIG_0" :type :getter)
18273 (:returning ((* (:array #.(swig-insert-id "COLOR" ()) 1024)) )
18274 :strings-convert t)
18275 (make-instance 'ff:foreign-pointer :foreign-address (swig-ff-call)))
18278 <H3><A name="Allegrocl_nn20"></A>17.3.6 Classes and Structs and Unions
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
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
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
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
18344 A *xxx(int i); /* sets A->x = A->y = i */
18345 Foo *yyy(int i); /* sets Foo->x = Foo->y = i */
18347 int zzz(A *inst = 0); /* return inst->x + inst->y */
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 <synonym>) <primary>)</TT>
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
18371 <DIV class="targetlang">
18373 CL-USER> (load "synonym.dll")
18374 ; Foreign loading synonym.dll.
18376 CL-USER> (load "synonym.cl")
18377 ; Loading c:\mikel\src\swig\test\synonym.cl
18380 synonym> (setf a (xxx 3))
18381 #<A nil #x3261a0 @ #x207299da>
18382 synonym> (setf foo (yyy 10))
18383 #<A nil #x3291d0 @ #x2072e982>
18384 synonym> (zzz a)
18386 synonym> (zzz foo)
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>
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>
18401 <H3><A name="Allegrocl_nn30"></A>17.3.9 Function overloading/Parameter
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
18413 <DIV class="code">overload.h:
18422 float xxx(int i, int x = 0); /* return i * x */
18423 float xxx(A *inst, int x); /* return x + A->x + A->y */
18426 <P>Creates the following three wrappers, for each of the possible
18427 argument combinations</P>
18428 <DIV class="code">overload_wrap.cxx
18430 EXPORT void ACL___delete_A__SWIG_0 (A *larg1) {
18431 A *arg1 = (A *) 0 ;
18443 EXPORT float ACL___xxx__SWIG_0 (int larg1, int larg2) {
18444 float lresult = (float)0 ;
18452 result = (float)xxx(arg1,arg2);
18462 EXPORT float ACL___xxx__SWIG_1 (int larg1) {
18463 float lresult = (float)0 ;
18469 result = (float)xxx(arg1);
18479 EXPORT float ACL___xxx__SWIG_2 (A *larg1, int larg2) {
18480 float lresult = (float)0 ;
18481 A *arg1 = (A *) 0 ;
18488 result = (float)xxx(arg1,arg2);
18498 <P> And the following foreign-function-call and method definitions on
18500 <DIV class="targetlang">overload.cl
18502 (swig-defmethod ("xxx" "ACL___xxx__SWIG_0" :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))))
18511 (swig-defmethod ("xxx" "ACL___xxx__SWIG_1" :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)))
18518 (swig-defmethod ("xxx" "ACL___xxx__SWIG_2" :type :function :arity 2)
18519 ((PARM0_inst #.(swig-insert-id "A" () :type :class) (* #.(swig-insert-id "A" ())) )
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))))
18527 (swig-dispatcher ("xxx" :type :function :arities (1 2)))
18530 <P>And their usage in a sample lisp session:</P>
18531 <DIV class="targetlang">
18533 overload> (setf a (new_A))
18534 #<A nil #x329268 @ #x206cf612>
18535 overload> (setf (A_x a) 10)
18537 overload> (setf (A_y a) 20)
18539 overload> (xxx 1)
18541 overload> (xxx 3 10)
18543 overload> (xxx a 1)
18545 overload> (xxx a 2)
18550 <H3><A name="Allegrocl_nn31"></A>17.3.10 Operator wrapping and Operator
18552 <P> Wrappers to defined C++ Operators are automatically renamed, using <TT>
18553 %rename</TT>, to the following defaults:</P>
18556 /* name conversion for overloaded operators. */
18558 %rename(__add__) *::operator+;
18559 %rename(__pos__) *::operator+();
18560 %rename(__pos__) *::operator+() const;
18562 %rename(__sub__) *::operator-;
18563 %rename(__neg__) *::operator-() const;
18564 %rename(__neg__) *::operator-();
18566 %rename(__mul__) *::operator*;
18567 %rename(__deref__) *::operator*();
18568 %rename(__deref__) *::operator*() const;
18570 %rename(__div__) *::operator/;
18571 %rename(__mod__) *::operator%;
18572 %rename(__logxor__) *::operator^;
18573 %rename(__logand__) *::operator&;
18574 %rename(__logior__) *::operator|;
18575 %rename(__lognot__) *::operator~();
18576 %rename(__lognot__) *::operator~() const;
18578 %rename(__not__) *::operator!();
18579 %rename(__not__) *::operator!() const;
18581 %rename(__assign__) *::operator=;
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&=;
18590 %rename(__logior_assign__) *::operator|=;
18592 %rename(__lshift__) *::operator<<;
18593 %rename(__lshift_assign__) *::operator<<=;
18594 %rename(__rshift__) *::operator>>;
18595 %rename(__rshift_assign__) *::operator>>=;
18597 %rename(__eq__) *::operator==;
18598 %rename(__ne__) *::operator!=;
18599 %rename(__lt__) *::operator<;
18600 %rename(__gt__) *::operator>;
18601 %rename(__lte__) *::operator<=;
18602 %rename(__gte__) *::operator>=;
18604 %rename(__and__) *::operator&&;
18605 %rename(__or__) *::operator||;
18607 %rename(__preincr__) *::operator++();
18608 %rename(__postincr__) *::operator++(int);
18609 %rename(__predecr__) *::operator--();
18610 %rename(__postdecr__) *::operator--(int);
18612 %rename(__comma__) *::operator,();
18613 %rename(__comma__) *::operator,() const;
18615 %rename(__member_ref__) *::operator->;
18616 %rename(__member_func_ref__) *::operator->*;
18618 %rename(__funcall__) *::operator();
18619 %rename(__aref__) *::operator[];
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><class-or-namespace>_</TT> has been added. Users may modify
18625 these default names by adding <TT>%rename</TT> directives in their own
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
18637 bool operator==(B const& other) const;
18642 <DIV class="code">opoverload.i
18647 #include <fstream>
18648 #include "opoverload.h"
18652 bool B___eq__(B const *inst, int const x)
18654 // insert the function definition into the wrapper code before
18655 // the wrapper for it.
18656 // ... do stuff ...
18660 %include "opoverload.h"
18664 bool __eq__(int const x) const;
18668 <P> Either operator can be called via a single call to the dispatch
18670 <DIV class="targetlang">
18672 opoverload> (B___eq__ x1 x2)
18674 opoverload> (B___eq__ x1 3)
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
18697 <H3><A name="Allegrocl_nn34"></A>17.3.13 Pass by value, pass by
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++
18712 <P> Every C++ wrapper generated by SWIG takes the following form:</P>
18713 <DIV class="diagram">
18715 return-val wrapper-name(parm0, parm1, ..., parmN)
18717 return-val lresult; /* return value from wrapper */
18718 <local-declaration>
18719 ... results; /* return value from function call */
18721 <binding locals to parameters>
18724 result = function-name(local0, local1, ..., localN);
18726 <convert and bind result to lresult>
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 <binding locals to parameters></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
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>
18750 %typemap(in) bool "$1 = (bool)$input;";
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 & "$1 = $input;";
18758 %typemap(in) SWIGTYPE "$1 = *$input;";
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 <convert and bind result to lresult> section
18765 of the above code diagram. It's default mapping is as follows:</P>
18768 %typemap(out) bool "$result = (int)$1;";
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 & "$result = $1;";
18776 %typemap(out) SWIGTYPE "$result = new $1_type($1);";
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>
18786 %typemap(ctype) bool "int";
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 & "$1_ltype";
18794 %typemap(ctype) SWIGTYPE "$&1_type";
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
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>
18823 <LI><TT>$in</TT> - expands to the name of the parameter being applied to
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
18839 %typemap(lin) SWIGTYPE "(cl:let (($out $in))\n $body)";
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>
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>
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 "$body";
18865 %typemap(lout) SWIGTYPE[ANY], SWIGTYPE *,
18866 SWIGTYPE & "(cl:make-instance '$lclass :foreign-address $body)";
18867 %typemap(lout) SWIGTYPE "(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
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>
18885 %typemap(ffitype) bool ":unsigned-char";
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>
18893 %typemap(ffitype) bool ":int";
18894 %typemap(ffitype) char ":char";
18895 %typemap(ffitype) unsigned char ":unsigned-char";
18896 %typemap(ffitype) signed char ":char";
18897 %typemap(ffitype) short, signed short ":short";
18898 %typemap(ffitype) unsigned short ":unsigned-short";
18899 %typemap(ffitype) int, signed int ":int";
18900 %typemap(ffitype) unsigned int ":unsigned-int";
18901 %typemap(ffitype) long, signed long ":long";
18902 %typemap(ffitype) unsigned long ":unsigned-long";
18903 %typemap(ffitype) float ":float";
18904 %typemap(ffitype) double ":double";
18905 %typemap(ffitype) char * "(* :char)";
18906 %typemap(ffitype) void * "(* :void)";
18907 %typemap(ffitype) void ":void";
18908 %typemap(ffitype) enum SWIGTYPE ":int";
18909 %typemap(ffitype) SWIGTYPE & "(* :void)";
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>
18920 %typemap(lisptype) bool "cl:boolean";
18921 %typemap(lisptype) char "cl:character";
18922 %typemap(lisptype) unsigned char "cl:integer";
18923 %typemap(lisptype) signed char "cl:integer";
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>
18932 %typemap(lispclass) bool "t";
18933 %typemap(lispclass) char "cl:character";
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 "cl:integer";
18939 %typemap(lispclass) float "cl:single-float";
18940 %typemap(lispclass) double "cl:double-float";
18941 %typemap(lispclass) char * "cl:string";
18944 <H3><A name="Allegrocl_nn46"></A>17.4.3 Modifying SWIG behavior using
18946 <P> The following example shows how we made use of the above typemaps to
18947 add support for the wchar_t type.</P>
18950 %typecheck(SWIG_TYPECHECK_UNICHAR) wchar_t { $1 = 1; };
18952 %typemap(in) wchar_t "$1 = $input;";
18953 %typemap(lin) wchar_t "(cl:let (($out (cl:char-code $in)))\n $body)";
18954 %typemap(lin) wchar_t* "(excl:with-native-string
18956 :external-format #+little-endian :fat-le
18957 #-little-endian :fat)\n
18960 %typemap(out) wchar_t "$result = $1;";
18961 %typemap(lout) wchar_t "(cl:code-char $body)";
18962 %typemap(lout) wchar_t* "(excl:native-to-string $body
18963 :external-format #+little-endian :fat-le
18964 #-little-endian :fat)";
18966 %typemap(ffitype) wchar_t ":unsigned-short";
18967 %typemap(lisptype) wchar_t "";
18968 %typemap(ctype) wchar_t "wchar_t";
18969 %typemap(lispclass) wchar_t "cl:character";
18970 %typemap(lispclass) wchar_t* "cl:string";
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
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
18988 <H3><A name="Allegrocl_nn49"></A>17.5.2 Existing identifier-converter
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
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">
19009 (defun identifier-convert-fn (id &key type class arity) ...body...)
19010 result ==> symbol or (setf symbol)
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>
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)
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>
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>
19051 % swig -allegrocl -c++ -module mymodule -identifier-converter my-identifier-converter
19054 <H1><A name="CSharp"></A>18 SWIG and C#</H1>
19057 <DIV class="sectiontoc">
19059 <LI><A href="#csharp_introduction">Introduction</A></LI>
19060 <LI><A href="#csharp_differences_java">Differences to the Java module</A>
19062 <LI><A href="#CSharp_arrays">C# Arrays</A>
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>
19070 <LI><A href="#csharp_exceptions">C# Exceptions</A>
19072 <LI><A href="#csharp_exception_example_check_typemap">C# exception
19073 example using "check" 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>
19082 <LI><A href="#csharp_directors">C# Directors</A>
19084 <LI><A href="#csharp_directors_example">Directors example</A></LI>
19085 <LI><A href="#csharp_directors_implementation">Directors implementation</A>
19087 <LI><A href="#csharp_director_caveats">Director caveats</A></LI>
19090 <LI><A href="#csharp_typemap_examples">C# Typemap examples</A>
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>
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 "Interop Marshaling". 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
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
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 <name></TT> commandline option will generate all
19143 code into the namespace specified by <TT><name></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">
19148 namespace com.bloggs.widget {
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 <name></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
19167 <LI> The default enum wrapping approach is proper C# enums, not typesafe
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
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>
19183 <P>Typemap equivalent names:</P>
19188 jstype -> cstype
19190 javaout -> csout
19191 javadirectorin -> csdirectorin
19192 javadirectorout -> csdirectorout
19193 javainterfaces -> csinterfaces and csinterfaces_derived
19194 javabase -> csbase
19195 javaclassmodifiers -> csclassmodifiers
19196 javacode -> cscode
19197 javaimports -> csimports
19198 javabody -> csbody
19199 javafinalize -> csfinalize
19200 javadestruct -> csdestruct
19201 javadestruct_derived -> csdestruct_derived
19205 <P>Additional typemaps:</P>
19208 csvarin C# code property set typemap
19209 csvarout C# code property get typemap
19210 csattributes C# attributes for attaching to proxy classes/enums
19214 <P>Feature equivalent names:</P>
19217 %javaconst -> %csconst
19218 %javaconstvalue -> %csconstvalue
19219 %javamethodmodifiers -> %csmethodmodifiers
19223 <P>Pragma equivalent names:</P>
19226 %pragma(java) -> %pragma(csharp)
19227 jniclassbase -> imclassbase
19228 jniclassclassmodifiers -> imclassclassmodifiers
19229 jniclasscode -> imclasscode
19230 jniclassimports -> imclassimports
19231 jniclassinterfaces -> imclassinterfaces
19235 <P>Special variable equivalent names:</P>
19238 $javaclassname -> $csclassname
19239 $&javaclassname -> $&csclassname
19240 $*javaclassname -> $*csclassname
19241 $javainput -> $csinput
19242 $jnicall -> $imcall
19246 <P> Unlike the "javain" typemap, the "csin" typemap does not support the
19247 'pgcpp' attribute as the C# module does not have a premature garbage
19248 collection prevention parameter. The "csin" 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 "csin" applicable attributes.</P>
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>
19272 %typemap(imtype, out="IntPtr") char * "string"
19273 char * function(char *);
19276 <P> The output type is thus IntPtr and the input type is string. The
19277 resulting intermediary C# code is:</P>
19280 public static extern IntPtr function(string jarg1);
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>
19295 inattributes="[MarshalAs(UnmanagedType.LPStr)]",
19296 outattributes="[return: MarshalAs(UnmanagedType.LPStr)]") const char * "String"
19298 const char * GetMsg() {}
19299 void SetMsg(const char *msg) {}
19302 <P> The intermediary class will then have the marshalling as specified
19303 by everything in the 'imtype' typemap:</P>
19306 class examplePINVOKE {
19308 [DllImport("example", EntryPoint="CSharp_GetMsg")]
19309 [return: MarshalAs(UnmanagedType.LPStr)]
19310 public static extern String GetMsg();
19312 [DllImport("example", EntryPoint="CSharp_SetMsg")]
19313 public static extern void SetMsg([MarshalAs(UnmanagedType.LPStr)]String jarg1);
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>
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>
19335 %typemap(csattributes) AClass "[ThreadSafe]"
19336 %csattributes AClass::AClass(double d) "[ThreadSafe(false)]"
19337 %csattributes AClass::AMethod() "[ThreadSafe(true)]"
19342 AClass(double a) {}
19348 <P> will generate a C# proxy class:</P>
19352 public class AClass : IDisposable {
19354 [ThreadSafe(false)]
19355 public AClass(double a) ...
19358 public void AMethod() ...
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>
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>
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>
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>
19390 %module (imclassname="name") modulename
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>
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>
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
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
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
19445 SWIGTYPE_p_double a = example.new_doubleArray(10); // Create an array
19446 for (int i=0; i<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
19452 <P> and for the <TT>%array_class</TT> example, the equivalent usage
19456 doubleArray c = new doubleArray(10); // Create double[10]
19457 for (int i=0; i<10; i++)
19458 c.setitem(i, 2*i); // Assign values
19459 example.print_array(c.cast()); // Pass to C
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>
19486 void myArrayCopy(int *sourceArray, int *targetArray, int nitems);
19489 <P> We can now instruct SWIG to use the default marshalling typemaps by</P>
19492 %include "arrays_csharp.i"
19494 %apply int INPUT[] {int *sourceArray}
19495 %apply int OUTPUT[] {int *targetArray}
19498 <P> As a result, we get the following method in the module class:</P>
19501 public static void myArrayCopy(int[] sourceArray, int[] targetArray, int nitems) {
19502 examplePINVOKE.myArrayCopy(sourceArray, targetArray, nitems);
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>
19512 [DllImport("example", EntryPoint="CSharp_myArrayCopy")]
19513 public static extern void myArrayCopy([In, MarshalAs(UnmanagedType.LPArray)]int[] jarg1,
19514 [Out, MarshalAs(UnmanagedType.LPArray)]int[] jarg2, int jarg3);
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>
19522 void myArraySwap(int *array1, int *array2, int nitems);
19525 <P> Now, we can instruct SWIG to wrap this by</P>
19528 %include "arrays_csharp.i"
19530 %apply int INOUT[] {int *array1}
19531 %apply int INOUT[] {int *array2}
19534 <P> This results in the module class method</P>
19537 public static void myArraySwap(int[] array1, int[] array2, int nitems) {
19538 examplePINVOKE.myArraySwap(array1, array2, nitems);
19542 <P> and intermediate class method</P>
19545 [DllImport("example", EntryPoint="CSharp_myArraySwap")]
19546 public static extern void myArraySwap([In, Out, MarshalAs(UnmanagedType.LPArray)]int[] jarg1,
19547 [In, Out, MarshalAs(UnmanagedType.LPArray)]int[] jarg2, int jarg3);
19550 <H3><A name="CSharp_arrays_pinning"></A>18.3.3 Managed arrays using
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>
19569 void myArrayCopy(int *sourceArray, int *targetArray, int nitems);
19572 <P> We now need to declare the module class method unsafe, as we are
19573 using pointers:</P>
19576 %csmethodmodifiers myArrayCopy "public unsafe";
19579 <P> Apply the appropriate typemaps to the array parameters:</P>
19582 %include "arrays_csharp.i"
19584 %apply int FIXED[] {int *sourceArray}
19585 %apply int FIXED[] {int *targetArray}
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>
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 ) {
19597 examplePINVOKE.myArrayCopy((IntPtr)swig_ptrTo_sourceArray, (IntPtr)swig_ptrTo_targetArray, nitems);
19604 <P> On the method signature level the only difference to the version
19605 using P/Invoke default marshalling is the "unsafe" 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>
19612 [DllImport("example", EntryPoint="CSharp_myArrayCopy")]
19613 public static extern void myArrayCopy(IntPtr jarg1, IntPtr jarg2, int jarg3);
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>
19666 static void SWIG_CSharpSetPendingException(SWIG_CSharpExceptionCodes code,
19669 static void SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpExceptionArgumentCodes code,
19671 const char *param_name);
19674 <P> The first parameter defines which .NET exceptions can be thrown:</P>
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;
19692 SWIG_CSharpArgumentException,
19693 SWIG_CSharpArgumentNullException,
19694 SWIG_CSharpArgumentOutOfRangeException,
19695 } SWIG_CSharpExceptionArgumentCodes;
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 "check" typemap</H3>
19708 <P> Lets say we have the following simple C++ method:</P>
19711 void positivesonly(int number);
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 "check" 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>
19724 %typemap(check, canthrow=1) int number %{
19726 SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentOutOfRangeException,
19727 "only positive numbers accepted", "number");
19730 // SWIGEXCODE is a macro used by many other csout typemaps
19732 "\n if ($modulePINVOKE.SWIGPendingException.Pending)"
19733 "\n throw $modulePINVOKE.SWIGPendingException.Retrieve();"
19735 %typemap(csout, excode=SWIGEXCODE) void {
19742 void positivesonly(int number) {
19748 <P> When the following C# code is executed:</P>
19751 public class runme {
19752 static void Main() {
19753 example.positivesonly(-1);
19758 <P> The exception is thrown:</P>
19761 Unhandled Exception: System.ArgumentOutOfRangeException: only positive numbers accepted
19762 Parameter name: number
19763 in <0x00034> example:positivesonly (int)
19764 in <0x0000c> runme:Main ()
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>
19771 SWIGEXPORT void SWIGSTDCALL CSharp_positivesonly(int jarg1) {
19777 SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentOutOfRangeException,
19778 "only positive numbers accepted", "number");
19782 positivesonly(arg1);
19787 <P> This largely comes from the "check" typemap. The managed code in the
19788 module class is:</P>
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();
19801 <P> This comes largely from the "csout" typemap.</P>
19802 <P> The "csout" typemap is the same as the default void "csout" 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 "csin" 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 "check" typemap did not exist, then the following module
19817 class would instead be generated:</P>
19820 public class example {
19821 public static void positivesonly(int number) {
19822 examplePINVOKE.positivesonly(number);
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 "check" typemap, such as:</P>
19833 %typemap(check) int number %{
19835 SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentOutOfRangeException,
19836 "only positive numbers accepted", "number");
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>
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.
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>
19862 %exception negativesonly(int value) %{
19865 } catch (std::out_of_range e) {
19866 SWIG_CSharpSetPendingException(SWIG_CSharpApplicationException, e.what());
19871 #include <stdexcept>
19872 void negativesonly(int value) {
19874 throw std::out_of_range("number should be negative");
19879 <P> The generated unmanaged code this time catches the C++ exception and
19880 converts it into a C# <TT>ApplicationException</TT>.</P>
19883 SWIGEXPORT void SWIGSTDCALL CSharp_negativesonly(int jarg1) {
19889 negativesonly(arg1);
19891 } catch (std::out_of_range e) {
19892 SWIG_CSharpSetPendingException(SWIG_CSharpApplicationException, e.what());
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>
19904 public static void negativesonly(int value) {
19905 examplePINVOKE.negativesonly(value);
19906 if (examplePINVOKE.SWIGPendingException.Pending)
19907 throw examplePINVOKE.SWIGPendingException.Retrieve();
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 "throws" typemaps. The following example has a user supplied "throws"
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>
19922 %typemap(throws, canthrow=1) std::out_of_range {
19923 SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentException, $1.what(), NULL);
19928 #include <stdexcept>
19929 void evensonly(int input) throw (std::out_of_range) {
19931 throw std::out_of_range("number is not even");
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>
19941 SWIGEXPORT void SWIGSTDCALL CSharp_evensonly(int jarg1) {
19948 catch(std::out_of_range &_e) {
19950 SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentException, (&_e)->what(), NULL);
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>
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;
19985 extern "C" SWIGEXPORT
19986 void SWIGSTDCALL CustomExceptionRegisterCallback(CSharpExceptionCallback_t customCallback) {
19987 customExceptionCallback = customCallback;
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);
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);
20004 [DllImport("$dllimport", EntryPoint="CustomExceptionRegisterCallback")]
20005 public static extern
20006 void CustomExceptionRegisterCallback(CustomExceptionDelegate customCallback);
20008 static void SetPendingCustomException(string message) {
20009 SWIGPendingException.Set(new CustomApplicationException(message));
20012 static CustomExceptionHelper() {
20013 CustomExceptionRegisterCallback(customDelegate);
20016 static CustomExceptionHelper exceptionHelper = new CustomExceptionHelper();
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>
20051 // Custom C# Exception
20052 class CustomApplicationException : System.ApplicationException {
20053 public CustomApplicationException(string message)
20059 <P> and the SWIG interface code:</P>
20062 %typemap(throws, canthrow=1) std::out_of_range {
20063 SWIG_CSharpSetPendingExceptionCustom($1.what());
20068 void oddsonly(int input) throw (std::out_of_range) {
20070 throw std::out_of_range("number is not odd");
20075 <P> The "throws" typemap now simply calls our new <TT>
20076 SWIG_CSharpSetPendingExceptionCustom()</TT> function so that the
20077 exception can be caught, as such:</P>
20081 example.oddsonly(2);
20082 } catch (CustomApplicationException e) {
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
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>
20110 virtual unsigned int UIntMethod(unsigned int x) {
20111 std::cout << "Base - UIntMethod(" << x << ")" << std::endl;
20114 virtual void BaseBoolMethod(const Base &b, bool flag) {}
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->UIntMethod(x); }
20127 void delBase() { delete m_base; m_base = 0; }
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>
20136 /* File : example.i */
20137 %module(directors="1") example
20139 #include "example.h"
20142 %feature("director") Base;
20144 %include "example.h"
20147 <P> The following is a C# class inheriting from <TT>Base</TT>:</P>
20150 public class CSharpDerived : Base
20152 public override uint UIntMethod(uint x)
20154 Console.WriteLine("CSharpDerived - UIntMethod({0})", x);
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">
20168 Caller myCaller = new Caller();
20170 // Test pure C++ class
20171 using (Base myBase = new Base())
20173 makeCalls(myCaller, myBase);
20176 // Test director / C# derived class
20177 using (Base myBase = new CSharpDerived())
20179 makeCalls(myCaller, myBase);
20183 static void makeCalls(Caller myCaller, Base myBase)
20185 myCaller.set(myBase);
20186 myCaller.UIntMethodCall(123);
20192 <P> If the above is run, the output is then:</P>
20193 <DIV class="shell">
20195 Base - UIntMethod(123)
20196 CSharpDerived - UIntMethod(123)
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>
20212 using System.Runtime.InteropServices;
20214 public class Base : IDisposable {
20215 private HandleRef swigCPtr;
20216 protected bool swigCMemOwn;
20218 internal Base(IntPtr cPtr, bool cMemoryOwn) {
20219 swigCMemOwn = cMemoryOwn;
20220 swigCPtr = new HandleRef(this, cPtr);
20223 internal static HandleRef getCPtr(Base obj) {
20224 return (obj == null) ? new HandleRef(null, IntPtr.Zero) : obj.swigCPtr;
20231 public virtual void Dispose() {
20233 if(swigCPtr.Handle != IntPtr.Zero && swigCMemOwn) {
20234 swigCMemOwn = false;
20235 examplePINVOKE.delete_Base(swigCPtr);
20237 swigCPtr = new HandleRef(null, IntPtr.Zero);
20238 GC.SuppressFinalize(this);
20242 public virtual uint UIntMethod(uint x) {
20243 uint ret = examplePINVOKE.Base_UIntMethod(swigCPtr, x);
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();
20253 public Base() : this(examplePINVOKE.new_Base(), true) {
20254 SwigDirectorConnect();
20257 private void SwigDirectorConnect() {
20258 if (SwigDerivedClassHasMethod("UIntMethod", swigMethodTypes0))
20259 swigDelegate0 = new SwigDelegateBase_0(SwigDirectorUIntMethod);
20260 if (SwigDerivedClassHasMethod("BaseBoolMethod", swigMethodTypes1))
20261 swigDelegate1 = new SwigDelegateBase_1(SwigDirectorBaseBoolMethod);
20262 examplePINVOKE.Base_director_connect(swigCPtr, swigDelegate0, swigDelegate1);
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;
20271 private uint SwigDirectorUIntMethod(uint x) {
20272 return UIntMethod(x);
20275 private void SwigDirectorBaseBoolMethod(IntPtr b, bool flag) {
20276 BaseBoolMethod(new Base(b, false), flag);
20279 internal delegate uint SwigDelegateBase_0(uint x);
20280 internal delegate void SwigDelegateBase_1(IntPtr b, bool flag);
20282 private SwigDelegateBase_0 swigDelegate0;
20283 private SwigDelegateBase_1 swigDelegate1;
20285 private static Type[] swigMethodTypes0 = new Type[] { typeof(uint) };
20286 private static Type[] swigMethodTypes1 = new Type[] { typeof(Base), typeof(bool) };
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>
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<SwigDirector_Base *>(obj);
20323 director->swig_connect_director(callback0, callback1);
20327 class SwigDirector_Base : public Base, public Swig::Director {
20329 SwigDirector_Base();
20330 virtual unsigned int UIntMethod(unsigned int x);
20331 virtual ~SwigDirector_Base();
20332 virtual void BaseBoolMethod(Base const &b, bool flag);
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);
20340 SWIG_Callback0_t swig_callbackUIntMethod;
20341 SWIG_Callback1_t swig_callbackBaseBoolMethod;
20342 void swig_init_callbacks();
20345 void SwigDirector_Base::swig_connect_director(SWIG_Callback0_t callbackUIntMethod,
20346 SWIG_Callback1_t callbackBaseBoolMethod) {
20347 swig_callbackUIntMethod = callbackUIntMethod;
20348 swig_callbackBaseBoolMethod = callbackBaseBoolMethod;
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>
20364 void SwigDirector_Base::BaseBoolMethod(Base const &b, bool flag) {
20366 unsigned int jflag ;
20368 if (!swig_callbackBaseBoolMethod) {
20369 Base::BaseBoolMethod(b,flag);
20372 jb = (Base *) &b;
20374 swig_callbackBaseBoolMethod(jb, jflag);
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>
20389 virtual ~Defaults();
20390 virtual void DefaultMethod(int a=-100);
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>
20399 public class CSharpDefaults : Defaults
20401 public override void DefaultMethod()
20403 DefaultMethod(-100); // note C++ default value used
20405 public override void DefaultMethod(int x)
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
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 "<TT>csharp.swg</TT>" and "<TT>typemaps.i</TT>
20427 " 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>
20439 Wheel(int sz) : size(sz) {}
20445 Bike(int val) : wheel(val) {}
20446 Wheel& getWheel() { return wheel; }
20450 <P> and the following usage from C# after running the code through SWIG:</P>
20453 Wheel wheel = new Bike(10).getWheel();
20454 Console.WriteLine("wheel size: " + wheel.size);
20455 // Simulate a garbage collection
20456 System.GC.Collect();
20457 System.GC.WaitForPendingFinalizers();
20458 Console.WriteLine("wheel size: " + wheel.size);
20461 <P> Don't be surprised that if the resulting output gives strange
20462 results such as...</P>
20463 <DIV class="shell">
20466 wheel size: 135019664
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>
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;
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& 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);
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>
20506 public class Wheel : IDisposable {
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;
20515 public class Bike : IDisposable {
20517 public Wheel getWheel() {
20518 IntPtr cPtr = examplePINVOKE.Bike_getWheel(swigCPtr);
20520 if (cPtr != IntPtr.Zero) {
20521 ret = new Wheel(cPtr, false);
20522 ret.addReference(this);
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>
20542 Element(int val) : value(val) {}
20547 Container() : element(0) {}
20548 void setElement(Element* e) { element = e; }
20549 Element* getElement() { return element; }
20553 <P> and usage from C++</P>
20556 Container container;
20557 Element element(20);
20558 container.setElement(&element);
20559 cout << "element.value: " << container.getElement()->value << endl;
20562 <P> and more or less equivalent usage from C#</P>
20565 Container container = new Container();
20566 Element element = new Element(20);
20567 container.setElement(element);
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>
20575 Container container = new Container();
20576 Element element = new Element(20);
20577 container.setElement(element);
20578 Console.WriteLine("element.value: " + container.getElement().value);
20579 // Simulate a garbage collection
20580 System.GC.Collect();
20581 System.GC.WaitForPendingFinalizers();
20582 Console.WriteLine("element.value: " + container.getElement().value);
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>
20592 public class Container : IDisposable {
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);
20604 public void setElement(Element e) {
20605 examplePINVOKE.Container_setElement(swigCPtr, getCPtrAndAddReference(e));
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>
20616 %typemap(csin) Element *e "getCPtrAndAddReference($csinput)"
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);
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 "javain" 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 "csin"
20636 typemap (the C# equivalent to the "javain" 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>
20646 CDate(int year, int month, int day);
20653 static int doSomething(const CDate &dateIn, CDate &dateOut);
20654 Action(const CDate &date, CDate &dateOut);
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>
20664 public class Action : IDisposable {
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();
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();
20683 <P> The <TT>CDate &</TT> and <TT>const CDate &</TT> C# code is generated
20684 from the following two default typemaps:</P>
20687 %typemap(cstype) SWIGTYPE & "$csclassname"
20688 %typemap(csin) SWIGTYPE & "$csclassname.getCPtr($csinput)"
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>
20697 System.DateTime dateIn = new System.DateTime(2011, 4, 13);
20698 System.DateTime dateOut = new System.DateTime();
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);
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>
20713 %typemap(cstype) const CDate& "System.DateTime"
20715 pre=" CDate temp$csinput = new CDate($csinput.Year, $csinput.Month, $csinput.Day);"
20716 ) const CDate &
20717 "$csclassname.getCPtr(temp$csinput)"
20719 %typemap(cstype) CDate& "out System.DateTime"
20721 pre=" CDate temp$csinput = new CDate();",
20722 post=" $csinput = new System.DateTime(temp$csinput.getYear(),"
20723 " temp$csinput.getMonth(), temp$csinput.getDay(), 0, 0, 0);",
20724 cshin="out $csinput"
20726 "$csclassname.getCPtr(temp$csinput)"
20730 <P> The resulting generated proxy code in the <TT>Action</TT> class
20734 public class Action : IDisposable {
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();
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();
20747 dateOut = new System.DateTime(tempdateOut.getYear(),
20748 tempdateOut.getMonth(), tempdateOut.getDay(), 0, 0, 0);
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();
20756 return examplePINVOKE.new_Action(CDate.getCPtr(tempdateIn), CDate.getCPtr(tempdateOut));
20758 dateOut = new System.DateTime(tempdateOut.getYear(),
20759 tempdateOut.getMonth(), tempdateOut.getDay(), 0, 0, 0);
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();
20771 <P> A few things to note:</P>
20773 <LI> The "cstype" typemap has changed the parameter type to <TT>
20774 System.DateTime</TT> instead of the default generated <TT>CDate</TT>
20776 <LI> The non-const <TT>CDate &</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
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 "csout" typemap).</LI>
20790 <LI> The temporary variables in the "csin" typemaps are called <TT>
20791 temp$csin</TT>, where "$csin" is replaced with the parameter name.
20792 "$csin" is used to mangle the variable name so that more than one <TT>
20793 CDate &</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 "csin" 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>
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
20809 void addYears(CDate *pDate, int years) {
20810 *pDate = CDate(pDate->getYear() + years, pDate->getMonth(), pDate->getDay());
20814 <P> If usage of <TT>CDate *</TT> commonly follows this input/output
20815 pattern, usage from C# like the following</P>
20818 System.DateTime christmasEve = new System.DateTime(2000, 12, 24);
20819 example.addYears(ref christmasEve, 10); // christmasEve now contains 2010-12-24
20822 <P> will be possible with the following <TT>CDate *</TT> typemaps</P>
20825 %typemap(cstype, out="System.DateTime") CDate * "ref System.DateTime"
20828 pre=" CDate temp$csinput = new CDate($csinput.Year, $csinput.Month, $csinput.Day);",
20829 post=" $csinput = new System.DateTime(temp$csinput.getYear(),"
20830 " temp$csinput.getMonth(), temp$csinput.getDay(), 0, 0, 0);",
20831 cshin="ref $csinput"
20833 "$csclassname.getCPtr(temp$csinput)"
20836 <P> Globals are wrapped by the module class and for a module called
20837 example, the typemaps result in the following code:</P>
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);
20844 examplePINVOKE.addYears(CDate.getCPtr(temppDate), years);
20846 pDate = new System.DateTime(temppDate.getYear(), temppDate.getMonth(), temppDate.getDay(), 0, 0, 0);
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>
20861 pre=" using (CDate temp$csinput = new CDate($csinput.Year, $csinput.Month, $csinput.Day)) {",
20862 post=" $csinput = new System.DateTime(temp$csinput.getYear(),"
20863 " temp$csinput.getMonth(), temp$csinput.getDay(), 0, 0, 0);",
20864 terminator=" } // terminate temp$csinput using block",
20865 cshin="ref $csinput"
20867 "$csclassname.getCPtr(temp$csinput)"
20869 void subtractYears(CDate *pDate, int years) {
20870 *pDate = CDate(pDate->getYear() - years, pDate->getMonth(), pDate->getDay());
20874 <P> The resulting generated code shows the termination of the <TT>using</TT>
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)) {
20882 examplePINVOKE.subtractYears(CDate.getCPtr(temppDate), years);
20884 pDate = new System.DateTime(temppDate.getYear(), temppDate.getMonth(), temppDate.getDay(), 0, 0, 0);
20886 } // terminate temppDate using block
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>
20901 CDate ImportantDate = CDate(1999, 12, 31);
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
20909 example.ImportantDate = new System.DateTime(2000, 11, 22);
20910 System.DateTime importantDate = example.ImportantDate;
20911 Console.WriteLine("Important date: " + importantDate);
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">
20921 %typemap(cstype, out="System.DateTime") CDate * "ref System.DateTime"
20924 pre=" CDate temp$csinput = new CDate($csinput.Year, $csinput.Month, $csinput.Day);",
20925 post=" $csinput = new System.DateTime(temp$csinput.getYear(),"
20926 " temp$csinput.getMonth(), temp$csinput.getDay(), 0, 0, 0);",
20927 cshin="ref $csinput"
20929 "$csclassname.getCPtr(temp$csinput)"
20931 %typemap(csvarin, excode=SWIGEXCODE2) CDate * %{
20932 /* csvarin typemap code */
20934 CDate temp$csinput = new CDate($csinput.Year, $csinput.Month, $csinput.Day);
20938 %typemap(csvarout, excode=SWIGEXCODE2) CDate * %{
20939 /* csvarout typemap code */
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(),
20948 <P> For a module called example, the typemaps result in the following
20952 public class example {
20953 public static System.DateTime ImportantDate {
20954 /* csvarin typemap code */
20956 CDate tempvalue = new CDate(value.Year, value.Month, value.Day);
20957 examplePINVOKE.ImportantDate_set(CDate.getCPtr(tempvalue));
20959 /* csvarout typemap code */
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(),
20971 <P> Some points to note:</P>
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>
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>
21009 int Part1() { return 1; }
21013 <P> The default C# proxy class generated is:</P>
21016 public class ExtendMe : IDisposable {
21018 public int Part1() {
21024 <P> The default csclassmodifiers typemap shipped with SWIG is</P>
21027 %typemap(csclassmodifiers) SWIGTYPE "public class"
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>
21035 %typemap(csclassmodifiers) ExtendMe "public partial class"
21038 <P> The C# proxy class becomes a partial class:</P>
21041 public partial class ExtendMe : IDisposable {
21043 public int Part1() {
21049 <P> You can then of course declare another part of the partial class
21050 elsewhere, for example:</P>
21053 public partial class ExtendMe : IDisposable {
21054 public int Part2() {
21060 <P> and compile the following code:</P>
21063 ExtendMe em = new ExtendMe();
21064 Console.WriteLine("part1: {0}", em.Part1());
21065 Console.WriteLine("part2: {0}", em.Part2());
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>
21083 %typemap(cscode) ExtendMe %{
21084 public int Part3() {
21091 <P> The generated C# proxy class will instead be:</P>
21094 public class ExtendMe : IDisposable {
21096 public int Part3() {
21099 public int Part1() {
21106 <!-- Hand-written HTML -->
21107 <H1><A name="Chicken"></A>19 SWIG and Chicken</H1>
21110 <DIV class="sectiontoc">
21112 <LI><A href="#Chicken_nn2">Preliminaries</A>
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>
21118 <LI><A href="#Chicken_nn5">Code Generation</A>
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>
21127 <LI><A href="#Chicken_nn11">TinyCLOS</A></LI>
21128 <LI><A href="#Chicken_nn12">Linkage</A>
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>
21137 <LI><A href="#Chicken_nn16">Typemaps</A></LI>
21138 <LI><A href="#Chicken_nn17">Pointers</A>
21140 <LI><A href="#collection">Garbage collection</A></LI>
21143 <LI><A href="#Chicken_nn18">Unsupported features and known problems</A>
21145 <LI><A href="#Chicken_nn19">TinyCLOS problems with Chicken version <=
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
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>
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>
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">
21189 % chicken example.scm -output-file oexample.c
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>
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>
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>
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>
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>
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>
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 "int my_variable;", use the Scheme form <TT>
21243 (my-variable 2345)</TT>. To get the C variable, use <TT>(my-variable)</TT>
21245 <P> The <TT>%feature("constasvar")</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 "int sqrt(double x);" 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>
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>
21283 %module exception_test
21286 void test_throw(int i) throws (int) {
21287 if (i == 1) throw 15;
21292 <P>could be run with</P>
21293 <DIV class="targetlang">
21295 (handle-exceptions exvar
21297 (print "Correct!")
21298 (print "Threw something else " exvar))
21302 <H2><A name="Chicken_nn11"></A>19.3 TinyCLOS</H2>
21303 <P> The author of TinyCLOS, Gregor Kiczales, describes TinyCLOS as:
21304 "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."</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 <Foo>, 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 "primitive:"</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 "mymod:". 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>
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">
21345 $ swig -chicken example.i
21346 $ csc -v example.scm example_impl.c example_wrap.c test_script.scm -o example
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">
21355 $ swig -chicken example.i
21356 $ csc -sv example.scm example_wrap.c example_impl.c -o example.so
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">
21366 $ csc -v test_script.scm -lexample
21369 <P>An alternative is that the test_script.scm can have the code <CODE>
21370 (load-library 'example "example.so")</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
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 "example.so")</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">
21388 $ csc -sv modname.scm modname_wrap.c modname_impl.c -o modname.so
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">
21401 (declare (uses mod1))
21402 (declare (uses mod2))
21405 <P>Which would then be compiled with</P>
21406 <DIV class="shell">
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
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
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 "modname.i"</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
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
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
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>
21519 <H3><A name="Chicken_nn19"></A>19.7.1 TinyCLOS problems with Chicken
21520 version <= 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>
21530 int foo(int a, Foo *b);
21534 <P>will produce scheme code</P>
21535 <DIV class="targetlang">
21537 (define-method (foo (arg0 <top>) (arg1 <Foo>)) (<I>call primitive function</I>))
21538 (define-method (foo (arg0 <top>)) (<I>call primitive function</I>))
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>
21557 <!-- Hand-written HTML -->
21558 <H1><A name="Guile"></A>20 SWIG and Guile</H1>
21561 <DIV class="sectiontoc">
21563 <LI><A href="#Guile_nn2">Meaning of "Module"</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>
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>
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>
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>
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>
21588 <LI><A href="#Guile_nn20">Naming Issues</A></LI>
21589 <LI><A href="#Guile_nn21">Linking</A></LI>
21595 <P> This section details guile-specific support in SWIG.</P>
21596 <H2><A name="Guile_nn2"></A>20.1 Meaning of "Module"</H2>
21597 <P> There are three different concepts of "module" involved, defined
21598 separately for SWIG, Guile, and Libtool. To avoid horrible confusion,
21599 we explicitly prefix the context, e.g., "guile-module".</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 "-gh" argument causes swig to output GH
21604 code, and the "-scm" argument causes swig to output SCM code. Right now
21605 the "-scm" argument is the default. The "-scm" wrapper generation
21606 assumes a guile version >= 1.6 and has several advantages over the
21607 "-gh" wrapper generation including garbage collection and GOOPS
21608 support. The "-gh" 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>
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
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>
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 "simple" and "matrix" examples
21667 under <CODE>Examples/guile</CODE>.</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
21673 <DIV class="targetlang">
21675 (define-module (my module))
21676 (define my-so (dynamic-link "./example.so"))
21677 (dynamic-call "SWIG_init" my-so) ; make SWIG bindings
21678 ;; Scheme definitions can go here
21681 <P> Newer Guile versions provide a shorthand for <CODE>dynamic-link</CODE>
21682 and <CODE>dynamic-call</CODE>:</P>
21683 <DIV class="targetlang">
21685 (load-extension "./example.so" "SWIG_init")
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">
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">
21700 (module-map (lambda (sym var)
21701 (module-export! (current-module) (list sym)))
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>
21716 %scheme %{ (load-extension "./example.so" "SWIG_init") %}
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>
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>
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">
21755 (define my-so (dynamic-link "./foo.so"))
21756 ;; create new module and put bindings there:
21757 (dynamic-call "scm_init_my_modules_foo_module" my-so)
21759 </DIV> Newer Guile versions have a shorthand procedure for this:<DIV class="targetlang">
21761 (load-extension "./foo.so" "scm_init_my_modules_foo_module")
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 "hobbit" linkage, and requires also
21788 using the "-package" 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">
21792 swig -guile -package my/lib foo.i
21793 swig -guile -package my/lib -module foo foo.i
21796 <P> would create module <CODE>(my lib foo)</CODE> (assuming in the first
21797 case foo.i declares the module to be "foo"). 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
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>
21812 <LI><CODE>$descriptor</CODE> expands to a type descriptor for use with
21813 the <CODE>SWIG_NewPointerObj()</CODE> and <CODE>SWIG_ConvertPtr</CODE>
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>
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>
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>
21833 %values_as_list;</PRE>
21836 <P><EM>Multiple values as vectors.</EM> By issuing</P>
21839 %values_as_vector;</PRE>
21841 <P> vectors instead of lists will be used.</P>
21844 <P><EM>Multiple values for multiple-value continuations.</EM><STRONG>
21845 This is the most elegant way.</STRONG> By issuing</P>
21848 %multiple_values;</PRE>
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">
21857 (receive (quotient remainder)
21859 <VAR>body</VAR>...)
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>
21867 <P> See also the "multivalue" example.</P>
21868 <P>Constants are exported as a function that returns the value. The
21869 %feature("constasvar") 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
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>#<swig struct xyzzy * 0x1234affe></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 "smobs" (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 "-scm" argument to swig) uses
21915 swigrun.swg. The whole type system, when it is first initialized,
21916 creates two smobs named "swig" and "collected_swig". 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 "swig_type_info address" 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 "-scm" flag to swig. Thus the
21931 swig garbage collection support requires guile >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">
21947 MAP(SWIG_MemoryError, "swig-memory-error");
21948 MAP(SWIG_IOError, "swig-io-error");
21949 MAP(SWIG_RuntimeError, "swig-runtime-error");
21950 MAP(SWIG_IndexError, "swig-index-error");
21951 MAP(SWIG_TypeError, "swig-type-error");
21952 MAP(SWIG_DivisionByZero, "swig-division-by-zero");
21953 MAP(SWIG_OverflowError, "swig-overflow-error");
21954 MAP(SWIG_SyntaxError, "swig-syntax-error");
21955 MAP(SWIG_ValueError, "swig-value-error");
21956 MAP(SWIG_SystemError, "swig-system-error");
21959 <P> The default when not specified here is to use "swig-error". 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>
21971 <LI><CODE>guile-1.4</CODE> (default): Generates a format suitable for
21973 <LI><CODE>plain</CODE>: Generates a format suitable for Guile 1.4.1 and
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
21979 <P>You need to register the generated documentation file with Guile like
21980 this:<DIV class="targetlang">
21982 (use-modules (ice-9 documentation))
21983 (set! documentation-files
21984 (cons "<VAR>file</VAR>" documentation-files))
21987 <P>Documentation strings can be configured using the Guile-specific
21988 typemap argument <CODE>doc</CODE>. See <CODE>Lib/guile/typemaps.i</CODE>
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
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
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>
22033 Foo(int i) : a(i) {}
22035 int getMultBy(int i) { return a * i; }
22036 Foo getFooMultBy(int i) { return Foo(a * i); }
22038 Foo getFooPlus(int i) { return Foo(a + i); }
22041 <P> will produce (if <CODE>-emit-slot-accessors</CODE> is not passed as
22043 <DIV class="targetlang">
22045 (define-class <Foo> (<swig>)
22046 (a #:allocation #:swig-virtual
22047 #:slot-ref primitive:Foo-a-get
22048 #:slot-set! primitive:Foo-a-set)
22049 #:metaclass <swig-metaclass>
22050 #:new-function primitive:new-Foo
22052 (define-method (getMultBy (swig_smob <Foo>) i)
22053 (primitive:Foo-getMultBy (slot-ref swig_smob 'smob) i))
22054 (define-method (getFooMultBy (swig_smob <Foo>) i)
22055 (make <Foo> #:init-smob (primitive:Foo-getFooMultBy (slot-ref swig_smob 'smob) i)))
22057 (define-method (getFooPlus i)
22058 (make <Foo> #:init-smob (primitive:getFooPlus i)))
22060 (export <Foo> getMultBy getFooMultBy getFooPlus )
22063 <P> and will produce (if <CODE>-emit-slot-accessors</CODE> is passed as
22065 <DIV class="targetlang">
22067 (define-class <Foo> (<swig>)
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 <swig-metaclass>
22073 #:new-function primitive:new-Foo
22075 (define-method (getMultBy (swig_smob <Foo>) i)
22076 (primitive:Foo-getMultBy (slot-ref swig_smob 'smob) i))
22077 (define-method (getFooMultBy (swig_smob <Foo>) i)
22078 (make <Foo> #:init-smob (primitive:Foo-getFooMultBy (slot-ref swig_smob 'smob) i)))
22080 (define-method (getFooPlus i)
22081 (make <Foo> #:init-smob (primitive:getFooPlus i)))
22083 (export <Foo> <B>a</B> getMultBy getFooMultBy getFooPlus )
22086 <P> which can then be used by this code</P>
22087 <DIV class="targetlang">
22089 ;; not using getters and setters
22090 (define foo (make <Foo> #:args '(45)))
22092 (slot-set! foo 'a 3)
22094 (define foo2 (getFooMultBy foo 7))
22096 (slot-ref (getFooPlus foo 4) 'a)
22098 ;; using getters and setters
22099 (define foo (make <Foo> #:args '(45)))
22103 (a (getFooMultBy foo 7))
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 <Foo> #: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>
22115 %{ #include "foo.h" %}
22118 int someFunc(Foo &a) {
22123 %include "foo.h"
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 <Foo>.
22131 The generated GOOPS file would look like</P>
22132 <DIV class="targetlang">
22136 (define-method (someFunc (swig_smob <Foo>))
22137 (primitive:someFunc (slot-ref swig_smob 'smob)))
22141 (define-class <Foo> (<swig>)
22148 <P> Notice that <Foo> is used before it is defined. The fix is to just
22149 put the <CODE>%import "foo.h"</CODE> before the <CODE>%inline</CODE>
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>
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 "-primitive". 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 "primitive" 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">
22187 (use-modules ((Test-primitive) #:renamer (symbol-prefix-proc 'primitive:)))
22188 (use-modules ((Test) #:renamer (symbol-prefix-proc 'goops:)))
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>
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">
22215 %goops %{ (load-extension "./foo.so" "scm_init_my_modules_foo_module") %}
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">
22223 (define-module (my modules foo))
22225 ;; %goops directive goes here
22226 (load-extension "./foo.so" "scm_init_my_modules_foo_module")
22228 (use-modules (oop goops) (Swig common))
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
22244 <DIV class="targetlang">
22246 %scheme %{ (load-extension "./foo.so" "scm_init_my_modules_foo_module") %}
22247 // only include the following definition if (my modules foo) cannot
22248 // be loaded automatically
22250 (primitive-load "/path/to/foo-primitive.scm")
22251 (primitive-load "/path/to/Swig/common.scm")
22255 <P> Produces the following code at the top of the generated GOOPS
22257 <DIV class="targetlang">
22259 (define-module (my modules foo))
22261 ;; %goops directive goes here (if any)
22262 (primitive-load "/path/to/foo-primitive.scm")
22263 (primitive-load "/path/to/Swig/common.scm")
22265 (use-modules (oop goops) (Swig common))
22266 (use-modules ((my modules foo-primitive) :renamer (symbol-prefix-proc
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>
22279 %goops %{ (load-extension "./foo.so" "scm_init_my_modules_foo_module") %}
22282 <P> Produces the following code at the top of the generated GOOPS
22284 <DIV class="targetlang">
22286 (define-module (my modules foo))
22288 ;; %goops directive goes here (if any)
22289 (load-extension "./foo.so" "scm_init_my_modules_foo_module")
22291 (use-modules (oop goops) (Swig common))
22292 (use-modules ((my modules foo-primitive) :renamer (symbol-prefix-proc
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>
22319 <H1><A name="Java"></A>21 SWIG and Java</H1>
22322 <DIV class="sectiontoc">
22324 <LI><A href="#java_overview">Overview</A></LI>
22325 <LI><A href="#java_preliminaries">Preliminaries</A>
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>
22337 <LI><A href="#visual_studio">Running SWIG from Visual Studio</A></LI>
22338 <LI><A href="#nmake">Using NMAKE</A></LI>
22343 <LI><A href="#java_basic_tour">A tour of basic C/C++ wrapping</A>
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>
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>
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
22366 <LI><A href="#null_pointers">Null pointers</A></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>
22376 <LI><A href="#further_details">Further details on the generated Java
22379 <LI><A href="#imclass">The intermediary JNI class</A>
22381 <LI><A href="#imclass_pragmas">The intermediary JNI class pragmas</A></LI>
22384 <LI><A href="#java_module_class">The Java module class</A>
22386 <LI><A href="#module_class_pragmas">The Java module class pragmas</A></LI>
22389 <LI><A href="#java_proxy_classes">Java proxy classes</A>
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>
22400 <LI><A href="#type_wrapper_classes">Type wrapper classes</A></LI>
22401 <LI><A href="#enum_classes">Enum classes</A>
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>
22410 <LI><A href="#java_directors">Cross language polymorphism using
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>
22420 <LI><A href="#java_allprotected">Accessing protected members</A></LI>
22421 <LI><A href="#common_customization">Common customization features</A>
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>
22430 <LI><A href="#tips_techniques">Tips and techniques</A>
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>
22441 <LI><A href="#java_typemaps">Java typemaps</A>
22443 <LI><A href="#default_primitive_type_mappings">Default primitive type
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>
22459 <LI><A href="#typemap_examples">Typemap Examples</A>
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
22471 <LI><A href="#using_typemaps_return_arguments">Using typemaps to return
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
22477 <LI><A href="#void_pointers">Void pointers and a common Java base class</A>
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>
22488 <LI><A href="#java_directors_faq">Living with Java Directors</A></LI>
22489 <LI><A href="#odds_ends">Odds and ends</A>
22491 <LI><A href="#javadoc_comments">JavaDoc comments</A></LI>
22492 <LI><A href="#functional_interface">Functional interface without proxy
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>
22499 <LI><A href="#java_examples">Examples</A></LI>
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 "<A href="#SWIG">SWIG Basics</A>" 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
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
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>
22565 /* File: example.i */
22568 #include "stuff.h"
22573 <P> To build a Java module, run SWIG using the <TT>-java</TT> option :</P>
22576 %swig -java example.i
22579 <P> If building C++, add the <TT>-c++</TT> option:</P>
22582 $ swig -c++ -java example.i
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++
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>
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
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>
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 <name></TD><TD>set name of the Java package to <name></TD>
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
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>
22631 /usr/java/include/<operating_system>
22634 <P> The exact location may vary on your machine, but the above locations
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>
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
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
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 "<TT>example</TT>", the name of the
22666 corresponding shared library file should be "<TT>libexample.so</TT>"
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>
22678 public class runme {
22680 System.loadLibrary("example");
22683 public static void main(String argv[]) {
22684 System.out.println(example.fact(4));
22689 <P> Compile all the Java files and run:</P>
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
22702 <P> As shown in the previous section the code to load a native library
22703 (shared library) is <TT>System.loadLibrary("name")</TT>. This can fail
22704 with an UnsatisfiedLinkError exception and can be due to a number of
22706 <P> You may get an exception similar to this:</P>
22710 Exception in thread "main" 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.<clinit>(runme.java:5)
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>
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>
22743 Exception in thread "main" java.lang.UnsatisfiedLinkError: libexample.so: undefined
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.<clinit>(runme.java:5)
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>
22763 Exception in thread "main" 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)
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>
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
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>
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
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.
22817 libstdc++-libc6.1-1.so.2 => /usr/lib/libstdc++-libc6.1-1.so.2 (0x40019000)
22818 libm.so.6 => /lib/libm.so.6 (0x4005b000)
22819 libc.so.6 => /lib/libc.so.6 (0x40077000)
22820 /lib/ld-linux.so.2 => /lib/ld-linux.so.2 (0x40000000)
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>
22841 <LI>Open up a new workspace and use the AppWizard to select a DLL
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 "Custom Build" option.</LI>
22849 <LI>Enter "SWIG" in the description field.</LI>
22850 <LI>Enter "<TT>swig -java -o $(ProjDir)\$(InputName)_wrap.c $(InputPath)</TT>
22851 " in the "Build command(s) field"</LI>
22852 <LI>Enter "<TT>$(ProjDir)\$(InputName)_wrap.c</TT>" in the "Output
22853 files(s) field".</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 "Additional include directories", eg
22857 "C:\jdk1.3\include,C:\jdk1.3\include\win32".</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, "c:\jdk1.3\bin\javac
22868 <LI>Build your project.</LI>
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>
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>
22889 # Makefile for using SWIG and Java for C code
22893 INTERFACE = $(IFILE).i
22894 WRAPFILE = $(IFILE)_wrap.c
22896 # Location of the Visual C++ tools (32 bit assumed)
22899 TARGET = example.dll
22900 CC = $(TOOLS)\bin\cl.exe
22901 LINK = $(TOOLS)\bin\link.exe
22902 INCLUDE32 = -I$(TOOLS)\include
22905 # C Library needed to build a DLL
22907 DLLIBC = msvcrt.lib oldnames.lib
22909 # Windows libraries that are apparently needed
22910 WINLIB = kernel32.lib advapi32.lib user32.lib gdi32.lib comdlg32.lib winspool.lib
22912 # Libraries common to all DLLs
22913 LIBS = $(DLLIBC) $(WINLIB)
22916 LOPT = -debug:full -debugtype:cv /NODEFAULTLIB /RELEASE /NOLOGO \
22917 /MACHINE:$(MACHINE) -entry:_DllMainCRTStartup@12 -dll
22921 CFLAGS = /Z7 /Od /c /nologo
22922 JAVA_INCLUDE = -ID:\jdk1.3\include -ID:\jdk1.3\include\win32
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
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
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
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>
22972 swig -java -package com.bloggs.swig -outdir com/bloggs/swig example.i
22974 </DIV> SWIG won't create the directory, so make sure it exists
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
22987 <P> creates a static function that works exactly like you think it
22991 public class example {
22992 public static int fact(int n) {
22993 // makes call using JNI to the C function
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>
23002 System.out.println(example.fact(4));
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>
23013 // SWIG interface file with global variables
23017 extern int My_variable;
23018 extern double density;
23023 <P> Now in Java :</P>
23026 // Print out value of a C global variable
23027 System.out.println("My_variable = " + example.getMy_variable());
23028 // Set the value of a C global variable
23029 example.setDensity(0.8442);
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>
23041 %rename Clash RenamedClash;
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>
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>
23072 extern char *path; // Read-only (due to %immutable)
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>
23082 #define VERSION "1.0"
23083 %constant int FOO = 42;
23084 %constant const char *path = "/usr/local";
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>
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();
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
23115 %javaconst(0) LARGE;
23117 #define EXPRESSION (0x100+5)
23119 #define LARGE 2000ULL
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();
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>
23158 %javaconstvalue("new java.math.BigInteger(\"2000\")") LARGE;
23159 %javaconstvalue(1000) BIG;
23161 #define EXPRESSION (0x100+5)
23163 #define LARGE 2000ULL
23166 <P> Note the string quotes for <TT>"2000"</TT> are escaped. The
23167 following is then generated:</P>
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("2000");
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>
23185 static const int FIVE = 5;
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>
23196 public class example implements exampleConstants {
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>
23222 enum { ALE, LAGER=10, STOUT, PILSNER, PILZ=PILSNER };
23225 <P> is wrapped into the constants interface, in a similar manner as
23226 constants (see previous section):</P>
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();
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>
23251 %javaconst(0) PILSNER;
23252 enum { ALE, LAGER=10, STOUT, PILSNER, PILZ=PILSNER };
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;
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 "enumtypesafe.swg" file. Let's look at an example:</P>
23280 %include "enumtypesafe.swg" // optional as typesafe enums are the default
23281 enum Beverage { ALE, LAGER=10, STOUT, PILSNER, PILZ=PILSNER };
23284 <P>will generate:</P>
23287 public final class Beverage {
23288 public final static Beverage ALE = new Beverage("ALE");
23289 public final static Beverage LAGER = new Beverage("LAGER", exampleJNI.LAGER_get());
23290 public final static Beverage STOUT = new Beverage("STOUT");
23291 public final static Beverage PILSNER = new Beverage("PILSNER");
23292 public final static Beverage PILZ = new Beverage("PILZ", exampleJNI.PILZ_get());
23293 [... additional support methods omitted for brevity ...]
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
23305 %include "enumtypesafe.swg" // optional as typesafe enums are the default
23307 enum Beverage { ALE, LAGER=10, STOUT, PILSNER, PILZ=PILSNER };
23310 <P> will generate:</P>
23313 public final class Beverage {
23314 public final static Beverage ALE = new Beverage("ALE");
23315 public final static Beverage LAGER = new Beverage("LAGER", 10);
23316 public final static Beverage STOUT = new Beverage("STOUT");
23317 public final static Beverage PILSNER = new Beverage("PILSNER");
23318 public final static Beverage PILZ = new Beverage("PILZ", PILSNER);
23319 [... additional support methods omitted for brevity ...]
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 "enums.swg" file must be used. Let's take a look
23365 %include "enums.swg"
23367 enum Beverage { ALE, LAGER=10, STOUT, PILSNER, PILZ=PILSNER };
23370 <P> will generate:</P>
23373 public enum Beverage {
23379 [... additional support methods omitted for brevity ...]
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 "enumtypeunsafe.swg" file must be used. Let's take a
23402 look at an example.</P>
23405 %include "enumtypeunsafe.swg"
23407 enum Beverage { ALE, LAGER=10, STOUT, PILSNER, PILZ=PILSNER };
23410 <P> will generate:</P>
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;
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 "enumsimple.swg" 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>
23455 FILE *fopen(const char *filename, const char *mode);
23456 int fputs(const char *, FILE *);
23457 int fclose(FILE *);
23460 <P> When wrapped, you will be able to use the functions in a natural way
23461 from Java. For example:</P>
23464 SWIGTYPE_p_FILE f = example.fopen("junk","w");
23465 example.fputs("Hello World\n", f);
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>
23498 Bar *FooToBar(Foo *f) {
23502 /* C++-style cast */
23503 Foo *BarToFoo(Bar *b) {
23504 return dynamic_cast<Foo*>(b);
23507 Foo *IncrFoo(Foo *f, int i) {
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>
23528 <P> is used as follows:</P>
23531 Vector v = new Vector();
23534 double x = v.getX();
23535 double y = v.getY();
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
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>
23556 int x; /* Read-only members */
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>
23578 <P> If accessed in Java, you will see behavior like this:</P>
23582 SWIGTYPE_p_int x = b.getX();
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>
23591 SWIGTYPE_p_int x = b.getX();
23593 c.setX(x); // Copy contents of b.x to c.x
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>
23619 <P> Now, suppose that you access the <TT>f</TT> member of <TT>Bar</TT>
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
23633 Foo *x = &b->f; /* Points inside b */
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>
23641 b.getF().setA(3); // Modify b.f.a
23643 x.setA(3); // Modify x.a - this is the same as b.f.a
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>
23655 int search(char *item);
23656 void insert(char *item);
23657 void remove(char *item);
23663 <P> you can use it in Java like this:</P>
23666 List l = new List();
23667 l.insert("Ale");
23668 l.insert("Stout");
23669 l.insert("Lager");
23670 String item = l.get(2);
23671 int length = l.getLength();
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>
23686 <P> The static members work like any other Java static member:</P>
23690 int bar = Spam.getBar();
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>
23702 class Bar : public Foo {
23707 <P> those classes are wrapped into a hierarchy of Java classes that
23708 reflect the same inheritance structure:</P>
23712 Class c = b.getClass();
23713 System.out.println(c.getSuperclass().getName());
23716 <P> will of course display:</P>
23722 <P> Furthermore, if you have functions like this</P>
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
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>
23740 void spam1(Foo *x); // Pass by pointer
23741 void spam2(Foo &x); // Pass by reference
23742 void spam3(Foo x); // Pass by value
23743 void spam4(Foo x[]); // Array of objects
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>
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)
23760 <P> Similar behavior occurs for return values. For example, if you had
23761 functions like this,</P>
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>
23782 example.spam1(null); // Pointer - ok
23783 example.spam2(null); // Reference - NullPointerException
23784 example.spam3(null); // Value - NullPointerException
23785 example.spam4(null); // Array - ok
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>
23803 <P> You can use them in Java in a straightforward manner:</P>
23806 example.foo(3); // foo(int)
23807 example.foo("Hello"); // foo(char *c)
23810 <P> Similarly, if you have a class like this,</P>
23816 Foo(const Foo &);
23821 <P> you can write Java code like this:</P>
23824 Foo f = new Foo(); // Create a Foo
23825 Foo g = new Foo(f); // Copy f
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>
23834 void spam(unsigned short);
23837 <P> Here both int and unsigned short map onto a Java int. Here is
23838 another example:</P>
23842 void foo(Bar &b);
23845 <P> If declarations such as these appear, you will get a warning message
23849 example.i:12: Warning(515): Overloaded method spam(unsigned short) ignored.
23850 Method spam(int) at example.i:11 used.
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>
23857 %rename(spam_ushort) spam(unsigned short);
23860 void spam(unsigned short); // Now renamed to spam_ushort
23866 %ignore spam(unsigned short);
23869 void spam(unsigned short); // Ignored
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>
23880 void defaults(double d=10.0, int i=0);
23883 <P> The following methods are generated in the Java module class:</P>
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() { ... }
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
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>
23917 <P> it works in Java as follows:</P>
23920 int f = example.fact(3);
23921 Vector v = new Vector();
23923 double y = v.getY();
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>
23930 %rename(Bar_spam) Bar::spam;
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>
23953 #include <utility>
23956 template<class T1, class T2>
23958 typedef T1 first_type;
23959 typedef T2 second_type;
23963 pair(const T1&, const T2&);
23967 %template(pairii) pair<int,int>;
23973 pairii p = new pairii(3,4);
23974 int first = p.getFirst();
23975 int second = p.getSecond();
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 "smart pointers." Generally, this involves the use
23984 of a template class that implements <TT>operator->()</TT> like this:</P>
23987 template<class T> class SmartPtr {
23989 T *operator->();
23994 <P> Then, if you have a class like this,</P>
24004 <P> A smart pointer would be used in C++ as follows:</P>
24007 SmartPtr<Foo> p = CreateFoo(); // Created somehow (not shown)
24009 p->x = 3; // Foo::x
24010 int y = p->bar(); // Foo::bar
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>
24020 %template(SmartPtrFoo) SmartPtr<Foo>;
24024 <P> Now, in Java, everything should just "work":</P>
24027 SmartPtrFoo p = example.CreateFoo(); // Create a smart-pointer somehow
24028 p.setX(3); // Foo::x
24029 int y = p.bar(); // Foo::bar
24032 <P> If you ever need to access the underlying pointer returned by <TT>
24033 operator->()</TT> itself, simply use the <TT>__deref__()</TT> method.
24037 Foo f = p.__deref__(); // Returns underlying Foo *
24040 <H2><A name="further_details"></A>21.4 Further details on the generated
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
24052 <H3><A name="imclass"></A>21.4.1 The intermediary JNI class</H3>
24053 <P> In the <A href="#SWIG">"SWIG basics"</A> and <A href="#SWIGPlus">
24054 "SWIG and C++"</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>
24062 int spam(int num, Foo* foo);
24064 void egg(Foo* chips);
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>
24075 void delete_Foo(Foo *f) {
24078 int Foo_x_get(Foo *f) {
24081 void Foo_x_set(Foo *f, int value) {
24084 int Foo_spam(Foo *f, int num, Foo* foo) {
24085 return f->spam(num, foo);
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>
24095 SWIGEXPORT jlong JNICALL Java_exampleJNI_new_1Foo(JNIEnv *jenv, jclass jcls);
24096 SWIGEXPORT void JNICALL Java_exampleJNI_delete_1Foo(JNIEnv *jenv, jclass jcls,
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_);
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>
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_);
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
24151 %module (jniclassname="name") modulename
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
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>
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>
24174 <P> The pragma code appears in the generated intermediary JNI class
24175 where you would expect:</P>
24178 [ jniclassimports pragma ]
24179 [ jniclassclassmodifiers pragma ] jniclassname extends [ jniclassbase pragma ]
24180 implements [ jniclassinterfaces pragma ] {
24181 [ jniclasscode pragma ]
24182 ... SWIG generated native methods ...
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>
24191 %pragma(java) jniclasscode=%{
24194 System.loadLibrary("example");
24195 } catch (UnsatisfiedLinkError e) {
24196 System.err.println("Native code library failed to load. \n" + e);
24203 <P> Pragmas will take either <TT>""</TT> or <TT>%{ %}</TT> as
24204 delimiters. For example, let's change the intermediary JNI class access
24208 %pragma(java) jniclassclassmodifiers="public class"
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>
24218 public class example {
24219 public static void egg(Foo chips) {
24220 exampleJNI.egg(Foo.getCPtr(chips), chips);
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>
24231 example.egg(new Foo());
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
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
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>
24256 <P> The pragma code appears in the generated module class like this:</P>
24259 [ moduleimports pragma ]
24260 [ modulemodifiers pragma ] modulename extends [ modulebase pragma ]
24261 implements [ moduleinterfaces pragma ] {
24262 [ modulecode pragma ]
24263 ... SWIG generated wrapper functions ...
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
24277 private long swigCPtr;
24278 protected boolean swigCMemOwn;
24280 protected Foo(long cPtr, boolean cMemoryOwn) {
24281 swigCMemOwn = cMemoryOwn;
24285 protected static long getCPtr(Foo obj) {
24286 return (obj == null) ? 0 : obj.swigCPtr;
24289 protected void finalize() {
24293 public synchronized void delete() {
24294 if(swigCPtr != 0 && swigCMemOwn) {
24295 swigCMemOwn = false;
24296 exampleJNI.delete_Foo(swigCPtr);
24301 public void setX(int value) {
24302 exampleJNI.Foo_x_set(swigCPtr, this, value);
24305 public int getX() {
24306 return exampleJNI.Foo_x_get(swigCPtr, this);
24309 public int spam(int num, Foo foo) {
24310 return exampleJNI.Foo_spam(swigCPtr, this, num, Foo.getCPtr(foo), foo);
24314 this(exampleJNI.new_Foo(), true);
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
24335 int y = f.spam(5, new Foo());
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.
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
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>
24383 void set_value(Obj *v) { value = v; }
24387 <P> Now, consider the following Java code:</P>
24390 Node n = new Node(); // Create a node
24392 Obj o = new Obj(); // Create an object
24393 n.set_value(o); // Set value
24394 } // o goes out of scope
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>
24420 static Obj *createObj() { return new Obj(); }
24424 <P> If we call the factory function, then we have to manually delete the
24428 Obj obj = Factory.createObj(); // obj.swigCMemOwn = false
24433 <P> Now add in the %newobject directive:</P>
24436 %newobject Factory::createObj();
24441 static Obj *createObj() { return new Obj(); }
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>
24450 Obj obj = Factory.createObj(); // obj.swigCMemOwn = true;
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>
24469 virtual double foo();
24472 class Derived : public Base {
24474 virtual double foo();
24478 <P> The base class is generated much like any other proxy class seen so
24482 public class Base {
24483 private long swigCPtr;
24484 protected boolean swigCMemOwn;
24486 protected Base(long cPtr, boolean cMemoryOwn) {
24487 swigCMemOwn = cMemoryOwn;
24491 protected static long getCPtr(Base obj) {
24492 return (obj == null) ? 0 : obj.swigCPtr;
24495 protected void finalize() {
24499 public synchronized void delete() {
24500 if(swigCPtr != 0 && swigCMemOwn) {
24501 swigCMemOwn = false;
24502 exampleJNI.delete_Base(swigCPtr);
24507 public double foo() {
24508 return exampleJNI.Base_foo(swigCPtr, this);
24512 this(exampleJNI.new_Base(), true);
24518 <P> The <TT>Derived</TT> class extends <TT>Base</TT> mirroring the C++
24519 class inheritance hierarchy.</P>
24522 public class Derived extends Base {
24523 private long swigCPtr;
24525 protected Derived(long cPtr, boolean cMemoryOwn) {
24526 super(exampleJNI.SWIGDerivedUpcast(cPtr), cMemoryOwn);
24530 protected static long getCPtr(Derived obj) {
24531 return (obj == null) ? 0 : obj.swigCPtr;
24534 protected void finalize() {
24538 public synchronized void delete() {
24539 if(swigCPtr != 0 && swigCMemOwn) {
24540 swigCMemOwn = false;
24541 exampleJNI.delete_Derived(swigCPtr);
24547 public double foo() {
24548 return exampleJNI.Derived_foo(swigCPtr, this);
24552 this(exampleJNI.new_Derived(), true);
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
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>
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>
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>
24621 Runtime.getRuntime().addShutdownHook(
24623 public void run() { System.gc(); System.runFinalization(); }
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>
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>
24646 // any use of myA here would crash the JVM
24648 // any use of myA here would cause a Java null pointer exception to be thrown
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>
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>
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
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>
24678 void wobble(Wibble &w);
24681 <P> The module class contains the Java wrapper for the global <TT>wobble</TT>
24685 public class example {
24687 public static void wobble(Wibble w) {
24688 exampleJNI.wobble(Wibble.getCPtr(w), w);
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
24698 public class exampleJNI {
24700 public final static native void wobble(long jarg1, Wibble jarg1_);
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>
24711 public class exampleJNI {
24713 public final static native void wobble(long jarg1);
24717 <P> and the following simple call to <TT>wobble</TT>:</P>
24721 Wibble w = new Wibble();
24726 <P> The hotspot compiler effectively sees something like:</P>
24730 Wibble w = new Wibble();
24731 long w_ptr = Wibble.getCPtr(w);
24732 // w is no longer reachable
24733 exampleJNI.wobble(w_ptr);
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
24753 Wibble w = new Wibble();
24754 long w_ptr = Wibble.getCPtr(w);
24755 exampleJNI.wobble(w_ptr, w);
24756 // w is no longer reachable
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 "jtype" typemap to contain <TT>long</TT>
24768 and the "jstype" 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 "jtype" <A href="#java_typemaps">
24773 Java typemap</A>. The attribute is a flag and so should be set to "1" to
24774 enable the suppression, or it can be omitted or set to "0" to disable.
24778 %typemap(jtype, nopgcpp="1") Wibble & "long"
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>
24793 Test() : str("initial") {}
24797 <P> and the Java proxy class generated by SWIG:</P>
24800 public class Test {
24801 private long swigCPtr;
24802 protected boolean swigCMemOwn;
24804 protected Test(long cPtr, boolean cMemoryOwn) {
24805 swigCMemOwn = cMemoryOwn;
24809 protected static long getCPtr(Test obj) {
24810 return (obj == null) ? 0 : obj.swigCPtr;
24813 protected void finalize() {
24817 // Call C++ destructor
24818 public synchronized void delete() {
24819 if(swigCPtr != 0 && swigCMemOwn) {
24820 swigCMemOwn = false;
24821 exampleJNI.delete_Test(swigCPtr);
24826 // Call C++ constructor
24828 this(exampleJNI.new_Test(), true);
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
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>
24862 for (int i=0; i<100000; i++) {
24863 System.out.println("Iteration " + i);
24864 for (int k=0; k<10; k++) {
24865 Test test = new Test();
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
24876 public class SWIGTYPE_p_int {
24877 private long swigCPtr;
24879 protected SWIGTYPE_p_int(long cPtr, boolean bFutureUse) {
24883 protected SWIGTYPE_p_int() {
24887 protected static long getCPtr(SWIGTYPE_p_int obj) {
24888 return obj.swigCPtr;
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
24916 void spam(Snazzy *x, Snazzy &y, Snazzy z);
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>
24924 public static void spam(SWIGTYPE_p_Snazzy x, SWIGTYPE_p_Snazzy y, SWIGTYPE_p_Snazzy z) {
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
24935 typedef int Snazzy;
24936 void spam(Snazzy *x, Snazzy &y, Snazzy z);
24939 <P> Because the typedefs have been tracked the Java function generated
24943 public static void spam(SWIGTYPE_p_int x, SWIGTYPE_p_int y, int z) { ... }
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>
24956 %include "enumtypesafe.swg"
24958 enum Beverage { ALE, LAGER=10, STOUT, PILSNER, PILZ=PILSNER };
24961 <P> The following is the code that SWIG generates:</P>
24964 public final class Beverage {
24965 public final static Beverage ALE = new Beverage("ALE");
24966 public final static Beverage LAGER = new Beverage("LAGER", 10);
24967 public final static Beverage STOUT = new Beverage("STOUT");
24968 public final static Beverage PILSNER = new Beverage("PILSNER");
24969 public final static Beverage PILZ = new Beverage("PILZ", PILSNER);
24971 public final int swigValue() {
24975 public String toString() {
24979 public static Beverage swigToEnum(int swigValue) {
24980 if (swigValue < swigValues.length && swigValue >= 0 &&
24981 swigValues[swigValue].swigValue == swigValue)
24982 return swigValues[swigValue];
24983 for (int i = 0; i < swigValues.length; i++)
24984 if (swigValues[i].swigValue == swigValue)
24985 return swigValues[i];
24986 throw new IllegalArgumentException("No enum " + Beverage.class + " with value " +
24990 private Beverage(String swigName) {
24991 this.swigName = swigName;
24992 this.swigValue = swigNext++;
24995 private Beverage(String swigName, int swigValue) {
24996 this.swigName = swigName;
24997 this.swigValue = swigValue;
24998 swigNext = swigValue+1;
25001 private Beverage(String swigName, Beverage swigEnum) {
25002 this.swigName = swigName;
25003 this.swigValue = swigEnum.swigValue;
25004 swigNext = this.swigValue+1;
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;
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>
25032 %include "enums.swg"
25034 enum Beverage { ALE, LAGER=10, STOUT, PILSNER, PILZ=PILSNER };
25037 <P> SWIG will generate the following Java enum:</P>
25040 public enum Beverage {
25047 public final int swigValue() {
25051 public static Beverage swigToEnum(int swigValue) {
25052 Beverage[] swigValues = Beverage.class.getEnumConstants();
25053 if (swigValue < swigValues.length && swigValue >= 0 &&
25054 swigValues[swigValue].swigValue == swigValue)
25055 return swigValues[swigValue];
25056 for (Beverage swigEnum : swigValues)
25057 if (swigEnum.swigValue == swigValue)
25059 throw new IllegalArgumentException("No enum " + Beverage.class +
25060 " with value " + swigValue);
25063 private Beverage() {
25064 this.swigValue = SwigNext.next++;
25067 private Beverage(int swigValue) {
25068 this.swigValue = swigValue;
25069 SwigNext.next = swigValue+1;
25072 private Beverage(Beverage swigEnum) {
25073 this.swigValue = swigEnum.swigValue;
25074 SwigNext.next = this.swigValue+1;
25077 private final int swigValue;
25079 private static class SwigNext {
25080 private static int next = 0;
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
25099 <P> The following example demonstrates type unsafe enums:</P>
25102 %include "enumtypeunsafe.swg"
25104 enum Beverage { ALE, LAGER=10, STOUT, PILSNER, PILZ=PILSNER };
25107 <P> SWIG will generate the following simple class:</P>
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;
25119 <H2><A name="java_directors"></A>21.5 Cross language polymorphism using
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 "directors"
25145 option to the %module directive, like this:</P>
25148 %module(directors="1") modulename
25151 <P> Without this option no director code will be generated. Second, you
25152 must use the %feature("director") 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>
25157 // generate directors for all classes that have virtual methods
25158 %feature("director");
25160 // generate directors for all virtual methods in class Foo
25161 %feature("director") Foo;
25163 // generate a director for just Foo::bar()
25164 %feature("director") Foo::bar;
25167 <P> You can use the %feature("nodirector") directive to turn off
25168 directors for specific classes or methods. So for example,</P>
25171 %feature("director") Foo;
25172 %feature("nodirector") Foo::bar;
25175 <P> will generate directors for all virtual methods of class Foo except
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>
25182 %feature("director") Foo;
25185 virtual void one();
25186 virtual void two();
25189 class Bar: public Foo {
25191 virtual void three();
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 "appropriate place" 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 "appropriate place" 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>
25243 %module(directors="1") example;
25245 %feature("director") DirectorBase;
25247 class DirectorBase {
25249 virtual ~DirectorBase() {}
25250 virtual void upcall_method() {}
25253 void callup(DirectorBase *director) {
25254 director->upcall_method();
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>
25267 public class DirectorDerived extends DirectorBase {
25268 public DirectorDerived() {
25271 public void upcall_method() {
25272 System.out.println("DirectorDerived::upcall_method() invoked.");
25277 <P> Running the following Java code</P>
25280 DirectorDerived director = new DirectorDerived();
25281 example.callup(director);
25284 <P> will result in the following being output:</P>
25287 DirectorDerived::upcall_method() invoked.
25290 <H3><A name="java_directors_threading"></A>21.5.5 Director threading
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>
25307 %insert("runtime") %{
25308 #define SWIG_JAVA_NO_DETACH_CURRENT_THREAD
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,
25324 %module(directors="1", allprotected="1") modulename
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>
25336 %module(directors="1", allprotected="1") example
25338 %feature("director") ProtectedBase;
25340 // Ignore use of unsupported types (those defined in the protected section)
25341 %ignore ProtectedBase::typedefs;
25345 class 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;
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; }
25359 int ProtectedBase::staticMemberVariable = 10;
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>
25372 class MyProtectedBase extends ProtectedBase
25374 public MyProtectedBase() {
25377 public void accessProtected() {
25379 nonStaticMethod(1.2);
25382 setInstanceMemberVariable(5);
25383 int i = getInstanceMemberVariable();
25385 setStaticMemberVariable(10);
25386 i = getStaticMemberVariable();
25391 <H2><A name="common_customization"></A>21.7 Common customization
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>
25405 typedef struct Image {...};
25406 void set_transform(Image *im, double m[4][4]);
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>
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));
25422 void free_mat44(double (*x)[4]) {
25425 void mat44_set(double x[4][4], int i, int j, double v) {
25428 double mat44_get(double x[4][4], int i, int j) {
25434 <P> From Java, you could then write code like this:</P>
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);
25443 example.set_transform(im,a);
25444 example.free_mat44(a);
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>
25460 #include "someheader.h"
25469 static char tmp[1024];
25470 sprintf(tmp,"Vector(%g,%g,%g)", $self->x,$self->y,$self->z);
25473 Vector(double x, double y, double z) {
25474 Vector *v = (Vector *) malloc(sizeof(Vector));
25483 <P> Now, in Java</P>
25486 Vector v = new Vector(2,3,4);
25487 System.out.println(v);
25490 <P> will display</P>
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>
25512 %exception malloc {
25515 jclass clazz = (*jenv)->FindClass(jenv, "java/lang/OutOfMemoryError");
25516 (*jenv)->ThrowNew(jenv, clazz, "Not enough memory");
25520 void *malloc(size_t nbytes);
25526 SWIGTYPE_p_void a = example.malloc(2000000000);
25529 <P> will produce a familiar looking Java exception:</P>
25532 Exception in thread "main" 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)
25538 <P> If a library provides some kind of general error handling framework,
25539 you can also use that. For example:</P>
25542 %exception malloc {
25544 if (err_occurred()) {
25545 jclass clazz = (*jenv)->FindClass(jenv, "java/lang/OutOfMemoryError");
25546 (*jenv)->ThrowNew(jenv, clazz, "Not enough memory");
25550 void *malloc(size_t nbytes);
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>
25565 %exception getitem {
25568 } catch (std::out_of_range &e) {
25569 jclass clazz = jenv->FindClass("java/lang/Exception");
25570 jenv->ThrowNew(clazz, "Range error");
25577 FooClass *getitem(int index); // Might throw std::out_of_range exception
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>
25595 %javaexception("java.lang.Exception") getitem {
25598 } catch (std::out_of_range &e) {
25599 jclass clazz = jenv->FindClass("java/lang/Exception");
25600 jenv->ThrowNew(clazz, "Range error");
25607 FooClass *getitem(int index); // Might throw std::out_of_range exception
25612 <P> The generated proxy method now generates a throws clause containing <TT>
25613 java.lang.Exception</TT>:</P>
25616 public class FooClass {
25618 public FooClass getitem(int index) throws java.lang.Exception { ... }
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
25641 %javamethodmodifiers protect_me() "protected";
25645 <P> Will produce the method in the module class with protected access.</P>
25648 protected static void protect_me() {
25649 exampleJNI.protect_me();
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>
25664 void add(int x, int y, int *result) {
25672 int sub(int *x, int *y) {
25677 <P> The <TT>typemaps.i</TT> library file will help in these situations.
25682 %include "typemaps.i"
25684 void add(int, int, int *OUTPUT);
25685 int sub(int *INPUT, int *INPUT);
25688 <P> In Java, this allows you to pass simple values. For example:</P>
25691 int result = example.sub(7,4);
25692 System.out.println("7 - 4 = " + result);
25694 example.add(3,4,sum);
25695 System.out.println("3 + 4 = " + sum[0]);
25698 <P> Which will display:</P>
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>
25713 %include "typemaps.i"
25715 %apply int *OUTPUT { int *result };
25716 %apply int *INPUT { int *x, int *y};
25718 void add(int x, int y, int *result);
25719 int sub(int *x, int *y);
25722 <P> If a function mutates one of its parameters like this,</P>
25725 void negate(int *x) {
25730 <P> you can use <TT>INOUT</TT> like this:</P>
25733 %include "typemaps.i"
25735 void negate(int *INOUT);
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>
25743 example.negate(neg);
25744 System.out.println("Negative of 3 = " + neg[0]);
25747 <P> And no prizes for guessing the output:</P>
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>
25759 void negate(int *INOUT);
25762 <P> or using a reference:</P>
25765 void negate(int &INOUT);
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>
25775 void foo(Bar *OUTPUT);
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>
25787 %include "cpointer.i"
25790 extern void add(int x, int y, int *result);
25793 %pointer_functions(int, intp);
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>
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);
25808 <P> In Java, you would use the functions like this:</P>
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("3 + 4 = " + result);
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>
25821 intp intPtr = new intp();
25822 example.add(3,4,intPtr.cast());
25823 int result = intPtr.value();
25824 System.out.println("3 + 4 = " + result);
25827 <P> See the <A href="#Library">SWIG Library</A> chapter for further
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
25835 %include "arrays_java.i";
25837 void populate(int x[]) {
25839 for (i=0; i<4; i++)
25844 <P> These one dimensional arrays can then be used as if they were Java
25848 int[] array = new int[4];
25849 example.populate(array);
25851 System.out.print("array: ");
25852 for (int i=0; i<array.length; i++)
25853 System.out.print(array[i] + " ");
25855 example.setArray(array);
25857 int[] global_array = example.getArray();
25859 System.out.print("\nglobal_array: ");
25860 for (int i=0; i<array.length; i++)
25861 System.out.print(global_array[i] + " ");
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>
25869 array: 100 101 102 103
25870 global_array: 100 101 102 103
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.
25891 int sumitems(int *first, int nitems) {
25893 for (i = 0; i < nitems; i++) {
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>
25904 %include "arrays_java.i"
25905 %apply int[] {int *};
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
25914 int[] array = new int[10000000]; // Array of 10-million integers
25915 for (int i=0; i<array.length; i++) { // Set some values
25918 int sum = example.sumitems(array,10000);
25919 System.out.println("Sum = " + sum);
25922 <P> and the sum would be displayed:</P>
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>
25937 %include "carrays.i"
25938 %array_functions(int, intArray);
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>
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);
25952 <P> In Java, you would use the functions like this:</P>
25955 SWIGTYPE_p_int array = example.new_intArray(10000000); // Array of 10-million integers
25956 for (int i=0; i<10000; i++) { // Set some values
25957 example.intArray_setitem(array,i,i);
25959 int sum = example.sumitems(array,10000);
25960 System.out.println("Sum = " + sum);
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>
25969 %include "carrays.i"
25970 %array_class(int, intArray);
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>
25979 intArray array = new intArray(10000000); // Array of 10-million integers
25980 for (int i=0; i<10000; i++) { // Set some values
25981 array.setitem(i,i);
25983 int sum = example.sumitems(array.cast(),10000);
25984 System.out.println("Sum = " + sum);
25987 <P> The array "object" 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>
26012 /* File: java_heap.i */
26015 #include <stdexcept>
26016 #include "jni.h"
26019 * A stash area embedded in each allocation to hold java handles
26026 static JavaVM *cached_jvm = 0;
26028 JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *jvm, void *reserved) {
26030 return JNI_VERSION_1_2;
26033 static JNIEnv * JNU_GetEnv() {
26035 jint rc = cached_jvm->GetEnv((void **)&env, JNI_VERSION_1_2);
26036 if (rc == JNI_EDETACHED)
26037 throw std::runtime_error("current thread not attached");
26038 if (rc == JNI_EVERSION)
26039 throw std::runtime_error("jni version not supported");
26043 void * operator new(size_t t) {
26044 if (cached_jvm != 0) {
26045 JNIEnv *env = JNU_GetEnv();
26046 jbyteArray jba = env->NewByteArray((int) t + sizeof(Jalloc));
26047 if (env->ExceptionOccurred())
26049 void *jbuffer = static_cast<void *>(env->GetByteArrayElements(jba, 0));
26050 if (env->ExceptionOccurred())
26052 Jalloc *pJalloc = static_cast<Jalloc *>(jbuffer);
26053 pJalloc->jba = jba;
26054 /* Assign a global reference so byte array will persist until delete'ed */
26055 pJalloc->ref = env->NewGlobalRef(jba);
26056 if (env->ExceptionOccurred())
26058 return static_cast<void *>(static_cast<char *>(jbuffer) + sizeof(Jalloc));
26060 else { /* JNI_OnLoad not called, use malloc and mark as special */
26061 Jalloc *pJalloc = static_cast<Jalloc *>(malloc((int) t + sizeof(Jalloc)));
26064 pJalloc->ref = 0;
26065 return static_cast<void *>(
26066 static_cast<char *>(static_cast<void *>(pJalloc)) + sizeof(Jalloc));
26070 void operator delete(void *v) {
26072 void *buffer = static_cast<void *>( static_cast<char *>(v) - sizeof(Jalloc));
26073 Jalloc *pJalloc = static_cast<Jalloc *>(buffer);
26074 if (pJalloc->ref) {
26075 JNIEnv *env = JNU_GetEnv();
26076 env->DeleteGlobalRef(pJalloc->ref);
26077 env->ReleaseByteArrayElements(pJalloc->jba, static_cast<jbyte *>(buffer), 0);
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
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 "<A href="#Typemaps">Typemaps</A>" 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>
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>
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
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>
26131 <BR> const bool &</TD><TD>boolean</TD><TD>jboolean</TD></TR>
26133 <BR>const char &</TD><TD>char</TD><TD>jchar</TD></TR>
26134 <TR><TD>signed char
26135 <BR>const signed char &</TD><TD>byte</TD><TD>jbyte</TD></TR>
26136 <TR><TD>unsigned char
26137 <BR>const unsigned char &</TD><TD>short</TD><TD>jshort</TD></TR>
26139 <BR>const short &</TD><TD>short</TD><TD>jshort</TD></TR>
26140 <TR><TD>unsigned short
26141 <BR> const unsigned short &</TD><TD>int</TD><TD>jint</TD></TR>
26143 <BR> const int &</TD><TD>int</TD><TD>jint</TD></TR>
26144 <TR><TD>unsigned int
26145 <BR> const unsigned int &</TD><TD>long</TD><TD>jlong</TD></TR>
26147 <BR>const long &</TD><TD>int</TD><TD>jint</TD></TR>
26148 <TR><TD>unsigned long
26149 <BR>const unsigned long &</TD><TD>long</TD><TD>jlong</TD></TR>
26151 <BR> const long long &</TD><TD>long</TD><TD>jlong</TD></TR>
26152 <TR><TD>unsigned long long
26153 <BR>const unsigned long long &</TD><TD>java.math.BigInteger</TD><TD>
26156 <BR>const float &</TD><TD>float</TD><TD>jfloat</TD></TR>
26158 <BR> const double &</TD><TD>double</TD><TD>jdouble</TD></TR>
26160 <BR>char []</TD><TD>String</TD><TD>jstring</TD></TR>
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
26168 <P> Given the following C function:</P>
26171 void func(unsigned short a, char *b, const long &c, unsigned long long d);
26174 <P> The module class method would be:</P>
26177 public static void func(int a, String b, int c, java.math.BigInteger d) {...}
26180 <P> The intermediary JNI class would use the same types:</P>
26183 public final static native void func(int jarg1, String jarg2, int jarg3,
26184 java.math.BigInteger jarg4);
26187 <P> and the JNI function would look like this:</P>
26190 SWIGEXPORT void JNICALL Java_exampleJNI_func(JNIEnv *jenv, jclass jcls,
26191 jint jarg1, jstring jarg2, jint jarg3, jobject jarg4) {...}
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
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>
26232 printf("Received an integer : %d\n", $1);
26235 extern int fact(int nonnegative);
26239 <P> Typemaps are always associated with some specific aspect of code
26240 generation. In this case, the "in" 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
26251 System.out.println(example.fact(6));
26254 <P> and the output will be:</P>
26257 Received an integer : 6
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>
26268 %typemap(in) int nonnegative {
26270 printf("Received an integer : %d\n", $1);
26274 extern int fact(int nonnegative);
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>
26288 %typemap(in) int nonnegative {
26290 printf("Received an integer : %d\n", $1);
26293 typedef int Integer;
26294 extern int fact(Integer nonnegative); // Above typemap is applied
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.
26305 %typemap(in) (char *str, int len) {
26309 int count(char c, char *str, int len);
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>
26317 int c = example.count('e',"Hello World");
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
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 "jni" 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 "jstype"
26342 typemap) to the type used in the Java intermediary JNI class (as
26343 specified in the "jtype" 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 "jtype" typemap) to the Java type used
26348 in the Java module class, proxy classes and type wrapper classes (as
26349 specified in the "jstype" 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 "jtype"
26354 typemap) to the Java type used in the Java module class, proxy classes
26355 and type wrapper classes (as specified in the "jstype" 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 "jstype" typemap) to the type used in the Java
26363 intermediary JNI class (as specified in the "jtype" 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>
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 "<TT>java.swg</TT>" and so might be a good place for
26383 finding typemaps to base any new ones on.</P>
26384 <P> The "jni", "jtype" and "jstype" typemaps are usually defined
26385 together to handle the Java to C/C++ type mapping. An "in" typemap
26386 should be accompanied by a "javain" typemap and likewise an "out"
26387 typemap by a "javaout" typemap. If an "in" typemap is written, a
26388 "freearg" and "argout" typemap may also need to be written as some
26389 types have a default "freearg" and/or "argout" typemap which may need
26390 overriding. The "freearg" typemap sometimes releases memory allocated
26391 by the "in" typemap. The "argout" typemap sometimes sets values in
26392 function parameters which are passed by reference in Java.</P>
26393 <P> Note that the "in" typemap marshals the JNI type held in the "jni"
26394 typemap to the real C/C++ type and for the opposite direction, the
26395 "out" typemap marshals the real C/C++ type to the JNI type held in the
26396 "jni" typemap. For <A href="#Java_default_non_primitive_typemaps">
26397 non-primitive types</A> the "in" and "out" 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
26411 a = (short)i; /* okay */
26412 a = *(short*)&i; /* breaks aliasing rules */
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 "in" and "out" typemaps for pointers are
26421 %typemap(in) struct Foo * %{
26422 $1 = *(struct Foo **)&$input; /* cast jlong into C ptr */
26424 %typemap(out) struct Bar * %{
26425 *(struct Bar **)&$result = $1; /* cast C ptr into jlong */
26429 struct Bar * FooBar(struct Foo *f);
26432 <P> resulting in the following code which breaks the aliasing rules:</P>
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 ;
26444 arg1 = *(struct Foo **)&jarg1;
26445 result = (struct Bar *)FooBar(arg1);
26446 *(struct Bar **)&jresult = result;
26451 <P> If you are using gcc as your C compiler, you might get a
26452 "dereferencing type-punned pointer will break strict-aliasing rules"
26453 warning about this. Please see <A href="#compiling_dynamic">Compiling a
26454 dynamic module</A> to avoid runtime problems with these strict aliasing
26456 <P> The default code generated by SWIG for the Java module comes from
26457 the typemaps in the "<TT>java.swg</TT>" 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>
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>
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
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>
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>
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>
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
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>
26512 %typemap(typemapname, throws="ExceptionClass1, ExceptionClass2") type { ... }
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 "<A href="#Typemaps">
26518 Typemaps</A>" chapter and the Java specific typemaps listed in <A href="#typemaps_c_to_java_types">
26519 the previous section</A>, barring the "jni", "jtype" and "jstype"
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 "jtype" 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 "javain" 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>$&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 *&</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
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>
26574 %typemap(check) int * %{
26576 SWIG_JavaThrowException(jenv, SWIG_JavaIndexOutOfBoundsException, "Array element error");
26582 <P> If the typemap gets put into a function with void as return, $null
26583 will expand to nothing:</P>
26586 SWIGEXPORT void JNICALL Java_jnifn(...) {
26588 SWIG_JavaThrowException(jenv, SWIG_JavaIndexOutOfBoundsException, "Array element error");
26595 <P> otherwise $null expands to<I> NULL</I></P>
26598 SWIGEXPORT jobject JNICALL Java_jnifn(...) {
26600 SWIG_JavaThrowException(jenv, SWIG_JavaIndexOutOfBoundsException, "Array element error");
26607 <P><B> <TT>$javainput, $jnicall and $owner</TT></B>
26608 <BR> The $javainput special variable is used in "javain" typemaps and
26609 $jnicall and $owner are used in "javaout" 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>
26618 %typemap(javain) Class "Class.getCPtr($javainput)"
26619 %typemap(javain) unsigned short "$javainput"
26620 %typemap(javaout) Class * {
26621 return new Class($jnicall, $owner);
26626 Class * bar(Class cls, unsigned short ush) { return new Class(); };
26630 <P> The generated proxy code is then:</P>
26633 public static Class bar(Class cls, int ush) {
26634 return new Class(exampleJNI.bar(Class.getCPtr(cls), cls, ush), false);
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
26645 %newobject bar(Class cls, unsigned short ush);
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>
26653 public static Class bar(Class cls, int ush) {
26654 return new Class(exampleJNI.bar(Class.getCPtr(cls), cls, ush), true);
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 "javaclassmodifiers" 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
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>
26682 const jclass clazz = (*jenv)->FindClass(jenv, "java/lang/String");
26685 <P> whereas C++ code compilation of the same function call is a member
26686 function call using a class pointer like</P>
26689 const jclass clazz = jenv->FindClass("java/lang/String");
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>
26698 const jclass clazz = JCALL1(FindClass, jenv, "java/lang/String");
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 "1", 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 "1",
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="1") SWIGTYPE "CommonBase"</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
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 "javabody" 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 "public class"</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="delete",
26742 methodmodifiers="public synchronized")</TT>
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
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="delete",
26753 methodmodifiers="public synchronized")</TT></P>
26754 <DIV class="indent"> destructor wrapper - the <TT>delete()</TT> method
26755 (proxy classes only), same as "javadestruct" 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
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 "javagetcptr" and "javaptrconstructormodifiers" were
26771 available. These are deprecated and the "javabody" typemap can be used
26773 <P> In summary the contents of the typemaps make up a proxy class like
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 ...
26788 <P> Note the <TT><I>delete</I>()</TT> methodname and method modifiers
26789 are configurable, see "javadestruct" and "javadestruct_derived"
26790 typemaps above.</P>
26791 <P> The type wrapper class is similar in construction:</P>
26794 [ javaimports typemap ]
26795 [ javaclassmodifiers typemap ] javaclassname extends [ javabase typemap ]
26796 implements [ javainterfaces typemap ] {
26797 [ javabody typemap ]
26798 [ javacode typemap ]
26802 <P>The enum class is also similar in construction:</P>
26805 [ javaimports typemap ]
26806 [ javaclassmodifiers typemap ] javaclassname extends [ javabase typemap ]
26807 implements [ javainterfaces typemap ] {
26808 ... Enum values ...
26809 [ javabody typemap ]
26810 [ javacode typemap ]
26814 <P> The "javaimports" typemap is ignored if the enum class is wrapped by
26815 an inner Java class, that is when wrapping an enum declared within a
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>
26826 %typemap(javabody) SWIGTYPE %{
26827 private long swigCPtr;
26828 protected boolean swigCMemOwn;
26830 public $javaclassname(long cPtr, boolean cMemoryOwn) {
26831 swigCMemOwn = cMemoryOwn;
26835 public static long getCPtr($javaclassname obj) {
26836 return (obj == null) ? 0 : obj.swigCPtr;
26841 <P> The typemap code is the same that is in "<TT>java.swg</TT>", 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 "javabody_derived" 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
26852 %typemap(javabody) SWIGTYPE *, SWIGTYPE &, SWIGTYPE [], SWIGTYPE (CLASS::*) %{
26853 private long swigCPtr;
26855 public $javaclassname(long cPtr, boolean bFutureUse) {
26859 protected $javaclassname() {
26863 public static long getCPtr($javaclassname obj) {
26864 return (obj == null) ? 0 : obj.swigCPtr;
26869 <P> Again this is the same that is in "<TT>java.swg</TT>", barring the
26870 method modifier for <TT>getCPtr</TT>.</P>
26871 <H3><A name="java_directors_typemaps"></A>21.9.10 Director specific
26873 <P> The Java directors feature requires the "javadirectorin",
26874 "javadirectorout", "directorin" and the "directorout" typemaps in order
26875 to work properly. The "javapackage" typemap is an optional typemap used
26876 to identify the Java package path for individual SWIG generated proxy
26878 <P><TT>%typemap(directorin)</TT></P>
26879 <DIV class="indent">
26880 <P> The "directorin" 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 "descriptor" attribute. For example, integers are converted as
26887 %typemap(directorin,descriptor="I") int "$input = (jint) $1;"
26890 <P> <CODE>$input</CODE> is the SWIG name of the JNI temporary variable
26891 passed to Java in the upcall. The <CODE>descriptor="I"</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
26899 %typemap(directorin,descriptor="Ljava/lang/String;") char *
26900 %{ $input = jenv->NewStringUTF($1); %}
26903 <P> User-defined types have the default "descriptor" attribute "<CODE>
26904 L$packagepath/$javaclassname;</CODE>" 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 "method not found" runtime error.</P>
26913 <P><TT>%typemap(directorout)</TT></P>
26914 <DIV class="indent">
26915 <P> The "directorout" 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>
26920 %typemap(directorout) int %{ $result = (int)$input; %}
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>
26928 %typemap(directorout) char * {
26931 $result = (char *)jenv->GetStringUTFChars($input, 0);
26932 if (!$1) return $null;
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 "jtype" typemap) to the Java type used
26942 in the Java module class, proxy classes and type wrapper classes (as
26943 specified in the "jstype" 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>
26949 %typemap(javadirectorin) int "$jniinput"
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>
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 "jstype"
26961 typemap) to the type used in the Java intermediary JNI class (as
26962 specified in the "jtype" 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>
26968 %typemap(javadirectorout) int "$javacall"
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>
26976 <P><TT>%typemap(javapackage)</TT></P>
26977 <DIV class="indent">
26978 <P> The "javapackage" 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.
26984 // class Foo is handled in a different interface file:
26985 %import "Foo.i"
26987 %feature("director") Example;
26994 virtual ~Example();
26995 void ping(Foo *arg1, Bar *arg2);
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 "javapackage" 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>
27007 // class Foo is handled in a different interface file:
27008 %import "Foo.i"
27009 %typemap("javapackage") Foo, Foo *, Foo & "com.wombat.foo";
27010 %feature("director") Example;
27017 virtual ~Example();
27018 void ping(Foo *arg1, Bar *arg2);
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. "<CODE>
27030 TYPE...</CODE>" 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>
27035 %typemap("javapackage") SWIGTYPE, SWIGTYPE *, SWIGTYPE &
27036 "package.for.most.classes";
27038 %define OTHER_PACKAGE_SPEC(TYPE...)
27039 %typemap("javapackage") TYPE, TYPE *, TYPE & "package.for.other.classes";
27042 %define ANOTHER_PACKAGE_SPEC(TYPE...)
27043 %typemap("javapackage") TYPE, TYPE *, TYPE & "package.for.another.set";
27046 OTHER_PACKAGE_SPEC(Package_2_class_one)
27047 ANOTHER_PACKAGE_SPEC(Package_3_class_two)
27051 <P> The basic strategy here is to provide a default package typemap for
27052 the majority of the classes, only providing "javapackage" typemaps for
27053 the exceptions.</P>
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 "<TT>java.swg</TT>" and "<TT>typemaps.i</TT>
27058 " 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 "enums.swg" file should be examined in order to see
27072 the original overridden versions of the typemaps.</P>
27075 %include "enums.swg"
27077 %typemap(javain) enum SWIGTYPE "$javainput.ordinal()"
27078 %typemap(javaout) enum SWIGTYPE {
27079 return $javaclassname.class.getEnumConstants()[$jnicall];
27081 %typemap(javabody) enum SWIGTYPE ""
27084 enum HairType { blonde, ginger, brunette };
27085 void setHair(HairType h);
27086 HairType getHair();
27090 <P> SWIG will generate the following Java enum, which is somewhat
27091 simpler than the default:</P>
27094 public enum HairType {
27101 <P> and the two Java proxy methods will be:</P>
27104 public static void setHair(HairType h) {
27105 exampleJNI.setHair(h.ordinal());
27108 public static HairType getHair() {
27109 return HairType.class.getEnumConstants()[exampleJNI.getHair()];
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 "javain" 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 "javaout" 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 "enums.swg" 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>
27134 %include "std_string.i" // for std::string typemaps
27135 #include <string>
27137 class FileException {
27138 std::string message;
27140 FileException(const std::string& msg) : message(msg) {}
27141 std::string what() {
27147 std::string filename;
27149 SimpleFile(const std::string& filename) : filename(filename) {}
27150 void open() throw(FileException) {
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 "throws" typemap</A> is then used when SWIG encounters an exception
27159 specification. The default generic "throws" typemap looks like this:</P>
27162 %typemap(throws) SWIGTYPE, SWIGTYPE &, SWIGTYPE *, SWIGTYPE [ANY] %{
27163 SWIG_JavaThrowException(jenv, SWIG_JavaRuntimeException,
27164 "C++ $1_type exception thrown");
27169 <P> Basically SWIG will generate a C++ try catch block and the body of
27170 the "throws" 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>
27178 %typemap(throws, throws="java.io.IOException") FileException {
27179 jclass excep = jenv->FindClass("java/io/IOException");
27181 jenv->ThrowNew(excep, $1.what().c_str());
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>
27192 public class SimpleFile {
27194 public void open() throws java.io.IOException { ... }
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>
27207 %typemap(javabase) FileException "java.lang.Exception";
27208 %typemap(javacode) FileException %{
27209 public String getMessage() {
27215 <P> This generates:</P>
27218 public class FileException extends java.lang.Exception {
27220 public String getMessage() {
27224 public FileException(String msg) { ... }
27226 public String what() {
27227 return exampleJNI.FileException_what(swigCPtr, this);
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>
27244 bool calculate(float first, float second);
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>
27253 %typemap(javain) float "$module.CheckForNaN($javainput)"
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("Not a number");
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>
27270 public class example {
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("Not a number");
27281 public static boolean calculate(float first, float second) {
27282 return exampleJNI.calculate(example.CheckForNaN(first), example.CheckForNaN(second));
27287 <P> Note that the "javain" 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 "javain" typemap supports. The "javain"
27293 typemap above could be replaced with the following:</P>
27296 %typemap(javain, pre=" $module.CheckForNaN($javainput);") float "$javainput"
27299 <P> which would modify the <TT>calculate</TT> function to instead be
27303 public class example {
27305 public static boolean calculate(float first, float second) {
27306 example.CheckForNaN(first);
27307 example.CheckForNaN(second);
27309 return exampleJNI.calculate(first, second);
27315 <P> See the <A href="#java_date_marshalling">Date marshalling example</A>
27316 for an example using further "javain" 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>
27326 %typemap(javain, throws="java.lang.Exception") float "$module.CheckForNaN($javainput)"
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("Not a number");
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>
27344 public class example {
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("Not a number");
27355 public static boolean calculate(float first, float second) throws java.lang.Exception {
27356 return exampleJNI.calculate(example.CheckForNaN(first), example.CheckForNaN(second));
27361 <P> If we were a martyr to the JNI cause, we could replace the succinct
27362 code within the "javain" typemap with a few pages of JNI code. If we
27363 had, we would have put it in the "in" 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>
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) {
27379 size = (*jenv)->GetArrayLength(jenv, $input);
27380 $1 = (char **) malloc((size+1)*sizeof(char *));
27381 /* make a copy of each string */
27382 for (i = 0; i<size; i++) {
27383 jstring j_string = (jstring)(*jenv)->GetObjectArrayElement(jenv, $input, i);
27384 const char * c_string = (*jenv)->GetStringUTFChars(jenv, j_string, 0);
27385 $1[i] = malloc((strlen(c_string)+1)*sizeof(char));
27386 strcpy($1[i], c_string);
27387 (*jenv)->ReleaseStringUTFChars(jenv, j_string, c_string);
27388 (*jenv)->DeleteLocalRef(jenv, j_string);
27393 /* This cleans up the memory we malloc'd before the function call */
27394 %typemap(freearg) char ** {
27396 for (i=0; i<size$argnum-1; i++)
27401 /* This allows a C function to return a char ** as a Java String array */
27402 %typemap(out) char ** {
27405 jstring temp_string;
27406 const jclass clazz = (*jenv)->FindClass(jenv, "java/lang/String");
27408 while ($1[len]) len++;
27409 jresult = (*jenv)->NewObjectArray(jenv, len, clazz, NULL);
27410 /* exception checking omitted */
27412 for (i=0; i<len; i++) {
27413 temp_string = (*jenv)->NewStringUTF(jenv, *result++);
27414 (*jenv)->SetObjectArrayElement(jenv, jresult, i, temp_string);
27415 (*jenv)->DeleteLocalRef(jenv, temp_string);
27419 /* These 3 typemaps tell SWIG what JNI and Java types to use */
27420 %typemap(jni) char ** "jobjectArray"
27421 %typemap(jtype) char ** "String[]"
27422 %typemap(jstype) char ** "String[]"
27424 /* These 2 typemaps handle the conversion of the jtype to jstype typemap type
27426 %typemap(javain) char ** "$javainput"
27427 %typemap(javaout) char ** {
27431 /* Now a few test functions */
27434 int print_args(char **argv) {
27437 printf("argv[%d] = %s\n", i, argv[i]);
27443 char **get_args() {
27444 static char *values[] = { "Dave", "Mike", "Susan", "John", "Michelle", 0};
27445 return &values[0];
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>
27459 public class runme {
27463 System.loadLibrary("example");
27464 } catch (UnsatisfiedLinkError e) {
27465 System.err.println("Native code library failed to load. " + e);
27470 public static void main(String argv[]) {
27471 String animals[] = {"Cat","Dog","Cow","Goat"};
27472 example.print_args(animals);
27473 String args[] = example.get_args();
27474 for (int i=0; i<args.length; i++)
27475 System.out.println(i + ":" + args[i]);
27480 <P> When compiled and run we get:</P>
27495 <P> In the example, a few different typemaps are used. The "in" 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 "freearg" typemap is used to later release this memory after the
27499 execution of the C function. The "out" typemap is used for function
27500 return values. Lastly the "jni", "jtype" and "jstype" 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>
27508 int foo(int argc, char **argv);
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>
27516 example.foo(4, new String[]{"red", "green", "blue", "white"});
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>
27525 %typemap(in) (int argc, char **argv) {
27527 $1 = (*jenv)->GetArrayLength(jenv, $input);
27528 $2 = (char **) malloc(($1+1)*sizeof(char *));
27529 /* make a copy of each string */
27530 for (i = 0; i<$1; i++) {
27531 jstring j_string = (jstring)(*jenv)->GetObjectArrayElement(jenv, $input, i);
27532 const char * c_string = (*jenv)->GetStringUTFChars(jenv, j_string, 0);
27533 $2[i] = malloc((strlen(c_string)+1)*sizeof(char));
27534 strcpy($2[i], c_string);
27535 (*jenv)->ReleaseStringUTFChars(jenv, j_string, c_string);
27536 (*jenv)->DeleteLocalRef(jenv, j_string);
27541 %typemap(freearg) (int argc, char **argv) {
27543 for (i=0; i<$1-1; i++)
27548 %typemap(jni) (int argc, char **argv) "jobjectArray"
27549 %typemap(jtype) (int argc, char **argv) "String[]"
27550 %typemap(jstype) (int argc, char **argv) "String[]"
27552 %typemap(javain) (int argc, char **argv) "$javainput"
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>
27564 example.foo(new String[]{"red", "green", "blue", "white"});
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>
27584 /* Returns a status value and two values in out1 and out2 */
27585 int spam(double a, double b, double *out1, double *out2);
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>
27595 /* Define a new structure to use instead of double * */
27604 /* Returns a status value and two values in out1 and out2 */
27605 int spam(double a, double b, double *out1, double *out2) {
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.
27618 %typemap(in) double *OUTVALUE {
27619 jclass clazz = jenv->FindClass("MyDouble");
27620 jfieldID fid = jenv->GetFieldID(clazz, "swigCPtr", "J");
27621 jlong cPtr = jenv->GetLongField($input, fid);
27622 MyDouble *pMyDouble = NULL;
27623 *(MyDouble **)&pMyDouble = *(MyDouble **)&cPtr;
27624 $1 = &pMyDouble->value;
27627 %typemap(jtype) double *OUTVALUE "MyDouble"
27628 %typemap(jstype) double *OUTVALUE "MyDouble"
27629 %typemap(jni) double *OUTVALUE "jobject"
27631 %typemap(javain) double *OUTVALUE "$javainput"
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);
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 "in"
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>
27650 // File: runme.java
27652 public class runme {
27656 System.loadLibrary("example");
27657 } catch (UnsatisfiedLinkError e) {
27658 System.err.println("Native code library failed to load. " + e);
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 + " " + out1.getValue() + " " + out2.getValue());
27672 <P> When compiled and run we get:</P>
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>
27686 %include "std_string.i"
27688 #include <iostream>
27689 using namespace std;
27692 virtual void start() = 0;
27696 class Ambulance : public Vehicle {
27699 Ambulance(string volume) : vol(volume) {}
27700 virtual void start() {
27701 cout << "Ambulance started" << endl;
27703 void sound_siren() {
27704 cout << vol << " siren sounded!" << endl;
27709 Vehicle *vehicle_factory() {
27710 return new Ambulance("Very loud");
27714 <P> If we execute the following Java code:</P>
27717 Vehicle vehicle = example.vehicle_factory();
27720 Ambulance ambulance = (Ambulance)vehicle;
27721 ambulance.sound_siren();
27728 java.lang.ClassCastException
27729 at runme.main(runme.java:16)
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>
27744 %exception Ambulance::dynamic_cast(Vehicle *vehicle) {
27747 jclass excep = jenv->FindClass("java/lang/ClassCastException");
27749 jenv->ThrowNew(excep, "dynamic_cast exception");
27753 %extend Ambulance {
27754 static Ambulance *dynamic_cast(Vehicle *vehicle) {
27755 return dynamic_cast<Ambulance *>(vehicle);
27760 <P> It would then be used from Java like this</P>
27763 Ambulance ambulance = Ambulance.dynamic_cast(vehicle);
27764 ambulance.sound_siren();
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>
27773 %typemap(out) Vehicle * {
27774 Ambulance *downcast = dynamic_cast<Ambulance *>($1);
27775 *(Ambulance **)&$result = downcast;
27778 %typemap(javaout) Vehicle * {
27779 return new Ambulance($jnicall, $owner);
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>
27792 class FireEngine : public Vehicle {
27795 virtual void start() {
27796 cout << "FireEngine started" << endl;
27798 void roll_out_hose() {
27799 cout << "Hose rolled out" << endl;
27803 Vehicle *vehicle_factory(int vehicle_number) {
27804 if (vehicle_number == 0)
27805 return new Ambulance("Very loud");
27807 return new FireEngine();
27811 <P> To be able to downcast with this sort of Java code:</P>
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();
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>
27826 %typemap(jni) Vehicle *vehicle_factory "jobject"
27827 %typemap(jtype) Vehicle *vehicle_factory "Vehicle"
27828 %typemap(jstype) Vehicle *vehicle_factory "Vehicle"
27829 %typemap(javaout) Vehicle *vehicle_factory {
27833 %typemap(out) Vehicle *vehicle_factory {
27834 Ambulance *ambulance = dynamic_cast<Ambulance *>($1);
27835 FireEngine *fireengine = dynamic_cast<FireEngine *>($1);
27837 // call the Ambulance(long cPtr, boolean cMemoryOwn) constructor
27838 jclass clazz = jenv->FindClass("Ambulance");
27840 jmethodID mid = jenv->GetMethodID(clazz, "<init>", "(JZ)V");
27843 *(Ambulance **)&cptr = ambulance;
27844 $result = jenv->NewObject(clazz, mid, cptr, false);
27847 } else if (fireengine) {
27848 // call the FireEngine(long cPtr, boolean cMemoryOwn) constructor
27849 jclass clazz = jenv->FindClass("FireEngine");
27851 jmethodID mid = jenv->GetMethodID(clazz, "<init>", "(JZ)V");
27854 *(FireEngine **)&cptr = fireengine;
27855 $result = jenv->NewObject(clazz, mid, cptr, false);
27860 cout << "Unexpected type " << endl;
27864 cout << "Failed to create new java object" << endl;
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>
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);
27895 public int hashCode() {
27896 return (int)getPointer();
27901 Foo* returnFoo(Foo *foo) { return foo; }
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>
27909 Foo foo1 = new Foo();
27910 Foo foo2 = example.returnFoo(foo1);
27911 System.out.println("foo1? " + foo1.equals(foo2));
27914 <H3><A name="void_pointers"></A>21.10.9 Void pointers and a common Java
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
27931 %typemap(javabase) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE [],
27932 SWIGTYPE (CLASS::*) "SWIG"
27934 %typemap(javacode) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE [],
27935 SWIGTYPE (CLASS::*) %{
27936 protected long getPointer() {
27942 <P> Define new base class called SWIG:</P>
27945 public abstract class SWIG {
27946 protected abstract long getPointer();
27948 public boolean equals(Object obj) {
27949 boolean equal = false;
27950 if (obj instanceof SWIG)
27951 equal = (((SWIG)obj).getPointer() == this.getPointer());
27955 SWIGTYPE_p_void getVoidPointer() {
27956 return new SWIGTYPE_p_void(getPointer(), false);
27961 <P> This example contains some useful functionality which you may want
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>
27971 <H3><A name="struct_pointer_pointer"></A>21.10.10 Struct pointer to
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>
27979 int hoursAvailable;
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);
27989 <P> C code implementation:</P>
27992 int HireButler(Butler **ppButler) {
27993 Butler *pButler = (Butler *)malloc(sizeof(Butler));
27994 pButler->hoursAvailable = 24;
27995 pButler->greeting = (char *)malloc(32);
27996 strcpy(pButler->greeting, "At your service Sir");
27997 *ppButler = pButler;
28000 void FireButler(Butler *pButler) {
28001 free(pButler->greeting);
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>
28011 Butler jeeves = new Butler();
28012 example.HireButler(jeeves);
28013 System.out.println("Greeting: " + jeeves.getGreeting());
28014 System.out.println("Availability: " + jeeves.getHoursAvailable() + " hours per day");
28015 example.FireButler(jeeves);
28018 <P> Resulting in the following output when run:</P>
28019 <DIV class="shell">
28021 Greeting: At your service Sir
28022 Availability: 24 hours per day
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>
28036 // Do not generate the default proxy constructor or destructor
28037 %nodefaultctor Butler;
28038 %nodefaultdtor Butler;
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 */
28048 // Type typemaps for marshalling Butler **
28049 %typemap(jni) Butler ** "jobject"
28050 %typemap(jtype) Butler ** "Butler"
28051 %typemap(jstype) Butler ** "Butler"
28053 // Typemaps for Butler ** as a parameter output type
28054 %typemap(in) Butler ** (Butler *ppButler = 0) %{
28055 $1 = &ppButler;
28057 %typemap(argout) Butler ** {
28058 // Give Java proxy the C pointer (of newly created object)
28059 jclass clazz = (*jenv)->FindClass(jenv, "Butler");
28060 jfieldID fid = (*jenv)->GetFieldID(jenv, clazz, "swigCPtr", "J");
28062 *(Butler **)&cPtr = *$1;
28063 (*jenv)->SetLongField(jenv, $input, fid, cPtr);
28065 %typemap(javain) Butler ** "$javainput"
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
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>
28087 Butler jeeves = new Butler();
28088 System.out.println("Greeting: " + jeeves.getGreeting());
28089 System.out.println("Availability: " + jeeves.getHoursAvailable() + " hours per day");
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>
28100 // Don't expose the memory allocation/de-allocation functions
28101 %ignore FireButler(Butler *pButler);
28102 %ignore HireButler(Butler **ppButler);
28104 // Add in a custom proxy constructor and destructor
28107 Butler *pButler = 0;
28108 HireButler(&pButler);
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
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>
28134 Wheel(int sz) : size(sz) {}
28140 Bike(int val) : wheel(val) {}
28141 Wheel& getWheel() { return wheel; }
28145 <P> and the following usage from Java after running the code through
28149 Wheel wheel = new Bike(10).getWheel();
28150 System.out.println("wheel size: " + wheel.getSize());
28151 // Simulate a garbage collection
28153 System.runFinalization();
28154 System.out.println("wheel size: " + wheel.getSize());
28157 <P> Don't be surprised that if the resulting output gives strange
28158 results such as...</P>
28159 <DIV class="shell">
28162 wheel size: 135019664
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>
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;
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& getWheel {
28187 long cPtr = $jnicall;
28188 $javaclassname ret = null;
28190 ret = new $javaclassname(cPtr, $owner);
28191 ret.addReference(this);
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>
28202 public class Wheel {
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;
28211 public class Bike {
28213 public Wheel getWheel() {
28214 long cPtr = exampleJNI.Bike_getWheel(swigCPtr, this);
28217 ret = new Wheel(cPtr, false);
28218 ret.addReference(this);
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>
28237 Element(int val) : value(val) {}
28242 Container() : element(0) {}
28243 void setElement(Element* e) { element = e; }
28244 Element* getElement() { return element; }
28248 <P> and usage from C++</P>
28251 Container container;
28252 Element element(20);
28253 container.setElement(&element);
28254 cout << "element.value: " << container.getElement()->value << endl;
28257 <P> and more or less equivalent usage from Java</P>
28260 Container container = new Container();
28261 container.setElement(new Element(20));
28262 System.out.println("element value: " + container.getElement().getValue());
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>
28270 Container container = new Container();
28271 container.setElement(new Element(20));
28272 // Simulate a garbage collection
28274 System.runFinalization();
28275 System.out.println("element value: " + container.getElement().getValue());
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>
28285 public class Container {
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);
28297 public void setElement(Element e) {
28298 exampleJNI.Container_setElement(swigCPtr, this, getCPtrAndAddReference(e), e);
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>
28309 %typemap(javain) Element *e "getCPtrAndAddReference($javainput)"
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);
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 "javain" 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 "javain" 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>
28336 CDate(int year, int month, int day);
28343 static int doSomething(const CDate &dateIn, CDate &dateOut);
28344 Action(const CDate &date, CDate &dateOut);
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>
28354 public class Action {
28356 public static int doSomething(CDate dateIn, CDate dateOut) {
28357 return exampleJNI.Action_doSomething(CDate.getCPtr(dateIn), dateIn,
28358 CDate.getCPtr(dateOut), dateOut);
28361 public Action(CDate date, CDate dateOut) {
28362 this(exampleJNI.new_Action(CDate.getCPtr(date), date,
28363 CDate.getCPtr(dateOut), dateOut), true);
28368 <P> The <TT>CDate &</TT> and <TT>const CDate &</TT> Java code is
28369 generated from the following two default typemaps:</P>
28372 %typemap(jstype) SWIGTYPE & "$javaclassname"
28373 %typemap(javain) SWIGTYPE & "$javaclassname.getCPtr($javainput)"
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>
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();
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);
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>
28399 %typemap(jstype) const CDate& "java.util.GregorianCalendar"
28401 pre=" CDate temp$javainput = new CDate($javainput.get(java.util.Calendar.YEAR), "
28402 "$javainput.get(java.util.Calendar.MONTH), $javainput.get(java.util.Calendar.DATE));",
28403 pgcppname="temp$javainput") const CDate &
28404 "$javaclassname.getCPtr(temp$javainput)"
28406 %typemap(jstype) CDate& "java.util.Calendar"
28408 pre=" CDate temp$javainput = new CDate($javainput.get(java.util.Calendar.YEAR), "
28409 "$javainput.get(java.util.Calendar.MONTH), $javainput.get(java.util.Calendar.DATE));",
28410 post=" $javainput.set(temp$javainput.getYear(), temp$javainput.getMonth(), "
28411 "temp$javainput.getDay(), 0, 0, 0);",
28412 pgcppname="temp$javainput") CDate &
28413 "$javaclassname.getCPtr(temp$javainput)"
28416 <P> The resulting generated proxy code in the <TT>Action</TT> class
28420 public class Action {
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));
28431 return exampleJNI.Action_doSomething(CDate.getCPtr(tempdateIn), tempdateIn,
28432 CDate.getCPtr(tempdateOut), tempdateOut);
28434 dateOut.set(tempdateOut.getYear(), tempdateOut.getMonth(), tempdateOut.getDay(), 0, 0, 0);
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));
28447 return exampleJNI.new_Action(CDate.getCPtr(tempdate), tempdate,
28448 CDate.getCPtr(tempdateOut), tempdateOut);
28450 dateOut.set(tempdateOut.getYear(), tempdateOut.getMonth(), tempdateOut.getDay(), 0, 0, 0);
28454 public Action(java.util.GregorianCalendar date, java.util.Calendar dateOut) {
28455 this(Action.SwigConstructAction(date, dateOut), true);
28460 <P> A few things to note:</P>
28462 <LI> The "javatype" 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 "javaout" typemap.</LI>
28474 <LI> The temporary variables in the "javain" typemaps are called <TT>
28475 temp$javain</TT>, where "$javain" is replaced with the parameter name.
28476 "$javain" is used to mangle the variable name so that more than one <TT>
28477 CDate &</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 "javain" 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>
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>
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
28494 <P> Open up the C++ wrapper source code file and look for <CODE>
28495 "method_foo"</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 "javapackage" typemap in your
28499 SWIG interface file.</P>
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
28504 <P> Use the template's renamed name as the argument to the "javapackage"
28508 %typemap(javapackage) std::vector<int> "your.package.here"
28509 %template(VectorOfInt) std::vector<int>;
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>
28520 public static void MyClass_method_upcall(MyClass self, long jarg1)
28522 Foo darg1 = new Foo(jarg1, false);
28524 self.method_upcall(darg1);
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>
28537 public static void MyClass_method_upcall(MyClass self, long jarg1,
28540 Foo darg1 = (jarg1_object != null ? jarg1_object : new Foo(jarg1, false));
28542 self.method_upcall(darg1);
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("director")</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 "type symmetry" 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
28564 public static Foo javaObjectFoo(Foo obj);
28567 <P> From your code, this method is invoked as follows:</P>
28570 public class MyClassDerived {
28571 public void method_upcall(Foo foo_object)
28573 FooDerived derived = (foo_object != null ?
28574 (FooDerived) Foo.downcastFoo(foo_object) : null);
28575 /* rest of your code here */
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,
28585 public class FooDerived extends Foo {
28587 public static FooDerived downcastFooDerived(Foo foo_object)
28590 return (foo_object != null ? (FooDerived) Foo.downcastFoo(foo_object);
28593 catch (ClassCastException exc) {
28594 // Wasn't a FooDerived object, some other subclass of Foo
28601 <P> Then change the code in MyClassDerived as follows:</P>
28604 public class MyClassDerived extends MyClass {
28606 public void method_upcall(Foo foo_object)
28608 FooDerived derived = FooDerived.downcastFooDerived(foo_object);
28609 /* rest of your code here */
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>
28623 public abstract class UserVisibleFoo extends Foo {
28624 /** Make sure user overrides this method, it's where the upcall
28627 public abstract void method_upcall(Foo foo_object);
28629 /// Downcast from Foo to UserVisibleFoo
28630 public static UserVisibleFoo downcastUserVisibleFoo(Foo foo_object)
28633 return (foo_object != null ? (FooDerived) Foo.downcastFoo(foo_object) : null);
28636 catch (ClassCastException exc) {
28637 // Wasn't a FooDerived object, some other subclass of Foo
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>
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 "javaimports" 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>
28664 %javamethodmodifiers Barmy::lose_marbles() "
28666 * Calling this method will make you mad.
28667 * Use with <b>utmost</b> caution.
28671 %typemap(javaimports) Barmy "
28672 /** The crazy class. Use as a last resort. */"
28676 void lose_marbles() {}
28680 <P> Note the "public" 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>
28685 /** The crazy class. Use as a last resort. */
28686 public class Barmy {
28689 * Calling this method will make you mad.
28690 * Use with <b>utmost</b> caution.
28692 public void lose_marbles() {
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>
28713 int spam(int num, Foo* foo);
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>
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) {...}
28733 <P> This approach is not nearly as natural as using proxy classes as the
28734 functions need to be used like this:</P>
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);
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
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>
28760 %native (HandRolled) void HandRolled(int, char *);
28762 JNIEXPORT void JNICALL Java_packageName_moduleName_HandRolled(JNIEnv *, jclass,
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>
28773 public final static native void HandRolled(int jarg1, String jarg2);
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>
28780 public static void HandRolled(int arg0, String arg1) {
28781 exampleJNI.HandRolled(arg0, arg1);
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 "jtype", "jstype",
28788 "javain" and "javaout" 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>
28807 %typemap(javafinalize) SWIGTYPE ""
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>
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>
28843 <H1><A name="Lisp_nn1"></A>22 SWIG and Common Lisp</H1>
28846 <DIV class="sectiontoc">
28848 <LI><A href="#Lisp_nn2">Allegro Common Lisp</A></LI>
28849 <LI><A href="#Lisp_nn3">Common Foreign Function Interface(CFFI)</A>
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>
28857 <LI><A href="#Lisp_nn8">CLISP</A>
28859 <LI><A href="#Lisp_nn9">Additional Commandline Options</A></LI>
28860 <LI><A href="#Lisp_nn10">Details on CLISP bindings</A></LI>
28863 <LI><A href="#Lisp_nn11">UFFI</A></LI>
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">
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
28886 <P> To run the cffi module of SWIG requires very little effort, you just
28890 swig -cffi -module <I>module-name</I> <I>file-name</I>
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>
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
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
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>
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">
28927 #define x (y >> 1)
28938 struct bar * my_struct;
28942 struct foo * b[100];
28946 int pointer_func(void (*ClosureFun)( void* _fun, void* _data, void* _evt ), int p);
28948 int func123(div_t * p,int **q[100],int r[][1000][10]);
28950 void lispsort_double (int n, double * array);
28952 enum color { RED, BLUE, GREEN};
28954 </DIV> Corresponding to this we will write a simple interface file:<DIV class="code">
28958 %include "test.h"
28961 </DIV> The generated SWIG Code will be:<DIV class="targetlang">
28963 ;;;SWIG wrapper code starts here
28965 (cl:defmacro defanonenum (&body enums)
28966 "Converts anonymous enums to defconstants."
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))))
28973 (cl:eval-when (:compile-toplevel :load-toplevel)
28974 (cl:unless (cl:fboundp 'swig-lispify)
28975 (cl:defun swig-lispify (name flag cl:&optional (package cl:*package*))
28976 (cl:labels ((helper (lst last rest cl:&aux (c (cl:car lst)))
28980 ((cl:upper-case-p c)
28981 (helper (cl:cdr lst) 'upper
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
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)))
28995 (cl:error "Invalid character: ~A" c)))))
28996 (cl:let ((fix (cl:case flag
28997 ((constant enumvalue) "+")
28998 (variable "*")
28999 (cl:t ""))))
29004 (cl:nreverse (helper (cl:concatenate 'cl:list name) cl:nil cl:nil))
29008 ;;;SWIG wrapper code ends here
29011 (cl:defconstant y 5)
29013 (cl:defconstant x (cl:ash 5 -1))
29015 (cffi:defcstruct bar
29023 (cffi:defcvar ("my_struct" my_struct)
29026 (cffi:defcstruct foo
29030 (cffi:defcfun ("pointer_func" pointer_func) :int
29031 (ClosureFun :pointer)
29034 (cffi:defcfun ("func123" func123) :int
29039 (cffi:defcfun ("lispsort_double" lispsort_double) :void
29043 (cffi:defcenum color
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 "div_t*" is changed to Lisp type ":my-pointer", we lispify all
29063 names, export everything, and do some more stuff.</P>
29068 %typemap(cin) div_t* ":my-pointer";
29070 %feature("intern_function","1");
29071 %feature("export");
29073 %feature("inline") lispsort_double;
29075 %feature("intern_function", "my-lispify") lispsort_double;
29076 %rename func123 renamed_cool_func;
29077 %ignore "pointer_func";
29079 %include "test.h"
29083 <P> The<I> typemap(cin)</I> ensures that for all arguments which are
29084 input to C with the type "div_t*", the ":my-pointer" 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 "1" given to the
29089 feature is optional. The use of feature like<I>
29090 %feature("intern_function","1");</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("intern_function", "my-lispify") lispsort_double;</I>, here we
29094 are using an additional feature which allows us to use our lispify
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">
29106 (cl:defconstant #.(swig-lispify "y" 'constant) 5)
29108 (cl:export '#.(swig-lispify "y" 'constant))
29110 (cl:defconstant #.(swig-lispify "x" 'constant) (cl:ash 5 -1))
29112 (cl:export '#.(swig-lispify "x" 'constant))
29114 (cffi:defcstruct #.(swig-lispify "bar" 'classname)
29115 (#.(swig-lispify "p" 'slotname) :short)
29116 (#.(swig-lispify "q" 'slotname) :short)
29117 (#.(swig-lispify "a" 'slotname) :char)
29118 (#.(swig-lispify "b" 'slotname) :char)
29119 (#.(swig-lispify "z" 'slotname) :pointer)
29120 (#.(swig-lispify "n" 'slotname) :pointer))
29122 (cl:export '#.(swig-lispify "bar" 'classname))
29124 (cl:export '#.(swig-lispify "p" 'slotname))
29126 (cl:export '#.(swig-lispify "q" 'slotname))
29128 (cl:export '#.(swig-lispify "a" 'slotname))
29130 (cl:export '#.(swig-lispify "b" 'slotname))
29132 (cl:export '#.(swig-lispify "z" 'slotname))
29134 (cl:export '#.(swig-lispify "n" 'slotname))
29136 (cffi:defcvar ("my_struct" #.(swig-lispify "my_struct" 'variable))
29139 (cl:export '#.(swig-lispify "my_struct" 'variable))
29141 (cffi:defcstruct #.(swig-lispify "foo" 'classname)
29142 (#.(swig-lispify "a" 'slotname) :int)
29143 (#.(swig-lispify "b" 'slotname) :pointer))
29145 (cl:export '#.(swig-lispify "foo" 'classname))
29147 (cl:export '#.(swig-lispify "a" 'slotname))
29149 (cl:export '#.(swig-lispify "b" 'slotname))
29151 (cffi:defcfun ("renamed_cool_func" #.(swig-lispify "renamed_cool_func" 'function)) :int
29156 (cl:export '#.(swig-lispify "renamed_cool_func" 'function))
29158 (cl:declaim (cl:inline #.(my-lispify "lispsort_double" 'function)))
29160 (cffi:defcfun ("lispsort_double" #.(my-lispify "lispsort_double" 'function)) :void
29164 (cl:export '#.(my-lispify "lispsort_double" 'function))
29166 (cffi:defcenum #.(swig-lispify "color" 'enumname)
29167 #.(swig-lispify "RED" 'enumvalue :keyword)
29168 #.(swig-lispify "BLUE" 'enumvalue :keyword)
29169 #.(swig-lispify "GREEN" 'enumvalue :keyword))
29171 (cl:export '#.(swig-lispify "color" 'enumname))
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
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 "%{" and "%}" as shown below.</P>
29188 #include "Test/test.h"
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 "import" directive. The
29196 "include" directive specifies the target file for which wrapper code
29197 will be generated.</P>
29201 %import "ancillary/header.h"
29203 %include "target/header.h"
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">
29209 namespace OpenDemo {
29215 Test (void) {x = 0;}
29216 Test (float X) {x = X;}
29219 Test operator+ (const Test& v) const {return Test (x+v.x);}
29222 float lengthSquared (void) const {return this->dot (*this);}
29224 static float distance (const Test& a, const Test& b){return(a-b).length();}
29226 inline Test parallelComponent (const Test& unitBasis) const {
29227 return unitBasis * projection;
29230 Test setYtoZero (void) const {return Test (this->x);}
29232 static const Test zero;
29236 inline Test operator* (float s, const Test& v) {return v*s;}
29239 inline std::ostream& operator<< (std::ostream& o, const Test& v)
29241 return o << "(" << v.x << ")";
29245 inline Test RandomUnitVectorOnXZPlane (void)
29247 return RandomVectorInUnitRadiusSphere().setYtoZero().normalize();
29252 <P>The interface used is:</P>
29256 %include "test.cpp"
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">
29261 (cffi:defcfun ("_wrap_Test_x_set" Test_x_set) :void
29265 (cffi:defcfun ("_wrap_Test_x_get" Test_x_get) :float
29268 (cffi:defcfun ("_wrap_new_Test__SWIG_0" new_Test) :pointer)
29270 (cffi:defcfun ("_wrap_new_Test__SWIG_1" new_Test) :pointer
29273 (cffi:defcfun ("_wrap_Test___add__" Test___add__) :pointer
29277 (cffi:defcfun ("_wrap_Test_lengthSquared" Test_lengthSquared) :float
29280 (cffi:defcfun ("_wrap_Test_distance" Test_distance) :float
29284 (cffi:defcfun ("_wrap_Test_parallelComponent" Test_parallelComponent) :pointer
29286 (unitBasis :pointer))
29288 (cffi:defcfun ("_wrap_Test_setYtoZero" Test_setYtoZero) :pointer
29291 (cffi:defcvar ("Test_zero" Test_zero)
29294 (cffi:defcfun ("_wrap_delete_Test" delete_Test) :void
29297 (cffi:defcfun ("_wrap___mul__" __mul__) :pointer
29301 (cffi:defcfun ("_wrap___lshift__" __lshift__) :pointer
29305 (cffi:defcfun ("_wrap_RandomUnitVectorOnXZPlane" RandomUnitVectorOnXZPlane) :pointer)
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">
29313 (clos:defclass test()
29314 ((ff :reader ff-pointer)))
29316 (clos:defmethod (cl:setf x) (arg0 (obj test))
29317 (Test_x_set (ff-pointer obj) arg0))
29319 (clos:defmethod x ((obj test))
29320 (Test_x_get (ff-pointer obj)))
29322 (cl:shadow "+")
29323 (clos:defmethod + ((obj test) (self test) (v test))
29324 (Test___add__ (ff-pointer obj) (ff-pointer self) (ff-pointer v)))
29326 (clos:defmethod length-squared ((obj test) (self test))
29327 (Test_lengthSquared (ff-pointer obj) (ff-pointer self)))
29329 (clos:defmethod parallel-component ((obj test) (self test) (unitBasis test))
29330 (Test_parallelComponent (ff-pointer obj) (ff-pointer self) (ff-pointer unitBasis)))
29332 (clos:defmethod set-yto-zero ((obj test) (self test))
29333 (Test_setYtoZero (ff-pointer obj) (ff-pointer self)))
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 "[CFFI]" tag in the subject line.</P>
29342 <H3><A name="Lisp_nn7"></A>22.2.4 Inserting user code into generated
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 "header.h"</TT> directive. This can be
29348 done using the SWIG <TT>%insert(section) %{ ...code... %}</TT>
29355 #include "header.h"
29358 %include "header.h"
29363 <P> Additional sections have been added for inserting into the generated
29364 lisp interface file:</P>
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>
29370 <P> Note that the block <TT>%{ ... %}</TT> is effectively a shortcut for
29371 <TT>%insert("header") %{ ... %}</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>
29385 swig -clisp -module <I>module-name</I> <I>file-name</I>
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>
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>
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">
29425 (:use :common-lisp :ffi)
29442 (default-foreign-language :stdc)
29445 <P> The ffi wrappers for functions and variables are generated as shown
29446 below. When functions have arguments of type "double * array", 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 "int **z[100]" 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>
29455 extern "C" {
29456 int pointer_func(void (*ClosureFun)( void* _fun, void* _data, void* _evt ), int y);
29458 int func123(div_t * x,int **z[100],int y[][1000][10]);
29460 void lispsort_double (int n, double * array);
29462 void test123(float x , double y);
29466 </DIV><DIV class="targetlang">
29468 (ffi:def-call-out pointer_func
29469 (:name "pointer_func")
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)))
29475 (:return-type ffi:int)
29476 (:library +library-name+))
29478 (ffi:def-call-out func123
29479 (:name "func123")
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+))
29487 (ffi:def-call-out lispsort_double
29488 (:name "lispsort_double")
29489 (:arguments (n ffi:int)
29490 (array (ffi:c-ptr DOUBLE-FLOAT)))
29492 (:library +library-name+))
29494 (ffi:def-call-out test123
29495 (:name "test")
29496 (:arguments (x SINGLE-FLOAT)
29499 (:library +library-name+))
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>
29517 </DIV><DIV class="targetlang">
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)))
29527 (defconstant max 1000)
29531 <H2><A name="Lisp_nn11"></A>22.4 UFFI</H2>
29533 <H1><A name="Lua_nn1"></A>23 SWIG and Lua</H1>
29536 <DIV class="sectiontoc">
29538 <LI><A href="#Lua_nn2">Preliminaries</A></LI>
29539 <LI><A href="#Lua_nn3">Running SWIG</A>
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>
29546 <LI><A href="#Lua_nn7">A tour of basic C/C++ wrapping</A>
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>
29565 <LI><A href="#Lua_nn23">Typemaps</A>
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>
29573 <LI><A href="#Lua_nn28">Writing typemaps</A>
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>
29579 <LI><A href="#Lua_nn31">Customization of your Bindings</A>
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>
29585 <LI><A href="#Lua_nn34">Details on the Lua binding</A>
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>
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 <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>
29620 #include "example.h"
29622 int gcd(int x, int y);
29626 <P> To build a Lua module, run SWIG using the <TT>-lua</TT> option.</P>
29627 <DIV class="shell">
29629 $ swig -lua example.i
29632 <P> If building a C++ extension, add the <TT>-c++</TT> option:</P>
29633 <DIV class="shell">
29635 $ swig -c++ -lua example.i
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 "int luaopen_example(lua_State* L)"</TT> which must be called to
29647 register the module with the Lua interpreter. The name
29648 "luaopen_example" 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
29655 #include <stdio.h>
29656 #include "lua.h"
29657 #include "lualib.h"
29658 #include "lauxlib.h"
29660 extern int luaopen_example(lua_State* L); // declare the wrapped module
29662 int main(int argc,char* argv[])
29667 printf("%s: <filename.lua>\n",argv[0]);
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);
29676 printf("unable to load %s\n",argv[1]);
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 & add a <TT>#define LUA_EXTRALIBS
29685 {"example",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">
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
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 & 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">
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
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">
29714 require("example")
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">
29725 my_init=loadlib("example.so","luaopen_example") -- for Unix/Linux
29726 --my_init=loadlib("example.dll","luaopen_example") -- for Windows
29727 assert(my_init) -- name sure its not nil
29728 my_init() -- call the init fn of the lib
29731 <P> Or can be done in a single line of Lua code</P>
29732 <DIV class="targetlang">
29734 assert(loadlib("example.so","luaopen_example"))()
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">
29743 a,b,c=package.loadlib("example.so","luaopen_example") -- for Unix/Linux
29744 --a,b,c=package.loadlib("example.dll","luaopen_example") -- for Windows
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
29753 <DIV class="targetlang">
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
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">
29777 > print(example.gcd(4,6))
29779 > print(example.Foo)
29782 > print(example.Foo)
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
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
29803 int fact(int n);</PRE>
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">
29809 > print example.fact(4)
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">
29821 > for k,v in pairs(example) do _G[k]=v end
29822 > print(fact(4))
29827 <P> It is also possible to rename the module with an assignment.</P>
29828 <DIV class="targetlang">
29831 > print(e.fact(4))
29833 > print(example.fact(4))
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>
29842 <PRE>%module example
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">
29854 > print(example.Foo)
29856 > c=example.Foo -- c is a COPY of example.Foo, not the same thing
29860 > c=5 -- this will not effect the original example.Foo
29861 > print(example.Foo,c)
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">
29871 > -- e and example are the same table
29872 > -- so e.Foo and example.Foo are the same thing
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
29882 <PRE>%module example
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">
29892 > print(e.Foo) -- reading works ok
29894 > example.Foo=40 -- but writing does not
29895 This variable is immutable
29899 stdin:1: in main chunk
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
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">
29914 > -- example.PI does not exist
29915 > print(example.PI)
29917 > example.PI=3.142 -- new value added
29918 > print(example.PI)
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>
29928 <PRE>%module example
29929 %constant int ICONST=42;
29930 #define SCONST "Hello World"
29931 enum Days{SUNDAY,MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY};
29934 <P> This is 'effectively' converted into the following Lua code:</P>
29935 <DIV class="targetlang">
29938 example.SCONST="Hello World"
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 <file.h> interface:</P>
29952 <PRE>%module example
29954 FILE *fopen(const char *filename, const char *mode);
29955 int fputs(const char *, FILE *);
29956 int fclose(FILE *);
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">
29963 > f=example.fopen("junk","w")
29964 > example.fputs("Hello World",f)
29965 > example.fclose(f)
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">
29979 > print(swig_type(f))
29980 FILE * -- its a FILE*
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 & 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">
29991 > f=example.fopen("not there","r") -- this will return a NULL in C
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>
30006 <P> is used as follows:</P>
30007 <DIV class="targetlang">
30009 > p=example.new_Point()
30012 > print(p.x,p.y)
30017 <P> Similar access is provided for unions and the data members of C++
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">
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
30043 int x; // Read-only members
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>
30065 <P> Now, suppose that you access the f attribute of Bar like this:</P>
30066 <DIV class="targetlang">
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>
30077 Foo *x = &b->f; // Points inside b
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">
30085 > b.f.a = 3 -- Modify attribute of structure member
30087 > x.a = 3 -- Modifies the same structure
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>
30098 int search(char *item);
30099 void insert(char *item);
30100 void remove(char *item);
30106 <P> you can use it in Lua like this:</P>
30107 <DIV class="targetlang">
30109 > l = example.List()
30110 > l:insert("Ale")
30111 > l:insert("Stout")
30112 > l:insert("Lager")
30113 > print(l:get(1))
30115 > print(l:length)
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>
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">
30138 <P> In Lua, the static members can be accessed as follows:</P>
30141 > example.Spam_foo() -- calling Spam::foo()
30142 > a=example.Spam_bar -- reading Spam::bar
30143 > example.Spam_bar=b -- writing to Spam::bar
30146 <P> It is not (currently) possible to access static members of an
30148 <DIV class="targetlang">
30150 > s=example.Spam() -- s is a Spam instance
30151 > s.foo() -- Spam::foo() via an instance
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>
30163 class Bar : public Foo {
30168 <P> And if you have functions like this</P>
30170 <PRE>void spam(Foo *f);
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
30178 <P> In C++, there are many different ways a function might receive and
30179 manipulate objects. For example:</P>
30181 <PRE>void spam1(Foo *x); // Pass by pointer
30182 void spam2(Foo &x); // Pass by reference
30183 void spam3(Foo x); // Pass by value
30184 void spam4(Foo x[]); // Array of objects
30187 <P> In SWIG, there is no detailed distinction like this--specifically,
30188 there are only "objects". 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">
30194 > f = Foo() -- Create a Foo
30195 > spam1(f) -- Ok. Pointer
30196 > spam2(f) -- Ok. Reference
30197 > spam3(f) -- Ok. Value.
30198 > spam4(f) -- Ok. Array (1 element)
30201 <P> Similar behaviour occurs for return values. For example, if you had
30202 functions like this,</P>
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>
30219 <PRE>void foo(int);
30223 <P> You can use them in Lua in a straightforward manner:</P>
30224 <DIV class="targetlang">
30226 > foo(3) -- foo(int)
30227 > foo("Hello") -- foo(char *c)
30230 <P> However due to Lua's coercion mechanism is can sometimes do strange
30232 <DIV class="targetlang">
30234 > foo("3") -- "3" can be coerced into an int, so it calls foo(int)!
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
30240 <P> Similarly, if you have a class like this,</P>
30245 Foo(const Foo &);
30250 <P> you can write Lua code like this:</P>
30251 <DIV class="targetlang">
30253 > f = Foo() -- Create a Foo
30254 > g = Foo(f) -- Copy f
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>
30260 <PRE>void spam(int);
30266 <PRE>VOID FOO(bAR *B);
30267 void foo(Bar &b);
30270 <P> If declarations such as these appear, you will get a warning message
30272 <DIV class="shell">
30274 example.i:12: Warning(509): Overloaded spam(short) is shadowed by spam(int)
30278 <P> To fix this, you either need to ignore or rename one of the methods.
30281 <PRE>%rename(spam_short) spam(short);
30284 void spam(short); // Accessed as spam_short
30289 <PRE>%ignore spam(short);
30292 void spam(short); // Ignored
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 "SWIG and C++" 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>
30309 <PRE>class Complex {
30311 double rpart, ipart;
30313 Complex(double r = 0, double i = 0) : rpart(r), ipart(i) { }
30314 Complex(const Complex &c) : rpart(c.rpart), ipart(c.ipart) { }
30315 Complex &operator=(const Complex &c);
30316 Complex operator+(const Complex &c) const;
30317 Complex operator-(const Complex &c) const;
30318 Complex operator*(const Complex &c) const;
30319 Complex operator-() const;
30321 double re() const { return rpart; }
30322 double im() const { return ipart; }
30326 <P> When wrapped, it works like you expect:</P>
30327 <DIV class="targetlang">
30329 > c = Complex(3,4)
30330 > d = Complex(7,8)
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 {
30344 friend Complex operator+(double, const Complex &c);
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
30353 <DIV class="targetlang">
30354 <PRE>%rename(Complex_add_dc) operator+(double, const Complex &);
30356 Complex operator+(double, const Complex &c);
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>
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>
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
30380 <LI><TT>__pow__</TT> the exponential fn (no C++ equivalent, Lua uses <TT>
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><</TT></LI>
30386 <LI><TT>__le__</TT> operator<TT><=</TT></LI>
30388 <P> Note: in Lua, only the equals, less than, and less than equals
30389 operators are defined. The other operators (!=,>,>=) 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>
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>
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>
30406 <PRE>const char* __str__()
30408 static char buffer[255];
30409 sprintf(buffer,"Complex(%g,%g)",this->re(),this->im());
30414 <P> Then this will support the following code in Lua</P>
30415 <DIV class="targetlang">
30417 > c = Complex(3,4)
30418 > d = Complex(7,8)
30422 > s=tostring(e) -- s is the number in string form
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>
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
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>
30448 <PRE>class Complex {
30450 double rpart, ipart;
30452 Complex(double r = 0, double i = 0) : rpart(r), ipart(i) { }
30453 Complex(const Complex &c) : rpart(c.rpart), ipart(c.ipart) { }
30454 Complex &operator=(const Complex &c);
30455 Complex operator+(const Complex &c) const;
30456 Complex operator-(const Complex &c) const;
30457 Complex operator*(const Complex &c) const;
30458 Complex operator-() const;
30460 double re() const { return rpart; }
30461 double im() const { return ipart; }
30465 <P> Now we extend it with some new code</P>
30467 <PRE>%extend Complex {
30468 const char *__str__() {
30469 static char tmp[1024];
30470 sprintf(tmp,"Complex(%g,%g)", $self->re(),$self->im());
30473 bool operator==(const Complex& c)
30474 { return ($self->re()==c.re() && $self->im()==c.im();}
30478 <P> Now, in Lua</P>
30479 <DIV class="targetlang">
30481 > c = Complex(3,4)
30482 > d = Complex(7,8)
30484 > print(e) -- print uses __str__ to get the string form to print
30486 > print(e==Complex(10,12)) -- testing the == operator
30488 > print(e!=Complex(12,12)) -- the != uses the == operator
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
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>
30504 <PRE>%module example
30506 #include "pair.h"
30509 template<class T1, class T2>
30511 typedef T1 first_type;
30512 typedef T2 second_type;
30516 pair(const T1&, const T2&);
30520 %template(pairii) pair<int,int>;
30524 <DIV class="targetlang">
30526 > p = example.pairii(3,4)
30527 > print(p.first,p.second)
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 "smart pointers." Generally, this involves the use
30537 of a template class that implements operator->() like this:</P>
30539 <PRE>template<class T> class SmartPtr {
30541 T *operator->();
30546 <P> Then, if you have a class like this,</P>
30555 <P> A smart pointer would be used in C++ as follows:</P>
30557 <PRE>SmartPtr<Foo> p = CreateFoo(); // Created somehow (not shown)
30559 p->x = 3; // Foo::x
30560 int y = p->bar(); // Foo::bar
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>
30567 <PRE>%module example
30569 %template(SmartPtrFoo) SmartPtr<Foo>;
30573 <P> Now, in Lua, everything should just "work":</P>
30574 <DIV class="targetlang">
30576 > p = example.CreateFoo() -- Create a smart-pointer somehow
30577 > p.x = 3 -- Foo::x
30578 > print(p:bar()) -- Foo::bar
30581 <P> If you ever need to access the underlying pointer returned by <TT>
30582 operator->()</TT> itself, simply use the <TT>__deref__()</TT> method.
30584 <DIV class="targetlang">
30586 > f = p:__deref__() -- Returns underlying Foo *
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>
30596 int message() throw(const char *) {
30597 throw("I died.");
30602 <P> SWIG will automatically convert this to a Lua error.</P>
30603 <DIV class="targetlang">
30608 [C]: in function 'message'
30609 stdin:1: in main chunk
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
30618 <DIV class="targetlang">
30620 > function a() b() end -- function a() calls function b()
30621 > function b() message() end -- function b() calls C++ function message(), which throws
30622 > ok,res=pcall(a) -- call the function
30625 > ok,res=xpcall(a,debug.traceback) -- call the function
30629 [C]: in function 'message'
30630 runme.lua:70: in function 'b'
30631 runme.lua:67: in function <runme.lua:66>
30632 [C]: in function 'xpcall'
30633 runme.lua:95: in main chunk
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>
30653 void throw_A() throw(A*) {
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">
30663 object exception:A *
30665 [C]: in function 'unknown'
30666 stdin:1: in main chunk
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
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>
30678 %typemap(throws) my_except
30680 lua_pushstring(L,$1.what()); // assuming my_except::what() returns a const char* message
30681 SWIG_fail; // trigger the error handler
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>
30691 %apply SWIGTYPE EXCEPTION_BY_VAL {Exc}; // tell SWIG to return Exc by value to interpreter
30695 Exc(int c, const char *m) {
30697 strncpy(msg,m,256);
30703 void throw_exc() throw(Exc) {
30704 throw(Exc(42,"Hosed"));
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">
30712 > ok,res=pcall(throw_exc)
30717 > print(res.code,res.msg)
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
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 "<A href="#SWIGPlus_catches">
30728 Exception handling with %catches</A>" section and the "<A href="#exception">
30729 Exception handling with %exception</A>" 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>
30742 <PRE>%module example
30745 $1 = (int) lua_tonumber(L,$input);
30746 printf("Received an integer : %d\n",$1);
30749 extern int fact(int n);
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 "in" 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
30764 <DIV class="targetlang">
30765 <PRE>> require "example"
30766 > print(example.fact(6))
30767 Received an integer : 6
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 <typemaps.i>, which contains
30777 typemaps for these situations. For example, consider these functions:</P>
30779 <PRE>void add(int x, int y, int *result) {
30783 int sub(int *x1, int *y1) {
30787 void swap(int *sx, int *sy) {
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>
30802 <PRE>%include <typemaps.i>
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
30807 void add(int x, int y, int *result);
30808 int sub(int *x1, int *y1);
30809 void swap(int *sx, int *sy);
30812 <P>When wrapped, it gives the following results:</P>
30813 <DIV class="targetlang">
30814 <PRE>> require "example"
30815 > print(example.add(1,2))
30817 > print(demo.sub(1,2))
30820 > c,d=demo.swap(a,b)
30821 > print(a,b,c,d)
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&</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>
30841 <PRE>extern void sort_int(int* arr, int len);
30842 extern void sort_double(double* arr, int len);
30845 <P>There are basically two ways that SWIG can deal with this. The first
30846 way, uses the <TT><carrays.i></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><typemaps.i></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>
30858 <PRE>// using the C-array
30859 %include <carrays.i>
30860 // this declares a batch of function for manipulating C integer arrays
30861 %array_functions(int,int)
30863 extern void sort_int(int* arr, int len); // the function to wrap
30866 %include <typemaps.i>
30867 %apply (double *INOUT,int) {(double* arr,int len)};
30869 extern void sort_double(double* arr, int len); // the function to wrap
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 "example"
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))
30883 example.sort_int(arr,ARRAY_SIZE) -- call the function
30884 example.delete_int(arr) -- must delete the allocated memory
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
30892 t=example.sort_double(t) -- replace t with the result
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>
30913 <PRE>struct iMath; // some structure
30914 int Create_Math(iMath** pptr); // its creator (assume it mallocs)
30917 <P>Which would be used with the following C code:</P>
30921 ok=Create_Math(&ptr);
30922 // do things with ptr
30924 free(ptr); // dispose of iMath
30927 <P>SWIG has a ready written typemap to deal with such a kind of function
30928 in <typemaps.i>. 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>
30932 <PRE>%include <typemaps.i>
30933 %apply SWIGTYPE** OUTPUT{iMath **pptr }; // tell SWIG its an output
30935 struct iMath; // some structure
30936 int Create_Math(iMath** pptr); // its creator (assume it mallocs)
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
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 "<A href="#Typemaps">Typemaps</A>
30950 " 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
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 "<A href="#Typemaps">Typemaps</A>"
30964 chapter. However the following are the most commonly used ones.</P>
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>
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
31004 <BR> A common use for this code is:
31007 if (!SWIG_IsOK(SWIG_ConvertPtr( .....)){
31008 lua_pushstring(L,"something bad happened");
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
31017 "Error in <I>func_name</I> (arg <I>argnum</I>), expected '<I>type</I>' got '<I>whatever the type was</I>'"
31020 <P><TT>SWIG_fail_ptr(const char* fn_name,int argnum,swig_type_info*
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>
31034 <PRE>%native(my_func) int native_function(lua_State*L); // registers native_function() with SWIG
31037 int native_function(lua_State*L) // my native code
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>
31057 <PRE>%module example;
31060 function example.greet()
31061 print "hello world"
31064 print "Module loaded ok"
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
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>
31093 <PRE>%module example;
31097 <P> SWIG will effectively generate the pair of functions</P>
31099 <PRE>void Foo_set(double);
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">
31113 > print(example)
31115 > m=getmetatable(example)
31116 > table.foreach(m,print)
31117 .set table: 003F9088
31118 .get table: 003F9038
31119 __index function: 003F8FE0
31120 __newindex function: 003F8FF8
31122 > table.foreach(g,print)
31123 Foo function: 003FAFD8
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">
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 & returns the value
31138 if type(f)=="function" then return f() end
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)=="function" then f(value)
31148 else rawset(mod,name,value) end
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>
31173 <PRE>%module excpp;
31181 virtual void Print(){printf("Point @%p (%d,%d)\n",this,x,y);}
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
31195 <P> Some of the internals can be seen by looking at a classes metatable.</P>
31196 <DIV class="targetlang">
31198 > p=excpp.Point()
31201 > m=getmetatable(p)
31202 > table.foreach(m,print)
31204 __gc function: 003FB6C8
31205 __newindex function: 003FB6B0
31206 __index function: 003FB698
31207 .get table: 003FB4D8
31208 .set table: 003FB500
31209 .fn table: 003FB528
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
31218 <DIV class="targetlang">
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 & returns the value
31227 if type(f)=="function" 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)=="function" then return f end
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 & 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' & '__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 &
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>
31277 <H1><A name="Modula3"></A>24 SWIG and Modula-3</H1>
31280 <DIV class="sectiontoc">
31282 <LI><A href="#modula3_overview">Overview</A>
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>
31290 <LI><A href="#conception">Conception</A>
31292 <LI><A href="#cinterface">Interfaces to C libraries</A></LI>
31293 <LI><A href="#cppinterface">Interfaces to C++ libraries</A></LI>
31296 <LI><A href="#preliminaries">Preliminaries</A>
31298 <LI><A href="#compilers">Compilers</A></LI>
31299 <LI><A href="#commandline">Additional Commandline Options</A></LI>
31302 <LI><A href="#modula3_typemaps">Modula-3 typemaps</A>
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>
31312 <LI><A href="#hints">More hints to the generator</A>
31314 <LI><A href="#features">Features</A></LI>
31315 <LI><A href="#pragmas">Pragmas</A></LI>
31318 <LI><A href="#remarks">Remarks</A></LI>
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>
31332 <LI> <A href="http://www.elegosoft.com/cgi-bin/cvsweb.cgi/cm3/m3-libs/plplot/">
31334 <LI> <A href="http://www.elegosoft.com/cgi-bin/cvsweb.cgi/cm3/m3-libs/fftw/">
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
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
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>
31430 <TR><TD>Pragma <TT><* EXTERNAL *></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><* CALLBACK *></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>
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
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>
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>
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>
31471 <TR><TD align="center">
31472 <!-- pre tag overrides centering -->
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>--></TD><TD align="center">
31478 C library</TD></TR>
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
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 -->
31508 <BR> v</TD><TD></TD><TD align="center"> ^
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>--></TD><TD align="center">
31514 <BR> module<TT>_wrap.cxx</TT>
31515 <BR> generated by the SWIG core</TD></TR>
31517 <P> Wrapping C++ libraries arises additional problems:</P>
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>
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
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 <file></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 <<
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
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 <file></TD><TD> Disable generation
31572 of interfaces and wrappers. Instead generate suggestions for <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 <file></TD><TD> Disable generation
31582 of interfaces and wrappers. Instead generate templates for some basic
31583 typemaps.</TD></TR>
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 "m3", followed by "raw" or "wrap" 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 "in" for typemaps
31604 applied to input argument, "out" for output arguments, "arg" for all
31605 kind of arguments, "ret" 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>
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>
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 = "$1_name";</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>
31635 <TR><TD>m3wrapinname</TD><TD></TD><TD> New name of the input argument.</TD>
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
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>
31644 <TR><TD>m3wrapincheck</TD><TD><TT>IF Text.Length($1_name) > 10 THEN
31645 RAISE E("str too long"); 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>
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>
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>
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>
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>
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 "public - protected -
31694 private" 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("m3wrapinconv:import") 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("m3wrapinconv:import") 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>
31712 %insert(m3rawintf) %{
31717 <H3><A name="exceptions"></A>24.4.5 Exceptions</H3>
31718 <P> Modula-3 provides another possibility of an output of a function:
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("m3wrapinconv:throws") 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>
31734 <I> (* %relabel m3wrapinmode m3wrapinname m3wrapintype m3wrapindefault *)</I>
31735 PROCEDURE Name (READONLY str : TEXT := "" )
31736 <I> (* m3wrapoutcheck:throws *)</I>
31737 : NameResult RAISES {E} =
31739 arg1name = "str"; <I>(* m3wrapargconst *)</I>
31741 arg0 : C.char_star; <I>(* m3wrapretvar *)</I>
31742 arg1 : C.char_star; <I>(* m3wrapargvar *)</I>
31745 <I> (*m3wrapretname m3wraprettype*)</I>
31747 <I> (*m3wrapoutname m3wrapouttype*)</I>
31748 checksum : CARDINAL;
31752 arg1 := M3toC.SharedTtoS(str); <I>(* m3wrapinconv *)</I>
31753 IF Text.Length(arg1) > 10 THEN <I>(* m3wrapincheck *)</I>
31754 RAISE E("str too long");
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("invalid checksum");
31764 M3toC.FreeSharedS(str,arg1); <I>(* m3wrapfreearg *)</I>
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("modula3:multiretval") 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 "out" direction including the
31777 return value of the C function (if there is one). If more than one
31778 argument is "out" 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("constnumeric","12") 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>
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="true";</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="m3fftw";</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>
31799 <H2><A name="remarks"></A>24.6 Remarks</H2>
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>
31807 <!-- Hand-written HTML -->
31808 <H1><A name="MzScheme"></A>25 SWIG and MzScheme</H1>
31811 <DIV class="sectiontoc">
31813 <LI><A href="#MzScheme_nn2">Creating native MzScheme structures</A></LI>
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>
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);
31829 %typemap(in,numinputs=0) TYPE *NAME (TYPE temp) {
31834 /* setup the typemaps for the pointer to an output parameter cntrs */
31835 handle_ptr(struct diag_cntrs, cntrs);
31838 <P> Then in scheme, you can use regular struct access procedures like</P>
31841 ; suppose a function created a struct foo as
31842 ; (define foo (make-diag-cntrs (#x1 #x2 #x3) (make-inspector))
31844 (format "0x~x" (diag-cntrs-field1 foo))
31845 (format "0x~x" (diag-cntrs-field2 foo))
31849 <P> That's pretty much it. It works with nested structs as well.</P>
31852 <H1><A name="Ocaml"></A>26 SWIG and Ocaml</H1>
31855 <DIV class="sectiontoc">
31857 <LI><A href="#Ocaml_nn2">Preliminaries</A>
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>
31866 <LI><A href="#Ocaml_nn8">The low-level Ocaml/C interface</A>
31868 <LI><A href="#Ocaml_nn9">The generated module</A></LI>
31869 <LI><A href="#Ocaml_nn10">Enums</A>
31871 <LI><A href="#Ocaml_nn11">Enum typing in Ocaml</A></LI>
31874 <LI><A href="#Ocaml_nn12">Arrays</A>
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 *
31883 <LI><A href="#Ocaml_nn17">C++ Classes</A>
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>
31891 <LI><A href="#Ocaml_nn22">Director Classes</A>
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>
31904 <LI><A href="#Ocaml_nn31">Exceptions</A></LI>
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
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>
31945 %swig -ocaml example.i
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>
31966 % swig -ocaml -co swig.mli ; swig -ocaml co swig.ml
31967 % ocamlc -c swig.mli ; ocamlc -c swig.ml
31968 % ocamlc -c -ccopt "-I/usr/include/foo" example_wrap.c
31969 % ocamlc -c example.mli
31970 % ocamlc -c example.ml
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>
31978 % cp example_wrap.cxx example_wrap.cxx.c
31979 <BR>% ocamlc -c ... -ccopt -xc++ example_wrap.cxx.c
31984 <H3><A name="Ocaml_nn5"></A>26.1.3 The camlp4 module</H3>
31985 <P> The camlp4 module (swigp4.ml -> 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>"swig -ocaml -co swigp4.ml"</TT>. You
31990 should compile the file with <TT>"ocamlc -I `camlp4 -where` -pp
31991 'camlp4o pa_extend.cmo q_MLast.cmo' -c swigp4.ml"</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'("0") or
32001 <BR> _exit'(0)</TD><TD>f(C_list [ ... ]) as in
32002 <BR> atoi (C_list [ C_string "0" ]) or
32003 <BR> _exit (C_list [ C_int 0 ])</TD></TR>
32004 <TR><TD>object -> method ( ... )</TD><TD>(invoke object) "method"
32005 (C_list [ ... ])</TD></TR>
32006 <TR><TD> object<I> 'binop</I> argument as in
32007 <BR> a '+= b</TD><TD> (invoke object) "+=" argument as in
32008 <BR> (invoke a) "+=" b</TD><TD></TD></TR>
32009 <TR><TH colspan="2">Note that because camlp4 always recognizes << and
32010 >>, 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) "!" C_void</TD></TR>
32013 <TR><TD><B> Smart pointer access like this</B>
32014 <BR> object '-> method ( args )
32015 <BR></TD><TD> (invoke (invoke object "->" C_void))</TD></TR>
32016 <TR><TD><B> Invoke syntax</B>
32017 <BR> object . '( ... )</TD><TD> (invoke object) "()" (C_list [ ... ])</TD>
32019 <TR><TD><B> Array syntax</B>
32020 <BR> object '[ 10 ]</TD><TD> (invoke object) "[]" (C_int 10)</TD></TR>
32021 <TR><TD><B> Assignment syntax</B>
32022 <BR> let a = '10 and b = '"foo" and c = '1.0 and d = 'true</TD><TD> let
32023 a = C_int 10 and b = C_string "foo" and c = C_double 1.0 and d = C_bool
32025 <TR><TD><B> Cast syntax</B>
32026 <BR> let a = _atoi '("2") as int
32027 <BR> let b = (getenv "PATH") to string
32028 <BR> This works for int, string, float, bool</TD><TD> let a = get_int
32029 (_atoi (C_string "2"))
32030 <BR> let b = C_string (getenv "PATH")</TD></TR>
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
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.
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 -> c_obj -> c_obj)
32073 | C_string of string
32074 | C_enum of c_enum_t
32077 <P> A few functions exist which generate and return these:</P>
32079 <LI>caml_ptr_val receives a c_obj and returns a void *. This should be
32080 used for all pointer purposes.</LI>
32081 <LI>caml_long_val receives a c_obj and returns a long. This should be
32082 used for most integral purposes.
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
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
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>
32095 <P> Because of this style, a typemap can return any kind of value it
32096 wants from a function. This enables out typemaps and inout typemaps to
32097 work well. 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> 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 ] -> 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' -> C_list [ C_char
32105 'a' ; C_char b ]). 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. 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. When evaluated in
32116 caml_ptr_val, the returned value is the result of a call to the
32117 object's "&" 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>"header"</TD><TD>This code is inserted near the beginning of the
32135 C wrapper file, before any function definitions.</TD></TR>
32136 <TR><TD>"wrapper"</TD><TD>This code is inserted in the function
32137 definition section.</TD></TR>
32138 <TR><TD>"runtime"</TD><TD>This code is inserted near the end of the C
32139 wrapper file.</TD></TR>
32140 <TR><TD>"mli"</TD><TD>This code is inserted into the caml interface
32141 file. Special signatures should be inserted here.</TD></TR>
32142 <TR><TD>"ml"</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>"classtemplate"</TD><TD>The "classtemplate" place is special
32147 because it describes the output SWIG will generate for class
32148 definitions.</TD></TR>
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. 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. Other than
32155 that, correct uses of enums will not have a problem. 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>
32162 enum c_enum_type { a = 1, b, c = 4, d = 8 };
32164 enum c_enum_type { a = 1, b, c = 4, d = 8 };
32167 <P> The output mli contains:</P>
32170 type c_enum_type = [
32174 type c_enum_tag = [
32181 val int_to_enum c_enum_type -> int -> c_obj
32182 val enum_to_int c_enum_type -> c_obj -> c_obj
32185 <P> So it's possible to do this:</P>
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
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
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 "carray.i", 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
32245 <TABLE bgcolor="#dddddd" border="1" summary="float * and int typemap example">
32247 <CENTER>tarray.i</CENTER>
32253 #include <stdio.h>
32255 void printfloats( float *tab, int len ) {
32258 for( i = 0; i < len; i++ ) {
32259 printf( "%f ", tab[i] );
32262 printf( "\n" );
32266 %typemap(in) (float *tab, int len) {
32269 $2 = caml_array_len($input);
32270 $1 = ($*1_type *)malloc( $2 * sizeof( float ) );
32271 for( i = 0; i < $2; i++ ) {
32272 $1[i] = caml_double_val(caml_array_nth($input,i));
32276 void printfloats( float *tab, int len );
32279 <TR><TH>Sample Run</TH></TR>
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
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 -> c_obj -> c_obj) wrapped closures. 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 "&" method. 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. 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>"~"</TD><TD>Delete this object</TD></TR>
32301 <TR><TD>"&"</TD><TD>Return an ordinary C_ptr value representing this
32302 object's address</TD></TR>
32303 <TR><TD>"sizeof"</TD><TD>If enabled with ("sizeof"="1") on the module
32304 node, return the object's size in char.</TD></TR>
32305 <TR><TD>":methods"</TD><TD>Returns a list of strings containing the
32306 names of the methods this object contains</TD></TR>
32307 <TR><TD>":classof"</TD><TD>Returns the name of the class this object
32308 belongs to.</TD></TR>
32309 <TR><TD>":parents"</TD><TD>Returns a list of all direct parent classes
32310 which have been wrapped by SWIG.</TD></TR>
32311 <TR><TD>"::[parent-class]"</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>"[member-variable]"</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>
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">
32331 <CENTER>example.i</CENTER>
32337 #include "example.h"
32340 %include <stl.i>
32343 %template(StringVector) std::vector < string >;
32346 %include "example.h"
32349 <TR><TD><FONT size="-1"><I>This example is in Examples/ocaml/stl</I></FONT>
32352 <P> Since there's a makefile in that directory, the example is easy to
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
32359 bash-2.05a$ ./example_top
32360 Objective Caml version 3.06
32362 Camlp4 Parsing version 3.06
32366 # let x = new_StringVector '() ;;
32367 val x : Example.c_obj = C_obj <fun>
32368 # x -> ":methods" () ;;
32369 - : Example.c_obj =
32371 [C_string "nop"; C_string "size"; C_string "empty"; C_string "clear";
32372 C_string "push_back"; C_string "[]"; C_string "="; C_string "set";
32373 C_string "~"; C_string "&"; C_string ":parents"; C_string ":classof";
32374 C_string ":methods"]
32375 # x -> push_back ("foo") ;;
32376 - : Example.c_obj = C_void
32377 # x -> push_back ("bar") ;;
32378 - : Example.c_obj = C_void
32379 # x -> push_back ("baz") ;;
32380 - : Example.c_obj = C_void
32382 - : Example.c_obj = C_string "bar"
32383 # x -> set (1,"spam") ;;
32384 - : Example.c_obj = C_void
32386 - : Example.c_obj = C_string "spam"
32387 # for i = 0 to (x -> size() as int) - 1 do
32388 print_endline ((x '[i to int]) as string)
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">
32401 <CENTER>qt.i</CENTER>
32407 #include <qapplication.h>
32408 #include <qpushbutton.h>
32410 class QApplication {
32412 QApplication( int argc, char **argv );
32413 void setMainWidget( QWidget *widget );
32417 class QPushButton {
32419 QPushButton( char *str, QWidget *w );
32420 void resize( int x, int y );
32426 <H4><A name="Ocaml_nn20"></A>26.2.4.3 Compiling the example</H4>
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 "camlp4o pa_extend.cmo q_MLast.cmo" -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
32443 <H4><A name="Ocaml_nn21"></A>26.2.4.4 Sample Session</H4>
32446 bash-2.05a$ ./qt_top
32447 Objective Caml version 3.06
32449 Camlp4 Parsing version 3.06
32453 # let a = new_QApplication '(0,0) ;;
32454 val a : Qt.c_obj = C_obj <fun>
32455 # let hello = new_QPushButton '("hi",0) ;;
32456 val hello : Qt.c_obj = C_obj <fun>
32457 # hello -> resize (100,30) ;;
32458 - : Qt.c_obj = C_void
32459 # hello -> show () ;;
32460 - : Qt.c_obj = C_void
32461 # a -> exec () ;;
32464 <P> Assuming you have a working installation of QT, you will see a
32465 window containing the string "hi" 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
32473 <P> You can turn on director classes by using an optional module
32474 argument like this:</P>
32477 %module(directors="1")
32481 // Turn on the director class for a specific class like this:
32482 %feature("director")
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
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">
32511 <CENTER>example_prog.ml</CENTER>
32520 let triangle_class pts ob meth args =
32522 "cover" ->
32524 C_list [ x_arg ; y_arg ] ->
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 | _ -> raise (Failure "cover needs two double arguments."))
32529 | _ -> (invoke ob) meth args ;;
32534 (triangle_class ((0.0,0.0),(0.5,1.0),(1.0,0.0)))
32537 let _ = _draw_shape_coverage '(triangle, C_int 60, C_int 20) ;;
32541 <P> This is the meat of what you need to do. The actual "class"
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 "cover" 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 "engine" 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
32570 (triangle_class ((0.0,0.0),(0.5,1.0),(1.0,0.0)))
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 (&) 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>
32636 <H1><A name="Octave"></A>27 SWIG and Octave</H1>
32639 <DIV class="sectiontoc">
32641 <LI><A href="#Octave_nn2">Preliminaries</A></LI>
32642 <LI><A href="#Octave_nn3">Running SWIG</A>
32644 <LI><A href="#Octave_nn5">Compiling a dynamic module</A></LI>
32645 <LI><A href="#Octave_nn6">Using your module</A></LI>
32648 <LI><A href="#Octave_nn7">A tour of basic C/C++ wrapping</A>
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>
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>
32687 <PRE>%module example
32689 #include "example.h"
32691 int gcd(int x, int y);
32692 extern double Foo; </PRE>
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>
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 ".oct" 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">
32712 $ swig -octave -c++ example.i -o example_wrap.cxx
32713 $ mkoctfile example_wrap.cxx example.c
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> example</PRE>
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:
32728 <DIV class="targetlang">
32730 octave:1> example
32731 octave:2> example.gcd(4,6)
32733 octave:3> example.cvar.Foo
32735 octave:4> example.cvar.Foo=4;
32736 octave:5> example.cvar.Foo
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 "example", 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 "example". It will thusly
32748 find example.oct, that upon loading will register all of the module's
32750 <P> Giving this function a parameter "global" 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">
32755 octave:1> example("global")
32756 octave:2> gcd(4,6)
32758 octave:3> cvar.Foo
32760 octave:4> cvar.Foo=4;
32761 octave:5> cvar.Foo
32765 <P> It is also possible to rename the module namespace with an
32767 <BR><DIV class="targetlang">
32768 <PRE>octave:1> example;
32769 octave:2> c=example;
32770 octave:3> c.gcd(10,4)
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">
32779 octave:1> some_vars = cvar;
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
32786 <PRE>%module example
32787 int fact(int n); </PRE>
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> example.fact(4)
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
32799 <PRE>%module example
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> example;
32811 octave:2> c=example.cvar.Foo
32813 octave:3> example.cvar.Foo=4;
32816 octave:5> example.cvar.Foo
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>
32823 <PRE>%module example
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> example
32833 octave:2> 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>
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> example;
32844 octave:2> example.PI=3.142;
32845 octave:3> example.PI
32846 ans = 3.1420 </PRE>
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>
32854 <PRE>%module example
32855 %constant int ICONST=42;
32856 #define SCONST "Hello World"
32857 enum Days{SUNDAY,MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY};
32860 <P> This is 'effectively' converted into the following Octave code:</P>
32861 <DIV class="targetlang">
32862 <PRE>example.ICONST=42
32863 example.SCONST="Hello World"
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 <file.h> 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 <file.h> interface:</P>
32874 <PRE>%module example
32875 FILE *fopen(const char *filename, const char *mode);
32876 int fputs(const char *, FILE *);
32877 int fclose(FILE *);
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">
32884 octave:1> example;
32885 octave:2> f=example.fopen("w","junk");
32886 octave:3> example.fputs("Hello world",f);
32887 octave:4> example.fclose(f);
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> example;
32894 octave:2> f=example.fopen("junk","w");
32899 _p_FILE, ptr = 0x9b0cd00
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
32906 <DIV class="targetlang">
32907 <PRE>octave:1> example;
32908 octave:2> f=example.fopen("not there","r");
32909 error: value on right hand side of assignment is undefined
32910 error: evaluating assignment expression near line 2, column 2 </PRE>
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>
32927 <P> is used as follows:</P>
32928 <DIV class="targetlang">
32929 <PRE>octave:1> example;
32930 octave:2> p=example.Point();
32931 octave:3> p.x=3;
32932 octave:4> p.y=5;
32933 octave:5> p.x, p.y
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>
32951 Point(int _x,int _y) : x(_x),y(_y) {}
32952 double distance(const Point& rhs) {
32953 return sqrt(pow(x-rhs.x,2)+pow(y-rhs.y,2));
32955 void set(int _x,int _y) {
32961 <P> can be used from Octave like this</P>
32962 <DIV class="targetlang">
32963 <PRE>octave:1> example;
32964 octave:2> p1=example.Point(3,5);
32965 octave:3> p2=example.Point(1,2);
32966 octave:4> p1.distance(p2)
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
32973 <DIV class="targetlang">
32975 octave:5> swig_this(p1)
32977 octave:6> swig_type(p1)
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">
32991 octave:7> a=struct('x',4)
33017 <P> However, when dealing with wrapped objects, one gets the behavior</P>
33018 <DIV class="targetlang">
33020 octave:2> a=Point(3,5)
33024 Point, ptr = 0x9afbbb0
33031 Point, ptr = 0x9afbbb0
33034 octave:4> b.set(2,1);
33035 octave:5> b.x, b.y
33038 octave:6> a.x, a.y
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>
33082 A(int _value) : value(_value) {}
33083 A operator+ (const A& x) {
33084 return A(value+x.value);
33090 <P> is usable from Octave like this:</P>
33091 <DIV class="targetlang">
33093 a=A(2), b=A(3), c=a+b
33094 assert(c.value==5);
33097 <P> Octave operators are mapped in the following way:</P>
33101 __brace_asgn a{args} = rhs
33103 __paren_asgn a(args) = rhs
33104 __str generates string rep
33118 __lshift a <<b
33119 __rshift a >> b
33134 <P> On the C++ side, the default mappings are as follows:</P>
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<
33148 %rename(__rshift) *::operator-->
33150 %rename(__el_and) *::operator&&;
33151 %rename(__el_or) *::operator||;
33152 %rename(__xor) *::operator^;
33153 %rename(__invert) *::operator~;
33154 %rename(__lt) *::operator
33156 %rename(__le) *::operator<=;
33157 %rename(__gt) *::operator-->
33159 %rename(__ge) *::operator>=;
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[];
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
33182 sout<<$self->value;
33188 <P> Then in Octave one gets,</P>
33189 <DIV class="targetlang">
33191 octave:1> a=A(4);
33194 octave:3> printf("%s\n",a);
33196 octave:4> a.__str()
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>
33206 <PRE>%module example
33208 template<class __scalar>
33209 __scalar mul(__scalar a,__scalar b) {
33213 %include <std_complex.i>
33214 %template(mul) mul<std::complex<double> >
33215 %template(mul) mul<double>
33218 <P> and then used from Octave</P>
33219 <DIV class="targetlang">
33221 octave:1> mul(4,3)
33223 octave:2> mul(4.2,3.6)
33225 octave:3> mul(3+4i,10+2i)
33229 <P> Similarly, class templates can be instantiated as in the following
33232 <PRE>%module example
33233 %include <std_complex.i>
33234 %include <std_string.i>
33236 #include <sstream>
33237 template<class __scalar> class sum {
33240 sum(__scalar _s=0) : s(_s) {}
33241 sum& add(__scalar _s) {
33245 std::string __str() const {
33246 std::stringstream sout;
33252 %template(sum_complex) sum<std::complex<double> >;
33253 %template(sum_double) sum<double>;
33256 <P> and then used from Octave</P>
33257 <DIV class="targetlang">
33259 octave:2> a=sum_complex(2+3i);
33260 octave:3> a.add(2)
33264 octave:4> a.add(3+i)
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++
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">
33283 octave:1> a=subclass();
33284 octave:2> a.my_var = 4;
33285 octave:3> a.my_method = @(self) printf("my_var = ",self.my_var);
33286 octave:4> a.my_method();
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>
33297 virtual my_method() {
33298 printf("c-side routine called\n");
33301 void call_your_method(A& a) {
33307 <P> Then from Octave you can say:</P>
33308 <DIV class="targetlang">
33310 octave:1> B=@() subclass(A(),@my_method);
33311 octave:2> function my_method(self)
33312 octave:3> printf("octave-side routine called\n");
33314 octave:5> call_your_method(B());
33315 octave-side routine called
33318 <P> or more concisely,</P>
33319 <DIV class="targetlang">
33321 octave:1> B=@() subclass(A(),'my_method',@(self) printf("octave-side routine called\n"));
33322 octave:2> call_your_method(B());
33323 octave-side routine called
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">
33337 octave:1> B=@(some_var=2) subclass(A(),'some_var',some_var,@some_func,'another_func',@(self) do_stuff())
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">
33346 octave:1> B=@() subclass(A(),@my_method);
33347 octave:2> function my_method(self)
33348 octave:3> self.A.my_method();
33349 octave:4> printf("octave-side routine called\n");
33351 octave:6> call_your_method(B());
33352 c-side routine called
33353 octave-side routine called
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">
33376 A() { printf("A constructing\n"); }
33377 ~A() { printf("A destructing\n"); }
33382 <P> Would produce this behavior in Octave:</P>
33383 <DIV class="targetlang">
33385 octave:1> a=A();
33388 octave:3> clear a;
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
33413 double my_det(const double* mat,int m,int n);
33416 <P> that is accessed from Octave as,</P>
33417 <DIV class="targetlang">
33419 octave:1> my_det(rand(4));
33423 <BR></TT><HR NOSHADE>
33424 <H1><A name="Perl5"></A>28 SWIG and Perl5</H1>
33427 <DIV class="sectiontoc">
33429 <LI><A href="#Perl5_nn2">Overview</A></LI>
33430 <LI><A href="#Perl5_nn3">Preliminaries</A>
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>
33441 <LI><A href="#Perl5_nn11">Building Perl Extensions under Windows</A>
33443 <LI><A href="#Perl5_nn12">Running SWIG from Developer Studio</A></LI>
33444 <LI><A href="#Perl5_nn13">Using other compilers</A></LI>
33447 <LI><A href="#Perl5_nn14">The low-level interface</A>
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>
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>
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>
33471 <LI><A href="#Perl5_nn32">Typemap Examples</A>
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>
33481 <LI><A href="#Perl5_nn39">Proxy classes</A>
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>
33492 <LI><A href="#Perl5_nn47">Adding additional Perl code</A></LI>
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
33522 swig -perl example.i
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
33537 #include "Extern.h"
33538 #include "perl.h"
33539 #include "XSUB.h"
33542 <P> These are typically located in a directory like this</P>
33545 /usr/lib/perl5/5.00503/i386-linux/CORE
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
33554 % perl -e 'use Config; print $Config{archlib};'
33555 /usr/lib/perl5/5.00503/i386-linux
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>
33564 $ swig -perl example.i
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
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
33582 <H3><A name="Perl5_nn6"></A>28.2.3 Building a dynamic module with
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">
33589 # File : Makefile.PL
33590 use ExtUtils::MakeMaker;
33592 `NAME' => `example', # Name of package
33593 `LIBS' => [`-lm'], # Name of custom libraries
33594 `OBJECT' => `example.o example_wrap.o' # Object files
33599 <P> Now, to build a module, simply follow these steps :</P>
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 "Programming Perl, 2nd ed." 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>
33618 % swig -perl -static example.i
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">
33631 extern double My_variable;
33632 extern int fact(int);
33635 // Include code for rebuilding Perl
33636 %include <perlmain.i>
33639 <P> The same thing can be accomplished by running SWIG as follows :</P>
33642 % swig -perl -static -lperlmain.i example.i
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
33658 % gcc example.o example_wrap.o -L/usr/lib/perl5/5.00503/i386-linux/CORE \
33659 -lperl -lsocket -lnsl -lm -o myperl
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">
33673 print example::fact(4),"\n";
33677 <P> A common error received by first-time users is the following:</P>
33678 <DIV class="targetlang">
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.
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">
33694 Can't find 'boot_example' symbol in ./example.so
33696 BEGIN failed--compilation aborted at - line 1.
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">
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.
33713 BEGIN failed--compilation aborted at - line 1.
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
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>
33733 $ gcc -shared example.o example_wrap.o -L/home/beazley/projects/lib -lfoo \
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">
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.
33746 BEGIN failed--compilation aborted at - line 1.
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>
33759 $ gcc -shared example.o example_wrap.o -L/home/beazley/projects/lib -lfoo \
33760 <B>-Xlinker -rpath /home/beazley/projects/lib \</B>
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
33772 $ env LD_LIBRARY_PATH=/home/beazley/projects/lib perl
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
33779 <H3><A name="Perl5_nn9"></A>28.2.6 Compilation problems and compiling
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>
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>
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>
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>
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>
33815 % g++ -c example_wrap.cxx -I/usr/lib/perl/5.8.0/CORE -D_GNU_SOURCE
33818 <P> -D_GNU_SOURCE is also included in the Perl ccflags, which can be
33819 found by running</P>
33822 % perl -e 'use Config; print $Config{ccflags};'
33825 <P> So you could also compile the wrapper like</P>
33828 % g++ -c example_wrap.cxx -I/usr/lib/perl/5.8.0/CORE \
33829 `perl -e 'use Config; print $Config{ccflags}'`
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>
33847 <B>libstdc++-libc6.1-1.so.2 => /usr/lib/libstdc++-libc6.1-1.so.2 (0x40019000)</B>
33848 libm.so.6 => /lib/libm.so.6 (0x4005b000)
33849 libc.so.6 => /lib/libc.so.6 (0x40077000)
33850 /lib/ld-linux.so.2 => /lib/ld-linux.so.2 (0x40000000)
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>
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>
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>
33880 #define do_open Perl_do_open
33883 <P> The problem is, in the <iostream> header from GNU libstdc++v3 there
33884 is a private function named do_open. If <iostream> 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
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>
33923 <LI>Open up a new workspace and use the AppWizard to select a DLL
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 "Custom Build" option.</LI>
33933 <LI>Enter "SWIG" in the description field.</LI>
33934 <LI>Enter "<TT>swig -perl5 -o $(ProjDir)\$(InputName)_wrap.cxx
33935 $(InputPath)</TT>" in the "Build command(s) field"</LI>
33936 <LI>Enter "<TT>$(ProjDir)\$(InputName)_wrap.c</TT>xx" in the "Output
33937 files(s) field".</LI>
33938 <LI>Next, select the settings for the entire project and go to
33939 "C++:Preprocessor". Add the include directories for your Perl 5
33940 installation under "Additional include directories".</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 "Link
33946 Options". Add the Perl library file to your link libraries. For example
33947 "perl.lib". 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>
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">
33960 $a = example::fact(4);
33961 print "$a\n";
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
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">
33985 <P> Now, in Perl:</P>
33986 <DIV class="targetlang">
33989 $a = &example::fact(2);
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">
34005 <P> is accessed as follows :</P>
34006 <DIV class="targetlang">
34009 print $example::Spam,"\n";
34010 $example::Spam = $example::Spam + 4
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
34018 <P> To make ordinary variables read-only, you can also use the <TT>
34019 %immutable</TT> directive. For example:</P>
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
34043 extern char *path; // Declared later in the input
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
34057 <DIV class="targetlang">
34060 print $example::FOO,"\n"; # OK
34061 $example::FOO = 2; # Error
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
34068 <DIV class="targetlang">
34071 print example::FOO,"\n";
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>
34081 Matrix *new_Matrix(int n, int m);
34084 <P> The module returns a value generated as follows:</P>
34085 <DIV class="targetlang">
34087 $ptr = new_Matrix(int n, int m); # Save pointer return result
34088 bless $ptr, "p_Matrix"; # Bless it as a pointer to Matrix
34091 <P> SWIG uses the "blessing" 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">
34097 if (defined($ptr)) {
34098 print "Not a NULL pointer.";
34100 print "Is a NULL pointer.";
34105 <P> To create a NULL pointer, you should pass the <TT>undef</TT> value
34107 <P> The "value" 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
34115 <DIV class="targetlang">
34118 print "a and b point to the same thing in C";
34120 print "a and b point to different objects.";
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>
34136 Bar *FooToBar(Foo *f) {
34140 /* C++-style cast */
34141 Foo *BarToFoo(Bar *b) {
34142 return dynamic_cast<Foo*>(b);
34145 Foo *IncrFoo(Foo *f, int i) {
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 "SWIG Basics" chapter.
34170 <P> gets mapped into the following collection of accessor functions:</P>
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)
34184 <P> These functions are then used to access structure data from Perl as
34186 <DIV class="targetlang">
34188 $v = example::new_Vector();
34189 print example::Vector_x_get($v),"\n"; # Get x component
34190 example::Vector_x_set($v,7.8); # Change x component
34193 <P> Similar access is provided for unions and the data members of C++
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>
34203 int x; /* Read-only members */
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>
34224 <P> produces a single accessor function like this:</P>
34227 int *Foo_x_get(Foo *self) {
34232 <P> If you want to set an array member, you will need to supply a
34233 "memberin" 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.
34249 <P> generates accessor functions such as this:</P>
34252 Foo *Bar_f_get(Bar *b) {
34253 return &b->f;
34256 void Bar_f_set(Bar *b, Foo *val) {
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>
34270 int search(char *item);
34271 void insert(char *item);
34272 void remove(char *item);
34275 static void print(List *l);
34279 <P> When wrapped by SWIG, the following functions are created :</P>
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);
34294 <P> In Perl, these functions are used in a straightforward manner:</P>
34295 <DIV class="targetlang">
34298 $l = example::new_List();
34299 example::List_insert($l,"Ale");
34300 example::List_insert($l,"Stout");
34301 example::List_insert($l,"Lager")
34302 example::List_print($l)
34306 print example::List_length_get($l),"\n";
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>
34325 class Bar : public Foo {
34330 <P> and a function</P>
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
34346 /* Forward renaming declarations */
34347 %rename(foo_i) foo(int);
34348 %rename(foo_d) foo(double);
34350 void foo(int); // Becomes 'foo_i'
34351 void foo(char *c); // Stays 'foo' (not renamed)
34355 void foo(int); // Becomes 'foo_i'
34356 void foo(double); // Becomes 'foo_d'
34361 <P> Now, in Perl, the methods are accessed as follows:</P>
34362 <DIV class="targetlang">
34366 $s = example::new_Spam();
34367 example::Spam_foo_i($s,3);
34368 example::Spam_foo_d($s,3.14);
34371 <P> Please refer to the "SWIG Basics" 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
34379 <LI>operator++</LI>
34380 <LI>operator--</LI>
34385 <LI>operator==</LI>
34386 <LI>operator!=</LI>
34388 <LI>operator></LI>
34389 <LI>operator<</LI>
34390 <LI>operator and</LI>
34391 <LI>operator or</LI>
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">
34400 use example; # load the example module
34401 print example::fact(4),"\n" # Call a function in it
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
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
34421 %module "Foo::Bar::Baz"
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>
34436 %module(package="XML::Xerces") "XML::Xerces::SAX
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>
34448 This can be changed by giving SWIG the -package
34452 <div class="code"><pre>
34453 % swig -perl -package Foo example.i
34454 </pre></div>
34457 In this case, you still create a module called `<tt>example</tt>' exactly as before, but
34458 all of the functions in that module will be installed into the package
34459 `<tt>Foo</tt>.' For example :
34462 <div class="targetlang"><pre>
34463 use example; # Load the module like before
34464 print Foo::fact(4),"\n"; # Call a function in package FooBar
34465 </pre></div>
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>
34472 void add(int x, int y, int *result) {
34480 int sub(int *x, int *y) {
34485 <P> The easiest way to handle these situations is to use the <TT>
34486 typemaps.i</TT> file. For example:</P>
34490 %include "typemaps.i"
34492 void add(int, int, int *OUTPUT);
34493 int sub(int *INPUT, int *INPUT);
34496 <P> In Perl, this allows you to pass simple values. For example:</P>
34497 <DIV class="targetlang">
34499 $a = example::add(3,4);
34500 print "$a\n";
34502 $b = example::sub(7,4);
34503 print "$b\n";
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>
34515 %include "typemaps.i"
34517 %apply int *OUTPUT { int *result };
34518 %apply int *INPUT { int *x, int *y};
34520 void add(int x, int y, int *result);
34521 int sub(int *x, int *y);
34524 <P> If a function mutates one of its parameters like this,</P>
34527 void negate(int *x) {
34532 <P> you can use <TT>INOUT</TT> like this:</P>
34535 %include "typemaps.i"
34537 void negate(int *INOUT);
34540 <P> In Perl, a mutated parameter shows up as a return value. For
34542 <DIV class="targetlang">
34544 $a = example::negate(3);
34545 print "$a\n";
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>
34554 /* send message, return number of bytes sent, along with success code */
34555 int send_message(char *text, int len, int *success);
34558 <P> To wrap such a function, simply use the <TT>OUTPUT</TT> rule above.
34563 %include "typemaps.i"
34564 %apply int *OUTPUT { int *success };
34566 int send_message(char *text, int *success);
34569 <P> When used in Perl, the function will return multiple values.</P>
34570 <DIV class="targetlang">
34572 ($bytes, $success) = example::send_message("Hello World");
34575 <P> Another common use of multiple return values are in query functions.
34579 void get_dimensions(Matrix *m, int *rows, int *columns);
34582 <P> To wrap this, you might use the following:</P>
34586 %include "typemaps.i"
34587 %apply int *OUTPUT { int *rows, int *columns };
34589 void get_dimensions(Matrix *m, int *rows, *columns);
34592 <P> Now, in Perl:</P>
34593 <DIV class="targetlang">
34595 ($r,$c) = example::get_dimensions($m);
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>
34603 %include "typemaps.i"
34605 void add(int x, int y, int *REFERENCE);
34609 <DIV class="targetlang">
34613 example::add(3,4,\$c);
34614 print "$c\n";
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>
34628 class RangeError {}; // Used for an exception
34630 class DoubleArray {
34635 // Create a new array of fixed size
34636 DoubleArray(int size) {
34637 ptr = new double[size];
34640 // Destroy an array
34644 // Return the length of the array
34649 // Get an item from the array and perform bounds checking.
34650 double getitem(int i) {
34651 if ((i >= 0) && (i < n))
34654 throw RangeError();
34657 // Set an item in the array and perform bounds checking.
34658 void setitem(int i, double val) {
34659 if ((i >= 0) && (i < n))
34662 throw RangeError();
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>
34677 catch (RangeError) {
34678 croak("Array index out-of-bounds");
34682 class DoubleArray {
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
34699 %exception getitem {
34703 catch (RangeError) {
34704 croak("Array index out-of-bounds");
34708 %exception setitem {
34712 catch (RangeError) {
34713 croak("Array index out-of-bounds");
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>
34724 %define RANGE_ERROR
34729 catch (RangeError) {
34730 croak("Array index out-of-bounds");
34735 %exception getitem RANGE_ERROR;
34736 %exception setitem RANGE_ERROR;
34739 <P> Since SWIG's exception handling is user-definable, you are not
34740 limited to C++ exception handling. See the chapter on "<A href="#Customization">
34741 Customization features</A>" 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>
34750 catch (RangeError) {
34751 croak("Array index out-of-bounds");
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 "<A href="#Typemaps">Typemaps</A>
34764 " 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>
34778 $1 = (int) SvIV($input);
34779 printf("Received an integer : %d\n", $1);
34783 extern int fact(int n);
34788 <P> Typemaps are always associated with some specific aspect of code
34789 generation. In this case, the "in" 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">
34800 $n = example::fact(6);
34801 print "$n\n";
34805 Received an integer : 6
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">
34817 %typemap(in) int n {
34818 $1 = (int) SvIV($input);
34819 printf("n = %d\n",$1);
34822 typedef int Integer;
34823 extern int fact(Integer n); // Above typemap is applied
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.
34832 <DIV class="targetlang">
34834 %typemap(in) (char *str, unsigned len) {
34835 $1 = SvPV($input,$2);
34838 int count(char c, char *str, unsigned len);
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">
34846 example::count("e","Hello World");
34851 <H3><A name="Perl5_nn29"></A>28.7.2 Perl5 typemaps</H3>
34852 <P> The previous section illustrated an "in" 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 "out" typemap like this:</P>
34856 <DIV class="targetlang">
34858 %typemap(out) int {
34859 $result = sv_newmortal();
34860 set_setiv($result, (IV) $1);
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 "<A href="#Typemaps">
34889 Typemaps</A>" 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
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
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
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 "perlguts" 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>
34928 void sv_setiv(SV *sv, IV value);
34929 SV *newSViv(IV value);
34933 <P><B> Perl Floating Point Functions</B></P>
34937 void sv_setnv(SV *, double value);
34938 SV *newSVnv(double value);
34942 <P><B> Perl String Functions</B></P>
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);
34950 void sv_catpv(SV *, char *);
34951 void sv_catpvn(SV *, char *, STRLEN);
34954 <P><B> Perl References</B></P>
34957 void sv_setref_pv(SV *, char *, void *ptr);
34958 int sv_isobject(SV *);
34960 int sv_isa(SV *, char *0;
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 "<TT>perl5.swg</TT>" and "<TT>typemaps.i</TT>
34966 " in the SWIG library.</P>
34967 <H3><A name="Perl5_nn33"></A>28.8.1 Converting a Perl5 array to a char
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>
34977 // This tells SWIG to treat char ** as a special case
34978 %typemap(in) char ** {
34983 if (!SvROK($input))
34984 croak("Argument $argnum is not a reference.");
34985 if (SvTYPE(SvRV($input)) != SVt_PVAV)
34986 croak("Argument $argnum is not an array.");
34987 tempav = (AV*)SvRV($input);
34988 len = av_len(tempav);
34989 $1 = (char **) malloc((len+2)*sizeof(char *));
34990 for (i = 0; i <= len; i++) {
34991 tv = av_fetch(tempav, i, 0);
34992 $1[i] = (char *) SvPV(*tv,PL_na);
34997 // This cleans up the char ** array after the function call
34998 %typemap(freearg) char ** {
35002 // Creates a new Perl array and places a NULL-terminated char ** into it
35003 %typemap(out) char ** {
35007 /* Figure out how many elements we have */
35010 svs = (SV **) malloc(len*sizeof(SV *));
35011 for (i = 0; i < len ; i++) {
35012 svs[i] = sv_newmortal();
35013 sv_setpv((SV*)svs[i],$1[i]);
35015 myav = av_make(len,svs);
35017 $result = newRV_noinc((SV*)myav);
35018 sv_2mortal($result);
35022 // Now a few test functions
35024 int print_args(char **argv) {
35027 printf("argv[%d] = %s\n", i,argv[i]);
35033 // Returns a char ** list
35034 char **get_args() {
35035 static char *values[] = { "Dave", "Mike", "Susan", "John", "Michelle", 0};
35036 return &values[0];
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">
35047 @a = ("Dave", "Mike", "John", "Mary"); # 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,"\n"; # Print it out
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
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>
35065 %typemap(argout) int *OUTPUT {
35066 if (argvi >= items) {
35067 EXTEND(sp,1); /* Extend the stack by 1 object */
35069 $result = sv_newmortal();
35070 sv_setiv($target,(IV) *($1));
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>
35083 // This tells SWIG to treat an double * argument with name 'OutDouble' as
35084 // an output value.
35086 %typemap(argout) double *OUTPUT {
35087 $result = sv_newmortal();
35088 sv_setnv($result, *$input);
35089 argvi++; /* Increment return count -- important! */
35092 // We don't care what the input value is. Ignore, but set to a temporary variable
35094 %typemap(in,numinputs=0) double *OUTPUT(double junk) {
35098 // Now a function to test it
35100 /* Returns the first two input arguments */
35101 int multout(double a, double b, double *out1, double *out2) {
35108 // If we name both parameters OutDouble both will be output
35110 int multout(double a, double b, double *OUTPUT, double *OUTPUT);
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
35117 <DIV class="targetlang">
35119 @r = multout(7,13);
35120 print "multout(7,13) = @r\n";
35121 ($x,$y) = multout(7,13);
35124 <H3><A name="Perl5_nn36"></A>28.8.4 Accessing array structure members</H3>
35125 <P> Consider the following data structure :</P>
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 "memberin" typemap
35143 %typemap(memberin) int [SIZE] {
35145 for (i = 0; i < SIZE; i++) {
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>
35158 %typemap(memberin) int [ANY] {
35160 for (i = 0; i < $1_dim0; i++) {
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 "in" typemap. For example,
35170 the "in" typemap in the previous section would be used to convert an <TT>
35171 int[]</TT> array to C whereas the "memberin" 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
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>
35180 void add(double a, double b, double *c) {
35185 <P> A common misinterpretation of this function is the following Perl
35187 <DIV class="targetlang">
35192 $c = 0.0; # Output value
35193 add($a,$b,\$c); # Place result in c (Except that it doesn't work)
35196 <P> To make this work with a reference, you can use a typemap such as
35200 %typemap(in) double * (double dvalue) {
35202 if (!SvROK($input)) {
35203 croak("expected a reference\n");
35205 tempsv = SvRV($input);
35206 if ((!SvNOK(tempsv)) && (!SvIOK(tempsv))) {
35207 croak("expected a double reference\n");
35209 dvalue = SvNV(tempsv);
35213 %typemap(argout) double * {
35215 tempsv = SvRV($input);
35216 sv_setnv(tempsv, *$1);
35220 <P> Now, if you place this before the add function, you can do this :</P>
35221 <DIV class="targetlang">
35226 add($a,$b,\$c); # Now it works!
35227 print "$c\n";
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
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
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>
35260 if (SWIG_ConvertPtr($input, (void **) &f, SWIGTYPE_p_Foo, 0) == -1) return NULL;
35262 SV *sv = sv_newmortal();
35263 SWIG_MakePtr(sv, f, SWIGTYPE_p_Foo, 0);
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>
35270 %typemap(in) Foo * {
35271 if ((SWIG_ConvertPtr($input,(void **) &$1, $1_descriptor,0)) == -1) return NULL;
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>
35279 %typemap(in) Foo * {
35280 if ((SWIG_ConvertPtr($input,(void **) &$1, $descriptor(Foo *), 0)) == -1) return NULL;
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>
35296 $ swig -c++ -perl -noproxy example.i
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>
35312 Vector(double x, double y, double z);
35319 <P> When wrapped, SWIG creates the following set of low-level accessor
35320 functions as described in previous sections.</P>
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);
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">
35338 package example::Vector;
35339 @ISA = qw( example );
35341 %BLESSEDMEMBERS = ();
35346 $self = vectorc::new_Vector(@args);
35347 return undef if (!defined($self));
35348 bless $self, "example::Vector";
35351 tie %retval, "example::Vector", $self;
35352 return bless \%retval,"Vector";
35356 return unless $_[0]->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};
35365 my ($self,$field) = @_;
35366 my $member_func = "vectorc::Vector_${field}_get";
35367 my $val = &$member_func($self);
35368 if (exists $BLESSEDMEMBERS{$field}) {
35369 return undef if (!defined($val));
35371 tie %retval,$BLESSEDMEMBERS{$field},$val;
35372 return bless \%retval, $BLESSEDMEMBERS{$field};
35378 my ($self,$field,$newval) = @_;
35379 my $member_func = "vectorc::Vector_${field}_set";
35380 if (exists $BLESSEDMEMBERS{$field}) {
35381 &$member_func($self,tied(%{$newval}));
35383 &$member_func($self,$newval);
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 "new" and
35391 "DESTROY". 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
35396 <P> To use our new proxy class we can simply do the following:</P>
35397 <DIV class="targetlang">
35399 # Perl code using Vector class
35400 $v = new Vector(2,3,4);
35401 $w = Vector->new(-1,-2,-3);
35403 # Assignment of a single member
35406 # Assignment of all members
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>
35425 Vector *Vector_get(Vector *v, int index) {
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>
35436 Vector *new_Vector(double x, double y, double z) {
35438 v = new Vector(x,y,z); // Call C++ constructor
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
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
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">
35470 # Perl code to change ownership of an object
35471 $v = new Vector(x,y,z);
35475 <P> To acquire ownership of an object, the <TT>ACQUIRE</TT> method can
35477 <DIV class="targetlang">
35479 # Given Perl ownership of a file
35480 $u = Vector_get($v);
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>
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">
35509 %BLESSEDMEMBERS = (
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
35521 <P> This implementation allows us to operate on nested structures as
35523 <DIV class="targetlang">
35525 # Perl access of nested structure
35526 $p = new Particle();
35527 $p->{f}->{x} = 0.0;
35528 %${$p->{v}} = ( x=>0, y=>0, z=>0);
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>
35536 double dot_product(Vector *v1, Vector *v2);
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
35543 <DIV class="targetlang">
35547 $args[0] = tied(%{$args[0]}); # Get the real pointer values
35548 $args[1] = tied(%{$args[1]});
35549 my $result = vectorc::dot_product(@args);
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
35563 // SWIG interface file for shapes class
35566 #include "shapes.h"
35571 virtual double area() = 0;
35572 virtual double perimeter() = 0;
35573 void set_location(double x, double y);
35575 class Circle : public Shape {
35577 Circle(double radius);
35580 double perimeter();
35582 class Square : public Shape {
35584 Square(double size);
35587 double perimeter();
35592 <P> The resulting, Perl wrapper class will create the following code :</P>
35593 <DIV class="targetlang">
35599 @ISA = (shapes Shape);
35602 @ISA = (shapes Shape);
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("shadow")</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">
35626 /* Let's make the constructor of the class Square more verbose */
35627 %feature("shadow") Square(double w)
35631 my $self = examplec::new_Square(@_);
35632 print STDERR "Constructed an @{[ref($self)]}\n";
35633 bless $self, $pkg if defined($self);
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>
35651 void set_transform(Image *im, double x[4][4]);
35654 /* Rewrite the high level interface to set_transform */
35659 my $a = new_mat44();
35660 for (my $i = 0; $i < 4, $i++)
35662 for (my $j = 0; $j < 4, $j++)
35664 mat44_set($a, $i, $j, $x->[i][j])
35667 example.set_transform($im, $a);
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">
35683 set_transform($im, $a);
35687 <!-- Hand crafted HTML -->
35688 <H1><A name="Php"></A>29 SWIG and PHP</H1>
35691 <DIV class="sectiontoc">
35693 <LI><A href="#Php_nn1">Generating PHP Extensions</A>
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>
35699 <LI><A href="#Php_nn2">Basic PHP interface</A>
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>
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>
35714 <LI><A href="#Php_nn2_7">PHP Pragmas, Startup and Shutdown code</A></LI>
35717 <LI><A href="#Php_nn3">Cross language polymorphism</A>
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>
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 "php-dev" or "php-devel" 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
35755 swig -php example.i
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>
35787 gcc `php-config --includes` -fpic -c example_wrap.c
35788 gcc -shared example_wrap.o -o example.so
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>
35797 extension=/path/to/modulename.so
35800 <P> Alternatively, you can load it explicitly only for scripts which
35801 need it by adding this line:</P>
35804 dl("/path/to/modulename.so"); // Load the module
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>
35811 include("example.php");
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>
35831 %constant int E = 2.71828
35834 <P> you can access the constants in your php script like this,</P>
35837 include("example.php");
35839 echo "PI = " . PI . "\n";
35841 echo "E = " . E . "\n";
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>
35852 #define EASY_TO_MISPELL 0
35855 <P> accessed incorrectly in PHP,</P>
35858 include("example.php");
35860 if(EASY_TO_MISPEL) {
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
35883 <P> accessed from PHP,</P>
35886 include("example.php");
35891 <P> will output "Hello Test" rather than "Hello World". 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
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>
35922 void print_seki() {
35923 zend_printf("seki is now %f\n",seki);
35928 <P> is accessed as follows:</P>
35931 include("example.php");
35933 seki_set( seki_get() * 2); # The C variable is now 4.
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
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>
35953 double bar(double, double b = 3.0);
35957 <P> Will be accessed in PHP like this :</P>
35960 include("example.php");
35962 $b = bar(3.5, -1.5);
35963 $c = bar(3.5); # Use default argument for 2nd parameter
35967 <!-- This isn't correct for 1.3.30 and needs rewriting to reflect reality
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:
35973 <div class="code"><pre>
35975 $a = foo("2");
35977 </pre></div>
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
35985 <div class="code"><pre>
35986 $s = "2 A string representing two";
35987 $a = foo($s); # invokes 'foo(2)';
35988 print $s; # The value of $s was not changed.
35989 </pre></div>
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>
35998 <!-- This isn't correct for 1.3.30 and needs rewriting to reflect reality
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:
36007 <div class="code"><pre>
36008 void doit( int i );
36009 void doit( double i );
36010 </pre></div>
36013 it is questionable which to invoke when <tt>doit("2");</tt> is used in
36014 PHP. The string <tt>"2"</tt> simultaneously represents the integer
36015 <tt>2</tt> and the double <tt>2.0</tt>.
36019 In order to provide the most natural experience to PHP programmers,
36020 the default <tt>%typecheck</tt> implemented in <tt>php.swg</tt>
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.
36027 It should be noted that <tt>SWIGTYPE</tt> references and pointers will
36028 not be silently converted. So these two functions:
36031 <div class="code"><pre>
36032 void doit( const Vector & );
36033 void doit( int i );
36034 </pre></div>
36037 Cause less confusion and <tt>doit("2");</tt> will invoke the function
36038 taking the integer argument.
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>
36048 void add( int *in1, int *in2, int *result);
36051 <P> One can include<B> cpointer.i</B> to generate PHP wrappers to <TT>
36056 %include "cpointer.i"
36057 %pointer_functions(int,intp)
36059 void add( int *in1, int *in2, int *result);
36062 <P> This will result in the following usage in PHP:</P>
36067 include("example.php");
36071 $result=new_intp();
36073 add( $in1, $in2, $result );
36075 echo "The sum " . intp_value($in1) . " + " . intp_value($in2) . " = " . intp_value( $result) . "\n";
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>
36086 %include "typemaps.i"
36088 void add( int *INPUT, int *INPUT, int *OUTPUT);
36092 <P> This will result in the following usage in PHP:</P>
36097 include("example.php");
36101 $result= add($in1,$in2); # Note using variables for the input is unnecessary.
36103 echo "The sum $in1 + $in2 = $result\n";
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>
36114 %include "phppointers.i"
36116 void add( int *REF, int *REF, int *REF);
36120 <P> This will result in the following usage in PHP:</P>
36125 include("example.php");
36130 add(&$in1,&$in2,&$result);
36132 echo "The sum $in1 + $in2 = $result\n";
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 "-noproxy" 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>
36161 double magnitude();
36169 <P> Would be used in the following way from PHP5:</P>
36173 require "vector.php";
36180 echo "Magnitude of ($v->x,$v->y,$v->z) = " . $v->magnitude() . "\n";
36182 $v = NULL; # destructor called.
36184 $c = new Complex();
36189 # $c destructor called when $c goes out of scope.
36193 <P> Member variables and methods are accessed using the <TT>-></TT>
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>
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);
36211 Complex_re_set($obj,$d);
36212 Complex_re_get($obj);
36213 Complex_im_set($obj,$d);
36214 Complex_im_get($obj);
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>
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>
36236 $o_copy = new Object($o);
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>
36254 static int threats;
36259 <P> would be accessed in PHP as,</P>
36262 include("example.php");
36264 echo "There has now been " . Ko::threats() . " threats\n";
36268 <P> To set the static member variable, pass the value as the argument to
36269 the class function, e.g.</P>
36275 echo "There has now been " . Ko::threats() . " threats\n";
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>
36286 static void threats();
36289 </DIV> would be executed in PHP as,<DIV class="code">
36291 include("example.php");
36295 <H3><A name="Php_nn2_7"></A>29.2.7 PHP Pragmas, Startup and Shutdown
36297 <P> To place PHP code in the generated "example.php" file one can use
36298 the<B> code</B> pragma. The code is inserted after loading the shared
36303 %pragma(php) code="
36304 # This code is inserted into example.php
36305 echo \"example.php execution\\n\";
36309 <P> Results in the following in "example.php"</P>
36312 # This code is inserted into example.php
36313 echo "example.php execution\n";
36316 <P> The<B> include</B> pragma is a short cut to add include statements
36317 to the example.php file.</P>
36321 %pragma(php) code="
36322 include \"include.php\";
36324 %pragma(php) include="include.php" // equivalent.
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>
36332 %pragma(php) phpinfo="
36333 zend_printf("An example of PHP support through SWIG\n");
36334 php_info_print_table_start();
36335 php_info_print_table_header(2, \"Directive\", \"Value\");
36336 php_info_print_table_row(2, \"Example support\", \"enabled\");
36337 php_info_print_table_end();
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>
36347 zend_printf("Inserted into PHP_MINIT_FUNCTION\n");
36350 zend_printf("Inserted into PHP_MINIT_FUNCTION\n");
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>
36360 zend_printf("Inserted into PHP_MSHUTDOWN_FUNCTION\n");
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 "directors"
36393 option to the %module directive, like this:</P>
36396 %module(directors="1") modulename
36399 <P> Without this option no director code will be generated. Second, you
36400 must use the %feature("director") 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>
36405 // generate directors for all classes that have virtual methods
36406 %feature("director");
36408 // generate directors for all virtual methods in class Foo
36409 %feature("director") Foo;
36411 // generate a director for just Foo::bar()
36412 %feature("director") Foo::bar;
36415 <P> You can use the %feature("nodirector") directive to turn off
36416 directors for specific classes or methods. So for example,</P>
36419 %feature("director") Foo;
36420 %feature("nodirector") Foo::bar;
36423 <P> will generate directors for all virtual methods of class Foo except
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>
36430 %feature("director") Foo;
36434 virtual void one();
36435 virtual void two();
36438 class Bar: public Foo {
36440 virtual void three();
36444 <P> then at the PHP side you can define</P>
36445 <DIV class="targetlang">
36447 require("mymodule.php");
36449 class MyFoo extends Foo {
36451 print "one from php\n";
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 "_cPtr" and "thisown"
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 "appropriate place" 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 "appropriate place" 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 "extended" 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 "good reason not to" 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>->_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
36524 <P> This relationship can be reversed by calling the special <TT>
36525 ->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>
36539 class FooContainer {
36541 void addFoo(Foo *);
36546 <BR><DIV class="targetlang">
36548 $c = new FooContainer();
36550 $a->thisown = 0;
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("director:except") directive. The following code
36563 should suffice in most cases:</P>
36566 %feature("director:except") {
36567 if ($error == FAILURE) {
36568 throw Swig::DirectorMethodException();
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
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>
36590 catch (Swig::DirectorException &e) { SWIG_fail; }
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
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
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>
36635 <H1><A name="Pike"></A>30 SWIG and Pike</H1>
36638 <DIV class="sectiontoc">
36640 <LI><A href="#Pike_nn2">Preliminaries</A>
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>
36647 <LI><A href="#Pike_nn6">Basic C/C++ Mapping</A>
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>
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
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 "<A href="#SWIG">SWIG Basics</A>"
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>
36674 <PRE>%module example
36677 <BR>#include "example.h"
36680 <BR>int fact(int n);
36683 <P> To build a C extension module for Pike, run SWIG using the <TT>-pike</TT>
36686 <PRE>$ <B>swig -pike example.i</B>
36689 <P> If you're building a C++ extension, be sure to add the <TT>-c++</TT>
36692 <PRE>$ <B>swig -c++ -pike example.i</B>
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>
36705 <PRE>$ <B>swig -pike -o pseudonym.c example.i</B>
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>
36713 <PRE>/usr/local/pike/7.4.10/include/pike
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>
36725 Pike v7.4 release 10 running Hilfe v3.5 (Incremental Pike Frontend)
36726 > <B>import example;</B>
36727 > <B>fact(4);</B>
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
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
36748 <P> creates a new built-in function <TT>example.fact(n)</TT> that works
36749 exactly as you'd expect it to:</P>
36752 > <B>import example;</B>
36753 > <B>fact(4);</B>
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>
36768 <P> will result in two functions, <TT>Foo_get()</TT> and <TT>Foo_set()</TT>
36772 > <B>import example;</B>
36773 > <B>Foo_get();</B>
36774 (1) Result: 3.000000
36775 > <B>Foo_set(3.14159);</B>
36777 > <B>Foo_get();</B>
36778 (3) Result: 3.141590
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
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>
36800 static void print();
36801 static int nshapes;
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>
36810 <H1><A name="Python"></A>31 SWIG and Python</H1>
36813 <DIV class="sectiontoc">
36815 <LI><A href="#Python_nn2">Overview</A></LI>
36816 <LI><A href="#Python_nn3">Preliminaries</A>
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>
36828 <LI><A href="#Python_nn13">A tour of basic C/C++ wrapping</A>
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>
36848 <LI><A href="#Python_nn28">Further details on the Python class interface</A>
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>
36855 <LI><A href="#Python_directors">Cross language polymorphism</A>
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>
36866 <LI><A href="#Python_nn40">Common customization features</A>
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>
36874 <LI><A href="#Python_nn45">Tips and techniques</A>
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>
36885 <LI><A href="#Python_nn53">Typemaps</A>
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>
36893 <LI><A href="#Python_nn58">Typemap Examples</A>
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
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>
36904 <LI><A href="#Python_nn65">Docstring Features</A>
36906 <LI><A href="#Python_nn66">Module docstring</A></LI>
36907 <LI><A href="#Python_nn67">%feature("autodoc")</A>
36909 <LI><A href="#Python_nn68">%feature("autodoc", "0")</A></LI>
36910 <LI><A href="#Python_nn69">%feature("autodoc", "1")</A></LI>
36911 <LI><A href="#Python_nn70">%feature("autodoc", "docstring")</A></LI>
36914 <LI><A href="#Python_nn71">%feature("docstring")</A></LI>
36917 <LI><A href="#Python_nn72">Python Packages</A></LI>
36918 <LI><A href="#Python_python3support">Python 3 Support</A>
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>
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 "<A href="#SWIG">SWIG Basics</A>"
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>
36957 /* File: example.i */
36961 #define SWIG_FILE_WITH_INIT
36962 #include "example.h"
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>
36974 /* File: example.c */
36976 #include "example.h"
36979 if (n < 0){ /* This should probably return an error, but this is simpler */
36986 /* testing for overflow would be a good idea here */
36987 return n * fact(n-1);
36993 <P> With the header file:</P>
36996 /* File: example.h */
37001 <P> To build a Python module, run SWIG using the <TT>-python</TT>
37003 <DIV class="shell">
37005 $ swig -python example.i
37008 <P> If building a C++ extension, add the <TT>-c++</TT> option:</P>
37009 <DIV class="shell">
37011 $ swig -c++ -python example.i
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>
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>
37046 #!/usr/bin/env python
37049 setup.py file for SWIG example
37052 from distutils.core import setup, Extension
37055 example_module = Extension('_example',
37056 sources=['example_wrap.c', 'example.c'],
37059 setup (name = 'example',
37061 author = "SWIG Docs",
37062 description = """Simple swig example from docs""",
37063 ext_modules = [example_module],
37064 py_modules = ["example"],
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 "<TT>example.py</TT>", then the name
37075 of the corresponding object file will be"<TT>_example.so</TT>"</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">
37082 $ swig -python example.i
37083 $ python setup.py build_ext --inplace
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>
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>
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">
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
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 "<TT>example</TT>", then the name of the corresponding
37127 object file should be "<TT>_example.so</TT>" or "<TT>_examplemodule.so</TT>
37128 ". 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>
37158 extern int fact(int);
37159 extern int mod(int, int);
37160 extern double My_variable;
37163 %include "embed.i" // Include code for a static version of Python
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">
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 \
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 "work" 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">
37205 >>> import example
37206 >>> example.fact(4)
37211 <P> A common error received by first-time users is the following:</P>
37212 <DIV class="targetlang">
37214 >>> import example
37215 Traceback (most recent call last):
37216 File "<stdin>", line 1, in ?
37217 File "example.py", line 2, in ?
37219 ImportError: No module named _example
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">
37230 >>> import example
37231 Traceback (most recent call last):
37232 File "<stdin>", line 1, in ?
37233 ImportError: dynamic module does not define init function (init_example)
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">
37249 Traceback (most recent call last):
37250 File "example.py", line 3, in ?
37252 ImportError: ./_example.so: undefined symbol: fact
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
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">
37271 $ gcc -shared example.o example_wrap.o -L/home/beazley/projects/lib <B>-lfoo</B> \
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">
37279 >>> import example
37280 Traceback (most recent call last):
37281 File "<stdin>", line 1, in ?
37282 ImportError: libfoo.so: cannot open shared object file: No such file or directory
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">
37294 $ gcc -shared example.o example_wrap.o -L/home/beazley/projects/lib -lfoo \
37295 <B>-Xlinker -rpath /home/beazley/projects/lib </B> \
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
37305 <DIV class="shell">
37307 $ env LD_LIBRARY_PATH=/home/beazley/projects/lib python
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
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
37322 <P> On most machines, C++ extension modules should be linked using the
37323 C++ compiler. For example:</P>
37324 <DIV class="shell">
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
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>
37341 <DIV class="shell">
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
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">
37366 libstdc++-libc6.1-1.so.2 => /usr/lib/libstdc++-libc6.1-1.so.2 (0x40019000)
37367 libm.so.6 => /lib/libm.so.6 (0x4005b000)
37368 libc.so.6 => /lib/libc.so.6 (0x40077000)
37369 /lib/ld-linux.so.2 => /lib/ld-linux.so.2 (0x40000000)
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
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
37409 <H3><A name="Python_nn12"></A>31.2.8 Building Python Extensions under
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
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>
37431 <LI>Open up a new workspace and use the AppWizard to select a DLL
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 "Custom Build" option.</LI>
37441 <LI>Enter "SWIG" in the description field.</LI>
37442 <LI>Enter "<TT>swig -python -o $(ProjDir)\$(InputName)_wrap.c
37443 $(InputPath)</TT>" in the "Build command(s) field"</LI>
37444 <LI>Enter "<TT>$(ProjDir)\$(InputName)_wrap.c</TT>" in the "Output
37445 files(s) field".</LI>
37446 <LI>Next, select the settings for the entire project and go to
37447 "C++:Preprocessor". Add the include directories for your Python
37448 installation under "Additional include directories".</LI>
37449 <LI>Define the symbol __WIN32__ under preprocessor options.</LI>
37450 <LI>Finally, select the settings for the entire project and go to "Link
37451 Options". Add the Python library file to your link libraries. For
37452 example "python21.lib". 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>
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
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">
37466 >>> import example
37467 >>> print example.fact(4)
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
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">
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
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">
37511 >>> import example
37512 >>> print example.fact(4)
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
37522 <DIV class="targetlang">
37527 <P> "a" becomes a name for an object containing the value 3.4. If you
37529 <DIV class="targetlang">
37534 <P> then "a" and "b" are both names for the object containing the value
37535 3.4. Thus, there is only one object containing 3.4 and "a" and "b" 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
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>
37547 // SWIG interface file with global variables
37551 extern int My_variable;
37552 extern double density;
37557 <P> Now look at the Python interface:</P>
37558 <DIV class="targetlang">
37560 >>> import example
37561 >>> # Print out value of a C global variable
37562 >>> print example.cvar.My_variable
37564 >>> # Set the value of a C global variable
37565 >>> example.cvar.density = 0.8442
37566 >>> # Use in a math operation
37567 >>> example.cvar.density = example.cvar.density*1.10
37570 <P> If you make an error in variable assignment, you will receive an
37571 error message. For example:</P>
37572 <DIV class="targetlang">
37574 >>> example.cvar.density = "Hello"
37575 Traceback (most recent call last):
37576 File "<stdin>", line 1, in ?
37577 TypeError: C variable 'density (double )'
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
37584 <P> To make ordinary variables read-only, you can use the <TT>%immutable</TT>
37585 directive. For example:</P>
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>
37608 extern char *path; // Read-only (due to %immutable)
37611 <P> If you would like to access variables using a name other than "<TT>
37612 cvar</TT>", it can be changed using the <TT>-globals</TT> option :</P>
37613 <DIV class="shell">
37615 $ swig -python -globals myvar example.i
37618 <P> Some care is in order when importing multiple SWIG modules. If you
37619 use the "<TT>from <file> import *</TT>" 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
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>
37633 #define VERSION "1.0"
37635 enum Beverage { ALE, LAGER, STOUT, PILSNER };
37637 %constant int FOO = 42;
37638 %constant const char *path = "/usr/local";
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>
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>
37662 FILE *fopen(const char *filename, const char *mode);
37663 int fputs(const char *, FILE *);
37664 int fclose(FILE *);
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">
37671 >>> import example
37672 >>> f = example.fopen("junk","w")
37673 >>> example.fputs("Hello World\n", f)
37674 >>> example.fclose(f)
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">
37682 >>> print f
37683 <Swig Object at _08a71808_p_FILE>
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">
37696 >>> print str(f)
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
37703 <DIV class="targetlang">
37705 >>> print int(f)
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">
37716 >>> example.fclose(None)
37719 <P> and that will be equivalent to the following, but not really useful,
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>
37741 Bar *FooToBar(Foo *f) {
37745 /* C++-style cast */
37746 Foo *BarToFoo(Bar *b) {
37747 return dynamic_cast<Foo*>(b);
37750 Foo *IncrFoo(Foo *f, int i) {
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>
37771 <P> is used as follows:</P>
37772 <DIV class="targetlang">
37774 >>> v = example.Vector()
37775 >>> v.x = 3.5
37776 >>> v.y = 7.2
37777 >>> print v.x, v.y, v.z
37782 <P> Similar access is provided for unions and the data members of C++
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">
37788 >>> print v
37789 <C Vector instance at _18e31408_p_Vector>
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">
37798 >>> print v.this
37803 <P> Further details about the Python proxy class are covered a little
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>
37813 int x; /* Read-only members */
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>
37835 <P> If accessed in Python, you will see behavior like this:</P>
37836 <DIV class="targetlang">
37838 >>> b = example.Bar()
37839 >>> print b.x
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">
37849 >>> c = example.Bar()
37850 >>> c.x = b.x # Copy contents of b.x to c.x
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>
37871 <P> Now, suppose that you access the <TT>f</TT> attribute of <TT>Bar</TT>
37873 <DIV class="targetlang">
37875 >>> b = Bar()
37876 >>> x = b.f
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
37885 Foo *x = &b->f; /* Points inside b */
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">
37892 >>> b = Bar()
37893 >>> b.f.a = 3 # Modify attribute of structure member
37894 >>> x = b.f
37895 >>> x.a = 3 # Modifies the same structure
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>
37907 int search(char *item);
37908 void insert(char *item);
37909 void remove(char *item);
37915 <P> you can use it in Python like this:</P>
37916 <DIV class="targetlang">
37918 >>> l = example.List()
37919 >>> l.insert("Ale")
37920 >>> l.insert("Stout")
37921 >>> l.insert("Lager")
37922 >>> l.get(1)
37924 >>> print l.length
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
37946 <P> In Python, the static member can be access in three different ways:</P>
37947 <DIV class="targetlang">
37949 >>> example.Spam_foo() # Spam::foo()
37950 >>> s = example.Spam()
37951 >>> s.foo() # Spam::foo() via an instance
37952 >>> example.Spam.foo() # Spam::foo(). Python-2.2 only
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
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">
37962 >>> print example.cvar.Spam_bar
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>
37975 class Bar : public Foo {
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">
37985 >>> b = Bar()
37986 >>> instance(b,Foo)
37988 >>> issubclass(Bar,Foo)
37990 >>> issubclass(Foo,Bar)
37994 <P> Furthermore, if you have functions like this</P>
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
38005 <P> In C++, there are many different ways a function might receive and
38006 manipulate objects. For example:</P>
38009 void spam1(Foo *x); // Pass by pointer
38010 void spam2(Foo &x); // Pass by reference
38011 void spam3(const Foo &x);// Pass by const reference
38012 void spam4(Foo x); // Pass by value
38013 void spam5(Foo x[]); // Array of objects
38016 <P> In Python, there is no detailed distinction like this--specifically,
38017 there are only "objects". 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">
38023 >>> f = Foo() # Create a Foo
38024 >>> spam1(f) # Ok. Pointer
38025 >>> spam2(f) # Ok. Reference
38026 >>> spam3(f) # Ok. Const reference
38027 >>> spam4(f) # Ok. Value.
38028 >>> spam5(f) # Ok. Array (1 element)
38031 <P> Similar behavior occurs for return values. For example, if you had
38032 functions like this,</P>
38038 const Foo &spam9();
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>
38057 <P> You can use them in Python in a straightforward manner:</P>
38058 <DIV class="targetlang">
38060 >>> foo(3) # foo(int)
38061 >>> foo("Hello") # foo(char *c)
38064 <P> Similarly, if you have a class like this,</P>
38070 Foo(const Foo &);
38075 <P> you can write Python code like this:</P>
38076 <DIV class="targetlang">
38078 >>> f = Foo() # Create a Foo
38079 >>> g = Foo(f) # Copy f
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>
38094 void foo(Bar &b);
38097 <P> If declarations such as these appear, you will get a warning message
38099 <DIV class="shell">
38101 example.i:12: Warning(509): Overloaded spam(short) is shadowed by spam(int)
38105 <P> To fix this, you either need to ignore or rename one of the methods.
38109 %rename(spam_short) spam(short);
38112 void spam(short); // Accessed as spam_short
38118 %ignore spam(short);
38121 void spam(short); // Ignored
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 "SWIG and C++" 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>
38138 double rpart, ipart;
38140 Complex(double r = 0, double i = 0) : rpart(r), ipart(i) { }
38141 Complex(const Complex &c) : rpart(c.rpart), ipart(c.ipart) { }
38142 Complex &operator=(const Complex &c);
38144 Complex operator+=(const Complex &c) const;
38145 Complex operator+(const Complex &c) const;
38146 Complex operator-(const Complex &c) const;
38147 Complex operator*(const Complex &c) const;
38148 Complex operator-() const;
38150 double re() const { return rpart; }
38151 double im() const { return ipart; }
38155 <P> When wrapped, it works like you expect:</P>
38156 <DIV class="targetlang">
38158 >>> c = Complex(3,4)
38159 >>> d = Complex(7,8)
38160 >>> e = c + d
38161 >>> e.re()
38163 >>> e.im()
38165 >>> c += d
38166 >>> c.re()
38168 >>> c.im()
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>
38180 friend Complex operator+(double, const Complex &c);
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
38190 %rename(Complex_add_dc) operator+(double, const Complex &);
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>
38214 <P> it works in Python as follows:</P>
38215 <DIV class="targetlang">
38217 >>> import example
38218 >>> example.fact(3)
38220 >>> v = example.Vector()
38221 >>> v.x = 3.4
38222 >>> print v.y
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>
38231 %rename(Bar_spam) Bar::spam;
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>
38257 #include "pair.h"
38260 template<class T1, class T2>
38262 typedef T1 first_type;
38263 typedef T2 second_type;
38267 pair(const T1&, const T2&);
38271 %template(pairii) pair<int,int>;
38275 <DIV class="targetlang">
38277 >>> import example
38278 >>> p = example.pairii(3,4)
38279 >>> p.first
38281 >>> p.second
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 "smart pointers." Generally, this involves the use
38291 of a template class that implements <TT>operator->()</TT> like this:</P>
38294 template<class T> class SmartPtr {
38296 T *operator->();
38301 <P> Then, if you have a class like this,</P>
38311 <P> A smart pointer would be used in C++ as follows:</P>
38314 SmartPtr<Foo> p = CreateFoo(); // Created somehow (not shown)
38316 p->x = 3; // Foo::x
38317 int y = p->bar(); // Foo::bar
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>
38327 %template(SmartPtrFoo) SmartPtr<Foo>;
38331 <P> Now, in Python, everything should just "work":</P>
38332 <DIV class="targetlang">
38334 >>> p = example.CreateFoo() # Create a smart-pointer somehow
38335 >>> p.x = 3 # Foo::x
38336 >>> p.bar() # Foo::bar
38339 <P> If you ever need to access the underlying pointer returned by <TT>
38340 operator->()</TT> itself, simply use the <TT>__deref__()</TT> method.
38342 <DIV class="targetlang">
38344 >>> f = p.__deref__() # Returns underlying Foo *
38347 <H3><A name="Python_nn27a"></A>31.3.15 C++ Reference Counted Objects
38349 <P> Another usual idiom in C++ is the use of reference counted objects.
38350 Consider for example:<DIV class="code">
38353 // implement the ref counting mechanism
38359 virtual ~RCObj() = 0;
38365 int unref() const {
38366 if (ref_count() == 0 || del_ref() == 0 ) {
38370 return ref_count();
38397 a->ref(); // 'a' is ref here
38399 B *b1 = new B(a); // 'a' is ref here
38401 B *b2 = new B(a); // 'a' is ref here
38402 delete b2; // 'a' is unref, but not deleted
38405 delete b1; // 'a' is unref, but not deleted
38406 a->unref(); // 'a' is unref and deleted
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 "ref" and "unref" features, or <TT>%ref</TT>
38416 and <TT>%unref</TT> directives (since 1.3.28). For example:</P>
38422 %feature("ref") RCObj "$this->ref();"
38423 %feature("unref") RCObj "$this->unref();"
38425 %include "rcobj.h"
38426 %include "A.h"
38429 </DIV> or, using the directive form:<DIV class="code">
38434 %ref RCObj "$this->ref();"
38435 %unref RCObj "$this->unref();"
38437 %include "rcobj.h"
38438 %include "A.h"
38442 <P> where the code passed to the "ref" and "unref" 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">
38450 a = A() # SWIG ref 'a' (new object is passed to python)
38451 b1 = B(a) # C++ ref 'a'
38453 b2 = B(a) # C++ ref 'a'
38454 return a # 'b1' and 'b2' are released, C++ unref 'a' twice
38457 exit # 'a' is released, SWIG unref 'a'
38460 <P> Note that the user doesn't explicitly need to call 'a->ref()' nor
38461 'a->unref()' (as neither 'delete a'). Instead, SWIG take cares of
38462 executing the "ref" and "unref" codes as needed. If the user doesn't
38463 specify the "ref/unref" features, SWIG will produce a code equivalent
38464 to define them as:</P>
38467 %feature("ref") ""
38468 %feature("unref") "delete $this;"
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
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">"SWIG basics"</A> and <A href="#SWIGPlus">
38485 "SWIG and C++"</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>
38497 <P> then SWIG transforms it into a set of low-level procedural wrappers.
38504 void delete_Foo(Foo *f) {
38507 int Foo_x_get(Foo *f) {
38510 void Foo_x_set(Foo *f, int value) {
38513 int Foo_spam(Foo *f, int arg1) {
38514 return f->spam(arg1);
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">
38527 def __init__(self):
38528 self.this = _example.new_Foo()
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)
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">
38544 >>> f = example.Foo()
38545 >>> f.x = 3
38546 >>> y = f.spam(5)
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>
38572 <DIV class="targetlang">
38574 >>> f = Foo()
38575 >>> f.thisown
38577 >>> g = f.bar()
38578 >>> g.thisown
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>
38595 <BR><DIV class="targetlang">
38597 >>> f = Foo()
38598 >>> s = f.spam()
38599 >>> print s.thisown
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
38625 <P> When wrapped in Python, careful observation will reveal that
38626 ownership changes whenever an object is assigned to a global variable.
38628 <DIV class="targetlang">
38630 >>> f = example.Foo()
38631 >>> f.thisown
38633 >>> example.cvar.head = f
38634 >>> f.thisown
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">
38644 >>> f = example.Foo()
38645 >>> g = example.Foo()
38646 >>> f.thisown
38648 >>> g.thisown
38650 >>> f.next = g
38651 >>> g.thisown
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
38665 void set_value(Object *v) { value = v; }
38670 <P> Now, consider the following Python code:</P>
38671 <DIV class="targetlang">
38673 >>> v = Object() # Create an object
38674 >>> n = Node() # Create a node
38675 >>> n.set_value(v) # Set value
38676 >>> v.thisown
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">
38691 >>> v.thisown = 0
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
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 "directors"
38747 option to the %module directive, like this:</P>
38750 %module(directors="1") modulename
38753 <P> Without this option no director code will be generated. Second, you
38754 must use the %feature("director") 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>
38759 // generate directors for all classes that have virtual methods
38760 %feature("director");
38762 // generate directors for all virtual methods in class Foo
38763 %feature("director") Foo;
38765 // generate a director for just Foo::bar()
38766 %feature("director") Foo::bar;
38769 <P> You can use the %feature("nodirector") directive to turn off
38770 directors for specific classes or methods. So for example,</P>
38773 %feature("director") Foo;
38774 %feature("nodirector") Foo::bar;
38777 <P> will generate directors for all virtual methods of class Foo except
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>
38784 %feature("director") Foo;
38788 virtual void one();
38789 virtual void two();
38792 class Bar: public Foo {
38794 virtual void three();
38798 <P> then at the python side you can define</P>
38799 <DIV class="targetlang">
38803 class MyFoo(mymodule.Foo):
38804 def __init__(self, foo):
38805 mymodule.Foo(self, foo)
38808 print "one from python"
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 "this" and "thisown" 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 "appropriate place" 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 "appropriate place" 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 "extended" 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 "good reason not to" 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
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>
38902 class FooContainer {
38904 void addFoo(Foo *);
38909 <BR><DIV class="targetlang">
38911 >>> c = FooContainer()
38912 >>> a = Foo().__disown()__
38913 >>> c.addFoo(a)
38914 >>> b = Foo()
38915 >>> b = b.__disown()__
38916 >>> c.addFoo(b)
38917 >>> c.addFoo(Foo().__disown()__)
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("director:except") directive. The following
38930 code should suffice in most cases:</P>
38933 %feature("director:except") {
38934 if ($error != NULL) {
38935 throw Swig::DirectorMethodException();
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
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>
38957 catch (Swig::DirectorException &e) { SWIG_fail; }
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
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
39002 <P><B> Note:</B> The director typemaps for return types based in const
39003 references, such as<DIV class="code">
39007 virtual const int& bar();
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>
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>
39042 void set_transform(Image *im, double m[4][4]);
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">
39054 >>> set_transform(im,a)
39055 Traceback (most recent call last):
39056 File "<stdin>", line 1, in ?
39057 TypeError: Type error. Expected _p_a_4__double
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>
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));
39071 void free_mat44(double (*x)[4]) {
39074 void mat44_set(double x[4][4], int i, int j, double v) {
39077 double mat44_get(double x[4][4], int i, int j) {
39083 <P> From Python, you could then write code like this:</P>
39084 <DIV class="targetlang">
39086 >>> a = new_mat44()
39087 >>> mat44_set(a,0,0,1.0)
39088 >>> mat44_set(a,1,1,1.0)
39089 >>> mat44_set(a,2,2,1.0)
39091 >>> set_transform(im,a)
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>
39106 void set_transform(Image *im, double x[4][4]);
39109 /* Rewrite the high level interface to set_transform */
39111 def set_transform(im,x):
39115 mat44_set(a,i,j,x[i][j])
39116 _example.set_transform(im,a)
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">
39131 >>> set_transform(im,a)
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("shadow")</TT>. For
39150 // Rewrite bar() python code
39152 %feature("shadow") Foo::bar(int) %{
39154 #do something before
39156 #do something after
39165 <P> where <TT>$action</TT> will be replaced by the call to the C/C++
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>
39178 // Add python code to bar()
39180 %feature("pythonprepend") Foo::bar(int) %{
39181 #do something before C++ call
39184 %feature("pythonappend") Foo::bar(int) %{
39185 #do something after C++ call
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>
39203 // Add python code to bar()
39205 %pythonprepend Foo::bar(int) %{
39206 #do something before C++ call
39209 %pythonappend Foo::bar(int) %{
39210 #do something after C++ call
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>
39228 #include "someheader.h"
39237 static char tmp[1024];
39238 sprintf(tmp,"Vector(%g,%g,%g)", $self->x,$self->y,$self->z);
39241 Vector(double x, double y, double z) {
39242 Vector *v = (Vector *) malloc(sizeof(Vector));
39251 <P> Now, in Python</P>
39252 <DIV class="targetlang">
39254 >>> v = example.Vector(2,3,4)
39255 >>> print v
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
39266 Vector __add__(Vector *other) {
39268 v.x = $self->x + other->x;
39269 v.y = $self->y + other->y;
39270 v.z = $self->z + other->z;
39276 <P> Use it like this:</P>
39277 <DIV class="targetlang">
39279 >>> import example
39280 >>> v = example.Vector(2,3,4)
39281 >>> w = example.Vector(10,11,12)
39282 >>> print v+w
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>
39300 %exception malloc {
39303 PyErr_SetString(PyExc_MemoryError,"Not enough memory");
39307 void *malloc(size_t nbytes);
39311 <DIV class="targetlang">
39313 >>> a = example.malloc(2000000000)
39314 Traceback (most recent call last):
39315 File "<stdin>", line 1, in ?
39316 MemoryError: Not enough memory
39320 <P> If a library provides some kind of general error handling framework,
39321 you can also use that. For example:</P>
39326 if (err_occurred()) {
39327 PyErr_SetString(PyExc_RuntimeError, err_message());
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>
39339 %exception getitem {
39342 } catch (std::out_of_range &e) {
39343 PyErr_SetString(PyExc_IndexError, const_cast<char*>(e.what()));
39350 Foo *getitem(int index); // Exception handled added
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>
39360 PyExc_ArithmeticError
39361 PyExc_AssertionError
39362 PyExc_AttributeError
39363 PyExc_EnvironmentError
39366 PyExc_FloatingPointError
39371 PyExc_KeyboardInterrupt
39375 PyExc_NotImplementedError
39377 PyExc_OverflowError
39379 PyExc_StandardError
39385 PyExc_ZeroDivisionError
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>
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>
39401 void add(int x, int y, int *result) {
39409 int sub(int *x, int *y) {
39414 <P> The easiest way to handle these situations is to use the <TT>
39415 typemaps.i</TT> file. For example:</P>
39419 %include "typemaps.i"
39421 void add(int, int, int *OUTPUT);
39422 int sub(int *INPUT, int *INPUT);
39425 <P> In Python, this allows you to pass simple values. For example:</P>
39426 <DIV class="targetlang">
39428 >>> a = add(3,4)
39429 >>> print a
39431 >>> b = sub(7,4)
39432 >>> print b
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>
39445 %include "typemaps.i"
39447 %apply int *OUTPUT { int *result };
39448 %apply int *INPUT { int *x, int *y};
39450 void add(int x, int y, int *result);
39451 int sub(int *x, int *y);
39454 <P> If a function mutates one of its parameters like this,</P>
39457 void negate(int *x) {
39462 <P> you can use <TT>INOUT</TT> like this:</P>
39465 %include "typemaps.i"
39467 void negate(int *INOUT);
39470 <P> In Python, a mutated parameter shows up as a return value. For
39472 <DIV class="targetlang">
39474 >>> a = negate(3)
39475 >>> print a
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
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>
39488 /* send message, return number of bytes sent, along with success code */
39489 int send_message(char *text, int len, int *success);
39492 <P> To wrap such a function, simply use the <TT>OUTPUT</TT> rule above.
39497 %include "typemaps.i"
39498 %apply int *OUTPUT { int *success };
39500 int send_message(char *text, int *success);
39503 <P> When used in Python, the function will return multiple values.</P>
39504 <DIV class="targetlang">
39506 bytes, success = send_message("Hello World")
39508 print "Whoa!"
39510 print "Sent", bytes
39513 <P> Another common use of multiple return values are in query functions.
39517 void get_dimensions(Matrix *m, int *rows, int *columns);
39520 <P> To wrap this, you might use the following:</P>
39524 %include "typemaps.i"
39525 %apply int *OUTPUT { int *rows, int *columns };
39527 void get_dimensions(Matrix *m, int *rows, *columns);
39530 <P> Now, in Python:</P>
39531 <DIV class="targetlang">
39533 >>> r,c = get_dimensions(m)
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>
39540 void foo(Bar *OUTPUT);
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>
39552 %include "cpointer.i"
39555 extern void add(int x, int y, int *result);
39558 %pointer_functions(int, intp);
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>
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);
39573 <P> In Python, you would use the functions like this:</P>
39574 <DIV class="targetlang">
39576 >>> result = new_intp()
39577 >>> print result
39579 >>> add(3,4,result)
39580 >>> print intp_value(result)
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">
39589 >>> result = intp()
39590 >>> add(3,4,result)
39591 >>> print result.value()
39595 <P> See the <A href="#Library">SWIG Library</A> chapter for further
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.
39602 int sumitems(int *first, int nitems) {
39604 for (i = 0; i < nitems; i++) {
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>
39616 %include "carrays.i"
39617 %array_class(int, intArray);
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">
39626 >>> a = intArray(10000000) # Array of 10-million integers
39627 >>> for i in xrange(10000): # Set some values
39629 >>> sumitems(a,10000)
39634 <P> The array "object" 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>
39653 </DIV><DIV class="targetlang">
39656 >>> foo("Hello")
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
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
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
39676 %apply (char *STRING, int LENGTH) { (char *data, int size) };
39678 int parity(char *data, int size, int initial);
39681 <P> Now in Python:</P>
39682 <DIV class="targetlang">
39684 >>> parity("e\x09ffss\x00\x00\x01\nx", 0)
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 "<A href="#Typemaps">
39698 Typemaps</A>" 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
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>
39713 $1 = (int) PyLong_AsLong($input);
39714 printf("Received an integer : %d\n",$1);
39717 extern int fact(int n);
39721 <P> Typemaps are always associated with some specific aspect of code
39722 generation. In this case, the "in" 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
39731 <DIV class="targetlang">
39733 >>> from example import *
39734 >>> fact(6)
39735 Received an integer : 6
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>
39746 %typemap(in) int nonnegative {
39747 $1 = (int) PyLong_AsLong($input);
39749 PyErr_SetString(PyExc_ValueError,"Expected a nonnegative value.");
39754 extern int fact(int nonnegative);
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>
39768 %typemap(in) int n {
39769 $1 = (int) PyLong_AsLong($input);
39770 printf("n = %d\n",$1);
39773 typedef int Integer;
39774 extern int fact(Integer n); // Above typemap is applied
39778 <P> Typemaps can also be defined for groups of consecutive arguments.
39782 %typemap(in) (char *str, int len) {
39783 $1 = PyString_AsString($input);
39784 $2 = PyString_Size($input);
39787 int count(char c, char *str, int len);
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">
39795 >>> example.count('e','Hello World')
39800 <H3><A name="Python_nn55"></A>31.8.2 Python typemaps</H3>
39801 <P> The previous section illustrated an "in" 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 "out" typemap like this:</P>
39807 %typemap(out) int {
39808 $result = PyInt_FromLong((long) $1);
39812 <P> A detailed list of available methods can be found in the "<A href="#Typemaps">
39813 Typemaps</A>" 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 "<A href="#Typemaps">
39828 Typemaps</A>" 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
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
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>
39861 PyObject *PyInt_FromLong(long l);
39862 long PyInt_AsLong(PyObject *);
39863 int PyInt_Check(PyObject *);
39866 <P><B> Python Floating Point Functions</B></P>
39869 PyObject *PyFloat_FromDouble(double);
39870 double PyFloat_AsDouble(PyObject *);
39871 int PyFloat_Check(PyObject *);
39874 <P><B> Python String Functions</B></P>
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 *);
39884 <P><B> Python List Functions</B></P>
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 *);
39901 <P><B> Python Tuple Functions</B></P>
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 *);
39912 <P><B> Python Dictionary Functions</B></P>
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);
39932 <P><B> Python File Conversion Functions</B></P>
39935 PyObject *PyFile_FromFile(FILE *f);
39936 FILE *PyFile_AsFile(PyObject *);
39937 int PyFile_Check(PyObject *);
39940 <P><B> Abstract Object Interface</B></P>
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 "<TT>python.swg</TT>" and "<TT>typemaps.i</TT>
39949 " 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>
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);
39965 $1 = (char **) malloc((size+1)*sizeof(char *));
39966 for (i = 0; i < size; i++) {
39967 PyObject *o = PyList_GetItem($input,i);
39968 if (PyString_Check(o))
39969 $1[i] = PyString_AsString(PyList_GetItem($input,i));
39971 PyErr_SetString(PyExc_TypeError,"list must contain strings");
39978 PyErr_SetString(PyExc_TypeError,"not a list");
39983 // This cleans up the char ** array we malloc'd before the function call
39984 %typemap(freearg) char ** {
39988 // Now a test function
39990 int print_args(char **argv) {
39993 printf("argv[%d] = %s\n", i,argv[i]);
40002 <P> When this module is compiled, the wrapped C function now operates as
40004 <DIV class="targetlang">
40006 >>> from argv import *
40007 >>> print_args(["Dave","Mike","Mary","Jane","John"])
40016 <P> In the example, two different typemaps are used. The "in" 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 "freearg" 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>
40027 int foo(int argc, char **argv);
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">
40035 >>> foo(4, ["foo","bar","spam","1"])
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>
40044 %typemap(in) (int argc, char **argv) {
40045 /* Check if is a list */
40046 if (PyList_Check($input)) {
40048 $1 = PyList_Size($input);
40049 $2 = (char **) malloc(($1+1)*sizeof(char *));
40050 for (i = 0; i < $1; i++) {
40051 PyObject *o = PyList_GetItem($input,i);
40052 if (PyString_Check(o))
40053 $2[i] = PyString_AsString(PyList_GetItem($input,i));
40055 PyErr_SetString(PyExc_TypeError,"list must contain strings");
40062 PyErr_SetString(PyExc_TypeError,"not a list");
40067 %typemap(freearg) (int argc, char **argv) {
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
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">
40081 >>> foo(["foo","bar","spam","1"])
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
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 ...
40100 <P> A typemap can be used to handle this case as follows :</P>
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.
40109 %typemap(argout) double *OutValue {
40110 PyObject *o, *o2, *o3;
40111 o = PyFloat_FromDouble(*$1);
40112 if ((!$result) || ($result == Py_None)) {
40115 if (!PyTuple_Check($result)) {
40116 PyObject *o2 = $result;
40117 $result = PyTuple_New(1);
40118 PyTuple_SetItem(target,0,o2);
40120 o3 = PyTuple_New(1);
40121 PyTuple_SetItem(o3,0,o);
40123 $result = PySequence_Concat(o2,o3);
40129 int spam(double a, double b, double *OutValue, double *OutValue);
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
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>
40145 %typemap(in,numinputs=0) double *OutValue(double temp) {
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">
40158 >>> a = spam(4,5)
40159 >>> print a
40161 >>> x,y,z = spam(4,5)
40165 <H3><A name="Python_nn62"></A>31.9.4 Mapping Python tuples into small
40167 <P> In some applications, it is sometimes desirable to pass small arrays
40168 of numbers as arguments. For example :</P>
40171 extern void set_direction(double a[4]); // Set direction vector
40174 <P> This too, can be handled used typemaps as follows :</P>
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
40180 if (PyTuple_Check($input)) {
40181 if (!PyArg_ParseTuple($input,"dddd",temp,temp+1,temp+2,temp+3)) {
40182 PyErr_SetString(PyExc_TypeError,"tuple must have 4 elements");
40187 PyErr_SetString(PyExc_TypeError,"expected a tuple.");
40194 <P> This allows our <TT>set_direction</TT> function to be called from
40195 Python as follows :</P>
40196 <DIV class="targetlang">
40198 >>> set_direction((0.5,0.0,1.0,-0.25))
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
40210 // Map a Python sequence into any sized C double array
40211 %typemap(in) double[ANY](double temp[$1_dim0]) {
40213 if (!PySequence_Check($input)) {
40214 PyErr_SetString(PyExc_TypeError,"Expecting a sequence");
40217 if (PyObject_Length($input) != $1_dim0) {
40218 PyErr_SetString(PyExc_ValueError,"Expecting a sequence with $1_dim0 elements");
40221 for (i =0; i < $1_dim0; i++) {
40222 PyObject *o = PySequence_GetItem($input,i);
40223 if (!PyFloat_Check(o)) {
40225 PyErr_SetString(PyExc_ValueError,"Expecting a sequence of floats");
40228 temp[i] = PyFloat_AsDouble(o);
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>
40240 void foo(double x[10]);
40241 void bar(double a[4], double b[8]);
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
40251 static int convert_darray(PyObject *input, double *ptr, int size) {
40253 if (!PySequence_Check(input)) {
40254 PyErr_SetString(PyExc_TypeError,"Expecting a sequence");
40257 if (PyObject_Length(input) != size) {
40258 PyErr_SetString(PyExc_ValueError,"Sequence size mismatch");
40261 for (i =0; i < size; i++) {
40262 PyObject *o = PySequence_GetItem(input,i);
40263 if (!PyFloat_Check(o)) {
40265 PyErr_SetString(PyExc_ValueError,"Expecting a sequence of floats");
40268 ptr[i] = PyFloat_AsDouble(o);
40275 %typemap(in) double [ANY](double temp[$1_dim0]) {
40276 if (!convert_darray($input,temp,$1_dim0))) {
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
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>
40314 if (SWIG_ConvertPtr($input, (void **) &f, SWIGTYPE_p_Foo, SWIG_POINTER_EXCEPTION) == -1)
40318 obj = SWIG_NewPointerObj(f, SWIGTYPE_p_Foo, 0);
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>
40325 %typemap(in) Foo * {
40326 if ((SWIG_ConvertPtr($input,(void **) &$1, $1_descriptor,SWIG_POINTER_EXCEPTION)) == -1)
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>
40335 %typemap(in) Foo * {
40336 if ((SWIG_ConvertPtr($input,(void **) &$1, $descriptor(Foo *),
40337 SWIG_POINTER_EXCEPTION)) == -1)
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>"function_name(*args)"</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>
40359 bool function_name(int x, int y, Foo* foo=NULL, Bar* bar=NULL);
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>
40373 %module(docstring="This is the example module's docstring") example
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.
40382 "The `XmlResource` class allows program resources defining menus,
40383 layout of controls on a panel, etc. to be loaded from an XML file."
40386 %module(docstring=DOCSTRING) xrc
40389 <H3><A name="Python_nn67"></A>31.10.2 %feature("autodoc")</H3>
40390 <P> As alluded to above SWIG will generate all the function and method
40391 proxy wrappers with just "*args" (or "*args, **kwargs" 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 "autodoc" 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("autodoc", "0")</H4>
40410 <P> When the "0" 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>
40415 %feature("autodoc", "0");
40416 bool function_name(int x, int y, Foo* foo=NULL, Bar* bar=NULL);
40419 <P> Then Python code like this will be generated:</P>
40420 <DIV class="targetlang">
40422 def function_name(*args, **kwargs):
40423 """function_name(x, y, foo=None, bar=None) -> bool"""
40427 <H4><A name="Python_nn69"></A>31.10.2.2 %feature("autodoc", "1")</H4>
40428 <P> When the "1" 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 "1"
40435 option will result in Python code like this:</P>
40436 <DIV class="targetlang">
40438 def function_name(*args, **kwargs):
40439 """function_name(int x, int y, Foo foo=None, Bar bar=None) -> bool"""
40443 <H4><A name="Python_nn70"></A>31.10.2.3 %feature("autodoc", "docstring")</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>
40451 %feature("autodoc", "GetPosition() -> (x, y)") GetPosition;
40452 void GetPosition(int* OUTPUT, int* OUTPUT);
40455 <H3><A name="Python_nn71"></A>31.10.3 %feature("docstring")</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 "docstring" 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">
40465 """This is the docstring"""
40468 <P> Otherwise, to aid readability it is output like this:</P>
40469 <DIV class="targetlang">
40472 This is a multi-line docstring
40473 with more than one line.
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>
40483 %module(package="wx") xrc
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>
40502 <P> There is a list of known-to-be-broken features in Python 3:</P>
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>
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>
40516 def foo(self, bar : "int" = 0) -> "void" : ...
40519 <P> Also, even if without passing SWIG the <TT>-py3</TT> option, the
40520 parameter list still could be generated:</P>
40523 def foo(self, bar = 0): ...
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>
40542 void get_path(char *s);
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>
40550 %include <pybuffer.i>
40551 %pybuffer_mutable_string(char *str);
40552 void get_path(char *s);
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">
40559 >>> p = bytearray(10)
40560 >>> get_path(p)
40561 >>> print(p)
40562 bytearray(b'/Foo/Bar/\x00')
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>
40574 %pybuffer_mutable_binary(char *str, size_t size);
40576 int snprintf(char *str, size_t size, const char *format, ...);
40580 <DIV class="targetlang">
40582 >>> buf = bytearray(6)
40583 >>> snprintf(buf, "Hello world!")
40584 >>> print(buf)
40585 bytearray(b'Hello\x00')
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
40596 %pybuffer_mutable_string(char *str);
40598 size_t make_upper(char *str);
40602 <DIV class="targetlang">
40604 >>> buf = bytearray(b'foo\x00')
40605 >>> make_upper(buf)
40606 >>> print(buf)
40607 bytearray(b'FOO\x00')
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>
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
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>
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>
40638 %include <pyabc.i>
40639 %include <std_map.i>
40640 %include <std_list.i>
40643 %template(Mapii) map<int, int>;
40644 %template(IntList) list<int>;
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>
40655 %pythonabc(MySet, collections.MutableSet);
40658 <P> For details of abstract base class, please see PEP 3119.</P>
40660 <!-- LocalWords: polymorphism Typemaps STL typemap typemaps Docstring autodoc
40663 <!-- LocalWords: docstring SWIG's cxx py GCC linux DLL gcc fPIC Wiki Xlinker
40666 <!-- LocalWords: examplemodule DHAVE CONFIG lpython lm ldl mypython lsocket
40669 <!-- LocalWords: lnsl lpthread distutils enums namespaces
40672 <H1><A name="Ruby"></A>32 SWIG and Ruby</H1>
40675 <DIV class="sectiontoc">
40677 <LI><A href="#Ruby_nn2">Preliminaries</A>
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>
40687 <LI><A href="#Ruby_nn9">Building Ruby Extensions under Windows 95/NT</A>
40689 <LI><A href="#Ruby_nn10">Running SWIG from Developer Studio</A></LI>
40692 <LI><A href="#Ruby_nn11">The Ruby-to-C/C++ Mapping</A>
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>
40712 <LI><A href="#Ruby_nn26">Exception Unrolling</A></LI>
40717 <LI><A href="#Ruby_nn27">Naming</A>
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>
40725 <LI><A href="#Ruby_nn32">Input and output parameters</A></LI>
40726 <LI><A href="#Ruby_nn33">Exception handling</A>
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>
40734 <LI><A href="#Ruby_nn37">Typemaps</A>
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>
40743 <LI><A href="#Ruby_in_typemap"> "in" typemap</A></LI>
40744 <LI><A href="#Ruby_typecheck_typemap">"typecheck" typemap</A></LI>
40745 <LI><A href="#Ruby_out_typemap"> "out" typemap</A></LI>
40746 <LI><A href="#Ruby_arginit_typemap">"arginit" typemap</A></LI>
40747 <LI><A href="#Ruby_default_typemap">"default" typemap</A></LI>
40748 <LI><A href="#Ruby_check_typemap">"check" typemap</A></LI>
40749 <LI><A href="#Ruby_argout_typemap_">"argout" typemap</A></LI>
40750 <LI><A href="#Ruby_freearg_typemap_">"freearg" typemap</A></LI>
40751 <LI><A href="#Ruby_newfree_typemap">"newfree" typemap</A></LI>
40752 <LI><A href="#Ruby_memberin_typemap">"memberin" typemap</A></LI>
40753 <LI><A href="#Ruby_varin_typemap">"varin" typemap</A></LI>
40754 <LI><A href="#Ruby_varout_typemap_">"varout" typemap</A></LI>
40755 <LI><A href="#Ruby_throws_typemap">"throws" 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>
40763 <LI><A href="#Ruby_nn40">Typemap variables</A></LI>
40764 <LI><A href="#Ruby_nn41">Useful Functions</A>
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>
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>
40778 <LI><A href="#Ruby_nn51">Ruby Datatype Wrapping</A></LI>
40781 <LI><A href="#Ruby_nn52">Example: STL Vector to Ruby Array</A></LI>
40784 <LI><A href="#Ruby_nn65">Docstring Features</A>
40786 <LI><A href="#Ruby_nn66">Module docstring</A></LI>
40787 <LI><A href="#Ruby_nn67">%feature("autodoc")</A>
40789 <LI><A href="#Ruby_nn68">%feature("autodoc", "0")</A></LI>
40790 <LI><A href="#Ruby_autodoc1">%feature("autodoc", "1")</A></LI>
40791 <LI><A href="#Ruby_autodoc2">%feature("autodoc", "2")</A></LI>
40792 <LI><A href="#Ruby_feature_autodoc3">%feature("autodoc", "3")</A></LI>
40793 <LI><A href="#Ruby_nn70">%feature("autodoc", "docstring")</A></LI>
40796 <LI><A href="#Ruby_nn71">%feature("docstring")</A></LI>
40799 <LI><A href="#Ruby_nn53">Advanced Topics</A>
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>
40806 <LI><A href="#Ruby_nn57">Memory Management</A>
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>
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 "<A href="#SWIG">SWIG Basics</A>" 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>
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>
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
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
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("\n")'</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 .
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>
40871 <P>Create a file called <TT>extconf.rb</TT> that looks like the
40873 <DIV class="code targetlang">
40874 <PRE>require 'mkmf'
40875 <BR>create_makefile('example')
40879 <P>Type the following to build the extension:</P>
40880 <DIV class="code shell">
40881 <PRE>$ <B>ruby extconf.rb</B>
40883 <BR>$ <B>make install</B>
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("Makefile", "a") { |mf|
40892 <BR> puts <<EOM
40893 <BR> # Your make rules go here
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>
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>
40920 <DIV class="code targetlang">
40921 <PRE># The feature name begins with a lowercase letter...
40924 <BR># ... but the module name begins with an uppercase letter
40925 <BR>puts "Your login name: #{Etc.getlogin}"
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>
40933 <PRE>%module example
40936 <P> will result in an extension module using the feature name "example"
40937 and Ruby module name "Example".</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>
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, "supc++")
40971 <BR>create_makefile('example')
40974 <H2><A name="Ruby_nn9"></A>32.2 Building Ruby Extensions under Windows
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> <B>ruby extconf.rb</B>
40984 <BR>C:\swigtest> <B>nmake</B>
40985 <BR>C:\swigtest> <B>nmake install</B>
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
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>
40999 <LI> Open up a new workspace and use the AppWizard to select a DLL
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 "Custom Build" option.</LI>
41009 <LI> Enter "SWIG" in the description field.</LI>
41010 <LI> Enter "<TT>swig -ruby -o $(ProjDir)\$(InputName)_wrap.c
41011 $(InputPath)</TT>" in the "Build command(s) field". You may have to
41012 include the path to swig.exe.</LI>
41013 <LI> Enter "<TT>$(ProjDir)\$(InputName)_wrap.c</TT>" in the "Output
41014 files(s) field".</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 "Additional include directories".</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 "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>
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'
41039 <BR># Call a c function
41040 <BR>print "Foo = ", Example.Foo, "\n"
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> <B>ruby run.rb</B>
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>
41057 <PRE>%module example</PRE>
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
41064 <PRE>%module "foo::bar::spam"</PRE>
41066 <P> An alternate method of specifying a nested module name is to use the
41067 <!--span style="font-family: monospace;"-->
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
41071 <!--span style="font-family: monospace;"-->
41072 %module directive in your SWIG interface file. So for example, this
41073 declaration at the top of your SWIG interface file:
41076 <PRE>%module "foo::bar::spam"</PRE>
41078 <P> will result in a nested module name of
41079 <!--span style="font-family: monospace;"-->
41080 Foo::Bar::Spam, but you can achieve the
41081 <!--span style="font-style: italic;"-->
41082 same effect by specifying:
41085 <PRE>%module spam</PRE>
41087 <P> and then running SWIG with the
41088 <!--span style="font-family: monospace;"-->
41089 -prefix command line option:
41091 <DIV class="code shell">
41092 <PRE>$ <B>swig -ruby -prefix "foo::bar::" example.i</B></PRE>
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>
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>
41113 <PRE>%module example
41115 <BR>int fact(int n);
41118 <P> and C source file <TT>example.c</TT>:</P>
41120 <PRE>int fact(int n) {
41123 <BR> return (n * fact(n-1));
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">
41131 <BR>irb(main):001:0> <B>require 'example'</B>
41133 <BR>irb(main):002:0> <B>Example.fact(4)</B>
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>
41143 <PRE>// SWIG interface file with global variables
41144 <BR>%module example
41147 <BR>extern int variable1;
41148 <BR>extern double Variable2;
41153 <P> Now look at the Ruby interface:</P>
41154 <DIV class="code targetlang">
41156 <BR>irb(main):001:0> <B>require 'Example'</B>
41158 <BR>irb(main):002:0> <B>Example.variable1 = 2</B>
41160 <BR>irb(main):003:0> <B>Example.Variable2 = 4 * 10.3</B>
41162 <BR>irb(main):004:0> <B>Example.Variable2</B>
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> <B>Example.Variable2 = "hello"</B>
41170 <BR>TypeError: no implicit conversion to float from string
41171 <BR>from (irb):5:in `Variable2='
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
41178 <P>To make ordinary variables read-only, you can also use the <TT>
41179 %immutable</TT> directive. For example:</P>
41183 <BR>extern char *path;
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>
41195 <PRE>#define PI 3.14159
41196 <BR>#define VERSION "1.0"
41198 <BR>%constant int FOO = 42;
41199 <BR>%constant const char *path = "/usr/local";
41201 <BR>const int BAR = 32;
41204 <P> Remember to use the :: operator in Ruby to get at these constant
41206 <DIV class="code targetlang">
41208 <BR>irb(main):001:0> <B>require 'Example'</B>
41210 <BR>irb(main):002:0> <B>Example::PI</B>
41214 <H3><A name="Ruby_nn16"></A>32.3.5 Pointers</H3>
41215 <P> "Opaque" 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>
41220 <PRE>Foo *get_foo();
41221 <BR>void set_foo(Foo *foo);
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> <B>foo = Example::get_foo()</B>
41228 <BR>#<SWIG::TYPE_p_Foo:0x402b1654>
41231 <P> A <TT>NULL</TT> pointer is always represented by the Ruby <TT>nil</TT>
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. "getters" and "setters") for all of the struct members. For
41236 example, this struct declaration:</P>
41238 <PRE>struct Vector {
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">
41248 <BR>irb(main):001:0> <B>require 'Example'</B>
41250 <BR>irb(main):002:0> <B>f = Example::Vector.new</B>
41251 <BR>#<Example::Vector:0x4020b268>
41252 <BR>irb(main):003:0> <B>f.x = 10</B>
41254 <BR>irb(main):004:0> <B>f.x</B>
41258 <P> Similar access is provided for unions and the public data members of
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>
41267 <BR> int x; /* Read-only members */
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
41288 <P> produces a single accessor function like this:</P>
41290 <PRE>int *Foo_x_get(Foo *self) {
41291 <BR> return self->x;
41295 <P> If you want to set an array member, you will need to supply a
41296 "memberin" 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
41312 <P> generates accessor functions such as this:</P>
41314 <PRE>Foo *Bar_f_get(Bar *b) {
41315 <BR> return &b->f;
41318 <BR>void Bar_f_set(Bar *b, Foo *val) {
41319 <BR> b->f = *val;
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>
41334 <BR> int search(char *item);
41335 <BR> void insert(char *item);
41336 <BR> void remove(char *item);
41337 <BR> char *get(int n);
41339 <BR> static void print(List *l);
41343 <P> SWIG would create a <TT>List</TT> class with:</P>
41345 <LI> instance methods<I> search</I>,<I> insert</I>,<I> remove</I>, and<I>
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>
41351 <P> In Ruby, these functions are used as follows:</P>
41352 <DIV class="code targetlang">
41353 <PRE>require 'Example'
41355 <BR>l = Example::List.new
41357 <BR>l.insert("Ale")
41358 <BR>l.insert("Stout")
41359 <BR>l.insert("Lager")
41360 <BR>Example.print(l)
41362 <BR>----- produces the following output
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>
41373 <PRE>class Parent {
41377 <BR>class Child : public Parent {
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>
41386 <PRE>irb(main):001:0> <B>c = Child.new</B>
41387 <BR>#<Bar:0x4016efd4>
41388 <BR>irb(main):002:0> <B>c.instance_of? Child</B>
41390 <BR>irb(main):003:0> <B>b.instance_of? Parent</B>
41392 <BR>irb(main):004:0> <B>b.is_a? Child</B>
41394 <BR>irb(main):005:0> <B>b.is_a? Parent</B>
41396 <BR>irb(main):006:0> <B>Child < Parent</B>
41398 <BR>irb(main):007:0> <B>Child > Parent</B>
41402 <P> Furthermore, if you have a function like this:</P>
41404 <PRE>void spam(Parent *f);
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>
41417 <PRE>class Derived : public Base1, public Base2
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 "ancestor" 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.
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
41439 <DIV class="code shell">
41440 <PRE>$ <B>swig -c++ -ruby -minherit example.i</B></PRE>
41442 <P> Using our previous example, if your SWIG interface file contains a
41443 declaration like this:</P>
41445 <PRE>class Derived : public Base1, public Base2
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 "inherit" 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">
41462 <BR> # Define Base1 methods here
41469 <BR> # Define Base2 methods here
41476 <BR> include Base1::Impl
41477 <BR> include Base2::Impl
41478 <BR> # Define Derived methods here
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 "inheriting" 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
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 "Duck Typing"</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>
41505 <PRE>void foo(int);
41506 <BR>void foo(char *c);
41509 <P> You can use them in Ruby in a straightforward manner:</P>
41510 <DIV class="code targetlang">
41511 <PRE>irb(main):001:0> <B>foo(3)</B> # foo(int)
41512 <BR>irb(main):002:0> <B>foo("Hello")</B> # foo(char *c)
41515 <P>Similarly, if you have a class like this,</P>
41520 <BR> Foo(const Foo &);
41525 <P>you can write Ruby code like this:</P>
41526 <DIV class="code targetlang">
41527 <PRE>irb(main):001:0> <B>f = Foo.new</B> # Create a Foo
41528 <BR>irb(main):002:0> <B>g = Foo.new(f)</B> # Copy f
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>
41534 <PRE>void spam(int);
41535 <BR>void spam(short);
41540 <PRE>void foo(Bar *b);
41541 <BR>void foo(Bar &b);
41544 <P> If declarations such as these appear, you will get a warning message
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.
41551 <P> To fix this, you either need to ignore or rename one of the methods.
41554 <PRE>%rename(spam_short) spam(short);
41556 <BR>void spam(int);
41557 <BR>void spam(short); // Accessed as spam_short
41562 <PRE>%ignore spam(short);
41564 <BR>void spam(int);
41565 <BR>void spam(short); // Ignored
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">"SWIG and C++"</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>
41580 <PRE>class Complex {
41582 <BR> Complex operator+(Complex &);
41587 <P> the resulting Ruby class will also support the addition (+) method
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>
41594 <PRE>%rename(add_complex) operator+(Complex &, Complex &);
41596 <BR>Complex operator+(Complex &, Complex &);
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)
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>
41614 <PRE>%module example
41616 <BR>namespace foo {
41617 <BR> int fact(int n);
41618 <BR> struct Vector {
41624 <P>it works in Ruby as follows:</P>
41625 <DIV class="code targetlang">
41626 <PRE>irb(main):001:0> <B>require 'example'</B>
41628 <BR>irb(main):002:0> <B>Example.fact(3)</B>
41630 <BR>irb(main):003:0> <B>v = Example::Vector.new</B>
41631 <BR>#<Example::Vector:0x4016f4d4>
41632 <BR>irb(main):004:0> <B>v.x = 3.4</B>
41634 <BR>irb(main):004:0> <B>v.y</B>
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>
41641 <PRE>%rename(Bar_spam) Bar::spam;
41643 <BR>namespace Foo {
41647 <BR>namespace Bar {
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>
41664 <PRE>%module example
41667 <BR>#include "pair.h"
41670 <BR>template<class T1, class T2>
41672 <BR> typedef T1 first_type;
41673 <BR> typedef T2 second_type;
41677 <BR> pair(const T1&, const T2&);
41681 <BR>%template(Pairii) pair<int,int>;
41685 <DIV class="code targetlang">
41686 <PRE>irb(main):001:0> <B>require 'example'</B>
41688 <BR>irb(main):002:0> <B>p = Example::Pairii.new(3, 4)</B>
41689 <BR>#<Example:Pairii:0x4016f4df>
41690 <BR>irb(main):003:0> <B>p.first</B>
41692 <BR>irb(main):004:0> <B>p.second</B>
41696 <H3><A name="Ruby_nn23_1"></A>32.3.13 C++ Standard Template Library
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>
41708 <PRE>%module example
41710 <BR>float sum(const std::vector<float>& values);
41713 <P> Rather than go through the hassle of writing an "in" typemap to
41714 convert an array of Ruby numbers into a std::vector<float>, you can
41715 just use the <TT>std_vector.i</TT> module from the standard SWIG
41718 <PRE>%module example
41720 <BR><B>%include std_vector.i</B>
41721 <BR>float sum(const std::vector<float>& values);
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="targetlang"-->
41731 <!--span class="targetlang"-->
41734 <BR>v.each { |x| puts x }
41736 <!--span style="font-weight: bold;"-->
41738 <BR style="font-weight: bold;">
41739 <!--span style="font-weight: bold;"-->
41741 <BR style="font-weight: bold;">
41742 <!--span style="font-weight: bold;"-->
41744 <BR>v.delete_if { |x| x == 3 }
41746 <!--span style="font-weight: bold;"-->
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. 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
41756 <BR> std::vector< swig::GC_VALUE > NativeVector;
41759 <BR> %template(NativeVector) std::vector< swig::GC_VALUE >;
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="font-family: monospace;"-->
41766 require 'nativevector'
41767 <BR style="font-family: monospace;">
41768 <!--span style="font-family: monospace;"-->
41769 include NativeVector
41770 <BR style="font-family: monospace;">
41771 <BR style="font-family: monospace;">
41772 <!--span style="font-family: monospace;"-->
41773 v = NativeVector.new
41774 <BR style="font-family: monospace;">
41775 <!--span style="font-family: monospace;"-->
41777 <BR style="font-family: monospace;">
41778 <!--span style="font-family: monospace;"-->
41780 <BR style="font-family: monospace;">
41781 <!--span style="font-family: monospace;"-->
41783 <BR style="font-family: monospace;">
41784 <BR style="font-family: monospace;">
41785 <!--span style="font-family: monospace;"-->
41787 <BR style="font-family: monospace;">
41788 <BR style="font-family: monospace;">
41789 <!--span style="font-family: monospace;"-->
41791 <BR style="font-family: monospace;">
41792 <BR style="font-family: monospace;">
41793 <!--span style="font-family: monospace;"-->
41795 <BR style="font-family: monospace;">
41796 <!--span style="font-weight: bold; font-family: monospace;"-->
41797 => [1, [1,2], 'hello', #<A:0x245325>]</DIV>
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. Functors are often
41805 just a very simple struct with
41806 <!--span style="font-family: monospace;"-->
41807 operator() redefined or an actual C/C++ function. This allows you, for
41808 example, to always keep the sort order of a STL container to your
41810 <P>The Ruby STL mappings allows you to modify those containers that
41811 support functors using Ruby procs or methods, instead. Currently, this
41813 <!--span style="font-family: monospace;"-->
41815 <!--span style="font-family: monospace;"-->
41817 <!--span style="font-family: monospace;"-->
41819 <!--span style="font-family: monospace;"-->
41821 <P>The functors in swig are called
41822 <!--span style="font-family: monospace;"-->
41823 swig::UnaryFunction and
41824 <!--span style="font-family: monospace;"-->
41825 swig::BinaryFunction.
41826 <BR> For C++ predicates (ie. functors that must return bool as a result)
41827 <!--span style="font-family: monospace;"-->
41828 swig::UnaryPredicate and
41829 <!--span style="font-family: monospace;"-->
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;
41834 <BR> %include <std_set.i>
41836 <BR> %typemap(IntSet) std::set< int, swig::BinaryPredicate >;</DIV>
41837 <P>You can then use the set from Ruby with or without a proc object as a
41839 <DIV class="targetlang" style="font-family: monospace;">require 'intset'
41840 <BR> include Intset
41842 <BR> # Default sorting behavior defined in C++
41843 <BR> a = IntSet.new
41849 <!--span style="font-weight: bold;"-->
41850 => [1,2,3]
41852 <BR> # Custom sorting behavior defined by a Ruby proc<DIV>
41853 <!--span class="targetlang"-->
41854 b = IntSet.new( proc { |a,b| a > b } )
41855 <BR> b << 1
41856 <BR> b << 2
41857 <BR> b << 3
41859 <BR style="font-weight: bold;">
41860 <!--span style="font-weight: bold;"-->
41861 => [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. 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. 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. This proxy class is
41870 <!--span style="font-family: monospace;"-->
41871 swig::Iterator or swig::ConstIterator. 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. </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. For out typemaps, the special functions
41879 <!--span style="font-family: monospace;"-->
41880 make_const_iterator and
41881 <!--span style="font-family: monospace;"-->
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,
41888 <P>The iterators support a
41889 <!--span style="font-family: monospace;"-->
41891 <!--span style="font-family: monospace;"-->
41892 previous() member function to just change the iterator without
41893 returning anything.
41894 <!--span style="font-family: monospace;"-->
41895 previous() should obviously only be used for bidirectional iterators.
41896 You can also advance the iterator multiple steps by using standard
41897 math operations like
41898 <!--span style="font-family: monospace;"-->
41900 <P>The value the iterator points at can be accessed with
41901 <!--span style="font-family: monospace;"-->
41902 value() -- this is equivalent to dereferencing it with
41903 <!--span style="font-family: monospace;"-->
41904 *i. For non-const iterators, a
41905 <!--span style="font-family: monospace;"-->
41906 value=() function is also provided which allows you to change the value
41907 pointed by the iterator. This is equivalent to the C++ construct of
41908 dereferencing and assignment, like
41909 <!--span style="font-family: monospace;"-->
41910 *i = something. </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="code"-->
41914 %module doublevector
41916 <!--span class="code"-->
41917 <BR> %include std_vector.i
41919 <!--span class="code"-->
41920 <BR> %template(DoubleVector) std::vector<double>;</DIV>
41921 <P>Its iterator can then be used from Ruby like:</P>
41922 <DIV class="targetlang" style="font-family: monospace;">require
41924 <BR> include Doublevector
41926 <BR> v = DoubleVector.new
41932 <BR> # an elaborate and less efficient way of doing v.map! { |x| x+2 }
41937 <BR> val = i.value
41938 <BR> val += 2
41939 <BR> i.value = val
41944 <!--span style="font-weight: bold;"-->
41945 >> [3, 4, 5 ]</DIV>
41947 <P>If you'd rather have STL classes without any iterators, you should
41949 <!--span style="font-family: monospace;"-->
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 "smart pointers." Generally, this involves the use
41954 of a template class that implements <TT>operator->()</TT> like this:</P>
41956 <PRE>template<class T> class SmartPtr {
41958 <BR> T *operator->();
41963 <P>Then, if you have a class like this,</P>
41972 <P>A smart pointer would be used in C++ as follows:</P>
41974 <PRE>SmartPtr<Foo> p = CreateFoo(); // Created somehow (not shown)
41976 <BR>p->x = 3; // Foo::x
41977 <BR>int y = p->bar(); // Foo::bar
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>
41984 <PRE>%module example
41986 <BR>%template(SmartPtrFoo) SmartPtr<Foo>;
41990 <P>Now, in Ruby, everything should just "work":</P>
41991 <DIV class="code targetlang">
41992 <PRE>irb(main):001:0> <B>p = Example::CreateFoo()</B> # Create a smart-pointer somehow
41993 <BR>#<Example::SmartPtrFoo:0x4016f4df>
41994 <BR>irb(main):002:0> <B>p.x = 3</B> # Foo::x
41996 <BR>irb(main):003:0> <B>p.bar()</B> # Foo::bar
41999 <P> If you ever need to access the underlying pointer returned by <TT>
42000 operator->()</TT> itself, simply use the <TT>__deref__()</TT> method.
42002 <DIV class="code targetlang">
42003 <PRE>irb(main):004:0> <B>f = p.__deref__()</B> # Returns underlying Foo *
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 "directors" 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("director:except")</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>
42022 <PRE>%feature("director:except") {
42023 <BR> throw Swig::DirectorMethodException($error);
42027 <P> When this feature is activated, the call to the Ruby instance method
42028 is "wrapped" 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>
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>
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>
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
42066 <PRE>class MyArray {
42068 <BR> // Construct an empty array
42071 <BR> // Return the size of this array
42072 <BR> size_t length() const;
42075 <BR>%extend MyArray {
42076 <BR> // MyArray#size is an alias for MyArray#length
42077 <BR> size_t size() const {
42078 <BR> return $self->length();
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>
42086 <PRE>// MyArray#size is an alias for MyArray#length
42087 <BR>%alias MyArray::length "size";
42089 <BR>class MyArray {
42091 <BR> // Construct an empty array
42094 <BR> // Return the size of this array
42095 <BR> size_t length() const;
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>
42103 <PRE>%alias MyArray::length "amount,quantity,size";</PRE>
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 "features" mechanism and so the same name matching rules used for other
42113 kinds of features apply (see the chapter on <A href="#Customization">
42114 "Customization Features"</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>
42129 <PRE>%rename("is_it_safe?") is_it_safe();
42131 <BR>%typemap(out) int is_it_safe
42132 <BR> "$result = ($1 != 0) ? Qtrue : Qfalse;";
42134 <BR>int is_it_safe();
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>
42142 <PRE>%predicate is_it_safe();
42144 <BR>int is_it_safe();
42148 <P>This method would be invoked from Ruby code like this:</P>
42149 <DIV class="code targetlang">
42150 <PRE>irb(main):001:0> <B>Example::is_it_safe?</B>
42155 <P> The <TT>%predicate</TT> directive is implemented using SWIG's
42156 "features" mechanism and so the same name matching rules used for other
42157 kinds of features apply (see the chapter on <A href="#Customization">
42158 "Customization Features"</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
42171 <PRE>%bang sort!(arr);
42173 <BR>int sort(int arr[]); </PRE>
42175 <P>This method would be invoked from Ruby code like this:</P>
42177 <PRE>irb(main):001:0> <B>Example::sort!(arr)</B></PRE>
42179 <P> The <TT>%bang</TT> directive is implemented using SWIG's "features"
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 "Customization Features"</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>
42190 <BR> int getValue() { return value_; }
42192 <BR> void setValue(int value) { value_ = value; }
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>
42203 <PRE>irb(main):001:0> <B>foo = Foo.new()</B>
42204 <BR>irb(main):002:0> <B>foo.value = 5</B>
42205 <BR>irb(main):003:0> <B>puts foo.value</B></PRE>
42207 <P> This can be done by using the %rename directive:</P>
42209 <PRE>%rename("value") Foo::getValue();
42210 <BR>%rename("value=") Foo::setValue(int value);
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>
42218 <PRE>void add(int x, int y, int *result) {
42219 <BR> *result = x + y;
42222 <BR>int sub(int *x, int *y) {
42227 <P> The easiest way to handle these situations is to use the <TT>
42228 typemaps.i</TT> file. For example:</P>
42230 <PRE>%module Example
42231 <BR>%include "typemaps.i"
42233 <BR>void add(int, int, int *OUTPUT);
42234 <BR>int sub(int *INPUT, int *INPUT);
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)
42242 <BR>b = Example.sub(7,4)
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>
42253 <PRE>%module Example
42254 <BR>%include "typemaps.i"
42256 <BR>%apply int *OUTPUT { int *result };
42257 <BR>%apply int *INPUT { int *x, int *y};
42259 <BR>void add(int x, int y, int *result);
42260 <BR>int sub(int *x, int *y);
42263 <P> If a function mutates one of its parameters like this,</P>
42265 <PRE>void negate(int *x) {
42270 <P>you can use <TT>INOUT</TT> like this:</P>
42272 <PRE>%include "typemaps.i"
42274 <BR>void negate(int *INOUT);
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)
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>
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);
42293 <P> To wrap such a function, simply use the <TT>OUTPUT</TT> rule above.
42296 <PRE>%module example
42297 <BR>%include "typemaps.i"
42299 <BR>int send_message(char *, int *OUTPUT, int *OUTPUT);
42302 <P> When used in Ruby, the function will return an array of multiple
42304 <DIV class="code targetlang">
42305 <PRE>bytes, success, error_code = send_message("Hello World")
42307 <BR> print "error #{error_code} : in send_message"
42309 <BR> print "Sent", bytes
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>
42318 <PRE>%module Example
42319 <BR>%include "typemaps.i"
42320 <BR>%apply int *OUTPUT { int *rows, int *columns };
42322 <BR>void get_dimensions(Matrix *m, int *rows, int*columns);
42326 <DIV class="code targetlang">
42327 <PRE>r, c = Example.get_dimensions(m)
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>
42338 <PRE>class DoubleArray {
42343 <BR> // Create a new array of fixed size
42344 <BR> DoubleArray(int size) {
42345 <BR> ptr = new double[size];
42349 <BR> // Destroy an array
42350 <BR> ~DoubleArray() {
42354 <BR> // Return the length of the array
42355 <BR> int length() {
42359 <BR> // Get an array item and perform bounds checking.
42360 <BR> double getitem(int i) {
42361 <BR> if ((i >= 0) && (i < n))
42362 <BR> return ptr[i];
42364 <BR> throw RangeError();
42367 <BR> // Set an array item and perform bounds checking.
42368 <BR> void setitem(int i, double val) {
42369 <BR> if ((i >= 0) && (i < n))
42372 <BR> throw RangeError();
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>
42386 <BR> catch (const RangeError&) {
42387 <BR> static VALUE cpperror = rb_define_class("CPPError", rb_eStandardError);
42388 <BR> rb_raise(cpperror, "Range error.");
42392 <BR>class DoubleArray {
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
42406 <PRE>%exception getitem {
42410 <BR> catch (const RangeError&) {
42411 <BR> static VALUE cpperror = rb_define_class("CPPError", rb_eStandardError);
42412 <BR> rb_raise(cpperror, "Range error in getitem.");
42416 <BR>%exception setitem {
42420 <BR> catch (const RangeError&) {
42421 <BR> static VALUE cpperror = rb_define_class("CPPError", rb_eStandardError);
42422 <BR> rb_raise(cpperror, "Range error in setitem.");
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. 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. </P>
42440 <P>For example, this yields the class over after its construction:
42446 <BR> Window(int x, int y, int w, int h);
42447 <BR>// .... other methods here ....
42450 <BR>// Add support for yielding self in the Class' constructor.
42451 <BR>%exception Window::Window {
42453 <BR> if (rb_block_given_p()) {
42454 <BR> rb_yield(self);
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> w.color = Fltk::RED
42462 <BR> w.border = false
42464 <!--span class="targetlang"-->
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:
42472 <BR> // void func(int x);
42474 <BR> %typemap(in,numinputs=0) int RUBY_YIELD_SELF {
42475 <BR> if ( !rb_block_given_p() )
42476 <BR> rb_raise("No block given");
42477 <BR> return rb_yield(self);
42481 <BR> void func(int x, int RUBY_YIELD_SELF );
42483 <P>For more information on typemaps, see <A href="#Ruby_nn37">Typemaps</A>
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
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>
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, "MyError") 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 ":AssertionFailedException", 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
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
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>
42565 <PRE> %exceptionclass CustomError;
42568 <BR> class CustomError { };
42572 <BR> void test() { throw CustomError; }
42577 <P>From Ruby you can now call this method like this:</P>
42578 <DIV class="code targetlang">
42582 <BR>rescue CustomError => e
42583 <BR> puts "Caught custom error"
42586 <P>For another example look at swig/Examples/ruby/exception_class.
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 "<A href="#Typemaps">Typemaps</A>
42593 " chapter. </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 ): </P>
42603 <!--span style="font-family: monospace;" class="code"-->
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>"in"</TT>, <TT>
42607 "out"</TT>, or <TT>"argout"</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="value"</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, ... ] ;
42617 <BR>typepattern : type [ (parms) ]
42618 <BR> | type name [ (parms) ]
42619 <BR> | ( typelist ) [ (parms) ]
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> | " ... "
42635 <P>For example, to convert integers from Ruby to C, you might define a
42636 typemap like this:</P>
42638 <PRE>%module example
42640 <BR>%typemap(in) int {
42641 <BR> $1 = (int) NUM2INT($input);
42642 <BR> printf("Received an integer : %d\n",$1);
42646 <BR>extern int fact(int n);
42650 <P> Typemaps are always associated with some specific aspect of code
42651 generation. In this case, the "in" 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
42660 <DIV class="code targetlang">
42661 <PRE>require 'example'
42663 <BR>puts Example.fact(6)
42666 <P>prints the result:</P>
42667 <DIV class="code shell">
42668 <PRE>Received an integer : 6
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>
42676 <PRE>%module example
42678 <BR>%typemap(in) int n {
42679 <BR> $1 = (int) NUM2INT($input);
42680 <BR> printf("n = %d\n",$1);
42684 <BR>extern int fact(int n);
42688 <P> In this case, the typemap code is only attached to arguments that
42689 exactly match "<TT>int n</TT>".</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>
42697 <PRE>%typemap(in) int n {
42698 <BR> $1 = (int) NUM2INT($input);
42699 <BR> printf("n = %d\n",$1);
42702 <BR>typedef int Integer;
42703 <BR>extern int fact(Integer n); // Above typemap is applied
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
42712 <PRE>%typemap(in) (char *str, int len) {
42713 <BR> $1 = STR2CSTR($input);
42714 <BR> $2 = (int) RSTRING($input)->len;
42717 <BR>int count(char c, char *str, int len);
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')
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>
42734 <BR>%typemap(in) int {
42738 <BR>int fact(int); // typemap1
42739 <BR>int gcd(int x, int y); // typemap1
42742 <BR>%typemap(in) int {
42746 <BR>int isprime(int); // typemap2
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>
42760 <BR>%typemap(in) int {
42765 <BR> int blah(int x); // typemap has no effect. Declaration is attached to Foo which
42766 <BR> // appears before the %typemap declaration.
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>
42773 <PRE>%typemap(in) Integer = int;
42778 <PRE>%typemap(in) Integer, Number, int32_t = int;
42781 <P> Types are often managed by a collection of different typemaps. For
42784 <PRE>%typemap(in) int { ... }
42785 <BR>%typemap(out) int { ... }
42786 <BR>%typemap(varin) int { ... }
42787 <BR>%typemap(varout) int { ... }
42790 <P> To copy all of these typemaps to a new type, use <TT>%apply</TT>.
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
42797 <P> The patterns for <TT>%apply</TT> follow the same rules as for <TT>
42798 %typemap</TT>. For example:</P>
42800 <PRE>%apply int *output { Integer *output }; // Typemap with name
42801 <BR>%apply (char *buf, int len) { (char *buffer, int size) }; // Multiple arguments
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>
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;
42812 <P> The <TT>%clear</TT> directive clears all typemaps for a given type.
42815 <PRE>%clear int; // Removes all types for int
42816 <BR>%clear int *output, long *output;
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
42825 <P> Typemap declarations can be declared in the global scope, within a
42826 C++ namespace, and within a C++ class. For example:</P>
42828 <PRE>%typemap(in) int {
42832 <BR>namespace std {
42834 <BR> %typemap(in) string {
42841 <BR> typedef const int & const_reference;
42842 <BR> %typemap(out) const_reference {
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>
42852 <PRE>namespace std {
42854 <BR> %typemap(in) string {
42860 <P> is really defining a typemap for the type <TT>std::string</TT>. You
42861 could have code like this:</P>
42863 <PRE>namespace std {
42865 <BR> %typemap(in) string { /* std::string */
42870 <BR>namespace Foo {
42872 <BR> %typemap(in) string { /* Foo::string */
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>
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 "in" typemap</H4>
42889 <P>Converts Ruby objects to input function arguments. For example:</P>
42891 <PRE>%typemap(in) int {
42892 <BR> $1 = NUM2INT($input);
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>
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 "in" typemap allows the number of converted
42917 arguments to be specified. For example:</P>
42919 <PRE>// Ignored argument.
42920 <BR>%typemap(in, numinputs=0) int *out (int temp) {
42921 <BR> $1 = &temp;
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 "typecheck" typemap</H4>
42927 <P> The "typecheck" 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>
42931 <PRE>%typemap(typecheck,precedence=SWIG_TYPECHECK_INTEGER) int {
42932 <BR> $1 = FIXNUM_P($input) ? 1 : 0;
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
42939 <P> If you define new "in" typemaps<EM> and</EM> your program uses
42940 overloaded methods, you should also define a collection of "typecheck"
42941 typemaps. More details about this follow in a later section on
42942 "Typemaps and Overloading."</P>
42943 <H4><A name="Ruby_out_typemap"></A>32.7.6.3 "out" 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> $result = INT2NUM( $1 );
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>
42969 <H4><A name="Ruby_arginit_typemap"></A>32.7.6.4 "arginit" typemap</H4>
42970 <P> The "arginit" 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
42975 <PRE>// Set argument to NULL before any conversion occurs
42976 <BR>%typemap(arginit) int *data {
42981 <H4><A name="Ruby_default_typemap"></A>32.7.6.5 "default" typemap</H4>
42982 <P> The "default" typemap is used to turn an argument into a default
42983 argument. For example:</P>
42985 <PRE>%typemap(default) int flags {
42986 <BR> $1 = DEFAULT_FLAGS;
42989 <BR>int foo(int x, int y, int flags);
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 "check" typemap</H4>
43002 <P> The "check" 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>
43006 <PRE>%typemap(check) int positive {
43007 <BR> if ($1 <= 0) {
43008 <BR> SWIG_exception(SWIG_ValueError,"Expected positive value.");
43013 <H4><A name="Ruby_argout_typemap_"></A>32.7.6.7 "argout" typemap</H4>
43014 <P> The "argout" 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 "argout" typemap is almost always
43017 combined with an "in" typemap---possibly to ignore the input value. For
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 = &temp;
43025 <BR>%typemap(argout, fragment="output_helper") 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) );
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>
43043 <P> The code supplied to the "argout" typemap is always placed after the
43044 "out" 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 "freearg" typemap</H4>
43050 <P> The "freearg" 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 "freearg" typemap
43053 usually cleans up argument resources allocated by the "in" typemap. For
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);
43061 <BR>// Free the list
43062 <BR>%typemap(freearg) int *items {
43067 <P> The "freearg" 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
43072 <H4><A name="Ruby_newfree_typemap"></A>32.7.6.9 "newfree" typemap</H4>
43073 <P> The "newfree" 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>
43077 <PRE>%typemap(newfree) string * {
43080 <BR>%typemap(out) string * {
43081 <BR> $result = PyString_FromString($1->c_str());
43085 <BR>%newobject foo;
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 "memberin" typemap</H4>
43093 <P> The "memberin" 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>
43097 <PRE>%typemap(memberin) int [4] {
43098 <BR> memmove($1, $input, 4*sizeof(int));
43102 <P> It is rarely necessary to write "memberin" typemaps---SWIG already
43103 provides a default implementation for arrays, strings, and other
43105 <H4><A name="Ruby_varin_typemap"></A>32.7.6.11 "varin" typemap</H4>
43106 <P> The "varin" 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 "varout" typemap</H4>
43110 <P> The "varout" 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 "throws" typemap</H4>
43114 <P> The "throws" 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>
43123 <PRE>%typemap(throws) const char * %{
43124 <BR> rb_raise(rb_eRuntimeError, $1);
43127 <BR>void bar() throw (const char *);
43130 <P> As can be seen from the generated code below, SWIG generates an
43131 exception handler with the catch block comprising the "throws" typemap
43138 <BR>catch(char const *_e) {
43139 <BR> rb_raise(rb_eRuntimeError, _e);
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. It
43151 is roughly the opposite of the "in" typemap, making its typemap rule
43152 often similar to the "out" typemap.</P>
43153 <DIV class="code"><TT>
43154 <BR> %typemap(directorin) int {
43155 <BR> $result = INT2NUM($1);
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>
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 It is roughly the opposite of the "out" typemap, making its rule often
43181 similar to the "in" typemap.</P>
43182 <DIV class="code"><TT style="font-family: monospace;">
43183 <BR> %typemap(directorout) int {</TT><TT>
43184 <BR> $result = NUM2INT($1);</TT>
43185 <BR> <TT style="font-family: monospace;">}
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>
43205 <P>Currently, the directorout nor the out typemap support the option
43206 <!--span style="font-family: monospace;"-->
43207 numoutputs, but the Ruby module provides that functionality through a
43208 %feature directive. Thus, a function can be made to return "nothing"
43210 <DIV class="code" style="font-family: monospace;">
43211 %feature("numoutputs","0") 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.
43215 <H4><A name="Ruby_directorargout_typemap"></A>32.7.6.16 directorargout
43217 <P>Output argument processing in director member functions.</P>
43218 <DIV class="code"><TT style="font-family: monospace;">
43219 %typemap(directorargout, fragment="output_helper") 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>
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 "<A href="#Typemaps">
43249 Typemaps</A>" chapter. This is a list of the most common variables:</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
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.) </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). 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. That should
43285 help you avoid having to rewrite a lot of typemaps across multiple
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">
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>
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="font-family: monospace;"-->
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)
43315 <BR> ok = SWIG_AsVal_size_t($input, &$1);
43316 <BR> if (!SWIG_IsOK(ok)) {
43317 <BR> SWIG_exception_fail(SWIG_ArgError(ok), Ruby_Format_TypeError(
43318 "$1_name", "$1_type","$symname", $argnum, $input ));
43319 <BR> }
43321 <BR> }</DIV><DIV style="font-family: monospace;"> </DIV><DIV class="diagram">
43322 <TABLE border="1" cellpadding="2" cellspacing="2" summary="Ruby objects" width="100%">
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>
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>
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>
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)->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>
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
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>
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>
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)->len;
43451 <BR> $1 = (char **) malloc((size+1)*sizeof(char *));
43452 <BR> /* Get the first element in memory */
43453 <BR> VALUE *ptr = RARRAY($input)->ptr;
43454 <BR> for (i=0; i < 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 */
43460 <BR>// This cleans up the char ** array created before
43461 <BR>// the function call
43463 <BR>%typemap(freearg) char ** {
43464 <BR> free((char *) $1);
43467 <BR>// Now a test function
43469 <BR>int print_args(char **argv) {
43471 <BR> while (argv[i]) {
43472 <BR> printf("argv[%d] = %s\n", i,argv[i]);
43481 <P> When this module is compiled, the wrapped C function now operates as
43483 <DIV class="code targetlang">
43484 <PRE>require 'Argv'
43485 <BR>Argv.print_args(["Dave","Mike","Mary","Jane","John"])
43493 <P> In the example, two different typemaps are used. The "in" 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 "freearg" 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 "keyword arguments" 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
43508 <PRE>void setVitalStats(const char *person, int nattributes, const char **names, int *values);
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("Fred",
43515 <BR> 'weight' => 270,
43516 <BR> 'age' => 42
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>
43525 <PRE>%typemap(in) (int nattributes, const char **names, const int *values)
43526 <BR> (VALUE keys_arr, int i, VALUE key, VALUE val) {
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
43540 <P>Since we expect the input argument to be a <TT>Hash</TT>, let's next
43541 add a check for that:</P>
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>
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>
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("size"), 0, NULL));</B>
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
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("size"), 0, NULL));
43577 <BR> if ($1 > 0) {
43578 <BR> $2 = (char **) malloc($1*sizeof(char *));
43579 <BR> $3 = (int *) malloc($1*sizeof(int));
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>
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("size"), 0, NULL));
43595 <BR> if ($1 > 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("keys"), 0, NULL);
43599 <BR> for (i = 0; i < $1; i++) {
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
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("size"), 0, NULL));
43616 <BR> if ($1 > 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("keys"), 0, NULL);
43620 <BR> for (i = 0; i < $1; i++) {
43621 <BR> <B>key = rb_ary_entry(keys_arr, i);
43622 <BR> val = rb_hash_aref($input, key);</B>
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>
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("size"), 0, NULL));
43638 <BR> if ($1 > 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("keys"), 0, NULL);
43642 <BR> for (i = 0; i < $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>
43652 <P> Finally, we can convert these Ruby objects into their C equivalents
43653 and store them in our local C arrays:</P>
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("size"), 0, NULL));
43661 <BR> if ($1 > 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("keys"), 0, NULL);
43665 <BR> for (i = 0; i < $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>
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 "freearg" typemap to free
43680 that memory so that there is no memory leak. Fortunately, this typemap
43681 is a lot easier to write:</P>
43683 <PRE>%typemap(freearg) (int nattributes, const char **names, const int *values) {
43684 <BR> free((void *) $2);
43685 <BR> free((void *) $3);
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
43710 <P> <TT>VALUE SWIG_NewPointerObj(void *ptr, swig_type_info *ty, int own)</TT>
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">
43726 <BR>SWIG_ConvertPtr($input, (void **) &foo, SWIGTYPE_p_Foo, 1);
43729 <BR>obj = SWIG_NewPointerObj(f, SWIGTYPE_p_Foo, 0);
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 **) &$1, $1_descriptor, 1);
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>
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>
43764 <PRE>%define PTR_VECTOR_TO_RUBY_ARRAY(vectorclassname, classname)
43765 <BR>%typemap(out) vectorclassname &, const vectorclassname & {
43766 <BR> VALUE arr = rb_ary_new2($1->size());
43767 <BR> vectorclassname::iterator i = $1->begin(), iend = $1->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;
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;
43782 <P> Note, that the "<TT>c ## classname.klass"</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>
43786 <PRE>PTR_VECTOR_TO_RUBY_ARRAY(vector<foo *="">, Foo)
43789 <P> It is also possible to create a STL vector of Ruby objects:</P>
43791 <PRE>%define RUBY_ARRAY_TO_PTR_VECTOR(vectorclassname, classname)
43792 <BR>%typemap(in) vectorclassname &, const vectorclassname & {
43793 <BR> Check_Type($input, T_ARRAY);
43794 <BR> vectorclassname *vec = new vectorclassname;
43795 <BR> int len = RARRAY($input)->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->push_back(element);
43807 <BR>%typemap(freearg) vectorclassname &, const vectorclassname & {
43813 <P> It is also possible to create a Ruby array from a vector of static
43816 <PRE>%define VECTOR_TO_RUBY_ARRAY(vectorclassname, classname)
43817 <BR>%typemap(out) vectorclassname &, const vectorclassname & {
43818 <BR> VALUE arr = rb_ary_new2($1->size());
43819 <BR> vectorclassname::iterator i = $1->begin(), iend = $1->end();
43820 <BR> for ( ; i!=iend; i++ )
43821 <BR> rb_ary_push(arr, Data_Wrap_Struct(c ## classname.klass, 0, 0, &(*i)));
43822 <BR> $result = arr;
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, &(*i)));
43829 <BR> $result = arr;
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. Refer to the section called
43837 the<A href="#Ruby_nn23_1"> C++ Standard Template Library</A>.
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. </P>
43850 <P>For example, to generate html web pages from a C++ file, you'd do: </P>
43851 <DIV class="code shell">
43852 <!--span style="font-family: monospace; font-weight: bold;"-->
43853 $ rdoc -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="font-family: monospace; font-weight: bold;"-->
43857 $ rdoc -r 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 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>
43864 <PRE>%module(docstring="This is the example module's docstring") example
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.
43871 <PRE>%define DOCSTRING
43872 <BR>"The `XmlResource` class allows program resources defining menus,
43873 <BR>layout of controls on a panel, etc. to be loaded from an XML file."
43876 <BR>%module(docstring=DOCSTRING) xrc
43879 <H3><A name="Ruby_nn67"></A>32.8.2 %feature("autodoc")</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 "autodoc" 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("autodoc", "0")</H4>
43891 <P> When the "0" 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>
43895 <PRE>%feature("autodoc", "0");
43896 <BR>bool function_name(int x, int y, Foo* foo=NULL, Bar* bar=NULL);
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) -> bool
43905 <H4><A name="Ruby_autodoc1"></A>32.8.2.2 %feature("autodoc", "1")</H4>
43906 <P> When the "1" 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 "1" 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) -> bool
43919 <H4><A name="Ruby_autodoc2"></A>32.8.2.3 %feature("autodoc", "2")</H4>
43920 <P> When the "2" 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. Given the example above, then turning on the parameter types
43923 with the "2" option will result in Ruby code like this:</P>
43924 <H4><A name="Ruby_feature_autodoc3"></A>32.8.2.4 %feature("autodoc",
43925 "3")</H4>
43926 <P> When the "3" option is used then the function will be documented
43927 using a combination of "1" and "2" above. Given the example above,
43928 then turning on the parameter types with the "2" 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) -> bool
43940 <H4><A name="Ruby_nn70"></A>32.8.2.5 %feature("autodoc", "docstring")</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>
43947 <PRE>%feature("autodoc", "GetPosition() -> (x, y)") GetPosition;
43948 <BR>void GetPosition(int* OUTPUT, int* OUTPUT);
43951 <H3><A name="Ruby_nn71"></A>32.8.3 %feature("docstring")</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 "docstring" 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> <=></TD></TR>
43970 <TR><TD>__hash__</TD><TD> hash</TD></TR>
43971 <TR><TD>__nonzero__</TD><TD> nonzero?</TD></TR>
43973 <TR><TD><B> Callable</B></TD></TR>
43974 <TR><TD>__call__</TD><TD> call</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>
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> <<</TD></TR>
43990 <TR><TD>__rshift__</TD><TD> >></TD></TR>
43991 <TR><TD>__and__</TD><TD> &</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>
44002 <TR><TD><B>Additions in 1.3.13</B></TD></TR>
44003 <TR><TD>__lt__</TD><TD> <</TD></TR>
44004 <TR><TD>__le__</TD><TD> <=</TD></TR>
44005 <TR><TD>__eq__</TD><TD> ==</TD></TR>
44006 <TR><TD>__gt__</TD><TD> ></TD></TR>
44007 <TR><TD>__ge__</TD><TD> >=</TD></TR>
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>
44025 <BR>#include "Shape.h"
44033 <BR> Shape(double x, double y);
44035 <BR> double getX() const;
44036 <BR> double getY() const;
44040 <P> We also have a separate interface file (<TT>circle.i</TT>) that
44041 defines a derived class:</P>
44043 <PRE>%module circle
44046 <BR>#include "Shape.h"
44047 <BR>#include "Circle.h"
44050 <BR>// Import the base class definition from Shape module
44051 <BR>%import shape.i
44053 <BR>class Circle : public Shape {
44055 <BR> double radius;
44057 <BR> Circle(double x, double y, double r);
44058 <BR> double getRadius() const;
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>
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'
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'])
44078 <BR># Create the makefile
44079 <BR>create_makefile('shape')
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
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
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>
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>
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">
44112 <BR>irb(main):001:0> <B>require 'shape'</B>
44114 <BR>irb(main):002:0> <B>require 'circle'</B>
44116 <BR>irb(main):003:0> <B>c = Circle::Circle.new(5, 5, 20)</B>
44117 <BR>#<Circle::Circle:0xa097208>
44118 <BR>irb(main):004:0> <B>c.kind_of? Shape::Shape</B>
44120 <BR>irb(main):005:0> <B>c.getX()</B>
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">
44131 <BR> def initialize
44136 <BR> @members.each { |m| yield m }
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">
44145 <BR> <B>include Enumerable</B>
44150 <BR>@members.each { |m| yield m }
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>
44160 <PRE>%mixin Set "Enumerable";
44164 <BR> // Constructor
44167 <BR> // Iterates through set members
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,
44176 <PRE>%mixin Set "Fee,Fi,Fo,Fum";</PRE>
44178 <P> Note that the <TT>%mixin</TT> directive is implemented using SWIG's
44179 "features" mechanism and so the same name matching rules used for other
44180 kinds of features apply (see the chapter on <A href="#Customization">
44181 "Customization Features"</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>
44188 <LI> The Ruby object is responsible for freeing the C struct or C++
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>
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 "root" 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 "marked."
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">
44211 <!--span style="text-decoration: underline;"-->
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 "mark" function and a "sweep" 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 "mark" function. The "mark" 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 "mark" 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 "free" function must be defined that deallocates this
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 "free"
44229 function must be registered for the object. If the Ruby object is not
44230 responsible for freeing the underlying memory, then a "free" 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>
44235 <LI> When calling a C++ object's constructor from Ruby, SWIG will assign
44236 a "free" 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 "free" function thereby making the underlying library
44240 responsible for freeing the object.</LI>
44242 <P>To make this clearer, let's look at an example. Assume we have a Foo
44243 and a Bar class.</P>
44245 <PRE>/* File "RubyOwernshipExample.h" */
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; }
44267 <P>First, consider this Ruby code:</P>
44268 <DIV class="code targetlang">
44269 <PRE>foo = Foo.new</PRE>
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 "free" function. When the Ruby object
44274 is garbage collected, the "free" 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">
44279 <BR>foo = bar.get_foo()</PRE>
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 "free" 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.
44287 <DIV class="code targetlang">
44289 <BR>foo = bar.get_new_foo()</PRE>
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">
44299 <BR>bar.set_foo(foo)</PRE>
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
44312 <PRE>/* File RubyOwnershipExample.i */
44314 <BR>%module RubyOwnershipExample
44317 <BR>#include "RubyOwnershipExample.h"
44333 <BR> Foo* get_foo();
44336 <!--span style="font-weight: bold;"-->
44337 %newobject get_new_foo;
44338 <BR> Foo* get_new_foo();
44341 <!--span style="font-weight: bold;"-->
44342 %apply SWIGTYPE *DISOWN {Foo *foo};
44343 <BR> void set_foo(Foo *foo);
44345 <!--span style="font-weight: bold;"-->
44352 <P> This code can be seen in swig/examples/ruby/tracking.</P>
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>
44362 <BR>#include <string>
44363 <BR>#include <vector>
44365 <BR>#include "zoo.h"
44371 <BR> typedef std::vector<Animal*> AnimalsType;
44372 <BR> typedef AnimalsType::iterator IterType;
44374 <BR> AnimalsType animals;
44376 <BR> std::string name_;
44378 <BR> // Construct an animal with this name
44379 <BR> Animal(const char* name) : name_(name) {}
44381 <BR> // Return the animal's name
44382 <BR> const char* get_name() const { return name.c_str(); }
44388 <BR> std::vector<animal *=""> animals;
44391 <BR> // Construct an empty zoo
44394 <BR> /* Create a new animal. */
44395 <BR> static Animal* Zoo::create_animal(const char* name)
44397 <BR> return new Animal(name);
44400 <BR> // Add a new animal to the zoo
44401 <BR> void add_animal(Animal* animal) {
44402 <BR> animals.push_back(animal);
44405 <BR> Animal* remove_animal(size_t i) {
44406 <BR> Animal* result = this->animals[i];
44407 <BR> IterType iter = this->animals.begin();
44408 <BR> std::advance(iter, i);
44409 <BR> this->animals.erase(iter);
44411 <BR> return result;
44414 <BR> // Return the number of animals in the zoo
44415 <BR> size_t get_num_animals() const {
44416 <BR> return animals.size();
44419 <BR> // Return a pointer to the ith animal
44420 <BR> Animal* get_animal(size_t i) const {
44421 <BR> return animals[i];
44427 <P>Let's say you SWIG this code and then run IRB:
44429 <DIV class="code targetlang">
44431 <!--span style="font-weight: bold;"-->
44433 <BR>irb(main):001:0>
44434 <!--span style="font-weight: bold;"-->
44438 <BR>irb(main):002:0>
44439 <!--span style="font-weight: bold;"-->
44440 tiger1 = Example::Animal.new("tiger1")
44441 <BR>=> #<Example::Animal:0x2be3820>
44443 <BR>irb(main):004:0>
44444 <!--span style="font-weight: bold;"-->
44446 <BR>=> "tiger1"
44448 <BR>irb(main):003:0>
44449 <!--span style="font-weight: bold;"-->
44450 zoo = Example::Zoo.new()
44451 <BR>=> #<Example::Zoo:0x2be0a60>
44453 <BR>irb(main):006:0>
44454 <!--span style="font-weight: bold;"-->
44455 zoo.add_animal(tiger)
44458 <BR>irb(main):007:0>
44459 <!--span style="font-weight: bold;"-->
44460 zoo.get_num_animals()
44463 <BR>irb(main):007:0>
44464 <!--span style="font-weight: bold;"-->
44465 tiger2 = zoo.remove_animal(0)
44466 <BR>=> #<Example::Animal:0x2bd4a18>
44468 <BR>irb(main):008:0>
44469 <!--span style="font-weight: bold;"-->
44471 <BR>=> "tiger1"
44473 <BR>irb(main):009:0>
44474 <!--span style="font-weight: bold;"-->
44475 tiger1.equal?(tiger2)
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:
44484 <DIV class="code targetlang">
44485 <PRE>irb(main):010:0>
44486 <!--span style="font-weight: bold;"-->
44490 <BR>irb(main):011:0>
44491 <!--span style="font-weight: bold;"-->
44495 <BR>irb(main):012:0>
44496 <!--span style="font-weight: bold;"-->
44498 <BR>(irb):12: [BUG] Segmentation fault
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
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"> "Customization Features"</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
44525 <BR>#include "example.h"
44529 <!--span style="font-weight: bold;"-->
44530 /* Tell SWIG that create_animal creates a new object */
44532 <!--span style="font-weight: bold;"-->
44533 %newobject Zoo::create_animal;
44536 <!--span style="font-weight: bold;"-->
44537 /* Tell SWIG to keep track of mappings between C/C++ structs/classes. */
44538 <BR style="font-weight: bold;">
44539 <!--span style="font-weight: bold;"-->
44542 <BR>%include "example.h"</PRE>
44544 <P>When this code runs we see:
44547 <DIV class="code targetlang">
44549 <!--span style="font-weight: bold;"-->
44551 <BR>irb(main):001:0>
44552 <!--span style="font-weight: bold;"-->
44556 <BR>irb(main):002:0>
44557 <!--span style="font-weight: bold;"-->
44558 tiger1 = Example::Animal.new("tiger1")
44559 <BR>=> #<Example::Animal:0x2be37d8>
44561 <BR>irb(main):003:0>
44562 <!--span style="font-weight: bold;"-->
44563 zoo = Example::Zoo.new()
44564 <BR>=> #<Example::Zoo:0x2be0a18>
44566 <BR>irb(main):004:0>
44567 <!--span style="font-weight: bold;"-->
44568 zoo.add_animal(tiger1)
44571 <BR>irb(main):006:0>
44572 <!--span style="font-weight: bold;"-->
44573 tiger2 = zoo.remove_animal(0)
44574 <BR>=> #<Example::Animal:0x2be37d8>
44576 <BR>irb(main):007:0>
44577 <!--span style="font-weight: bold;"-->
44578 tiger1.equal?(tiger2)
44581 <BR>irb(main):008:0>
44582 <!--span style="font-weight: bold;"-->
44586 <BR>irb(main):009:0>
44587 <!--span style="font-weight: bold;"-->
44591 <BR>irb(main):010:0>
44592 <!--span style="font-weight: bold;"-->
44594 <BR>=> "tiger1"
44595 <BR>irb(main):011:0>
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:
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>
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:
44625 <DIV class="targetlang">
44627 <BR>irb(main):001:0>
44628 <!--span style="font-weight: bold;"-->
44632 <BR>irb(main):002:0> tiger1 =
44633 <!--span style="font-weight: bold;"-->
44634 Example::Animal.new("tiger1")
44635 <BR>=> #<Example::Animal:0x2bea6a8>
44637 <BR>irb(main):003:0> zoo =
44638 <!--span style="font-weight: bold;"-->
44640 <BR>=> #<Example::Zoo:0x2be7960>
44642 <BR>irb(main):004:0>
44643 <!--span style="font-weight: bold;"-->
44644 zoo.add_animal(tiger1)
44647 <BR>irb(main):007:0>
44648 <!--span style="font-weight: bold;"-->
44652 <BR>irb(main):007:0>
44653 <!--span style="font-weight: bold;"-->
44657 <BR>irb(main):005:0>
44658 <!--span style="font-weight: bold;"-->
44659 tiger2 = zoo.get_animal(0)
44660 <BR>(irb):12: [BUG] Segmentation fault</PRE>
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="font-family: monospace;"-->
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' "features" mechanism it uses the same name
44671 matching rules as other kinds of features (see the chapter on <A href="#Customization">
44672 "Customization Features"</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>
44681 <PRE>%module example
44684 <BR>#include "example.h"
44687 <BR>/* Keep track of mappings between C/C++ structs/classes
44688 <BR> and Ruby objects so we can implement a mark function. */
44690 <!--span style="font-weight: bold;"-->
44693 <BR>/* Specify the mark function */
44695 <!--span style="font-weight: bold;"-->
44696 %markfunc Zoo "mark_Zoo";
44698 <BR>%include "example.h"
44702 <BR>static void mark_Zoo(void* ptr) {
44703 <BR> Zoo* zoo = (Zoo*) ptr;
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->get_num_animals();
44709 <BR> for(int i = 0; i < count; ++i) {
44710 <BR> Animal* animal = zoo->get_animal(i);
44711 <BR> VALUE object = SWIG_RubyInstanceFor(animal);
44713 <BR> if (object != Qnil) {
44714 <BR> rb_gc_mark(object);
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">
44729 <BR></B>irb(main):002:0>
44730 <!--span style="font-weight: bold;"-->
44731 tiger1=Example::Animal.new("tiger1")
44732 <BR>=> #<Example::Animal:0x2be3bf8>
44734 <BR>irb(main):003:0>
44735 <!--span style="font-weight: bold;"-->
44737 <BR>=> #<Example::Zoo:0x2be1780>
44739 <BR>irb(main):004:0>
44740 <!--span style="font-weight: bold;"-->
44741 zoo = Example::Zoo.new()
44742 <BR>=> #<Example::Zoo:0x2bde9c0>
44744 <BR>irb(main):005:0>
44745 <!--span style="font-weight: bold;"-->
44746 zoo.add_animal(tiger1)
44749 <BR>irb(main):009:0>
44750 <!--span style="font-weight: bold;"-->
44754 <BR>irb(main):010:0>
44755 <!--span style="font-weight: bold;"-->
44758 <BR>irb(main):014:0>
44759 <!--span style="font-weight: bold;"-->
44760 tiger2 = zoo.get_animal(0)
44761 <BR>=> #<Example::Animal:0x2be3bf8>
44763 <BR>irb(main):015:0>
44764 <!--span style="font-weight: bold;"-->
44766 <BR>=> "tiger1"
44767 <BR>irb(main):016:0>
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 "free" 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 "free"
44780 function via the use of the <TT>%freefunc</TT> directive. The <TT>
44781 %freefunc</TT> directive is implemented using SWIG's' "features"
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 "Customization Features"</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="font-family: monospace;"-->
44801 Zoo::add_animal function should be marked with a
44802 <!--span style="font-family: monospace;"-->
44803 DISOWN typemap and the destructor should be updated as below::</P>
44806 <BR> IterType iter = this->animals.begin();
44807 <BR> IterType end = this->animals.end();
44809 <BR> for(iter; iter != end; ++iter) {
44810 <BR> Animal* animal = *iter;
44811 <BR> delete animal;
44815 <P>When we use these objects in IRB we see:</P>
44816 <DIV class="code targetlang">
44817 <PRE class="targetlang">
44818 <!--span style="font-weight: bold;"-->
44820 <BR>irb(main):002:0>
44821 <!--span style="font-weight: bold;"-->
44825 <BR>irb(main):003:0>
44826 <!--span style="font-weight: bold;"-->
44827 zoo = Example::Zoo.new()
44828 <BR>=> #<Example::Zoo:0x2be0fe8>
44830 <BR>irb(main):005:0>
44831 <!--span style="font-weight: bold;"-->
44832 tiger1 = Example::Animal.new("tiger1")
44833 <BR>=> #<Example::Animal:0x2bda760>
44835 <BR>irb(main):006:0>
44836 <!--span style="font-weight: bold;"-->
44837 zoo.add_animal(tiger1)
44840 <BR>irb(main):007:0>
44841 <!--span style="font-weight: bold;"-->
44845 <BR>irb(main):008:0>
44846 <!--span style="font-weight: bold;"-->
44850 <BR>irb(main):009:0>
44851 <!--span style="font-weight: bold;"-->
44853 <BR>(irb):12: [BUG] Segmentation fault
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
44869 <PRE>%module example
44872 <BR>#include "example.h"
44875 <BR>/* Specify that ownership is transferred to the zoo
44876 <BR> when calling add_animal */
44877 <BR>%apply SWIGTYPE *DISOWN { Animal* animal };
44879 <BR>/* Track objects */
44882 <BR>/* Specify the mark function */
44883 <BR>%freefunc Zoo "free_Zoo";
44885 <BR>%include "example.h"
44888 <BR> static void free_Zoo(void* ptr) {
44889 <BR> Zoo* zoo = (Zoo*) ptr;
44891 <BR> /* Loop over each animal */
44892 <BR> int count = zoo->get_num_animals();
44894 <BR> for(int i = 0; i < count; ++i) {
44895 <BR> /* Get an animal */
44896 <BR> Animal* animal = zoo->get_animal(i);
44898 <BR> /* Unlink the Ruby object from the C++ object */
44899 <BR> SWIG_RubyUnlinkObjects(animal);
44901 <BR> /* Now remove the tracking for this animal */
44902 <BR> SWIG_RubyRemoveTracking(animal);
44905 <BR> /* Now call SWIG_RubyRemoveTracking for the zoo */
44906 <BR> SWIG_RubyRemoveTracking(ptr);
44908 <BR> /* Now free the zoo which will free the animals it contains */
44913 <P>Now when we use these objects in IRB we see:</P>
44914 <DIV class="code targetlang">
44916 <!--span style="font-weight: bold;"-->
44918 <BR>irb(main):002:0>
44919 <!--span style="font-weight: bold;"-->
44923 <BR>irb(main):003:0>
44924 <!--span style="font-weight: bold;"-->
44925 zoo = Example::Zoo.new()
44926 <BR>=> #<Example::Zoo:0x2be0fe8>
44928 <BR>irb(main):005:0>
44929 <!--span style="font-weight: bold;"-->
44930 tiger1 = Example::Animal.new("tiger1")
44931 <BR>=> #<Example::Animal:0x2bda760>
44933 <BR>irb(main):006:0>
44934 <!--span style="font-weight: bold;"-->
44935 zoo.add_animal(tiger1)
44938 <BR>irb(main):007:0>
44939 <!--span style="font-weight: bold;"-->
44943 <BR>irb(main):008:0>
44944 <!--span style="font-weight: bold;"-->
44948 <BR>irb(main):009:0>
44949 <!--span style="font-weight: bold;"-->
44951 <BR>RuntimeError: This Animal * already released
44952 <BR> from (irb):10:in `get_name'
44954 <BR>irb(main):011:0></PRE>
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. 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
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. 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. Ruby will then be
44978 careful not to remove any of those objects in that location.</P>
44979 <P>So far so good. For a normal Ruby session, all the above is
44980 completely transparent and magic to the extensions developer. </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. As such,
44983 ruby_init() will likely end up being called from within some other
44984 function. This can lead Ruby to measure incorrectly where the stack
44985 begins and can result in Ruby incorrectly collecting those temporary
44986 VALUE objects that are created once another function is called. 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. </P>
44990 <P>To solve the problem, SWIG can now generate code with director
44991 functions containing the optional macros SWIG_INIT_STACK and
44992 SWIG_RELEASE_STACK. These macros will try to force Ruby to
44993 reinitiliaze the beginning of the stack the first time a director
44994 function is called. This will lead Ruby to measure and not collect any
44995 VALUE objects defined from that point on. </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
44998 Class::memberfunction; // only re-init the stack in this director
45000 <BR> %ignorestack Class::memberfunction; // do not re-init the stack in
45001 this director method
45002 <BR> %initstack Class; // init the stack on all the
45003 methods of this class
45004 <BR> %initstack; // all director functions will re-init the stack</DIV>
45006 <H1><A name="Tcl"></A>33 SWIG and Tcl</H1>
45009 <DIV class="sectiontoc">
45011 <LI><A href="#Tcl_nn2">Preliminaries</A>
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>
45023 <LI><A href="#Tcl_nn11">Building Tcl/Tk Extensions under Windows 95/NT</A>
45025 <LI><A href="#Tcl_nn12">Running SWIG from Developer Studio</A></LI>
45026 <LI><A href="#Tcl_nn13">Using NMAKE</A></LI>
45029 <LI><A href="#Tcl_nn14">A tour of basic C/C++ wrapping</A>
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>
45047 <LI><A href="#Tcl_nn29">Further details on the Tcl class interface</A>
45049 <LI><A href="#Tcl_nn30">Proxy classes</A></LI>
45050 <LI><A href="#Tcl_nn31">Memory management</A></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>
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>
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>
45070 <LI><A href="#Tcl_nn45">Proxy classes</A></LI>
45073 <LI><A href="#Tcl_nn46">Tcl/Tk Stubs</A></LI>
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>
45085 $ swig -tcl example.i
45088 <P> If building a C++ extension, add the <TT>-c++</TT> option:</P>
45091 $ swig -c++ -tcl example.i
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>
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
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>
45116 $ swig -tcl example.i
45118 $ gcc -c example_wrap.c -I/usr/local/include
45119 $ gcc -shared example.o example_wrap.o -o example.so
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 "<TT>example</TT>
45131 ", the name of the corresponding object file should be "<TT>example.so</TT>
45132 ". 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>
45151 extern int fact(int);
45152 extern int mod(int, int);
45153 extern double My_variable;
45156 %include "tclsh.i" // Include code for rebuilding tclsh
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>
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 \
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>
45192 % load ./example.so
45198 <P> A common error received by first-time users is the following:</P>
45201 % load ./example.so
45202 couldn't find procedure Example_Init
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
45213 <P> Another common error is something similar to the following:</P>
45216 % load ./example.so
45217 couldn't load file "./example.so": ./example.so: undefined symbol: fact
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
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>
45237 $ gcc -shared example.o example_wrap.o -L/home/beazley/projects/lib -lfoo \
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>
45245 % load ./example.so
45246 couldn't load file "./example.so": libfoo.so: cannot open shared object file:
45247 No such file or directory
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>
45259 $ gcc -shared example.o example_wrap.o -L/home/beazley/projects/lib -lfoo \
45260 -Xlinker -rpath /home/beazley/projects/lib \
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
45272 $ env LD_LIBRARY_PATH=/home/beazley/projects/lib tclsh
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>
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
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>
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
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>
45322 libstdc++-libc6.1-1.so.2 => /usr/lib/libstdc++-libc6.1-1.so.2 (0x40019000)
45323 libm.so.6 => /lib/libm.so.6 (0x4005b000)
45324 libc.so.6 => /lib/libc.so.6 (0x40077000)
45325 /lib/ld-linux.so.2 => /lib/ld-linux.so.2 (0x40000000)
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
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>
45364 swig -tcl -prefix Foo example.i
45367 <P> If you have a function "<TT>bar</TT>" in the SWIG file, the prefix
45368 option will append the prefix to the name when creating a command and
45369 call it "<TT>Foo_bar</TT>".</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>
45375 swig -tcl -namespace example.i
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
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>
45394 <LI>Open up a new workspace and use the AppWizard to select a DLL
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 "Custom Build" option.</LI>
45404 <LI>Enter "SWIG" in the description field.</LI>
45405 <LI>Enter "<TT>swig -tcl -o $(ProjDir)\$(InputName)_wrap.c $(InputPath)</TT>
45406 " in the "Build command(s) field"</LI>
45407 <LI>Enter "<TT>$(ProjDir)\$(InputName)_wrap.c</TT>" in the "Output
45408 files(s) field".</LI>
45409 <LI>Next, select the settings for the entire project and go to
45410 "C++:Preprocessor". Add the include directories for your Tcl
45411 installation under "Additional include directories".</LI>
45412 <LI>Finally, select the settings for the entire project and go to "Link
45413 Options". Add the Tcl library file to your link libraries. For example
45414 "<TT>tcl80.lib</TT>". 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>
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>
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>
45439 # Makefile for building various SWIG generated extensions
45443 INTERFACE = $(IFILE).i
45444 WRAPFILE = $(IFILE)_wrap.c
45446 # Location of the Visual C++ tools (32 bit assumed)
45449 TARGET = example.dll
45450 CC = $(TOOLS)\bin\cl.exe
45451 LINK = $(TOOLS)\bin\link.exe
45452 INCLUDE32 = -I$(TOOLS)\include
45455 # C Library needed to build a DLL
45457 DLLIBC = msvcrt.lib oldnames.lib
45459 # Windows libraries that are apparently needed
45460 WINLIB = kernel32.lib advapi32.lib user32.lib gdi32.lib comdlg32.lib
45463 # Libraries common to all DLLs
45464 LIBS = $(DLLIBC) $(WINLIB)
45467 LOPT = -debug:full -debugtype:cv /NODEFAULTLIB /RELEASE /NOLOGO /
45468 MACHINE:$(MACHINE) -entry:_DllMainCRTStartup@12 -dll
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
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
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
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
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
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>
45506 couldn't find procedure Md_Init
45509 <P> To fix this, supply an extra argument to <TT>load</TT> like this:</P>
45512 % load ./md5.so md5
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
45524 <P> creates a built-in function <TT>fact</TT> that works exactly like
45525 you think it does:</P>
45528 % load ./example.so
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
45540 // SWIG interface file with global variables
45544 extern double density;
45549 <P> Now look at the Tcl interface:</P>
45552 % puts $density # Output value of C global variable
45554 % set density 0.95 # Change value
45557 <P> If you make an error in variable assignment, you will get an error
45558 message. For example:</P>
45561 % set density "hello"
45562 can't set "density": Type error. expected a double.
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
45569 <P> To make ordinary variables read-only, you can use the <TT>%immutable</TT>
45570 directive. For example:</P>
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>
45593 extern char *path; // Read-only (due to %immutable)
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>
45603 #define VERSION "1.0"
45605 enum Beverage { ALE, LAGER, STOUT, PILSNER };
45607 %constant int FOO = 42;
45608 %constant const char *path = "/usr/local";
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>
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
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>
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
45639 %apply int CONSTANT { int x };
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>
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>
45666 FILE *fopen(const char *filename, const char *mode);
45667 int fputs(const char *, FILE *);
45668 int fclose(FILE *);
45671 <P> When wrapped, you will be able to use the functions in a natural way
45672 from Tcl. For example:</P>
45675 % load ./example.so
45676 % set f [fopen junk w]
45677 % fputs "Hello World\n" $f
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
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>
45710 Bar *FooToBar(Foo *f) {
45714 /* C++-style cast */
45715 Foo *BarToFoo(Bar *b) {
45716 return dynamic_cast<Foo*>(b);
45719 Foo *IncrFoo(Foo *f, int i) {
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.
45741 <P> is used as follows:</P>
45745 % v configure -x 3.5 -y 7.2
45746 % puts "[v cget -x] [v cget -y] [v cget -z]"
45751 <P> Similar access is provided for unions and the data members of C++
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>
45759 % puts [v cget -this]
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>
45773 int x; /* Read-only members */
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>
45795 <P> If accessed in Tcl, you will see behavior like this:</P>
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>
45810 % c configure -x [b cget -x] # Copy contents of b.x to c.x
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>
45831 <P> Now, suppose that you access the <TT>f</TT> attribute of <TT>Bar</TT>
45836 % set x [b cget -f]
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
45845 Foo *x = &b->f; /* Points inside b */
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
45854 % set x [b cget -f]
45856 invalid command name "x"
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>
45865 % set x [b cget -f]
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
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
45883 <P> In many of these structure examples, a simple name like "v" or "b"
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>
45892 <P> you can call the function in Tcl as follows:</P>
45895 % Foo x # Create a Foo object
45896 % blah x # Pass the object to a function
45899 <P> It is also possible to call the function using the raw pointer
45900 value. For instance:</P>
45903 % blah [x cget -this] # Pass object to a function
45906 <P> It is also possible to create and use objects using variables. For
45910 % set b [Bar] # Create a Bar
45911 % $b cget -f # Member access
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.
45922 % Foo f # Create object f
45923 % rename f ""
45929 % Foo f # Create object f
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>
45944 int search(char *item);
45945 void insert(char *item);
45946 void remove(char *item);
45952 <P> you can use it in Tcl like this:</P>
45961 % puts [l cget -length]
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>
45979 <P> In Tcl, the static member is accessed as follows:</P>
45982 % Spam_foo # Spam::foo()
45983 % puts $Spam_bar # Spam::bar
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>
45995 class Bar : public Foo {
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>
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>
46011 % Foo f # Create a Foo
46012 % Bar b # Create a Bar
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
46020 <P> In C++, there are many different ways a function might receive and
46021 manipulate objects. For example:</P>
46024 void spam1(Foo *x); // Pass by pointer
46025 void spam2(Foo &x); // Pass by reference
46026 void spam3(Foo x); // Pass by value
46027 void spam4(Foo x[]); // Array of objects
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>
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)
46043 <P> Similar behavior occurs for return values. For example, if you had
46044 functions like this,</P>
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
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>
46066 <P> You can use them in Tcl in a straightforward manner:</P>
46070 % foo Hello # foo(char *c)
46073 <P> Similarly, if you have a class like this,</P>
46079 Foo(const Foo &);
46084 <P> you can write Tcl code like this:</P>
46087 % Foo f # Create a Foo
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>
46103 void foo(Bar &b);
46106 <P> If declarations such as these appear, you will get a warning message
46110 example.i:12: Warning(509): Overloaded spam(short) is shadowed by spam(int)
46114 <P> To fix this, you either need to ignore or rename one of the methods.
46118 %rename(spam_short) spam(short);
46121 void spam(short); // Accessed as spam_short
46127 %ignore spam(short);
46130 void spam(short); // Ignored
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 "SWIG and C++" 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>
46147 double rpart, ipart;
46149 Complex(double r = 0, double i = 0) : rpart(r), ipart(i) { }
46150 Complex(const Complex &c) : rpart(c.rpart), ipart(c.ipart) { }
46151 Complex &operator=(const Complex &c);
46152 Complex operator+(const Complex &c) const;
46153 Complex operator-(const Complex &c) const;
46154 Complex operator*(const Complex &c) const;
46155 Complex operator-() const;
46157 double re() const { return rpart; }
46158 double im() const { return ipart; }
46162 <P> When wrapped, it works like this:</P>
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>
46185 % set e [c - d] # operator-(const Complex &)
46186 % puts "[$e re] [$e im]"
46188 % set f [c -] # operator-()
46189 % puts "[$f re] [$f im]"
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>
46201 friend Complex operator+(double, const Complex &c);
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
46212 %rename(Complex_add_dc) operator+(double, const Complex &);
46214 Complex operator+(double, const Complex &c);
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>
46235 <P> it works in Tcl as follows:</P>
46238 % load ./example.so
46242 % v configure -x 3.4
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>
46249 %rename(Bar_spam) Bar::spam;
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>
46275 #include "pair.h"
46278 template<class T1, class T2>
46280 typedef T1 first_type;
46281 typedef T2 second_type;
46285 pair(const T1&, const T2&);
46289 %template(pairii) pair<int,int>;
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 "smart pointers." Generally, this involves the use
46308 of a template class that implements <TT>operator->()</TT> like this:</P>
46311 template<class T> class SmartPtr {
46313 T *operator->();
46318 <P> Then, if you have a class like this,</P>
46328 <P> A smart pointer would be used in C++ as follows:</P>
46331 SmartPtr<Foo> p = CreateFoo(); // Created somehow (not shown)
46333 p->x = 3; // Foo::x
46334 int y = p->bar(); // Foo::bar
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>
46344 %template(SmartPtrFoo) SmartPtr<Foo>;
46348 <P> Now, in Tcl, everything should just "work":</P>
46351 % set p [CreateFoo] # Create a smart-pointer somehow
46352 % $p configure -x 3 # Foo::x
46353 % $p bar # Foo::bar
46356 <P> If you ever need to access the underlying pointer returned by <TT>
46357 operator->()</TT> itself, simply use the <TT>__deref__()</TT> method.
46361 % set f [$p __deref__] # Returns underlying Foo *
46364 <H2><A name="Tcl_nn29"></A>33.4 Further details on the Tcl class
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">"SWIG basics"</A> and <A href="#SWIGPlus">
46375 "SWIG and C++"</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>
46387 <P> then SWIG transforms it into a set of low-level procedural wrappers.
46394 void delete_Foo(Foo *f) {
46397 int Foo_x_get(Foo *f) {
46400 void Foo_x_set(Foo *f, int value) {
46403 int Foo_spam(Foo *f, int arg1) {
46404 return f->spam(arg1);
46408 <P> These wrappers are actually found in the Tcl extension module. For
46409 example, you can certainly do this:</P>
46412 % load ./example.so
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>
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>
46466 <BR><DIV class="code">
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
46494 <P> When wrapped in Tcl, careful observation will reveal that ownership
46495 changes whenever an object is assigned to a global variable. For
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>
46518 % f configure -next g
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
46533 void set_value(Object *v) { value = v; }
46538 <P> Now, consider the following Tcl code:</P>
46541 % Object v # Create an object
46542 % Node n # Create a node
46543 % n setvalue v # Set value
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>
46559 % v -disown # Give ownership to C/C++
46560 % v -acquire # Acquire ownership
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>
46570 void add(int x, int y, int *result) {
46578 int sub(int *x, int *y) {
46583 <P> The easiest way to handle these situations is to use the <TT>
46584 typemaps.i</TT> file. For example:</P>
46588 %include "typemaps.i"
46590 void add(int, int, int *OUTPUT);
46591 int sub(int *INPUT, int *INPUT);
46594 <P> In Tcl, this allows you to pass simple values instead of pointer.
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>
46611 %include "typemaps.i"
46613 %apply int *OUTPUT { int *result };
46614 %apply int *INPUT { int *x, int *y};
46616 void add(int x, int y, int *result);
46617 int sub(int *x, int *y);
46620 <P> If a function mutates one of its parameters like this,</P>
46623 void negate(int *x) {
46628 <P> you can use <TT>INOUT</TT> like this:</P>
46631 %include "typemaps.i"
46633 void negate(int *INOUT);
46636 <P> In Tcl, a mutated parameter shows up as a return value. For example:</P>
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>
46649 /* send message, return number of bytes sent, along with success code */
46650 int send_message(char *text, int len, int *success);
46653 <P> To wrap such a function, simply use the <TT>OUTPUT</TT> rule above.
46658 %include "typemaps.i"
46659 %apply int *OUTPUT { int *success };
46661 int send_message(char *text, int *success);
46664 <P> When used in Tcl, the function will return multiple values as a
46668 set r [send_message "Hello World"]
46669 set bytes [lindex $r 0]
46670 set success [lindex $r 1]
46673 <P> Another common use of multiple return values are in query functions.
46677 void get_dimensions(Matrix *m, int *rows, int *columns);
46680 <P> To wrap this, you might use the following:</P>
46684 %include "typemaps.i"
46685 %apply int *OUTPUT { int *rows, int *columns };
46687 void get_dimensions(Matrix *m, int *rows, *columns);
46690 <P> Now, in Perl:</P>
46693 set dim [get_dimensions $m]
46694 set r [lindex $dim 0]
46695 set c [lindex $dim 1]
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>
46706 class RangeError {}; // Used for an exception
46708 class DoubleArray {
46713 // Create a new array of fixed size
46714 DoubleArray(int size) {
46715 ptr = new double[size];
46718 // Destroy an array
46722 // Return the length of the array
46727 // Get an item from the array and perform bounds checking.
46728 double getitem(int i) {
46729 if ((i >= 0) && (i < n))
46732 throw RangeError();
46735 // Set an item in the array and perform bounds checking.
46736 void setitem(int i, double val) {
46737 if ((i >= 0) && (i < n))
46740 throw RangeError();
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>
46753 $action // Gets substituted by actual function call
46755 catch (RangeError) {
46756 Tcl_SetStringObj(tcl_result,"Array index out-of-bounds");
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
46768 %exception getitem {
46772 catch (RangeError) {
46773 Tcl_SetStringObj(tcl_result,"Array index out-of-bounds");
46778 %exception setitem {
46782 catch (RangeError) {
46783 Tcl_SetStringObj(tcl_result,"Array index out-of-bounds");
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>
46795 %define RANGE_ERROR
46800 catch (RangeError) {
46801 Tcl_SetStringObj(tcl_result,"Array index out-of-bounds");
46807 %exception getitem RANGE_ERROR;
46808 %exception setitem RANGE_ERROR;
46811 <P> Since SWIG's exception handling is user-definable, you are not
46812 limited to C++ exception handling. See the chapter on "<A href="#Customization">
46813 Customization Features</A>" 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 "<A href="#Typemaps">Typemaps</A>
46819 " 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>
46833 if (Tcl_GetIntFromObj(interp,$input,&$1) == TCL_ERROR) return TCL_ERROR;
46834 printf("Received an integer : %d\n",$1);
46837 extern int fact(int n);
46841 <P> Typemaps are always associated with some specific aspect of code
46842 generation. In this case, the "in" 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
46853 % load ./example.so
46855 Received an integer : 6
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>
46866 %typemap(in) int n {
46867 if (Tcl_GetIntFromObj(interp,$input,&$1) == TCL_ERROR) return TCL_ERROR;
46868 printf("n = %d\n",$1);
46871 extern int fact(int n);
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>
46885 %typemap(in) int n {
46886 if (Tcl_GetIntFromObj(interp,$input,&$1) == TCL_ERROR) return TCL_ERROR;
46887 printf("n = %d\n",$1);
46890 typedef int Integer;
46891 extern int fact(Integer n); // Above typemap is applied
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.
46902 %typemap(in) (char *str, int len) {
46903 $1 = Tcl_GetStringFromObj($input,&$2);
46906 int count(char c, char *str, int len);
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>
46914 % count e "Hello World"
46918 <H3><A name="Tcl_nn36"></A>33.7.2 Tcl typemaps</H3>
46919 <P> The previous section illustrated an "in" 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 "out" typemap like this:</P>
46925 %typemap(out) int {
46926 Tcl_SetObjResult(interp,Tcl_NewIntObj($1));
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
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
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 "<A href="#Typemaps">
46967 Typemaps</A>" 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
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>
47002 // This tells SWIG to treat char ** as a special case
47003 %typemap(in) char ** {
47004 Tcl_Obj **listobjv;
47007 if (Tcl_ListObjGetElements(interp, $input, &nitems, &listobjv) == TCL_ERROR) {
47010 $1 = (char **) malloc((nitems+1)*sizeof(char *));
47011 for (i = 0; i < nitems; i++) {
47012 $1[i] = Tcl_GetStringFromObj(listobjv[i],0);
47017 // This gives SWIG some cleanup code that will get called after the function call
47018 %typemap(freearg) char ** {
47024 // Now a test functions
47026 int print_args(char **argv) {
47029 printf("argv[%d] = %s\n", i,argv[i]);
47035 %include "tclsh.i"
47042 % print_args {John Guido Larry}
47049 <H3><A name="Tcl_nn39"></A>33.7.5 Returning values in arguments</H3>
47050 <P> The "argout" typemap can be used to return a value originating from
47051 a function argument. For example :</P>
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);
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) {
47066 // Now a function returning two values
47067 int mypow(double a, double b, double *outvalue) {
47068 if ((a < 0) || (b < 0)) return -1;
47069 *outvalue = pow(a,b);
47074 <P> When wrapped, SWIG matches the <TT>argout</TT> typemap to the "<TT>
47075 double *outvalue</TT>" 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>
47080 % mypow 2 3 # Returns two values, a status value and the result
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>
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);
47096 <P><B> Floating Point</B></P>
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);
47104 <P><B> Strings</B></P>
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);
47113 <P><B> Lists</B></P>
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);
47128 <P><B> Objects</B></P>
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);
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
47141 <P><B> Integer conversion</B></P>
47144 %typemap(in) int, short, long {
47146 if (Tcl_GetIntFromObj(interp, $input, &temp) == TCL_ERROR)
47148 $1 = ($1_ltype) temp;
47152 <BR><DIV class="code">
47154 %typemap(out) int, short, long {
47155 Tcl_SetIntObj($result,(int) $1);
47159 <P><B> Floating point conversion</B></P>
47162 %typemap(in) float, double {
47164 if (Tcl_GetDoubleFromObj(interp, $input, &temp) == TCL_ERROR)
47166 $1 = ($1_ltype) temp;
47170 <BR><DIV class="code">
47172 %typemap(out) float, double {
47173 Tcl_SetDoubleObj($result, $1);
47177 <P><B> String Conversion</B></P>
47180 %typemap(in) char * {
47182 $1 = Tcl_GetStringFromObj(interp, &len);
47187 <BR><DIV class="code">
47189 %typemap(out) char * {
47190 Tcl_SetStringObj($result,$1);
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
47206 <P> <TT>Tcl_Obj *SWIG_NewPointerObj(void *ptr, swig_type_info *ty, int
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">
47221 if (SWIG_ConvertPtr($input, (void **) &f, SWIGTYPE_p_Foo, 0) == -1) return NULL;
47224 obj = SWIG_NewPointerObj(f, SWIGTYPE_p_Foo, 0);
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">
47231 %typemap(in) Foo * {
47232 if ((SWIG_ConvertPtr($input,(void **) &$1, $1_descriptor,0)) == -1) return NULL;
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">
47240 %typemap(in) Foo * {
47241 if ((SWIG_ConvertPtr($input,(void **) &$1, $descriptor(Foo *), 0)) == -1) return NULL;
47245 <H2><A name="Tcl_nn43"></A>33.8 Turning a SWIG module into a Tcl
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
47253 % swig -tcl -pkgversion 2.3 example.i
47256 <P> After building the SWIG generated module, you need to execute the "<TT>
47257 pkg_mkIndex</TT>" command inside tclsh. For example :</P>
47261 % pkg_mkIndex . example.so
47265 <P> This creates a file "<TT>pkgIndex.tcl</TT>" 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>
47271 pkgIndex.tcl # The file created by pkg_mkIndex
47272 example.so # The SWIG generated module
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>
47282 % package require example
47288 <P> If you're working with an example in the current directory and this
47289 doesn't work, do this instead :</P>
47293 % lappend auto_path .
47294 % package require example
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
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>
47310 /* File : array.i */
47314 double *new_double(int size) {
47315 return (double *) malloc(size*sizeof(double));
47317 void delete_double(double *a) {
47320 double get_double(double *a, int index) {
47323 void set_double(double *a, int index, double val) {
47326 int *new_int(int size) {
47327 return (int *) malloc(size*sizeof(int));
47329 void delete_int(int *a) {
47332 int get_int(int *a, int index) {
47335 int set_int(int *a, int index, int val) {
47342 <P> While these could be called directly, we could also write a Tcl
47343 script like this :</P>
47346 proc Array {type size} {
47347 set ptr [new_$type $size]
47349 set method [lindex $args 0]
47350 set parms [concat $ptr [lrange $args 1 end]]
47352 get {return [eval "get_$type $parms"]}
47353 set {return [eval "set_$type $parms"]}
47354 delete {eval "delete_$type $ptr; rename $ptr {}"}
47357 # Create a procedure
47358 uplevel "proc $ptr args {set ptr $ptr; set type $type;$code}"
47363 <P> Our script allows easy array access as follows :</P>
47366 set a [Array double 100] ;# Create a double [100]
47367 for {set i 0} {$i < 100} {incr i 1} { ;# Clear the array
47370 $a set 3 3.1455 ;# Set an individual element
47371 set b [$a get 10] ;# Retrieve an element
47373 set ia [Array int 50] ;# Create an int[50]
47374 for {set i 0} {$i < 50} {incr i 1} { ;# Clear it
47377 $ia set 3 7 ;# Set an individual element
47378 set ib [$ia get 10] ;# Get an individual element
47380 $a delete ;# Destroy a
47381 $ia delete ;# Destroy ia
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>
47401 # Provides a simple object oriented interface using
47402 # SWIG's low level interface.
47405 proc new {objectType handle_r args} {
47406 # Creates a new SWIG object of the given type,
47407 # returning a handle in the variable "handle_r".
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
47414 # Create the new object
47416 eval set handle \[new_$objectType $args\]
47418 # Set up the object procedure
47420 proc $handle {cmd args} "eval ${objectType}_\$cmd $handle \$args"
47422 # And the trace ...
47424 uplevel trace variable $handle_r uw "{deleteObject $objectType $handle}"
47426 # Return the handle so that 'new' can be used as an argument to a procedure
47431 proc deleteObject {objectType handle name element op} {
47433 # Check that the object handle has a reasonable form
47435 if {![regexp {_[0-9a-f]*_(.+)_p} $handle]} {
47436 error "deleteObject: not a valid object handle: $handle"
47439 # Remove the object procedure
47441 catch {rename $handle {}}
47443 # Delete the object
47445 delete_$objectType $handle
47448 proc delete {handle_r} {
47450 # A synonym for unset that is more familiar to C++ programmers
47452 uplevel unset $handle_r
47456 <P> To use this file, we simply source it and execute commands such as
47457 "new" and "delete" to manipulate objects. For example :</P>
47463 #include "list.h"
47466 // Very simple C++ example
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
47481 <P> Now a Tcl script using the interface...</P>
47484 load ./list.so list ; # Load the module
47485 source swig_c++.tcl ; # Source the object file
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="8.3"</TT> or the version being compiled with
47511 using <TT>-DSWIG_TCL_STUBS_VERSION=TCL_VERSION</TT>.</P>
47513 <H1><A name="R"></A>34 SWIG and R</H1>
47516 <DIV class="sectiontoc">
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>
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>
47537 <LI>Garbage collection of created objects</LI>
47538 <LI>C Array wrappings</LI>
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">
47546 PKG_LIBS="example.c" R CMD SHLIB example_wrap.c
47549 <P> The corresponding comments for C++ mode are</P>
47550 <DIV class="shell">
47552 swig -c++ -r -o example_wrap.cpp example.i
47553 PKG_LIBS="example.cxx" R CMD SHLIB example_wrap.cpp
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">
47565 dyn.load(paste("example", .Platform$dynlib.ext, sep=""))
47566 source("example.R")
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
47577 source('BigFile.R')
47578 save(list=ls(all=TRUE),file="BigFile.RData", compress=TRUE)
47579 q(save="no")
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). [
47590 and [ are overloaded to allow for R syntax (one based indices and
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
47606 <H1><A name="Extending"></A>35 Extending SWIG to support new languages</H1>
47609 <DIV class="sectiontoc">
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>
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>
47626 <LI><A href="#Extending_nn14">Primitive Data Structures</A>
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>
47636 <LI><A href="#Extending_nn21">Navigating and manipulating parse trees</A>
47638 <LI><A href="#Extending_nn22">Working with attributes</A></LI>
47639 <LI><A href="#Extending_nn23">Type system</A>
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>
47649 <LI><A href="#Extending_nn30">Parameters</A></LI>
47650 <LI><A href="#Extending_nn31">Writing a Language Module</A>
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>
47670 <LI><A href="#Extending_nn44">Typemaps</A>
47672 <LI><A href="#Extending_nn45">Proxy classes</A></LI>
47675 <LI><A href="#Extending_nn46">Guide to parse tree nodes</A></LI>
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
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
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>
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, "The C Programming
47702 Language" by Kernighan and Ritchie (a.k.a, "K&R") and the C++ standard,
47703 "ISO/IEC 14882 Programming Languages - C++" 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>
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>
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>
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>
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>
47775 %include "swig.swg" // Global SWIG configuration
47776 %include "<EM>langconfig.swg</EM>" // Language specific configuration
47777 %include "yourinterface.i" // Your interface file
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
47787 /* Code insertion directives such as %wrapper %{ ... %} */
47789 #define %begin %insert("begin")
47790 #define %runtime %insert("runtime")
47791 #define %header %insert("header")
47792 #define %wrapper %insert("wrapper")
47793 #define %init %insert("init")
47795 /* Access control directives */
47797 #define %immutable %feature("immutable","1")
47798 #define %mutable %feature("immutable")
47800 /* Directives for callback functions */
47802 #define %callback(x) %feature("callback") `x`;
47803 #define %nocallback %feature("callback");
47805 /* %ignore directive */
47807 #define %ignore %rename($ignore)
47808 #define %ignorewarn(x) %rename("$ignore:" x)
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>
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">
47836 <EM>storage</EM> <EM>type</EM> <EM>declarator</EM> <EM>initializer</EM>;
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>
47858 int blah(Foo *x, Bar *y);
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>
47877 int (x); /* A variable x */
47878 int (y)(int); /* A function y */
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 "Effective STL"
47884 discusses this problem in a section on avoiding C++'s "most vexing
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>
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
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 "Node". 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">
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)
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)
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 <n></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 <n></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">
47968 $ swig -c++ -python -debug-module 4 example.i
47969 +++ include ----------------------------------------
47970 | name - "example.i"
47972 +++ module ----------------------------------------
47973 | name - "example"
47975 +++ insert ----------------------------------------
47976 | code - "\n#include \"example.h\"\n"
47978 +++ include ----------------------------------------
47979 | name - "example.h"
47981 +++ class ----------------------------------------
47982 | abstract - "1"
47983 | sym:name - "Shape"
47984 | name - "Shape"
47985 | kind - "class"
47986 | symtab - 0x40194140
47987 | sym:symtab - 0x40191078
47989 +++ access ----------------------------------------
47990 | kind - "public"
47992 +++ constructor ----------------------------------------
47993 | sym:name - "Shape"
47994 | name - "Shape"
47995 | decl - "f()."
47996 | code - "{\n nshapes++;\n }"
47997 | sym:symtab - 0x40194140
47999 +++ destructor ----------------------------------------
48000 | sym:name - "~Shape"
48001 | name - "~Shape"
48002 | storage - "virtual"
48003 | code - "{\n nshapes--;\n }"
48004 | sym:symtab - 0x40194140
48006 +++ cdecl ----------------------------------------
48007 | sym:name - "x"
48008 | name - "x"
48009 | decl - ""
48010 | type - "double"
48011 | sym:symtab - 0x40194140
48013 +++ cdecl ----------------------------------------
48014 | sym:name - "y"
48015 | name - "y"
48016 | decl - ""
48017 | type - "double"
48018 | sym:symtab - 0x40194140
48020 +++ cdecl ----------------------------------------
48021 | sym:name - "move"
48022 | name - "move"
48023 | decl - "f(double,double)."
48024 | parms - double ,double
48025 | type - "void"
48026 | sym:symtab - 0x40194140
48028 +++ cdecl ----------------------------------------
48029 | sym:name - "area"
48030 | name - "area"
48031 | decl - "f(void)."
48033 | storage - "virtual"
48034 | value - "0"
48035 | type - "double"
48036 | sym:symtab - 0x40194140
48038 +++ cdecl ----------------------------------------
48039 | sym:name - "perimeter"
48040 | name - "perimeter"
48041 | decl - "f(void)."
48043 | storage - "virtual"
48044 | value - "0"
48045 | type - "double"
48046 | sym:symtab - 0x40194140
48048 +++ cdecl ----------------------------------------
48049 | sym:name - "nshapes"
48050 | name - "nshapes"
48051 | decl - ""
48052 | storage - "static"
48053 | type - "int"
48054 | sym:symtab - 0x40194140
48056 +++ class ----------------------------------------
48057 | sym:name - "Circle"
48058 | name - "Circle"
48059 | kind - "class"
48060 | bases - 0x40194510
48061 | symtab - 0x40194538
48062 | sym:symtab - 0x40191078
48064 +++ access ----------------------------------------
48065 | kind - "private"
48067 +++ cdecl ----------------------------------------
48068 | name - "radius"
48069 | decl - ""
48070 | type - "double"
48072 +++ access ----------------------------------------
48073 | kind - "public"
48075 +++ constructor ----------------------------------------
48076 | sym:name - "Circle"
48077 | name - "Circle"
48079 | decl - "f(double)."
48080 | code - "{ }"
48081 | sym:symtab - 0x40194538
48083 +++ cdecl ----------------------------------------
48084 | sym:name - "area"
48085 | name - "area"
48086 | decl - "f(void)."
48088 | storage - "virtual"
48089 | type - "double"
48090 | sym:symtab - 0x40194538
48092 +++ cdecl ----------------------------------------
48093 | sym:name - "perimeter"
48094 | name - "perimeter"
48095 | decl - "f(void)."
48097 | storage - "virtual"
48098 | type - "double"
48099 | sym:symtab - 0x40194538
48101 +++ class ----------------------------------------
48102 | sym:name - "Square"
48103 | name - "Square"
48104 | kind - "class"
48105 | bases - 0x40194760
48106 | symtab - 0x40194788
48107 | sym:symtab - 0x40191078
48109 +++ access ----------------------------------------
48110 | kind - "private"
48112 +++ cdecl ----------------------------------------
48113 | name - "width"
48114 | decl - ""
48115 | type - "double"
48117 +++ access ----------------------------------------
48118 | kind - "public"
48120 +++ constructor ----------------------------------------
48121 | sym:name - "Square"
48122 | name - "Square"
48124 | decl - "f(double)."
48125 | code - "{ }"
48126 | sym:symtab - 0x40194788
48128 +++ cdecl ----------------------------------------
48129 | sym:name - "area"
48130 | name - "area"
48131 | decl - "f(void)."
48133 | storage - "virtual"
48134 | type - "double"
48135 | sym:symtab - 0x40194788
48137 +++ cdecl ----------------------------------------
48138 | sym:name - "perimeter"
48139 | name - "perimeter"
48140 | decl - "f(void)."
48142 | storage - "virtual"
48143 | type - "double"
48144 | sym:symtab - 0x40194788
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>
48168 %rename(foo_i) foo(int);
48169 %rename(foo_d) foo(double);
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 <n></TT> or <TT>debug-module <n></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">
48184 $ swig -debug-top 4 example.i
48186 +++ cdecl ----------------------------------------
48187 | sym:name - "foo_i"
48188 | name - "foo"
48189 | decl - "f(int)."
48191 | type - "void"
48192 | sym:symtab - 0x40165078
48194 +++ cdecl ----------------------------------------
48195 | sym:name - "foo_d"
48196 | name - "foo"
48197 | decl - "f(double)."
48199 | type - "void"
48200 | sym:symtab - 0x40165078
48202 +++ cdecl ----------------------------------------
48203 | sym:name - "foo"
48204 | name - "foo"
48205 | decl - "f(p.Bar)."
48207 | type - "void"
48208 | sym:symtab - 0x40165078
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>
48216 %rename(foo) foo_i(int);
48217 %rename(foo) foo_d(double;
48220 void foo_d(double);
48224 <P> When you run SWIG on this you now get:</P>
48225 <DIV class="shell">
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 )
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
48240 %feature("except") getitem(int) {
48243 } catch (badindex) {
48251 Object *getitem(int index) throws(badindex);
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">
48263 +++ cdecl ----------------------------------------
48264 | sym:name - "getitem"
48265 | name - "getitem"
48266 | decl - "f(int).p."
48268 | type - "Object"
48269 | feature:except - "{\n try {\n $action\n } catc..."
48270 | sym:symtab - 0x40168ac8
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
48291 virtual int *bar(int x);
48295 <P> When the parser constructs a node for the member <TT>bar</TT>, it
48296 creates a raw "cdecl" node with the following attributes:</P>
48297 <DIV class="diagram">
48308 <P> To produce wrapper code, this "cdecl" 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">
48316 type : p.int <-- Notice change in return type
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">
48332 parms : Foo *self, int x <-- Added parameter
48334 wrap:action : result = (arg1)->bar(arg2) <-- Action code added
48335 sym:name : Foo_bar <-- Symbol name changed
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 "SWIG
48341 Basics" chapter. A small fragment of "action" 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>
48352 class PYTHON : public Language {
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 *);
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>
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>
48400 <P> In most cases, other typenames in the source are aliases for one of
48401 these primitive types. Specifically:</P>
48404 typedef String SwigType;
48406 typedef Hash ParmList;
48408 typedef Hash Symtab;
48409 typedef Hash Typetab;
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 "" 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
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>
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>
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>
48447 <P><B> <TT>char *Strstr(const String_or_char *s, const String_or_char
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>
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>
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>
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.
48471 <P> Returns the number of replacements made (if any).</P>
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>
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>
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
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>
48569 List *l = (some list);
48572 for (i = First(l); i.item; i = Next(i)) {
48573 Printf(stdout,"%s\n", i.item);
48576 Hash *h = (some hash);
48579 for (j = First(j); j.item; j= Next(j)) {
48580 Printf(stdout,"%s : %s\n", j.key, j.item);
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>
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>
48632 /* Print into a string */
48633 String *s = NewString("");
48634 Printf(s,"Hello\n");
48635 for (i = 0; i < 10; i++) {
48636 Printf(s,"%d\n", i);
48639 /* Print string into a file */
48640 Printf(f, "%s\n", s);
48643 <P> Similarly, the preprocessor and parser all operate on string-files.</P>
48645 <H2><A name="Extending_nn21"></A>35.6 Navigating and manipulating parse
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
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
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
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>
48701 int functionHandler(Node *n) {
48702 String *name = Getattr(n,"name");
48703 String *symname = Getattr(n,"sym:name");
48704 SwigType *type = Getattr(n,"type");
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>
48715 Setattr(n,"python:docstring", doc); /* Store docstring */
48719 <P> A quick way to check the value of an attribute is to use the <TT>
48720 checkAttribute()</TT> function like this:</P>
48723 if (checkAttribute(n,"storage","virtual")) {
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("foo",n,"type",NIL)</TT>, then the "type" attribute will be
48741 copied and saved as "foo:type". The namespace name itself is stored in
48742 the "view" 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
48756 int variableHandler(Node *n) {
48757 Swig_save("variableHandler",n,"type","sym:name",NIL);
48758 String *symname = Getattr(n,"sym:name");
48759 SwigType *type = Getattr(n,"type");
48761 Append(symname,"_global"); // Change symbol name
48762 SwigType_add_pointer(type); // Add pointer
48766 Swig_restore(n); // Restore original values
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 "*<EM>name</EM>", a
48777 copy of the attribute is saved as with <TT>Swig_save()</TT>. If an
48778 attribute is specified as "?<EM>name</EM>", 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
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">
48794 C datatype SWIG encoding (strings)
48795 ----------------------------- --------------------------
48796 int "int"
48797 int * "p.int"
48798 const int * "p.q(const).int"
48799 int (*x)(int,double) "p.f(int,double).int"
48800 int [20][30] "a(20).a(30).int"
48801 int (F::*)(int) "m(F).f(int).int"
48802 vector<int> * "p.vector<(int)>"
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 "p.f(int,double).int" is a "pointer to a function(int,double) that
48808 returns int".</P>
48809 <P> The following operator encodings are used in type strings:</P>
48810 <DIV class="diagram">
48813 ------------------- -------------------------------
48815 a(n). Array of dimension n
48817 m(class). Member pointer to class
48819 q(qlist). Qualifiers
48822 <P> In addition, type names may be parameterized by templates. This is
48823 represented by enclosing the template parameters in <TT><( ... )></TT>.
48824 Variable length arguments are represented by the special base type of <TT>
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">
48831 `p.a(10).p.f(int,p.f(int).int)` foo(int, int (*x)(int));
48834 <P> This corresponds to the immediately obvious C declaration:</P>
48835 <DIV class="diagram">
48837 (*(*foo(int,int (*)(int)))[10])(int,int (*)(int));
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>
48851 <P> is processed in a few pieces. In this case, you have the base type "<TT>
48852 int</TT>" and the declarator of type "<TT>a(30).p.</TT>". To make the
48853 final type, the two parts are just joined together using string
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>
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>
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>"const"</TT> or <TT>"volatile"</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
48887 <P><B> <TT>void SwigType_add_function(SwigType *ty, ParmList *p)</TT></B>
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>
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>"a(20).a(10).p.int"</TT>, then this function would return <TT>
48907 "a(20).a(10)."</TT> and modify <TT>ty</TT> so that it has the value <TT>
48908 "p.int"</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>"f(int).int"</TT>, then this function would return <TT>
48913 "f(int)."</TT> and modify <TT>ty</TT> so that it has the value <TT>"int"</TT>
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>"p.a(20).int"</TT>, this function would return <TT>"int"</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>"p.a(20).int"</TT>, this function would return <TT>
48922 "p.a(20)."</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
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>
48960 typedef int Integer;
48961 typedef Integer *IntegerPtr;
48962 typedef int Number;
48966 <P> produces two trees like this:</P>
48967 <DIV class="diagram">
48973 Integer Size Number IntegerPtr
48976 <P> To resolve a single typedef relationship, the following function is
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">
48987 Original type After typedef_resolve()
48988 ------------------------ -----------------------
48991 p.IntegerPtr p.p.Integer
48992 p.p.Integer p.p.int
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">
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
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>
49027 typedef double Matrix4[4][4];
49028 Matrix4 x; // type = 'Matrix4', ltype='p.a(4).double'
49030 typedef const char * Literal;
49031 Literal y; // type = 'Literal', ltype='p.char'
49034 <H3><A name="Extending_nn29"></A>35.8.6 Output functions</H3>
49035 <P> The following functions produce strings that are suitable for
49037 <P><B> <TT>String *SwigType_str(SwigType *ty, const String_or_char *id =
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 "p.f(int).int"
49041 and <TT>id</TT> is "foo", then this function produces "<TT>int
49042 (*foo)(int)</TT>". 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
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 "<TT>
49054 q(const).p.char</TT>" and <TT>id</TT> is "<TT>foo</TT>", this function
49055 produces the string "<TT>(char *) foo</TT>".</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 "<TT>
49061 q(const).p.char</TT>" and <TT>id</TT> is "<TT>foo</TT>", this function
49062 produces the string "<TT>(const char *) foo</TT>".</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">
49075 "type" - Parameter type (required)
49076 "name" - Parameter name (optional)
49077 "value" - Initializer (optional)
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">
49087 for (p = parms; p; p = nextSibling(p)) {
49088 SwigType *type = Getattr(p,"type");
49089 String *name = Getattr(p,"name");
49090 String *value = Getattr(p,"value");
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
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 "<TT>(int *p, int n, double x);</TT>".</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>
49136 #include "swigmod.h"
49138 class PYTHON : public Language {
49141 virtual void main(int argc, char *argv[]) {
49142 printf("I'm the Python module.\n");
49145 virtual int top(Node *n) {
49146 printf("Generating code.\n");
49152 extern "C" Language *
49153 swig_python(void) {
49154 return new PYTHON();
49158 <P> The "swigmod.h" 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 "swigconfig.h" 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. "PYTHON" 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 "C"</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
49182 <P> Save the code for your language module in a file named "<TT>
49183 python.cxx</TT>" 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">
49194 $ <B>./autogen.sh</B>
49197 <P> Next re-run <TT>configure</TT> to regenerate all of the Makefiles:</P>
49198 <DIV class="shell">
49200 $ <B>./configure</B>
49203 <P> Finally, rebuild SWIG with your module added:</P>
49204 <DIV class="shell">
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>
49219 void Language::main(int argc, char *argv[]) {
49220 for (int i = 1; i < argc; i++) {
49222 if(strcmp(argv[i],"-interface") == 0) {
49224 interface = NewString(argv[i+1]);
49226 Swig_mark_arg(i+1);
49231 } else if (strcmp(argv[i],"-globals") == 0) {
49233 global_name = NewString(argv[i+1]);
49235 Swig_mark_arg(i+1);
49240 } else if ( (strcmp(argv[i],"-proxy") == 0)) {
49243 } else if (strcmp(argv[i],"-keyword") == 0) {
49246 } else if (strcmp(argv[i],"-help") == 0) {
49247 fputs(usage,stderr);
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
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>
49268 void main(int argc, char *argv[]) {
49269 ... command line options ...
49271 /* Set language-specific subdirectory in SWIG library */
49272 SWIG_library_directory("python");
49274 /* Set language-specific preprocessing symbol */
49275 Preprocessor_define("SWIGPYTHON 1", 0);
49277 /* Set language-specific configuration file */
49278 SWIG_config_file("python.swg");
49280 /* Set typemap language (historical) */
49281 SWIG_typemap_lang("python");
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>
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>
49314 <P> An outline of <TT>top()</TT> might be as follows:</P>
49317 int Python::top(Node *n) {
49319 /* Get the module name */
49320 String *module = Getattr(n,"name");
49322 /* Get the output file name */
49323 String *outfile = Getattr(n,"outfile");
49325 /* Initialize I/O (see next section) */
49328 /* Output module initialization code */
49331 /* Emit code for children */
49335 /* Cleanup files */
49342 <H3><A name="Extending_nn37"></A>35.10.6 Module I/O and wrapper skeleton</H3>
49344 <!-- please report bugs in this section to mgossage -->
49345 <P> Within SWIG wrappers, there are four main sections. These are (in
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
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>
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
49358 <P> To perform this will require several additions to the code in
49359 various places, such as:</P>
49362 class PYTHON : public Language {
49364 /* General DOH objects used for holding the strings */
49376 int Python::top(Node *n) {
49380 /* Initialize I/O */
49381 f_begin = NewFile(outfile, "w", SWIG_output_files());
49383 FileErrorDisplay(outfile);
49384 SWIG_exit(EXIT_FAILURE);
49386 f_runtime = NewString("");
49387 f_init = NewString("");
49388 f_header = NewString("");
49389 f_wrappers = NewString("");
49391 /* Register file targets with the SWIG file handler */
49392 Swig_register_filebyname("begin", f_begin);
49393 Swig_register_filebyname("header", f_header);
49394 Swig_register_filebyname("wrapper", f_wrappers);
49395 Swig_register_filebyname("runtime", f_runtime);
49396 Swig_register_filebyname("init", f_init);
49398 /* Output module initialization code */
49399 Swig_banner(f_begin);
49402 /* Emit code for children */
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);
49412 /* Cleanup files */
49415 Delete(f_wrappers);
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
49433 <P> A simple modification to write some basic details to the wrapper
49434 looks like this:</P>
49437 int Python::functionWrapper(Node *n) {
49438 /* Get some useful attributes of this function */
49439 String *name = Getattr(n,"sym:name");
49440 SwigType *type = Getattr(n,"type");
49441 ParmList *parms = Getattr(n,"parms");
49442 String *parmstr= ParmList_str_defaultargs(parms); // to string
49443 String *func = SwigType_str(type, NewStringf("%s(%s)", name, parmstr));
49444 String *action = Getattr(n,"wrap:action");
49446 Printf(f_wrappers,"functionWrapper : %s\n", func);
49447 Printf(f_wrappers," action : %s\n", action);
49452 <P> This will now produce some useful information within your wrapper
49454 <DIV class="shell">
49456 functionWrapper : void delete_Shape(Shape *self)
49457 action : delete arg1;
49459 functionWrapper : void Shape_x_set(Shape *self,double x)
49460 action : if (arg1) (arg1)->x = arg2;
49462 functionWrapper : double Shape_x_get(Shape *self)
49463 action : result = (double) ((arg1)->x);
49465 functionWrapper : void Shape_y_set(Shape *self,double y)
49466 action : if (arg1) (arg1)->y = arg2;
49470 <H3><A name="Extending_nn38"></A>35.10.7 Low-level code generators</H3>
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>
49487 /* wrapper for TYPE3 some_function(TYPE1,TYPE2); */
49488 RETURN_TYPE _wrap_some_function(ARGS){
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);
49498 result=some_function(arg1,arg2);
49500 convert 'result' to whatever the language wants;
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>
49516 <LI>The skeleton: the function wrapper, and call, but without the
49518 <LI>The conversion: converting the arguments to-from what the language
49521 <P> The first step will be done in the code, the second will be done in
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>
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>
49534 virtual int functionWrapper(Node *n) {
49535 /* get useful atributes */
49536 String *name = Getattr(n,"sym:name");
49537 SwigType *type = Getattr(n,"type");
49538 ParmList *parms = Getattr(n,"parms");
49541 /* create the wrapper object */
49542 Wrapper *wrapper = NewWrapper();
49544 /* create the functions wrappered name */
49545 String *wname = Swig_name_wrapper(iname);
49547 /* deal with overloading */
49550 /* write the wrapper function definition */
49551 Printv(wrapper->def,"RETURN_TYPE ", wname, "(ARGS) {",NIL);
49553 /* if any additional local variable needed, add them now */
49556 /* write the list of locals/arguments required */
49557 emit_args(type, parms, wrapper);
49559 /* check arguments */
49562 /* write typemaps(in) */
49565 /* write constriants */
49568 /* Emit the function call */
49569 emit_action(n,wrapper);
49571 /* return value if necessary */
49574 /* write typemaps(out) */
49577 /* add cleanup code */
49580 /* Close the function(ok) */
49581 Printv(wrapper->code, "return ALL_OK;\n", NIL);
49583 /* add the failure cleanup code */
49586 /* Close the function(error) */
49587 Printv(wrapper->code, "return ERROR;\n", "}\n", NIL);
49589 /* final substititions if applicable */
49592 /* Dump the function out */
49593 Wrapper_print(wrapper,f_wrappers);
49597 DelWrapper(wrapper);
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>
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>"skip" 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
49634 <TR><TD>Examples/test-suite/ subdir name</TD><TD>(none)</TD></TR>
49636 <!-- add more uses here (remember to adjust header) -->
49638 <P> As you can see, most usages are direct.</P>
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>
49658 <DT><B> Makefile.in</B></DT>
49660 <P> Some of the variables AC_SUBSTituted are essential to the support of
49661 your language module. Fashion these into a shell script "test" clause
49662 and assign that to a skip tag using "-z" and "-o":</P>
49663 <DIV class="code"> <TT>skip-qux99 = [ -z "@QUX99INCLUDE@" -o -z
49664 "@QUX99LIBS" ]</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>
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>
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
49710 <LI> typemaps.i</LI>
49711 <LI> std_string.i</LI>
49712 <LI> std_vector.i</LI>
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 "simple" C example and the "class" 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>
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 "classes" 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>
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>
49768 <LI> Demonstrate basic C code working by porting the "simple" example
49769 including a runtime test, see for example <TT>Examples/python/simple</TT>
49771 <LI> Demonstrate basic C++ code working by porting the "class" example
49772 including a runtime test, see for example <TT>Examples/python/class</TT>
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
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>
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&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&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>
49808 $ make beautify-file INDENTFILE=Modules/emit.cxx
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
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
49821 <P><B> cdecl</B></P>
49822 <P> Describes general C declarations including variables, functions, and
49823 typedefs. A declaration is parsed as "storage T D" where storage is a
49824 storage class, T is a base type, and D is a declarator.</P>
49825 <DIV class="diagram">
49827 "name" - Declarator name
49828 "type" - Base type T
49829 "decl" - Declarator type (abstract)
49830 "storage" - Storage class (static, extern, typedef, etc.)
49831 "parms" - Function parameters (if a function)
49832 "code" - Function body code (if supplied)
49833 "value" - Default value (if supplied)
49836 <P><B> constructor</B></P>
49837 <P> C++ constructor declaration.</P>
49838 <DIV class="diagram">
49840 "name" - Name of constructor
49841 "parms" - Parameters
49842 "decl" - Declarator (function with parameters)
49843 "code" - Function body code (if any)
49844 "feature:new" - Set to indicate return of new object.
49847 <P><B> destructor</B></P>
49848 <P> C++ destructor declaration.</P>
49849 <DIV class="diagram">
49851 "name" - Name of destructor
49852 "code" - Function body code (if any)
49853 "storage" - Storage class (set if virtual)
49854 "value" - Default value (set if pure virtual).
49857 <P><B> access</B></P>
49858 <P> C++ access change.</P>
49859 <DIV class="diagram">
49861 "kind" - public, protected, private
49864 <P><B> constant</B></P>
49865 <P> Constant created by %constant or #define.</P>
49866 <DIV class="diagram">
49868 "name" - Name of constant.
49869 "type" - Base type.
49870 "value" - Value.
49871 "storage" - Set to %constant
49872 "feature:immutable" - Set to indicate read-only
49875 <P><B> class</B></P>
49876 <P> C++ class definition or C structure definition.</P>
49877 <DIV class="diagram">
49879 "name" - Name of the class.
49880 "kind" - Class kind ("struct", "union", "class")
49881 "symtab" - Enclosing symbol table.
49882 "tdname" - Typedef name. Use for typedef struct { ... } A.
49883 "abstract" - Set if class has pure virtual methods.
49884 "baselist" - List of base class names.
49885 "storage" - Storage class (if any)
49886 "unnamed" - Set if class is unnamed.
49889 <P><B> enum</B></P>
49890 <P> Enumeration.</P>
49891 <DIV class="diagram">
49893 "name" - Name of the enum (if supplied).
49894 "storage" - Storage class (if any)
49895 "tdname" - Typedef name (typedef enum { ... } name).
49896 "unnamed" - Set if enum is unnamed.
49899 <P><B> enumitem</B></P>
49900 <P> Enumeration value.</P>
49901 <DIV class="diagram">
49903 "name" - Name of the enum value.
49904 "type" - Type (integer or char)
49905 "value" - Enum value (if given)
49906 "feature:immutable" - Set to indicate read-only
49909 <P><B> namespace</B></P>
49910 <P> C++ namespace.</P>
49911 <DIV class="diagram">
49913 "name" - Name of the namespace.
49914 "symtab" - Symbol table for enclosed scope.
49915 "unnamed" - Set if unnamed namespace
49916 "alias" - Alias name. Set for namespace A = B;
49919 <P><B> using</B></P>
49920 <P> C++ using directive.</P>
49921 <DIV class="diagram">
49923 "name" - Name of the object being referred to.
49924 "uname" - Qualified name actually given to using.
49925 "node" - Node being referenced.
49926 "namespace" - Namespace name being reference (using namespace name)
49929 <P><B> classforward</B></P>
49930 <P> A forward C++ class declaration.</P>
49931 <DIV class="diagram">
49933 "name" - Name of the class.
49934 "kind" - Class kind ("union", "struct", "class")
49937 <P><B> insert</B></P>
49938 <P> Code insertion directive. For example, %{ ... %} or
49939 %insert(section).</P>
49940 <DIV class="diagram">
49942 "code" - Inserted code
49943 "section" - Section name ("header", "wrapper", etc.)
49947 <P> Top of the parse tree.</P>
49948 <DIV class="diagram">
49950 "module" - Module name
49953 <P><B> extend</B></P>
49954 <P> %extend directive.</P>
49955 <DIV class="diagram">
49957 "name" - Module name
49958 "symtab" - Symbol table of enclosed scope.
49961 <P><B> apply</B></P>
49962 <P> %apply pattern { patternlist }.</P>
49963 <DIV class="diagram">
49965 "pattern" - Source pattern.
49966 "symtab" - Symbol table of enclosed scope.
49969 <P><B> clear</B></P>
49970 <P> %clear patternlist;</P>
49971 <DIV class="diagram">
49973 "firstChild" - Patterns to clear
49976 <P><B> include</B></P>
49977 <P> %include directive.</P>
49978 <DIV class="diagram">
49980 "name" - Filename
49981 "firstChild" - Children
49984 <P><B> import</B></P>
49985 <P> %import directive.</P>
49986 <DIV class="diagram">
49988 "name" - Filename
49989 "firstChild" - Children
49992 <P><B> module</B></P>
49993 <P> %module directive.</P>
49994 <DIV class="diagram">
49996 "name" - Name of the module
49999 <P><B> typemap</B></P>
50000 <P> %typemap directive.</P>
50001 <DIV class="diagram">
50003 "method" - Typemap method name.
50004 "code" - Typemap code.
50005 "kwargs" - Keyword arguments (if any)
50006 "firstChild" - Typemap patterns
50009 <P><B> typemapcopy</B></P>
50010 <P> %typemap directive with copy.</P>
50011 <DIV class="diagram">
50013 "method" - Typemap method name.
50014 "pattern" - Typemap source pattern.
50015 "firstChild" - Typemap patterns
50018 <P><B> typemapitem</B></P>
50019 <P> %typemap pattern. Used with %apply, %clear, %typemap.</P>
50020 <DIV class="diagram">
50022 "pattern" - Typemap pattern (a parameter list)
50023 "parms" - Typemap parameters.
50026 <P><B> types</B></P>
50027 <P> %types directive.</P>
50028 <DIV class="diagram">
50030 "parms" - List of parameter types.
50031 "convcode" - Code which replaces the default casting / conversion code
50034 <P><B> extern</B></P>
50035 <P> extern "X" { ... } declaration.</P>
50036 <DIV class="diagram">
50038 "name" - Name "C", "Fortran", etc.