Commit | Line | Data |
---|---|---|
920dae64 AT |
1 | <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd"> |
2 | <HTML> | |
3 | <HEAD> | |
4 | <TITLE>SWIG-1.3 Documentation</TITLE> | |
5 | <META HTTP-EQUIV="Content-Type" CONTENT="text/html; CHARSET=iso-iso-8859-1"> | |
6 | <STYLE TYPE="text/css"><!-- | |
7 | div.sectiontoc { | |
8 | border-style: dotted; | |
9 | border-width: 2px; | |
10 | padding: 2pt; | |
11 | } | |
12 | ||
13 | h2 { | |
14 | padding: 3px; | |
15 | color: #000000; | |
16 | border-bottom: 2px | |
17 | solid #dddddd; | |
18 | } | |
19 | ||
20 | h3, h4 { | |
21 | margin-left: 1em; | |
22 | } | |
23 | ||
24 | p,lu,li,table,dl { | |
25 | margin-left: 2em; | |
26 | margin-right: 2em; | |
27 | } | |
28 | ||
29 | div.indent { | |
30 | margin-left: 4em; | |
31 | margin-right: 4em; | |
32 | } | |
33 | ||
34 | div.code { | |
35 | border-style: solid; | |
36 | border-width: 1px; | |
37 | padding: 2pt; | |
38 | margin-left: 4em; | |
39 | margin-right: 4em; | |
40 | background-color: #F0FFFF; | |
41 | } | |
42 | ||
43 | div.targetlang { | |
44 | border-style: solid; | |
45 | border-width: 1px; | |
46 | padding: 2pt; | |
47 | margin-left: 4em; | |
48 | margin-right: 4em; | |
49 | background-color: #d7f6bb; | |
50 | } | |
51 | ||
52 | ||
53 | div.shell { | |
54 | border-style: solid; | |
55 | border-width: 1px; | |
56 | padding: 2pt; | |
57 | margin-left: 4em; | |
58 | margin-right: 4em; | |
59 | background-color: #DCDCDC; | |
60 | } | |
61 | ||
62 | div.diagram { | |
63 | border-style: solid; | |
64 | border-width: 1px; | |
65 | padding: 2pt; | |
66 | margin-left: 4em; | |
67 | margin-right: 4em; | |
68 | background-color: #FFEBCD; | |
69 | } | |
70 | ||
71 | ul li p { | |
72 | margin-left: 0; | |
73 | margin-right: 0; | |
74 | } | |
75 | ||
76 | ol li p { | |
77 | margin-left: 0; | |
78 | margin-right: 0; | |
79 | } | |
80 | ||
81 | dl dd p { | |
82 | margin-left: 0; | |
83 | margin-right: 0; | |
84 | } | |
85 | ||
86 | div.indent p { | |
87 | margin-left: 0; | |
88 | margin-right: 0; | |
89 | } | |
90 | ||
91 | ||
92 | BODY { font-family: serif } | |
93 | H1 { font-family: sans-serif } | |
94 | H2 { font-family: sans-serif } | |
95 | H3 { font-family: sans-serif } | |
96 | H4 { font-family: sans-serif } | |
97 | H5 { font-family: sans-serif } | |
98 | H6 { font-family: sans-serif } | |
99 | SUB { font-size: smaller } | |
100 | SUP { font-size: smaller } | |
101 | PRE { font-family: monospace } | |
102 | --></STYLE> | |
103 | </HEAD> | |
104 | <BODY BGCOLOR="#ffffff" LINK="#0000ff" VLINK="#0000ff" ALINK="#0000ff"> | |
105 | <CENTER><A HREF="#CONTENTS"><IMG SRC="swig16.png" BORDER="0" WIDTH="167" HEIGHT="85" ALT="SWIG-1.3 Documentation"><BR> | |
106 | <H1>SWIG-1.3 Documentation</H1></A><BR> | |
107 | </CENTER> | |
108 | <HR NOSHADE> | |
109 | <H1 ALIGN="CENTER"><A NAME="CONTENTS">Table of Contents</A></H1> | |
110 | <BR> | |
111 | <BR><B><A HREF="#Sections">SWIG-1.3 Development Documentation</A></B> | |
112 | <UL> | |
113 | <LI><A HREF="#1_1">Sections</A> | |
114 | <UL> | |
115 | <LI><A HREF="#1_1_1">SWIG Core Documentation</A></LI> | |
116 | <LI><A HREF="#1_1_2">Language Module Documentation</A></LI> | |
117 | <LI><A HREF="#1_1_3">Developer Documentation</A></LI> | |
118 | <LI><A HREF="#1_1_4">Documentation that has not yet been updated</A></LI> | |
119 | </UL> | |
120 | </LI> | |
121 | </UL> | |
122 | <B><A HREF="#Preface">1 Preface</A></B> | |
123 | <UL> | |
124 | <LI><A HREF="#Preface_nn2">1.1 Introduction</A></LI> | |
125 | <LI><A HREF="#Preface_nn3">1.2 Special Introduction for Version 1.3</A></LI> | |
126 | <LI><A HREF="#Preface_nn4">1.3 SWIG Versions</A></LI> | |
127 | <LI><A HREF="#Preface_nn5">1.4 SWIG resources</A></LI> | |
128 | <LI><A HREF="#Preface_nn6">1.5 Prerequisites</A></LI> | |
129 | <LI><A HREF="#Preface_nn7">1.6 Organization of this manual</A></LI> | |
130 | <LI><A HREF="#Preface_nn8">1.7 How to avoid reading the manual</A></LI> | |
131 | <LI><A HREF="#Preface_nn9">1.8 Backwards Compatibility</A></LI> | |
132 | <LI><A HREF="#Preface_nn10">1.9 Credits</A></LI> | |
133 | <LI><A HREF="#Preface_nn11">1.10 Bug reports</A></LI> | |
134 | </UL> | |
135 | <B><A HREF="#Introduction">2 Introduction</A></B> | |
136 | <UL> | |
137 | <LI><A HREF="#Introduction_nn2">2.1 What is SWIG?</A></LI> | |
138 | <LI><A HREF="#Introduction_nn3">2.2 Why use SWIG?</A></LI> | |
139 | <LI><A HREF="#Introduction_nn4">2.3 A SWIG example</A> | |
140 | <UL> | |
141 | <LI><A HREF="#Introduction_nn5">2.3.1 SWIG interface file</A></LI> | |
142 | <LI><A HREF="#Introduction_nn6">2.3.2 The swig command</A></LI> | |
143 | <LI><A HREF="#Introduction_nn7">2.3.3 Building a Perl5 module</A></LI> | |
144 | <LI><A HREF="#Introduction_nn8">2.3.4 Building a Python module</A></LI> | |
145 | <LI><A HREF="#Introduction_nn9">2.3.5 Shortcuts</A></LI> | |
146 | </UL> | |
147 | </LI> | |
148 | <LI><A HREF="#Introduction_nn10">2.4 Supported C/C++ language features</A> | |
149 | </LI> | |
150 | <LI><A HREF="#Introduction_nn11">2.5 Non-intrusive interface building</A> | |
151 | </LI> | |
152 | <LI><A HREF="#Introduction_build_system">2.6 Incorporating SWIG into a | |
153 | build system</A></LI> | |
154 | <LI><A HREF="#Introduction_nn12">2.7 Hands off code generation</A></LI> | |
155 | <LI><A HREF="#Introduction_nn13">2.8 SWIG and freedom</A></LI> | |
156 | </UL> | |
157 | <B><A HREF="#Windows">3 Getting started on Windows</A></B> | |
158 | <UL> | |
159 | <LI><A HREF="#Windows_nn2">3.1 Installation on Windows</A> | |
160 | <UL> | |
161 | <LI><A HREF="#Windows_nn3">3.1.1 Windows Executable</A></LI> | |
162 | </UL> | |
163 | </LI> | |
164 | <LI><A HREF="#examples">3.2 SWIG Windows Examples</A> | |
165 | <UL> | |
166 | <LI><A HREF="#Windows_nn5">3.2.1 Instructions for using the Examples | |
167 | with Visual Studio</A> | |
168 | <UL> | |
169 | <LI><A HREF="#Windows_nn6">3.2.1.1 Python</A></LI> | |
170 | <LI><A HREF="#Windows_nn7">3.2.1.2 TCL</A></LI> | |
171 | <LI><A HREF="#Windows_nn8">3.2.1.3 Perl</A></LI> | |
172 | <LI><A HREF="#Windows_nn9">3.2.1.4 Java</A></LI> | |
173 | <LI><A HREF="#Windows_nn10">3.2.1.5 Ruby</A></LI> | |
174 | <LI><A HREF="#Windows_nn11">3.2.1.6 C#</A></LI> | |
175 | </UL> | |
176 | </LI> | |
177 | <LI><A HREF="#Windows_nn12">3.2.2 Instructions for using the Examples | |
178 | with other compilers</A></LI> | |
179 | </UL> | |
180 | </LI> | |
181 | <LI><A HREF="#Windows_nn13">3.3 SWIG on Cygwin and MinGW</A> | |
182 | <UL> | |
183 | <LI><A HREF="#swig_exe">3.3.1 Building swig.exe on Windows</A> | |
184 | <UL> | |
185 | <LI><A HREF="#Windows_nn15">3.3.1.1 Building swig.exe using MinGW and | |
186 | MSYS</A></LI> | |
187 | <LI><A HREF="#Windows_nn16">3.3.1.2 Building swig.exe using Cygwin</A></LI> | |
188 | <LI><A HREF="#Windows_nn17">3.3.1.3 Building swig.exe alternatives</A></LI> | |
189 | </UL> | |
190 | </LI> | |
191 | <LI><A HREF="#examples_cygwin">3.3.2 Running the examples on Windows | |
192 | using Cygwin</A></LI> | |
193 | </UL> | |
194 | </LI> | |
195 | </UL> | |
196 | <B><A HREF="#Scripting">4 Scripting Languages</A></B> | |
197 | <UL> | |
198 | <LI><A HREF="#Scripting_nn2">4.1 The two language view of the world</A></LI> | |
199 | <LI><A HREF="#Scripting_nn3">4.2 How does a scripting language talk to | |
200 | C?</A> | |
201 | <UL> | |
202 | <LI><A HREF="#Scripting_nn4">4.2.1 Wrapper functions</A></LI> | |
203 | <LI><A HREF="#Scripting_nn5">4.2.2 Variable linking</A></LI> | |
204 | <LI><A HREF="#Scripting_nn6">4.2.3 Constants</A></LI> | |
205 | <LI><A HREF="#Scripting_nn7">4.2.4 Structures and classes</A></LI> | |
206 | <LI><A HREF="#Scripting_nn8">4.2.5 Proxy classes</A></LI> | |
207 | </UL> | |
208 | </LI> | |
209 | <LI><A HREF="#Scripting_nn9">4.3 Building scripting language extensions</A> | |
210 | <UL> | |
211 | <LI><A HREF="#Scripting_nn10">4.3.1 Shared libraries and dynamic loading</A> | |
212 | </LI> | |
213 | <LI><A HREF="#Scripting_nn11">4.3.2 Linking with shared libraries</A></LI> | |
214 | <LI><A HREF="#Scripting_nn12">4.3.3 Static linking</A></LI> | |
215 | </UL> | |
216 | </LI> | |
217 | </UL> | |
218 | <B><A HREF="#SWIG">5 SWIG Basics</A></B> | |
219 | <UL> | |
220 | <LI><A HREF="#SWIG_nn2">5.1 Running SWIG</A> | |
221 | <UL> | |
222 | <LI><A HREF="#SWIG_nn3">5.1.1 Input format</A></LI> | |
223 | <LI><A HREF="#output">5.1.2 SWIG Output</A></LI> | |
224 | <LI><A HREF="#SWIG_nn5">5.1.3 Comments</A></LI> | |
225 | <LI><A HREF="#SWIG_nn6">5.1.4 C Preprocessor</A></LI> | |
226 | <LI><A HREF="#SWIG_nn7">5.1.5 SWIG Directives</A></LI> | |
227 | <LI><A HREF="#SWIG_nn8">5.1.6 Parser Limitations</A></LI> | |
228 | </UL> | |
229 | </LI> | |
230 | <LI><A HREF="#SWIG_nn9">5.2 Wrapping Simple C Declarations</A> | |
231 | <UL> | |
232 | <LI><A HREF="#SWIG_nn10">5.2.1 Basic Type Handling</A></LI> | |
233 | <LI><A HREF="#SWIG_nn11">5.2.2 Global Variables</A></LI> | |
234 | <LI><A HREF="#SWIG_nn12">5.2.3 Constants</A></LI> | |
235 | <LI><A HREF="#SWIG_nn13">5.2.4 A brief word about const</A></LI> | |
236 | <LI><A HREF="#SWIG_nn14">5.2.5 A cautionary tale of char *</A></LI> | |
237 | </UL> | |
238 | </LI> | |
239 | <LI><A HREF="#SWIG_nn15">5.3 Pointers and complex objects</A> | |
240 | <UL> | |
241 | <LI><A HREF="#SWIG_nn16">5.3.1 Simple pointers</A></LI> | |
242 | <LI><A HREF="#SWIG_nn17">5.3.2 Run time pointer type checking</A></LI> | |
243 | <LI><A HREF="#SWIG_nn18">5.3.3 Derived types, structs, and classes</A></LI> | |
244 | <LI><A HREF="#SWIG_nn19">5.3.4 Undefined datatypes</A></LI> | |
245 | <LI><A HREF="#SWIG_nn20">5.3.5 Typedef</A></LI> | |
246 | </UL> | |
247 | </LI> | |
248 | <LI><A HREF="#SWIG_nn21">5.4 Other Practicalities</A> | |
249 | <UL> | |
250 | <LI><A HREF="#SWIG_nn22">5.4.1 Passing structures by value</A></LI> | |
251 | <LI><A HREF="#SWIG_nn23">5.4.2 Return by value</A></LI> | |
252 | <LI><A HREF="#SWIG_nn24">5.4.3 Linking to structure variables</A></LI> | |
253 | <LI><A HREF="#SWIG_nn25">5.4.4 Linking to char *</A></LI> | |
254 | <LI><A HREF="#SWIG_nn26">5.4.5 Arrays</A></LI> | |
255 | <LI><A HREF="#SWIG_readonly_variables">5.4.6 Creating read-only | |
256 | variables</A></LI> | |
257 | <LI><A HREF="#SWIG_nn28">5.4.7 Renaming and ignoring declarations</A></LI> | |
258 | <LI><A HREF="#SWIG_default_args">5.4.8 Default/optional arguments</A></LI> | |
259 | <LI><A HREF="#SWIG_nn30">5.4.9 Pointers to functions and callbacks</A></LI> | |
260 | </UL> | |
261 | </LI> | |
262 | <LI><A HREF="#SWIG_nn31">5.5 Structures and unions</A> | |
263 | <UL> | |
264 | <LI><A HREF="#SWIG_nn32">5.5.1 Typedef and structures</A></LI> | |
265 | <LI><A HREF="#SWIG_nn33">5.5.2 Character strings and structures</A></LI> | |
266 | <LI><A HREF="#SWIG_nn34">5.5.3 Array members</A></LI> | |
267 | <LI><A HREF="#SWIG_nn35">5.5.4 Structure data members</A></LI> | |
268 | <LI><A HREF="#SWIG_nn36">5.5.5 C constructors and destructors</A></LI> | |
269 | <LI><A HREF="#SWIG_adding_member_functions">5.5.6 Adding member | |
270 | functions to C structures</A></LI> | |
271 | <LI><A HREF="#SWIG_nn38">5.5.7 Nested structures</A></LI> | |
272 | <LI><A HREF="#SWIG_nn39">5.5.8 Other things to note about structure | |
273 | wrapping</A></LI> | |
274 | </UL> | |
275 | </LI> | |
276 | <LI><A HREF="#SWIG_nn40">5.6 Code Insertion</A> | |
277 | <UL> | |
278 | <LI><A HREF="#SWIG_nn41">5.6.1 The output of SWIG</A></LI> | |
279 | <LI><A HREF="#SWIG_nn42">5.6.2 Code insertion blocks</A></LI> | |
280 | <LI><A HREF="#SWIG_nn43">5.6.3 Inlined code blocks</A></LI> | |
281 | <LI><A HREF="#SWIG_nn44">5.6.4 Initialization blocks</A></LI> | |
282 | </UL> | |
283 | </LI> | |
284 | <LI><A HREF="#SWIG_nn45">5.7 An Interface Building Strategy</A> | |
285 | <UL> | |
286 | <LI><A HREF="#SWIG_nn46">5.7.1 Preparing a C program for SWIG</A></LI> | |
287 | <LI><A HREF="#SWIG_nn47">5.7.2 The SWIG interface file</A></LI> | |
288 | <LI><A HREF="#SWIG_nn48">5.7.3 Why use separate interface files?</A></LI> | |
289 | <LI><A HREF="#SWIG_nn49">5.7.4 Getting the right header files</A></LI> | |
290 | <LI><A HREF="#SWIG_nn50">5.7.5 What to do with main()</A></LI> | |
291 | </UL> | |
292 | </LI> | |
293 | </UL> | |
294 | <B><A HREF="#SWIGPlus">6 SWIG and C++</A></B> | |
295 | <UL> | |
296 | <LI><A HREF="#SWIGPlus_nn2">6.1 Comments on C++ Wrapping</A></LI> | |
297 | <LI><A HREF="#SWIGPlus_nn3">6.2 Approach</A></LI> | |
298 | <LI><A HREF="#SWIGPlus_nn4">6.3 Supported C++ features</A></LI> | |
299 | <LI><A HREF="#SWIGPlus_nn5">6.4 Command line options and compilation</A></LI> | |
300 | <LI><A HREF="#SWIGPlus_nn6">6.5 Simple C++ wrapping</A> | |
301 | <UL> | |
302 | <LI><A HREF="#SWIGPlus_nn7">6.5.1 Constructors and destructors</A></LI> | |
303 | <LI><A HREF="#SWIGPlus_nn8">6.5.2 Default constructors</A></LI> | |
304 | <LI><A HREF="#SWIGPlus_nn9">6.5.3 When constructor wrappers aren't | |
305 | created</A></LI> | |
306 | <LI><A HREF="#SWIGPlus_nn10">6.5.4 Copy constructors</A></LI> | |
307 | <LI><A HREF="#SWIGPlus_nn11">6.5.5 Member functions</A></LI> | |
308 | <LI><A HREF="#SWIGPlus_nn12">6.5.6 Static members</A></LI> | |
309 | <LI><A HREF="#SWIGPlus_nn13">6.5.7 Member data</A></LI> | |
310 | </UL> | |
311 | </LI> | |
312 | <LI><A HREF="#SWIGPlus_default_args">6.6 Default arguments</A></LI> | |
313 | <LI><A HREF="#SWIGPlus_nn15">6.7 Protection</A></LI> | |
314 | <LI><A HREF="#SWIGPlus_nn16">6.8 Enums and constants</A></LI> | |
315 | <LI><A HREF="#SWIGPlus_nn17">6.9 Friends</A></LI> | |
316 | <LI><A HREF="#SWIGPlus_nn18">6.10 References and pointers</A></LI> | |
317 | <LI><A HREF="#SWIGPlus_nn19">6.11 Pass and return by value</A></LI> | |
318 | <LI><A HREF="#SWIGPlus_nn20">6.12 Inheritance</A></LI> | |
319 | <LI><A HREF="#SWIGPlus_nn21">6.13 A brief discussion of multiple | |
320 | inheritance, pointers, and type checking</A></LI> | |
321 | <LI><A HREF="#SWIGPlus_nn22">6.14 Renaming</A></LI> | |
322 | <LI><A HREF="#SWIGPlus_overloaded_methods">6.15 Wrapping Overloaded | |
323 | Functions and Methods</A> | |
324 | <UL> | |
325 | <LI><A HREF="#SWIGPlus_nn24">6.15.1 Dispatch function generation</A></LI> | |
326 | <LI><A HREF="#SWIGPlus_nn25">6.15.2 Ambiguity in Overloading</A></LI> | |
327 | <LI><A HREF="#ambiguity_resolution_renaming">6.15.3 Ambiguity resolution | |
328 | and renaming</A></LI> | |
329 | <LI><A HREF="#SWIGPlus_nn27">6.15.4 Comments on overloading</A></LI> | |
330 | </UL> | |
331 | </LI> | |
332 | <LI><A HREF="#SWIGPlus_nn28">6.16 Wrapping overloaded operators</A></LI> | |
333 | <LI><A HREF="#SWIGPlus_nn29">6.17 Class extension</A></LI> | |
334 | <LI><A HREF="#SWIGPlus_nn30">6.18 Templates</A></LI> | |
335 | <LI><A HREF="#SWIGPlus_nn31">6.19 Namespaces</A></LI> | |
336 | <LI><A HREF="#SWIGPlus_exception_specifications">6.20 Exception | |
337 | specifications</A></LI> | |
338 | <LI><A HREF="#SWIGPlus_nn33">6.21 Pointers to Members</A></LI> | |
339 | <LI><A HREF="#SWIGPlus_nn34">6.22 Smart pointers and operator->()</A></LI> | |
340 | <LI><A HREF="#SWIGPlus_nn35">6.23 Using declarations and inheritance</A></LI> | |
341 | <LI><A HREF="#SWIGPlus_nn36">6.24 Partial class definitions</A></LI> | |
342 | <LI><A HREF="#SWIGPlus_nn37">6.25 A brief rant about const-correctness</A> | |
343 | </LI> | |
344 | <LI><A HREF="#SWIGPlus_nn38">6.26 Proxy classes</A> | |
345 | <UL> | |
346 | <LI><A HREF="#SWIGPlus_nn39">6.26.1 Construction of proxy classes</A></LI> | |
347 | <LI><A HREF="#SWIGPlus_nn40">6.26.2 Resource management in proxies</A></LI> | |
348 | <LI><A HREF="#SWIGPlus_nn41">6.26.3 Language specific details</A></LI> | |
349 | </UL> | |
350 | </LI> | |
351 | <LI><A HREF="#SWIGPlus_nn42">6.27 Where to go for more information</A></LI> | |
352 | </UL> | |
353 | <B><A HREF="#Preprocessor">7 Preprocessing</A></B> | |
354 | <UL> | |
355 | <LI><A HREF="#Preprocessor_nn2">7.1 File inclusion</A></LI> | |
356 | <LI><A HREF="#Preprocessor_nn3">7.2 File imports</A></LI> | |
357 | <LI><A HREF="#Preprocessor_nn4">7.3 Conditional Compilation</A></LI> | |
358 | <LI><A HREF="#Preprocessor_nn5">7.4 Macro Expansion</A></LI> | |
359 | <LI><A HREF="#Preprocessor_nn6">7.5 SWIG Macros</A></LI> | |
360 | <LI><A HREF="#Preprocessor_nn7">7.6 C99 and GNU Extensions</A></LI> | |
361 | <LI><A HREF="#Preprocessor_nn8">7.7 Preprocessing and %{ ... %} blocks</A> | |
362 | </LI> | |
363 | <LI><A HREF="#Preprocessor_nn9">7.8 Preprocessing and { ... }</A></LI> | |
364 | <LI><A HREF="#Preprocessor_nn10">7.9 Viewing preprocessor output</A></LI> | |
365 | </UL> | |
366 | <B><A HREF="#Library">8 SWIG library</A></B> | |
367 | <UL> | |
368 | <LI><A HREF="#Library_nn2">8.1 The %include directive and library search | |
369 | path</A></LI> | |
370 | <LI><A HREF="#Library_nn3">8.2 C Arrays and Pointers</A> | |
371 | <UL> | |
372 | <LI><A HREF="#Library_nn4">8.2.1 cpointer.i</A></LI> | |
373 | <LI><A HREF="#Library_nn5">8.2.2 carrays.i</A></LI> | |
374 | <LI><A HREF="#Library_nn6">8.2.3 cmalloc.i</A></LI> | |
375 | <LI><A HREF="#Library_nn7">8.2.4 cdata.i</A></LI> | |
376 | </UL> | |
377 | </LI> | |
378 | <LI><A HREF="#Library_nn8">8.3 C String Handling</A> | |
379 | <UL> | |
380 | <LI><A HREF="#Library_nn9">8.3.1 Default string handling</A></LI> | |
381 | <LI><A HREF="#Library_nn10">8.3.2 Passing binary data</A></LI> | |
382 | <LI><A HREF="#Library_nn11">8.3.3 Using %newobject to release memory</A></LI> | |
383 | <LI><A HREF="#Library_nn12">8.3.4 cstring.i</A></LI> | |
384 | </UL> | |
385 | </LI> | |
386 | <LI><A HREF="#Library_stl_cpp_library">8.4 STL/C++ Library</A> | |
387 | <UL> | |
388 | <LI><A HREF="#Library_nn14">8.4.1 std_string.i</A></LI> | |
389 | <LI><A HREF="#Library_nn15">8.4.2 std_vector.i</A></LI> | |
390 | <LI><A HREF="#Library_stl_exceptions">8.4.3 STL exceptions</A></LI> | |
391 | </UL> | |
392 | </LI> | |
393 | <LI><A HREF="#Library_nn16">8.5 Utility Libraries</A> | |
394 | <UL> | |
395 | <LI><A HREF="#Library_nn17">8.5.1 exception.i</A></LI> | |
396 | </UL> | |
397 | </LI> | |
398 | </UL> | |
399 | <B><A HREF="#Arguments">9 Argument Handling</A></B> | |
400 | <UL> | |
401 | <LI><A HREF="#Arguments_nn2">9.1 The typemaps.i library</A> | |
402 | <UL> | |
403 | <LI><A HREF="#Arguments_nn3">9.1.1 Introduction</A></LI> | |
404 | <LI><A HREF="#Arguments_nn4">9.1.2 Input parameters</A></LI> | |
405 | <LI><A HREF="#Arguments_nn5">9.1.3 Output parameters</A></LI> | |
406 | <LI><A HREF="#Arguments_nn6">9.1.4 Input/Output parameters</A></LI> | |
407 | <LI><A HREF="#Arguments_nn7">9.1.5 Using different names</A></LI> | |
408 | </UL> | |
409 | </LI> | |
410 | <LI><A HREF="#Arguments_nn8">9.2 Applying constraints to input values</A> | |
411 | <UL> | |
412 | <LI><A HREF="#Arguments_nn9">9.2.1 Simple constraint example</A></LI> | |
413 | <LI><A HREF="#Arguments_nn10">9.2.2 Constraint methods</A></LI> | |
414 | <LI><A HREF="#Arguments_nn11">9.2.3 Applying constraints to new | |
415 | datatypes</A></LI> | |
416 | </UL> | |
417 | </LI> | |
418 | </UL> | |
419 | <B><A HREF="#Typemaps">10 Typemaps</A></B> | |
420 | <UL> | |
421 | <LI><A HREF="#Typemaps_nn2">10.1 Introduction</A> | |
422 | <UL> | |
423 | <LI><A HREF="#Typemaps_nn3">10.1.1 Type conversion</A></LI> | |
424 | <LI><A HREF="#Typemaps_nn4">10.1.2 Typemaps</A></LI> | |
425 | <LI><A HREF="#Typemaps_nn5">10.1.3 Pattern matching</A></LI> | |
426 | <LI><A HREF="#Typemaps_nn6">10.1.4 Reusing typemaps</A></LI> | |
427 | <LI><A HREF="#Typemaps_nn7">10.1.5 What can be done with typemaps?</A></LI> | |
428 | <LI><A HREF="#Typemaps_nn8">10.1.6 What can't be done with typemaps?</A></LI> | |
429 | <LI><A HREF="#Typemaps_nn9">10.1.7 The rest of this chapter</A></LI> | |
430 | </UL> | |
431 | </LI> | |
432 | <LI><A HREF="#Typemaps_nn10">10.2 Typemap specifications</A> | |
433 | <UL> | |
434 | <LI><A HREF="#Typemaps_nn11">10.2.1 Defining a typemap</A></LI> | |
435 | <LI><A HREF="#Typemaps_nn12">10.2.2 Typemap scope</A></LI> | |
436 | <LI><A HREF="#Typemaps_nn13">10.2.3 Copying a typemap</A></LI> | |
437 | <LI><A HREF="#Typemaps_nn14">10.2.4 Deleting a typemap</A></LI> | |
438 | <LI><A HREF="#Typemaps_nn15">10.2.5 Placement of typemaps</A></LI> | |
439 | </UL> | |
440 | </LI> | |
441 | <LI><A HREF="#Typemaps_nn16">10.3 Pattern matching rules</A> | |
442 | <UL> | |
443 | <LI><A HREF="#Typemaps_nn17">10.3.1 Basic matching rules</A></LI> | |
444 | <LI><A HREF="#Typemaps_nn18">10.3.2 Typedef reductions</A></LI> | |
445 | <LI><A HREF="#Typemaps_nn19">10.3.3 Default typemaps</A></LI> | |
446 | <LI><A HREF="#Typemaps_mixed_default">10.3.4 Mixed default typemaps</A></LI> | |
447 | <LI><A HREF="#Typemaps_nn20">10.3.5 Multi-arguments typemaps</A></LI> | |
448 | </UL> | |
449 | </LI> | |
450 | <LI><A HREF="#Typemaps_nn21">10.4 Code generation rules</A> | |
451 | <UL> | |
452 | <LI><A HREF="#Typemaps_nn22">10.4.1 Scope</A></LI> | |
453 | <LI><A HREF="#Typemaps_nn23">10.4.2 Declaring new local variables</A></LI> | |
454 | <LI><A HREF="#Typemaps_nn24">10.4.3 Special variables</A></LI> | |
455 | </UL> | |
456 | </LI> | |
457 | <LI><A HREF="#Typemaps_nn25">10.5 Common typemap methods</A> | |
458 | <UL> | |
459 | <LI><A HREF="#Typemaps_nn26">10.5.1 "in" typemap</A></LI> | |
460 | <LI><A HREF="#Typemaps_nn27">10.5.2 "typecheck" typemap</A></LI> | |
461 | <LI><A HREF="#Typemaps_nn28">10.5.3 "out" typemap</A></LI> | |
462 | <LI><A HREF="#Typemaps_nn29">10.5.4 "arginit" typemap</A></LI> | |
463 | <LI><A HREF="#Typemaps_nn30">10.5.5 "default" typemap</A></LI> | |
464 | <LI><A HREF="#Typemaps_nn31">10.5.6 "check" typemap</A></LI> | |
465 | <LI><A HREF="#Typemaps_nn32">10.5.7 "argout" typemap</A></LI> | |
466 | <LI><A HREF="#Typemaps_nn33">10.5.8 "freearg" typemap</A></LI> | |
467 | <LI><A HREF="#Typemaps_nn34">10.5.9 "newfree" typemap</A></LI> | |
468 | <LI><A HREF="#Typemaps_nn35">10.5.10 "memberin" typemap</A></LI> | |
469 | <LI><A HREF="#Typemaps_nn36">10.5.11 "varin" typemap</A></LI> | |
470 | <LI><A HREF="#Typemaps_nn37">10.5.12 "varout" typemap</A></LI> | |
471 | <LI><A HREF="#throws_typemap">10.5.13 "throws" typemap</A></LI> | |
472 | </UL> | |
473 | </LI> | |
474 | <LI><A HREF="#Typemaps_nn39">10.6 Some typemap examples</A> | |
475 | <UL> | |
476 | <LI><A HREF="#Typemaps_nn40">10.6.1 Typemaps for arrays</A></LI> | |
477 | <LI><A HREF="#Typemaps_nn41">10.6.2 Implementing constraints with | |
478 | typemaps</A></LI> | |
479 | </UL> | |
480 | </LI> | |
481 | <LI><A HREF="#Typemaps_nn42">10.7 Multi-argument typemaps</A></LI> | |
482 | <LI><A HREF="#runtime_type_checker">10.8 The run-time type checker</A> | |
483 | <UL> | |
484 | <LI><A HREF="#Typemaps_nn45">10.8.1 Implementation</A></LI> | |
485 | <LI><A HREF="#Typemaps_nn46">10.8.2 Usage</A></LI> | |
486 | </UL> | |
487 | </LI> | |
488 | <LI><A HREF="#Typemaps_overloading">10.9 Typemaps and overloading</A></LI> | |
489 | <LI><A HREF="#Typemaps_nn48">10.10 More about %apply and %clear</A></LI> | |
490 | <LI><A HREF="#Typemaps_nn49">10.11 Reducing wrapper code size</A></LI> | |
491 | <LI><A HREF="#Typemaps_nn47">10.12 Passing data between typemaps</A></LI> | |
492 | <LI><A HREF="#Typemaps_nn51">10.13 Where to go for more information?</A></LI> | |
493 | </UL> | |
494 | <B><A HREF="#Customization">11 Customization Features</A></B> | |
495 | <UL> | |
496 | <LI><A HREF="#exception">11.1 Exception handling with %exception</A> | |
497 | <UL> | |
498 | <LI><A HREF="#Customization_nn3">11.1.1 Handling exceptions in C code</A> | |
499 | </LI> | |
500 | <LI><A HREF="#Customization_nn4">11.1.2 Exception handling with | |
501 | longjmp()</A></LI> | |
502 | <LI><A HREF="#Customization_nn5">11.1.3 Handling C++ exceptions</A></LI> | |
503 | <LI><A HREF="#Customization_nn6">11.1.4 Defining different exception | |
504 | handlers</A></LI> | |
505 | <LI><A HREF="#Customization_nn7">11.1.5 Using The SWIG exception library</A> | |
506 | </LI> | |
507 | </UL> | |
508 | </LI> | |
509 | <LI><A HREF="#ownership">11.2 Object ownership and %newobject</A></LI> | |
510 | <LI><A HREF="#features">11.3 Features and the %feature directive</A> | |
511 | <UL> | |
512 | <LI><A HREF="#Customization_feature_flags">11.3.1 Feature flags</A></LI> | |
513 | <LI><A HREF="#Customization_clearing_features">11.3.2 Clearing features</A> | |
514 | </LI> | |
515 | <LI><A HREF="#Customization_features_default_args">11.3.3 Features and | |
516 | default arguments</A></LI> | |
517 | <LI><A HREF="#features_example">11.3.4 Feature example</A></LI> | |
518 | </UL> | |
519 | </LI> | |
520 | </UL> | |
521 | <B><A HREF="#Contract">12 Contracts</A></B> | |
522 | <UL> | |
523 | <LI><A HREF="#Contract_nn2">12.1 The %contract directive</A></LI> | |
524 | <LI><A HREF="#Contract_nn3">12.2 %contract and classes</A></LI> | |
525 | <LI><A HREF="#Contract_nn4">12.3 Constant aggregation and | |
526 | %aggregate_check</A></LI> | |
527 | <LI><A HREF="#Contract_nn5">12.4 Notes</A></LI> | |
528 | </UL> | |
529 | <B><A HREF="#Varargs">13 Variable Length Arguments</A></B> | |
530 | <UL> | |
531 | <LI><A HREF="#Varargs_nn2">13.1 Introduction</A></LI> | |
532 | <LI><A HREF="#Varargs_nn3">13.2 The Problem</A></LI> | |
533 | <LI><A HREF="#Varargs_nn4">13.3 Default varargs support</A></LI> | |
534 | <LI><A HREF="#Varargs_nn5">13.4 Argument replacement using %varargs</A></LI> | |
535 | <LI><A HREF="#Varargs_nn6">13.5 Varargs and typemaps</A></LI> | |
536 | <LI><A HREF="#Varargs_nn7">13.6 Varargs wrapping with libffi</A></LI> | |
537 | <LI><A HREF="#Varargs_nn8">13.7 Wrapping of va_list</A></LI> | |
538 | <LI><A HREF="#Varargs_nn9">13.8 C++ Issues</A></LI> | |
539 | <LI><A HREF="#Varargs_nn10">13.9 Discussion</A></LI> | |
540 | </UL> | |
541 | <B><A HREF="#Warnings">14 Warning Messages</A></B> | |
542 | <UL> | |
543 | <LI><A HREF="#Warnings_nn2">14.1 Introduction</A></LI> | |
544 | <LI><A HREF="#Warnings_nn3">14.2 Warning message suppression</A></LI> | |
545 | <LI><A HREF="#Warnings_nn4">14.3 Enabling additional warnings</A></LI> | |
546 | <LI><A HREF="#Warnings_nn5">14.4 Issuing a warning message</A></LI> | |
547 | <LI><A HREF="#Warnings_nn6">14.5 Commentary</A></LI> | |
548 | <LI><A HREF="#Warnings_nn7">14.6 Warnings as errors</A></LI> | |
549 | <LI><A HREF="#Warnings_nn8">14.7 Message output format</A></LI> | |
550 | <LI><A HREF="#Warnings_nn9">14.8 Warning number reference</A> | |
551 | <UL> | |
552 | <LI><A HREF="#Warnings_nn10">14.8.1 Deprecated features (100-199)</A></LI> | |
553 | <LI><A HREF="#Warnings_nn11">14.8.2 Preprocessor (200-299)</A></LI> | |
554 | <LI><A HREF="#Warnings_nn12">14.8.3 C/C++ Parser (300-399)</A></LI> | |
555 | <LI><A HREF="#Warnings_nn13">14.8.4 Types and typemaps (400-499)</A></LI> | |
556 | <LI><A HREF="#Warnings_nn14">14.8.5 Code generation (500-599)</A></LI> | |
557 | <LI><A HREF="#Warnings_nn15">14.8.6 Language module specific (800-899)</A> | |
558 | </LI> | |
559 | <LI><A HREF="#Warnings_nn16">14.8.7 User defined (900-999)</A></LI> | |
560 | </UL> | |
561 | </LI> | |
562 | <LI><A HREF="#Warnings_nn17">14.9 History</A></LI> | |
563 | </UL> | |
564 | <B><A HREF="#Modules">15 Working with Modules</A></B> | |
565 | <UL> | |
566 | <LI><A HREF="#Modules_nn2">15.1 The SWIG runtime code</A></LI> | |
567 | <LI><A HREF="#external_run_time">15.2 External access to the runtime</A></LI> | |
568 | <LI><A HREF="#Modules_nn4">15.3 A word of caution about static libraries</A> | |
569 | </LI> | |
570 | <LI><A HREF="#Modules_nn5">15.4 References</A></LI> | |
571 | <LI><A HREF="#Modules_nn6">15.5 Reducing the wrapper file size</A></LI> | |
572 | </UL> | |
573 | <B><A HREF="#CSharp">16 SWIG and C#</A></B> | |
574 | <UL> | |
575 | <LI><A HREF="#csharp_introduction">16.1 Introduction</A></LI> | |
576 | <LI><A HREF="#csharp_differences_java">16.2 Differences to the Java | |
577 | module</A></LI> | |
578 | <LI><A HREF="#csharp_exceptions">16.3 C# Exceptions</A> | |
579 | <UL> | |
580 | <LI><A HREF="#csharp_exception_example_check_typemap">16.3.1 C# | |
581 | exception example using "check" typemap</A></LI> | |
582 | <LI><A HREF="#csharp_exception_example_percent_exception">16.3.2 C# | |
583 | exception example using %exception</A></LI> | |
584 | <LI><A HREF="#csharp_exception_example_exception_specifications">16.3.3 | |
585 | C# exception example using exception specifications</A></LI> | |
586 | <LI><A HREF="#csharp_custom_application_exception">16.3.4 Custom C# | |
587 | ApplicationException example</A></LI> | |
588 | </UL> | |
589 | </LI> | |
590 | </UL> | |
591 | <B><A HREF="#Chicken">17 SWIG and Chicken</A></B> | |
592 | <UL> | |
593 | <LI><A HREF="#Chicken_nn2">17.1 Preliminaries</A> | |
594 | <UL> | |
595 | <LI><A HREF="#Chicken_nn3">17.1.1 Running SWIG in C mode</A></LI> | |
596 | <LI><A HREF="#Chicken_nn4">17.1.2 Running SWIG in C++ mode</A></LI> | |
597 | </UL> | |
598 | </LI> | |
599 | <LI><A HREF="#Chicken_nn5">17.2 Code Generation</A> | |
600 | <UL> | |
601 | <LI><A HREF="#Chicken_nn6">17.2.1 Naming Conventions</A></LI> | |
602 | <LI><A HREF="#Chicken_nn7">17.2.2 Modules</A></LI> | |
603 | <LI><A HREF="#Chicken_nn8">17.2.3 Constants and Variables</A></LI> | |
604 | <LI><A HREF="#Chicken_nn9">17.2.4 Functions</A></LI> | |
605 | <LI><A HREF="#Chicken_nn10">17.2.5 Exceptions</A></LI> | |
606 | </UL> | |
607 | </LI> | |
608 | <LI><A HREF="#Chicken_nn11">17.3 TinyCLOS</A></LI> | |
609 | <LI><A HREF="#Chicken_nn12">17.4 Linkage</A> | |
610 | <UL> | |
611 | <LI><A HREF="#Chicken_nn13">17.4.1 Static binary or shared library | |
612 | linked at compile time</A></LI> | |
613 | <LI><A HREF="#Chicken_nn14">17.4.2 Building chicken extension libraries</A> | |
614 | </LI> | |
615 | <LI><A HREF="#Chicken_nn15">17.4.3 Linking multiple SWIG modules with | |
616 | TinyCLOS</A></LI> | |
617 | </UL> | |
618 | </LI> | |
619 | <LI><A HREF="#Chicken_nn16">17.5 Typemaps</A></LI> | |
620 | <LI><A HREF="#Chicken_nn17">17.6 Pointers</A> | |
621 | <UL> | |
622 | <LI><A HREF="#collection">17.6.1 Garbage collection</A></LI> | |
623 | </UL> | |
624 | </LI> | |
625 | <LI><A HREF="#Chicken_nn18">17.7 Unsupported features and known problems</A> | |
626 | </LI> | |
627 | </UL> | |
628 | <B><A HREF="#Guile">18 SWIG and Guile</A></B> | |
629 | <UL> | |
630 | <LI><A HREF="#Guile_nn2">18.1 Meaning of "Module"</A></LI> | |
631 | <LI><A HREF="#Guile_nn3">18.2 Using the SCM or GH Guile API</A></LI> | |
632 | <LI><A HREF="#Guile_nn4">18.3 Linkage</A> | |
633 | <UL> | |
634 | <LI><A HREF="#Guile_nn5">18.3.1 Simple Linkage</A></LI> | |
635 | <LI><A HREF="#Guile_nn6">18.3.2 Passive Linkage</A></LI> | |
636 | <LI><A HREF="#Guile_nn7">18.3.3 Native Guile Module Linkage</A></LI> | |
637 | <LI><A HREF="#Guile_nn8">18.3.4 Old Auto-Loading Guile Module Linkage</A> | |
638 | </LI> | |
639 | <LI><A HREF="#Guile_nn9">18.3.5 Hobbit4D Linkage</A></LI> | |
640 | </UL> | |
641 | </LI> | |
642 | <LI><A HREF="#Guile_nn10">18.4 Underscore Folding</A></LI> | |
643 | <LI><A HREF="#Guile_nn11">18.5 Typemaps</A></LI> | |
644 | <LI><A HREF="#Guile_nn12">18.6 Representation of pointers as smobs</A> | |
645 | <UL> | |
646 | <LI><A HREF="#Guile_nn13">18.6.1 GH Smobs</A></LI> | |
647 | <LI><A HREF="#Guile_nn14">18.6.2 SCM Smobs</A></LI> | |
648 | <LI><A HREF="#Guile_nn15">18.6.3 Garbage Collection</A></LI> | |
649 | </UL> | |
650 | </LI> | |
651 | <LI><A HREF="#Guile_nn16">18.7 Exception Handling</A></LI> | |
652 | <LI><A HREF="#Guile_nn17">18.8 Procedure documentation</A></LI> | |
653 | <LI><A HREF="#Guile_nn18">18.9 Procedures with setters</A></LI> | |
654 | <LI><A HREF="#Guile_nn19">18.10 GOOPS Proxy Classes</A> | |
655 | <UL> | |
656 | <LI><A HREF="#Guile_nn20">18.10.1 Naming Issues</A></LI> | |
657 | <LI><A HREF="#Guile_nn21">18.10.2 Linking</A></LI> | |
658 | </UL> | |
659 | </LI> | |
660 | </UL> | |
661 | <B><A HREF="#Java">19 SWIG and Java</A></B> | |
662 | <UL> | |
663 | <LI><A HREF="#java_overview">19.1 Overview</A></LI> | |
664 | <LI><A HREF="#java_preliminaries">19.2 Preliminaries</A> | |
665 | <UL> | |
666 | <LI><A HREF="#running_swig">19.2.1 Running SWIG</A></LI> | |
667 | <LI><A HREF="#java_commandline">19.2.2 Additional Commandline Options</A> | |
668 | </LI> | |
669 | <LI><A HREF="#getting_right_headers">19.2.3 Getting the right header | |
670 | files</A></LI> | |
671 | <LI><A HREF="#compiling_dynamic">19.2.4 Compiling a dynamic module</A></LI> | |
672 | <LI><A HREF="#using_module">19.2.5 Using your module</A></LI> | |
673 | <LI><A HREF="#dynamic_linking_problems">19.2.6 Dynamic linking problems</A> | |
674 | </LI> | |
675 | <LI><A HREF="#compilation_problems_cpp">19.2.7 Compilation problems and | |
676 | compiling with C++</A></LI> | |
677 | <LI><A HREF="#building_windows">19.2.8 Building on Windows</A> | |
678 | <UL> | |
679 | <LI><A HREF="#visual_studio">19.2.8.1 Running SWIG from Visual Studio</A> | |
680 | </LI> | |
681 | <LI><A HREF="#nmake">19.2.8.2 Using NMAKE</A></LI> | |
682 | </UL> | |
683 | </LI> | |
684 | </UL> | |
685 | </LI> | |
686 | <LI><A HREF="#java_basic_tour">19.3 A tour of basic C/C++ wrapping</A> | |
687 | <UL> | |
688 | <LI><A HREF="#module_packages_classes">19.3.1 Modules, packages and | |
689 | generated Java classes</A></LI> | |
690 | <LI><A HREF="#functions">19.3.2 Functions</A></LI> | |
691 | <LI><A HREF="#global_variables">19.3.3 Global variables</A></LI> | |
692 | <LI><A HREF="#constants">19.3.4 Constants</A></LI> | |
693 | <LI><A HREF="#enumerations">19.3.5 Enumerations</A> | |
694 | <UL> | |
695 | <LI><A HREF="#anonymous_enums">19.3.5.1 Anonymous enums</A></LI> | |
696 | <LI><A HREF="#typesafe_enums">19.3.5.2 Typesafe enums</A></LI> | |
697 | <LI><A HREF="#proper_enums">19.3.5.3 Proper Java enums</A></LI> | |
698 | <LI><A HREF="#typeunsafe_enums">19.3.5.4 Type unsafe enums</A></LI> | |
699 | <LI><A HREF="#simple_enums">19.3.5.5 Simple enums</A></LI> | |
700 | </UL> | |
701 | </LI> | |
702 | <LI><A HREF="#pointers">19.3.6 Pointers</A></LI> | |
703 | <LI><A HREF="#structures">19.3.7 Structures</A></LI> | |
704 | <LI><A HREF="#classes">19.3.8 C++ classes</A></LI> | |
705 | <LI><A HREF="#inheritance">19.3.9 C++ inheritance</A></LI> | |
706 | <LI><A HREF="#pointers_refs_arrays">19.3.10 Pointers, references, arrays | |
707 | and pass by value</A> | |
708 | <UL> | |
709 | <LI><A HREF="#null_pointers">19.3.10.1 Null pointers</A></LI> | |
710 | </UL> | |
711 | </LI> | |
712 | <LI><A HREF="#overloaded_functions">19.3.11 C++ overloaded functions</A></LI> | |
713 | <LI><A HREF="#java_default_arguments">19.3.12 C++ default arguments</A></LI> | |
714 | <LI><A HREF="#namespaces">19.3.13 C++ namespaces</A></LI> | |
715 | <LI><A HREF="#templates">19.3.14 C++ templates</A></LI> | |
716 | <LI><A HREF="#smart_pointers">19.3.15 C++ Smart Pointers</A></LI> | |
717 | </UL> | |
718 | </LI> | |
719 | <LI><A HREF="#further_details">19.4 Further details on the generated | |
720 | Java classes</A> | |
721 | <UL> | |
722 | <LI><A HREF="#imclass">19.4.1 The intermediary JNI class</A> | |
723 | <UL> | |
724 | <LI><A HREF="#imclass_pragmas">19.4.1.1 The intermediary JNI class | |
725 | pragmas</A></LI> | |
726 | </UL> | |
727 | </LI> | |
728 | <LI><A HREF="#java_module_class">19.4.2 The Java module class</A> | |
729 | <UL> | |
730 | <LI><A HREF="#module_class_pragmas">19.4.2.1 The Java module class | |
731 | pragmas</A></LI> | |
732 | </UL> | |
733 | </LI> | |
734 | <LI><A HREF="#java_proxy_classes">19.4.3 Java proxy classes</A> | |
735 | <UL> | |
736 | <LI><A HREF="#memory_management">19.4.3.1 Memory management</A></LI> | |
737 | <LI><A HREF="#inheritance_mirroring">19.4.3.2 Inheritance</A></LI> | |
738 | <LI><A HREF="#proxy_classes_gc">19.4.3.3 Proxy classes and garbage | |
739 | collection</A></LI> | |
740 | </UL> | |
741 | </LI> | |
742 | <LI><A HREF="#type_wrapper_classes">19.4.4 Type wrapper classes</A></LI> | |
743 | <LI><A HREF="#enum_classes">19.4.5 Enum classes</A> | |
744 | <UL> | |
745 | <LI><A HREF="#typesafe_enums_classes">19.4.5.1 Typesafe enum classes</A></LI> | |
746 | <LI><A HREF="#proper_enums_classes">19.4.5.2 Proper Java enum classes</A> | |
747 | </LI> | |
748 | <LI><A HREF="#typeunsafe_enums_classes">19.4.5.3 Type unsafe enum | |
749 | classes</A></LI> | |
750 | </UL> | |
751 | </LI> | |
752 | </UL> | |
753 | </LI> | |
754 | <LI><A HREF="#java_directors">19.5 Cross language polymorphism using | |
755 | directors (experimental)</A> | |
756 | <UL> | |
757 | <LI><A HREF="#java_enabling_directors">19.5.1 Enabling directors</A></LI> | |
758 | <LI><A HREF="#java_directors_classes">19.5.2 Director classes</A></LI> | |
759 | <LI><A HREF="#java_directors_overhead">19.5.3 Overhead and code bloat</A> | |
760 | </LI> | |
761 | <LI><A HREF="#java_directors_example">19.5.4 Simple directors example</A> | |
762 | </LI> | |
763 | </UL> | |
764 | </LI> | |
765 | <LI><A HREF="#common_customization">19.6 Common customization features</A> | |
766 | <UL> | |
767 | <LI><A HREF="#helper_functions">19.6.1 C/C++ helper functions</A></LI> | |
768 | <LI><A HREF="#class_extension">19.6.2 Class extension with %extend</A></LI> | |
769 | <LI><A HREF="#exception_handling">19.6.3 Exception handling with | |
770 | %exception and %javaexception</A></LI> | |
771 | <LI><A HREF="#method_access">19.6.4 Method access with | |
772 | %javamethodmodifiers</A></LI> | |
773 | </UL> | |
774 | </LI> | |
775 | <LI><A HREF="#tips_techniques">19.7 Tips and techniques</A> | |
776 | <UL> | |
777 | <LI><A HREF="#input_output_parameters">19.7.1 Input and output | |
778 | parameters using primitive pointers and references</A></LI> | |
779 | <LI><A HREF="#simple_pointers">19.7.2 Simple pointers</A></LI> | |
780 | <LI><A HREF="#c_arrays">19.7.3 Wrapping C arrays with Java arrays</A></LI> | |
781 | <LI><A HREF="#unbounded_c_arrays">19.7.4 Unbounded C Arrays</A></LI> | |
782 | </UL> | |
783 | </LI> | |
784 | <LI><A HREF="#java_typemaps">19.8 Java typemaps</A> | |
785 | <UL> | |
786 | <LI><A HREF="#default_primitive_type_mappings">19.8.1 Default primitive | |
787 | type mappings</A></LI> | |
788 | <LI><A HREF="#jvm64">19.8.2 Sixty four bit JVMs</A></LI> | |
789 | <LI><A HREF="#what_is_typemap">19.8.3 What is a typemap?</A></LI> | |
790 | <LI><A HREF="#typemaps_c_to_java_types">19.8.4 Typemaps for mapping | |
791 | C/C++ types to Java types</A></LI> | |
792 | <LI><A HREF="#typemap_attributes">19.8.5 Java typemap attributes</A></LI> | |
793 | <LI><A HREF="#special_variables">19.8.6 Java special variables</A></LI> | |
794 | <LI><A HREF="#typemaps_for_c_and_c++">19.8.7 Typemaps for both C and C++ | |
795 | compilation</A></LI> | |
796 | <LI><A HREF="#java_code_typemaps">19.8.8 Java code typemaps</A></LI> | |
797 | <LI><A HREF="#java_directors_typemaps">19.8.9 Director specific typemaps</A> | |
798 | </LI> | |
799 | </UL> | |
800 | </LI> | |
801 | <LI><A HREF="#typemap_examples">19.9 Typemap Examples</A> | |
802 | <UL> | |
803 | <LI><A HREF="#simpler_enum_classes">19.9.1 Simpler Java enums for enums | |
804 | without initializers</A></LI> | |
805 | <LI><A HREF="#exception_typemap">19.9.2 Handling C++ exception | |
806 | specifications as Java exceptions</A></LI> | |
807 | <LI><A HREF="#nan_exception_typemap">19.9.3 NaN Exception - exception | |
808 | handling for a particular type</A></LI> | |
809 | <LI><A HREF="#converting_java_string_arrays">19.9.4 Converting Java | |
810 | String arrays to char **</A></LI> | |
811 | <LI><A HREF="#expanding_java_object">19.9.5 Expanding a Java object to | |
812 | multiple arguments</A></LI> | |
813 | <LI><A HREF="#using_typemaps_return_arguments">19.9.6 Using typemaps to | |
814 | return arguments</A></LI> | |
815 | <LI><A HREF="#adding_downcasts">19.9.7 Adding Java downcasts to | |
816 | polymorphic return types</A></LI> | |
817 | <LI><A HREF="#adding_equals_method">19.9.8 Adding an equals method to | |
818 | the Java classes</A></LI> | |
819 | <LI><A HREF="#void_pointers">19.9.9 Void pointers and a common Java base | |
820 | class</A></LI> | |
821 | <LI><A HREF="#struct_pointer_pointer">19.9.10 Struct pointer to pointer</A> | |
822 | </LI> | |
823 | </UL> | |
824 | </LI> | |
825 | <LI><A HREF="#java_directors_faq">19.10 Living with Java Directors</A></LI> | |
826 | <LI><A HREF="#odds_ends">19.11 Odds and ends</A> | |
827 | <UL> | |
828 | <LI><A HREF="#javadoc_comments">19.11.1 JavaDoc comments</A></LI> | |
829 | <LI><A HREF="#functional_interface">19.11.2 Functional interface without | |
830 | proxy classes</A></LI> | |
831 | <LI><A HREF="#using_own_jni_functions">19.11.3 Using your own JNI | |
832 | functions</A></LI> | |
833 | <LI><A HREF="#performance">19.11.4 Performance concerns and hints</A></LI> | |
834 | </UL> | |
835 | </LI> | |
836 | <LI><A HREF="#java_examples">19.12 Examples</A></LI> | |
837 | </UL> | |
838 | <B><A HREF="#Modula3">20 SWIG and Modula-3</A></B> | |
839 | <UL> | |
840 | <LI><A HREF="#modula3_overview">20.1 Overview</A> | |
841 | <UL> | |
842 | <LI><A HREF="#whyscripting">20.1.1 Why not scripting ?</A></LI> | |
843 | <LI><A HREF="#whymodula3">20.1.2 Why Modula-3 ?</A></LI> | |
844 | <LI><A HREF="#whycpp">20.1.3 Why C / C++ ?</A></LI> | |
845 | <LI><A HREF="#whyswig">20.1.4 Why SWIG ?</A></LI> | |
846 | </UL> | |
847 | </LI> | |
848 | <LI><A HREF="#conception">20.2 Conception</A> | |
849 | <UL> | |
850 | <LI><A HREF="#cinterface">20.2.1 Interfaces to C libraries</A></LI> | |
851 | <LI><A HREF="#cppinterface">20.2.2 Interfaces to C++ libraries</A></LI> | |
852 | </UL> | |
853 | </LI> | |
854 | <LI><A HREF="#preliminaries">20.3 Preliminaries</A> | |
855 | <UL> | |
856 | <LI><A HREF="#compilers">20.3.1 Compilers</A></LI> | |
857 | <LI><A HREF="#commandline">20.3.2 Additional Commandline Options</A></LI> | |
858 | </UL> | |
859 | </LI> | |
860 | <LI><A HREF="#modula3_typemaps">20.4 Modula-3 typemaps</A> | |
861 | <UL> | |
862 | <LI><A HREF="#inoutparam">20.4.1 Inputs and outputs</A></LI> | |
863 | <LI><A HREF="#ordinals">20.4.2 Subranges, Enumerations, Sets</A></LI> | |
864 | <LI><A HREF="#class">20.4.3 Objects</A></LI> | |
865 | <LI><A HREF="#imports">20.4.4 Imports</A></LI> | |
866 | <LI><A HREF="#exceptions">20.4.5 Exceptions</A></LI> | |
867 | <LI><A HREF="#typemap_example">20.4.6 Example</A></LI> | |
868 | </UL> | |
869 | </LI> | |
870 | <LI><A HREF="#hints">20.5 More hints to the generator</A> | |
871 | <UL> | |
872 | <LI><A HREF="#features">20.5.1 Features</A></LI> | |
873 | <LI><A HREF="#pragmas">20.5.2 Pragmas</A></LI> | |
874 | </UL> | |
875 | </LI> | |
876 | <LI><A HREF="#remarks">20.6 Remarks</A></LI> | |
877 | </UL> | |
878 | <B><A HREF="#MzScheme">21 SWIG and MzScheme</A></B> | |
879 | <UL> | |
880 | <LI><A HREF="#MzScheme_nn2">21.1 Creating native MzScheme structures</A></LI> | |
881 | </UL> | |
882 | <B><A HREF="#Ocaml">22 SWIG and Ocaml</A></B> | |
883 | <UL> | |
884 | <LI><A HREF="#Ocaml_nn2">22.1 Preliminaries</A> | |
885 | <UL> | |
886 | <LI><A HREF="#Ocaml_nn3">22.1.1 Running SWIG</A></LI> | |
887 | <LI><A HREF="#Ocaml_nn4">22.1.2 Compiling the code</A></LI> | |
888 | <LI><A HREF="#Ocaml_nn5">22.1.3 The camlp4 module</A></LI> | |
889 | <LI><A HREF="#Ocaml_nn6">22.1.4 Using your module</A></LI> | |
890 | <LI><A HREF="#Ocaml_nn7">22.1.5 Compilation problems and compiling with | |
891 | C++</A></LI> | |
892 | </UL> | |
893 | </LI> | |
894 | <LI><A HREF="#Ocaml_nn8">22.2 The low-level Ocaml/C interface</A> | |
895 | <UL> | |
896 | <LI><A HREF="#Ocaml_nn9">22.2.1 The generated module</A></LI> | |
897 | <LI><A HREF="#Ocaml_nn10">22.2.2 Enums</A> | |
898 | <UL> | |
899 | <LI><A HREF="#Ocaml_nn11">22.2.2.1 Enum typing in Ocaml</A></LI> | |
900 | </UL> | |
901 | </LI> | |
902 | <LI><A HREF="#Ocaml_nn12">22.2.3 Arrays</A> | |
903 | <UL> | |
904 | <LI><A HREF="#Ocaml_nn13">22.2.3.1 Simple types of bounded arrays</A></LI> | |
905 | <LI><A HREF="#Ocaml_nn14">22.2.3.2 Complex and unbounded arrays</A></LI> | |
906 | <LI><A HREF="#Ocaml_nn15">22.2.3.3 Using an object</A></LI> | |
907 | <LI><A HREF="#Ocaml_nn16">22.2.3.4 Example typemap for a function taking | |
908 | float * and int</A></LI> | |
909 | </UL> | |
910 | </LI> | |
911 | <LI><A HREF="#Ocaml_nn17">22.2.4 C++ Classes</A> | |
912 | <UL> | |
913 | <LI><A HREF="#Ocaml_nn18">22.2.4.1 STL vector and string Example</A></LI> | |
914 | <LI><A HREF="#Ocaml_nn19">22.2.4.2 C++ Class Example</A></LI> | |
915 | <LI><A HREF="#Ocaml_nn20">22.2.4.3 Compiling the example</A></LI> | |
916 | <LI><A HREF="#Ocaml_nn21">22.2.4.4 Sample Session</A></LI> | |
917 | </UL> | |
918 | </LI> | |
919 | <LI><A HREF="#Ocaml_nn22">22.2.5 Director Classes</A> | |
920 | <UL> | |
921 | <LI><A HREF="#Ocaml_nn23">22.2.5.1 Director Introduction</A></LI> | |
922 | <LI><A HREF="#Ocaml_nn24">22.2.5.2 Overriding Methods in Ocaml</A></LI> | |
923 | <LI><A HREF="#Ocaml_nn25">22.2.5.3 Director Usage Example</A></LI> | |
924 | <LI><A HREF="#Ocaml_nn26">22.2.5.4 Creating director objects</A></LI> | |
925 | <LI><A HREF="#Ocaml_nn27">22.2.5.5 Typemaps for directors, directorin, | |
926 | directorout, directorargout</A></LI> | |
927 | <LI><A HREF="#Ocaml_nn28">22.2.5.6 directorin typemap</A></LI> | |
928 | <LI><A HREF="#Ocaml_nn29">22.2.5.7 directorout typemap</A></LI> | |
929 | <LI><A HREF="#Ocaml_nn30">22.2.5.8 directorargout typemap</A></LI> | |
930 | </UL> | |
931 | </LI> | |
932 | <LI><A HREF="#Ocaml_nn31">22.2.6 Exceptions</A></LI> | |
933 | </UL> | |
934 | </LI> | |
935 | </UL> | |
936 | <B><A HREF="#Perl5">23 SWIG and Perl5</A></B> | |
937 | <UL> | |
938 | <LI><A HREF="#Perl5_nn2">23.1 Overview</A></LI> | |
939 | <LI><A HREF="#Perl5_nn3">23.2 Preliminaries</A> | |
940 | <UL> | |
941 | <LI><A HREF="#Perl5_nn4">23.2.1 Getting the right header files</A></LI> | |
942 | <LI><A HREF="#Perl5_nn5">23.2.2 Compiling a dynamic module</A></LI> | |
943 | <LI><A HREF="#Perl5_nn6">23.2.3 Building a dynamic module with MakeMaker</A> | |
944 | </LI> | |
945 | <LI><A HREF="#Perl5_nn7">23.2.4 Building a static version of Perl</A></LI> | |
946 | <LI><A HREF="#Perl5_nn8">23.2.5 Using the module</A></LI> | |
947 | <LI><A HREF="#Perl5_nn9">23.2.6 Compilation problems and compiling with | |
948 | C++</A></LI> | |
949 | <LI><A HREF="#Perl5_nn10">23.2.7 Compiling for 64-bit platforms</A></LI> | |
950 | </UL> | |
951 | </LI> | |
952 | <LI><A HREF="#Perl5_nn11">23.3 Building Perl Extensions under Windows</A> | |
953 | <UL> | |
954 | <LI><A HREF="#Perl5_nn12">23.3.1 Running SWIG from Developer Studio</A></LI> | |
955 | <LI><A HREF="#Perl5_nn13">23.3.2 Using other compilers</A></LI> | |
956 | </UL> | |
957 | </LI> | |
958 | <LI><A HREF="#Perl5_nn14">23.4 The low-level interface</A> | |
959 | <UL> | |
960 | <LI><A HREF="#Perl5_nn15">23.4.1 Functions</A></LI> | |
961 | <LI><A HREF="#Perl5_nn16">23.4.2 Global variables</A></LI> | |
962 | <LI><A HREF="#Perl5_nn17">23.4.3 Constants</A></LI> | |
963 | <LI><A HREF="#Perl5_nn18">23.4.4 Pointers</A></LI> | |
964 | <LI><A HREF="#Perl5_nn19">23.4.5 Structures</A></LI> | |
965 | <LI><A HREF="#Perl5_nn20">23.4.6 C++ classes</A></LI> | |
966 | <LI><A HREF="#Perl5_nn21">23.4.7 C++ classes and type-checking</A></LI> | |
967 | <LI><A HREF="#Perl5_nn22">23.4.8 C++ overloaded functions</A></LI> | |
968 | <LI><A HREF="#Perl5_nn23">23.4.9 Operators</A></LI> | |
969 | <LI><A HREF="#Perl5_nn24">23.4.10 Modules and packages</A></LI> | |
970 | </UL> | |
971 | </LI> | |
972 | <LI><A HREF="#Perl5_nn25">23.5 Input and output parameters</A></LI> | |
973 | <LI><A HREF="#Perl5_nn26">23.6 Exception handling</A></LI> | |
974 | <LI><A HREF="#Perl5_nn27">23.7 Remapping datatypes with typemaps</A> | |
975 | <UL> | |
976 | <LI><A HREF="#Perl5_nn28">23.7.1 A simple typemap example</A></LI> | |
977 | <LI><A HREF="#Perl5_nn29">23.7.2 Perl5 typemaps</A></LI> | |
978 | <LI><A HREF="#Perl5_nn30">23.7.3 Typemap variables</A></LI> | |
979 | <LI><A HREF="#Perl5_nn31">23.7.4 Useful functions</A></LI> | |
980 | </UL> | |
981 | </LI> | |
982 | <LI><A HREF="#Perl5_nn32">23.8 Typemap Examples</A> | |
983 | <UL> | |
984 | <LI><A HREF="#Perl5_nn33">23.8.1 Converting a Perl5 array to a char **</A> | |
985 | </LI> | |
986 | <LI><A HREF="#Perl5_nn34">23.8.2 Return values</A></LI> | |
987 | <LI><A HREF="#Perl5_nn35">23.8.3 Returning values from arguments</A></LI> | |
988 | <LI><A HREF="#Perl5_nn36">23.8.4 Accessing array structure members</A></LI> | |
989 | <LI><A HREF="#Perl5_nn37">23.8.5 Turning Perl references into C pointers</A> | |
990 | </LI> | |
991 | <LI><A HREF="#Perl5_nn38">23.8.6 Pointer handling</A></LI> | |
992 | </UL> | |
993 | </LI> | |
994 | <LI><A HREF="#Perl5_nn39">23.9 Proxy classes</A> | |
995 | <UL> | |
996 | <LI><A HREF="#Perl5_nn40">23.9.1 Preliminaries</A></LI> | |
997 | <LI><A HREF="#Perl5_nn41">23.9.2 Structure and class wrappers</A></LI> | |
998 | <LI><A HREF="#Perl5_nn42">23.9.3 Object Ownership</A></LI> | |
999 | <LI><A HREF="#Perl5_nn43">23.9.4 Nested Objects</A></LI> | |
1000 | <LI><A HREF="#Perl5_nn44">23.9.5 Proxy Functions</A></LI> | |
1001 | <LI><A HREF="#Perl5_nn45">23.9.6 Inheritance</A></LI> | |
1002 | <LI><A HREF="#Perl5_nn46">23.9.7 Modifying the proxy methods</A></LI> | |
1003 | </UL> | |
1004 | </LI> | |
1005 | </UL> | |
1006 | <B><A HREF="#Php">24 SWIG and PHP4</A></B> | |
1007 | <UL> | |
1008 | <LI><A HREF="#Php_nn1">24.1 Generating PHP4 Extensions</A> | |
1009 | <UL> | |
1010 | <LI><A HREF="#Php_nn1_1">24.1.1 Building a loadable extension</A></LI> | |
1011 | <LI><A HREF="#Php_nn1_2">24.1.2 Building extensions into PHP</A></LI> | |
1012 | <LI><A HREF="#Php_nn1_3">24.1.3 Using PHP4 Extensions</A></LI> | |
1013 | </UL> | |
1014 | </LI> | |
1015 | <LI><A HREF="#Php_nn2">24.2 Basic PHP4 interface</A> | |
1016 | <UL> | |
1017 | <LI><A HREF="#Php_nn2_1">24.2.1 Constants</A></LI> | |
1018 | <LI><A HREF="#Php_nn2_2">24.2.2 Global Variables</A></LI> | |
1019 | <LI><A HREF="#Php_nn2_3">24.2.3 Functions</A></LI> | |
1020 | <LI><A HREF="#Php_nn2_4">24.2.4 Overloading</A></LI> | |
1021 | <LI><A HREF="#Php_nn2_5">24.2.5 Pointers and References</A></LI> | |
1022 | <LI><A HREF="#Php_nn2_6">24.2.6 Structures and C++ classes</A> | |
1023 | <UL> | |
1024 | <LI><A HREF="#Php_nn2_6_1">24.2.6.1 Using -noproxy</A></LI> | |
1025 | <LI><A HREF="#Php_nn2_6_2">24.2.6.2 Constructors and Destructors</A></LI> | |
1026 | <LI><A HREF="#Php_nn2_6_3">24.2.6.3 Static Member Variables</A></LI> | |
1027 | <LI><A HREF="#Php_nn2_6_4">24.2.6.4 Static Member Functions</A></LI> | |
1028 | </UL> | |
1029 | </LI> | |
1030 | <LI><A HREF="#Php_nn2_7">24.2.7 PHP4 Pragmas, Startup and Shutdown code</A> | |
1031 | </LI> | |
1032 | </UL> | |
1033 | </LI> | |
1034 | </UL> | |
1035 | <B><A HREF="#Pike">25 SWIG and Pike</A></B> | |
1036 | <UL> | |
1037 | <LI><A HREF="#Pike_nn2">25.1 Preliminaries</A> | |
1038 | <UL> | |
1039 | <LI><A HREF="#Pike_nn3">25.1.1 Running SWIG</A></LI> | |
1040 | <LI><A HREF="#Pike_nn4">25.1.2 Getting the right header files</A></LI> | |
1041 | <LI><A HREF="#Pike_nn5">25.1.3 Using your module</A></LI> | |
1042 | </UL> | |
1043 | </LI> | |
1044 | <LI><A HREF="#Pike_nn6">25.2 Basic C/C++ Mapping</A> | |
1045 | <UL> | |
1046 | <LI><A HREF="#Pike_nn7">25.2.1 Modules</A></LI> | |
1047 | <LI><A HREF="#Pike_nn8">25.2.2 Functions</A></LI> | |
1048 | <LI><A HREF="#Pike_nn9">25.2.3 Global variables</A></LI> | |
1049 | <LI><A HREF="#Pike_nn10">25.2.4 Constants and enumerated types</A></LI> | |
1050 | <LI><A HREF="#Pike_nn11">25.2.5 Constructors and Destructors</A></LI> | |
1051 | <LI><A HREF="#Pike_nn12">25.2.6 Static Members</A></LI> | |
1052 | </UL> | |
1053 | </LI> | |
1054 | </UL> | |
1055 | <B><A HREF="#Python">26 SWIG and Python</A></B> | |
1056 | <UL> | |
1057 | <LI><A HREF="#Python_nn2">26.1 Overview</A></LI> | |
1058 | <LI><A HREF="#Python_nn3">26.2 Preliminaries</A> | |
1059 | <UL> | |
1060 | <LI><A HREF="#Python_nn4">26.2.1 Running SWIG</A></LI> | |
1061 | <LI><A HREF="#Python_nn5">26.2.2 Getting the right header files</A></LI> | |
1062 | <LI><A HREF="#Python_nn6">26.2.3 Compiling a dynamic module</A></LI> | |
1063 | <LI><A HREF="#Python_nn7">26.2.4 Using distutils</A></LI> | |
1064 | <LI><A HREF="#Python_nn8">26.2.5 Static linking</A></LI> | |
1065 | <LI><A HREF="#Python_nn9">26.2.6 Using your module</A></LI> | |
1066 | <LI><A HREF="#Python_nn10">26.2.7 Compilation of C++ extensions</A></LI> | |
1067 | <LI><A HREF="#Python_nn11">26.2.8 Compiling for 64-bit platforms</A></LI> | |
1068 | <LI><A HREF="#Python_nn12">26.2.9 Building Python Extensions under | |
1069 | Windows</A></LI> | |
1070 | </UL> | |
1071 | </LI> | |
1072 | <LI><A HREF="#Python_nn13">26.3 A tour of basic C/C++ wrapping</A> | |
1073 | <UL> | |
1074 | <LI><A HREF="#Python_nn14">26.3.1 Modules</A></LI> | |
1075 | <LI><A HREF="#Python_nn15">26.3.2 Functions</A></LI> | |
1076 | <LI><A HREF="#Python_nn16">26.3.3 Global variables</A></LI> | |
1077 | <LI><A HREF="#Python_nn17">26.3.4 Constants and enums</A></LI> | |
1078 | <LI><A HREF="#Python_nn18">26.3.5 Pointers</A></LI> | |
1079 | <LI><A HREF="#Python_nn19">26.3.6 Structures</A></LI> | |
1080 | <LI><A HREF="#Python_nn20">26.3.7 C++ classes</A></LI> | |
1081 | <LI><A HREF="#Python_nn21">26.3.8 C++ inheritance</A></LI> | |
1082 | <LI><A HREF="#Python_nn22">26.3.9 Pointers, references, values, and | |
1083 | arrays</A></LI> | |
1084 | <LI><A HREF="#Python_nn23">26.3.10 C++ overloaded functions</A></LI> | |
1085 | <LI><A HREF="#Python_nn24">26.3.11 C++ operators</A></LI> | |
1086 | <LI><A HREF="#Python_nn25">26.3.12 C++ namespaces</A></LI> | |
1087 | <LI><A HREF="#Python_nn26">26.3.13 C++ templates</A></LI> | |
1088 | <LI><A HREF="#Python_nn27">26.3.14 C++ Smart Pointers</A></LI> | |
1089 | <LI><A HREF="#Python_nn27a">26.3.15 C++ Reference Counted Objects | |
1090 | (ref/unref)</A></LI> | |
1091 | </UL> | |
1092 | </LI> | |
1093 | <LI><A HREF="#Python_nn28">26.4 Further details on the Python class | |
1094 | interface</A> | |
1095 | <UL> | |
1096 | <LI><A HREF="#Python_nn29">26.4.1 Proxy classes</A></LI> | |
1097 | <LI><A HREF="#Python_nn30">26.4.2 Memory management</A></LI> | |
1098 | <LI><A HREF="#Python_nn31">26.4.3 Python 2.2 and classic classes</A></LI> | |
1099 | </UL> | |
1100 | </LI> | |
1101 | <LI><A HREF="#directors">26.5 Cross language polymorphism</A> | |
1102 | <UL> | |
1103 | <LI><A HREF="#Python_nn33">26.5.1 Enabling directors</A></LI> | |
1104 | <LI><A HREF="#Python_nn34">26.5.2 Director classes</A></LI> | |
1105 | <LI><A HREF="#Python_nn35">26.5.3 Ownership and object destruction</A></LI> | |
1106 | <LI><A HREF="#Python_nn36">26.5.4 Exception unrolling</A></LI> | |
1107 | <LI><A HREF="#Python_nn37">26.5.5 Overhead and code bloat</A></LI> | |
1108 | <LI><A HREF="#Python_nn38">26.5.6 Typemaps</A></LI> | |
1109 | <LI><A HREF="#Python_nn39">26.5.7 Miscellaneous</A></LI> | |
1110 | </UL> | |
1111 | </LI> | |
1112 | <LI><A HREF="#Python_nn40">26.6 Common customization features</A> | |
1113 | <UL> | |
1114 | <LI><A HREF="#Python_nn41">26.6.1 C/C++ helper functions</A></LI> | |
1115 | <LI><A HREF="#Python_nn42">26.6.2 Adding additional Python code</A></LI> | |
1116 | <LI><A HREF="#Python_nn43">26.6.3 Class extension with %extend</A></LI> | |
1117 | <LI><A HREF="#Python_nn44">26.6.4 Exception handling with %exception</A></LI> | |
1118 | </UL> | |
1119 | </LI> | |
1120 | <LI><A HREF="#Python_nn45">26.7 Tips and techniques</A> | |
1121 | <UL> | |
1122 | <LI><A HREF="#Python_nn46">26.7.1 Input and output parameters</A></LI> | |
1123 | <LI><A HREF="#Python_nn47">26.7.2 Simple pointers</A></LI> | |
1124 | <LI><A HREF="#Python_nn48">26.7.3 Unbounded C Arrays</A></LI> | |
1125 | <LI><A HREF="#Python_nn49">26.7.4 String handling</A></LI> | |
1126 | <LI><A HREF="#Python_nn50">26.7.5 Arrays</A></LI> | |
1127 | <LI><A HREF="#Python_nn51">26.7.6 String arrays</A></LI> | |
1128 | <LI><A HREF="#Python_nn52">26.7.7 STL wrappers</A></LI> | |
1129 | </UL> | |
1130 | </LI> | |
1131 | <LI><A HREF="#Python_nn53">26.8 Typemaps</A> | |
1132 | <UL> | |
1133 | <LI><A HREF="#Python_nn54">26.8.1 What is a typemap?</A></LI> | |
1134 | <LI><A HREF="#Python_nn55">26.8.2 Python typemaps</A></LI> | |
1135 | <LI><A HREF="#Python_nn56">26.8.3 Typemap variables</A></LI> | |
1136 | <LI><A HREF="#Python_nn57">26.8.4 Useful Python Functions</A></LI> | |
1137 | </UL> | |
1138 | </LI> | |
1139 | <LI><A HREF="#Python_nn58">26.9 Typemap Examples</A> | |
1140 | <UL> | |
1141 | <LI><A HREF="#Python_nn59">26.9.1 Converting Python list to a char **</A> | |
1142 | </LI> | |
1143 | <LI><A HREF="#Python_nn60">26.9.2 Expanding a Python object into | |
1144 | multiple arguments</A></LI> | |
1145 | <LI><A HREF="#Python_nn61">26.9.3 Using typemaps to return arguments</A></LI> | |
1146 | <LI><A HREF="#Python_nn62">26.9.4 Mapping Python tuples into small | |
1147 | arrays</A></LI> | |
1148 | <LI><A HREF="#Python_nn63">26.9.5 Mapping sequences to C arrays</A></LI> | |
1149 | <LI><A HREF="#Python_nn64">26.9.6 Pointer handling</A></LI> | |
1150 | </UL> | |
1151 | </LI> | |
1152 | <LI><A HREF="#Python_nn65">26.10 Docstring Features</A> | |
1153 | <UL> | |
1154 | <LI><A HREF="#Python_nn66">26.10.1 Module docstring</A></LI> | |
1155 | <LI><A HREF="#Python_nn67">26.10.2 %feature("autodoc")</A> | |
1156 | <UL> | |
1157 | <LI><A HREF="#Python_nn68">26.10.2.1 %feature("autodoc", "0")</A></LI> | |
1158 | <LI><A HREF="#Python_nn69">26.10.2.2 %feature("autodoc", "1")</A></LI> | |
1159 | <LI><A HREF="#Python_nn70">26.10.2.3 %feature("autodoc", "docstring")</A> | |
1160 | </LI> | |
1161 | </UL> | |
1162 | </LI> | |
1163 | <LI><A HREF="#Python_nn71">26.10.3 %feature("docstring")</A></LI> | |
1164 | </UL> | |
1165 | </LI> | |
1166 | <LI><A HREF="#Python_nn72">26.11 Python Packages</A></LI> | |
1167 | </UL> | |
1168 | <B><A HREF="#Ruby">27 SWIG and Ruby</A></B> | |
1169 | <UL> | |
1170 | <LI><A HREF="#Ruby_nn2">27.1 Preliminaries</A> | |
1171 | <UL> | |
1172 | <LI><A HREF="#Ruby_nn3">27.1.1 Running SWIG</A></LI> | |
1173 | <LI><A HREF="#Ruby_nn4">27.1.2 Getting the right header files</A></LI> | |
1174 | <LI><A HREF="#Ruby_nn5">27.1.3 Compiling a dynamic module</A></LI> | |
1175 | <LI><A HREF="#Ruby_nn6">27.1.4 Using your module</A></LI> | |
1176 | <LI><A HREF="#Ruby_nn7">27.1.5 Static linking</A></LI> | |
1177 | <LI><A HREF="#Ruby_nn8">27.1.6 Compilation of C++ extensions</A></LI> | |
1178 | </UL> | |
1179 | </LI> | |
1180 | <LI><A HREF="#Ruby_nn9">27.2 Building Ruby Extensions under Windows | |
1181 | 95/NT</A> | |
1182 | <UL> | |
1183 | <LI><A HREF="#Ruby_nn10">27.2.1 Running SWIG from Developer Studio</A></LI> | |
1184 | </UL> | |
1185 | </LI> | |
1186 | <LI><A HREF="#Ruby_nn11">27.3 The Ruby-to-C/C++ Mapping</A> | |
1187 | <UL> | |
1188 | <LI><A HREF="#Ruby_nn12">27.3.1 Modules</A></LI> | |
1189 | <LI><A HREF="#Ruby_nn13">27.3.2 Functions</A></LI> | |
1190 | <LI><A HREF="#Ruby_nn14">27.3.3 Variable Linking</A></LI> | |
1191 | <LI><A HREF="#Ruby_nn15">27.3.4 Constants</A></LI> | |
1192 | <LI><A HREF="#Ruby_nn16">27.3.5 Pointers</A></LI> | |
1193 | <LI><A HREF="#Ruby_nn17">27.3.6 Structures</A></LI> | |
1194 | <LI><A HREF="#Ruby_nn18">27.3.7 C++ classes</A></LI> | |
1195 | <LI><A HREF="#Ruby_nn19">27.3.8 C++ Inheritance</A></LI> | |
1196 | <LI><A HREF="#Ruby_nn20">27.3.9 C++ Overloaded Functions</A></LI> | |
1197 | <LI><A HREF="#Ruby_nn21">27.3.10 C++ Operators</A></LI> | |
1198 | <LI><A HREF="#Ruby_nn22">27.3.11 C++ namespaces</A></LI> | |
1199 | <LI><A HREF="#Ruby_nn23">27.3.12 C++ templates</A></LI> | |
1200 | <LI><A HREF="#ruby_cpp_smart_pointers">27.3.13 C++ Smart Pointers</A></LI> | |
1201 | <LI><A HREF="#Ruby_nn25">27.3.14 Cross-Language Polymorphism</A> | |
1202 | <UL> | |
1203 | <LI><A HREF="#Ruby_nn26">27.3.14.1 Exception Unrolling</A></LI> | |
1204 | </UL> | |
1205 | </LI> | |
1206 | </UL> | |
1207 | </LI> | |
1208 | <LI><A HREF="#Ruby_nn27">27.4 Input and output parameters</A></LI> | |
1209 | <LI><A HREF="#Ruby_nn28">27.5 Simple exception handling</A></LI> | |
1210 | <LI><A HREF="#Ruby_nn29">27.5 Typemaps</A> | |
1211 | <UL> | |
1212 | <LI><A HREF="#Ruby_nn30">27.5.1 What is a typemap?</A></LI> | |
1213 | <LI><A HREF="#Ruby_nn31">27.5.2 Ruby typemaps</A></LI> | |
1214 | <LI><A HREF="#Ruby_nn32">27.5.3 Typemap variables</A></LI> | |
1215 | <LI><A HREF="#Ruby_nn33">27.5.4 Useful Functions</A> | |
1216 | <UL> | |
1217 | <LI><A HREF="#Ruby_nn34">27.5.4.1 C Datatypes to Ruby Objects</A></LI> | |
1218 | <LI><A HREF="#Ruby_nn35">27.5.4.2 Ruby Objects to C Datatypes</A></LI> | |
1219 | <LI><A HREF="#Ruby_nn36">27.5.4.3 Macros for VALUE</A></LI> | |
1220 | <LI><A HREF="#Ruby_nn37">27.5.4.4 Exceptions</A></LI> | |
1221 | <LI><A HREF="#Ruby_nn38">27.5.4.5 Iterators</A></LI> | |
1222 | </UL> | |
1223 | </LI> | |
1224 | <LI><A HREF="#ruby_typemap_examples">27.5.5 Typemap Examples</A></LI> | |
1225 | <LI><A HREF="#Ruby_nn40">27.5.6 Converting a Ruby array to a char **</A></LI> | |
1226 | <LI><A HREF="#Ruby_nn41">27.5.7 Collecting arguments in a hash</A></LI> | |
1227 | <LI><A HREF="#Ruby_nn42">27.5.8 Pointer handling</A> | |
1228 | <UL> | |
1229 | <LI><A HREF="#Ruby_nn43">27.5.8.1 Ruby Datatype Wrapping</A></LI> | |
1230 | </UL> | |
1231 | </LI> | |
1232 | </UL> | |
1233 | </LI> | |
1234 | <LI><A HREF="#ruby_operator_overloading">27.6 Operator overloading</A> | |
1235 | <UL> | |
1236 | <LI><A HREF="#Ruby_nn45">27.6.1 Example: STL Vector to Ruby Array</A></LI> | |
1237 | </UL> | |
1238 | </LI> | |
1239 | <LI><A HREF="#Ruby_nn46">27.7 Advanced Topics</A> | |
1240 | <UL> | |
1241 | <LI><A HREF="#Ruby_nn47">27.7.1 Creating Multi-Module Packages</A></LI> | |
1242 | <LI><A HREF="#Ruby_nn48">27.7.2 Defining Aliases</A></LI> | |
1243 | <LI><A HREF="#Ruby_nn49">27.7.3 Predicate Methods</A></LI> | |
1244 | <LI><A HREF="#Ruby_nn50">27.7.4 Specifying Mixin Modules</A></LI> | |
1245 | </UL> | |
1246 | </LI> | |
1247 | <LI><A HREF="#Ruby_nn51">27.8 Memory Management</A> | |
1248 | <UL> | |
1249 | <LI><A HREF="#Ruby_nn52">27.9.1 Mark and Sweep Garbage Collector</A></LI> | |
1250 | <LI><A HREF="#Ruby_nn53">27.8.1 Object Ownership</A></LI> | |
1251 | <LI><A HREF="#Ruby_nn54">27.8.2 Object Tracking</A></LI> | |
1252 | <LI><A HREF="#Ruby_nn55">27.8.3 Mark Functions</A></LI> | |
1253 | <LI><A HREF="#Ruby_nn56">27.8.4 Free Functions</A></LI> | |
1254 | </UL> | |
1255 | </LI> | |
1256 | </UL> | |
1257 | <B><A HREF="#Tcl">28 SWIG and Tcl</A></B> | |
1258 | <UL> | |
1259 | <LI><A HREF="#Tcl_nn2">28.1 Preliminaries</A> | |
1260 | <UL> | |
1261 | <LI><A HREF="#Tcl_nn3">28.1.1 Getting the right header files</A></LI> | |
1262 | <LI><A HREF="#Tcl_nn4">28.1.2 Compiling a dynamic module</A></LI> | |
1263 | <LI><A HREF="#Tcl_nn5">28.1.3 Static linking</A></LI> | |
1264 | <LI><A HREF="#Tcl_nn6">28.1.4 Using your module</A></LI> | |
1265 | <LI><A HREF="#Tcl_nn7">28.1.5 Compilation of C++ extensions</A></LI> | |
1266 | <LI><A HREF="#Tcl_nn8">28.1.6 Compiling for 64-bit platforms</A></LI> | |
1267 | <LI><A HREF="#Tcl_nn9">28.1.7 Setting a package prefix</A></LI> | |
1268 | <LI><A HREF="#Tcl_nn10">28.1.8 Using namespaces</A></LI> | |
1269 | </UL> | |
1270 | </LI> | |
1271 | <LI><A HREF="#Tcl_nn11">28.2 Building Tcl/Tk Extensions under Windows | |
1272 | 95/NT</A> | |
1273 | <UL> | |
1274 | <LI><A HREF="#Tcl_nn12">28.2.1 Running SWIG from Developer Studio</A></LI> | |
1275 | <LI><A HREF="#Tcl_nn13">28.2.2 Using NMAKE</A></LI> | |
1276 | </UL> | |
1277 | </LI> | |
1278 | <LI><A HREF="#Tcl_nn14">28.3 A tour of basic C/C++ wrapping</A> | |
1279 | <UL> | |
1280 | <LI><A HREF="#Tcl_nn15">28.3.1 Modules</A></LI> | |
1281 | <LI><A HREF="#Tcl_nn16">28.3.2 Functions</A></LI> | |
1282 | <LI><A HREF="#Tcl_nn17">28.3.3 Global variables</A></LI> | |
1283 | <LI><A HREF="#Tcl_nn18">28.3.4 Constants and enums</A></LI> | |
1284 | <LI><A HREF="#Tcl_nn19">28.3.5 Pointers</A></LI> | |
1285 | <LI><A HREF="#Tcl_nn20">28.3.6 Structures</A></LI> | |
1286 | <LI><A HREF="#Tcl_nn21">28.3.7 C++ classes</A></LI> | |
1287 | <LI><A HREF="#Tcl_nn22">28.3.8 C++ inheritance</A></LI> | |
1288 | <LI><A HREF="#Tcl_nn23">28.3.9 Pointers, references, values, and arrays</A> | |
1289 | </LI> | |
1290 | <LI><A HREF="#Tcl_nn24">28.3.10 C++ overloaded functions</A></LI> | |
1291 | <LI><A HREF="#Tcl_nn25">28.3.11 C++ operators</A></LI> | |
1292 | <LI><A HREF="#Tcl_nn26">28.3.12 C++ namespaces</A></LI> | |
1293 | <LI><A HREF="#Tcl_nn27">28.3.13 C++ templates</A></LI> | |
1294 | <LI><A HREF="#Tcl_nn28">28.3.14 C++ Smart Pointers</A></LI> | |
1295 | </UL> | |
1296 | </LI> | |
1297 | <LI><A HREF="#Tcl_nn29">28.4 Further details on the Tcl class interface</A> | |
1298 | <UL> | |
1299 | <LI><A HREF="#Tcl_nn30">28.4.1 Proxy classes</A></LI> | |
1300 | <LI><A HREF="#Tcl_nn31">28.4.2 Memory management</A></LI> | |
1301 | </UL> | |
1302 | </LI> | |
1303 | <LI><A HREF="#Tcl_nn32">28.5 Input and output parameters</A></LI> | |
1304 | <LI><A HREF="#Tcl_nn33">28.6 Exception handling</A></LI> | |
1305 | <LI><A HREF="#Tcl_nn34">28.7 Typemaps</A> | |
1306 | <UL> | |
1307 | <LI><A HREF="#Tcl_nn35">28.7.1 What is a typemap?</A></LI> | |
1308 | <LI><A HREF="#Tcl_nn36">28.7.2 Tcl typemaps</A></LI> | |
1309 | <LI><A HREF="#Tcl_nn37">28.7.3 Typemap variables</A></LI> | |
1310 | <LI><A HREF="#Tcl_nn38">28.7.4 Converting a Tcl list to a char **</A></LI> | |
1311 | <LI><A HREF="#Tcl_nn39">28.7.5 Returning values in arguments</A></LI> | |
1312 | <LI><A HREF="#Tcl_nn40">28.7.6 Useful functions</A></LI> | |
1313 | <LI><A HREF="#Tcl_nn41">28.7.7 Standard typemaps</A></LI> | |
1314 | <LI><A HREF="#Tcl_nn42">28.7.8 Pointer handling</A></LI> | |
1315 | </UL> | |
1316 | </LI> | |
1317 | <LI><A HREF="#Tcl_nn43">28.8 Turning a SWIG module into a Tcl Package.</A> | |
1318 | </LI> | |
1319 | <LI><A HREF="#Tcl_nn44">28.9 Building new kinds of Tcl interfaces (in | |
1320 | Tcl)</A> | |
1321 | <UL> | |
1322 | <LI><A HREF="#Tcl_nn45">28.9.1 Proxy classes</A></LI> | |
1323 | </UL> | |
1324 | </LI> | |
1325 | </UL> | |
1326 | <B><A HREF="#Lua_nn1">29 SWIG and Lua</A></B> | |
1327 | <UL> | |
1328 | <LI><A HREF="#Lua_nn2">29.1 Preliminaries</A></LI> | |
1329 | <LI><A HREF="#Lua_nn3">29.2 Running SWIG</A> | |
1330 | <UL> | |
1331 | <LI><A HREF="#Lua_nn4">29.2.1 Compiling and Linking and Interpreter</A></LI> | |
1332 | <LI><A HREF="#Lua_nn5">29.2.2 Compiling a dynamic module</A></LI> | |
1333 | <LI><A HREF="#Lua_nn6">29.2.3 Using your module</A></LI> | |
1334 | </UL> | |
1335 | </LI> | |
1336 | <LI><A HREF="#Lua_nn7">29.3 A tour of basic C/C++ wrapping</A> | |
1337 | <UL> | |
1338 | <LI><A HREF="#Lua_nn8">29.3.1 Modules</A></LI> | |
1339 | <LI><A HREF="#Lua_nn9">29.3.2 Functions</A></LI> | |
1340 | <LI><A HREF="#Lua_nn10">29.3.3 Global variables</A></LI> | |
1341 | <LI><A HREF="#Lua_nn11">29.3.4 Constants and enums</A></LI> | |
1342 | <LI><A HREF="#Lua_nn12">29.3.5 Pointers</A></LI> | |
1343 | <LI><A HREF="#Lua_nn13">29.3.6 Structures</A></LI> | |
1344 | <LI><A HREF="#Lua_nn14">29.3.7 C++ classes</A></LI> | |
1345 | <LI><A HREF="#Lua_nn15">29.3.8 C++ inheritance</A></LI> | |
1346 | <LI><A HREF="#Lua_nn16">29.3.9 Pointers, references, values, and arrays</A> | |
1347 | </LI> | |
1348 | <LI><A HREF="#Lua_nn17">29.3.10 C++ overloaded functions</A></LI> | |
1349 | <LI><A HREF="#Lua_nn18">29.3.11 C++ operators</A></LI> | |
1350 | <LI><A HREF="#Lua_nn19">29.3.12 Class extension with %extend</A></LI> | |
1351 | <LI><A HREF="#Lua_nn20">29.3.13 C++ templates</A></LI> | |
1352 | <LI><A HREF="#Lua_nn21">29.3.14 C++ Smart Pointers</A></LI> | |
1353 | </UL> | |
1354 | </LI> | |
1355 | <LI><A HREF="#Lua_nn22">29.4 Details on the Lua binding</A> | |
1356 | <UL> | |
1357 | <LI><A HREF="#Lua_nn23">29.4.1 Binding global data into the module.</A></LI> | |
1358 | <LI><A HREF="#Lua_nn24">29.4.2 Userdata and Metatables</A></LI> | |
1359 | <LI><A HREF="#Lua_nn25">29.4.3 Memory management</A></LI> | |
1360 | </UL> | |
1361 | </LI> | |
1362 | </UL> | |
1363 | <B><A HREF="#Extending">30 Extending SWIG</A></B> | |
1364 | <UL> | |
1365 | <LI><A HREF="#Extending_nn2">30.1 Introduction</A></LI> | |
1366 | <LI><A HREF="#Extending_nn3">30.2 Prerequisites</A></LI> | |
1367 | <LI><A HREF="#Extending_nn4">30.3 The Big Picture</A></LI> | |
1368 | <LI><A HREF="#Extending_nn5">30.4 Execution Model</A> | |
1369 | <UL> | |
1370 | <LI><A HREF="#Extending_nn6">30.4.1 Preprocessing</A></LI> | |
1371 | <LI><A HREF="#Extending_nn7">30.4.2 Parsing</A></LI> | |
1372 | <LI><A HREF="#Extending_nn8">30.4.3 Parse Trees</A></LI> | |
1373 | <LI><A HREF="#Extending_nn9">30.4.4 Attribute namespaces</A></LI> | |
1374 | <LI><A HREF="#Extending_nn10">30.4.5 Symbol Tables</A></LI> | |
1375 | <LI><A HREF="#Extending_nn11">30.4.6 The %feature directive</A></LI> | |
1376 | <LI><A HREF="#Extending_nn12">30.4.7 Code Generation</A></LI> | |
1377 | <LI><A HREF="#Extending_nn13">30.4.8 SWIG and XML</A></LI> | |
1378 | </UL> | |
1379 | </LI> | |
1380 | <LI><A HREF="#Extending_nn14">30.5 Primitive Data Structures</A> | |
1381 | <UL> | |
1382 | <LI><A HREF="#Extending_nn15">30.5.1 Strings</A></LI> | |
1383 | <LI><A HREF="#Extending_nn16">30.5.2 Hashes</A></LI> | |
1384 | <LI><A HREF="#Extending_nn17">30.5.3 Lists</A></LI> | |
1385 | <LI><A HREF="#Extending_nn18">30.5.4 Common operations</A></LI> | |
1386 | <LI><A HREF="#Extending_nn19">30.5.5 Iterating over Lists and Hashes</A></LI> | |
1387 | <LI><A HREF="#Extending_nn20">30.5.6 I/O</A></LI> | |
1388 | </UL> | |
1389 | </LI> | |
1390 | <LI><A HREF="#Extending_nn21">30.6 Navigating and manipulating parse | |
1391 | trees</A></LI> | |
1392 | <LI><A HREF="#Extending_nn22">30.7 Working with attributes</A></LI> | |
1393 | <LI><A HREF="#Extending_nn23">30.8 Type system</A> | |
1394 | <UL> | |
1395 | <LI><A HREF="#Extending_nn24">30.8.1 String encoding of types</A></LI> | |
1396 | <LI><A HREF="#Extending_nn25">30.8.2 Type construction</A></LI> | |
1397 | <LI><A HREF="#Extending_nn26">30.8.3 Type tests</A></LI> | |
1398 | <LI><A HREF="#Extending_nn27">30.8.4 Typedef and inheritance</A></LI> | |
1399 | <LI><A HREF="#Extending_nn28">30.8.5 Lvalues</A></LI> | |
1400 | <LI><A HREF="#Extending_nn29">30.8.6 Output functions</A></LI> | |
1401 | </UL> | |
1402 | </LI> | |
1403 | <LI><A HREF="#Extending_nn30">30.9 Parameters</A></LI> | |
1404 | <LI><A HREF="#Extending_nn31">30.10 Writing a Language Module</A> | |
1405 | <UL> | |
1406 | <LI><A HREF="#Extending_nn32">30.10.1 Execution model</A></LI> | |
1407 | <LI><A HREF="#Extending_nn33">30.10.2 Starting out</A></LI> | |
1408 | <LI><A HREF="#Extending_nn34">30.10.3 Command line options</A></LI> | |
1409 | <LI><A HREF="#Extending_nn35">30.10.4 Configuration and preprocessing</A> | |
1410 | </LI> | |
1411 | <LI><A HREF="#Extending_nn36">30.10.5 Entry point to code generation</A></LI> | |
1412 | <LI><A HREF="#Extending_nn37">30.10.6 Module I/O and wrapper skeleton</A> | |
1413 | </LI> | |
1414 | <LI><A HREF="#Extending_nn38">30.10.7 Low-level code generators</A></LI> | |
1415 | <LI><A HREF="#Extending_nn39">30.10.8 Configuration files</A></LI> | |
1416 | <LI><A HREF="#Extending_nn40">30.10.9 Runtime support</A></LI> | |
1417 | <LI><A HREF="#Extending_nn41">30.10.10 Standard library files</A></LI> | |
1418 | <LI><A HREF="#Extending_nn42">30.10.11 Examples and test cases</A></LI> | |
1419 | <LI><A HREF="#Extending_nn43">30.10.12 Documentation</A></LI> | |
1420 | </UL> | |
1421 | </LI> | |
1422 | <LI><A HREF="#Extending_nn44">30.11 Typemaps</A> | |
1423 | <UL> | |
1424 | <LI><A HREF="#Extending_nn45">30.11.1 Proxy classes</A></LI> | |
1425 | </UL> | |
1426 | </LI> | |
1427 | <LI><A HREF="#Extending_nn46">30.12 Guide to parse tree nodes</A></LI> | |
1428 | </UL> | |
1429 | <HR NOSHADE> | |
1430 | <H1><A name="Sections"></A>SWIG-1.3 Development Documentation</H1> | |
1431 | Last update : SWIG-1.3.26 (October 9, 2005) | |
1432 | <H2><A NAME="1_1">Sections</A></H2> | |
1433 | <P> The SWIG documentation is being updated to reflect new SWIG features | |
1434 | and enhancements. However, this update process is not quite | |
1435 | finished--there is a lot of old SWIG-1.1 documentation and it is taking | |
1436 | some time to update all of it. Please pardon our dust (or volunteer to | |
1437 | help!).</P> | |
1438 | <H3><A NAME="1_1_1">SWIG Core Documentation</A></H3> | |
1439 | <UL> | |
1440 | <LI><A href="#Preface">Preface</A></LI> | |
1441 | <LI><A href="#Introduction">Introduction</A></LI> | |
1442 | <LI><A href="#Windows">Getting started on Windows</A></LI> | |
1443 | <LI><A href="#Scripting">Scripting</A></LI> | |
1444 | <LI><A href="#SWIG">SWIG Basics</A> (Read this!)</LI> | |
1445 | <LI><A href="#SWIGPlus">SWIG and C++</A></LI> | |
1446 | <LI><A href="#Preprocessor">The SWIG preprocessor</A></LI> | |
1447 | <LI><A href="#Library">The SWIG Library</A></LI> | |
1448 | <LI><A href="#Arguments">Argument handling</A></LI> | |
1449 | <LI><A href="#Typemaps">Typemaps</A></LI> | |
1450 | <LI><A href="#Customization">Customization features</A></LI> | |
1451 | <LI><A href="#Contract">Contracts</A></LI> | |
1452 | <LI><A href="#Varargs">Variable length arguments</A></LI> | |
1453 | <LI><A href="#Warnings">Warning messages</A></LI> | |
1454 | <LI><A href="#Modules">Working with Modules</A></LI> | |
1455 | </UL> | |
1456 | <H3><A NAME="1_1_2">Language Module Documentation</A></H3> | |
1457 | <UL> | |
1458 | <LI><A href="Lisp.html#Lisp_nn1">Common Lisp support</A></LI> | |
1459 | <LI><A href="#CSharp">C# support</A></LI> | |
1460 | <LI><A href="#Chicken">Chicken support</A></LI> | |
1461 | <LI><A href="#Guile">Guile support</A></LI> | |
1462 | <LI><A href="#Java">Java support</A></LI> | |
1463 | <LI><A href="#Lua_nn1">Lua support</A></LI> | |
1464 | <LI><A href="#Modula3">Modula3 support</A></LI> | |
1465 | <LI><A href="#MzScheme">MzScheme support</A></LI> | |
1466 | <LI><A href="#Ocaml">Ocaml support</A></LI> | |
1467 | <LI><A href="#Perl5">Perl5 support</A></LI> | |
1468 | <LI><A href="#Php">PHP support</A></LI> | |
1469 | <LI><A href="#Pike">Pike support</A></LI> | |
1470 | <LI><A href="#Python">Python support</A></LI> | |
1471 | <LI><A href="#Ruby">Ruby support</A></LI> | |
1472 | <LI><A href="#Tcl">Tcl support</A></LI> | |
1473 | </UL> | |
1474 | <H3><A NAME="1_1_3">Developer Documentation</A></H3> | |
1475 | <UL> | |
1476 | <LI><A href="#Extending">Extending SWIG</A></LI> | |
1477 | </UL> | |
1478 | <H3><A NAME="1_1_4">Documentation that has not yet been updated</A></H3> | |
1479 | <P> This documentation has not been completely updated from SWIG-1.1, | |
1480 | but most of the topics still apply to the current release. Make sure | |
1481 | you read the <A href="#SWIG">SWIG Basics</A> chapter before reading any | |
1482 | of these chapters. Also, SWIG-1.3.10 features extensive changes to the | |
1483 | implementation of typemaps. Make sure you read the <A href="#Typemaps"> | |
1484 | Typemaps</A> chapter above if you are using this feature.</P> | |
1485 | <UL> | |
1486 | <LI><A href="Advanced.html#Advanced">Advanced topics</A> (see <A href="#Modules"> | |
1487 | Modules</A> for updated information).</LI> | |
1488 | </UL> | |
1489 | <HR NOSHADE> | |
1490 | <H1><A name="Preface"></A>1 Preface</H1> | |
1491 | ||
1492 | <!-- INDEX --> | |
1493 | <DIV class="sectiontoc"> | |
1494 | <UL> | |
1495 | <LI><A href="#Preface_nn2">Introduction</A></LI> | |
1496 | <LI><A href="#Preface_nn3">Special Introduction for Version 1.3</A></LI> | |
1497 | <LI><A href="#Preface_nn4">SWIG Versions</A></LI> | |
1498 | <LI><A href="#Preface_nn5">SWIG resources</A></LI> | |
1499 | <LI><A href="#Preface_nn6">Prerequisites</A></LI> | |
1500 | <LI><A href="#Preface_nn7">Organization of this manual</A></LI> | |
1501 | <LI><A href="#Preface_nn8">How to avoid reading the manual</A></LI> | |
1502 | <LI><A href="#Preface_nn9">Backwards Compatibility</A></LI> | |
1503 | <LI><A href="#Preface_nn10">Credits</A></LI> | |
1504 | <LI><A href="#Preface_nn11">Bug reports</A></LI> | |
1505 | </UL> | |
1506 | </DIV> | |
1507 | <!-- INDEX --> | |
1508 | <H2><A name="Preface_nn2"></A>1.1 Introduction</H2> | |
1509 | <P> SWIG (Simplified Wrapper and Interface Generator) is a software | |
1510 | development tool for building scripting language interfaces to C and | |
1511 | C++ programs. Originally developed in 1995, SWIG was first used by | |
1512 | scientists in the Theoretical Physics Division at Los Alamos National | |
1513 | Laboratory for building user interfaces to simulation codes running on | |
1514 | the Connection Machine 5 supercomputer. In this environment, scientists | |
1515 | needed to work with huge amounts of simulation data, complex hardware, | |
1516 | and a constantly changing code base. The use of a scripting language | |
1517 | interface provided a simple yet highly flexible foundation for solving | |
1518 | these types of problems. SWIG simplifies development by largely | |
1519 | automating the task of scripting language integration--allowing | |
1520 | developers and users to focus on more important problems.</P> | |
1521 | <P> Although SWIG was originally developed for scientific applications, | |
1522 | it has since evolved into a general purpose tool that is used in a wide | |
1523 | variety of applications--in fact almost anything where C/C++ | |
1524 | programming is involved.</P> | |
1525 | <H2><A name="Preface_nn3"></A>1.2 Special Introduction for Version 1.3</H2> | |
1526 | <P> Since SWIG was released in 1996, its user base and applicability has | |
1527 | continued to grow. Although its rate of development has varied, an | |
1528 | active development effort has continued to make improvements to the | |
1529 | system. Today, nearly a dozen developers are working to create | |
1530 | SWIG-2.0---a system that aims to provide wrapping support for nearly | |
1531 | all of the ANSI C++ standard and approximately ten target languages | |
1532 | including Guile, Java, Mzscheme, Ocaml, Perl, Pike, PHP, Python, Ruby, | |
1533 | and Tcl.</P> | |
1534 | <H2><A name="Preface_nn4"></A>1.3 SWIG Versions</H2> | |
1535 | <P> For several years, the most stable version of SWIG has been release | |
1536 | 1.1p5. Starting with version 1.3, a new version numbering scheme has | |
1537 | been adopted. Odd version numbers (1.3, 1.5, etc.) represent | |
1538 | development versions of SWIG. Even version numbers (1.4, 1.6, etc.) | |
1539 | represent stable releases. Currently, developers are working to create | |
1540 | a stable SWIG-2.0 release. Don't let the development status of SWIG-1.3 | |
1541 | scare you---it is much more stable (and capable) than SWIG-1.1p5.</P> | |
1542 | <H2><A name="Preface_nn5"></A>1.4 SWIG resources</H2> | |
1543 | <P> The official location of SWIG related material is</P> | |
1544 | <DIV class="shell"> | |
1545 | <PRE> | |
1546 | <A href="http://www.swig.org">http://www.swig.org</A> | |
1547 | </PRE> | |
1548 | </DIV> | |
1549 | <P> This site contains the latest version of the software, users guide, | |
1550 | and information regarding bugs, installation problems, and | |
1551 | implementation tricks.</P> | |
1552 | <P> You can also subscribe to the SWIG mailing list by visiting the page</P> | |
1553 | <DIV class="shell"> | |
1554 | <PRE> | |
1555 | <A href="http://www.swig.org/mail.html">http://www.swig.org/mail.html</A> | |
1556 | </PRE> | |
1557 | </DIV> | |
1558 | <P> The mailing list often discusses some of the more technical aspects | |
1559 | of SWIG along with information about beta releases and future work.</P> | |
1560 | <P> CVS access to the latest version of SWIG is also available. More | |
1561 | information about this can be obtained at:</P> | |
1562 | <DIV class="shell"> | |
1563 | <PRE> | |
1564 | <A href="http://www.swig.org/cvs.html">http://www.swig.org/cvs.html</A> | |
1565 | </PRE> | |
1566 | </DIV> | |
1567 | <H2><A name="Preface_nn6"></A>1.5 Prerequisites</H2> | |
1568 | <P> This manual assumes that you know how to write C/C++ programs and | |
1569 | that you have at least heard of scripting languages such as Tcl, | |
1570 | Python, and Perl. A detailed knowledge of these scripting languages is | |
1571 | not required although some familiarity won't hurt. No prior experience | |
1572 | with building C extensions to these languages is required---after all, | |
1573 | this is what SWIG does automatically. However, you should be reasonably | |
1574 | familiar with the use of compilers, linkers, and makefiles since making | |
1575 | scripting language extensions is somewhat more complicated than writing | |
1576 | a normal C program.</P> | |
1577 | <P> Recent SWIG releases have become significantly more capable in their | |
1578 | C++ handling--especially support for advanced features like namespaces, | |
1579 | overloaded operators, and templates. Whenever possible, this manual | |
1580 | tries to cover the technicalities of this interface. However, this | |
1581 | isn't meant to be a tutorial on C++ programming. For many of the gory | |
1582 | details, you will almost certainly want to consult a good C++ | |
1583 | reference. If you don't program in C++, you may just want to skip those | |
1584 | parts of the manual.</P> | |
1585 | <H2><A name="Preface_nn7"></A>1.6 Organization of this manual</H2> | |
1586 | <P> The first few chapters of this manual describe SWIG in general and | |
1587 | provide an overview of its capabilities. The remaining chapters are | |
1588 | devoted to specific SWIG language modules and are self contained. Thus, | |
1589 | if you are using SWIG to build Python interfaces, you can probably skip | |
1590 | to that chapter and find almost everything you need to know. Caveat: we | |
1591 | are currently working on a documentation rewrite and many of the older | |
1592 | language module chapters are still somewhat out of date.</P> | |
1593 | <H2><A name="Preface_nn8"></A>1.7 How to avoid reading the manual</H2> | |
1594 | <P> If you hate reading manuals, glance at the "Introduction" which | |
1595 | contains a few simple examples. These examples contain about 95% of | |
1596 | everything you need to know to use SWIG. After that, simply use the | |
1597 | language-specific chapters as a reference. The SWIG distribution also | |
1598 | comes with a large directory of examples that illustrate different | |
1599 | topics.</P> | |
1600 | <H2><A name="Preface_nn9"></A>1.8 Backwards Compatibility</H2> | |
1601 | <P> If you are a previous user of SWIG, don't expect recent versions of | |
1602 | SWIG to provide backwards compatibility. In fact, backwards | |
1603 | compatibility issues may arise even between successive 1.3.x releases. | |
1604 | Although these incompatibilities are regrettable, SWIG-1.3 is an active | |
1605 | development project. The primary goal of this effort is to make SWIG | |
1606 | better---a process that would simply be impossible if the developers | |
1607 | are constantly bogged down with backwards compatibility issues.</P> | |
1608 | <P> On a positive note, a few incompatibilities are a small price to pay | |
1609 | for the large number of new features that have been added---namespaces, | |
1610 | templates, smart pointers, overloaded methods, operators, and more.</P> | |
1611 | <P> If you need to work with different versions of SWIG and backwards | |
1612 | compatibility is an issue, you can use the SWIG_VERSION preprocessor | |
1613 | symbol which holds the version of SWIG being executed. SWIG_VERSION is | |
1614 | a hexadecimal integer such as 0x010311 (corresponding to SWIG-1.3.11). | |
1615 | This can be used in an interface file to define different typemaps, | |
1616 | take advantage of different features etc:</P> | |
1617 | <DIV class="code"> | |
1618 | <PRE> | |
1619 | #if SWIG_VERSION >= 0x010311 | |
1620 | /* Use some fancy new feature */ | |
1621 | #endif | |
1622 | </PRE> | |
1623 | </DIV> | |
1624 | <P> Note: The version symbol is not defined in the generated SWIG | |
1625 | wrapper file. The SWIG preprocessor has defined SWIG_VERSION since | |
1626 | SWIG-1.3.11.</P> | |
1627 | <H2><A name="Preface_nn10"></A>1.9 Credits</H2> | |
1628 | <P> SWIG is an unfunded project that would not be possible without the | |
1629 | contributions of many people. Most recent SWIG development has been | |
1630 | supported by Matthias Köppe, William Fulton, Lyle Johnson, Richard | |
1631 | Palmer, Thien-Thi Nguyen, Jason Stewart, Loic Dachary, Masaki | |
1632 | Fukushima, Luigi Ballabio, Sam Liddicott, Art Yerkes, Marcelo Matus, | |
1633 | Harco de Hilster, John Lenz, and Surendra Singhi.</P> | |
1634 | <P> Historically, the following people contributed to early versions of | |
1635 | SWIG. Peter Lomdahl, Brad Holian, Shujia Zhou, Niels Jensen, and Tim | |
1636 | Germann at Los Alamos National Laboratory were the first users. Patrick | |
1637 | Tullmann at the University of Utah suggested the idea of automatic | |
1638 | documentation generation. John Schmidt and Kurtis Bleeker at the | |
1639 | University of Utah tested out the early versions. Chris Johnson | |
1640 | supported SWIG's developed at the University of Utah. John Buckman, | |
1641 | Larry Virden, and Tom Schwaller provided valuable input on the first | |
1642 | releases and improving the portability of SWIG. David Fletcher and Gary | |
1643 | Holt have provided a great deal of input on improving SWIG's Perl5 | |
1644 | implementation. Kevin Butler contributed the first Windows NT port.</P> | |
1645 | <H2><A name="Preface_nn11"></A>1.10 Bug reports</H2> | |
1646 | <P> Although every attempt has been made to make SWIG bug-free, we are | |
1647 | also trying to make feature improvements that may introduce bugs. To | |
1648 | report a bug, either send mail to the SWIG developer list at the <A href="http://www.swig.org/mail.html"> | |
1649 | swig-dev mailing list</A> or report a bug at the <A href="http://www.swig.org/bugs.html"> | |
1650 | SWIG bug tracker</A>. In your report, be as specific as possible, | |
1651 | including (if applicable), error messages, tracebacks (if a core dump | |
1652 | occurred), corresponding portions of the SWIG interface file used, and | |
1653 | any important pieces of the SWIG generated wrapper code. We can only | |
1654 | fix bugs if we know about them.</P> | |
1655 | <HR NOSHADE> | |
1656 | <H1><A name="Introduction"></A>2 Introduction</H1> | |
1657 | ||
1658 | <!-- INDEX --> | |
1659 | <DIV class="sectiontoc"> | |
1660 | <UL> | |
1661 | <LI><A href="#Introduction_nn2">What is SWIG?</A></LI> | |
1662 | <LI><A href="#Introduction_nn3">Why use SWIG?</A></LI> | |
1663 | <LI><A href="#Introduction_nn4">A SWIG example</A> | |
1664 | <UL> | |
1665 | <LI><A href="#Introduction_nn5">SWIG interface file</A></LI> | |
1666 | <LI><A href="#Introduction_nn6">The swig command</A></LI> | |
1667 | <LI><A href="#Introduction_nn7">Building a Perl5 module</A></LI> | |
1668 | <LI><A href="#Introduction_nn8">Building a Python module</A></LI> | |
1669 | <LI><A href="#Introduction_nn9">Shortcuts</A></LI> | |
1670 | </UL> | |
1671 | </LI> | |
1672 | <LI><A href="#Introduction_nn10">Supported C/C++ language features</A></LI> | |
1673 | <LI><A href="#Introduction_nn11">Non-intrusive interface building</A></LI> | |
1674 | <LI><A href="#Introduction_build_system">Incorporating SWIG into a build | |
1675 | system</A></LI> | |
1676 | <LI><A href="#Introduction_nn12">Hands off code generation</A></LI> | |
1677 | <LI><A href="#Introduction_nn13">SWIG and freedom</A></LI> | |
1678 | </UL> | |
1679 | </DIV> | |
1680 | <!-- INDEX --> | |
1681 | <H2><A name="Introduction_nn2"></A>2.1 What is SWIG?</H2> | |
1682 | <P> SWIG is a software development tool that simplifies the task of | |
1683 | interfacing different languages to C and C++ programs. In a nutshell, | |
1684 | SWIG is a compiler that takes C declarations and creates the wrappers | |
1685 | needed to access those declarations from other languages including | |
1686 | including Perl, Python, Tcl, Ruby, Guile, and Java. SWIG normally | |
1687 | requires no modifications to existing code and can often be used to | |
1688 | build a usable interface in only a few minutes. Possible applications | |
1689 | of SWIG include:</P> | |
1690 | <UL> | |
1691 | <LI>Building interpreted interfaces to existing C programs.</LI> | |
1692 | <LI>Rapid prototyping and application development.</LI> | |
1693 | <LI>Interactive debugging.</LI> | |
1694 | <LI>Reengineering or refactoring of legacy software into a scripting | |
1695 | language components.</LI> | |
1696 | <LI>Making a graphical user interface (using Tk for example).</LI> | |
1697 | <LI>Testing of C libraries and programs (using scripts).</LI> | |
1698 | <LI>Building high performance C modules for scripting languages.</LI> | |
1699 | <LI>Making C programming more enjoyable (or tolerable depending on your | |
1700 | point of view).</LI> | |
1701 | <LI>Impressing your friends.</LI> | |
1702 | <LI>Obtaining vast sums of research funding (although obviously not | |
1703 | applicable to the author).</LI> | |
1704 | </UL> | |
1705 | <P> SWIG was originally designed to make it extremely easy for | |
1706 | scientists and engineers to build extensible scientific software | |
1707 | without having to get a degree in software engineering. Because of | |
1708 | this, the use of SWIG tends to be somewhat informal and ad-hoc (e.g., | |
1709 | SWIG does not require users to provide formal interface specifications | |
1710 | as you would find in a dedicated IDL compiler). Although this style of | |
1711 | development isn't appropriate for every project, it is particularly | |
1712 | well suited to software development in the small; especially the | |
1713 | research and development work that is commonly found in scientific and | |
1714 | engineering projects.</P> | |
1715 | <H2><A name="Introduction_nn3"></A>2.2 Why use SWIG?</H2> | |
1716 | <P> As stated in the previous section, the primary purpose of SWIG is to | |
1717 | simplify the task of integrating C/C++ with other programming | |
1718 | languages. However, why would anyone want to do that? To answer that | |
1719 | question, it is useful to list a few strengths of C/C++ programming:</P> | |
1720 | <UL> | |
1721 | <LI>Excellent support for writing programming libraries.</LI> | |
1722 | <LI>High performance (number crunching, data processing, graphics, | |
1723 | etc.).</LI> | |
1724 | <LI>Systems programming and systems integration.</LI> | |
1725 | <LI>Large user community and software base.</LI> | |
1726 | </UL> | |
1727 | <P> Next, let's list a few problems with C/C++ programming</P> | |
1728 | <UL> | |
1729 | <LI>Writing a user interface is rather painful (i.e., consider | |
1730 | programming with MFC, X11, GTK, or any number of other libraries).</LI> | |
1731 | <LI>Testing is time consuming (the compile/debug cycle).</LI> | |
1732 | <LI>Not easy to reconfigure or customize without recompilation.</LI> | |
1733 | <LI>Modularization can be tricky.</LI> | |
1734 | <LI>Security concerns (buffer overflow for instance).</LI> | |
1735 | </UL> | |
1736 | <P> To address these limitations, many programmers have arrived at the | |
1737 | conclusion that it is much easier to use different programming | |
1738 | languages for different tasks. For instance, writing a graphical user | |
1739 | interface may be significantly easier in a scripting language like | |
1740 | Python or Tcl (consider the reasons why millions of programmers have | |
1741 | used languages like Visual Basic if you need more proof). An | |
1742 | interactive interpreter might also serve as a useful debugging and | |
1743 | testing tool. Other languages like Java might greatly simplify the task | |
1744 | of writing distributed computing software. The key point is that | |
1745 | different programming languages offer different strengths and | |
1746 | weaknesses. Moreover, it is extremely unlikely that any programming is | |
1747 | ever going to be perfect. Therefore, by combining languages together, | |
1748 | you can utilize the best features of each language and greatly simplify | |
1749 | certain aspects of software development.</P> | |
1750 | <P> From the standpoint of C/C++, a lot of people use SWIG because they | |
1751 | want to break out of the traditional monolithic C programming model | |
1752 | which usually results in programs that resemble this:</P> | |
1753 | <UL> | |
1754 | <LI>A collection of functions and variables that do something useful.</LI> | |
1755 | <LI>A <TT>main()</TT> program that starts everything.</LI> | |
1756 | <LI>A horrible collection of hacks that form some kind of user interface | |
1757 | (but which no-one really wants to touch).</LI> | |
1758 | </UL> | |
1759 | <P> Instead of going down that route, incorporating C/C++ into a higher | |
1760 | level language often results in a more modular design, less code, | |
1761 | better flexibility, and increased programmer productivity.</P> | |
1762 | <P> SWIG tries to make the problem of C/C++ integration as painless as | |
1763 | possible. This allows you to focus on the underlying C program and | |
1764 | using the high-level language interface, but not the tedious and | |
1765 | complex chore of making the two languages talk to each other. At the | |
1766 | same time, SWIG recognizes that all applications are different. | |
1767 | Therefore, it provides a wide variety of customization features that | |
1768 | let you change almost every aspect of the language bindings. This is | |
1769 | the main reason why SWIG has such a large user manual ;-).</P> | |
1770 | <H2><A name="Introduction_nn4"></A>2.3 A SWIG example</H2> | |
1771 | <P> The best way to illustrate SWIG is with a simple example. Consider | |
1772 | the following C code:</P> | |
1773 | <DIV class="code"> | |
1774 | <PRE> | |
1775 | /* File : example.c */ | |
1776 | ||
1777 | double My_variable = 3.0; | |
1778 | ||
1779 | /* Compute factorial of n */ | |
1780 | int fact(int n) { | |
1781 | if (n <= 1) return 1; | |
1782 | else return n*fact(n-1); | |
1783 | } | |
1784 | ||
1785 | /* Compute n mod m */ | |
1786 | int my_mod(int n, int m) { | |
1787 | return(n % m); | |
1788 | } | |
1789 | </PRE> | |
1790 | </DIV> | |
1791 | <P> Suppose that you wanted to access these functions and the global | |
1792 | variable <TT>My_variable</TT> from Tcl. You start by making a SWIG | |
1793 | interface file as shown below (by convention, these files carry a .i | |
1794 | suffix) :</P> | |
1795 | <H3><A name="Introduction_nn5"></A>2.3.1 SWIG interface file</H3> | |
1796 | <DIV class="code"> | |
1797 | <PRE> | |
1798 | /* File : example.i */ | |
1799 | %module example | |
1800 | %{ | |
1801 | /* Put headers and other declarations here */ | |
1802 | extern double My_variable; | |
1803 | extern int fact(int); | |
1804 | extern int my_mod(int n, int m); | |
1805 | %} | |
1806 | ||
1807 | extern double My_variable; | |
1808 | extern int fact(int); | |
1809 | extern int my_mod(int n, int m); | |
1810 | </PRE> | |
1811 | </DIV> | |
1812 | <P> The interface file contains ANSI C function prototypes and variable | |
1813 | declarations. The <TT>%module</TT> directive defines the name of the | |
1814 | module that will be created by SWIG. The <TT>%{,%}</TT> block provides | |
1815 | a location for inserting additional code such as C header files or | |
1816 | additional C declarations.</P> | |
1817 | <H3><A name="Introduction_nn6"></A>2.3.2 The swig command</H3> | |
1818 | <P> SWIG is invoked using the <TT>swig</TT> command. We can use this to | |
1819 | build a Tcl module (under Linux) as follows :</P> | |
1820 | <DIV class="shell"> | |
1821 | <PRE> | |
1822 | unix > <B>swig -tcl example.i</B> | |
1823 | unix > <B>gcc -c -fpic example.c example_wrap.c -I/usr/local/include</B> | |
1824 | unix > <B>gcc -shared example.o example_wrap.o -o example.so</B> | |
1825 | unix > <B>tclsh</B> | |
1826 | % <B>load ./example.so</B> | |
1827 | % <B>fact 4</B> | |
1828 | 24 | |
1829 | % <B>my_mod 23 7</B> | |
1830 | 2 | |
1831 | % <B>expr $My_variable + 4.5</B> | |
1832 | 7.5 | |
1833 | % | |
1834 | </PRE> | |
1835 | </DIV> | |
1836 | <P> The <TT>swig</TT> command produced a new file called <TT> | |
1837 | example_wrap.c</TT> that should be compiled along with the <TT>example.c</TT> | |
1838 | file. Most operating systems and scripting languages now support | |
1839 | dynamic loading of modules. In our example, our Tcl module has been | |
1840 | compiled into a shared library that can be loaded into Tcl. When | |
1841 | loaded, Tcl can now access the functions and variables declared in the | |
1842 | SWIG interface. A look at the file <TT>example_wrap.c</TT> reveals a | |
1843 | hideous mess. However, you almost never need to worry about it.</P> | |
1844 | <H3><A name="Introduction_nn7"></A>2.3.3 Building a Perl5 module</H3> | |
1845 | <P> Now, let's turn these functions into a Perl5 module. Without making | |
1846 | any changes type the following (shown for Solaris):</P> | |
1847 | <DIV class="shell"> | |
1848 | <PRE> | |
1849 | unix > <B>swig -perl5 example.i</B> | |
1850 | unix > <B>gcc -c example.c example_wrap.c \ | |
1851 | -I/usr/local/lib/perl5/sun4-solaris/5.003/CORE</B> | |
1852 | unix > <B>ld -G example.o example_wrap.o -o example.so</B> # This is for Solaris | |
1853 | unix > <B>perl5.003 | |
1854 | use example; | |
1855 | print example::fact(4), "\n"; | |
1856 | print example::my_mod(23,7), "\n"; | |
1857 | print $example::My_variable + 4.5, "\n"; | |
1858 | <ctrl-d></B> | |
1859 | 24 | |
1860 | 2 | |
1861 | 7.5 | |
1862 | unix > | |
1863 | </PRE> | |
1864 | </DIV> | |
1865 | <H3><A name="Introduction_nn8"></A>2.3.4 Building a Python module</H3> | |
1866 | <P> Finally, let's build a module for Python (shown for Irix).</P> | |
1867 | <DIV class="shell"> | |
1868 | <PRE> | |
1869 | unix > <B>swig -python example.i</B> | |
1870 | unix > <B>gcc -c -fpic example.c example_wrap.c -I/usr/local/include/python2.0</B> | |
1871 | unix > <B>gcc -shared example.o example_wrap.o -o _example.so</B> | |
1872 | unix > <B>python</B> | |
1873 | Python 2.0 (#6, Feb 21 2001, 13:29:45) | |
1874 | [GCC egcs-2.91.66 19990314/Linux (egcs-1.1.2 release)] on linux2 | |
1875 | Type "copyright", "credits" or "license" for more information. | |
1876 | >>> <B>import example</B> | |
1877 | >>> <B>example.fact(4)</B> | |
1878 | 24 | |
1879 | >>> <B>example.my_mod(23,7)</B> | |
1880 | 2 | |
1881 | >>> <B>example.cvar.My_variable + 4.5</B> | |
1882 | 7.5 | |
1883 | </PRE> | |
1884 | </DIV> | |
1885 | <H3><A name="Introduction_nn9"></A>2.3.5 Shortcuts</H3> | |
1886 | <P> To the truly lazy programmer, one may wonder why we needed the extra | |
1887 | interface file at all. As it turns out, you can often do without it. | |
1888 | For example, you could also build a Perl5 module by just running SWIG | |
1889 | on the C header file and specifying a module name as follows</P> | |
1890 | <DIV class="shell"> | |
1891 | <PRE> | |
1892 | unix > <B>swig -perl5 -module example example.h</B> | |
1893 | unix > <B>gcc -c example.c example_wrap.c \ | |
1894 | -I/usr/local/lib/perl5/sun4-solaris/5.003/CORE</B> | |
1895 | unix > <B>ld -G example.o example_wrap.o -o example.so</B> | |
1896 | unix > <B>perl5.003 | |
1897 | use example; | |
1898 | print example::fact(4), "\n"; | |
1899 | print example::my_mod(23,7), "\n"; | |
1900 | print $example::My_variable + 4.5, "\n"; | |
1901 | <ctrl-d></B> | |
1902 | 24 | |
1903 | 2 | |
1904 | 7.5 | |
1905 | </PRE> | |
1906 | </DIV> | |
1907 | <H2><A name="Introduction_nn10"></A>2.4 Supported C/C++ language | |
1908 | features</H2> | |
1909 | <P> A primary goal of the SWIG project is to make the language binding | |
1910 | process extremely easy. Although a few simple examples have been shown, | |
1911 | SWIG is quite capable in supporting most of C++. Some of the major | |
1912 | features include:</P> | |
1913 | <UL> | |
1914 | <LI>Full C99 preprocessing.</LI> | |
1915 | <LI>All ANSI C and C++ datatypes.</LI> | |
1916 | <LI>Functions, variables, and constants.</LI> | |
1917 | <LI>Classes.</LI> | |
1918 | <LI>Single and multiple inheritance.</LI> | |
1919 | <LI>Overloaded functions and methods.</LI> | |
1920 | <LI>Overloaded operators.</LI> | |
1921 | <LI>C++ templates (including member templates, specialization, and | |
1922 | partial specialization).</LI> | |
1923 | <LI>Namespaces.</LI> | |
1924 | <LI>Variable length arguments.</LI> | |
1925 | <LI>C++ smart pointers.</LI> | |
1926 | </UL> | |
1927 | <P> Currently, the only major C++ feature not supported is nested | |
1928 | classes--a limitation that will be removed in a future release.</P> | |
1929 | <P> It is important to stress that SWIG is not a simplistic C++ lexing | |
1930 | tool like several apparently similar wrapper generation tools. SWIG not | |
1931 | only parses C++, it implements the full C++ type system and it is able | |
1932 | to understand C++ semantics. SWIG generates its wrappers with full | |
1933 | knowledge of this information. As a result, you will find SWIG to be | |
1934 | just as capable of dealing with nasty corner cases as it is in wrapping | |
1935 | simple C++ code. In fact, SWIG is able handle C++ code that stresses | |
1936 | the very limits of many C++ compilers.</P> | |
1937 | <H2><A name="Introduction_nn11"></A>2.5 Non-intrusive interface building</H2> | |
1938 | <P> When used as intended, SWIG requires minimal (if any) modification | |
1939 | to existing C or C++ code. This makes SWIG extremely easy to use with | |
1940 | existing packages and promotes software reuse and modularity. By making | |
1941 | the C/C++ code independent of the high level interface, you can change | |
1942 | the interface and reuse the code in other applications. It is also | |
1943 | possible to support different types of interfaces depending on the | |
1944 | application.</P> | |
1945 | <H2><A name="Introduction_build_system"></A>2.6 Incorporating SWIG into | |
1946 | a build system</H2> | |
1947 | <P> SWIG is a command line tool and as such can be incorporated into any | |
1948 | build system that supports invoking external tools/compilers. SWIG is | |
1949 | most commonly invoked from within a Makefile, but is also known to be | |
1950 | invoked from from popular IDEs such as Microsoft Visual Studio.</P> | |
1951 | <P> If you are using the GNU Autotools (<A href="http://www.gnu.org/software/autoconf"> | |
1952 | Autoconf</A>/ <A href="http://www.gnu.org/software/automake">Automake</A> | |
1953 | / <A href="http://www.gnu.org/software/libtool">Libtool</A>) to | |
1954 | configure SWIG use in your project, the SWIG Autoconf macros can be | |
1955 | 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"> | |
1956 | http://www.gnu.org/software/ac-archive/htmldoc/ac_pkg_swig.html</A>. The | |
1957 | <TT>ac_python_devel</TT> macro is also helpful for generating Python | |
1958 | extensions. See the <A href="http://www.gnu.org/software/ac-archive/htmldoc/index.html"> | |
1959 | Autoconf Macro Archive</A> for further information on this and other | |
1960 | Autoconf macros.</P> | |
1961 | <P> There is growing support for SWIG in some build tools, for example <A | |
1962 | href="http://www.cmake.org">CMake</A> is a cross-platform, open-source | |
1963 | build manager with built in support for SWIG. CMake can detect the SWIG | |
1964 | executable and many of the target language libraries for linking | |
1965 | against. CMake knows how to build shared libraries and loadable modules | |
1966 | on many different operating systems. This allows easy cross platform | |
1967 | SWIG development. It also can generate the custom commands necessary | |
1968 | for driving SWIG from IDE's and makefiles. All of this can be done from | |
1969 | a single cross platform input file. The following example is a CMake | |
1970 | input file for creating a python wrapper for the SWIG interface file, | |
1971 | example.i:</P> | |
1972 | <DIV class="code"> | |
1973 | <PRE> | |
1974 | ||
1975 | # This is a CMake example for Python | |
1976 | ||
1977 | FIND_PACKAGE(SWIG REQUIRED) | |
1978 | INCLUDE(${SWIG_USE_FILE}) | |
1979 | ||
1980 | FIND_PACKAGE(PythonLibs) | |
1981 | INCLUDE_DIRECTORIES(${PYTHON_INCLUDE_PATH}) | |
1982 | ||
1983 | INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}) | |
1984 | ||
1985 | SET(CMAKE_SWIG_FLAGS "") | |
1986 | ||
1987 | SET_SOURCE_FILES_PROPERTIES(example.i PROPERTIES CPLUSPLUS ON) | |
1988 | SET_SOURCE_FILES_PROPERTIES(example.i PROPERTIES SWIG_FLAGS "-includeall") | |
1989 | SWIG_ADD_MODULE(example python example.i example.cxx) | |
1990 | SWIG_LINK_LIBRARIES(example ${PYTHON_LIBRARIES}) | |
1991 | ||
1992 | </PRE> | |
1993 | </DIV> | |
1994 | <P> The above example will generate native build files such as | |
1995 | makefiles, nmake files and Visual Studio projects which will invoke | |
1996 | SWIG and compile the generated C++ files into _example.so (UNIX) or | |
1997 | _example.dll (Windows).</P> | |
1998 | <H2><A name="Introduction_nn12"></A>2.7 Hands off code generation</H2> | |
1999 | <P> SWIG is designed to produce working code that needs no | |
2000 | hand-modification (in fact, if you look at the output, you probably | |
2001 | won't want to modify it). You should think of your target language | |
2002 | interface being defined entirely by the input to SWIG, not the | |
2003 | resulting output file. While this approach may limit flexibility for | |
2004 | hard-core hackers, it allows others to forget about the low-level | |
2005 | implementation details.</P> | |
2006 | <H2><A name="Introduction_nn13"></A>2.8 SWIG and freedom</H2> | |
2007 | <P> No, this isn't a special section on the sorry state of world | |
2008 | politics. However, it may be useful to know that SWIG was written with | |
2009 | a certain "philosophy" about programming---namely that programmers are | |
2010 | smart and that tools should just stay out of their way. Because of | |
2011 | that, you will find that SWIG is extremely permissive in what it lets | |
2012 | you get away with. In fact, you can use SWIG to go well beyond | |
2013 | "shooting yourself in the foot" if dangerous programming is your goal. | |
2014 | On the other hand, this kind of freedoom may be exactly what is needed | |
2015 | to work with complicated and unusual C/C++ applications.</P> | |
2016 | <P> Ironically, the freedom that SWIG provides is countered by an | |
2017 | extremely conservative approach to code generation. At it's core, SWIG | |
2018 | tries to distill even the most advanced C++ code down to a small | |
2019 | well-defined set of interface building techniques based on ANSI C | |
2020 | programming. Because of this, you will find that SWIG interfaces can be | |
2021 | easily compiled by virtually every C/C++ compiler and that they can be | |
2022 | used on any platform. Again, this is an important part of staying out | |
2023 | of the programmer's way----the last thing any developer wants to do is | |
2024 | to spend their time debugging the output of a tool that relies on | |
2025 | non-portable or unreliable programming features.</P> | |
2026 | <HR NOSHADE> | |
2027 | <H1><A name="Windows"></A>3 Getting started on Windows</H1> | |
2028 | ||
2029 | <!-- INDEX --> | |
2030 | <DIV class="sectiontoc"> | |
2031 | <UL> | |
2032 | <LI><A href="#Windows_nn2">Installation on Windows</A> | |
2033 | <UL> | |
2034 | <LI><A href="#Windows_nn3">Windows Executable</A></LI> | |
2035 | </UL> | |
2036 | </LI> | |
2037 | <LI><A href="#examples">SWIG Windows Examples</A> | |
2038 | <UL> | |
2039 | <LI><A href="#Windows_nn5">Instructions for using the Examples with | |
2040 | Visual Studio</A> | |
2041 | <UL> | |
2042 | <LI><A href="#Windows_nn6">Python</A></LI> | |
2043 | <LI><A href="#Windows_nn7">TCL</A></LI> | |
2044 | <LI><A href="#Windows_nn8">Perl</A></LI> | |
2045 | <LI><A href="#Windows_nn9">Java</A></LI> | |
2046 | <LI><A href="#Windows_nn10">Ruby</A></LI> | |
2047 | <LI><A href="#Windows_nn11">C#</A></LI> | |
2048 | </UL> | |
2049 | </LI> | |
2050 | <LI><A href="#Windows_nn12">Instructions for using the Examples with | |
2051 | other compilers</A></LI> | |
2052 | </UL> | |
2053 | </LI> | |
2054 | <LI><A href="#Windows_nn13">SWIG on Cygwin and MinGW</A> | |
2055 | <UL> | |
2056 | <LI><A href="#swig_exe">Building swig.exe on Windows</A> | |
2057 | <UL> | |
2058 | <LI><A href="#Windows_nn15">Building swig.exe using MinGW and MSYS</A></LI> | |
2059 | <LI><A href="#Windows_nn16">Building swig.exe using Cygwin</A></LI> | |
2060 | <LI><A href="#Windows_nn17">Building swig.exe alternatives</A></LI> | |
2061 | </UL> | |
2062 | </LI> | |
2063 | <LI><A href="#examples_cygwin">Running the examples on Windows using | |
2064 | Cygwin</A></LI> | |
2065 | </UL> | |
2066 | </LI> | |
2067 | </UL> | |
2068 | </DIV> | |
2069 | <!-- INDEX --> | |
2070 | <P> This chapter describes SWIG usage on Microsoft Windows. Installing | |
2071 | SWIG and running the examples is covered as well as building the SWIG | |
2072 | executable. Usage within the Unix like environments MinGW and Cygwin is | |
2073 | also detailed.</P> | |
2074 | <H2><A name="Windows_nn2"></A>3.1 Installation on Windows</H2> | |
2075 | <P> SWIG does not come with the usual Windows type installation program, | |
2076 | however it is quite easy to get started. The main steps are:</P> | |
2077 | <UL> | |
2078 | <LI>Download the swigwin zip package from the <A href="http://www.swig.org"> | |
2079 | SWIG website</A> and unzip into a directory. This is all that needs | |
2080 | downloading for the Windows platform.</LI> | |
2081 | <LI>Set environment variables as described in the <A href="#examples"> | |
2082 | SWIG Windows Examples</A> section in order to run examples using Visual | |
2083 | C++.</LI> | |
2084 | </UL> | |
2085 | <H3><A name="Windows_nn3"></A>3.1.1 Windows Executable</H3> | |
2086 | <P> The swigwin distribution contains the SWIG Windows executable, | |
2087 | swig.exe, which will run on 32 bit versions of Windows, ie Windows | |
2088 | 95/98/ME/NT/2000/XP. If you want to build your own swig.exe have a look | |
2089 | at <A href="#swig_exe">Building swig.exe on Windows</A>.</P> | |
2090 | <H2><A name="examples"></A>3.2 SWIG Windows Examples</H2> | |
2091 | <P> Using Microsoft Visual C++ is the most common approach to compiling | |
2092 | and linking SWIG's output. The Examples directory has a few Visual C++ | |
2093 | project files (.dsp files). These were produced by Visual C++ 6, | |
2094 | although they should also work in Visual C++ 5. Later versions of | |
2095 | Visual Studio should also be able to open and convert these project | |
2096 | files. The C# examples come with .NET 2003 solution (.sln) and project | |
2097 | files instead of Visual C++ 6 project files. The project files have | |
2098 | been set up to execute SWIG in a custom build rule for the SWIG | |
2099 | interface (.i) file. Alternatively run the <A href="#examples_cygwin"> | |
2100 | examples using Cygwin</A>.</P> | |
2101 | <P> More information on each of the examples is available with the | |
2102 | examples distributed with SWIG (Examples/index.html).</P> | |
2103 | <H3><A name="Windows_nn5"></A>3.2.1 Instructions for using the Examples | |
2104 | with Visual Studio</H3> | |
2105 | <P> Ensure the SWIG executable is as supplied in the SWIG root directory | |
2106 | in order for the examples to work. Most languages require some | |
2107 | environment variables to be set<B> before</B> running Visual C++. Note | |
2108 | that Visual C++ must be re-started to pick up any changes in | |
2109 | environment variables. Open up an example .dsp file, Visual C++ will | |
2110 | create a workspace for you (.dsw file). Ensure the Release build is | |
2111 | selected then do a Rebuild All from the Build menu. The required | |
2112 | environment variables are displayed with their current values.</P> | |
2113 | <P> The list of required environment variables for each module language | |
2114 | is also listed below. They are usually set from the Control Panel and | |
2115 | System properties, but this depends on which flavour of Windows you are | |
2116 | running. If you don't want to use environment variables then change all | |
2117 | occurences of the environment variables in the .dsp files with hard | |
2118 | coded values. If you are interested in how the project files are set up | |
2119 | there is explanatory information in some of the language module's | |
2120 | documentation.</P> | |
2121 | <H4><A name="Windows_nn6"></A>3.2.1.1 Python</H4> | |
2122 | <P><B> <TT>PYTHON_INCLUDE</TT></B> : Set this to the directory that | |
2123 | contains python.h | |
2124 | <BR><B> <TT>PYTHON_LIB</TT></B> : Set this to the python library | |
2125 | including path for linking</P> | |
2126 | <P> Example using Python 2.1.1: | |
2127 | <BR> <TT>PYTHON_INCLUDE: d:\python21\include | |
2128 | <BR> PYTHON_LIB: d:\python21\libs\python21.lib | |
2129 | <BR></TT></P> | |
2130 | <H4><A name="Windows_nn7"></A>3.2.1.2 TCL</H4> | |
2131 | <P><B> <TT>TCL_INCLUDE</TT></B> : Set this to the directory containing | |
2132 | tcl.h | |
2133 | <BR><B> <TT>TCL_LIB</TT></B> : Set this to the TCL library including | |
2134 | path for linking</P> | |
2135 | <P> Example using ActiveTcl 8.3.3.3 | |
2136 | <BR> <TT>TCL_INCLUDE: d:\tcl\include | |
2137 | <BR> TCL_LIB: d:\tcl\lib\tcl83.lib | |
2138 | <BR></TT></P> | |
2139 | <H4><A name="Windows_nn8"></A>3.2.1.3 Perl</H4> | |
2140 | <P><B> <TT>PERL5_INCLUDE</TT></B> : Set this to the directory containing | |
2141 | perl.h | |
2142 | <BR><B> <TT>PERL5_LIB</TT></B> : Set this to the Perl library including | |
2143 | path for linking</P> | |
2144 | <P> Example using nsPerl 5.004_04:</P> | |
2145 | <P> <TT>PERL5_INCLUDE: D:\nsPerl5.004_04\lib\CORE | |
2146 | <BR> PERL5_LIB: D:\nsPerl5.004_04\lib\CORE\perl.lib | |
2147 | <BR></TT></P> | |
2148 | <H4><A name="Windows_nn9"></A>3.2.1.4 Java</H4> | |
2149 | <P><B> <TT>JAVA_INCLUDE</TT></B> : Set this to the directory containing | |
2150 | jni.h | |
2151 | <BR><B> <TT>JAVA_BIN</TT></B> : Set this to the bin directory containing | |
2152 | javac.exe</P> | |
2153 | <P> Example using JDK1.3: | |
2154 | <BR> <TT>JAVA_INCLUDE: d:\jdk1.3\include | |
2155 | <BR> JAVA_BIN: d:\jdk1.3\bin | |
2156 | <BR></TT></P> | |
2157 | <H4><A name="Windows_nn10"></A>3.2.1.5 Ruby</H4> | |
2158 | <P><B> <TT>RUBY_INCLUDE</TT></B> : Set this to the directory containing | |
2159 | ruby.h | |
2160 | <BR><B> <TT>RUBY_LIB</TT></B> : Set this to the ruby library including | |
2161 | path for linking</P> | |
2162 | <P> Example using Ruby 1.6.4: | |
2163 | <BR> <TT>RUBY_INCLUDE: D:\ruby\lib\ruby\1.6\i586-mswin32 | |
2164 | <BR> RUBY_LIB: D:\ruby\lib\mswin32-ruby16.lib | |
2165 | <BR></TT></P> | |
2166 | <H4><A name="Windows_nn11"></A>3.2.1.6 C#</H4> | |
2167 | <P> The C# examples do not require any environment variables to be set | |
2168 | as a C# project file is included. Just open up the .sln solution file | |
2169 | in Visual Studio .NET 2003 and do a Rebuild All from the Build menu. | |
2170 | The accompanying C# and C++ project file are automatically used by the | |
2171 | solution file.</P> | |
2172 | <H3><A name="Windows_nn12"></A>3.2.2 Instructions for using the Examples | |
2173 | with other compilers</H3> | |
2174 | <P> If you do not have access to Visual C++ you will have to set up | |
2175 | project files / Makefiles for your chosen compiler. There is a section | |
2176 | in each of the language modules detailing what needs setting up using | |
2177 | Visual C++ which may be of some guidance. Alternatively you may want to | |
2178 | use Cygwin as described in the following section.</P> | |
2179 | <H2><A name="Windows_nn13"></A>3.3 SWIG on Cygwin and MinGW</H2> | |
2180 | <P> SWIG can also be compiled and run using <A href="http://www.cygwin.com"> | |
2181 | Cygwin</A> or <A href="http://www.mingw.org">MinGW</A> which provides a | |
2182 | Unix like front end to Windows and comes free with gcc, an ANSI C/C++ | |
2183 | compiler. However, this is not a recommended approach as the prebuilt | |
2184 | executable is supplied.</P> | |
2185 | <H3><A name="swig_exe"></A>3.3.1 Building swig.exe on Windows</H3> | |
2186 | <P> If you want to replicate the build of swig.exe that comes with the | |
2187 | download, follow the MinGW instructions below. This is not necessary to | |
2188 | use the supplied swig.exe. This information is provided for those that | |
2189 | want to modify the SWIG source code in a Windows environment. Normally | |
2190 | this is not needed, so most people will want to ignore this section.</P> | |
2191 | <H4><A name="Windows_nn15"></A>3.3.1.1 Building swig.exe using MinGW and | |
2192 | MSYS</H4> | |
2193 | <UL> | |
2194 | <LI>Install MinGW and MSYS from the <A href="http://www.mingw.org">MinGW</A> | |
2195 | site. This provides a Unix environment on Windows.</LI> | |
2196 | <LI>Follow the usual Unix instructions in the README file in the SWIG | |
2197 | root directory to build swig.exe from the MinGW command prompt.</LI> | |
2198 | </UL> | |
2199 | <H4><A name="Windows_nn16"></A>3.3.1.2 Building swig.exe using Cygwin</H4> | |
2200 | <P> Note that SWIG can also be built using Cygwin. However, the SWIG | |
2201 | will then require the Cygwin DLL when executing. Follow the Unix | |
2202 | instructions in the README file in the SWIG root directory. Note that | |
2203 | the Cygwin environment will also allow one to regenerate the autotool | |
2204 | generated files which are supplied with the release distribution. These | |
2205 | files are generated using the <TT>autogen.sh</TT> script and will only | |
2206 | need regenerating in circumstances such as changing the build system.</P> | |
2207 | <H4><A name="Windows_nn17"></A>3.3.1.3 Building swig.exe alternatives</H4> | |
2208 | <P> If you don't want to install Cygwin or MinGW, use a different | |
2209 | compiler to build SWIG. For example, all the source code files can be | |
2210 | added to a Visual C++ project file in order to build swig.exe from the | |
2211 | Visual C++ IDE.</P> | |
2212 | <H3><A name="examples_cygwin"></A>3.3.2 Running the examples on Windows | |
2213 | using Cygwin</H3> | |
2214 | <P> The examples and test-suite work as successfully on Cygwin as on any | |
2215 | other Unix operating system. The modules which are known to work are | |
2216 | Python, Tcl, Perl, Ruby, Java and C#. Follow the Unix instructions in | |
2217 | the README file in the SWIG root directory to build the examples.</P> | |
2218 | <HR NOSHADE> | |
2219 | <H1><A name="Scripting"></A>4 Scripting Languages</H1> | |
2220 | ||
2221 | <!-- INDEX --> | |
2222 | <DIV class="sectiontoc"> | |
2223 | <UL> | |
2224 | <LI><A href="#Scripting_nn2">The two language view of the world</A></LI> | |
2225 | <LI><A href="#Scripting_nn3">How does a scripting language talk to C?</A> | |
2226 | <UL> | |
2227 | <LI><A href="#Scripting_nn4">Wrapper functions</A></LI> | |
2228 | <LI><A href="#Scripting_nn5">Variable linking</A></LI> | |
2229 | <LI><A href="#Scripting_nn6">Constants</A></LI> | |
2230 | <LI><A href="#Scripting_nn7">Structures and classes</A></LI> | |
2231 | <LI><A href="#Scripting_nn8">Proxy classes</A></LI> | |
2232 | </UL> | |
2233 | </LI> | |
2234 | <LI><A href="#Scripting_nn9">Building scripting language extensions</A> | |
2235 | <UL> | |
2236 | <LI><A href="#Scripting_nn10">Shared libraries and dynamic loading</A></LI> | |
2237 | <LI><A href="#Scripting_nn11">Linking with shared libraries</A></LI> | |
2238 | <LI><A href="#Scripting_nn12">Static linking</A></LI> | |
2239 | </UL> | |
2240 | </LI> | |
2241 | </UL> | |
2242 | </DIV> | |
2243 | <!-- INDEX --> | |
2244 | <P> This chapter provides a brief overview of scripting language | |
2245 | extension programming and the mechanisms by which scripting language | |
2246 | interpreters access C and C++ code.</P> | |
2247 | <H2><A name="Scripting_nn2"></A>4.1 The two language view of the world</H2> | |
2248 | <P> When a scripting language is used to control a C program, the | |
2249 | resulting system tends to look as follows:</P> | |
2250 | <CENTER><IMG alt="Scripting language input - C/C++ functions output" HEIGHT="149" | |
2251 | src="ch2.1.png" WIDTH="377"></CENTER> | |
2252 | <P> In this programming model, the scripting language interpreter is | |
2253 | used for high level control whereas the underlying functionality of the | |
2254 | C/C++ program is accessed through special scripting language | |
2255 | "commands." If you have ever tried to write your own simple command | |
2256 | interpreter, you might view the scripting language approach to be a | |
2257 | highly advanced implementation of that. Likewise, If you have ever used | |
2258 | a package such as MATLAB or IDL, it is a very similar model--the | |
2259 | interpreter executes user commands and scripts. However, most of the | |
2260 | underlying functionality is written in a low-level language like C or | |
2261 | Fortran.</P> | |
2262 | <P> The two-language model of computing is extremely powerful because it | |
2263 | exploits the strengths of each language. C/C++ can be used for maximal | |
2264 | performance and complicated systems programming tasks. Scripting | |
2265 | languages can be used for rapid prototyping, interactive debugging, | |
2266 | scripting, and access to high-level data structures such associative | |
2267 | arrays.</P> | |
2268 | <H2><A name="Scripting_nn3"></A>4.2 How does a scripting language talk | |
2269 | to C?</H2> | |
2270 | <P> Scripting languages are built around a parser that knows how to | |
2271 | execute commands and scripts. Within this parser, there is a mechanism | |
2272 | for executing commands and accessing variables. Normally, this is used | |
2273 | to implement the builtin features of the language. However, by | |
2274 | extending the interpreter, it is usually possible to add new commands | |
2275 | and variables. To do this, most languages define a special API for | |
2276 | adding new commands. Furthermore, a special foreign function interface | |
2277 | defines how these new commands are supposed to hook into the | |
2278 | interpreter.</P> | |
2279 | <P> Typically, when you add a new command to a scripting interpreter you | |
2280 | need to do two things; first you need to write a special "wrapper" | |
2281 | function that serves as the glue between the interpreter and the | |
2282 | underlying C function. Then you need to give the interpreter | |
2283 | information about the wrapper by providing details about the name of | |
2284 | the function, arguments, and so forth. The next few sections illustrate | |
2285 | the process.</P> | |
2286 | <H3><A name="Scripting_nn4"></A>4.2.1 Wrapper functions</H3> | |
2287 | <P> Suppose you have an ordinary C function like this :</P> | |
2288 | <DIV class="code"> | |
2289 | <PRE> | |
2290 | int fact(int n) { | |
2291 | if (n <= 1) return 1; | |
2292 | else return n*fact(n-1); | |
2293 | } | |
2294 | </PRE> | |
2295 | </DIV> | |
2296 | <P> In order to access this function from a scripting language, it is | |
2297 | necessary to write a special "wrapper" function that serves as the glue | |
2298 | between the scripting language and the underlying C function. A wrapper | |
2299 | function must do three things :</P> | |
2300 | <UL> | |
2301 | <LI>Gather function arguments and make sure they are valid.</LI> | |
2302 | <LI>Call the C function.</LI> | |
2303 | <LI>Convert the return value into a form recognized by the scripting | |
2304 | language.</LI> | |
2305 | </UL> | |
2306 | <P> As an example, the Tcl wrapper function for the <TT>fact()</TT> | |
2307 | function above example might look like the following :</P> | |
2308 | <DIV class="code"> | |
2309 | <PRE> | |
2310 | int wrap_fact(ClientData clientData, Tcl_Interp *interp, | |
2311 | int argc, char *argv[]) { | |
2312 | int result; | |
2313 | int arg0; | |
2314 | if (argc != 2) { | |
2315 | interp->result = "wrong # args"; | |
2316 | return TCL_ERROR; | |
2317 | } | |
2318 | arg0 = atoi(argv[1]); | |
2319 | result = fact(arg0); | |
2320 | sprintf(interp->result,"%d", result); | |
2321 | return TCL_OK; | |
2322 | } | |
2323 | ||
2324 | </PRE> | |
2325 | </DIV> | |
2326 | <P> Once you have created a wrapper function, the final step is to tell | |
2327 | the scripting language about the new function. This is usually done in | |
2328 | an initialization function called by the language when the module is | |
2329 | loaded. For example, adding the above function to the Tcl interpreter | |
2330 | requires code like the following :</P> | |
2331 | <DIV class="code"> | |
2332 | <PRE> | |
2333 | int Wrap_Init(Tcl_Interp *interp) { | |
2334 | Tcl_CreateCommand(interp, "fact", wrap_fact, (ClientData) NULL, | |
2335 | (Tcl_CmdDeleteProc *) NULL); | |
2336 | return TCL_OK; | |
2337 | } | |
2338 | </PRE> | |
2339 | </DIV> | |
2340 | <P> When executed, Tcl will now have a new command called "<TT>fact</TT> | |
2341 | " that you can use like any other Tcl command.</P> | |
2342 | <P> Although the process of adding a new function to Tcl has been | |
2343 | illustrated, the procedure is almost identical for Perl and Python. | |
2344 | Both require special wrappers to be written and both need additional | |
2345 | initialization code. Only the specific details are different.</P> | |
2346 | <H3><A name="Scripting_nn5"></A>4.2.2 Variable linking</H3> | |
2347 | <P> Variable linking refers to the problem of mapping a C/C++ global | |
2348 | variable to a variable in the scripting language interpeter. For | |
2349 | example, suppose you had the following variable:</P> | |
2350 | <DIV class="code"> | |
2351 | <PRE> | |
2352 | double Foo = 3.5; | |
2353 | </PRE> | |
2354 | </DIV> | |
2355 | <P> It might be nice to access it from a script as follows (shown for | |
2356 | Perl):</P> | |
2357 | <DIV class="targetlang"> | |
2358 | <PRE> | |
2359 | $a = $Foo * 2.3; # Evaluation | |
2360 | $Foo = $a + 2.0; # Assignment | |
2361 | </PRE> | |
2362 | </DIV> | |
2363 | <P> To provide such access, variables are commonly manipulated using a | |
2364 | pair of get/set functions. For example, whenever the value of a | |
2365 | variable is read, a "get" function is invoked. Similarly, whenever the | |
2366 | value of a variable is changed, a "set" function is called.</P> | |
2367 | <P> In many languages, calls to the get/set functions can be attached to | |
2368 | evaluation and assignment operators. Therefore, evaluating a variable | |
2369 | such as <TT>$Foo</TT> might implicitly call the get function. | |
2370 | Similarly, typing <TT>$Foo = 4</TT> would call the underlying set | |
2371 | function to change the value.</P> | |
2372 | <H3><A name="Scripting_nn6"></A>4.2.3 Constants</H3> | |
2373 | <P> In many cases, a C program or library may define a large collection | |
2374 | of constants. For example:</P> | |
2375 | <DIV class="code"> | |
2376 | <PRE> | |
2377 | #define RED 0xff0000 | |
2378 | #define BLUE 0x0000ff | |
2379 | #define GREEN 0x00ff00 | |
2380 | </PRE> | |
2381 | </DIV> | |
2382 | <P> To make constants available, their values can be stored in scripting | |
2383 | language variables such as <TT>$RED</TT>, <TT>$BLUE</TT>, and <TT> | |
2384 | $GREEN</TT>. Virtually all scripting languages provide C functions for | |
2385 | creating variables so installing constants is usually a trivial | |
2386 | exercise.</P> | |
2387 | <H3><A name="Scripting_nn7"></A>4.2.4 Structures and classes</H3> | |
2388 | <P> Although scripting languages have no trouble accessing simple | |
2389 | functions and variables, accessing C/C++ structures and classes present | |
2390 | a different problem. This is because the implementation of structures | |
2391 | is largely related to the problem of data representation and layout. | |
2392 | Furthermore, certain language features are difficult to map to an | |
2393 | interpreter. For instance, what does C++ inheritance mean in a Perl | |
2394 | interface?</P> | |
2395 | <P> The most straightforward technique for handling structures is to | |
2396 | implement a collection of accessor functions that hide the underlying | |
2397 | representation of a structure. For example,</P> | |
2398 | <DIV class="code"> | |
2399 | <PRE> | |
2400 | struct Vector { | |
2401 | Vector(); | |
2402 | ~Vector(); | |
2403 | double x,y,z; | |
2404 | }; | |
2405 | ||
2406 | </PRE> | |
2407 | </DIV> | |
2408 | <P> can be transformed into the following set of functions :</P> | |
2409 | <DIV class="code"> | |
2410 | <PRE> | |
2411 | Vector *new_Vector(); | |
2412 | void delete_Vector(Vector *v); | |
2413 | double Vector_x_get(Vector *v); | |
2414 | double Vector_y_get(Vector *v); | |
2415 | double Vector_z_get(Vector *v); | |
2416 | void Vector_x_set(Vector *v, double x); | |
2417 | void Vector_y_set(Vector *v, double y); | |
2418 | void Vector_z_set(Vector *v, double z); | |
2419 | ||
2420 | </PRE> | |
2421 | </DIV> | |
2422 | <P> Now, from an interpreter these function might be used as follows:</P> | |
2423 | <DIV class="targetlang"> | |
2424 | <PRE> | |
2425 | % set v [new_Vector] | |
2426 | % Vector_x_set $v 3.5 | |
2427 | % Vector_y_get $v | |
2428 | % delete_Vector $v | |
2429 | % ... | |
2430 | </PRE> | |
2431 | </DIV> | |
2432 | <P> Since accessor functions provide a mechanism for accessing the | |
2433 | internals of an object, the interpreter does not need to know anything | |
2434 | about the actual representation of a <TT>Vector</TT>.</P> | |
2435 | <H3><A name="Scripting_nn8"></A>4.2.5 Proxy classes</H3> | |
2436 | <P> In certain cases, it is possible to use the low-level accessor | |
2437 | functions to create a proxy class, also known as a shadow class. A | |
2438 | proxy class is a special kind of object that gets created in a | |
2439 | scripting language to access a C/C++ class (or struct) in a way that | |
2440 | looks like the original structure (that is, it proxies the real C++ | |
2441 | class). For example, if you have the following C definition :</P> | |
2442 | <DIV class="code"> | |
2443 | <PRE> | |
2444 | class Vector { | |
2445 | public: | |
2446 | Vector(); | |
2447 | ~Vector(); | |
2448 | double x,y,z; | |
2449 | }; | |
2450 | </PRE> | |
2451 | </DIV> | |
2452 | <P> A proxy classing mechanism would allow you to access the structure | |
2453 | in a more natural manner from the interpreter. For example, in Python, | |
2454 | you might want to do this:</P> | |
2455 | <DIV class="targetlang"> | |
2456 | <PRE> | |
2457 | >>> v = Vector() | |
2458 | >>> v.x = 3 | |
2459 | >>> v.y = 4 | |
2460 | >>> v.z = -13 | |
2461 | >>> ... | |
2462 | >>> del v | |
2463 | </PRE> | |
2464 | </DIV> | |
2465 | <P> Similarly, in Perl5 you may want the interface to work like this:</P> | |
2466 | <DIV class="targetlang"> | |
2467 | <PRE> | |
2468 | $v = new Vector; | |
2469 | $v->{x} = 3; | |
2470 | $v->{y} = 4; | |
2471 | $v->{z} = -13; | |
2472 | ||
2473 | </PRE> | |
2474 | </DIV> | |
2475 | <P> Finally, in Tcl :</P> | |
2476 | <DIV class="targetlang"> | |
2477 | <PRE> | |
2478 | Vector v | |
2479 | v configure -x 3 -y 4 -z 13 | |
2480 | ||
2481 | </PRE> | |
2482 | </DIV> | |
2483 | <P> When proxy classes are used, two objects are at really work--one in | |
2484 | the scripting language, and an underlying C/C++ object. Operations | |
2485 | affect both objects equally and for all practical purposes, it appears | |
2486 | as if you are simply manipulating a C/C++ object.</P> | |
2487 | <H2><A name="Scripting_nn9"></A>4.3 Building scripting language | |
2488 | extensions</H2> | |
2489 | <P> The final step in using a scripting language with your C/C++ | |
2490 | application is adding your extensions to the scripting language itself. | |
2491 | There are two primary approaches for doing this. The preferred | |
2492 | technique is to build a dynamically loadable extension in the form a | |
2493 | shared library. Alternatively, you can recompile the scripting language | |
2494 | interpreter with your extensions added to it.</P> | |
2495 | <H3><A name="Scripting_nn10"></A>4.3.1 Shared libraries and dynamic | |
2496 | loading</H3> | |
2497 | <P> To create a shared library or DLL, you often need to look at the | |
2498 | manual pages for your compiler and linker. However, the procedure for a | |
2499 | few common machines is shown below:</P> | |
2500 | <DIV class="shell"> | |
2501 | <PRE> | |
2502 | # Build a shared library for Solaris | |
2503 | gcc -c example.c example_wrap.c -I/usr/local/include | |
2504 | ld -G example.o example_wrap.o -o example.so | |
2505 | ||
2506 | # Build a shared library for Linux | |
2507 | gcc -fpic -c example.c example_wrap.c -I/usr/local/include | |
2508 | gcc -shared example.o example_wrap.o -o example.so | |
2509 | ||
2510 | # Build a shared library for Irix | |
2511 | gcc -c example.c example_wrap.c -I/usr/local/include | |
2512 | ld -shared example.o example_wrap.o -o example.so | |
2513 | ||
2514 | </PRE> | |
2515 | </DIV> | |
2516 | <P> To use your shared library, you simply use the corresponding command | |
2517 | in the scripting language (load, import, use, etc...). This will import | |
2518 | your module and allow you to start using it. For example:</P> | |
2519 | <DIV class="targetlang"> | |
2520 | <PRE> | |
2521 | % load ./example.so | |
2522 | % fact 4 | |
2523 | 24 | |
2524 | % | |
2525 | </PRE> | |
2526 | </DIV> | |
2527 | <P> When working with C++ codes, the process of building shared | |
2528 | libraries may be more complicated--primarily due to the fact that C++ | |
2529 | modules may need additional code in order to operate correctly. On many | |
2530 | machines, you can build a shared C++ module by following the above | |
2531 | procedures, but changing the link line to the following :</P> | |
2532 | <DIV class="shell"> | |
2533 | <PRE> | |
2534 | c++ -shared example.o example_wrap.o -o example.so | |
2535 | </PRE> | |
2536 | </DIV> | |
2537 | <H3><A name="Scripting_nn11"></A>4.3.2 Linking with shared libraries</H3> | |
2538 | <P> When building extensions as shared libraries, it is not uncommon for | |
2539 | your extension to rely upon other shared libraries on your machine. In | |
2540 | order for the extension to work, it needs to be able to find all of | |
2541 | these libraries at run-time. Otherwise, you may get an error such as | |
2542 | the following :</P> | |
2543 | <DIV class="targetlang"> | |
2544 | <PRE> | |
2545 | >>> import graph | |
2546 | Traceback (innermost last): | |
2547 | File "<stdin>", line 1, in ? | |
2548 | File "/home/sci/data1/beazley/graph/graph.py", line 2, in ? | |
2549 | import graphc | |
2550 | ImportError: 1101:/home/sci/data1/beazley/bin/python: rld: Fatal Error: cannot | |
2551 | successfully map soname 'libgraph.so' under any of the filenames /usr/lib/libgraph.so:/ | |
2552 | lib/libgraph.so:/lib/cmplrs/cc/libgraph.so:/usr/lib/cmplrs/cc/libgraph.so: | |
2553 | >>> | |
2554 | </PRE> | |
2555 | </DIV> | |
2556 | <P> What this error means is that the extension module created by SWIG | |
2557 | depends upon a shared library called "<TT>libgraph.so</TT>" that the | |
2558 | system was unable to locate. To fix this problem, there are a few | |
2559 | approaches you can take.</P> | |
2560 | <UL> | |
2561 | <LI>Link your extension and explicitly tell the linker where the | |
2562 | required libraries are located. Often times, this can be done with a | |
2563 | special linker flag such as <TT>-R</TT>, <TT>-rpath</TT>, etc. This is | |
2564 | not implemented in a standard manner so read the man pages for your | |
2565 | linker to find out more about how to set the search path for shared | |
2566 | libraries.</LI> | |
2567 | <LI>Put shared libraries in the same directory as the executable. This | |
2568 | technique is sometimes required for correct operation on non-Unix | |
2569 | platforms.</LI> | |
2570 | <LI>Set the UNIX environment variable <TT>LD_LIBRARY_PATH</TT> to the | |
2571 | directory where shared libraries are located before running Python. | |
2572 | Although this is an easy solution, it is not recommended. Consider | |
2573 | setting the path using linker options instead.</LI> | |
2574 | </UL> | |
2575 | <H3><A name="Scripting_nn12"></A>4.3.3 Static linking</H3> | |
2576 | <P> With static linking, you rebuild the scripting language interpreter | |
2577 | with extensions. The process usually involves compiling a short main | |
2578 | program that adds your customized commands to the language and starts | |
2579 | the interpreter. You then link your program with a library to produce a | |
2580 | new scripting language executable.</P> | |
2581 | <P> Although static linking is supported on all platforms, this is not | |
2582 | the preferred technique for building scripting language extensions. In | |
2583 | fact, there are very few practical reasons for doing this--consider | |
2584 | using shared libraries instead.</P> | |
2585 | <HR NOSHADE> | |
2586 | <H1><A name="SWIG"></A>5 SWIG Basics</H1> | |
2587 | ||
2588 | <!-- INDEX --> | |
2589 | <DIV class="sectiontoc"> | |
2590 | <UL> | |
2591 | <LI><A href="#SWIG_nn2">Running SWIG</A> | |
2592 | <UL> | |
2593 | <LI><A href="#SWIG_nn3">Input format</A></LI> | |
2594 | <LI><A href="#output">SWIG Output</A></LI> | |
2595 | <LI><A href="#SWIG_nn5">Comments</A></LI> | |
2596 | <LI><A href="#SWIG_nn6">C Preprocessor</A></LI> | |
2597 | <LI><A href="#SWIG_nn7">SWIG Directives</A></LI> | |
2598 | <LI><A href="#SWIG_nn8">Parser Limitations</A></LI> | |
2599 | </UL> | |
2600 | </LI> | |
2601 | <LI><A href="#SWIG_nn9">Wrapping Simple C Declarations</A> | |
2602 | <UL> | |
2603 | <LI><A href="#SWIG_nn10">Basic Type Handling</A></LI> | |
2604 | <LI><A href="#SWIG_nn11">Global Variables</A></LI> | |
2605 | <LI><A href="#SWIG_nn12">Constants</A></LI> | |
2606 | <LI><A href="#SWIG_nn13">A brief word about <TT>const</TT></A></LI> | |
2607 | <LI><A href="#SWIG_nn14">A cautionary tale of <TT>char *</TT></A></LI> | |
2608 | </UL> | |
2609 | </LI> | |
2610 | <LI><A href="#SWIG_nn15">Pointers and complex objects</A> | |
2611 | <UL> | |
2612 | <LI><A href="#SWIG_nn16">Simple pointers</A></LI> | |
2613 | <LI><A href="#SWIG_nn17">Run time pointer type checking</A></LI> | |
2614 | <LI><A href="#SWIG_nn18">Derived types, structs, and classes</A></LI> | |
2615 | <LI><A href="#SWIG_nn19">Undefined datatypes</A></LI> | |
2616 | <LI><A href="#SWIG_nn20">Typedef</A></LI> | |
2617 | </UL> | |
2618 | </LI> | |
2619 | <LI><A href="#SWIG_nn21">Other Practicalities</A> | |
2620 | <UL> | |
2621 | <LI><A href="#SWIG_nn22">Passing structures by value</A></LI> | |
2622 | <LI><A href="#SWIG_nn23">Return by value</A></LI> | |
2623 | <LI><A href="#SWIG_nn24">Linking to structure variables</A></LI> | |
2624 | <LI><A href="#SWIG_nn25">Linking to <TT>char *</TT></A></LI> | |
2625 | <LI><A href="#SWIG_nn26">Arrays</A></LI> | |
2626 | <LI><A href="#SWIG_readonly_variables">Creating read-only variables</A></LI> | |
2627 | <LI><A href="#SWIG_nn28">Renaming and ignoring declarations</A></LI> | |
2628 | <LI><A href="#SWIG_default_args">Default/optional arguments</A></LI> | |
2629 | <LI><A href="#SWIG_nn30">Pointers to functions and callbacks</A></LI> | |
2630 | </UL> | |
2631 | </LI> | |
2632 | <LI><A href="#SWIG_nn31">Structures and unions</A> | |
2633 | <UL> | |
2634 | <LI><A href="#SWIG_nn32">Typedef and structures</A></LI> | |
2635 | <LI><A href="#SWIG_nn33">Character strings and structures</A></LI> | |
2636 | <LI><A href="#SWIG_nn34">Array members</A></LI> | |
2637 | <LI><A href="#SWIG_nn35">Structure data members</A></LI> | |
2638 | <LI><A href="#SWIG_nn36">C constructors and destructors</A></LI> | |
2639 | <LI><A href="#SWIG_adding_member_functions">Adding member functions to C | |
2640 | structures</A></LI> | |
2641 | <LI><A href="#SWIG_nn38">Nested structures</A></LI> | |
2642 | <LI><A href="#SWIG_nn39">Other things to note about structure wrapping</A> | |
2643 | </LI> | |
2644 | </UL> | |
2645 | </LI> | |
2646 | <LI><A href="#SWIG_nn40">Code Insertion</A> | |
2647 | <UL> | |
2648 | <LI><A href="#SWIG_nn41">The output of SWIG</A></LI> | |
2649 | <LI><A href="#SWIG_nn42">Code insertion blocks</A></LI> | |
2650 | <LI><A href="#SWIG_nn43">Inlined code blocks</A></LI> | |
2651 | <LI><A href="#SWIG_nn44">Initialization blocks</A></LI> | |
2652 | </UL> | |
2653 | </LI> | |
2654 | <LI><A href="#SWIG_nn45">An Interface Building Strategy</A> | |
2655 | <UL> | |
2656 | <LI><A href="#SWIG_nn46">Preparing a C program for SWIG</A></LI> | |
2657 | <LI><A href="#SWIG_nn47">The SWIG interface file</A></LI> | |
2658 | <LI><A href="#SWIG_nn48">Why use separate interface files?</A></LI> | |
2659 | <LI><A href="#SWIG_nn49">Getting the right header files</A></LI> | |
2660 | <LI><A href="#SWIG_nn50">What to do with main()</A></LI> | |
2661 | </UL> | |
2662 | </LI> | |
2663 | </UL> | |
2664 | </DIV> | |
2665 | <!-- INDEX --> | |
2666 | <P> This chapter describes the basic operation of SWIG, the structure of | |
2667 | its input files, and how it handles standard ANSI C declarations. C++ | |
2668 | support is described in the next chapter. However, C++ programmers | |
2669 | should still read this chapter to understand the basics. Specific | |
2670 | details about each target language are described in later chapters.</P> | |
2671 | <H2><A name="SWIG_nn2"></A>5.1 Running SWIG</H2> | |
2672 | <P> To run SWIG, use the <TT>swig</TT> command with one or more of the | |
2673 | following options and a filename like this:</P> | |
2674 | <DIV class="shell"> | |
2675 | <PRE> | |
2676 | swig [ <EM>options</EM> ] filename | |
2677 | ||
2678 | -chicken Generate CHICKEN wrappers | |
2679 | -csharp Generate C# wrappers | |
2680 | -guile Generate Guile wrappers | |
2681 | -java Generate Java wrappers | |
2682 | -mzscheme Generate Mzscheme wrappers | |
2683 | -ocaml Generate Ocaml wrappers | |
2684 | -perl Generate Perl wrappers | |
2685 | -php Generate PHP wrappers | |
2686 | -pike Generate Pike wrappers | |
2687 | -python Generate Python wrappers | |
2688 | -ruby Generate Ruby wrappers | |
2689 | -sexp Generate Lisp S-Expressions wrappers | |
2690 | -tcl Generate Tcl wrappers | |
2691 | -xml Generate XML wrappers | |
2692 | -c++ Enable C++ parsing | |
2693 | -D<EM>symbol</EM> Define a preprocessor symbol | |
2694 | -Fstandard Display error/warning messages in commonly used format | |
2695 | -Fmicrosoft Display error/warning messages in Microsoft format | |
2696 | -help Display all options | |
2697 | -I<EM>dir</EM> Add a directory to the file include path | |
2698 | -l<EM>file</EM> Include a SWIG library file. | |
2699 | -module <EM>name</EM> Set the name of the SWIG module | |
2700 | -o <EM>outfile</EM> Name of output file | |
2701 | -outdir <EM>dir</EM> Set language specific files output directory | |
2702 | -swiglib Show location of SWIG library | |
2703 | -version Show SWIG version number | |
2704 | ||
2705 | </PRE> | |
2706 | </DIV> | |
2707 | <P> This is a subset of commandline options. Additional options are also | |
2708 | defined for each target language. A full list can be obtained by typing | |
2709 | <TT>swig -help</TT> or <TT>swig -<EM>lang</EM> -help</TT>.</P> | |
2710 | <H3><A name="SWIG_nn3"></A>5.1.1 Input format</H3> | |
2711 | <P> As input, SWIG expects a file containing ANSI C/C++ declarations and | |
2712 | special SWIG directives. More often than not, this is a special SWIG | |
2713 | interface file which is usually denoted with a special <TT>.i</TT> or <TT> | |
2714 | .swg</TT> suffix. In certain cases, SWIG can be used directly on raw | |
2715 | header files or source files. However, this is not the most typical | |
2716 | case and there are several reasons why you might not want to do this | |
2717 | (described later).</P> | |
2718 | <P> The most common format of a SWIG interface is as follows:</P> | |
2719 | <DIV class="code"> | |
2720 | <PRE> | |
2721 | %module mymodule | |
2722 | %{ | |
2723 | #include "myheader.h" | |
2724 | %} | |
2725 | // Now list ANSI C/C++ declarations | |
2726 | int foo; | |
2727 | int bar(int x); | |
2728 | ... | |
2729 | </PRE> | |
2730 | </DIV> | |
2731 | <P> The name of the module is supplied using the special <TT>%module</TT> | |
2732 | directive (or the <TT>-module</TT> command line option). This directive | |
2733 | must appear at the beginning of the file and is used to name the | |
2734 | resulting extension module (in addition, this name often defines a | |
2735 | namespace in the target language). If the module name is supplied on | |
2736 | the command line, it overrides the name specified with the <TT>%module</TT> | |
2737 | directive.</P> | |
2738 | <P> Everything in the <TT>%{ ... %}</TT> block is simply copied verbatim | |
2739 | to the resulting wrapper file created by SWIG. This section is almost | |
2740 | always used to include header files and other declarations that are | |
2741 | required to make the generated wrapper code compile. It is important to | |
2742 | emphasize that just because you include a declaration in a SWIG input | |
2743 | file, that declaration does<EM> not</EM> automatically appear in the | |
2744 | generated wrapper code---therefore you need to make sure you include | |
2745 | the proper header files in the <TT>%{ ... %}</TT> section. It should be | |
2746 | noted that the text enclosed in <TT>%{ ... %}</TT> is not parsed or | |
2747 | interpreted by SWIG. The <TT>%{...%}</TT> syntax and semantics in SWIG | |
2748 | is analogous to that of the declarations section used in input files to | |
2749 | parser generation tools such as yacc or bison.</P> | |
2750 | <H3><A name="output"></A>5.1.2 SWIG Output</H3> | |
2751 | <P> The output of SWIG is a C/C++ file that contains all of the wrapper | |
2752 | code needed to build an extension module. SWIG may generate some | |
2753 | additional files depending on the target language. By default, an input | |
2754 | file with the name <TT>file.i</TT> is transformed into a file <TT> | |
2755 | file_wrap.c</TT> or <TT>file_wrap.cxx</TT> (depending on whether or not | |
2756 | the <TT>-c++</TT> option has been used). The name of the output file | |
2757 | can be changed using the <TT>-o</TT> option. In certain cases, file | |
2758 | suffixes are used by the compiler to determine the source language (C, | |
2759 | C++, etc.). Therefore, you have to use the <TT>-o</TT> option to change | |
2760 | the suffix of the SWIG-generated wrapper file if you want something | |
2761 | different than the default. For example:</P> | |
2762 | <DIV class="shell"> | |
2763 | <PRE> | |
2764 | $ swig -c++ -python -o example_wrap.cpp example.i | |
2765 | </PRE> | |
2766 | </DIV> | |
2767 | <P> The C/C++ output file created by SWIG often contains everything that | |
2768 | is needed to construct a extension module for the target scripting | |
2769 | language. SWIG is not a stub compiler nor is it usually necessary to | |
2770 | edit the output file (and if you look at the output, you probably won't | |
2771 | want to). To build the final extension module, the SWIG output file is | |
2772 | compiled and linked with the rest of your C/C++ program to create a | |
2773 | shared library.</P> | |
2774 | <P> Many target languages will also generate proxy class files in the | |
2775 | target language. The default output directory for these language | |
2776 | specific files is the same directory as the generated C/C++ file. This | |
2777 | can can be modified using the <TT>-outdir</TT> option. For example:</P> | |
2778 | <DIV class="shell"> | |
2779 | <PRE> | |
2780 | $ swig -c++ -python -outdir pyfiles -o cppfiles/example_wrap.cpp example.i | |
2781 | </PRE> | |
2782 | </DIV> | |
2783 | <P> If the directories <TT>cppfiles</TT> and <TT>pyfiles</TT> exist, the | |
2784 | following will be generated:</P> | |
2785 | <DIV class="shell"> | |
2786 | <PRE> | |
2787 | cppfiles/example_wrap.cpp | |
2788 | pyfiles/example.py | |
2789 | </PRE> | |
2790 | </DIV> | |
2791 | <H3><A name="SWIG_nn5"></A>5.1.3 Comments</H3> | |
2792 | <P> C and C++ style comments may appear anywhere in interface files. In | |
2793 | previous versions of SWIG, comments were used to generate documentation | |
2794 | files. However, this feature is currently under repair and will | |
2795 | reappear in a later SWIG release.</P> | |
2796 | <H3><A name="SWIG_nn6"></A>5.1.4 C Preprocessor</H3> | |
2797 | <P> Like C, SWIG preprocesses all input files through an enhanced | |
2798 | version of the C preprocessor. All standard preprocessor features are | |
2799 | supported including file inclusion, conditional compilation and macros. | |
2800 | However, <TT>#include</TT> statements are ignored unless the <TT> | |
2801 | -includeall</TT> command line option has been supplied. The reason for | |
2802 | disabling includes is that SWIG is sometimes used to process raw C | |
2803 | header files. In this case, you usually only want the extension module | |
2804 | to include functions in the supplied header file rather than everything | |
2805 | that might be included by that header file (i.e., system headers, C | |
2806 | library functions, etc.).</P> | |
2807 | <P> It should also be noted that the SWIG preprocessor skips all text | |
2808 | enclosed inside a <TT>%{...%}</TT> block. In addition, the preprocessor | |
2809 | includes a number of macro handling enhancements that make it more | |
2810 | powerful than the normal C preprocessor. These extensions are described | |
2811 | in the "<A href="#Preprocessor">Preprocessor</A>" chapter.</P> | |
2812 | <H3><A name="SWIG_nn7"></A>5.1.5 SWIG Directives</H3> | |
2813 | <P> Most of SWIG's operation is controlled by special directives that | |
2814 | are always preceded by a "<TT>%</TT>" to distinguish them from normal C | |
2815 | declarations. These directives are used to give SWIG hints or to alter | |
2816 | SWIG's parsing behavior in some manner.</P> | |
2817 | <P> Since SWIG directives are not legal C syntax, it is generally not | |
2818 | possible to include them in header files. However, SWIG directives can | |
2819 | be included in C header files using conditional compilation like this:</P> | |
2820 | <DIV class="code"> | |
2821 | <PRE> | |
2822 | /* header.h --- Some header file */ | |
2823 | ||
2824 | /* SWIG directives -- only seen if SWIG is running */ | |
2825 | #ifdef SWIG | |
2826 | %module foo | |
2827 | #endif | |
2828 | </PRE> | |
2829 | </DIV> | |
2830 | <P> <TT>SWIG</TT> is a special preprocessing symbol defined by SWIG when | |
2831 | it is parsing an input file.</P> | |
2832 | <H3><A name="SWIG_nn8"></A>5.1.6 Parser Limitations</H3> | |
2833 | <P> Although SWIG can parse most C/C++ declarations, it does not provide | |
2834 | a complete C/C++ parser implementation. Most of these limitations | |
2835 | pertain to very complicated type declarations and certain advanced C++ | |
2836 | features. Specifically, the following features are not currently | |
2837 | supported:</P> | |
2838 | <UL> | |
2839 | <LI>Non-conventional type declarations. For example, SWIG does not | |
2840 | support declarations such as the following (even though this is legal | |
2841 | C):<DIV class="code"> | |
2842 | <PRE> | |
2843 | /* Non-conventional placement of storage specifier (extern) */ | |
2844 | const int extern Number; | |
2845 | ||
2846 | /* Extra declarator grouping */ | |
2847 | Matrix (foo); // A global variable | |
2848 | ||
2849 | /* Extra declarator grouping in parameters */ | |
2850 | void bar(Spam (Grok)(Doh)); | |
2851 | ||
2852 | </PRE> | |
2853 | </DIV> | |
2854 | <P> In practice, few (if any) C programmers actually write code like | |
2855 | this since this style is never featured in programming books. However, | |
2856 | if you're feeling particularly obfuscated, you can certainly break SWIG | |
2857 | (although why would you want to?).</P> | |
2858 | </LI> | |
2859 | <LI>Running SWIG on C++ source files (what would appear in a .C or .cxx | |
2860 | file) is not recommended. Even though SWIG can parse C++ class | |
2861 | declarations, it ignores declarations that are decoupled from their | |
2862 | original class definition (the declarations are parsed, but a lot of | |
2863 | warning messages may be generated). For example:<DIV class="code"> | |
2864 | <PRE> | |
2865 | /* Not supported by SWIG */ | |
2866 | int foo::bar(int) { | |
2867 | ... whatever ... | |
2868 | } | |
2869 | </PRE> | |
2870 | </DIV></LI> | |
2871 | <LI>Certain advanced features of C++ such as nested classes are not yet | |
2872 | supported. Please see the section on using SWIG with C++ for more | |
2873 | information.</LI> | |
2874 | </UL> | |
2875 | <P> In the event of a parsing error, conditional compilation can be used | |
2876 | to skip offending code. For example:</P> | |
2877 | <DIV class="code"> | |
2878 | <PRE> | |
2879 | #ifndef SWIG | |
2880 | ... some bad declarations ... | |
2881 | #endif | |
2882 | </PRE> | |
2883 | </DIV> | |
2884 | <P> Alternatively, you can just delete the offending code from the | |
2885 | interface file.</P> | |
2886 | <P> One of the reasons why SWIG does not provide a full C++ parser | |
2887 | implementation is that it has been designed to work with incomplete | |
2888 | specifications and to be very permissive in its handling of C/C++ | |
2889 | datatypes (e.g., SWIG can generate interfaces even when there are | |
2890 | missing class declarations or opaque datatypes). Unfortunately, this | |
2891 | approach makes it extremely difficult to implement certain parts of a | |
2892 | C/C++ parser as most compilers use type information to assist in the | |
2893 | parsing of more complex declarations (for the truly curious, the | |
2894 | primary complication in the implementation is that the SWIG parser does | |
2895 | not utilize a separate<EM> typedef-name</EM> terminal symbol as | |
2896 | described on p. 234 of K&R).</P> | |
2897 | <H2><A name="SWIG_nn9"></A>5.2 Wrapping Simple C Declarations</H2> | |
2898 | <P> SWIG wraps simple C declarations by creating an interface that | |
2899 | closely matches the way in which the declarations would be used in a C | |
2900 | program. For example, consider the following interface file:</P> | |
2901 | <DIV class="code"> | |
2902 | <PRE> | |
2903 | %module example | |
2904 | ||
2905 | %inline %{ | |
2906 | extern double sin(double x); | |
2907 | extern int strcmp(const char *, const char *); | |
2908 | extern int Foo; | |
2909 | %} | |
2910 | #define STATUS 50 | |
2911 | #define VERSION "1.1" | |
2912 | </PRE> | |
2913 | </DIV> | |
2914 | <P> In this file, there are two functions <TT>sin()</TT> and <TT> | |
2915 | strcmp()</TT>, a global variable <TT>Foo</TT>, and two constants <TT> | |
2916 | STATUS</TT> and <TT>VERSION</TT>. When SWIG creates an extension module, | |
2917 | these declarations are accessible as scripting language functions, | |
2918 | variables, and constants respectively. For example, in Tcl:</P> | |
2919 | <DIV class="targetlang"> | |
2920 | <PRE> | |
2921 | % sin 3 | |
2922 | 5.2335956 | |
2923 | % strcmp Dave Mike | |
2924 | -1 | |
2925 | % puts $Foo | |
2926 | 42 | |
2927 | % puts $STATUS | |
2928 | 50 | |
2929 | % puts $VERSION | |
2930 | 1.1 | |
2931 | </PRE> | |
2932 | </DIV> | |
2933 | <P> Or in Python:</P> | |
2934 | <DIV class="targetlang"> | |
2935 | <PRE> | |
2936 | >>> example.sin(3) | |
2937 | 5.2335956 | |
2938 | >>> example.strcmp('Dave','Mike') | |
2939 | -1 | |
2940 | >>> print example.cvar.Foo | |
2941 | 42 | |
2942 | >>> print example.STATUS | |
2943 | 50 | |
2944 | >>> print example.VERSION | |
2945 | 1.1 | |
2946 | </PRE> | |
2947 | </DIV> | |
2948 | <P> Whenever possible, SWIG creates an interface that closely matches | |
2949 | the underlying C/C++ code. However, due to subtle differences between | |
2950 | languages, run-time environments, and semantics, it is not always | |
2951 | possible to do so. The next few sections describes various aspects of | |
2952 | this mapping.</P> | |
2953 | <H3><A name="SWIG_nn10"></A>5.2.1 Basic Type Handling</H3> | |
2954 | <P> In order to build an interface, SWIG has to convert C/C++ datatypes | |
2955 | to equivalent types in the target language. Generally, scripting | |
2956 | languages provide a more limited set of primitive types than C. | |
2957 | Therefore, this conversion process involves a certain amount of type | |
2958 | coercion.</P> | |
2959 | <P> Most scripting languages provide a single integer type that is | |
2960 | implemented using the <TT>int</TT> or <TT>long</TT> datatype in C. The | |
2961 | following list shows all of the C datatypes that SWIG will convert to | |
2962 | and from integers in the target language:</P> | |
2963 | <DIV class="code"> | |
2964 | <PRE> | |
2965 | int | |
2966 | short | |
2967 | long | |
2968 | unsigned | |
2969 | signed | |
2970 | unsigned short | |
2971 | unsigned long | |
2972 | unsigned char | |
2973 | signed char | |
2974 | bool | |
2975 | </PRE> | |
2976 | </DIV> | |
2977 | <P> When an integral value is converted from C, a cast is used to | |
2978 | convert it to the representation in the target language. Thus, a 16 bit | |
2979 | short in C may be promoted to a 32 bit integer. When integers are | |
2980 | converted in the other direction, the value is cast back into the | |
2981 | original C type. If the value is too large to fit, it is silently | |
2982 | truncated. | |
2983 | <!-- Dave: Maybe we should fix this --> | |
2984 | </P> | |
2985 | <P> <TT>unsigned char</TT> and <TT>signed char</TT> are special cases | |
2986 | that are handled as small 8-bit integers. Normally, the <TT>char</TT> | |
2987 | datatype is mapped as a one-character ASCII string.</P> | |
2988 | <P> The <TT>bool</TT> datatype is cast to and from an integer value of 0 | |
2989 | and 1 unless the target language provides a special boolean type.</P> | |
2990 | <P> Some care is required when working with large integer values. Most | |
2991 | scripting languages use 32-bit integers so mapping a 64-bit long | |
2992 | integer may lead to truncation errors. Similar problems may arise with | |
2993 | 32 bit unsigned integers (which may appear as large negative numbers). | |
2994 | As a rule of thumb, the <TT>int</TT> datatype and all variations of <TT> | |
2995 | char</TT> and <TT>short</TT> datatypes are safe to use. For <TT>unsigned | |
2996 | int</TT> and <TT>long</TT> datatypes, you will need to carefully check | |
2997 | the correct operation of your program after it has been wrapped with | |
2998 | SWIG.</P> | |
2999 | <P> Although the SWIG parser supports the <TT>long long</TT> datatype, | |
3000 | not all language modules support it. This is because <TT>long long</TT> | |
3001 | usually exceeds the integer precision available in the target language. | |
3002 | In certain modules such as Tcl and Perl5, <TT>long long</TT> integers | |
3003 | are encoded as strings. This allows the full range of these numbers to | |
3004 | be represented. However, it does not allow <TT>long long</TT> values to | |
3005 | be used in arithmetic expressions. It should also be noted that | |
3006 | although <TT>long long</TT> is part of the ISO C99 standard, it is not | |
3007 | universally supported by all C compilers. Make sure you are using a | |
3008 | compiler that supports <TT>long long</TT> before trying to use this | |
3009 | type with SWIG.</P> | |
3010 | <P> SWIG recognizes the following floating point types :</P> | |
3011 | <DIV class="code"> | |
3012 | <PRE> | |
3013 | float | |
3014 | double | |
3015 | </PRE> | |
3016 | </DIV> | |
3017 | <P> Floating point numbers are mapped to and from the natural | |
3018 | representation of floats in the target language. This is almost always | |
3019 | a C <TT>double</TT>. The rarely used datatype of <TT>long double</TT> | |
3020 | is not supported by SWIG.</P> | |
3021 | <P> The <TT>char</TT> datatype is mapped into a NULL terminated ASCII | |
3022 | string with a single character. When used in a scripting language it | |
3023 | shows up as a tiny string containing the character value. When | |
3024 | converting the value back into C, SWIG takes a character string from | |
3025 | the scripting language and strips off the first character as the char | |
3026 | value. Thus if the value "foo" is assigned to a <TT>char</TT> datatype, | |
3027 | it gets the value `f'.</P> | |
3028 | <P> The <TT>char *</TT> datatype is handled as a NULL-terminated ASCII | |
3029 | string. SWIG maps this into a 8-bit character string in the target | |
3030 | scripting language. SWIG converts character strings in the target | |
3031 | language to NULL terminated strings before passing them into C/C++. The | |
3032 | default handling of these strings does not allow them to have embedded | |
3033 | NULL bytes. Therefore, the <TT>char *</TT> datatype is not generally | |
3034 | suitable for passing binary data. However, it is possible to change | |
3035 | this behavior by defining a SWIG typemap. See the chapter on <A href="#Typemaps"> | |
3036 | Typemaps</A> for details about this.</P> | |
3037 | <P> At this time, SWIG does not provide any special support for Unicode | |
3038 | or wide-character strings (the C <TT>wchar_t</TT> type). This is a | |
3039 | delicate topic that is poorly understood by many programmers and not | |
3040 | implemented in a consistent manner across languages. For those | |
3041 | scripting languages that provide Unicode support, Unicode strings are | |
3042 | often available in an 8-bit representation such as UTF-8 that can be | |
3043 | mapped to the <TT>char *</TT> type (in which case the SWIG interface | |
3044 | will probably work). If the program you are wrapping uses Unicode, | |
3045 | there is no guarantee that Unicode characters in the target language | |
3046 | will use the same internal representation (e.g., UCS-2 vs. UCS-4). You | |
3047 | may need to write some special conversion functions.</P> | |
3048 | <H3><A name="SWIG_nn11"></A>5.2.2 Global Variables</H3> | |
3049 | <P> Whenever possible, SWIG maps C/C++ global variables into scripting | |
3050 | language variables. For example,</P> | |
3051 | <DIV class="code"> | |
3052 | <PRE> | |
3053 | %module example | |
3054 | double foo; | |
3055 | ||
3056 | </PRE> | |
3057 | </DIV> | |
3058 | <P> results in a scripting language variable like this:</P> | |
3059 | <DIV class="code"> | |
3060 | <PRE> | |
3061 | # Tcl | |
3062 | set foo [3.5] ;# Set foo to 3.5 | |
3063 | puts $foo ;# Print the value of foo | |
3064 | ||
3065 | # Python | |
3066 | cvar.foo = 3.5 # Set foo to 3.5 | |
3067 | print cvar.foo # Print value of foo | |
3068 | ||
3069 | # Perl | |
3070 | $foo = 3.5; # Set foo to 3.5 | |
3071 | print $foo,"\n"; # Print value of foo | |
3072 | ||
3073 | # Ruby | |
3074 | Module.foo = 3.5 # Set foo to 3.5 | |
3075 | print Module.foo, "\n" # Print value of foo | |
3076 | </PRE> | |
3077 | </DIV> | |
3078 | <P> Whenever the scripting language variable is used, the underlying C | |
3079 | global variable is accessed. Although SWIG makes every attempt to make | |
3080 | global variables work like scripting language variables, it is not | |
3081 | always possible to do so. For instance, in Python, all global variables | |
3082 | must be accessed through a special variable object known as <TT>cvar</TT> | |
3083 | (shown above). In Ruby, variables are accessed as attributes of the | |
3084 | module. Other languages may convert variables to a pair of accessor | |
3085 | functions. For example, the Java module generates a pair of functions <TT> | |
3086 | double get_foo()</TT> and <TT>set_foo(double val)</TT> that are used to | |
3087 | manipulate the value.</P> | |
3088 | <P> Finally, if a global variable has been declared as <TT>const</TT>, | |
3089 | it only supports read-only access. Note: this behavior is new to | |
3090 | SWIG-1.3. Earlier versions of SWIG incorrectly handled <TT>const</TT> | |
3091 | and created constants instead.</P> | |
3092 | <H3><A name="SWIG_nn12"></A>5.2.3 Constants</H3> | |
3093 | <P> Constants can be created using <TT>#define</TT>, enumerations, or a | |
3094 | special <TT>%constant</TT> directive. The following interface file | |
3095 | shows a few valid constant declarations :</P> | |
3096 | <DIV class="code"> | |
3097 | <PRE> | |
3098 | #define I_CONST 5 // An integer constant | |
3099 | #define PI 3.14159 // A Floating point constant | |
3100 | #define S_CONST "hello world" // A string constant | |
3101 | #define NEWLINE '\n' // Character constant | |
3102 | ||
3103 | enum boolean {NO=0, YES=1}; | |
3104 | enum months {JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, | |
3105 | SEP, OCT, NOV, DEC}; | |
3106 | %constant double BLAH = 42.37; | |
3107 | #define F_CONST (double) 5 // A floating pointer constant with cast | |
3108 | #define PI_4 PI/4 | |
3109 | #define FLAGS 0x04 | 0x08 | 0x40 | |
3110 | ||
3111 | </PRE> | |
3112 | </DIV> | |
3113 | <P> In <TT>#define</TT> declarations, the type of a constant is inferred | |
3114 | by syntax. For example, a number with a decimal point is assumed to be | |
3115 | floating point. In addition, SWIG must be able to fully resolve all of | |
3116 | the symbols used in a <TT>#define</TT> in order for a constant to | |
3117 | actually be created. This restriction is necessary because <TT>#define</TT> | |
3118 | is also used to define preprocessor macros that are definitely not | |
3119 | meant to be part of the scripting language interface. For example:</P> | |
3120 | <DIV class="code"> | |
3121 | <PRE> | |
3122 | #define EXTERN extern | |
3123 | ||
3124 | EXTERN void foo(); | |
3125 | </PRE> | |
3126 | </DIV> | |
3127 | <P> In this case, you probably don't want to create a constant called <TT> | |
3128 | EXTERN</TT> (what would the value be?). In general, SWIG will not create | |
3129 | constants for macros unless the value can be completely determined by | |
3130 | the preprocessor. For instance, in the above example, the declaration</P> | |
3131 | <DIV class="code"> | |
3132 | <PRE> | |
3133 | #define PI_4 PI/4 | |
3134 | </PRE> | |
3135 | </DIV> | |
3136 | <P> defines a constant because <TT>PI</TT> was already defined as a | |
3137 | constant and the value is known.</P> | |
3138 | <P> The use of constant expressions is allowed, but SWIG does not | |
3139 | evaluate them. Rather, it passes them through to the output file and | |
3140 | lets the C compiler perform the final evaluation (SWIG does perform a | |
3141 | limited form of type-checking however).</P> | |
3142 | <P> For enumerations, it is critical that the original enum definition | |
3143 | be included somewhere in the interface file (either in a header file or | |
3144 | in the <TT>%{,%}</TT> block). SWIG only translates the enumeration into | |
3145 | code needed to add the constants to a scripting language. It needs the | |
3146 | original enumeration declaration in order to get the correct enum | |
3147 | values as assigned by the C compiler.</P> | |
3148 | <P> The <TT>%constant</TT> directive is used to more precisely create | |
3149 | constants corresponding to different C datatypes. Although it is not | |
3150 | usually not needed for simple values, it is more useful when working | |
3151 | with pointers and other more complex datatypes. Typically, <TT> | |
3152 | %constant</TT> is only used when you want to add constants to the | |
3153 | scripting language interface that are not defined in the original | |
3154 | header file.</P> | |
3155 | <H3><A name="SWIG_nn13"></A>5.2.4 A brief word about <TT>const</TT></H3> | |
3156 | <P> A common confusion with C programming is the semantic meaning of the | |
3157 | <TT>const</TT> qualifier in declarations--especially when it is mixed | |
3158 | with pointers and other type modifiers. In fact, previous versions of | |
3159 | SWIG handled <TT>const</TT> incorrectly--a situation that SWIG-1.3.7 | |
3160 | and newer releases have fixed.</P> | |
3161 | <P> Starting with SWIG-1.3, all variable declarations, regardless of any | |
3162 | use of <TT>const</TT>, are wrapped as global variables. If a | |
3163 | declaration happens to be declared as <TT>const</TT>, it is wrapped as | |
3164 | a read-only variable. To tell if a variable is <TT>const</TT> or not, | |
3165 | you need to look at the right-most occurrence of the <TT>const</TT> | |
3166 | qualifier (that appears before the variable name). If the right-most <TT> | |
3167 | const</TT> occurs after all other type modifiers (such as pointers), | |
3168 | then the variable is <TT>const</TT>. Otherwise, it is not.</P> | |
3169 | <P> Here are some examples of <TT>const</TT> declarations.</P> | |
3170 | <DIV class="code"> | |
3171 | <PRE> | |
3172 | const char a; // A constant character | |
3173 | char const b; // A constant character (the same) | |
3174 | char *const c; // A constant pointer to a character | |
3175 | const char *const d; // A constant pointer to a constant character | |
3176 | </PRE> | |
3177 | </DIV> | |
3178 | <P> Here is an example of a declaration that is not <TT>const</TT>:</P> | |
3179 | <DIV class="code"> | |
3180 | <PRE> | |
3181 | const char *e; // A pointer to a constant character. The pointer | |
3182 | // may be modified. | |
3183 | </PRE> | |
3184 | </DIV> | |
3185 | <P> In this case, the pointer <TT>e</TT> can change---it's only the | |
3186 | value being pointed to that is read-only.</P> | |
3187 | <P><B> Compatibility Note:</B> One reason for changing SWIG to handle <TT> | |
3188 | const</TT> declarations as read-only variables is that there are many | |
3189 | situations where the value of a <TT>const</TT> variable might change. | |
3190 | For example, a library might export a symbol as <TT>const</TT> in its | |
3191 | public API to discourage modification, but still allow the value to | |
3192 | change through some other kind of internal mechanism. Furthermore, | |
3193 | programmers often overlook the fact that with a constant declaration | |
3194 | like <TT>char *const</TT>, the underlying data being pointed to can be | |
3195 | modified--it's only the pointer itself that is constant. In an embedded | |
3196 | system, a <TT>const</TT> declaration might refer to a read-only memory | |
3197 | address such as the location of a memory-mapped I/O device port (where | |
3198 | the value changes, but writing to the port is not supported by the | |
3199 | hardware). Rather than trying to build a bunch of special cases into | |
3200 | the <TT>const</TT> qualifier, the new interpretation of <TT>const</TT> | |
3201 | as "read-only" is simple and exactly matches the actual semantics of <TT> | |
3202 | const</TT> in C/C++. If you really want to create a constant as in older | |
3203 | versions of SWIG, use the <TT>%constant</TT> directive instead. For | |
3204 | example:</P> | |
3205 | <DIV class="code"> | |
3206 | <PRE> | |
3207 | %constant double PI = 3.14159; | |
3208 | </PRE> | |
3209 | </DIV> | |
3210 | <P> or</P> | |
3211 | <DIV class="code"> | |
3212 | <PRE> | |
3213 | #ifdef SWIG | |
3214 | #define const %constant | |
3215 | #endif | |
3216 | const double foo = 3.4; | |
3217 | const double bar = 23.4; | |
3218 | const int spam = 42; | |
3219 | #ifdef SWIG | |
3220 | #undef const | |
3221 | #endif | |
3222 | ... | |
3223 | ||
3224 | </PRE> | |
3225 | </DIV> | |
3226 | <H3><A name="SWIG_nn14"></A>5.2.5 A cautionary tale of <TT>char *</TT></H3> | |
3227 | <P> Before going any further, there is one bit of caution involving <TT> | |
3228 | char *</TT> that must now be mentioned. When strings are passed from a | |
3229 | scripting language to a C <TT>char *</TT>, the pointer usually points | |
3230 | to string data stored inside the interpreter. It is almost always a | |
3231 | really bad idea to modify this data. Furthermore, some languages may | |
3232 | explicitly disallow it. For instance, in Python, strings are supposed | |
3233 | be immutable. If you violate this, you will probably receive a vast | |
3234 | amount of wrath when you unleash your module on the world.</P> | |
3235 | <P> The primary source of problems are functions that might modify | |
3236 | string data in place. A classic example would be a function like this:</P> | |
3237 | <DIV class="code"> | |
3238 | <PRE> | |
3239 | char *strcat(char *s, const char *t) | |
3240 | </PRE> | |
3241 | </DIV> | |
3242 | <P> Although SWIG will certainly generate a wrapper for this, its | |
3243 | behavior will be undefined. In fact, it will probably cause your | |
3244 | application to crash with a segmentation fault or other memory related | |
3245 | problem. This is because <TT>s</TT> refers to some internal data in the | |
3246 | target language---data that you shouldn't be touching.</P> | |
3247 | <P> The bottom line: don't rely on <TT>char *</TT> for anything other | |
3248 | than read-only input values. However, it must be noted that you could | |
3249 | change the behavior of SWIG using <A href="#Typemaps">typemaps</A>.</P> | |
3250 | <H2><A name="SWIG_nn15"></A>5.3 Pointers and complex objects</H2> | |
3251 | <P> Most C programs manipulate arrays, structures, and other types of | |
3252 | objects. This section discusses the handling of these datatypes.</P> | |
3253 | <H3><A name="SWIG_nn16"></A>5.3.1 Simple pointers</H3> | |
3254 | <P> Pointers to primitive C datatypes such as</P> | |
3255 | <DIV class="code"> | |
3256 | <PRE> | |
3257 | int * | |
3258 | double *** | |
3259 | char ** | |
3260 | </PRE> | |
3261 | </DIV> | |
3262 | <P> are fully supported by SWIG. Rather than trying to convert the data | |
3263 | being pointed to into a scripting representation, SWIG simply encodes | |
3264 | the pointer itself into a representation that contains the actual value | |
3265 | of the pointer and a type-tag. Thus, the SWIG representation of the | |
3266 | above pointers (in Tcl), might look like this:</P> | |
3267 | <DIV class="targetlang"> | |
3268 | <PRE> | |
3269 | _10081012_p_int | |
3270 | _1008e124_ppp_double | |
3271 | _f8ac_pp_char | |
3272 | </PRE> | |
3273 | </DIV> | |
3274 | <P> A NULL pointer is represented by the string "NULL" or the value 0 | |
3275 | encoded with type information.</P> | |
3276 | <P> All pointers are treated as opaque objects by SWIG. Thus, a pointer | |
3277 | may be returned by a function and passed around to other C functions as | |
3278 | needed. For all practical purposes, the scripting language interface | |
3279 | works in exactly the same way as you would use the pointer in a C | |
3280 | program. The only difference is that there is no mechanism for | |
3281 | dereferencing the pointer since this would require the target language | |
3282 | to understand the memory layout of the underlying object.</P> | |
3283 | <P> The scripting language representation of a pointer value should | |
3284 | never be manipulated directly. Even though the values shown look like | |
3285 | hexadecimal addresses, the numbers used may differ from the actual | |
3286 | machine address (e.g., on little-endian machines, the digits may appear | |
3287 | in reverse order). Furthermore, SWIG does not normally map pointers | |
3288 | into high-level objects such as associative arrays or lists (for | |
3289 | example, converting an <TT>int *</TT> into an list of integers). There | |
3290 | are several reasons why SWIG does not do this:</P> | |
3291 | <UL> | |
3292 | <LI>There is not enough information in a C declaration to properly map | |
3293 | pointers into higher level constructs. For example, an <TT>int *</TT> | |
3294 | may indeed be an array of integers, but if it contains ten million | |
3295 | elements, converting it into a list object is probably a bad idea.</LI> | |
3296 | <LI>The underlying semantics associated with a pointer is not known by | |
3297 | SWIG. For instance, an <TT>int *</TT> might not be an array at | |
3298 | all--perhaps it is an output value!</LI> | |
3299 | <LI>By handling all pointers in a consistent manner, the implementation | |
3300 | of SWIG is greatly simplified and less prone to error.</LI> | |
3301 | </UL> | |
3302 | <H3><A name="SWIG_nn17"></A>5.3.2 Run time pointer type checking</H3> | |
3303 | <P> By allowing pointers to be manipulated from a scripting language, | |
3304 | extension modules effectively bypass compile-time type checking in the | |
3305 | C/C++ compiler. To prevent errors, a type signature is encoded into all | |
3306 | pointer values and is used to perform run-time type checking. This | |
3307 | type-checking process is an integral part of SWIG and can not be | |
3308 | disabled or modified without using typemaps (described in later | |
3309 | chapters).</P> | |
3310 | <P> Like C, <TT>void *</TT> matches any kind of pointer. Furthermore, <TT> | |
3311 | NULL</TT> pointers can be passed to any function that expects to receive | |
3312 | a pointer. Although this has the potential to cause a crash, <TT>NULL</TT> | |
3313 | pointers are also sometimes used as sentinel values or to denote a | |
3314 | missing/empty value. Therefore, SWIG leaves NULL pointer checking up to | |
3315 | the application.</P> | |
3316 | <H3><A name="SWIG_nn18"></A>5.3.3 Derived types, structs, and classes</H3> | |
3317 | <P> For everything else (structs, classes, arrays, etc...) SWIG applies | |
3318 | a very simple rule :</P> | |
3319 | <CENTER><B> Everything else is a pointer</B></CENTER> | |
3320 | <P> In other words, SWIG manipulates everything else by reference. This | |
3321 | model makes sense because most C/C++ programs make heavy use of | |
3322 | pointers and SWIG can use the type-checked pointer mechanism already | |
3323 | present for handling pointers to basic datatypes.</P> | |
3324 | <P> Although this probably sounds complicated, it's really quite simple. | |
3325 | Suppose you have an interface file like this :</P> | |
3326 | <DIV class="code"> | |
3327 | <PRE> | |
3328 | %module fileio | |
3329 | FILE *fopen(char *, char *); | |
3330 | int fclose(FILE *); | |
3331 | unsigned fread(void *ptr, unsigned size, unsigned nobj, FILE *); | |
3332 | unsigned fwrite(void *ptr, unsigned size, unsigned nobj, FILE *); | |
3333 | void *malloc(int nbytes); | |
3334 | void free(void *); | |
3335 | ||
3336 | </PRE> | |
3337 | </DIV> | |
3338 | <P> In this file, SWIG doesn't know what a <TT>FILE</TT> is, but since | |
3339 | it's used as a pointer, so it doesn't really matter what it is. If you | |
3340 | wrapped this module into Python, you can use the functions just like | |
3341 | you expect :</P> | |
3342 | <DIV class="targetlang"> | |
3343 | <PRE> | |
3344 | # Copy a file | |
3345 | def filecopy(source,target): | |
3346 | f1 = fopen(source,"r") | |
3347 | f2 = fopen(target,"w") | |
3348 | buffer = malloc(8192) | |
3349 | nbytes = fread(buffer,8192,1,f1) | |
3350 | while (nbytes > 0): | |
3351 | fwrite(buffer,8192,1,f2) | |
3352 | nbytes = fread(buffer,8192,1,f1) | |
3353 | free(buffer) | |
3354 | ||
3355 | </PRE> | |
3356 | </DIV> | |
3357 | <P> In this case <TT>f1</TT>, <TT>f2</TT>, and <TT>buffer</TT> are all | |
3358 | opaque objects containing C pointers. It doesn't matter what value they | |
3359 | contain--our program works just fine without this knowledge.</P> | |
3360 | <H3><A name="SWIG_nn19"></A>5.3.4 Undefined datatypes</H3> | |
3361 | <P> When SWIG encounters an undeclared datatype, it automatically | |
3362 | assumes that it is a structure or class. For example, suppose the | |
3363 | following function appeared in a SWIG input file:</P> | |
3364 | <DIV class="code"> | |
3365 | <PRE> | |
3366 | void matrix_multiply(Matrix *a, Matrix *b, Matrix *c); | |
3367 | </PRE> | |
3368 | </DIV> | |
3369 | <P> SWIG has no idea what a "<TT>Matrix</TT>" is. However, it is | |
3370 | obviously a pointer to something so SWIG generates a wrapper using its | |
3371 | generic pointer handling code.</P> | |
3372 | <P> Unlike C or C++, SWIG does not actually care whether <TT>Matrix</TT> | |
3373 | has been previously defined in the interface file or not. This allows | |
3374 | SWIG to generate interfaces from only partial or limited information. | |
3375 | In some cases, you may not care what a <TT>Matrix</TT> really is as | |
3376 | long as you can pass an opaque reference to one around in the scripting | |
3377 | language interface.</P> | |
3378 | <P> An important detail to mention is that SWIG will gladly generate | |
3379 | wrappers for an interface when there are unspecified type names. | |
3380 | However,<B> all unspecified types are internally handled as pointers to | |
3381 | structures or classes!</B> For example, consider the following | |
3382 | declaration:</P> | |
3383 | <DIV class="code"> | |
3384 | <PRE> | |
3385 | void foo(size_t num); | |
3386 | </PRE> | |
3387 | </DIV> | |
3388 | <P> If <TT>size_t</TT> is undeclared, SWIG generates wrappers that | |
3389 | expect to receive a type of <TT>size_t *</TT> (this mapping is | |
3390 | described shortly). As a result, the scripting interface might behave | |
3391 | strangely. For example:</P> | |
3392 | <DIV class="code"> | |
3393 | <PRE> | |
3394 | foo(40); | |
3395 | TypeError: expected a _p_size_t. | |
3396 | </PRE> | |
3397 | </DIV> | |
3398 | <P> The only way to fix this problem is to make sure you properly | |
3399 | declare type names using <TT>typedef</TT>.</P> | |
3400 | ||
3401 | <!-- We might want to add an error reporting flag to swig --> | |
3402 | <H3><A name="SWIG_nn20"></A>5.3.5 Typedef</H3> | |
3403 | <P> Like C, <TT>typedef</TT> can be used to define new type names in | |
3404 | SWIG. For example:</P> | |
3405 | <DIV class="code"> | |
3406 | <PRE> | |
3407 | typedef unsigned int size_t; | |
3408 | </PRE> | |
3409 | </DIV> | |
3410 | <P> <TT>typedef</TT> definitions appearing in a SWIG interface are not | |
3411 | propagated to the generated wrapper code. Therefore, they either need | |
3412 | to be defined in an included header file or placed in the declarations | |
3413 | section like this:</P> | |
3414 | <DIV class="code"> | |
3415 | <PRE> | |
3416 | %{ | |
3417 | /* Include in the generated wrapper file */ | |
3418 | typedef unsigned int size_t; | |
3419 | %} | |
3420 | /* Tell SWIG about it */ | |
3421 | typedef unsigned int size_t; | |
3422 | </PRE> | |
3423 | </DIV> | |
3424 | <P> or</P> | |
3425 | <DIV class="code"> | |
3426 | <PRE> | |
3427 | %inline %{ | |
3428 | typedef unsigned int size_t; | |
3429 | %} | |
3430 | </PRE> | |
3431 | </DIV> | |
3432 | <P> In certain cases, you might be able to include other header files to | |
3433 | collect type information. For example:</P> | |
3434 | <DIV class="code"> | |
3435 | <PRE> | |
3436 | %module example | |
3437 | %import "sys/types.h" | |
3438 | </PRE> | |
3439 | </DIV> | |
3440 | <P> In this case, you might run SWIG as follows:</P> | |
3441 | <DIV class="shell"> | |
3442 | <PRE> | |
3443 | $ swig -I/usr/include -includeall example.i | |
3444 | </PRE> | |
3445 | </DIV> | |
3446 | <P> It should be noted that your mileage will vary greatly here. System | |
3447 | headers are notoriously complicated and may rely upon a variety of | |
3448 | non-standard C coding extensions (e.g., such as special directives to | |
3449 | GCC). Unless you exactly specify the right include directories and | |
3450 | preprocessor symbols, this may not work correctly (you will have to | |
3451 | experiment).</P> | |
3452 | <P> SWIG tracks <TT>typedef</TT> declarations and uses this information | |
3453 | for run-time type checking. For instance, if you use the above <TT> | |
3454 | typedef</TT> and had the following function declaration:</P> | |
3455 | <DIV class="code"> | |
3456 | <PRE> | |
3457 | void foo(unsigned int *ptr); | |
3458 | </PRE> | |
3459 | </DIV> | |
3460 | <P> The corresponding wrapper function will accept arguments of type <TT> | |
3461 | unsigned int *</TT> or <TT>size_t *</TT>.</P> | |
3462 | <H2><A name="SWIG_nn21"></A>5.4 Other Practicalities</H2> | |
3463 | <P> So far, this chapter has presented almost everything you need to | |
3464 | know to use SWIG for simple interfaces. However, some C programs use | |
3465 | idioms that are somewhat more difficult to map to a scripting language | |
3466 | interface. This section describes some of these issues.</P> | |
3467 | <H3><A name="SWIG_nn22"></A>5.4.1 Passing structures by value</H3> | |
3468 | <P> Sometimes a C function takes structure parameters that are passed by | |
3469 | value. For example, consider the following function:</P> | |
3470 | <DIV class="code"> | |
3471 | <PRE> | |
3472 | double dot_product(Vector a, Vector b); | |
3473 | </PRE> | |
3474 | </DIV> | |
3475 | <P> To deal with this, SWIG transforms the function to use pointers by | |
3476 | creating a wrapper equivalent to the following:</P> | |
3477 | <DIV class="code"> | |
3478 | <PRE> | |
3479 | double wrap_dot_product(Vector *a, Vector *b) { | |
3480 | Vector x = *a; | |
3481 | Vector y = *b; | |
3482 | return dot_product(x,y); | |
3483 | } | |
3484 | </PRE> | |
3485 | </DIV> | |
3486 | <P> In the target language, the <TT>dot_product()</TT> function now | |
3487 | accepts pointers to Vectors instead of Vectors. For the most part, this | |
3488 | transformation is transparent so you might not notice.</P> | |
3489 | <H3><A name="SWIG_nn23"></A>5.4.2 Return by value</H3> | |
3490 | <P> C functions that return structures or classes datatypes by value are | |
3491 | more difficult to handle. Consider the following function:</P> | |
3492 | <DIV class="code"> | |
3493 | <PRE> | |
3494 | Vector cross_product(Vector v1, Vector v2); | |
3495 | </PRE> | |
3496 | </DIV> | |
3497 | <P> This function wants to return <TT>Vector</TT>, but SWIG only really | |
3498 | supports pointers. As a result, SWIG creates a wrapper like this:</P> | |
3499 | <DIV class="code"> | |
3500 | <PRE> | |
3501 | Vector *wrap_cross_product(Vector *v1, Vector *v2) { | |
3502 | Vector x = *v1; | |
3503 | Vector y = *v2; | |
3504 | Vector *result; | |
3505 | result = (Vector *) malloc(sizeof(Vector)); | |
3506 | *(result) = cross(x,y); | |
3507 | return result; | |
3508 | } | |
3509 | </PRE> | |
3510 | </DIV> | |
3511 | <P> or if SWIG was run with the <TT>-c++</TT> option:</P> | |
3512 | <DIV class="code"> | |
3513 | <PRE> | |
3514 | Vector *wrap_cross(Vector *v1, Vector *v2) { | |
3515 | Vector x = *v1; | |
3516 | Vector y = *v2; | |
3517 | Vector *result = new Vector(cross(x,y)); // Uses default copy constructor | |
3518 | return result; | |
3519 | } | |
3520 | </PRE> | |
3521 | </DIV> | |
3522 | <P> In both cases, SWIG allocates a new object and returns a reference | |
3523 | to it. It is up to the user to delete the returned object when it is no | |
3524 | longer in use. Clearly, this will leak memory if you are unaware of the | |
3525 | implicit memory allocation and don't take steps to free the result. | |
3526 | That said, it should be noted that some language modules can now | |
3527 | automatically track newly created objects and reclaim memory for you. | |
3528 | Consult the documentation for each language module for more details.</P> | |
3529 | <P> It should also be noted that the handling of pass/return by value in | |
3530 | C++ has some special cases. For example, the above code fragments don't | |
3531 | work correctly if <TT>Vector</TT> doesn't define a default constructor. | |
3532 | The section on SWIG and C++ has more information about this case.</P> | |
3533 | <H3><A name="SWIG_nn24"></A>5.4.3 Linking to structure variables</H3> | |
3534 | <P> When global variables or class members involving structures are | |
3535 | encountered, SWIG handles them as pointers. For example, a global | |
3536 | variable like this</P> | |
3537 | <DIV class="code"> | |
3538 | <PRE> | |
3539 | Vector unit_i; | |
3540 | </PRE> | |
3541 | </DIV> | |
3542 | <P> gets mapped to an underlying pair of set/get functions like this :</P> | |
3543 | <DIV class="code"> | |
3544 | <PRE> | |
3545 | Vector *unit_i_get() { | |
3546 | return &unit_i; | |
3547 | } | |
3548 | void unit_i_set(Vector *value) { | |
3549 | unit_i = *value; | |
3550 | } | |
3551 | </PRE> | |
3552 | </DIV> | |
3553 | <P> Again some caution is in order. A global variable created in this | |
3554 | manner will show up as a pointer in the target scripting language. It | |
3555 | would be an extremely bad idea to free or destroy such a pointer. Also, | |
3556 | C++ classes must supply a properly defined copy constructor in order | |
3557 | for assignment to work correctly.</P> | |
3558 | <H3><A name="SWIG_nn25"></A>5.4.4 Linking to <TT>char *</TT></H3> | |
3559 | <P> When a global variable of type <TT>char *</TT> appears, SWIG uses <TT> | |
3560 | malloc()</TT> or <TT>new</TT> to allocate memory for the new value. | |
3561 | Specifically, if you have a variable like this</P> | |
3562 | <DIV class="code"> | |
3563 | <PRE> | |
3564 | char *foo; | |
3565 | </PRE> | |
3566 | </DIV> | |
3567 | <P> SWIG generates the following code:</P> | |
3568 | <DIV class="code"> | |
3569 | <PRE> | |
3570 | /* C mode */ | |
3571 | void foo_set(char *value) { | |
3572 | if (foo) free(foo); | |
3573 | foo = (char *) malloc(strlen(value)+1); | |
3574 | strcpy(foo,value); | |
3575 | } | |
3576 | ||
3577 | /* C++ mode. When -c++ option is used */ | |
3578 | void foo_set(char *value) { | |
3579 | if (foo) delete [] foo; | |
3580 | foo = new char[strlen(value)+1]; | |
3581 | strcpy(foo,value); | |
3582 | } | |
3583 | </PRE> | |
3584 | </DIV> | |
3585 | <P> If this is not the behavior that you want, consider making the | |
3586 | variable read-only using the <TT>%immutable</TT> directive. | |
3587 | Alternatively, you might write a short assist-function to set the value | |
3588 | exactly like you want. For example:</P> | |
3589 | <DIV class="code"> | |
3590 | <PRE> | |
3591 | %inline %{ | |
3592 | void set_foo(char *value) { | |
3593 | strncpy(foo,value, 50); | |
3594 | } | |
3595 | %} | |
3596 | </PRE> | |
3597 | </DIV> | |
3598 | <P> Note: If you write an assist function like this, you will have to | |
3599 | call it as a function from the target scripting language (it does not | |
3600 | work like a variable). For example, in Python you will have to write:</P> | |
3601 | <DIV class="targetlang"> | |
3602 | <PRE> | |
3603 | >>> set_foo("Hello World") | |
3604 | </PRE> | |
3605 | </DIV> | |
3606 | <P> A common mistake with <TT>char *</TT> variables is to link to a | |
3607 | variable declared like this:</P> | |
3608 | <DIV class="code"> | |
3609 | <PRE> | |
3610 | char *VERSION = "1.0"; | |
3611 | </PRE> | |
3612 | </DIV> | |
3613 | <P> In this case, the variable will be readable, but any attempt to | |
3614 | change the value results in a segmentation or general protection fault. | |
3615 | This is due to the fact that SWIG is trying to release the old value | |
3616 | using <TT>free</TT> or <TT>delete</TT> when the string literal value | |
3617 | currently assigned to the variable wasn't allocated using <TT>malloc()</TT> | |
3618 | or <TT>new</TT>. To fix this behavior, you can either mark the variable | |
3619 | as read-only, write a typemap (as described in Chapter 6), or write a | |
3620 | special set function as shown. Another alternative is to declare the | |
3621 | variable as an array:</P> | |
3622 | <DIV class="code"> | |
3623 | <PRE> | |
3624 | char VERSION[64] = "1.0"; | |
3625 | </PRE> | |
3626 | </DIV> | |
3627 | <P> When variables of type <TT>const char *</TT> are declared, SWIG | |
3628 | still generates functions for setting and getting the value. However, | |
3629 | the default behavior does<EM> not</EM> release the previous contents | |
3630 | (resulting in a possible memory leak). In fact, you may get a warning | |
3631 | message such as this when wrapping such a variable:</P> | |
3632 | <DIV class="shell"> | |
3633 | <PRE> | |
3634 | example.i:20. Typemap warning. Setting const char * variable may leak memory | |
3635 | </PRE> | |
3636 | </DIV> | |
3637 | <P> The reason for this behavior is that <TT>const char *</TT> variables | |
3638 | are often used to point to string literals. For example:</P> | |
3639 | <DIV class="code"> | |
3640 | <PRE> | |
3641 | const char *foo = "Hello World\n"; | |
3642 | </PRE> | |
3643 | </DIV> | |
3644 | <P> Therefore, it's a really bad idea to call <TT>free()</TT> on such a | |
3645 | pointer. On the other hand, it<EM> is</EM> legal to change the pointer | |
3646 | to point to some other value. When setting a variable of this type, | |
3647 | SWIG allocates a new string (using malloc or new) and changes the | |
3648 | pointer to point to the new value. However, repeated modifications of | |
3649 | the value will result in a memory leak since the old value is not | |
3650 | released.</P> | |
3651 | <H3><A name="SWIG_nn26"></A>5.4.5 Arrays</H3> | |
3652 | <P> Arrays are fully supported by SWIG, but they are always handled as | |
3653 | pointers instead of mapping them to a special array object or list in | |
3654 | the target language. Thus, the following declarations :</P> | |
3655 | <DIV class="code"> | |
3656 | <PRE> | |
3657 | int foobar(int a[40]); | |
3658 | void grok(char *argv[]); | |
3659 | void transpose(double a[20][20]); | |
3660 | </PRE> | |
3661 | </DIV> | |
3662 | <P> are processed as if they were really declared like this:</P> | |
3663 | <DIV class="code"> | |
3664 | <PRE> | |
3665 | int foobar(int *a); | |
3666 | void grok(char **argv); | |
3667 | void transpose(double (*a)[20]); | |
3668 | </PRE> | |
3669 | </DIV> | |
3670 | <P> Like C, SWIG does not perform array bounds checking. It is up to the | |
3671 | user to make sure the pointer points a suitably allocated region of | |
3672 | memory.</P> | |
3673 | <P> Multi-dimensional arrays are transformed into a pointer to an array | |
3674 | of one less dimension. For example:</P> | |
3675 | <DIV class="code"> | |
3676 | <PRE> | |
3677 | int [10]; // Maps to int * | |
3678 | int [10][20]; // Maps to int (*)[20] | |
3679 | int [10][20][30]; // Maps to int (*)[20][30] | |
3680 | </PRE> | |
3681 | </DIV> | |
3682 | <P> It is important to note that in the C type system, a | |
3683 | multidimensional array <TT>a[][]</TT> is<B> NOT</B> equivalent to a | |
3684 | single pointer <TT>*a</TT> or a double pointer such as <TT>**a</TT>. | |
3685 | Instead, a pointer to an array is used (as shown above) where the | |
3686 | actual value of the pointer is the starting memory location of the | |
3687 | array. The reader is strongly advised to dust off their C book and | |
3688 | re-read the section on arrays before using them with SWIG.</P> | |
3689 | <P> Array variables are supported, but are read-only by default. For | |
3690 | example:</P> | |
3691 | <DIV class="code"> | |
3692 | <PRE> | |
3693 | int a[100][200]; | |
3694 | </PRE> | |
3695 | </DIV> | |
3696 | <P> In this case, reading the variable 'a' returns a pointer of type <TT> | |
3697 | int (*)[200]</TT> that points to the first element of the array <TT> | |
3698 | &a[0][0]</TT>. Trying to modify 'a' results in an error. This is because | |
3699 | SWIG does not know how to copy data from the target language into the | |
3700 | array. To work around this limitation, you may want to write a few | |
3701 | simple assist functions like this:</P> | |
3702 | <DIV class="code"> | |
3703 | <PRE> | |
3704 | %inline %{ | |
3705 | void a_set(int i, int j, int val) { | |
3706 | a[i][j] = val; | |
3707 | } | |
3708 | int a_get(int i, int j) { | |
3709 | return a[i][j]; | |
3710 | } | |
3711 | %} | |
3712 | </PRE> | |
3713 | </DIV> | |
3714 | <P> To dynamically create arrays of various sizes and shapes, it may be | |
3715 | useful to write some helper functions in your interface. For example:</P> | |
3716 | <DIV class="code"> | |
3717 | <PRE> | |
3718 | // Some array helpers | |
3719 | %inline %{ | |
3720 | /* Create any sort of [size] array */ | |
3721 | int *int_array(int size) { | |
3722 | return (int *) malloc(size*sizeof(int)); | |
3723 | } | |
3724 | /* Create a two-dimension array [size][10] */ | |
3725 | int (*int_array_10(int size))[10] { | |
3726 | return (int (*)[10]) malloc(size*10*sizeof(int)); | |
3727 | } | |
3728 | %} | |
3729 | </PRE> | |
3730 | </DIV> | |
3731 | <P> Arrays of <TT>char</TT> are handled as a special case by SWIG. In | |
3732 | this case, strings in the target language can be stored in the array. | |
3733 | For example, if you have a declaration like this,</P> | |
3734 | <DIV class="code"> | |
3735 | <PRE> | |
3736 | char pathname[256]; | |
3737 | </PRE> | |
3738 | </DIV> | |
3739 | <P> SWIG generates functions for both getting and setting the value that | |
3740 | are equivalent to the following code:</P> | |
3741 | <DIV class="code"> | |
3742 | <PRE> | |
3743 | char *pathname_get() { | |
3744 | return pathname; | |
3745 | } | |
3746 | void pathname_set(char *value) { | |
3747 | strncpy(pathname,value,256); | |
3748 | } | |
3749 | </PRE> | |
3750 | </DIV> | |
3751 | <P> In the target language, the value can be set like a normal variable.</P> | |
3752 | <H3><A name="SWIG_readonly_variables"></A>5.4.6 Creating read-only | |
3753 | variables</H3> | |
3754 | <P> A read-only variable can be created by using the <TT>%immutable</TT> | |
3755 | directive as shown :</P> | |
3756 | <DIV class="code"> | |
3757 | <PRE> | |
3758 | // File : interface.i | |
3759 | ||
3760 | int a; // Can read/write | |
3761 | %immutable; | |
3762 | int b,c,d // Read only variables | |
3763 | %mutable; | |
3764 | double x,y // read/write | |
3765 | </PRE> | |
3766 | </DIV> | |
3767 | <P> The <TT>%immutable</TT> directive enables read-only mode until it is | |
3768 | explicitly disabled using the <TT>%mutable</TT> directive. As an | |
3769 | alternative to turning read-only mode off and on like this, individual | |
3770 | declarations can also be tagged as immutable. For example:</P> | |
3771 | <DIV class="code"> | |
3772 | <PRE> | |
3773 | %immutable x; // Make x read-only | |
3774 | ... | |
3775 | double x; // Read-only (from earlier %immutable directive) | |
3776 | double y; // Read-write | |
3777 | ... | |
3778 | </PRE> | |
3779 | </DIV> | |
3780 | <P> The <TT>%mutable</TT> and <TT>%immutable</TT> directives are | |
3781 | actually <A href="#features">%feature directives</A> defined like this:</P> | |
3782 | <DIV class="code"> | |
3783 | <PRE> | |
3784 | #define %immutable %feature("immutable") | |
3785 | #define %mutable %feature("immutable","") | |
3786 | </PRE> | |
3787 | </DIV> | |
3788 | <P> If you wanted to make all wrapped variables read-only, barring one | |
3789 | or two, it might be easier to take this approach:</P> | |
3790 | <DIV class="code"> | |
3791 | <PRE> | |
3792 | %immutable; // Make all variables read-only | |
3793 | %feature("immutable","0") x; // except, make x read/write | |
3794 | ... | |
3795 | double x; | |
3796 | double y; | |
3797 | double z; | |
3798 | ... | |
3799 | </PRE> | |
3800 | </DIV> | |
3801 | <P> Read-only variables are also created when declarations are declared | |
3802 | as <TT>const</TT>. For example:</P> | |
3803 | <DIV class="code"> | |
3804 | <PRE> | |
3805 | const int foo; /* Read only variable */ | |
3806 | char * const version="1.0"; /* Read only variable */ | |
3807 | </PRE> | |
3808 | </DIV> | |
3809 | <P><B> Compatibility note:</B> Read-only access used to be controlled by | |
3810 | a pair of directives <TT>%readonly</TT> and <TT>%readwrite</TT>. | |
3811 | Although these directives still work, they generate a warning message. | |
3812 | Simply change the directives to <TT>%immutable;</TT> and <TT>%mutable;</TT> | |
3813 | to silence the warning. Don't forget the extra semicolon!</P> | |
3814 | <H3><A name="SWIG_nn28"></A>5.4.7 Renaming and ignoring declarations</H3> | |
3815 | <P> Normally, the name of a C declaration is used when that declaration | |
3816 | is wrapped into the target language. However, this may generate a | |
3817 | conflict with a keyword or already existing function in the scripting | |
3818 | language. To resolve a name conflict, you can use the <TT>%rename</TT> | |
3819 | directive as shown :</P> | |
3820 | <DIV class="code"> | |
3821 | <PRE> | |
3822 | // interface.i | |
3823 | ||
3824 | %rename(my_print) print; | |
3825 | extern void print(char *); | |
3826 | ||
3827 | %rename(foo) a_really_long_and_annoying_name; | |
3828 | extern int a_really_long_and_annoying_name; | |
3829 | ||
3830 | </PRE> | |
3831 | </DIV> | |
3832 | <P> SWIG still calls the correct C function, but in this case the | |
3833 | function <TT>print()</TT> will really be called "<TT>my_print()</TT>" | |
3834 | in the target language.</P> | |
3835 | <P> The placement of the <TT>%rename</TT> directive is arbitrary as long | |
3836 | as it appears before the declarations to be renamed. A common technique | |
3837 | is to write code for wrapping a header file like this:</P> | |
3838 | <DIV class="code"> | |
3839 | <PRE> | |
3840 | // interface.i | |
3841 | ||
3842 | %rename(my_print) print; | |
3843 | %rename(foo) a_really_long_and_annoying_name; | |
3844 | ||
3845 | %include "header.h" | |
3846 | </PRE> | |
3847 | </DIV> | |
3848 | <P> <TT>%rename</TT> applies a renaming operation to all future | |
3849 | occurrences of a name. The renaming applies to functions, variables, | |
3850 | class and structure names, member functions, and member data. For | |
3851 | example, if you had two-dozen C++ classes, all with a member function | |
3852 | named `print' (which is a keyword in Python), you could rename them all | |
3853 | to `output' by specifying :</P> | |
3854 | <DIV class="code"> | |
3855 | <PRE> | |
3856 | %rename(output) print; // Rename all `print' functions to `output' | |
3857 | </PRE> | |
3858 | </DIV> | |
3859 | <P> SWIG does not normally perform any checks to see if the functions it | |
3860 | wraps are already defined in the target scripting language. However, if | |
3861 | you are careful about namespaces and your use of modules, you can | |
3862 | usually avoid these problems.</P> | |
3863 | <P> Closely related to <TT>%rename</TT> is the <TT>%ignore</TT> | |
3864 | directive. <TT>%ignore</TT> instructs SWIG to ignore declarations that | |
3865 | match a given identifier. For example:</P> | |
3866 | <DIV class="code"> | |
3867 | <PRE> | |
3868 | %ignore print; // Ignore all declarations named print | |
3869 | %ignore _HAVE_FOO_H; // Ignore an include guard constant | |
3870 | ... | |
3871 | %include "foo.h" // Grab a header file | |
3872 | ... | |
3873 | </PRE> | |
3874 | </DIV> | |
3875 | <P> One use of <TT>%ignore</TT> is to selectively remove certain | |
3876 | declarations from a header file without having to add conditional | |
3877 | compilation to the header. However, it should be stressed that this | |
3878 | only works for simple declarations. If you need to remove a whole | |
3879 | section of problematic code, the SWIG preprocessor should be used | |
3880 | instead.</P> | |
3881 | <P> More powerful variants of <TT>%rename</TT> and <TT>%ignore</TT> | |
3882 | directives can be used to help wrap C++ overloaded functions and | |
3883 | methods or C++ methods which use default arguments. This is described | |
3884 | in the <A href="#ambiguity_resolution_renaming">Ambiguity resolution | |
3885 | and renaming</A> section in the C++ chapter.</P> | |
3886 | <P><B> Compatibility note:</B> Older versions of SWIG provided a special | |
3887 | <TT>%name</TT> directive for renaming declarations. For example:</P> | |
3888 | <DIV class="code"> | |
3889 | <PRE> | |
3890 | %name(output) extern void print(char *); | |
3891 | </PRE> | |
3892 | </DIV> | |
3893 | <P> This directive is still supported, but it is deprecated and should | |
3894 | probably be avoided. The <TT>%rename</TT> directive is more powerful | |
3895 | and better supports wrapping of raw header file information.</P> | |
3896 | <H3><A name="SWIG_default_args"></A>5.4.8 Default/optional arguments</H3> | |
3897 | <P> SWIG supports default arguments in both C and C++ code. For example:</P> | |
3898 | <DIV class="code"> | |
3899 | <PRE> | |
3900 | int plot(double x, double y, int color=WHITE); | |
3901 | </PRE> | |
3902 | </DIV> | |
3903 | <P> In this case, SWIG generates wrapper code where the default | |
3904 | arguments are optional in the target language. For example, this | |
3905 | function could be used in Tcl as follows :</P> | |
3906 | <DIV class="targetlang"> | |
3907 | <PRE> | |
3908 | % plot -3.4 7.5 # Use default value | |
3909 | % plot -3.4 7.5 10 # set color to 10 instead | |
3910 | ||
3911 | </PRE> | |
3912 | </DIV> | |
3913 | <P> Although the ANSI C standard does not allow default arguments, | |
3914 | default arguments specified in a SWIG interface work with both C and | |
3915 | C++.</P> | |
3916 | <P><B> Note:</B> There is a subtle semantic issue concerning the use of | |
3917 | default arguments and the SWIG generated wrapper code. When default | |
3918 | arguments are used in C code, the default values are emitted into the | |
3919 | wrappers and the function is invoked with a full set of arguments. This | |
3920 | is different to when wrapping C++ where an overloaded wrapper method is | |
3921 | generated for each defaulted argument. Please refer to the section on <A | |
3922 | href="#SWIGPlus_default_args">default arguments</A> in the C++ chapter | |
3923 | for further details.</P> | |
3924 | <H3><A name="SWIG_nn30"></A>5.4.9 Pointers to functions and callbacks</H3> | |
3925 | <P> Occasionally, a C library may include functions that expect to | |
3926 | receive pointers to functions--possibly to serve as callbacks. SWIG | |
3927 | provides full support for function pointers provided that the callback | |
3928 | functions are defined in C and not in the target language. For example, | |
3929 | consider a function like this:</P> | |
3930 | <DIV class="code"> | |
3931 | <PRE> | |
3932 | int binary_op(int a, int b, int (*op)(int,int)); | |
3933 | </PRE> | |
3934 | </DIV> | |
3935 | <P> When you first wrap something like this into an extension module, | |
3936 | you may find the function to be impossible to use. For instance, in | |
3937 | Python:</P> | |
3938 | <DIV class="targetlang"> | |
3939 | <PRE> | |
3940 | >>> def add(x,y): | |
3941 | ... return x+y | |
3942 | ... | |
3943 | >>> binary_op(3,4,add) | |
3944 | Traceback (most recent call last): | |
3945 | File "<stdin>", line 1, in ? | |
3946 | TypeError: Type error. Expected _p_f_int_int__int | |
3947 | >>> | |
3948 | </PRE> | |
3949 | </DIV> | |
3950 | <P> The reason for this error is that SWIG doesn't know how to map a | |
3951 | scripting language function into a C callback. However, existing C | |
3952 | functions can be used as arguments provided you install them as | |
3953 | constants. One way to do this is to use the <TT>%constant</TT> | |
3954 | directive like this:</P> | |
3955 | <DIV class="code"> | |
3956 | <PRE> | |
3957 | /* Function with a callback */ | |
3958 | int binary_op(int a, int b, int (*op)(int,int)); | |
3959 | ||
3960 | /* Some callback functions */ | |
3961 | %constant int add(int,int); | |
3962 | %constant int sub(int,int); | |
3963 | %constant int mul(int,int); | |
3964 | </PRE> | |
3965 | </DIV> | |
3966 | <P> In this case, <TT>add</TT>, <TT>sub</TT>, and <TT>mul</TT> become | |
3967 | function pointer constants in the target scripting language. This | |
3968 | allows you to use them as follows:</P> | |
3969 | <DIV class="targetlang"> | |
3970 | <PRE> | |
3971 | >>> binary_op(3,4,add) | |
3972 | 7 | |
3973 | >>> binary_op(3,4,mul) | |
3974 | 12 | |
3975 | >>> | |
3976 | </PRE> | |
3977 | </DIV> | |
3978 | <P> Unfortunately, by declaring the callback functions as constants, | |
3979 | they are no longer accesible as functions. For example:</P> | |
3980 | <DIV class="targetlang"> | |
3981 | <PRE> | |
3982 | >>> add(3,4) | |
3983 | Traceback (most recent call last): | |
3984 | File "<stdin>", line 1, in ? | |
3985 | TypeError: object is not callable: '_ff020efc_p_f_int_int__int' | |
3986 | >>> | |
3987 | </PRE> | |
3988 | </DIV> | |
3989 | <P> If you want to make a function available as both a callback function | |
3990 | and a function, you can use the <TT>%callback</TT> and <TT>%nocallback</TT> | |
3991 | directives like this:</P> | |
3992 | <DIV class="code"> | |
3993 | <PRE> | |
3994 | /* Function with a callback */ | |
3995 | int binary_op(int a, int b, int (*op)(int,int)); | |
3996 | ||
3997 | /* Some callback functions */ | |
3998 | %callback("%s_cb") | |
3999 | int add(int,int); | |
4000 | int sub(int,int); | |
4001 | int mul(int,int); | |
4002 | %nocallback | |
4003 | </PRE> | |
4004 | </DIV> | |
4005 | <P> The argument to <TT>%callback</TT> is a printf-style format string | |
4006 | that specifies the naming convention for the callback constants (<TT>%s</TT> | |
4007 | gets replaced by the function name). The callback mode remains in | |
4008 | effect until it is explicitly disabled using <TT>%nocallback</TT>. When | |
4009 | you do this, the interface now works as follows:</P> | |
4010 | <DIV class="targetlang"> | |
4011 | <PRE> | |
4012 | >>> binary_op(3,4,add_cb) | |
4013 | 7 | |
4014 | >>> binary_op(3,4,mul_cb) | |
4015 | 12 | |
4016 | >>> add(3,4) | |
4017 | 7 | |
4018 | >>> mul(3,4) | |
4019 | 12 | |
4020 | </PRE> | |
4021 | </DIV> | |
4022 | <P> Notice that when the function is used as a callback, special names | |
4023 | such as <TT>add_cb</TT> is used instead. To call the function normally, | |
4024 | just use the original function name such as <TT>add()</TT>.</P> | |
4025 | <P> SWIG provides a number of extensions to standard C printf formatting | |
4026 | that may be useful in this context. For instance, the following | |
4027 | variation installs the callbacks as all upper-case constants such as <TT> | |
4028 | ADD</TT>, <TT>SUB</TT>, and <TT>MUL</TT>:</P> | |
4029 | <DIV class="code"> | |
4030 | <PRE> | |
4031 | /* Some callback functions */ | |
4032 | %callback("%(upper)s") | |
4033 | int add(int,int); | |
4034 | int sub(int,int); | |
4035 | int mul(int,int); | |
4036 | %nocallback | |
4037 | </PRE> | |
4038 | </DIV> | |
4039 | <P> A format string of <TT>"%(lower)s"</TT> converts all characters to | |
4040 | lower-case. A string of <TT>"%(title)s"</TT> capitalizes the first | |
4041 | character and converts the rest to lower case.</P> | |
4042 | <P> And now, a final note about function pointer support. Although SWIG | |
4043 | does not normally allow callback functions to be written in the target | |
4044 | language, this can be accomplished with the use of typemaps and other | |
4045 | advanced SWIG features. This is described in a later chapter.</P> | |
4046 | <H2><A name="SWIG_nn31"></A>5.5 Structures and unions</H2> | |
4047 | <P> This section describes the behavior of SWIG when processing ANSI C | |
4048 | structures and union declarations. Extensions to handle C++ are | |
4049 | described in the next section.</P> | |
4050 | <P> If SWIG encounters the definition of a structure or union, it | |
4051 | creates a set of accessor functions. Although SWIG does not need | |
4052 | structure definitions to build an interface, providing definitions make | |
4053 | it possible to access structure members. The accessor functions | |
4054 | generated by SWIG simply take a pointer to an object and allow access | |
4055 | to an individual member. For example, the declaration :</P> | |
4056 | <DIV class="code"> | |
4057 | <PRE> | |
4058 | struct Vector { | |
4059 | double x,y,z; | |
4060 | } | |
4061 | ||
4062 | </PRE> | |
4063 | </DIV> | |
4064 | <P> gets transformed into the following set of accessor functions :</P> | |
4065 | <DIV class="code"> | |
4066 | <PRE> | |
4067 | double Vector_x_get(struct Vector *obj) { | |
4068 | return obj->x; | |
4069 | } | |
4070 | double Vector_y_get(struct Vector *obj) { | |
4071 | return obj->y; | |
4072 | } | |
4073 | double Vector_z_get(struct Vector *obj) { | |
4074 | return obj->z; | |
4075 | } | |
4076 | void Vector_x_set(struct Vector *obj, double value) { | |
4077 | obj->x = value; | |
4078 | } | |
4079 | void Vector_y_set(struct Vector *obj, double value) { | |
4080 | obj->y = value; | |
4081 | } | |
4082 | void Vector_z_set(struct Vector *obj, double value) { | |
4083 | obj->z = value; | |
4084 | } | |
4085 | </PRE> | |
4086 | </DIV> | |
4087 | <P> In addition, SWIG creates default constructor and destructor | |
4088 | functions if none are defined in the interface. For example:</P> | |
4089 | <DIV class="code"> | |
4090 | <PRE> | |
4091 | struct Vector *new_Vector() { | |
4092 | return (Vector *) calloc(1,sizeof(struct Vector)); | |
4093 | } | |
4094 | void delete_Vector(struct Vector *obj) { | |
4095 | free(obj); | |
4096 | } | |
4097 | </PRE> | |
4098 | </DIV> | |
4099 | <P> Using these low-level accessor functions, an object can be minimally | |
4100 | manipulated from the target language using code like this:</P> | |
4101 | <DIV class="code"> | |
4102 | <PRE> | |
4103 | v = new_Vector() | |
4104 | Vector_x_set(v,2) | |
4105 | Vector_y_set(v,10) | |
4106 | Vector_z_set(v,-5) | |
4107 | ... | |
4108 | delete_Vector(v) | |
4109 | </PRE> | |
4110 | </DIV> | |
4111 | <P> However, most of SWIG's language modules also provide a high-level | |
4112 | interface that is more convenient. Keep reading.</P> | |
4113 | <H3><A name="SWIG_nn32"></A>5.5.1 Typedef and structures</H3> | |
4114 | <P> SWIG supports the following construct which is quite common in C | |
4115 | programs :</P> | |
4116 | <DIV class="code"> | |
4117 | <PRE> | |
4118 | typedef struct { | |
4119 | double x,y,z; | |
4120 | } Vector; | |
4121 | ||
4122 | </PRE> | |
4123 | </DIV> | |
4124 | <P> When encountered, SWIG assumes that the name of the object is | |
4125 | `Vector' and creates accessor functions like before. The only | |
4126 | difference is that the use of <TT>typedef</TT> allows SWIG to drop the <TT> | |
4127 | struct</TT> keyword on its generated code. For example:</P> | |
4128 | <DIV class="code"> | |
4129 | <PRE> | |
4130 | double Vector_x_get(Vector *obj) { | |
4131 | return obj->x; | |
4132 | } | |
4133 | </PRE> | |
4134 | </DIV> | |
4135 | <P> If two different names are used like this :</P> | |
4136 | <DIV class="code"> | |
4137 | <PRE> | |
4138 | typedef struct vector_struct { | |
4139 | double x,y,z; | |
4140 | } Vector; | |
4141 | ||
4142 | </PRE> | |
4143 | </DIV> | |
4144 | <P> the name <TT>Vector</TT> is used instead of <TT>vector_struct</TT> | |
4145 | since this is more typical C programming style. If declarations defined | |
4146 | later in the interface use the type <TT>struct vector_struct</TT>, SWIG | |
4147 | knows that this is the same as <TT>Vector</TT> and it generates the | |
4148 | appropriate type-checking code.</P> | |
4149 | <H3><A name="SWIG_nn33"></A>5.5.2 Character strings and structures</H3> | |
4150 | <P> Structures involving character strings require some care. SWIG | |
4151 | assumes that all members of type <TT>char *</TT> have been dynamically | |
4152 | allocated using <TT>malloc()</TT> and that they are NULL-terminated | |
4153 | ASCII strings. When such a member is modified, the previously contents | |
4154 | will be released, and the new contents allocated. For example :</P> | |
4155 | <DIV class="code"> | |
4156 | <PRE> | |
4157 | %module mymodule | |
4158 | ... | |
4159 | struct Foo { | |
4160 | char *name; | |
4161 | ... | |
4162 | } | |
4163 | ||
4164 | </PRE> | |
4165 | </DIV> | |
4166 | <P> This results in the following accessor functions :</P> | |
4167 | <DIV class="code"> | |
4168 | <PRE> | |
4169 | char *Foo_name_get(Foo *obj) { | |
4170 | return Foo->name; | |
4171 | } | |
4172 | ||
4173 | char *Foo_name_set(Foo *obj, char *c) { | |
4174 | if (obj->name) free(obj->name); | |
4175 | obj->name = (char *) malloc(strlen(c)+1); | |
4176 | strcpy(obj->name,c); | |
4177 | return obj->name; | |
4178 | } | |
4179 | </PRE> | |
4180 | </DIV> | |
4181 | <P> If this behavior differs from what you need in your applications, | |
4182 | the SWIG "memberin" typemap can be used to change it. See the typemaps | |
4183 | chapter for further details.</P> | |
4184 | <P> Note: If the <TT>-c++</TT> option is used, <TT>new</TT> and <TT> | |
4185 | delete</TT> are used to perform memory allocation.</P> | |
4186 | <H3><A name="SWIG_nn34"></A>5.5.3 Array members</H3> | |
4187 | <P> Arrays may appear as the members of structures, but they will be | |
4188 | read-only. SWIG will write an accessor function that returns the | |
4189 | pointer to the first element of the array, but will not write a | |
4190 | function to change the contents of the array itself. When this | |
4191 | situation is detected, SWIG may generate a warning message such as the | |
4192 | following :</P> | |
4193 | <DIV class="shell"> | |
4194 | <PRE> | |
4195 | interface.i:116. Warning. Array member will be read-only | |
4196 | </PRE> | |
4197 | </DIV> | |
4198 | <P> To eliminate the warning message, typemaps can be used, but this is | |
4199 | discussed in a later chapter. In many cases, the warning message is | |
4200 | harmless.</P> | |
4201 | <H3><A name="SWIG_nn35"></A>5.5.4 Structure data members</H3> | |
4202 | <P> Occasionally, a structure will contain data members that are | |
4203 | themselves structures. For example:</P> | |
4204 | <DIV class="code"> | |
4205 | <PRE> | |
4206 | typedef struct Foo { | |
4207 | int x; | |
4208 | } Foo; | |
4209 | ||
4210 | typedef struct Bar { | |
4211 | int y; | |
4212 | Foo f; /* struct member */ | |
4213 | } Bar; | |
4214 | </PRE> | |
4215 | </DIV> | |
4216 | <P> When a structure member is wrapped, it is always handled as a | |
4217 | pointer. For example:</P> | |
4218 | <DIV class="code"> | |
4219 | <PRE> | |
4220 | Foo *Bar_f_get(Bar *b) { | |
4221 | return &b->f; | |
4222 | } | |
4223 | void Bar_f_set(Bar *b, Foo *value) { | |
4224 | b->f = *value; | |
4225 | } | |
4226 | </PRE> | |
4227 | </DIV> | |
4228 | <P> The reasons for this are somewhat subtle but have to do with the | |
4229 | problem of modifying and accessing data inside the data member. For | |
4230 | example, suppose you wanted to modify the value of <TT>f.x</TT> of a <TT> | |
4231 | Bar</TT> object like this:</P> | |
4232 | <DIV class="code"> | |
4233 | <PRE> | |
4234 | Bar *b; | |
4235 | b->f.x = 37; | |
4236 | </PRE> | |
4237 | </DIV> | |
4238 | <P> Translating this assignment to function calls (as would be used | |
4239 | inside the scripting language interface) results in the following code:</P> | |
4240 | <DIV class="code"> | |
4241 | <PRE> | |
4242 | Bar *b; | |
4243 | Foo_x_set(Bar_f_get(b),37); | |
4244 | </PRE> | |
4245 | </DIV> | |
4246 | <P> In this code, if the <TT>Bar_f_get()</TT> function were to return a <TT> | |
4247 | Foo</TT> instead of a <TT>Foo *</TT>, then the resulting modification | |
4248 | would be applied to a<EM> copy</EM> of <TT>f</TT> and not the data | |
4249 | member <TT>f</TT> itself. Clearly that's not what you want!</P> | |
4250 | <P> It should be noted that this transformation to pointers only occurs | |
4251 | if SWIG knows that a data member is a structure or class. For instance, | |
4252 | if you had a structure like this,</P> | |
4253 | <DIV class="code"> | |
4254 | <PRE> | |
4255 | struct Foo { | |
4256 | WORD w; | |
4257 | }; | |
4258 | </PRE> | |
4259 | </DIV> | |
4260 | <P> and nothing was known about <TT>WORD</TT>, then SWIG will generate | |
4261 | more normal accessor functions like this:</P> | |
4262 | <DIV class="code"> | |
4263 | <PRE> | |
4264 | WORD Foo_w_get(Foo *f) { | |
4265 | return f->w; | |
4266 | } | |
4267 | void Foo_w_set(FOO *f, WORD value) { | |
4268 | f->w = value; | |
4269 | } | |
4270 | </PRE> | |
4271 | </DIV> | |
4272 | <P><B> Compatibility Note:</B> SWIG-1.3.11 and earlier releases | |
4273 | transformed all non-primitive member datatypes to pointers. Starting in | |
4274 | SWIG-1.3.12, this transformation<EM> only</EM> occurs if a datatype is | |
4275 | known to be a structure, class, or union. This is unlikely to break | |
4276 | existing code. However, if you need to tell SWIG that an undeclared | |
4277 | datatype is really a struct, simply use a forward struct declaration | |
4278 | such as <TT>"struct Foo;"</TT>.</P> | |
4279 | <H3><A name="SWIG_nn36"></A>5.5.5 C constructors and destructors</H3> | |
4280 | <P> When wrapping structures, it is generally useful to have a mechanism | |
4281 | for creating and destroying objects. If you don't do anything, SWIG | |
4282 | will automatically generate functions for creating and destroying | |
4283 | objects using <TT>malloc()</TT> and <TT>free()</TT>. Note: the use of <TT> | |
4284 | malloc()</TT> only applies when SWIG is used on C code (i.e., when the <TT> | |
4285 | -c++</TT> option is<EM> not</EM> supplied on the command line). C++ is | |
4286 | handled differently.</P> | |
4287 | <P> If you don't want SWIG to generate constructors and destructors, you | |
4288 | can use the <TT>%nodefault</TT> directive or the <TT>-no_default</TT> | |
4289 | command line option. For example:</P> | |
4290 | <DIV class="shell"> | |
4291 | <PRE> | |
4292 | swig -no_default example.i | |
4293 | </PRE> | |
4294 | </DIV> | |
4295 | <P> or</P> | |
4296 | <DIV class="code"> | |
4297 | <PRE> | |
4298 | %module foo | |
4299 | ... | |
4300 | %nodefault; // Don't create default constructors/destructors | |
4301 | ... declarations ... | |
4302 | %makedefault; // Reenable default constructors/destructors | |
4303 | </PRE> | |
4304 | </DIV> | |
4305 | <P> If you need more precise control, <TT>%nodefault</TT> can | |
4306 | selectively target individual structure definitions. For example:</P> | |
4307 | <DIV class="code"> | |
4308 | <PRE> | |
4309 | %nodefault Foo; // No default constructor/destructors for Foo | |
4310 | ... | |
4311 | struct Foo { // No default generated. | |
4312 | }; | |
4313 | ||
4314 | struct Bar { // Default constructor/destructor generated. | |
4315 | }; | |
4316 | </PRE> | |
4317 | </DIV> | |
4318 | <P><B> Compatibility note:</B> Prior to SWIG-1.3.7, SWIG did not | |
4319 | generate default constructors or destructors unless you explicitly | |
4320 | turned them on using <TT>-make_default</TT>. However, it appears that | |
4321 | most users want to have constructor and destructor functions so it has | |
4322 | now been enabled as the default behavior.</P> | |
4323 | <H3><A name="SWIG_adding_member_functions"></A>5.5.6 Adding member | |
4324 | functions to C structures</H3> | |
4325 | <P> Most languages provide a mechanism for creating classes and | |
4326 | supporting object oriented programming. From a C standpoint, object | |
4327 | oriented programming really just boils down to the process of attaching | |
4328 | functions to structures. These functions normally operate on an | |
4329 | instance of the structure (or object). Although there is a natural | |
4330 | mapping of C++ to such a scheme, there is no direct mechanism for | |
4331 | utilizing it with C code. However, SWIG provides a special <TT>%extend</TT> | |
4332 | directive that makes it possible to attach methods to C structures for | |
4333 | purposes of building an object oriented interface. Suppose you have a C | |
4334 | header file with the following declaration :</P> | |
4335 | <DIV class="code"> | |
4336 | <PRE> | |
4337 | /* file : vector.h */ | |
4338 | ... | |
4339 | typedef struct { | |
4340 | double x,y,z; | |
4341 | } Vector; | |
4342 | ||
4343 | </PRE> | |
4344 | </DIV> | |
4345 | <P> You can make a <TT>Vector</TT> look alot like a class by writing a | |
4346 | SWIG interface like this:</P> | |
4347 | <DIV class="code"> | |
4348 | <PRE> | |
4349 | // file : vector.i | |
4350 | %module mymodule | |
4351 | %{ | |
4352 | #include "vector.h" | |
4353 | %} | |
4354 | ||
4355 | %include vector.h // Just grab original C header file | |
4356 | %extend Vector { // Attach these functions to struct Vector | |
4357 | Vector(double x, double y, double z) { | |
4358 | Vector *v; | |
4359 | v = (Vector *) malloc(sizeof(Vector)); | |
4360 | v->x = x; | |
4361 | v->y = y; | |
4362 | v->z = z; | |
4363 | return v; | |
4364 | } | |
4365 | ~Vector() { | |
4366 | free(self); | |
4367 | } | |
4368 | double magnitude() { | |
4369 | return sqrt(self->x*self->x+self->y*self->y+self->z*self->z); | |
4370 | } | |
4371 | void print() { | |
4372 | printf("Vector [%g, %g, %g]\n", self->x,self->y,self->z); | |
4373 | } | |
4374 | }; | |
4375 | ||
4376 | </PRE> | |
4377 | </DIV> | |
4378 | <P> Now, when used with proxy classes in Python, you can do things like | |
4379 | this :</P> | |
4380 | <DIV class="targetlang"> | |
4381 | <PRE> | |
4382 | >>> v = Vector(3,4,0) # Create a new vector | |
4383 | >>> print v.magnitude() # Print magnitude | |
4384 | 5.0 | |
4385 | >>> v.print() # Print it out | |
4386 | [ 3, 4, 0 ] | |
4387 | >>> del v # Destroy it | |
4388 | </PRE> | |
4389 | </DIV> | |
4390 | <P> The <TT>%extend</TT> directive can also be used inside the | |
4391 | definition of the Vector structure. For example:</P> | |
4392 | <DIV class="code"> | |
4393 | <PRE> | |
4394 | // file : vector.i | |
4395 | %module mymodule | |
4396 | %{ | |
4397 | #include "vector.h" | |
4398 | %} | |
4399 | ||
4400 | typedef struct { | |
4401 | double x,y,z; | |
4402 | %extend { | |
4403 | Vector(double x, double y, double z) { ... } | |
4404 | ~Vector() { ... } | |
4405 | ... | |
4406 | } | |
4407 | } Vector; | |
4408 | </PRE> | |
4409 | </DIV> | |
4410 | <P> Finally, <TT>%extend</TT> can be used to access externally written | |
4411 | functions provided they follow the naming convention used in this | |
4412 | example :</P> | |
4413 | <DIV class="code"> | |
4414 | <PRE> | |
4415 | /* File : vector.c */ | |
4416 | /* Vector methods */ | |
4417 | #include "vector.h" | |
4418 | Vector *new_Vector(double x, double y, double z) { | |
4419 | Vector *v; | |
4420 | v = (Vector *) malloc(sizeof(Vector)); | |
4421 | v->x = x; | |
4422 | v->y = y; | |
4423 | v->z = z; | |
4424 | return v; | |
4425 | } | |
4426 | void delete_Vector(Vector *v) { | |
4427 | free(v); | |
4428 | } | |
4429 | ||
4430 | double Vector_magnitude(Vector *v) { | |
4431 | return sqrt(v->x*v->x+v->y*v->y+v->z*v->z); | |
4432 | } | |
4433 | ||
4434 | // File : vector.i | |
4435 | // Interface file | |
4436 | %module mymodule | |
4437 | %{ | |
4438 | #include "vector.h" | |
4439 | %} | |
4440 | ||
4441 | typedef struct { | |
4442 | double x,y,z; | |
4443 | %extend { | |
4444 | Vector(int,int,int); // This calls new_Vector() | |
4445 | ~Vector(); // This calls delete_Vector() | |
4446 | double magnitude(); // This will call Vector_magnitude() | |
4447 | ... | |
4448 | } | |
4449 | } Vector; | |
4450 | </PRE> | |
4451 | </DIV> | |
4452 | <P> A little known feature of the <TT>%extend</TT> directive is that it | |
4453 | can also be used to add synthesized attributes or to modify the | |
4454 | behavior of existing data attributes. For example, suppose you wanted | |
4455 | to make <TT>magnitude</TT> a read-only attribute of <TT>Vector</TT> | |
4456 | instead of a method. To do this, you might write some code like this:</P> | |
4457 | <DIV class="code"> | |
4458 | <PRE> | |
4459 | // Add a new attribute to Vector | |
4460 | %extend Vector { | |
4461 | const double magnitude; | |
4462 | } | |
4463 | // Now supply the implementation of the Vector_magnitude_get function | |
4464 | %{ | |
4465 | const double Vector_magnitude_get(Vector *v) { | |
4466 | return (const double) return sqrt(v->x*v->x+v->y*v->y+v->z*v->z); | |
4467 | } | |
4468 | %} | |
4469 | ||
4470 | </PRE> | |
4471 | </DIV> | |
4472 | <P> Now, for all practial purposes, <TT>magnitude</TT> will appear like | |
4473 | an attribute of the object.</P> | |
4474 | <P> A similar technique can also be used to work with problematic data | |
4475 | members. For example, consider this interface:</P> | |
4476 | <DIV class="code"> | |
4477 | <PRE> | |
4478 | struct Person { | |
4479 | char name[50]; | |
4480 | ... | |
4481 | } | |
4482 | </PRE> | |
4483 | </DIV> | |
4484 | <P> By default, the <TT>name</TT> attribute is read-only because SWIG | |
4485 | does not normally know how to modify arrays. However, you can rewrite | |
4486 | the interface as follows to change this:</P> | |
4487 | <DIV class="code"> | |
4488 | <PRE> | |
4489 | struct Person { | |
4490 | %extend { | |
4491 | char *name; | |
4492 | } | |
4493 | ... | |
4494 | } | |
4495 | ||
4496 | // Specific implementation of set/get functions | |
4497 | %{ | |
4498 | char *Person_name_get(Person *p) { | |
4499 | return p->name; | |
4500 | } | |
4501 | void Person_name_set(Person *p, char *val) { | |
4502 | strncpy(p->name,val,50); | |
4503 | } | |
4504 | %} | |
4505 | </PRE> | |
4506 | </DIV> | |
4507 | <P> Finally, it should be stressed that even though <TT>%extend</TT> can | |
4508 | be used to add new data members, these new members can not require the | |
4509 | allocation of additional storage in the object (e.g., their values must | |
4510 | be entirely synthesized from existing attributes of the structure).</P> | |
4511 | <P><B> Compatibility note:</B> The <TT>%extend</TT> directive is a new | |
4512 | name for the <TT>%addmethods</TT> directive. Since <TT>%addmethods</TT> | |
4513 | could be used to extend a structure with more than just methods, a more | |
4514 | suitable directive name has been chosen.</P> | |
4515 | <H3><A name="SWIG_nn38"></A>5.5.7 Nested structures</H3> | |
4516 | <P> Occasionally, a C program will involve structures like this :</P> | |
4517 | <DIV class="code"> | |
4518 | <PRE> | |
4519 | typedef struct Object { | |
4520 | int objtype; | |
4521 | union { | |
4522 | int ivalue; | |
4523 | double dvalue; | |
4524 | char *strvalue; | |
4525 | void *ptrvalue; | |
4526 | } intRep; | |
4527 | } Object; | |
4528 | ||
4529 | </PRE> | |
4530 | </DIV> | |
4531 | <P> When SWIG encounters this, it performs a structure splitting | |
4532 | operation that transforms the declaration into the equivalent of the | |
4533 | following:</P> | |
4534 | <DIV class="code"> | |
4535 | <PRE> | |
4536 | typedef union { | |
4537 | int ivalue; | |
4538 | double dvalue; | |
4539 | char *strvalue; | |
4540 | void *ptrvalue; | |
4541 | } Object_intRep; | |
4542 | ||
4543 | typedef struct Object { | |
4544 | int objType; | |
4545 | Object_intRep intRep; | |
4546 | } Object; | |
4547 | ||
4548 | </PRE> | |
4549 | </DIV> | |
4550 | <P> SWIG will then create an <TT>Object_intRep</TT> structure for use | |
4551 | inside the interface file. Accessor functions will be created for both | |
4552 | structures. In this case, functions like this would be created :</P> | |
4553 | <DIV class="code"> | |
4554 | <PRE> | |
4555 | Object_intRep *Object_intRep_get(Object *o) { | |
4556 | return (Object_intRep *) &o->intRep; | |
4557 | } | |
4558 | int Object_intRep_ivalue_get(Object_intRep *o) { | |
4559 | return o->ivalue; | |
4560 | } | |
4561 | int Object_intRep_ivalue_set(Object_intRep *o, int value) { | |
4562 | return (o->ivalue = value); | |
4563 | } | |
4564 | double Object_intRep_dvalue_get(Object_intRep *o) { | |
4565 | return o->dvalue; | |
4566 | } | |
4567 | ... etc ... | |
4568 | ||
4569 | </PRE> | |
4570 | </DIV> | |
4571 | <P> Although this process is a little hairy, it works like you would | |
4572 | expect in the target scripting language--especially when proxy classes | |
4573 | are used. For instance, in Perl:</P> | |
4574 | <DIV class="targetlang"> | |
4575 | <PRE> | |
4576 | # Perl5 script for accessing nested member | |
4577 | $o = CreateObject(); # Create an object somehow | |
4578 | $o->{intRep}->{ivalue} = 7 # Change value of o.intRep.ivalue | |
4579 | </PRE> | |
4580 | </DIV> | |
4581 | <P> If you have a lot nested structure declarations, it is advisable to | |
4582 | double-check them after running SWIG. Although, there is a good chance | |
4583 | that they will work, you may have to modify the interface file in | |
4584 | certain cases.</P> | |
4585 | <H3><A name="SWIG_nn39"></A>5.5.8 Other things to note about structure | |
4586 | wrapping</H3> | |
4587 | <P> SWIG doesn't care if the declaration of a structure in a <TT>.i</TT> | |
4588 | file exactly matches that used in the underlying C code (except in the | |
4589 | case of nested structures). For this reason, there are no problems | |
4590 | omitting problematic members or simply omitting the structure | |
4591 | definition altogether. If you are happy passing pointers around, this | |
4592 | can be done without ever giving SWIG a structure definition.</P> | |
4593 | <P> Starting with SWIG1.3, a number of improvements have been made to | |
4594 | SWIG's code generator. Specifically, even though structure access has | |
4595 | been described in terms of high-level accessor functions such as this,</P> | |
4596 | <DIV class="code"> | |
4597 | <PRE> | |
4598 | double Vector_x_get(Vector *v) { | |
4599 | return v->x; | |
4600 | } | |
4601 | </PRE> | |
4602 | </DIV> | |
4603 | <P> most of the generated code is actually inlined directly into wrapper | |
4604 | functions. Therefore, no function <TT>Vector_x_get()</TT> actually | |
4605 | exists in the generated wrapper file. For example, when creating a Tcl | |
4606 | module, the following function is generated instead:</P> | |
4607 | <DIV class="code"> | |
4608 | <PRE> | |
4609 | static int | |
4610 | _wrap_Vector_x_get(ClientData clientData, Tcl_Interp *interp, | |
4611 | int objc, Tcl_Obj *CONST objv[]) { | |
4612 | struct Vector *arg1 ; | |
4613 | double result ; | |
4614 | ||
4615 | if (SWIG_GetArgs(interp, objc, objv,"p:Vector_x_get self ",&arg0, | |
4616 | SWIGTYPE_p_Vector) == TCL_ERROR) | |
4617 | return TCL_ERROR; | |
4618 | result = (double ) (arg1->x); | |
4619 | Tcl_SetObjResult(interp,Tcl_NewDoubleObj((double) result)); | |
4620 | return TCL_OK; | |
4621 | } | |
4622 | </PRE> | |
4623 | </DIV> | |
4624 | <P> The only exception to this rule are methods defined with <TT>%extend</TT> | |
4625 | . In this case, the added code is contained in a separate function.</P> | |
4626 | <P> Finally, it is important to note that most language modules may | |
4627 | choose to build a more advanced interface. Although you may never use | |
4628 | the low-level interface described here, most of SWIG's language modules | |
4629 | use it in some way or another.</P> | |
4630 | <H2><A name="SWIG_nn40"></A>5.6 Code Insertion</H2> | |
4631 | <P> Sometimes it is necessary to insert special code into the resulting | |
4632 | wrapper file generated by SWIG. For example, you may want to include | |
4633 | additional C code to perform initialization or other operations. There | |
4634 | are four common ways to insert code, but it's useful to know how the | |
4635 | output of SWIG is structured first.</P> | |
4636 | <H3><A name="SWIG_nn41"></A>5.6.1 The output of SWIG</H3> | |
4637 | <P> When SWIG creates its output file, it is broken up into four | |
4638 | sections corresponding to runtime code, headers, wrapper functions, and | |
4639 | module initialization code (in that order).</P> | |
4640 | <UL> | |
4641 | <LI><B>Runtime code</B>. | |
4642 | <BR> This code is internal to SWIG and is used to include type-checking | |
4643 | and other support functions that are used by the rest of the module.</LI> | |
4644 | <LI><B>Header section</B>. | |
4645 | <BR> This is user-defined support code that has been included by the <TT> | |
4646 | %{ ... %}</TT> directive. Usually this consists of header files and | |
4647 | other helper functions.</LI> | |
4648 | <LI><B>Wrapper code</B>. | |
4649 | <BR> These are the wrappers generated automatically by SWIG.</LI> | |
4650 | <LI><B>Module initialization</B>. | |
4651 | <BR> The function generated by SWIG to initialize the module upon | |
4652 | loading.</LI> | |
4653 | </UL> | |
4654 | <H3><A name="SWIG_nn42"></A>5.6.2 Code insertion blocks</H3> | |
4655 | <P> Code is inserted into the appropriate code section by using one of | |
4656 | the following code insertion directives:</P> | |
4657 | <DIV class="code"> | |
4658 | <PRE> | |
4659 | %runtime %{ | |
4660 | ... code in runtime section ... | |
4661 | %} | |
4662 | ||
4663 | %header %{ | |
4664 | ... code in header section ... | |
4665 | %} | |
4666 | ||
4667 | %wrapper %{ | |
4668 | ... code in wrapper section ... | |
4669 | %} | |
4670 | ||
4671 | %init %{ | |
4672 | ... code in init section ... | |
4673 | %} | |
4674 | </PRE> | |
4675 | </DIV> | |
4676 | <P> The bare <TT>%{ ... %}</TT> directive is a shortcut that is the same | |
4677 | as <TT>%header %{ ... %}</TT>.</P> | |
4678 | <P> Everything in a code insertion block is copied verbatim into the | |
4679 | output file and is not parsed by SWIG. Most SWIG input files have at | |
4680 | least one such block to include header files and support C code. | |
4681 | Additional code blocks may be placed anywhere in a SWIG file as needed.</P> | |
4682 | <DIV class="code"> | |
4683 | <PRE> | |
4684 | %module mymodule | |
4685 | %{ | |
4686 | #include "my_header.h" | |
4687 | %} | |
4688 | ... Declare functions here | |
4689 | %{ | |
4690 | ||
4691 | void some_extra_function() { | |
4692 | ... | |
4693 | } | |
4694 | %} | |
4695 | </PRE> | |
4696 | </DIV> | |
4697 | <P> A common use for code blocks is to write "helper" functions. These | |
4698 | are functions that are used specifically for the purpose of building an | |
4699 | interface, but which are generally not visible to the normal C program. | |
4700 | For example :</P> | |
4701 | <DIV class="code"> | |
4702 | <PRE> | |
4703 | %{ | |
4704 | /* Create a new vector */ | |
4705 | static Vector *new_Vector() { | |
4706 | return (Vector *) malloc(sizeof(Vector)); | |
4707 | } | |
4708 | ||
4709 | %} | |
4710 | // Now wrap it | |
4711 | Vector *new_Vector(); | |
4712 | </PRE> | |
4713 | </DIV> | |
4714 | <H3><A name="SWIG_nn43"></A>5.6.3 Inlined code blocks</H3> | |
4715 | <P> Since the process of writing helper functions is fairly common, | |
4716 | there is a special inlined form of code block that is used as follows :</P> | |
4717 | <DIV class="code"> | |
4718 | <PRE> | |
4719 | %inline %{ | |
4720 | /* Create a new vector */ | |
4721 | Vector *new_Vector() { | |
4722 | return (Vector *) malloc(sizeof(Vector)); | |
4723 | } | |
4724 | %} | |
4725 | ||
4726 | </PRE> | |
4727 | </DIV> | |
4728 | <P> The <TT>%inline</TT> directive inserts all of the code that follows | |
4729 | verbatim into the header portion of an interface file. The code is then | |
4730 | parsed by both the SWIG preprocessor and parser. Thus, the above | |
4731 | example creates a new command <TT>new_Vector</TT> using only one | |
4732 | declaration. Since the code inside an <TT>%inline %{ ... %}</TT> block | |
4733 | is given to both the C compiler and SWIG, it is illegal to include any | |
4734 | SWIG directives inside a <TT>%{ ... %}</TT> block.</P> | |
4735 | <H3><A name="SWIG_nn44"></A>5.6.4 Initialization blocks</H3> | |
4736 | <P> When code is included in the <TT>%init</TT> section, it is copied | |
4737 | directly into the module initialization function. For example, if you | |
4738 | needed to perform some extra initialization on module loading, you | |
4739 | could write this:</P> | |
4740 | <DIV class="code"> | |
4741 | <PRE> | |
4742 | %init %{ | |
4743 | init_variables(); | |
4744 | %} | |
4745 | </PRE> | |
4746 | </DIV> | |
4747 | <H2><A name="SWIG_nn45"></A>5.7 An Interface Building Strategy</H2> | |
4748 | <P> This section describes the general approach for building interface | |
4749 | with SWIG. The specifics related to a particular scripting language are | |
4750 | found in later chapters.</P> | |
4751 | <H3><A name="SWIG_nn46"></A>5.7.1 Preparing a C program for SWIG</H3> | |
4752 | <P> SWIG doesn't require modifications to your C code, but if you feed | |
4753 | it a collection of raw C header files or source code, the results might | |
4754 | not be what you expect---in fact, they might be awful. Here's a series | |
4755 | of steps you can follow to make an interface for a C program :</P> | |
4756 | <UL> | |
4757 | <LI>Identify the functions that you want to wrap. It's probably not | |
4758 | necessary to access every single function in a C program--thus, a | |
4759 | little forethought can dramatically simplify the resulting scripting | |
4760 | language interface. C header files are particularly good source for | |
4761 | finding things to wrap.</LI> | |
4762 | <LI>Create a new interface file to describe the scripting language | |
4763 | interface to your program.</LI> | |
4764 | <LI>Copy the appropriate declarations into the interface file or use | |
4765 | SWIG's <TT>%include</TT> directive to process an entire C source/header | |
4766 | file.</LI> | |
4767 | <LI>Make sure everything in the interface file uses ANSI C/C++syntax.</LI> | |
4768 | <LI>Make sure all necessary `<TT>typedef</TT>' declarations and | |
4769 | type-information is available in the interface file.</LI> | |
4770 | <LI>If your program has a main() function, you may need to rename it | |
4771 | (read on).</LI> | |
4772 | <LI>Run SWIG and compile.</LI> | |
4773 | </UL> | |
4774 | <P> Although this may sound complicated, the process turns out to be | |
4775 | fairly easy once you get the hang of it.</P> | |
4776 | <P> In the process of building an interface, SWIG may encounter syntax | |
4777 | errors or other problems. The best way to deal with this is to simply | |
4778 | copy the offending code into a separate interface file and edit it. | |
4779 | However, the SWIG developers have worked very hard to improve the SWIG | |
4780 | parser--you should report parsing errors to the <A href="http://www.swig.org/mail.html"> | |
4781 | swig-dev mailing list</A> or to the <A href="http://www.swig.org/bugs.html"> | |
4782 | SWIG bug tracker</A>.</P> | |
4783 | <H3><A name="SWIG_nn47"></A>5.7.2 The SWIG interface file</H3> | |
4784 | <P> The preferred method of using SWIG is to generate separate interface | |
4785 | file. Suppose you have the following C header file :</P> | |
4786 | <DIV class="code"> | |
4787 | <PRE> | |
4788 | /* File : header.h */ | |
4789 | ||
4790 | #include <stdio.h> | |
4791 | #include <math.h> | |
4792 | ||
4793 | extern int foo(double); | |
4794 | extern double bar(int, int); | |
4795 | extern void dump(FILE *f); | |
4796 | ||
4797 | </PRE> | |
4798 | </DIV> | |
4799 | <P> A typical SWIG interface file for this header file would look like | |
4800 | the following :</P> | |
4801 | <DIV class="code"> | |
4802 | <PRE> | |
4803 | /* File : interface.i */ | |
4804 | %module mymodule | |
4805 | %{ | |
4806 | #include "header.h" | |
4807 | %} | |
4808 | extern int foo(double); | |
4809 | extern double bar(int, int); | |
4810 | extern void dump(FILE *f); | |
4811 | ||
4812 | </PRE> | |
4813 | </DIV> | |
4814 | <P> Of course, in this case, our header file is pretty simple so we | |
4815 | could have made an interface file like this as well:</P> | |
4816 | <DIV class="code"> | |
4817 | <PRE> | |
4818 | /* File : interface.i */ | |
4819 | %module mymodule | |
4820 | %include header.h | |
4821 | </PRE> | |
4822 | </DIV> | |
4823 | <P> Naturally, your mileage may vary.</P> | |
4824 | <H3><A name="SWIG_nn48"></A>5.7.3 Why use separate interface files?</H3> | |
4825 | <P> Although SWIG can parse many header files, it is more common to | |
4826 | write a special <TT>.i</TT> file defining the interface to a package. | |
4827 | There are several reasons why you might want to do this:</P> | |
4828 | <UL> | |
4829 | <LI>It is rarely necessary to access every single function in a large | |
4830 | package. Many C functions might have little or no use in a scripted | |
4831 | environment. Therfore, why wrap them?</LI> | |
4832 | <LI>Separate interface files provide an opportunity to provide more | |
4833 | precise rules about how an interface is to be constructed.</LI> | |
4834 | <LI>Interface files can provide more structure and organization.</LI> | |
4835 | <LI>SWIG can't parse certain definitions that appear in header files. | |
4836 | Having a separate file allows you to eliminate or work around these | |
4837 | problems.</LI> | |
4838 | <LI>Interface files provide a more precise definition of what the | |
4839 | interface is. Users wanting to extend the system can go to the | |
4840 | interface file and immediately see what is available without having to | |
4841 | dig it out of header files.</LI> | |
4842 | </UL> | |
4843 | <H3><A name="SWIG_nn49"></A>5.7.4 Getting the right header files</H3> | |
4844 | <P> Sometimes, it is necessary to use certain header files in order for | |
4845 | the code generated by SWIG to compile properly. Make sure you include | |
4846 | certain header files by using a <TT>%{,%}</TT> block like this:</P> | |
4847 | <DIV class="code"> | |
4848 | <PRE> | |
4849 | %module graphics | |
4850 | %{ | |
4851 | #include <GL/gl.h> | |
4852 | #include <GL/glu.h> | |
4853 | %} | |
4854 | ||
4855 | // Put rest of declarations here | |
4856 | ... | |
4857 | </PRE> | |
4858 | </DIV> | |
4859 | <H3><A name="SWIG_nn50"></A>5.7.5 What to do with main()</H3> | |
4860 | <P> If your program defines a <TT>main()</TT> function, you may need to | |
4861 | get rid of it or rename it in order to use a scripting language. Most | |
4862 | scripting languages define their own <TT>main()</TT> procedure that is | |
4863 | called instead. <TT>main()</TT> also makes no sense when working with | |
4864 | dynamic loading. There are a few approaches to solving the <TT>main()</TT> | |
4865 | conflict :</P> | |
4866 | <UL> | |
4867 | <LI>Get rid of <TT>main()</TT> entirely.</LI> | |
4868 | <LI>Rename <TT>main()</TT> to something else. You can do this by | |
4869 | compiling your C program with an option like <TT>-Dmain=oldmain</TT>.</LI> | |
4870 | <LI>Use conditional compilation to only include <TT>main()</TT> when not | |
4871 | using a scripting language.</LI> | |
4872 | </UL> | |
4873 | <P> Getting rid of <TT>main()</TT> may cause potential initialization | |
4874 | problems of a program. To handle this problem, you may consider writing | |
4875 | a special function called <TT>program_init()</TT> that initializes your | |
4876 | program upon startup. This function could then be called either from | |
4877 | the scripting language as the first operation, or when the SWIG | |
4878 | generated module is loaded.</P> | |
4879 | <P> As a general note, many C programs only use the <TT>main()</TT> | |
4880 | function to parse command line options and to set parameters. However, | |
4881 | by using a scripting language, you are probably trying to create a | |
4882 | program that is more interactive. In many cases, the old <TT>main()</TT> | |
4883 | program can be completely replaced by a Perl, Python, or Tcl script.</P> | |
4884 | <P><B> Note:</B> If some cases, you might be inclined to create a | |
4885 | scripting language wrapper for <TT>main()</TT>. If you do this, the | |
4886 | compilation will probably work and your module might even load | |
4887 | correctly. The only trouble is that when you call your <TT>main()</TT> | |
4888 | wrapper, you will find that it actually invokes the <TT>main()</TT> of | |
4889 | the scripting language interpreter itself! This behavior is a side | |
4890 | effect of the symbol binding mechanism used in the dynamic linker. The | |
4891 | bottom line: don't do this.</P> | |
4892 | <HR NOSHADE> | |
4893 | <H1><A name="SWIGPlus"></A>6 SWIG and C++</H1> | |
4894 | ||
4895 | <!-- INDEX --> | |
4896 | <DIV class="sectiontoc"> | |
4897 | <UL> | |
4898 | <LI><A href="#SWIGPlus_nn2">Comments on C++ Wrapping</A></LI> | |
4899 | <LI><A href="#SWIGPlus_nn3">Approach</A></LI> | |
4900 | <LI><A href="#SWIGPlus_nn4">Supported C++ features</A></LI> | |
4901 | <LI><A href="#SWIGPlus_nn5">Command line options and compilation</A></LI> | |
4902 | <LI><A href="#SWIGPlus_nn6">Simple C++ wrapping</A> | |
4903 | <UL> | |
4904 | <LI><A href="#SWIGPlus_nn7">Constructors and destructors</A></LI> | |
4905 | <LI><A href="#SWIGPlus_nn8">Default constructors</A></LI> | |
4906 | <LI><A href="#SWIGPlus_nn9">When constructor wrappers aren't created</A></LI> | |
4907 | <LI><A href="#SWIGPlus_nn10">Copy constructors</A></LI> | |
4908 | <LI><A href="#SWIGPlus_nn11">Member functions</A></LI> | |
4909 | <LI><A href="#SWIGPlus_nn12">Static members</A></LI> | |
4910 | <LI><A href="#SWIGPlus_nn13">Member data</A></LI> | |
4911 | </UL> | |
4912 | </LI> | |
4913 | <LI><A href="#SWIGPlus_default_args">Default arguments</A></LI> | |
4914 | <LI><A href="#SWIGPlus_nn15">Protection</A></LI> | |
4915 | <LI><A href="#SWIGPlus_nn16">Enums and constants</A></LI> | |
4916 | <LI><A href="#SWIGPlus_nn17">Friends</A></LI> | |
4917 | <LI><A href="#SWIGPlus_nn18">References and pointers</A></LI> | |
4918 | <LI><A href="#SWIGPlus_nn19">Pass and return by value</A></LI> | |
4919 | <LI><A href="#SWIGPlus_nn20">Inheritance</A></LI> | |
4920 | <LI><A href="#SWIGPlus_nn21">A brief discussion of multiple inheritance, | |
4921 | pointers, and type checking</A></LI> | |
4922 | <LI><A href="#SWIGPlus_nn22">Renaming</A></LI> | |
4923 | <LI><A href="#SWIGPlus_overloaded_methods">Wrapping Overloaded Functions | |
4924 | and Methods</A> | |
4925 | <UL> | |
4926 | <LI><A href="#SWIGPlus_nn24">Dispatch function generation</A></LI> | |
4927 | <LI><A href="#SWIGPlus_nn25">Ambiguity in Overloading</A></LI> | |
4928 | <LI><A href="#ambiguity_resolution_renaming">Ambiguity resolution and | |
4929 | renaming</A></LI> | |
4930 | <LI><A href="#SWIGPlus_nn27">Comments on overloading</A></LI> | |
4931 | </UL> | |
4932 | </LI> | |
4933 | <LI><A href="#SWIGPlus_nn28">Wrapping overloaded operators</A></LI> | |
4934 | <LI><A href="#SWIGPlus_nn29">Class extension</A></LI> | |
4935 | <LI><A href="#SWIGPlus_nn30">Templates</A></LI> | |
4936 | <LI><A href="#SWIGPlus_nn31">Namespaces</A></LI> | |
4937 | <LI><A href="#SWIGPlus_exception_specifications">Exception | |
4938 | specifications</A></LI> | |
4939 | <LI><A href="#SWIGPlus_nn33">Pointers to Members</A></LI> | |
4940 | <LI><A href="#SWIGPlus_nn34">Smart pointers and operator->()</A></LI> | |
4941 | <LI><A href="#SWIGPlus_nn35">Using declarations and inheritance</A></LI> | |
4942 | <LI><A href="#SWIGPlus_nn36">Partial class definitions</A></LI> | |
4943 | <LI><A href="#SWIGPlus_nn37">A brief rant about const-correctness</A></LI> | |
4944 | <LI><A href="#SWIGPlus_nn38">Proxy classes</A> | |
4945 | <UL> | |
4946 | <LI><A href="#SWIGPlus_nn39">Construction of proxy classes</A></LI> | |
4947 | <LI><A href="#SWIGPlus_nn40">Resource management in proxies</A></LI> | |
4948 | <LI><A href="#SWIGPlus_nn41">Language specific details</A></LI> | |
4949 | </UL> | |
4950 | </LI> | |
4951 | <LI><A href="#SWIGPlus_nn42">Where to go for more information</A></LI> | |
4952 | </UL> | |
4953 | </DIV> | |
4954 | <!-- INDEX --> | |
4955 | <P> This chapter describes SWIG's support for wrapping C++. As a | |
4956 | prerequisite, you should first read the chapter <A href="#SWIG">SWIG | |
4957 | Basics</A> to see how SWIG wraps ANSI C. Support for C++ builds upon | |
4958 | ANSI C wrapping and that material will be useful in understanding this | |
4959 | chapter.</P> | |
4960 | <H2><A name="SWIGPlus_nn2"></A>6.1 Comments on C++ Wrapping</H2> | |
4961 | <P> Because of its complexity and the fact that C++ can be difficult to | |
4962 | integrate with itself let alone other languages, SWIG only provides | |
4963 | support for a subset of C++ features. Fortunately, this is now a rather | |
4964 | large subset.</P> | |
4965 | <P> In part, the problem with C++ wrapping is that there is no | |
4966 | semantically obvious (or automatic ) way to map many of its advanced | |
4967 | features into other languages. As a simple example, consider the | |
4968 | problem of wrapping C++ multiple inheritance to a target language with | |
4969 | no such support. Similarly, the use of overloaded operators and | |
4970 | overloaded functions can be problematic when no such capability exists | |
4971 | in a target language.</P> | |
4972 | <P> A more subtle issue with C++ has to do with the way that some C++ | |
4973 | programmers think about programming libraries. In the world of SWIG, | |
4974 | you are really trying to create binary-level software components for | |
4975 | use in other languages. In order for this to work, a "component" has to | |
4976 | contain real executable instructions and there has to be some kind of | |
4977 | binary linking mechanism for accessing its functionality. In contrast, | |
4978 | C++ has increasingly relied upon generic programming and templates for | |
4979 | much of its functionality. Although templates are a powerful feature, | |
4980 | they are largely orthogonal to the whole notion of binary components | |
4981 | and libraries. For example, an STL <TT>vector</TT> does not define any | |
4982 | kind of binary object for which SWIG can just create a wrapper. To | |
4983 | further complicate matters, these libraries often utilize a lot of | |
4984 | behind the scenes magic in which the semantics of seemingly basic | |
4985 | operations (e.g., pointer dereferencing, procedure call, etc.) can be | |
4986 | changed in dramatic and sometimes non-obvious ways. Although this | |
4987 | "magic" may present few problems in a C++-only universe, it greatly | |
4988 | complicates the problem of crossing language boundaries and provides | |
4989 | many opportunities to shoot yourself in the foot. You will just have to | |
4990 | be careful.</P> | |
4991 | <H2><A name="SWIGPlus_nn3"></A>6.2 Approach</H2> | |
4992 | <P> To wrap C++, SWIG uses a layered approach to code generation. At the | |
4993 | lowest level, SWIG generates a collection of procedural ANSI-C style | |
4994 | wrappers. These wrappers take care of basic type conversion, type | |
4995 | checking, error handling, and other low-level details of the C++ | |
4996 | binding. These wrappers are also sufficient to bind C++ into any target | |
4997 | language that supports built-in procedures. In some sense, you might | |
4998 | view this layer of wrapping as providing a C library interface to C++. | |
4999 | Optionally, SWIG can also generate proxy classes that provide a natural | |
5000 | OO interface to the underlying code. These proxies are built on top of | |
5001 | the low-level procedural wrappers and are typically written in the | |
5002 | target language itself. For instance, in Python, a real Python class is | |
5003 | used to provide a wrapper around the underlying C++ object.</P> | |
5004 | <P> It is important to emphasize that SWIG takes a deliberately | |
5005 | conservative and non-intrusive approach to C++ wrapping. SWIG does not | |
5006 | encapsulate C++ classes inside special C++ adaptor or proxy classes, it | |
5007 | does not rely upon templates, nor does it use C++ inheritance when | |
5008 | generating wrappers. The last thing that most C++ programs need is even | |
5009 | more compiler magic. Therefore, SWIG tries to maintain a very strict | |
5010 | and clean separation between the implementation of your C++ application | |
5011 | and the resulting wrapper code. You might say that SWIG has been | |
5012 | written to follow the principle of least surprise--it does not play | |
5013 | sneaky tricks with the C++ type system, it doesn't mess with your class | |
5014 | hierarchies, and it doesn't introduce new semantics. Although this | |
5015 | approach might not provide the most seamless integration with C++, it | |
5016 | is safe, simple, portable, and debuggable.</P> | |
5017 | <P> Most of this chapter focuses on the low-level procedural interface | |
5018 | to C++ that is used as the foundation for all language modules. Keep in | |
5019 | mind that most target languages also provide a high-level OO interface | |
5020 | via proxy classes. A few general details about proxies can be found at | |
5021 | the end of this chapter. However, more detailed coverage can be found | |
5022 | in the documentation for each target language.</P> | |
5023 | <H2><A name="SWIGPlus_nn4"></A>6.3 Supported C++ features</H2> | |
5024 | <P> SWIG's currently supports the following C++ features :</P> | |
5025 | <UL> | |
5026 | <LI>Classes.</LI> | |
5027 | <LI>Constructors and destructors</LI> | |
5028 | <LI>Virtual functions</LI> | |
5029 | <LI>Public inheritance (including multiple inheritance)</LI> | |
5030 | <LI>Static functions</LI> | |
5031 | <LI>Function and method overloading.</LI> | |
5032 | <LI>Operator overloading for many standard operators</LI> | |
5033 | <LI>References</LI> | |
5034 | <LI>Templates (including specialization and member templates).</LI> | |
5035 | <LI>Pointers to members</LI> | |
5036 | <LI>Namespaces</LI> | |
5037 | </UL> | |
5038 | <P> The following C++ features are not currently supported :</P> | |
5039 | <UL> | |
5040 | <LI>Nested classes</LI> | |
5041 | <LI>Overloaded versions of certain operators (new, delete, etc.)</LI> | |
5042 | </UL> | |
5043 | <P> SWIG's C++ support is an ongoing project so some of these | |
5044 | limitations may be lifted in future releases. However, we make no | |
5045 | promises. Also, submitting a bug report is a very good way to get | |
5046 | problems fixed (wink).</P> | |
5047 | <H2><A name="SWIGPlus_nn5"></A>6.4 Command line options and compilation</H2> | |
5048 | <P> When wrapping C++ code, it is critical that SWIG be called with the | |
5049 | `<TT>-c++</TT>' option. This changes the way a number of critical | |
5050 | features such as memory management are handled. It also enables the | |
5051 | recognition of C++ keywords. Without the <TT>-c++</TT> flag, SWIG will | |
5052 | either issue a warning or a large number of syntax errors if it | |
5053 | encounters C++ code in an interface file.</P> | |
5054 | <P> When compiling and linking the resulting wrapper file, it is normal | |
5055 | to use the C++ compiler. For example:</P> | |
5056 | <DIV class="shell"> | |
5057 | <PRE> | |
5058 | $ swig -c++ -tcl example.i | |
5059 | $ c++ -c example_wrap.cxx | |
5060 | $ c++ example_wrap.o $(OBJS) -o example.so | |
5061 | </PRE> | |
5062 | </DIV> | |
5063 | <P> Unfortunately, the process varies slightly on each machine. Make | |
5064 | sure you refer to the documentation on each target language for further | |
5065 | details. The SWIG Wiki also has further details.</P> | |
5066 | <H2><A name="SWIGPlus_nn6"></A>6.5 Simple C++ wrapping</H2> | |
5067 | <P> The following code shows a SWIG interface file for a simple C++ | |
5068 | class.</P> | |
5069 | <DIV class="code"> | |
5070 | <PRE> | |
5071 | %module list | |
5072 | %{ | |
5073 | #include "list.h" | |
5074 | %} | |
5075 | ||
5076 | // Very simple C++ example for linked list | |
5077 | ||
5078 | class List { | |
5079 | public: | |
5080 | List(); | |
5081 | ~List(); | |
5082 | int search(char *value); | |
5083 | void insert(char *); | |
5084 | void remove(char *); | |
5085 | char *get(int n); | |
5086 | int length; | |
5087 | static void print(List *l); | |
5088 | }; | |
5089 | </PRE> | |
5090 | </DIV> | |
5091 | <P> To generate wrappers for this class, SWIG first reduces the class to | |
5092 | a collection of low-level C-style accessor functions. The next few | |
5093 | sections describe this process. Later parts of the chapter describe a | |
5094 | higher level interface based on proxy classes.</P> | |
5095 | <H3><A name="SWIGPlus_nn7"></A>6.5.1 Constructors and destructors</H3> | |
5096 | <P> C++ constructors and destructors are translated into accessor | |
5097 | functions such as the following :</P> | |
5098 | <DIV class="code"> | |
5099 | <PRE> | |
5100 | List * new_List(void) { | |
5101 | return new List; | |
5102 | } | |
5103 | void delete_List(List *l) { | |
5104 | delete l; | |
5105 | } | |
5106 | ||
5107 | </PRE> | |
5108 | </DIV> | |
5109 | <H3><A name="SWIGPlus_nn8"></A>6.5.2 Default constructors</H3> | |
5110 | <P> If a C++ class does not define any public constructors or | |
5111 | destructors, SWIG will automatically create a default constructor or | |
5112 | destructor. However, there are a few rules that define this behavior:</P> | |
5113 | <UL> | |
5114 | <LI>A default constructor is not created if a class already defines a | |
5115 | constructor with arguments.</LI> | |
5116 | <LI>Default constructors are not generated for classes with pure virtual | |
5117 | methods or for classes that inherit from an abstract class, but don't | |
5118 | provide definitions for all of the pure methods.</LI> | |
5119 | <LI>A default constructor is not created unless all bases classes | |
5120 | support a default constructor.</LI> | |
5121 | <LI>Default constructors and destructors are not created if a class | |
5122 | defines constructors or destructors in a <TT>private</TT> or <TT> | |
5123 | protected</TT> section.</LI> | |
5124 | <LI>Default constructors and destructors are not created if any base | |
5125 | class defines a private default constructor or a private destructor.</LI> | |
5126 | </UL> | |
5127 | <P> SWIG should never generate a constructor or destructor for a class | |
5128 | in which it is illegal to do so. However, if it is necessary to disable | |
5129 | the default constructor/destructor creation, the <TT>%nodefault</TT> | |
5130 | directive can be used:</P> | |
5131 | <DIV class="code"> | |
5132 | <PRE> | |
5133 | %nodefault; // Disable creation of constructor/destructor | |
5134 | class Foo { | |
5135 | ... | |
5136 | }; | |
5137 | %makedefault; | |
5138 | </PRE> | |
5139 | </DIV> | |
5140 | <P> <TT>%nodefault</TT> can also take a class name. For example:</P> | |
5141 | <DIV class="code"> | |
5142 | <PRE> | |
5143 | %nodefault Foo; // Disable for class Foo only. | |
5144 | </PRE> | |
5145 | </DIV> | |
5146 | <P><B> Compatibility Note:</B> The generation of default | |
5147 | constructors/destructors was made the default behavior in SWIG 1.3.7. | |
5148 | This may break certain older modules, but the old behavior can be | |
5149 | easily restored using <TT>%nodefault</TT> or the <TT>-nodefault</TT> | |
5150 | command line option. Furthermore, in order for SWIG to properly | |
5151 | generate (or not generate) default constructors, it must be able to | |
5152 | gather information from both the <TT>private</TT> and <TT>protected</TT> | |
5153 | sections (specifically, it needs to know if a private or protected | |
5154 | constructor/destructor is defined). In older versions of SWIG, it was | |
5155 | fairly common to simply remove or comment out the private and protected | |
5156 | sections of a class due to parser limitations. However, this removal | |
5157 | may now cause SWIG to erroneously generate constructors for classes | |
5158 | that define a constructor in those sections. Consider restoring those | |
5159 | sections in the interface or using <TT>%nodefault</TT> to fix the | |
5160 | problem.</P> | |
5161 | <H3><A name="SWIGPlus_nn9"></A>6.5.3 When constructor wrappers aren't | |
5162 | created</H3> | |
5163 | <P> If a class defines a constructor, SWIG normally tries to generate a | |
5164 | wrapper for it. However, SWIG will not generate a constructor wrapper | |
5165 | if it thinks that it will result in illegal wrapper code. There are | |
5166 | really two cases where this might show up.</P> | |
5167 | <P> First, SWIG won't generate wrappers for protected or private | |
5168 | constructors. For example:</P> | |
5169 | <DIV class="code"> | |
5170 | <PRE> | |
5171 | class Foo { | |
5172 | protected: | |
5173 | Foo(); // Not wrapped. | |
5174 | public: | |
5175 | ... | |
5176 | }; | |
5177 | </PRE> | |
5178 | </DIV> | |
5179 | <P> Next, SWIG won't generate wrappers for a class if it appears to be | |
5180 | abstract--that is, it has undefined pure virtual methods. Here are some | |
5181 | examples:</P> | |
5182 | <DIV class="code"> | |
5183 | <PRE> | |
5184 | class Bar { | |
5185 | public: | |
5186 | Bar(); // Not wrapped. Bar is abstract. | |
5187 | virtual void spam(void) = 0; | |
5188 | }; | |
5189 | ||
5190 | class Grok : public Bar { | |
5191 | public: | |
5192 | Grok(); // Not wrapped. No implementation of abstract spam(). | |
5193 | }; | |
5194 | </PRE> | |
5195 | </DIV> | |
5196 | <P> Some users are surprised (or confused) to find missing constructor | |
5197 | wrappers in their interfaces. In almost all cases, this is caused when | |
5198 | classes are determined to be abstract. To see if this is the case, run | |
5199 | SWIG with all of its warnings turned on:</P> | |
5200 | <DIV class="shell"> | |
5201 | <PRE> | |
5202 | % swig -Wall -python module.i | |
5203 | </PRE> | |
5204 | </DIV> | |
5205 | <P> In this mode, SWIG will issue a warning for all abstract classes. It | |
5206 | is possible to force a class to be non-abstract using this:</P> | |
5207 | <DIV class="code"> | |
5208 | <PRE> | |
5209 | %feature("notabstract") Foo; | |
5210 | ||
5211 | class Foo : public Bar { | |
5212 | public: | |
5213 | Foo(); // Generated no matter what---not abstract. | |
5214 | ... | |
5215 | }; | |
5216 | </PRE> | |
5217 | </DIV> | |
5218 | <P> More information about <TT>%feature</TT> can be found in the <A href="#Customization"> | |
5219 | Customization features</A> chapter.</P> | |
5220 | <H3><A name="SWIGPlus_nn10"></A>6.5.4 Copy constructors</H3> | |
5221 | <P> If a class defines more than one constructor, its behavior depends | |
5222 | on the capabilities of the target language. If overloading is | |
5223 | supported, the copy constructor is accessible using the normal | |
5224 | constructor function. For example, if you have this:</P> | |
5225 | <DIV class="code"> | |
5226 | <PRE> | |
5227 | class List { | |
5228 | public: | |
5229 | List(); | |
5230 | List(const List &); // Copy constructor | |
5231 | ... | |
5232 | }; | |
5233 | </PRE> | |
5234 | </DIV> | |
5235 | <P> then the copy constructor can be used as follows:</P> | |
5236 | <DIV class="targetlang"> | |
5237 | <PRE> | |
5238 | x = new_List() # Create a list | |
5239 | y = new_List(x) # Copy list x | |
5240 | </PRE> | |
5241 | </DIV> | |
5242 | <P> If the target language does not support overloading, then the copy | |
5243 | constructor is available through a special function like this:</P> | |
5244 | <DIV class="code"> | |
5245 | <PRE> | |
5246 | List *copy_List(List *f) { | |
5247 | return new List(*f); | |
5248 | } | |
5249 | </PRE> | |
5250 | </DIV> | |
5251 | <P><B> Note:</B> For a class <TT>X</TT>, SWIG only treats a constructor | |
5252 | as a copy constructor if it can be applied to an object of type <TT>X</TT> | |
5253 | or <TT>X *</TT>. If more than one copy constructor is defined, only the | |
5254 | first definition that appears is used as the copy constructor--other | |
5255 | definitions will result in a name-clash. Constructors such as <TT> | |
5256 | X(const X &)</TT>, <TT>X(X &)</TT>, and <TT>X(X *)</TT> are handled as | |
5257 | copy constructors in SWIG.</P> | |
5258 | <P><B> Note:</B> SWIG does<EM> not</EM> generate a copy constructor | |
5259 | wrapper unless one is explicitly declared in the class. This differs | |
5260 | from the treatment of default constructors and destructors.</P> | |
5261 | <P><B> Compatibility note:</B> Special support for copy constructors was | |
5262 | not added until SWIG-1.3.12. In previous versions, copy constructors | |
5263 | could be wrapped, but they had to be renamed. For example:</P> | |
5264 | <DIV class="code"> | |
5265 | <PRE> | |
5266 | class Foo { | |
5267 | public: | |
5268 | Foo(); | |
5269 | %name(CopyFoo) Foo(const Foo &); | |
5270 | ... | |
5271 | }; | |
5272 | </PRE> | |
5273 | </DIV> | |
5274 | <P> For backwards compatibility, SWIG does not perform any special | |
5275 | copy-constructor handling if the constructor has been manually renamed. | |
5276 | For instance, in the above example, the name of the constructor is set | |
5277 | to <TT>new_CopyFoo()</TT>. This is the same as in older versions.</P> | |
5278 | <H3><A name="SWIGPlus_nn11"></A>6.5.5 Member functions</H3> | |
5279 | <P> All member functions are roughly translated into accessor functions | |
5280 | like this :</P> | |
5281 | <DIV class="code"> | |
5282 | <PRE> | |
5283 | int List_search(List *obj, char *value) { | |
5284 | return obj->search(value); | |
5285 | } | |
5286 | ||
5287 | </PRE> | |
5288 | </DIV> | |
5289 | <P> This translation is the same even if the member function has been | |
5290 | declared as <TT>virtual</TT>.</P> | |
5291 | <P> It should be noted that SWIG does not<EM> actually</EM> create a C | |
5292 | accessor function in the code it generates. Instead, member access such | |
5293 | as <TT>obj->search(value)</TT> is directly inlined into the generated | |
5294 | wrapper functions. However, the name and calling convention of the | |
5295 | wrappers match the accessor function prototype described above.</P> | |
5296 | <H3><A name="SWIGPlus_nn12"></A>6.5.6 Static members</H3> | |
5297 | <P> Static member functions are called directly without making any | |
5298 | special transformations. For example, the static member function <TT> | |
5299 | print(List *l)</TT> directly invokes <TT>List::print(List *l)</TT> in | |
5300 | the generated wrapper code.</P> | |
5301 | <P> Usually, static members are accessed as functions with names in | |
5302 | which the class name has been prepended with an underscore. For | |
5303 | example, <TT>List_print</TT>.</P> | |
5304 | <H3><A name="SWIGPlus_nn13"></A>6.5.7 Member data</H3> | |
5305 | <P> Member data is handled in exactly the same manner as for C | |
5306 | structures. A pair of accessor functions are created. For example :</P> | |
5307 | <DIV class="code"> | |
5308 | <PRE> | |
5309 | int List_length_get(List *obj) { | |
5310 | return obj->length; | |
5311 | } | |
5312 | int List_length_set(List *obj, int value) { | |
5313 | obj->length = value; | |
5314 | return value; | |
5315 | } | |
5316 | ||
5317 | </PRE> | |
5318 | </DIV> | |
5319 | <P> A read-only member can be created using the <TT>%immutable</TT> and <TT> | |
5320 | %mutable</TT> directives. For example, we probably wouldn't want the | |
5321 | user to change the length of a list so we could do the following to | |
5322 | make the value available, but read-only.</P> | |
5323 | <DIV class="code"> | |
5324 | <PRE> | |
5325 | class List { | |
5326 | public: | |
5327 | ... | |
5328 | %immutable; | |
5329 | int length; | |
5330 | %mutable; | |
5331 | ... | |
5332 | }; | |
5333 | </PRE> | |
5334 | </DIV> | |
5335 | <P> Alternatively, you can specify an immutable member in advance like | |
5336 | this:</P> | |
5337 | <DIV class="code"> | |
5338 | <PRE> | |
5339 | %immutable List::length; | |
5340 | ... | |
5341 | class List { | |
5342 | ... | |
5343 | int length; // Immutable by above directive | |
5344 | ... | |
5345 | }; | |
5346 | </PRE> | |
5347 | </DIV> | |
5348 | <P> Similarly, all data attributes declared as <TT>const</TT> are | |
5349 | wrapped as read-only members.</P> | |
5350 | <P> There are some subtle issues when wrapping data members that are | |
5351 | themselves classes. For instance, if you had another class like this,</P> | |
5352 | <DIV class="code"> | |
5353 | <PRE> | |
5354 | class Foo { | |
5355 | public: | |
5356 | List items; | |
5357 | ... | |
5358 | </PRE> | |
5359 | </DIV> | |
5360 | <P> then access to the <TT>items</TT> member actually uses pointers. For | |
5361 | example:</P> | |
5362 | <DIV class="code"> | |
5363 | <PRE> | |
5364 | List *Foo_items_get(Foo *self) { | |
5365 | return &self->items; | |
5366 | } | |
5367 | void Foo_items_set(Foo *self, List *value) { | |
5368 | self->items = *value; | |
5369 | } | |
5370 | </PRE> | |
5371 | </DIV> | |
5372 | <P> More information about this can be found in the "Structure data | |
5373 | members" section of the <A href="#SWIG">SWIG Basics</A> chapter.</P> | |
5374 | <P><B> Compatibility note:</B> Read-only access used to be controlled by | |
5375 | a pair of directives <TT>%readonly</TT> and <TT>%readwrite</TT>. | |
5376 | Although these directives still work, they generate a warning message. | |
5377 | Simply change the directives to <TT>%immutable;</TT> and <TT>%mutable;</TT> | |
5378 | to silence the warning. Don't forget the extra semicolon!</P> | |
5379 | <P><B> Compatibility note:</B> Prior to SWIG-1.3.12, all members of | |
5380 | unknown type were wrapped into accessor functions using pointers. For | |
5381 | example, if you had a structure like this</P> | |
5382 | <DIV class="code"> | |
5383 | <PRE> | |
5384 | struct Foo { | |
5385 | size_t len; | |
5386 | }; | |
5387 | </PRE> | |
5388 | </DIV> | |
5389 | <P> and nothing was known about <TT>size_t</TT>, then accessors would be | |
5390 | written to work with <TT>size_t *</TT>. Starting in SWIG-1.3.12, this | |
5391 | behavior has been modified. Specifically, pointers will<EM> only</EM> | |
5392 | be used if SWIG knows that a datatype corresponds to a structure or | |
5393 | class. Therefore, the above code would be wrapped into accessors | |
5394 | involving <TT>size_t</TT>. This change is subtle, but it smooths over a | |
5395 | few problems related to structure wrapping and some of SWIG's | |
5396 | customization features.</P> | |
5397 | <H2><A name="SWIGPlus_default_args"></A>6.6 Default arguments</H2> | |
5398 | <P> SWIG will wrap all types of functions that have default arguments. | |
5399 | For example member functions:</P> | |
5400 | <DIV class="code"> | |
5401 | <PRE> | |
5402 | class Foo { | |
5403 | public: | |
5404 | void bar(int x, int y = 3, int z = 4); | |
5405 | }; | |
5406 | </PRE> | |
5407 | </DIV> | |
5408 | <P> SWIG handles default arguments by generating an extra overloaded | |
5409 | method for each defaulted argument. SWIG is effectively handling | |
5410 | methods with default arguments as if it had wrapped the equivalent | |
5411 | overloaded methods. Thus for the example above, it is as if we had | |
5412 | instead given the following to SWIG:</P> | |
5413 | <DIV class="code"> | |
5414 | <PRE> | |
5415 | class Foo { | |
5416 | public: | |
5417 | void bar(int x, int y, int z); | |
5418 | void bar(int x, int y); | |
5419 | void bar(int x); | |
5420 | }; | |
5421 | </PRE> | |
5422 | </DIV> | |
5423 | <P> The wrappers produced are exactly the same as if the above code was | |
5424 | instead fed into SWIG. Details of this is covered later in the <A href="#SWIGPlus_overloaded_methods"> | |
5425 | Wrapping Overloaded Functions and Methods</A> section. This approach | |
5426 | allows SWIG to wrap all possible default arguments, but can be verbose. | |
5427 | For example if a method has ten default arguments, then eleven wrapper | |
5428 | methods are generated.</P> | |
5429 | <P> Please see the <A href="#Customization_features_default_args"> | |
5430 | Features and default arguments</A> section for more information on using | |
5431 | <TT>%feature</TT> with functions with default arguments. The <A href="#ambiguity_resolution_renaming"> | |
5432 | Ambiguity resolution and renaming</A> section also deals with using <TT> | |
5433 | %rename</TT> and <TT>%ignore</TT> on methods with default arguments. If | |
5434 | you are writing your own typemaps for types used in methods with | |
5435 | default arguments, you may also need to write a <TT>typecheck</TT> | |
5436 | typemap. See the <A href="#Typemaps_overloading">Typemaps and | |
5437 | overloading</A> section for details or otherwise use the <TT> | |
5438 | compactdefaultargs</TT> feature as mentioned below.</P> | |
5439 | <P><B> Compatibility note:</B> Versions of SWIG prior to SWIG-1.3.23 | |
5440 | wrapped default arguments slightly differently. Instead a single | |
5441 | wrapper method was generated and the default values were copied into | |
5442 | the C++ wrappers so that the method being wrapped was then called with | |
5443 | all the arguments specified. If the size of the wrappers are a concern | |
5444 | then this approach to wrapping methods with default arguments can be | |
5445 | re-activated by using the <TT>compactdefaultargs</TT> <A href="#features"> | |
5446 | feature</A>.</P> | |
5447 | <DIV class="code"> | |
5448 | <PRE> | |
5449 | %feature("compactdefaultargs") Foo::bar; | |
5450 | class Foo { | |
5451 | public: | |
5452 | void bar(int x, int y = 3, int z = 4); | |
5453 | }; | |
5454 | </PRE> | |
5455 | </DIV> | |
5456 | <P> This is great for reducing the size of the wrappers, but the caveat | |
5457 | is it does not work for the strongly typed languages which don't have | |
5458 | optional arguments in the language, such as C# and Java. Another | |
5459 | restriction of this feature is that it cannot handle default arguments | |
5460 | that are not public. The following example illustrates this:</P> | |
5461 | <DIV class="code"> | |
5462 | <PRE> | |
5463 | class Foo { | |
5464 | private: | |
5465 | static const int spam; | |
5466 | public: | |
5467 | void bar(int x, int y = spam); // Won't work with %feature("compactdefaultargs") - | |
5468 | // private default value | |
5469 | }; | |
5470 | </PRE> | |
5471 | </DIV> | |
5472 | <P> This produces uncompileable wrapper code because default values in | |
5473 | C++ are evaluated in the same scope as the member function whereas SWIG | |
5474 | evaluates them in the scope of a wrapper function (meaning that the | |
5475 | values have to be public).</P> | |
5476 | <P> This feature is automatically turned on when wrapping <A href="#SWIG_default_args"> | |
5477 | C code with default arguments</A> and whenever keyword arguments | |
5478 | (kwargs) are specified for either C or C++ code. Keyword arguments are | |
5479 | a language feature of some scripting languages, for example Ruby and | |
5480 | Python. SWIG is unable to support kwargs when wrapping overloaded | |
5481 | methods, so the default approach cannot be used.</P> | |
5482 | <H2><A name="SWIGPlus_nn15"></A>6.7 Protection</H2> | |
5483 | <P> SWIG wraps class members that are public following the C++ | |
5484 | conventions, i.e., by explicit public declaration or by the use of the <TT> | |
5485 | using</TT> directive. In general, anything specified in a private or | |
5486 | protected section will be ignored, although the internal code generator | |
5487 | sometimes looks at the contents of the private and protected sections | |
5488 | so that it can properly generate code for default constructors and | |
5489 | destructors. Directors could also modify the way non-public virtual | |
5490 | protected members are treated.</P> | |
5491 | <P> By default, members of a class definition are assumed to be private | |
5492 | until you explicitly give a `<TT>public:</TT>' declaration (This is the | |
5493 | same convention used by C++).</P> | |
5494 | <H2><A name="SWIGPlus_nn16"></A>6.8 Enums and constants</H2> | |
5495 | <P> Enumerations and constants are handled differently by the different | |
5496 | language modules and are described in detail in the appropriate | |
5497 | language chapter. However, many languages map enums and constants in a | |
5498 | class definition into constants with the classname as a prefix. For | |
5499 | example :</P> | |
5500 | <DIV class="code"> | |
5501 | <PRE> | |
5502 | class Swig { | |
5503 | public: | |
5504 | enum {ALE, LAGER, PORTER, STOUT}; | |
5505 | }; | |
5506 | ||
5507 | </PRE> | |
5508 | </DIV> | |
5509 | <P> Generates the following set of constants in the target scripting | |
5510 | language :</P> | |
5511 | <DIV class="targetlang"> | |
5512 | <PRE> | |
5513 | Swig_ALE = Swig::ALE | |
5514 | Swig_LAGER = Swig::LAGER | |
5515 | Swig_PORTER = Swig::PORTER | |
5516 | Swig_STOUT = Swig::STOUT | |
5517 | ||
5518 | </PRE> | |
5519 | </DIV> | |
5520 | <P> Members declared as <TT>const</TT> are wrapped as read-only members | |
5521 | and do not create constants.</P> | |
5522 | <H2><A name="SWIGPlus_nn17"></A>6.9 Friends</H2> | |
5523 | <P> Friend declarations are not longer ignored by SWIG. For example, if | |
5524 | you have this code:</P> | |
5525 | <DIV class="code"> | |
5526 | <PRE> | |
5527 | class Foo { | |
5528 | public: | |
5529 | ... | |
5530 | friend void blah(Foo *f); | |
5531 | ... | |
5532 | }; | |
5533 | </PRE> | |
5534 | </DIV> | |
5535 | <P> then the <TT>friend</TT> declaration does result in a wrapper code | |
5536 | equivalent to one generated for the following declaration</P> | |
5537 | <DIV class="code"> | |
5538 | <PRE> | |
5539 | class Foo { | |
5540 | public: | |
5541 | ... | |
5542 | }; | |
5543 | ||
5544 | void blah(Foo *f); | |
5545 | </PRE> | |
5546 | </DIV> | |
5547 | <P> A friend declaration, as in C++, is understood to be in the same | |
5548 | scope where the class is declared, hence, you can do</P> | |
5549 | <DIV class="code"> | |
5550 | <PRE> | |
5551 | ||
5552 | %ignore bar::blah(Foo *f); | |
5553 | ||
5554 | namespace bar { | |
5555 | ||
5556 | class Foo { | |
5557 | public: | |
5558 | ... | |
5559 | friend void blah(Foo *f); | |
5560 | ... | |
5561 | }; | |
5562 | } | |
5563 | </PRE> | |
5564 | </DIV> | |
5565 | <P> and a wrapper for the method 'blah' will not be generated.</P> | |
5566 | <H2><A name="SWIGPlus_nn18"></A>6.10 References and pointers</H2> | |
5567 | <P> C++ references are supported, but SWIG transforms them back into | |
5568 | pointers. For example, a declaration like this :</P> | |
5569 | <DIV class="code"> | |
5570 | <PRE> | |
5571 | class Foo { | |
5572 | public: | |
5573 | double bar(double &a); | |
5574 | } | |
5575 | </PRE> | |
5576 | </DIV> | |
5577 | <P> is accessed using a function similar to this:</P> | |
5578 | <DIV class="code"> | |
5579 | <PRE> | |
5580 | double Foo_bar(Foo *obj, double *a) { | |
5581 | obj->bar(*a); | |
5582 | } | |
5583 | </PRE> | |
5584 | </DIV> | |
5585 | <P> As a special case, most language modules pass <TT>const</TT> | |
5586 | references to primitive datatypes (<TT>int</TT>, <TT>short</TT>, <TT> | |
5587 | float</TT>, etc.) by value instead of pointers. For example, if you have | |
5588 | a function like this,</P> | |
5589 | <DIV class="code"> | |
5590 | <PRE> | |
5591 | void foo(const int &x); | |
5592 | </PRE> | |
5593 | </DIV> | |
5594 | <P> it is called from a script as follows:</P> | |
5595 | <DIV class="targetlang"> | |
5596 | <PRE> | |
5597 | foo(3) # Notice pass by value | |
5598 | </PRE> | |
5599 | </DIV> | |
5600 | <P> Functions that return a reference are remapped to return a pointer | |
5601 | instead. For example:</P> | |
5602 | <DIV class="code"> | |
5603 | <PRE> | |
5604 | class Bar { | |
5605 | public: | |
5606 | Foo &spam(); | |
5607 | }; | |
5608 | </PRE> | |
5609 | </DIV> | |
5610 | <P> Generates code like this:</P> | |
5611 | <DIV class="code"> | |
5612 | <PRE> | |
5613 | Foo *Bar_spam(Bar *obj) { | |
5614 | Foo &result = obj->spam(); | |
5615 | return &result; | |
5616 | } | |
5617 | </PRE> | |
5618 | </DIV> | |
5619 | <P> However, functions that return <TT>const</TT> references to | |
5620 | primitive datatypes (<TT>int</TT>, <TT>short</TT>, etc.) normally | |
5621 | return the result as a value rather than a pointer. For example, a | |
5622 | function like this,</P> | |
5623 | <DIV class="code"> | |
5624 | <PRE> | |
5625 | const int &bar(); | |
5626 | </PRE> | |
5627 | </DIV> | |
5628 | <P> will return integers such as 37 or 42 in the target scripting | |
5629 | language rather than a pointer to an integer.</P> | |
5630 | <P> Don't return references to objects allocated as local variables on | |
5631 | the stack. SWIG doesn't make a copy of the objects so this will | |
5632 | probably cause your program to crash.</P> | |
5633 | <P><B> Note:</B> The special treatment for references to primitive | |
5634 | datatypes is necessary to provide more seamless integration with more | |
5635 | advanced C++ wrapping applications---especially related to templates | |
5636 | and the STL. This was first added in SWIG-1.3.12.</P> | |
5637 | <H2><A name="SWIGPlus_nn19"></A>6.11 Pass and return by value</H2> | |
5638 | <P> Occasionally, a C++ program will pass and return class objects by | |
5639 | value. For example, a function like this might appear:</P> | |
5640 | <DIV class="code"> | |
5641 | <PRE> | |
5642 | Vector cross_product(Vector a, Vector b); | |
5643 | </PRE> | |
5644 | </DIV> | |
5645 | <P> If no information is supplied about <TT>Vector</TT>, SWIG creates a | |
5646 | wrapper function similar to the following:</P> | |
5647 | <DIV class="code"> | |
5648 | <PRE> | |
5649 | Vector *wrap_cross_product(Vector *a, Vector *b) { | |
5650 | Vector x = *a; | |
5651 | Vector y = *b; | |
5652 | Vector r = cross_product(x,y); | |
5653 | return new Vector(r); | |
5654 | }</PRE> | |
5655 | </DIV> | |
5656 | <P> In order for the wrapper code to compile, <TT>Vector</TT> must | |
5657 | define a copy constructor and a default constructor.</P> | |
5658 | <P> If <TT>Vector</TT> is defined as class in the interface, but it does | |
5659 | not support a default constructor, SWIG changes the wrapper code by | |
5660 | encapsulating the arguments inside a special C++ template wrapper | |
5661 | class. This produces a wrapper that looks like this:</P> | |
5662 | <DIV class="code"> | |
5663 | <PRE> | |
5664 | Vector cross_product(Vector *a, Vector *b) { | |
5665 | SwigValueWrapper<Vector> x = *a; | |
5666 | SwigValueWrapper<Vector> y = *b; | |
5667 | SwigValueWrapper<Vector> r = cross_product(x,y); | |
5668 | return new Vector(r); | |
5669 | } | |
5670 | </PRE> | |
5671 | </DIV> | |
5672 | <P> This transformation is a little sneaky, but it provides support for | |
5673 | pass-by-value even when a class does not provide a default constructor | |
5674 | and it makes it possible to properly support a number of SWIG's | |
5675 | customization options. The definition of <TT>SwigValueWrapper</TT> can | |
5676 | be found by reading the SWIG wrapper code. This class is really nothing | |
5677 | more than a thin wrapper around a pointer.</P> | |
5678 | <P><B> Note:</B> this transformation has no effect on typemaps or any | |
5679 | other part of SWIG---it should be transparent except that you may see | |
5680 | this code when reading the SWIG output file.</P> | |
5681 | <P><B> Note:</B> This template transformation is new in SWIG-1.3.11 and | |
5682 | may be refined in future SWIG releases. In practice, it is only | |
5683 | necessary to do this for classes that don't define a default | |
5684 | constructor.</P> | |
5685 | <P><B> Note:</B> The use of this template only occurs when objects are | |
5686 | passed or returned by value. It is not used for C++ pointers or | |
5687 | references.</P> | |
5688 | <P><B> Note:</B> The performance of pass-by-value is especially bad for | |
5689 | large objects and should be avoided if possible (consider using | |
5690 | references instead).</P> | |
5691 | <H2><A name="SWIGPlus_nn20"></A>6.12 Inheritance</H2> | |
5692 | <P> SWIG supports C++ inheritance of classes and allows both single and | |
5693 | multiple inheritance, as limited or allowed by the target language. The | |
5694 | SWIG type-checker knows about the relationship between base and derived | |
5695 | classes and allows pointers to any object of a derived class to be used | |
5696 | in functions of a base class. The type-checker properly casts pointer | |
5697 | values and is safe to use with multiple inheritance.</P> | |
5698 | <P> SWIG treats private or protected inheritance as close to the C++ | |
5699 | spirit, and target language capabilities, as possible. In most of the | |
5700 | cases, this means that swig will parse the non-public inheritance | |
5701 | declarations, but that will have no effect in the generated code, | |
5702 | besides the implicit policies derived for constructor and destructors.</P> | |
5703 | <P> The following example shows how SWIG handles inheritance. For | |
5704 | clarity, the full C++ code has been omitted.</P> | |
5705 | <DIV class="code"> | |
5706 | <PRE> | |
5707 | // shapes.i | |
5708 | %module shapes | |
5709 | %{ | |
5710 | #include "shapes.h" | |
5711 | %} | |
5712 | ||
5713 | class Shape { | |
5714 | public: | |
5715 | double x,y; | |
5716 | virtual double area() = 0; | |
5717 | virtual double perimeter() = 0; | |
5718 | void set_location(double x, double y); | |
5719 | }; | |
5720 | class Circle : public Shape { | |
5721 | public: | |
5722 | Circle(double radius); | |
5723 | ~Circle(); | |
5724 | double area(); | |
5725 | double perimeter(); | |
5726 | }; | |
5727 | class Square : public Shape { | |
5728 | public: | |
5729 | Square(double size); | |
5730 | ~Square(); | |
5731 | double area(); | |
5732 | double perimeter(); | |
5733 | } | |
5734 | </PRE> | |
5735 | </DIV> | |
5736 | <P> When wrapped into Python, we can now perform the following | |
5737 | operations :</P> | |
5738 | <DIV class="targetlang"> | |
5739 | <PRE> | |
5740 | $ python | |
5741 | >>> import shapes | |
5742 | >>> circle = shapes.new_Circle(7) | |
5743 | >>> square = shapes.new_Square(10) | |
5744 | >>> print shapes.Circle_area(circle) | |
5745 | 153.93804004599999757 | |
5746 | >>> print shapes.Shape_area(circle) | |
5747 | 153.93804004599999757 | |
5748 | >>> print shapes.Shape_area(square) | |
5749 | 100.00000000000000000 | |
5750 | >>> shapes.Shape_set_location(square,2,-3) | |
5751 | >>> print shapes.Shape_perimeter(square) | |
5752 | 40.00000000000000000 | |
5753 | >>> | |
5754 | </PRE> | |
5755 | </DIV> | |
5756 | <P> In this example, Circle and Square objects have been created. Member | |
5757 | functions can be invoked on each object by making calls to <TT> | |
5758 | Circle_area</TT>, <TT>Square_area</TT>, and so on. However, the same | |
5759 | results can be accomplished by simply using the <TT>Shape_area</TT> | |
5760 | function on either object.</P> | |
5761 | <P> One important point concerning inheritance is that the low-level | |
5762 | accessor functions are only generated for classes in which they are | |
5763 | actually declared. For instance, in the above example, the method <TT> | |
5764 | set_location()</TT> is only accessible as <TT>Shape_set_location()</TT> | |
5765 | and not as <TT>Circle_set_location()</TT> or <TT>Square_set_location()</TT> | |
5766 | . Of course, the <TT>Shape_set_location()</TT> function will accept any | |
5767 | kind of object derived from Shape. Similarly, accessor functions for | |
5768 | the attributes <TT>x</TT> and <TT>y</TT> are generated as <TT> | |
5769 | Shape_x_get()</TT>, <TT>Shape_x_set()</TT>, <TT>Shape_y_get()</TT>, and <TT> | |
5770 | Shape_y_set()</TT>. Functions such as <TT>Circle_x_get()</TT> are not | |
5771 | available--instead you should use <TT>Shape_x_get()</TT>.</P> | |
5772 | <P> Although the low-level C-like interface is functional, most language | |
5773 | modules also produce a higher level OO interface using proxy classes. | |
5774 | This approach is described later and can be used to provide a more | |
5775 | natural C++ interface.</P> | |
5776 | <P><B> Note:</B> For the best results, SWIG requires all base classes to | |
5777 | be defined in an interface. Otherwise, you may get an warning message | |
5778 | like this:</P> | |
5779 | <DIV class="shell"> | |
5780 | <PRE> | |
5781 | example:18. Nothing known about class 'Foo'. Ignored. | |
5782 | </PRE> | |
5783 | </DIV> | |
5784 | <P> If any base class is undefined, SWIG still generates correct type | |
5785 | relationships. For instance, a function accepting a <TT>Foo *</TT> will | |
5786 | accept any object derived from <TT>Foo</TT> regardless of whether or | |
5787 | not SWIG actually wrapped the <TT>Foo</TT> class. If you really don't | |
5788 | want to generate wrappers for the base class, but you want to silence | |
5789 | the warning, you might consider using the <TT>%import</TT> directive to | |
5790 | include the file that defines <TT>Foo</TT>. <TT>%import</TT> simply | |
5791 | gathers type information, but doesn't generate wrappers. Alternatively, | |
5792 | you could just define <TT>Foo</TT> as an empty class in the SWIG | |
5793 | interface.</P> | |
5794 | <P><B> Note:</B> <TT>typedef</TT>-names<EM> can</EM> be used as base | |
5795 | classes. For example:</P> | |
5796 | <DIV class="code"> | |
5797 | <PRE> | |
5798 | class Foo { | |
5799 | ... | |
5800 | }; | |
5801 | ||
5802 | typedef Foo FooObj; | |
5803 | class Bar : public FooObj { // Ok. Base class is Foo | |
5804 | ... | |
5805 | }; | |
5806 | </PRE> | |
5807 | </DIV> | |
5808 | <P> Similarly, <TT>typedef</TT> allows unnamed structures to be used as | |
5809 | base classes. For example:</P> | |
5810 | <DIV class="code"> | |
5811 | <PRE> | |
5812 | typedef struct { | |
5813 | ... | |
5814 | } Foo; | |
5815 | ||
5816 | class Bar : public Foo { // Ok. | |
5817 | ... | |
5818 | }; | |
5819 | </PRE> | |
5820 | </DIV> | |
5821 | <P><B> Compatibility Note:</B> Starting in version 1.3.7, SWIG only | |
5822 | generates low-level accessor wrappers for the declarations that are | |
5823 | actually defined in each class. This differs from SWIG1.1 which used to | |
5824 | inherit all of the declarations defined in base classes and regenerate | |
5825 | specialized accessor functions such as <TT>Circle_x_get()</TT>, <TT> | |
5826 | Square_x_get()</TT>, <TT>Circle_set_location()</TT>, and <TT> | |
5827 | Square_set_location()</TT>. This behavior resulted in huge amounts of | |
5828 | replicated code for large class hierarchies and made it awkward to | |
5829 | build applications spread across multiple modules (since accessor | |
5830 | functions are duplicated in every single module). It is also | |
5831 | unnecessary to have such wrappers when advanced features like proxy | |
5832 | classes are used.<B> Note:</B> Further optimizations are enabled when | |
5833 | using the <TT>-fvirtual</TT> option, which avoids the regenerating of | |
5834 | wrapper functions for virtual members that are already defined in a | |
5835 | base class.</P> | |
5836 | <H2><A name="SWIGPlus_nn21"></A>6.13 A brief discussion of multiple | |
5837 | inheritance, pointers, and type checking</H2> | |
5838 | <P> When a target scripting language refers to a C++ object, it normally | |
5839 | uses a tagged pointer object that contains both the value of the | |
5840 | pointer and a type string. For example, in Tcl, a C++ pointer might be | |
5841 | encoded as a string like this:</P> | |
5842 | <DIV class="diagram"> | |
5843 | <PRE> | |
5844 | _808fea88_p_Circle | |
5845 | </PRE> | |
5846 | </DIV> | |
5847 | <P> A somewhat common question is whether or not the type-tag could be | |
5848 | safely removed from the pointer. For instance, to get better | |
5849 | performance, could you strip all type tags and just use simple integers | |
5850 | instead?</P> | |
5851 | <P> In general, the answer to this question is no. In the wrappers, all | |
5852 | pointers are converted into a common data representation in the target | |
5853 | language. Typically this is the equivalent of casting a pointer to <TT> | |
5854 | void *</TT>. This means that any C++ type information associated with | |
5855 | the pointer is lost in the conversion.</P> | |
5856 | <P> The problem with losing type information is that it is needed to | |
5857 | properly support many advanced C++ features--especially multiple | |
5858 | inheritance. For example, suppose you had code like this:</P> | |
5859 | <DIV class="code"> | |
5860 | <PRE> | |
5861 | class A { | |
5862 | public: | |
5863 | int x; | |
5864 | }; | |
5865 | ||
5866 | class B { | |
5867 | public: | |
5868 | int y; | |
5869 | }; | |
5870 | ||
5871 | class C : public A, public B { | |
5872 | }; | |
5873 | ||
5874 | int A_function(A *a) { | |
5875 | return a->x; | |
5876 | } | |
5877 | ||
5878 | int B_function(B *b) { | |
5879 | return b->y; | |
5880 | } | |
5881 | </PRE> | |
5882 | </DIV> | |
5883 | <P> Now, consider the following code that uses <TT>void *</TT>.</P> | |
5884 | <DIV class="code"> | |
5885 | <PRE> | |
5886 | C *c = new C(); | |
5887 | void *p = (void *) c; | |
5888 | ... | |
5889 | int x = A_function((A *) p); | |
5890 | int y = B_function((B *) p); | |
5891 | </PRE> | |
5892 | </DIV> | |
5893 | <P> In this code, both <TT>A_function()</TT> and <TT>B_function()</TT> | |
5894 | may legally accept an object of type <TT>C *</TT> (via inheritance). | |
5895 | However, one of the functions will always return the wrong result when | |
5896 | used as shown. The reason for this is that even though <TT>p</TT> | |
5897 | points to an object of type <TT>C</TT>, the casting operation doesn't | |
5898 | work like you would expect. Internally, this has to do with the data | |
5899 | representation of <TT>C</TT>. With multiple inheritance, the data from | |
5900 | each base class is stacked together. For example:</P> | |
5901 | <DIV class="diagram"> | |
5902 | <PRE> | |
5903 | ------------ <--- (C *), (A *) | |
5904 | | A | | |
5905 | |------------| <--- (B *) | |
5906 | | B | | |
5907 | ------------ | |
5908 | </PRE> | |
5909 | </DIV> | |
5910 | <P> Because of this stacking, a pointer of type <TT>C *</TT> may change | |
5911 | value when it is converted to a <TT>A *</TT> or <TT>B *</TT>. However, | |
5912 | this adjustment does<EM> not</EM> occur if you are converting from a <TT> | |
5913 | void *</TT>.</P> | |
5914 | <P> The use of type tags marks all pointers with the real type of the | |
5915 | underlying object. This extra information is then used by SWIG | |
5916 | generated wrappers to correctly cast pointer values under inheritance | |
5917 | (avoiding the above problem).</P> | |
5918 | <P> One might be inclined to fix this problem using some variation of <TT> | |
5919 | dynamic_cast<></TT>. The only problem is that it doesn't work with <TT> | |
5920 | void</TT> pointers, it requires RTTI support, and it only works with | |
5921 | polymorphic classes (i.e., classes that define one or more virtual | |
5922 | functions).</P> | |
5923 | <P> The bottom line: learn to live with type-tagged pointers.</P> | |
5924 | <H2><A name="SWIGPlus_nn22"></A>6.14 Renaming</H2> | |
5925 | <P> C++ member functions and data can be renamed with the <TT>%name</TT> | |
5926 | directive. The <TT>%name</TT> directive only replaces the member | |
5927 | function name. For example :</P> | |
5928 | <DIV class="code"> | |
5929 | <PRE> | |
5930 | class List { | |
5931 | public: | |
5932 | List(); | |
5933 | %name(ListSize) List(int maxsize); | |
5934 | ~List(); | |
5935 | int search(char *value); | |
5936 | %name(find) void insert(char *); | |
5937 | %name(delete) void remove(char *); | |
5938 | char *get(int n); | |
5939 | int length; | |
5940 | static void print(List *l); | |
5941 | }; | |
5942 | ||
5943 | </PRE> | |
5944 | </DIV> | |
5945 | <P> This will create the functions <TT>List_find</TT>, <TT>List_delete</TT> | |
5946 | , and a function named <TT>new_ListSize</TT> for the overloaded | |
5947 | constructor.</P> | |
5948 | <P> The <TT>%name</TT> directive can be applied to all members including | |
5949 | constructors, destructors, static functions, data members, and | |
5950 | enumeration values.</P> | |
5951 | <P> The class name prefix can also be changed by specifying</P> | |
5952 | <DIV class="code"> | |
5953 | <PRE> | |
5954 | %name(newname) class List { | |
5955 | ... | |
5956 | } | |
5957 | </PRE> | |
5958 | </DIV> | |
5959 | <P> Although the <TT>%name()</TT> directive can be used to help deal | |
5960 | with overloaded methods, it really doesn't work very well because it | |
5961 | requires a lot of additional markup in your interface. Keep reading for | |
5962 | a better solution.</P> | |
5963 | <H2><A name="SWIGPlus_overloaded_methods"></A>6.15 Wrapping Overloaded | |
5964 | Functions and Methods</H2> | |
5965 | <P> In many language modules, SWIG provides partial support for | |
5966 | overloaded functions, methods, and constructors. For example, if you | |
5967 | supply SWIG with overloaded functions like this:</P> | |
5968 | <DIV class="code"> | |
5969 | <PRE> | |
5970 | void foo(int x) { | |
5971 | printf("x is %d\n", x); | |
5972 | } | |
5973 | void foo(char *x) { | |
5974 | printf("x is '%s'\n", x); | |
5975 | } | |
5976 | </PRE> | |
5977 | </DIV> | |
5978 | <P> The function is used in a completely natural way. For example:</P> | |
5979 | <DIV class="targetlang"> | |
5980 | <PRE> | |
5981 | >>> foo(3) | |
5982 | x is 3 | |
5983 | >>> foo("hello") | |
5984 | x is 'hello' | |
5985 | >>> | |
5986 | </PRE> | |
5987 | </DIV> | |
5988 | <P> Overloading works in a similar manner for methods and constructors. | |
5989 | For example if you have this code,</P> | |
5990 | <DIV class="code"> | |
5991 | <PRE> | |
5992 | class Foo { | |
5993 | public: | |
5994 | Foo(); | |
5995 | Foo(const Foo &); // Copy constructor | |
5996 | void bar(int x); | |
5997 | void bar(char *s, int y); | |
5998 | }; | |
5999 | </PRE> | |
6000 | </DIV> | |
6001 | <P> it might be used like this</P> | |
6002 | <DIV class="targetlang"> | |
6003 | <PRE> | |
6004 | >>> f = Foo() # Create a Foo | |
6005 | >>> f.bar(3) | |
6006 | >>> g = Foo(f) # Copy Foo | |
6007 | >>> f.bar("hello",2) | |
6008 | </PRE> | |
6009 | </DIV> | |
6010 | <H3><A name="SWIGPlus_nn24"></A>6.15.1 Dispatch function generation</H3> | |
6011 | <P> The implementation of overloaded functions and methods is somewhat | |
6012 | complicated due to the dynamic nature of scripting languages. Unlike | |
6013 | C++, which binds overloaded methods at compile time, SWIG must | |
6014 | determine the proper function as a runtime check for scripting language | |
6015 | targets. This check is further complicated by the typeless nature of | |
6016 | certain scripting languages. For instance, in Tcl, all types are simply | |
6017 | strings. Therefore, if you have two overloaded functions like this,</P> | |
6018 | <DIV class="code"> | |
6019 | <PRE> | |
6020 | void foo(char *x); | |
6021 | void foo(int x); | |
6022 | </PRE> | |
6023 | </DIV> | |
6024 | <P> the order in which the arguments are checked plays a rather critical | |
6025 | role.</P> | |
6026 | <P> For statically typed languages, SWIG uses the language's method | |
6027 | overloading mechanism. To implement overloading for the scripting | |
6028 | languages, SWIG generates a dispatch function that checks the number of | |
6029 | passed arguments and their types. To create this function, SWIG first | |
6030 | examines all of the overloaded methods and ranks them according to the | |
6031 | following rules:</P> | |
6032 | <OL> | |
6033 | <LI><B>Number of required arguments.</B> Methods are sorted by | |
6034 | increasing number of required arguments.</LI> | |
6035 | <LI> | |
6036 | <P><B>Argument type precedence.</B> All C++ datatypes are assigned a | |
6037 | numeric type precedence value (which is determined by the language | |
6038 | module).</P> | |
6039 | <DIV class="diagram"> | |
6040 | <PRE> | |
6041 | Type Precedence | |
6042 | ---------------- ---------- | |
6043 | TYPE * 0 (High) | |
6044 | void * 20 | |
6045 | Integers 40 | |
6046 | Floating point 60 | |
6047 | char 80 | |
6048 | Strings 100 (Low) | |
6049 | </PRE> | |
6050 | </DIV> | |
6051 | <P> Using these precedence values, overloaded methods with the same | |
6052 | number of required arguments are sorted in increased order of | |
6053 | precedence values.</P> | |
6054 | </LI> | |
6055 | </OL> | |
6056 | <P> This may sound very confusing, but an example will help. Consider | |
6057 | the following collection of overloaded methods:</P> | |
6058 | <DIV class="code"> | |
6059 | <PRE> | |
6060 | void foo(double); | |
6061 | void foo(int); | |
6062 | void foo(Bar *); | |
6063 | void foo(); | |
6064 | void foo(int x, int y, int z, int w); | |
6065 | void foo(int x, int y, int z = 3); | |
6066 | void foo(double x, double y); | |
6067 | void foo(double x, Bar *z); | |
6068 | </PRE> | |
6069 | </DIV> | |
6070 | <P> The first rule simply ranks the functions by required argument | |
6071 | count. This would produce the following list:</P> | |
6072 | <DIV class="diagram"> | |
6073 | <PRE> | |
6074 | rank | |
6075 | ----- | |
6076 | [0] foo() | |
6077 | [1] foo(double); | |
6078 | [2] foo(int); | |
6079 | [3] foo(Bar *); | |
6080 | [4] foo(int x, int y, int z = 3); | |
6081 | [5] foo(double x, double y) | |
6082 | [6] foo(double x, Bar *z) | |
6083 | [7] foo(int x, int y, int z, int w); | |
6084 | </PRE> | |
6085 | </DIV> | |
6086 | <P> The second rule, simply refines the ranking by looking at argument | |
6087 | type precedence values.</P> | |
6088 | <DIV class="diagram"> | |
6089 | <PRE> | |
6090 | rank | |
6091 | ----- | |
6092 | [0] foo() | |
6093 | [1] foo(Bar *); | |
6094 | [2] foo(int); | |
6095 | [3] foo(double); | |
6096 | [4] foo(int x, int y, int z = 3); | |
6097 | [5] foo(double x, Bar *z) | |
6098 | [6] foo(double x, double y) | |
6099 | [7] foo(int x, int y, int z, int w); | |
6100 | </PRE> | |
6101 | </DIV> | |
6102 | <P> Finally, to generate the dispatch function, the arguments passed to | |
6103 | an overloaded method are simply checked in the same order as they | |
6104 | appear in this ranking.</P> | |
6105 | <P> If you're still confused, don't worry about it---SWIG is probably | |
6106 | doing the right thing.</P> | |
6107 | <H3><A name="SWIGPlus_nn25"></A>6.15.2 Ambiguity in Overloading</H3> | |
6108 | <P> Regrettably, SWIG is not able to support every possible use of valid | |
6109 | C++ overloading. Consider the following example:</P> | |
6110 | <DIV class="code"> | |
6111 | <PRE> | |
6112 | void foo(int x); | |
6113 | void foo(long x); | |
6114 | </PRE> | |
6115 | </DIV> | |
6116 | <P> In C++, this is perfectly legal. However, in a scripting language, | |
6117 | there is generally only one kind of integer object. Therefore, which | |
6118 | one of these functions do you pick? Clearly, there is no way to truly | |
6119 | make a distinction just by looking at the value of the integer itself (<TT> | |
6120 | int</TT> and <TT>long</TT> may even be the same precision). Therefore, | |
6121 | when SWIG encounters this situation, it may generate a warning message | |
6122 | like this for scripting languages:</P> | |
6123 | <DIV class="shell"> | |
6124 | <PRE> | |
6125 | example.i:4: Warning(509): Overloaded foo(long) is shadowed by foo(int) at example.i:3. | |
6126 | </PRE> | |
6127 | </DIV> | |
6128 | <P> or for statically typed languages like Java:</P> | |
6129 | <DIV class="shell"> | |
6130 | <PRE> | |
6131 | example.i:4: Warning(516): Overloaded method foo(long) ignored. Method foo(int) | |
6132 | at example.i:3 used. | |
6133 | </PRE> | |
6134 | </DIV> | |
6135 | <P> This means that the second overloaded function will be inaccessible | |
6136 | from a scripting interface or the method won't be wrapped at all. This | |
6137 | is done as SWIG does not know how to disambiguate it from an earlier | |
6138 | method.</P> | |
6139 | <P> Ambiguity problems are known to arise in the following situations:</P> | |
6140 | <UL> | |
6141 | <LI>Integer conversions. Datatypes such as <TT>int</TT>, <TT>long</TT>, | |
6142 | and <TT>short</TT> cannot be disambiguated in some languages. Shown | |
6143 | above.</LI> | |
6144 | <LI>Floating point conversion. <TT>float</TT> and <TT>double</TT> can | |
6145 | not be disambiguated in some languages.</LI> | |
6146 | <LI>Pointers and references. For example, <TT>Foo *</TT> and <TT>Foo &</TT> | |
6147 | .</LI> | |
6148 | <LI>Pointers and arrays. For example, <TT>Foo *</TT> and <TT>Foo [4]</TT> | |
6149 | .</LI> | |
6150 | <LI>Pointers and instances. For example, <TT>Foo</TT> and <TT>Foo *</TT> | |
6151 | . Note: SWIG converts all instances to pointers.</LI> | |
6152 | <LI>Qualifiers. For example, <TT>const Foo *</TT> and <TT>Foo *</TT>.</LI> | |
6153 | <LI>Default vs. non default arguments. For example, <TT>foo(int a, int | |
6154 | b)</TT> and <TT>foo(int a, int b = 3)</TT>.</LI> | |
6155 | </UL> | |
6156 | <P> When an ambiguity arises, methods are checked in the same order as | |
6157 | they appear in the interface file. Therefore, earlier methods will | |
6158 | shadow methods that appear later.</P> | |
6159 | <P> When wrapping an overloaded function, there is a chance that you | |
6160 | will get an error message like this:</P> | |
6161 | <DIV class="shell"> | |
6162 | <PRE> | |
6163 | example.i:3: Warning(467): Overloaded foo(int) not supported (no type checking | |
6164 | rule for 'int'). | |
6165 | </PRE> | |
6166 | </DIV> | |
6167 | <P> This error means that the target language module supports | |
6168 | overloading, but for some reason there is no type-checking rule that | |
6169 | can be used to generate a working dispatch function. The resulting | |
6170 | behavior is then undefined. You should report this as a bug to the <A href="http://www.swig.org/bugs.html"> | |
6171 | SWIG bug tracking database</A>.</P> | |
6172 | <P> If you get an error message such as the following,</P> | |
6173 | <DIV class="shell"> | |
6174 | <PRE> | |
6175 | foo.i:6. Overloaded declaration ignored. Spam::foo(double ) | |
6176 | foo.i:5. Previous declaration is Spam::foo(int ) | |
6177 | foo.i:7. Overloaded declaration ignored. Spam::foo(Bar *,Spam *,int ) | |
6178 | foo.i:5. Previous declaration is Spam::foo(int ) | |
6179 | </PRE> | |
6180 | </DIV> | |
6181 | <P> it means that the target language module has not yet implemented | |
6182 | support for overloaded functions and methods. The only way to fix the | |
6183 | problem is to read the next section.</P> | |
6184 | <H3><A name="ambiguity_resolution_renaming"></A>6.15.3 Ambiguity | |
6185 | resolution and renaming</H3> | |
6186 | <P> If an ambiguity in overload resolution occurs or if a module doesn't | |
6187 | allow overloading, there are a few strategies for dealing with the | |
6188 | problem. First, you can tell SWIG to ignore one of the methods. This is | |
6189 | easy---simply use the <TT>%ignore</TT> directive. For example:</P> | |
6190 | <DIV class="code"> | |
6191 | <PRE> | |
6192 | %ignore foo(long); | |
6193 | ||
6194 | void foo(int); | |
6195 | void foo(long); // Ignored. Oh well. | |
6196 | </PRE> | |
6197 | </DIV> | |
6198 | <P> The other alternative is to rename one of the methods. This can be | |
6199 | done using <TT>%rename</TT>. For example:</P> | |
6200 | <DIV class="code"> | |
6201 | <PRE> | |
6202 | %rename(foo_long) foo(long); | |
6203 | ||
6204 | void foo(int); | |
6205 | void foo(long); // Accessed as foo_long() | |
6206 | </PRE> | |
6207 | </DIV> | |
6208 | <P> The <TT>%ignore</TT> and <TT>%rename</TT> directives are both rather | |
6209 | powerful in their ability to match declarations. When used in their | |
6210 | simple form, they apply to both global functions and methods. For | |
6211 | example:</P> | |
6212 | <DIV class="code"> | |
6213 | <PRE> | |
6214 | /* Forward renaming declarations */ | |
6215 | %rename(foo_i) foo(int); | |
6216 | %rename(foo_d) foo(double); | |
6217 | ... | |
6218 | void foo(int); // Becomes 'foo_i' | |
6219 | void foo(char *c); // Stays 'foo' (not renamed) | |
6220 | ||
6221 | class Spam { | |
6222 | public: | |
6223 | void foo(int); // Becomes 'foo_i' | |
6224 | void foo(double); // Becomes 'foo_d' | |
6225 | ... | |
6226 | }; | |
6227 | </PRE> | |
6228 | </DIV> | |
6229 | <P> If you only want the renaming to apply to a certain scope, the C++ | |
6230 | scope resolution operator (::) can be used. For example:</P> | |
6231 | <DIV class="code"> | |
6232 | <PRE> | |
6233 | %rename(foo_i) ::foo(int); // Only rename foo(int) in the global scope. | |
6234 | // (will not rename class members) | |
6235 | ||
6236 | %rename(foo_i) Spam::foo(int); // Only rename foo(int) in class Spam | |
6237 | </PRE> | |
6238 | </DIV> | |
6239 | <P> When a renaming operator is applied to a class as in <TT> | |
6240 | Spam::foo(int)</TT>, it is applied to that class and all derived | |
6241 | classes. This can be used to apply a consistent renaming across an | |
6242 | entire class hierarchy with only a few declarations. For example:</P> | |
6243 | <DIV class="code"> | |
6244 | <PRE> | |
6245 | %rename(foo_i) Spam::foo(int); | |
6246 | %rename(foo_d) Spam::foo(double); | |
6247 | ||
6248 | class Spam { | |
6249 | public: | |
6250 | virtual void foo(int); // Renamed to foo_i | |
6251 | virtual void foo(double); // Renamed to foo_d | |
6252 | ... | |
6253 | }; | |
6254 | ||
6255 | class Bar : public Spam { | |
6256 | public: | |
6257 | virtual void foo(int); // Renamed to foo_i | |
6258 | virtual void foo(double); // Renamed to foo_d | |
6259 | ... | |
6260 | }; | |
6261 | ||
6262 | class Grok : public Bar { | |
6263 | public: | |
6264 | virtual void foo(int); // Renamed to foo_i | |
6265 | virtual void foo(double); // Renamed to foo_d | |
6266 | ... | |
6267 | }; | |
6268 | </PRE> | |
6269 | </DIV> | |
6270 | <P> It is also possible to include <TT>%rename</TT> specifications in | |
6271 | the class definition itself. For example:</P> | |
6272 | <DIV class="code"> | |
6273 | <PRE> | |
6274 | class Spam { | |
6275 | %rename(foo_i) foo(int); | |
6276 | %rename(foo_d) foo(double); | |
6277 | public: | |
6278 | virtual void foo(int); // Renamed to foo_i | |
6279 | virtual void foo(double); // Renamed to foo_d | |
6280 | ... | |
6281 | }; | |
6282 | ||
6283 | class Bar : public Spam { | |
6284 | public: | |
6285 | virtual void foo(int); // Renamed to foo_i | |
6286 | virtual void foo(double); // Renamed to foo_d | |
6287 | ... | |
6288 | }; | |
6289 | </PRE> | |
6290 | </DIV> | |
6291 | <P> In this case, the <TT>%rename</TT> directives still get applied | |
6292 | across the entire inheritance hierarchy, but it's no longer necessary | |
6293 | to explicitly specify the class prefix <TT>Spam::</TT>.</P> | |
6294 | <P> A special form of <TT>%rename</TT> can be used to apply a renaming | |
6295 | just to class members (of all classes):</P> | |
6296 | <DIV class="code"> | |
6297 | <PRE> | |
6298 | %rename(foo_i) *::foo(int); // Only rename foo(int) if it appears in a class. | |
6299 | </PRE> | |
6300 | </DIV> | |
6301 | <P> Note: the <TT>*::</TT> syntax is non-standard C++, but the '*' is | |
6302 | meant to be a wildcard that matches any class name (we couldn't think | |
6303 | of a better alternative so if you have a better idea, send email to the | |
6304 | <A href="http://www.swig.org/mail.html">swig-dev mailing list</A>.</P> | |
6305 | <P> Although this discussion has primarily focused on <TT>%rename</TT> | |
6306 | all of the same rules also apply to <TT>%ignore</TT>. For example:</P> | |
6307 | <DIV class="code"> | |
6308 | <PRE> | |
6309 | %ignore foo(double); // Ignore all foo(double) | |
6310 | %ignore Spam::foo; // Ignore foo in class Spam | |
6311 | %ignore Spam::foo(double); // Ignore foo(double) in class Spam | |
6312 | %ignore *::foo(double); // Ignore foo(double) in all classes | |
6313 | </PRE> | |
6314 | </DIV> | |
6315 | <P> When applied to a base class, <TT>%ignore</TT> forces all | |
6316 | definitions in derived clases to disappear. For example, <TT>%ignore | |
6317 | Spam::foo(double)</TT> will eliminate <TT>foo(double)</TT> in <TT>Spam</TT> | |
6318 | and all classes derived from <TT>Spam</TT>.</P> | |
6319 | <P><B> Notes on %rename and %ignore:</B></P> | |
6320 | <UL> | |
6321 | <LI> | |
6322 | <P>Since, the <TT>%rename</TT> declaration is used to declare a renaming | |
6323 | in advance, it can be placed at the start of an interface file. This | |
6324 | makes it possible to apply a consistent name resolution without having | |
6325 | to modify header files. For example:</P> | |
6326 | <DIV class="code"> | |
6327 | <PRE> | |
6328 | %module foo | |
6329 | ||
6330 | /* Rename these overloaded functions */ | |
6331 | %rename(foo_i) foo(int); | |
6332 | %rename(foo_d) foo(double); | |
6333 | ||
6334 | %include "header.h" | |
6335 | </PRE> | |
6336 | </DIV></LI> | |
6337 | <LI> | |
6338 | <P>The scope qualifier (::) can also be used on simple names. For | |
6339 | example:</P> | |
6340 | <DIV class="code"> | |
6341 | <PRE> | |
6342 | %rename(bar) ::foo; // Rename foo to bar in global scope only | |
6343 | %rename(bar) Spam::foo; // Rename foo to bar in class Spam only | |
6344 | %rename(bar) *::foo; // Rename foo in classes only | |
6345 | </PRE> | |
6346 | </DIV></LI> | |
6347 | <LI> | |
6348 | <P>Name matching tries to find the most specific match that is defined. | |
6349 | A qualified name such as <TT>Spam::foo</TT> always has higher | |
6350 | precedence than an unqualified name <TT>foo</TT>. <TT>Spam::foo</TT> | |
6351 | has higher precedence than <TT>*::foo</TT> and <TT>*::foo</TT> has | |
6352 | higher precedence than <TT>foo</TT>. A parameterized name has higher | |
6353 | precedence than an unparameterized name within the same scope level. | |
6354 | However, an unparameterized name with a scope qualifier has higher | |
6355 | precedence than a parameterized name in global scope (e.g., a renaming | |
6356 | of <TT>Spam::foo</TT> takes precedence over a renaming of <TT>foo(int)</TT> | |
6357 | ).</P> | |
6358 | </LI> | |
6359 | <LI> | |
6360 | <P> The order in which <TT>%rename</TT> directives are defined does not | |
6361 | matter as long as they appear before the declarations to be renamed. | |
6362 | Thus, there is no difference between saying:</P> | |
6363 | <DIV class="code"> | |
6364 | <PRE> | |
6365 | %rename(bar) foo; | |
6366 | %rename(foo_i) Spam::foo(int); | |
6367 | %rename(Foo) Spam::foo; | |
6368 | </PRE> | |
6369 | </DIV> | |
6370 | <P> and this</P> | |
6371 | <DIV class="code"> | |
6372 | <PRE> | |
6373 | %rename(Foo) Spam::foo; | |
6374 | %rename(bar) foo; | |
6375 | %rename(foo_i) Spam::foo(int); | |
6376 | </PRE> | |
6377 | </DIV> | |
6378 | <P> (the declarations are not stored in a linked list and order has no | |
6379 | importance). Of course, a repeated <TT>%rename</TT> directive will | |
6380 | change the setting for a previous <TT>%rename</TT> directive if exactly | |
6381 | the same name, scope, and parameters are supplied.</P> | |
6382 | </LI> | |
6383 | <LI>For multiple inheritance where renaming rules are defined for | |
6384 | multiple base classes, the first renaming rule found on a depth-first | |
6385 | traversal of the class hierarchy is used.</LI> | |
6386 | <LI> | |
6387 | <P>The name matching rules strictly follow member qualification rules. | |
6388 | For example, if you have a class like this:</P> | |
6389 | <DIV class="code"> | |
6390 | <PRE> | |
6391 | class Spam { | |
6392 | public: | |
6393 | ... | |
6394 | void bar() const; | |
6395 | ... | |
6396 | }; | |
6397 | </PRE> | |
6398 | </DIV> | |
6399 | <P> the declaration</P> | |
6400 | <DIV class="code"> | |
6401 | <PRE> | |
6402 | %rename(name) Spam::bar(); | |
6403 | </PRE> | |
6404 | </DIV> | |
6405 | <P> will not apply as there is no unqualified member <TT>bar()</TT>. The | |
6406 | following will apply as the qualifier matches correctly:</P> | |
6407 | <DIV class="code"> | |
6408 | <PRE> | |
6409 | %rename(name) Spam::bar() const; | |
6410 | </PRE> | |
6411 | </DIV> | |
6412 | <P> An often overlooked C++ feature is that classes can define two | |
6413 | different overloaded members that differ only in their qualifiers, like | |
6414 | this:</P> | |
6415 | <DIV class="code"> | |
6416 | <PRE> | |
6417 | class Spam { | |
6418 | public: | |
6419 | ... | |
6420 | void bar(); // Unqualified member | |
6421 | void bar() const; // Qualified member | |
6422 | ... | |
6423 | }; | |
6424 | </PRE> | |
6425 | </DIV> | |
6426 | <P> %rename can then be used to target each of the overloaded methods | |
6427 | individually. For example we can give them separate names in the target | |
6428 | language:</P> | |
6429 | <DIV class="code"> | |
6430 | <PRE> | |
6431 | %rename(name1) Spam::bar(); | |
6432 | %rename(name2) Spam::bar() const; | |
6433 | </PRE> | |
6434 | </DIV> | |
6435 | <P> Similarly, if you merely wanted to ignore one of the declarations, | |
6436 | use <TT>%ignore</TT> with the full qualification. For example, the | |
6437 | following directive would tell SWIG to ignore the <TT>const</TT> | |
6438 | version of <TT>bar()</TT> above:</P> | |
6439 | <DIV class="code"> | |
6440 | <PRE> | |
6441 | %ignore Spam::bar() const; // Ignore bar() const, but leave other bar() alone | |
6442 | </PRE> | |
6443 | </DIV></LI> | |
6444 | <LI> | |
6445 | <P> The name matching rules also use default arguments for finer control | |
6446 | when wrapping methods that have default arguments. Recall that methods | |
6447 | with default arguments are wrapped as if the equivalent overloaded | |
6448 | methods had been parsed (<A href="#SWIGPlus_default_args">Default | |
6449 | arguments</A> section). Let's consider the following example class:</P> | |
6450 | <DIV class="code"> | |
6451 | <PRE> | |
6452 | class Spam { | |
6453 | public: | |
6454 | ... | |
6455 | void bar(int i=-1, double d=0.0); | |
6456 | ... | |
6457 | }; | |
6458 | </PRE> | |
6459 | </DIV> | |
6460 | <P> The following <TT>%rename</TT> will match exactly and apply to all | |
6461 | the target language overloaded methods because the declaration with the | |
6462 | default arguments exactly matches the wrapped method:</P> | |
6463 | <DIV class="code"> | |
6464 | <PRE> | |
6465 | %rename(newbar) Spam::bar(int i=-1, double d=0.0); | |
6466 | </PRE> | |
6467 | </DIV> | |
6468 | <P> The C++ method can then be called from the target language with the | |
6469 | new name no matter how many arguments are specified, for example: <TT> | |
6470 | newbar(2, 2.0)</TT>, <TT>newbar(2)</TT> or <TT>newbar()</TT>. However, | |
6471 | if the <TT>%rename</TT> does not contain the default arguments, it will | |
6472 | only apply to the single equivalent target language overloaded method. | |
6473 | So if instead we have:</P> | |
6474 | <DIV class="code"> | |
6475 | <PRE> | |
6476 | %rename(newbar) Spam::bar(int i, double d); | |
6477 | </PRE> | |
6478 | </DIV> | |
6479 | <P> The C++ method must then be called from the target language with the | |
6480 | new name <TT>newbar(2, 2.0)</TT> when both arguments are supplied or | |
6481 | with the original name as <TT>bar(2)</TT> (one argument) or <TT>bar()</TT> | |
6482 | (no arguments). In fact it is possible to use <TT>%rename</TT> on the | |
6483 | equivalent overloaded methods, to rename all the equivalent overloaded | |
6484 | methods:</P> | |
6485 | <DIV class="code"> | |
6486 | <PRE> | |
6487 | %rename(bar_2args) Spam::bar(int i, double d); | |
6488 | %rename(bar_1arg) Spam::bar(int i); | |
6489 | %rename(bar_default) Spam::bar(); | |
6490 | </PRE> | |
6491 | </DIV> | |
6492 | <P> Similarly, the extra overloaded methods can be selectively ignored | |
6493 | using <TT>%ignore</TT>.</P> | |
6494 | <P><B> Compatibility note:</B> The <TT>%rename</TT> directive introduced | |
6495 | the default argument matching rules in SWIG-1.3.23 at the same time as | |
6496 | the changes to wrapping methods with default arguments was introduced.</P> | |
6497 | </LI> | |
6498 | </UL> | |
6499 | <H3><A name="SWIGPlus_nn27"></A>6.15.4 Comments on overloading</H3> | |
6500 | <P> Support for overloaded methods was first added in SWIG-1.3.14. The | |
6501 | implementation is somewhat unusual when compared to similar tools. For | |
6502 | instance, the order in which declarations appear is largely irrelevant | |
6503 | in SWIG. Furthermore, SWIG does not rely upon trial execution or | |
6504 | exception handling to figure out which method to invoke.</P> | |
6505 | <P> Internally, the overloading mechanism is completely configurable by | |
6506 | the target language module. Therefore, the degree of overloading | |
6507 | support may vary from language to language. As a general rule, | |
6508 | statically typed languages like Java are able to provide more support | |
6509 | than dynamically typed languages like Perl, Python, Ruby, and Tcl.</P> | |
6510 | <H2><A name="SWIGPlus_nn28"></A>6.16 Wrapping overloaded operators</H2> | |
6511 | <P> Starting in SWIG-1.3.10, C++ overloaded operator declarations can be | |
6512 | wrapped. For example, consider a class like this:</P> | |
6513 | <DIV class="code"> | |
6514 | <PRE> | |
6515 | class Complex { | |
6516 | private: | |
6517 | double rpart, ipart; | |
6518 | public: | |
6519 | Complex(double r = 0, double i = 0) : rpart(r), ipart(i) { } | |
6520 | Complex(const Complex &c) : rpart(c.rpart), ipart(c.ipart) { } | |
6521 | Complex &operator=(const Complex &c) { | |
6522 | rpart = c.rpart; | |
6523 | ipart = c.ipart; | |
6524 | return *this; | |
6525 | } | |
6526 | Complex operator+(const Complex &c) const { | |
6527 | return Complex(rpart+c.rpart, ipart+c.ipart); | |
6528 | } | |
6529 | Complex operator-(const Complex &c) const { | |
6530 | return Complex(rpart-c.rpart, ipart-c.ipart); | |
6531 | } | |
6532 | Complex operator*(const Complex &c) const { | |
6533 | return Complex(rpart*c.rpart - ipart*c.ipart, | |
6534 | rpart*c.ipart + c.rpart*ipart); | |
6535 | } | |
6536 | Complex operator-() const { | |
6537 | return Complex(-rpart, -ipart); | |
6538 | } | |
6539 | double re() const { return rpart; } | |
6540 | double im() const { return ipart; } | |
6541 | }; | |
6542 | </PRE> | |
6543 | </DIV> | |
6544 | <P> When operator declarations appear, they are handled in<EM> exactly</EM> | |
6545 | the same manner as regular methods. However, the names of these methods | |
6546 | are set to strings like "<TT>operator +</TT>" or "<TT>operator -</TT>". | |
6547 | The problem with these names is that they are illegal identifiers in | |
6548 | most scripting languages. For instance, you can't just create a method | |
6549 | called "<TT>operator +</TT>" in Python--there won't be any way to call | |
6550 | it.</P> | |
6551 | <P> Some language modules already know how to automatically handle | |
6552 | certain operators (mapping them into operators in the target language). | |
6553 | However, the underlying implementation of this is really managed in a | |
6554 | very general way using the <TT>%rename</TT> directive. For example, in | |
6555 | Python a declaration similar to this is used:</P> | |
6556 | <DIV class="code"> | |
6557 | <PRE> | |
6558 | %rename(__add__) Complex::operator+; | |
6559 | </PRE> | |
6560 | </DIV> | |
6561 | <P> This binds the + operator to a method called <TT>__add__</TT> (which | |
6562 | is conveniently the same name used to implement the Python + operator). | |
6563 | Internally, the generated wrapper code for a wrapped operator will look | |
6564 | something like this pseudocode:</P> | |
6565 | <DIV class="code"> | |
6566 | <PRE> | |
6567 | _wrap_Complex___add__(args) { | |
6568 | ... get args ... | |
6569 | obj->operator+(args); | |
6570 | ... | |
6571 | } | |
6572 | </PRE> | |
6573 | </DIV> | |
6574 | <P> When used in the target language, it may now be possible to use the | |
6575 | overloaded operator normally. For example:</P> | |
6576 | <DIV class="targetlang"> | |
6577 | <PRE> | |
6578 | >>> a = Complex(3,4) | |
6579 | >>> b = Complex(5,2) | |
6580 | >>> c = a + b # Invokes __add__ method | |
6581 | </PRE> | |
6582 | </DIV> | |
6583 | <P> It is important to realize that there is nothing magical happening | |
6584 | here. The <TT>%rename</TT> directive really only picks a valid method | |
6585 | name. If you wrote this:</P> | |
6586 | <DIV class="code"> | |
6587 | <PRE> | |
6588 | %rename(add) operator+; | |
6589 | </PRE> | |
6590 | </DIV> | |
6591 | <P> The resulting scripting interface might work like this:</P> | |
6592 | <DIV class="targetlang"> | |
6593 | <PRE> | |
6594 | a = Complex(3,4) | |
6595 | b = Complex(5,2) | |
6596 | c = a.add(b) # Call a.operator+(b) | |
6597 | </PRE> | |
6598 | </DIV> | |
6599 | <P> All of the techniques described to deal with overloaded functions | |
6600 | also apply to operators. For example:</P> | |
6601 | <DIV class="code"> | |
6602 | <PRE> | |
6603 | %ignore Complex::operator=; // Ignore = in class Complex | |
6604 | %ignore *::operator=; // Ignore = in all classes | |
6605 | %ignore operator=; // Ignore = everywhere. | |
6606 | ||
6607 | %rename(__sub__) Complex::operator-; | |
6608 | %rename(__neg__) Complex::operator-(); // Unary - | |
6609 | </PRE> | |
6610 | </DIV> | |
6611 | <P> The last part of this example illustrates how multiple definitions | |
6612 | of the <TT>operator-</TT> method might be handled.</P> | |
6613 | <P> Handling operators in this manner is mostly straightforward. | |
6614 | However, there are a few subtle issues to keep in mind:</P> | |
6615 | <UL> | |
6616 | <LI> | |
6617 | <P>In C++, it is fairly common to define different versions of the | |
6618 | operators to account for different types. For example, a class might | |
6619 | also include a friend function like this:</P> | |
6620 | <DIV class="code"> | |
6621 | <PRE> | |
6622 | class Complex { | |
6623 | public: | |
6624 | friend Complex operator+(Complex &, double); | |
6625 | }; | |
6626 | Complex operator+(Complex &, double); | |
6627 | </PRE> | |
6628 | </DIV> | |
6629 | <P> SWIG simply ignores all <TT>friend</TT> declarations. Furthermore, | |
6630 | it doesn't know how to associate the associated <TT>operator+</TT> with | |
6631 | the class (because it's not a member of the class).</P> | |
6632 | <P> It's still possible to make a wrapper for this operator, but you'll | |
6633 | have to handle it like a normal function. For example:</P> | |
6634 | <DIV class="code"> | |
6635 | <PRE> | |
6636 | %rename(add_complex_double) operator+(Complex &, double); | |
6637 | </PRE> | |
6638 | </DIV></LI> | |
6639 | <LI> | |
6640 | <P>Certain operators are ignored by default. For instance, <TT>new</TT> | |
6641 | and <TT>delete</TT> operators are ignored as well as conversion | |
6642 | operators.</P> | |
6643 | </LI> | |
6644 | <LI>The semantics of certain C++ operators may not match those in the | |
6645 | target language.</LI> | |
6646 | </UL> | |
6647 | <H2><A name="SWIGPlus_nn29"></A>6.17 Class extension</H2> | |
6648 | <P> New methods can be added to a class using the <TT>%extend</TT> | |
6649 | directive. This directive is primarily used in conjunction with proxy | |
6650 | classes to add additional functionality to an existing class. For | |
6651 | example :</P> | |
6652 | <DIV class="code"> | |
6653 | <PRE> | |
6654 | %module vector | |
6655 | %{ | |
6656 | #include "vector.h" | |
6657 | %} | |
6658 | ||
6659 | class Vector { | |
6660 | public: | |
6661 | double x,y,z; | |
6662 | Vector(); | |
6663 | ~Vector(); | |
6664 | ... bunch of C++ methods ... | |
6665 | %extend { | |
6666 | char *__str__() { | |
6667 | static char temp[256]; | |
6668 | sprintf(temp,"[ %g, %g, %g ]", self->x,self->y,self->z); | |
6669 | return &temp[0]; | |
6670 | } | |
6671 | } | |
6672 | }; | |
6673 | </PRE> | |
6674 | </DIV> | |
6675 | <P> This code adds a <TT>__str__</TT> method to our class for producing | |
6676 | a string representation of the object. In Python, such a method would | |
6677 | allow us to print the value of an object using the <TT>print</TT> | |
6678 | command.</P> | |
6679 | <DIV class="targetlang"> | |
6680 | <PRE> | |
6681 | >>> | |
6682 | >>> v = Vector(); | |
6683 | >>> v.x = 3 | |
6684 | >>> v.y = 4 | |
6685 | >>> v.z = 0 | |
6686 | >>> print(v) | |
6687 | [ 3.0, 4.0, 0.0 ] | |
6688 | >>> | |
6689 | ||
6690 | </PRE> | |
6691 | </DIV> | |
6692 | <P> The <TT>%extend</TT> directive follows all of the same conventions | |
6693 | as its use with C structures. Please refer to the <A href="#SWIG">SWIG | |
6694 | Basics</A> chapter for further details.</P> | |
6695 | <P><B> Compatibility note:</B> The <TT>%extend</TT> directive is a new | |
6696 | name for the <TT>%addmethods</TT> directive. Since <TT>%addmethods</TT> | |
6697 | could be used to extend a structure with more than just methods, a more | |
6698 | suitable directive name has been chosen.</P> | |
6699 | <H2><A name="SWIGPlus_nn30"></A>6.18 Templates</H2> | |
6700 | <P> In all versions of SWIG, template type names may appear anywhere a | |
6701 | type is expected in an interface file. For example:</P> | |
6702 | <DIV class="code"> | |
6703 | <PRE> | |
6704 | void foo(vector<int> *a, int n); | |
6705 | void bar(list<int,100> *x); | |
6706 | </PRE> | |
6707 | </DIV> | |
6708 | <P> There are some restrictions on the use of non-type arguments. | |
6709 | Specifically, they have to be simple literals and not expressions. For | |
6710 | example:</P> | |
6711 | <DIV class="code"> | |
6712 | <PRE> | |
6713 | void bar(list<int,100> *x); // OK | |
6714 | void bar(list<int,2*50> *x); // Illegal | |
6715 | </PRE> | |
6716 | </DIV> | |
6717 | <P> The type system is smart enough to figure out clever games you might | |
6718 | try to play with <TT>typedef</TT>. For instance, consider this code:</P> | |
6719 | <DIV class="code"> | |
6720 | <PRE> | |
6721 | typedef int Integer; | |
6722 | void foo(vector<int> *x, vector<Integer> *y); | |
6723 | </PRE> | |
6724 | </DIV> | |
6725 | <P> In this case, <TT>vector<Integer></TT> is exactly the same type as <TT> | |
6726 | vector<int></TT>. The wrapper for <TT>foo()</TT> will accept either | |
6727 | variant.</P> | |
6728 | <P> Starting with SWIG-1.3.7, simple C++ template declarations can also | |
6729 | be wrapped. SWIG-1.3.12 greatly expands upon the earlier | |
6730 | implementation. Before discussing this any further, there are a few | |
6731 | things you need to know about template wrapping. First, a bare C++ | |
6732 | template does not define any sort of runnable object-code for which | |
6733 | SWIG can normally create a wrapper. Therefore, in order to wrap a | |
6734 | template, you need to give SWIG information about a particular template | |
6735 | instantiation (e.g., <TT>vector<int></TT>, <TT>array<double></TT>, | |
6736 | etc.). Second, an instantiation name such as <TT>vector<int></TT> is | |
6737 | generally not a valid identifier name in most target languages. Thus, | |
6738 | you will need to give the template instantiation a more suitable name | |
6739 | such as <TT>intvector</TT> when creating a wrapper.</P> | |
6740 | <P> To illustrate, consider the following template definition:</P> | |
6741 | <DIV class="code"> | |
6742 | <PRE> | |
6743 | template<class T> class List { | |
6744 | private: | |
6745 | T *data; | |
6746 | int nitems; | |
6747 | int maxitems; | |
6748 | public: | |
6749 | List(int max) { | |
6750 | data = new T [max]; | |
6751 | nitems = 0; | |
6752 | maxitems = max; | |
6753 | } | |
6754 | ~List() { | |
6755 | delete [] data; | |
6756 | }; | |
6757 | void append(T obj) { | |
6758 | if (nitems < maxitems) { | |
6759 | data[nitems++] = obj; | |
6760 | } | |
6761 | } | |
6762 | int length() { | |
6763 | return nitems; | |
6764 | } | |
6765 | T get(int n) { | |
6766 | return data[n]; | |
6767 | } | |
6768 | }; | |
6769 | </PRE> | |
6770 | </DIV> | |
6771 | <P> By itself, this template declaration is useless--SWIG simply ignores | |
6772 | it because it doesn't know how to generate any code until unless a | |
6773 | definition of <TT>T</TT> is provided.</P> | |
6774 | <P> One way to create wrappers for a specific template instantiation is | |
6775 | to simply provide an expanded version of the class directly like this:</P> | |
6776 | <DIV class="code"> | |
6777 | <PRE> | |
6778 | %rename(intList) List<int>; // Rename to a suitable identifier | |
6779 | class List<int> { | |
6780 | private: | |
6781 | int *data; | |
6782 | int nitems; | |
6783 | int maxitems; | |
6784 | public: | |
6785 | List(int max); | |
6786 | ~List(); | |
6787 | void append(int obj); | |
6788 | int length(); | |
6789 | int get(int n); | |
6790 | }; | |
6791 | </PRE> | |
6792 | </DIV> | |
6793 | <P> The <TT>%rename</TT> directive is needed to give the template class | |
6794 | an appropriate identifier name in the target language (most languages | |
6795 | would not recognize C++ template syntax as a valid class name). The | |
6796 | rest of the code is the same as what would appear in a normal class | |
6797 | definition.</P> | |
6798 | <P> Since manual expansion of templates gets old in a hurry, the <TT> | |
6799 | %template</TT> directive can be used to create instantiations of a | |
6800 | template class. Semantically, <TT>%template</TT> is simply a | |
6801 | shortcut---it expands template code in exactly the same way as shown | |
6802 | above. Here are some examples:</P> | |
6803 | <DIV class="code"> | |
6804 | <PRE> | |
6805 | /* Instantiate a few different versions of the template */ | |
6806 | %template(intList) List<int>; | |
6807 | %template(doubleList) List<double>; | |
6808 | </PRE> | |
6809 | </DIV> | |
6810 | <P> The argument to <TT>%template()</TT> is the name of the | |
6811 | instantiation in the target language. The name you choose should not | |
6812 | conflict with any other declarations in the interface file with one | |
6813 | exception---it is okay for the template name to match that of a typedef | |
6814 | declaration. For example:</P> | |
6815 | <DIV class="code"> | |
6816 | <PRE> | |
6817 | %template(intList) List<int>; | |
6818 | ... | |
6819 | typedef List<int> intList; // OK | |
6820 | </PRE> | |
6821 | </DIV> | |
6822 | <P> SWIG can also generate wrappers for function templates using a | |
6823 | similar technique. For example:</P> | |
6824 | <DIV class="code"> | |
6825 | <PRE> | |
6826 | // Function template | |
6827 | template<class T> T max(T a, T b) { return a > b ? a : b; } | |
6828 | ||
6829 | // Make some different versions of this function | |
6830 | %template(maxint) max<int>; | |
6831 | %template(maxdouble) max<double>; | |
6832 | </PRE> | |
6833 | </DIV> | |
6834 | <P> In this case, <TT>maxint</TT> and <TT>maxdouble</TT> become unique | |
6835 | names for specific instantiations of the function.</P> | |
6836 | <P> The number of arguments supplied to <TT>%template</TT> should match | |
6837 | that in the original template definition. Template default arguments | |
6838 | are supported. For example:</P> | |
6839 | <DIV class="code"> | |
6840 | <PRE> | |
6841 | template vector<typename T, int max=100> class vector { | |
6842 | ... | |
6843 | }; | |
6844 | ||
6845 | %template(intvec) vector<int>; // OK | |
6846 | %template(vec1000) vector<int,1000>; // OK | |
6847 | </PRE> | |
6848 | </DIV> | |
6849 | <P> The <TT>%template</TT> directive should not be used to wrap the same | |
6850 | template instantiation more than once in the same scope. This will | |
6851 | generate an error. For example:</P> | |
6852 | <DIV class="code"> | |
6853 | <PRE> | |
6854 | %template(intList) List<int>; | |
6855 | %template(Listint) List<int>; // Error. Template already wrapped. | |
6856 | </PRE> | |
6857 | </DIV> | |
6858 | <P> This error is caused because the template expansion results in two | |
6859 | identical classes with the same name. This generates a symbol table | |
6860 | conflict. Besides, it probably more efficient to only wrap a specific | |
6861 | instantiation only once in order to reduce the potential for code | |
6862 | bloat.</P> | |
6863 | <P> Since the type system knows how to handle <TT>typedef</TT>, it is | |
6864 | generally not necessary to instantiate different versions of a template | |
6865 | for typenames that are equivalent. For instance, consider this code:</P> | |
6866 | <DIV class="code"> | |
6867 | <PRE> | |
6868 | %template(intList) vector<int>; | |
6869 | typedef int Integer; | |
6870 | ... | |
6871 | void foo(vector<Integer> *x); | |
6872 | </PRE> | |
6873 | </DIV> | |
6874 | <P> In this case, <TT>vector<Integer></TT> is exactly the same type as <TT> | |
6875 | vector<int></TT>. Any use of <TT>Vector<Integer></TT> is mapped back to | |
6876 | the instantiation of <TT>vector<int></TT> created earlier. Therefore, | |
6877 | it is not necessary to instantiate a new class for the type <TT>Integer</TT> | |
6878 | (doing so is redundant and will simply result in code bloat).</P> | |
6879 | <P> When a template is instantiated using <TT>%template</TT>, | |
6880 | information about that class is saved by SWIG and used elsewhere in the | |
6881 | program. For example, if you wrote code like this,</P> | |
6882 | <DIV class="code"> | |
6883 | <PRE> | |
6884 | ... | |
6885 | %template(intList) List<int>; | |
6886 | ... | |
6887 | class UltraList : public List<int> { | |
6888 | ... | |
6889 | }; | |
6890 | </PRE> | |
6891 | </DIV> | |
6892 | <P> then SWIG knows that <TT>List<int></TT> was already wrapped as a | |
6893 | class called <TT>intList</TT> and arranges to handle the inheritance | |
6894 | correctly. If, on the other hand, nothing is known about <TT>List<int></TT> | |
6895 | , you will get a warning message similar to this:</P> | |
6896 | <DIV class="shell"> | |
6897 | <PRE> | |
6898 | example.h:42. Nothing known about class 'List<int >' (ignored). | |
6899 | example.h:42. Maybe you forgot to instantiate 'List<int >' using %template. | |
6900 | </PRE> | |
6901 | </DIV> | |
6902 | <P> If a template class inherits from another template class, you need | |
6903 | to make sure that base classes are instantiated before derived classes. | |
6904 | For example:</P> | |
6905 | <DIV class="code"> | |
6906 | <PRE> | |
6907 | template<class T> class Foo { | |
6908 | ... | |
6909 | }; | |
6910 | ||
6911 | template<class T> class Bar : public Foo<T> { | |
6912 | ... | |
6913 | }; | |
6914 | ||
6915 | // Instantiate base classes first | |
6916 | %template(intFoo) Foo<int>; | |
6917 | %template(doubleFoo) Foo<double>; | |
6918 | ||
6919 | // Now instantiate derived classes | |
6920 | %template(intBar) Bar<int>; | |
6921 | %template(doubleBar) Bar<double>; | |
6922 | </PRE> | |
6923 | </DIV> | |
6924 | <P> The order is important since SWIG uses the instantiation names to | |
6925 | properly set up the inheritance hierarchy in the resulting wrapper code | |
6926 | (and base classes need to be wrapped before derived classes). Don't | |
6927 | worry--if you get the order wrong, SWIG should generate a warning | |
6928 | message.</P> | |
6929 | <P> Occassionally, you may need to tell SWIG about base classes that are | |
6930 | defined by templates, but which aren't supposed to be wrapped. Since | |
6931 | SWIG is not able to automatically instantiate templates for this | |
6932 | purpose, you must do it manually. To do this, simply use <TT>%template</TT> | |
6933 | with no name. For example:</P> | |
6934 | <DIV class="code"> | |
6935 | <PRE> | |
6936 | // Instantiate traits<double,double>, but don't wrap it. | |
6937 | %template() traits<double,double>; | |
6938 | </PRE> | |
6939 | </DIV> | |
6940 | <P> If you have to instantiate a lot of different classes for many | |
6941 | different types, you might consider writing a SWIG macro. For example:</P> | |
6942 | <DIV class="code"> | |
6943 | <PRE> | |
6944 | %define TEMPLATE_WRAP(T,prefix) | |
6945 | %template(prefix ## Foo) Foo<T>; | |
6946 | %template(prefix ## Bar) Bar<T>; | |
6947 | ... | |
6948 | %enddef | |
6949 | ||
6950 | TEMPLATE_WRAP(int, int) | |
6951 | TEMPLATE_WRAP(double, double) | |
6952 | TEMPLATE_WRAP(char *, String) | |
6953 | ... | |
6954 | </PRE> | |
6955 | </DIV> | |
6956 | <P> The SWIG template mechanism<EM> does</EM> support specialization. | |
6957 | For instance, if you define a class like this,</P> | |
6958 | <DIV class="code"> | |
6959 | <PRE> | |
6960 | template<> class List<int> { | |
6961 | private: | |
6962 | int *data; | |
6963 | int nitems; | |
6964 | int maxitems; | |
6965 | public: | |
6966 | List(int max); | |
6967 | ~List(); | |
6968 | void append(int obj); | |
6969 | int length(); | |
6970 | int get(int n); | |
6971 | }; | |
6972 | </PRE> | |
6973 | </DIV> | |
6974 | <P> then SWIG will use this code whenever the user expands <TT>List<int></TT> | |
6975 | . In practice, this may have very little effect on the underlying | |
6976 | wrapper code since specialization is often used to provide slightly | |
6977 | modified method bodies (which are ignored by SWIG). However, special | |
6978 | SWIG directives such as <TT>%typemap</TT>, <TT>%extend</TT>, and so | |
6979 | forth can be attached to a specialization to provide customization for | |
6980 | specific types.</P> | |
6981 | <P> Partial template specialization is partially supported by SWIG. For | |
6982 | example, this code defines a template that is applied when the template | |
6983 | argument is a pointer.</P> | |
6984 | <DIV class="code"> | |
6985 | <PRE> | |
6986 | template<class T> class List<T*> { | |
6987 | private: | |
6988 | T *data; | |
6989 | int nitems; | |
6990 | int maxitems; | |
6991 | public: | |
6992 | List(int max); | |
6993 | ~List(); | |
6994 | void append(int obj); | |
6995 | int length(); | |
6996 | T get(int n); | |
6997 | }; | |
6998 | </PRE> | |
6999 | </DIV> | |
7000 | <P> SWIG should be able to handle most simple uses of partial | |
7001 | specialization. However, it may fail to match templates properly in | |
7002 | more complicated cases. For example, if you have this code,</P> | |
7003 | <DIV class="code"> | |
7004 | <PRE> | |
7005 | template<class T1, class T2> class Foo<T1, T2 *> { }; | |
7006 | </PRE> | |
7007 | </DIV> | |
7008 | <P> SWIG isn't able to match it properly for instantiations like <TT> | |
7009 | Foo<int *, int *></TT>. This problem is not due to parsing, but due to | |
7010 | the fact that SWIG does not currently implement all of the C++ argument | |
7011 | deduction rules.</P> | |
7012 | <P> Member function templates are supported. The underlying principle is | |
7013 | the same as for normal templates--SWIG can't create a wrapper unless | |
7014 | you provide more information about types. For example, a class with a | |
7015 | member template might look like this:</P> | |
7016 | <DIV class="code"> | |
7017 | <PRE> | |
7018 | class Foo { | |
7019 | public: | |
7020 | template<class T> void bar(T x, T y) { ... }; | |
7021 | ... | |
7022 | }; | |
7023 | </PRE> | |
7024 | </DIV> | |
7025 | <P> To expand the template, simply use <TT>%template</TT> inside the | |
7026 | class.</P> | |
7027 | <DIV class="code"> | |
7028 | <PRE> | |
7029 | class Foo { | |
7030 | public: | |
7031 | template<class T> void bar(T x, T y) { ... }; | |
7032 | ... | |
7033 | %template(barint) bar<int>; | |
7034 | %template(bardouble) bar<double>; | |
7035 | }; | |
7036 | </PRE> | |
7037 | </DIV> | |
7038 | <P> Or, if you want to leave the original class definition alone, just | |
7039 | do this:</P> | |
7040 | <DIV class="code"> | |
7041 | <PRE> | |
7042 | class Foo { | |
7043 | public: | |
7044 | template<class T> void bar(T x, T y) { ... }; | |
7045 | ... | |
7046 | }; | |
7047 | ... | |
7048 | %extend Foo { | |
7049 | %template(barint) bar<int>; | |
7050 | %template(bardouble) bar<double>; | |
7051 | }; | |
7052 | </PRE> | |
7053 | </DIV> | |
7054 | <P> or simply</P> | |
7055 | <DIV class="code"> | |
7056 | <PRE> | |
7057 | class Foo { | |
7058 | public: | |
7059 | template<class T> void bar(T x, T y) { ... }; | |
7060 | ... | |
7061 | }; | |
7062 | ... | |
7063 | ||
7064 | %template(bari) Foo::bar<int>; | |
7065 | %template(bard) Foo::bar<double>; | |
7066 | </PRE> | |
7067 | </DIV> | |
7068 | <P> In this case, the <TT>%extend</TT> directive is not needed, and <TT> | |
7069 | %template</TT> does the exactly same job, i.e., it adds two new methods | |
7070 | to the Foo class.</P> | |
7071 | <P> Note: because of the way that templates are handled, the <TT> | |
7072 | %template</TT> directive must always appear<EM> after</EM> the | |
7073 | definition of the template to be expanded.</P> | |
7074 | <P> Now, if your target language supports overloading, you can even try</P> | |
7075 | <DIV class="code"> | |
7076 | <PRE> | |
7077 | %template(bar) Foo::bar<int>; | |
7078 | %template(bar) Foo::bar<double>; | |
7079 | </PRE> | |
7080 | </DIV> | |
7081 | <P> and since the two new wrapped methods have the same name 'bar', they | |
7082 | will be overloaded, and when called, the correct method will be | |
7083 | dispatched depending on the argument type.</P> | |
7084 | <P> When used with members, the <TT>%template</TT> directive may be | |
7085 | placed in another template class. Here is a slightly perverse example:</P> | |
7086 | <DIV class="code"> | |
7087 | <PRE> | |
7088 | // A template | |
7089 | template<class T> class Foo { | |
7090 | public: | |
7091 | // A member template | |
7092 | template<class S> T bar(S x, S y) { ... }; | |
7093 | ... | |
7094 | }; | |
7095 | ||
7096 | // Expand a few member templates | |
7097 | %extend Foo { | |
7098 | %template(bari) bar<int>; | |
7099 | %template(bard) bar<double>; | |
7100 | } | |
7101 | ||
7102 | // Create some wrappers for the template | |
7103 | %template(Fooi) Foo<int>; | |
7104 | %template(Food) Foo<double>; | |
7105 | </PRE> | |
7106 | </DIV> | |
7107 | <P> Miraculously, you will find that each expansion of <TT>Foo</TT> has | |
7108 | member functions <TT>bari()</TT> and <TT>bard()</TT> added.</P> | |
7109 | <P> A common use of member templates is to define constructors for | |
7110 | copies and conversions. For example:</P> | |
7111 | <DIV class="code"> | |
7112 | <PRE> | |
7113 | template<class T1, class T2> struct pair { | |
7114 | T1 first; | |
7115 | T2 second; | |
7116 | pair() : first(T1()), second(T2()) { } | |
7117 | pair(const T1 &x, const T2 &y) : first(x), second(y) { } | |
7118 | template<class U1, class U2> pair(const pair<U1,U2> &x) | |
7119 | : first(x.first),second(x.second) { } | |
7120 | }; | |
7121 | </PRE> | |
7122 | </DIV> | |
7123 | <P> This declaration is perfectly acceptable to SWIG, but the | |
7124 | constructor template will be ignored unless you explicitly expand it. | |
7125 | To do that, you could expand a few versions of the constructor in the | |
7126 | template class itself. For example:</P> | |
7127 | <DIV class="code"> | |
7128 | <PRE> | |
7129 | %extend pair { | |
7130 | %template(pair) pair<T1,T2>; // Generate default copy constructor | |
7131 | }; | |
7132 | </PRE> | |
7133 | </DIV> | |
7134 | <P> When using <TT>%extend</TT> in this manner, notice how you can still | |
7135 | use the template parameters in the original template definition.</P> | |
7136 | <P> Alternatively, you could expand the constructor template in selected | |
7137 | instantiations. For example:</P> | |
7138 | <DIV class="code"> | |
7139 | <PRE> | |
7140 | // Instantiate a few versions | |
7141 | %template(pairii) pair<int,int>; | |
7142 | %template(pairdd) pair<double,double>; | |
7143 | ||
7144 | // Create a default constructor only | |
7145 | %extend pair<int,int> { | |
7146 | %template(paird) pair<int,int>; // Default constructor | |
7147 | }; | |
7148 | ||
7149 | // Create default and conversion constructors | |
7150 | %extend pair<double,double> { | |
7151 | %template(paird) pair<double,dobule>; // Default constructor | |
7152 | %template(pairc) pair<int,int>; // Conversion constructor | |
7153 | }; | |
7154 | </PRE> | |
7155 | </DIV> | |
7156 | <P>And if your target language supports overloading, then you can try | |
7157 | instead:</P> | |
7158 | <DIV class="code"> | |
7159 | <PRE> | |
7160 | // Create default and conversion constructors | |
7161 | %extend pair<double,double> { | |
7162 | %template(pair) pair<double,dobule>; // Default constructor | |
7163 | %template(pair) pair<int,int>; // Conversion constructor | |
7164 | }; | |
7165 | </PRE> | |
7166 | </DIV> | |
7167 | <P> In this case, the default and conversion constructors have the same | |
7168 | name. Hence, Swig will overload them and define an unique visible | |
7169 | constructor, that will dispatch the proper call depending on the | |
7170 | argument type.</P> | |
7171 | <P> If all of this isn't quite enough and you really want to make | |
7172 | someone's head explode, SWIG directives such as <TT>%rename</TT>, <TT> | |
7173 | %extend</TT>, and <TT>%typemap</TT> can be included directly in template | |
7174 | definitions. For example:</P> | |
7175 | <DIV class="code"> | |
7176 | <PRE> | |
7177 | // File : list.h | |
7178 | template<class T> class List { | |
7179 | ... | |
7180 | public: | |
7181 | %rename(__getitem__) get(int); | |
7182 | List(int max); | |
7183 | ~List(); | |
7184 | ... | |
7185 | T get(int index); | |
7186 | %extend { | |
7187 | char *__str__() { | |
7188 | /* Make a string representation */ | |
7189 | ... | |
7190 | } | |
7191 | } | |
7192 | }; | |
7193 | </PRE> | |
7194 | </DIV> | |
7195 | <P> In this example, the extra SWIG directives are propagated to<EM> | |
7196 | every</EM> template instantiation.</P> | |
7197 | <P> It is also possible to separate these declarations from the template | |
7198 | class. For example:</P> | |
7199 | <DIV class="code"> | |
7200 | <PRE> | |
7201 | %rename(__getitem__) List::get; | |
7202 | %extend List { | |
7203 | char *__str__() { | |
7204 | /* Make a string representation */ | |
7205 | ... | |
7206 | } | |
7207 | /* Make a copy */ | |
7208 | T *__copy__() { | |
7209 | return new List<T>(*self); | |
7210 | } | |
7211 | }; | |
7212 | ||
7213 | ... | |
7214 | template<class T> class List { | |
7215 | ... | |
7216 | public: | |
7217 | List() { }; | |
7218 | ... | |
7219 | }; | |
7220 | </PRE> | |
7221 | </DIV> | |
7222 | <P> When <TT>%extend</TT> is decoupled from the class definition, it is | |
7223 | legal to use the same template parameters as provided in the class | |
7224 | definition. These are replaced when the template is expanded. In | |
7225 | addition, the <TT>%extend</TT> directive can be used to add additional | |
7226 | methods to a specific instantiation. For example:</P> | |
7227 | <DIV class="code"> | |
7228 | <PRE> | |
7229 | %template(intList) List<int>; | |
7230 | ||
7231 | %extend List<int> { | |
7232 | void blah() { | |
7233 | printf("Hey, I'm an List<int>!\n"); | |
7234 | } | |
7235 | }; | |
7236 | </PRE> | |
7237 | </DIV> | |
7238 | <P> SWIG even supports overloaded templated functions. As usual the <TT> | |
7239 | %template</TT> directive is used to wrap templated functions. For | |
7240 | example:</P> | |
7241 | <DIV class="code"> | |
7242 | <PRE> | |
7243 | template<class T> void foo(T x) { }; | |
7244 | template<class T> void foo(T x, T y) { }; | |
7245 | ||
7246 | %template(foo) foo<int>; | |
7247 | </PRE> | |
7248 | </DIV> | |
7249 | <P> This will generate two overloaded wrapper methods, the first will | |
7250 | take a single integer as an argument and the second will take two | |
7251 | integer arguments.</P> | |
7252 | <P> Needless to say, SWIG's template support provides plenty of | |
7253 | opportunities to break the universe. That said, an important final | |
7254 | point is that<B> SWIG does not perform extensive error checking of | |
7255 | templates!</B> Specifically, SWIG does not perform type checking nor | |
7256 | does it check to see if the actual contents of the template declaration | |
7257 | make any sense. Since the C++ compiler will hopefully check this when | |
7258 | it compiles the resulting wrapper file, there is no practical reason | |
7259 | for SWIG to duplicate this functionality (besides, none of the SWIG | |
7260 | developers are masochistic enough to want to implement this right now).</P> | |
7261 | <P><B> Compatibility Note</B>: The first implementation of template | |
7262 | support relied heavily on macro expansion in the preprocessor. | |
7263 | Templates have been more tightly integrated into the parser and type | |
7264 | system in SWIG-1.3.12 and the preprocessor is no longer used. Code that | |
7265 | relied on preprocessing features in template expansion will no longer | |
7266 | work. However, SWIG still allows the # operator to be used to generate | |
7267 | a string from a template argument.</P> | |
7268 | <P><B> Compatibility Note</B>: In earlier versions of SWIG, the <TT> | |
7269 | %template</TT> directive introduced a new class name. This name could | |
7270 | then be used with other directives. For example:</P> | |
7271 | <DIV class="code"> | |
7272 | <PRE> | |
7273 | %template(vectori) vector<int>; | |
7274 | %extend vectori { | |
7275 | void somemethod() { } | |
7276 | }; | |
7277 | </PRE> | |
7278 | </DIV> | |
7279 | <P> This behavior is no longer supported. Instead, you should use the | |
7280 | original template name as the class name. For example:</P> | |
7281 | <DIV class="code"> | |
7282 | <PRE> | |
7283 | %template(vectori) vector<int>; | |
7284 | %extend vector<int> { | |
7285 | void somemethod() { } | |
7286 | }; | |
7287 | </PRE> | |
7288 | </DIV> | |
7289 | <P> Similar changes apply to typemaps and other customization features.</P> | |
7290 | <H2><A name="SWIGPlus_nn31"></A>6.19 Namespaces</H2> | |
7291 | <P> Support for C++ namespaces is a relatively late addition to SWIG, | |
7292 | first appearing in SWIG-1.3.12. Before describing the implementation, | |
7293 | it is worth nothing that the semantics of C++ namespaces is extremely | |
7294 | non-trivial--especially with regard to the C++ type system and class | |
7295 | machinery. At a most basic level, namespaces are sometimes used to | |
7296 | encapsulate common functionality. For example:</P> | |
7297 | <DIV class="code"> | |
7298 | <PRE> | |
7299 | namespace math { | |
7300 | double sin(double); | |
7301 | double cos(double); | |
7302 | ||
7303 | class Complex { | |
7304 | double im,re; | |
7305 | public: | |
7306 | ... | |
7307 | }; | |
7308 | ... | |
7309 | }; | |
7310 | </PRE> | |
7311 | </DIV> | |
7312 | <P> Members of the namespace are accessed in C++ by prepending the | |
7313 | namespace prefix to names. For example:</P> | |
7314 | <DIV class="code"> | |
7315 | <PRE> | |
7316 | double x = math::sin(1.0); | |
7317 | double magnitude(math::Complex *c); | |
7318 | math::Complex c; | |
7319 | ... | |
7320 | </PRE> | |
7321 | </DIV> | |
7322 | <P> At this level, namespaces are relatively easy to manage. However, | |
7323 | things start to get very ugly when you throw in the other ways a | |
7324 | namespace can be used. For example, selective symbols can be exported | |
7325 | from a namespace with <TT>using</TT>.</P> | |
7326 | <DIV class="code"> | |
7327 | <PRE> | |
7328 | using math::Complex; | |
7329 | double magnitude(Complex *c); // Namespace prefix stripped | |
7330 | </PRE> | |
7331 | </DIV> | |
7332 | <P> Similarly, the contents of an entire namespace can be made available | |
7333 | like this:</P> | |
7334 | <DIV class="code"> | |
7335 | <PRE> | |
7336 | using namespace math; | |
7337 | double x = sin(1.0); | |
7338 | double magnitude(Complex *c); | |
7339 | </PRE> | |
7340 | </DIV> | |
7341 | <P> Alternatively, a namespace can be aliased:</P> | |
7342 | <DIV class="code"> | |
7343 | <PRE> | |
7344 | namespace M = math; | |
7345 | double x = M::sin(1.0); | |
7346 | double magnitude(M::Complex *c); | |
7347 | </PRE> | |
7348 | </DIV> | |
7349 | <P> Using combinations of these features, it is possible to write | |
7350 | head-exploding code like this:</P> | |
7351 | <DIV class="code"> | |
7352 | <PRE> | |
7353 | namespace A { | |
7354 | class Foo { | |
7355 | }; | |
7356 | } | |
7357 | ||
7358 | namespace B { | |
7359 | namespace C { | |
7360 | using namespace A; | |
7361 | } | |
7362 | typedef C::Foo FooClass; | |
7363 | } | |
7364 | ||
7365 | namespace BIGB = B; | |
7366 | ||
7367 | namespace D { | |
7368 | using BIGB::FooClass; | |
7369 | class Bar : public FooClass { | |
7370 | } | |
7371 | }; | |
7372 | ||
7373 | class Spam : public D::Bar { | |
7374 | }; | |
7375 | ||
7376 | void evil(A::Foo *a, B::FooClass *b, B::C::Foo *c, BIGB::FooClass *d, | |
7377 | BIGB::C::Foo *e, D::FooClass *f); | |
7378 | ||
7379 | </PRE> | |
7380 | </DIV> | |
7381 | <P> Given the possibility for such perversion, it's hard to imagine how | |
7382 | every C++ programmer might want such code wrapped into the target | |
7383 | language. Clearly this code defines three different classes. However, | |
7384 | one of those classes is accessible under at least six different class | |
7385 | names!</P> | |
7386 | <P> SWIG fully supports C++ namespaces in its internal type system and | |
7387 | class handling code. If you feed SWIG the above code, it will be parsed | |
7388 | correctly, it will generate compilable wrapper code, and it will | |
7389 | produce a working scripting language module. However, the default | |
7390 | wrapping behavior is to flatten namespaces in the target language. This | |
7391 | means that the contents of all namespaces are merged together in the | |
7392 | resulting scripting language module. For example, if you have code like | |
7393 | this,</P> | |
7394 | <DIV class="code"> | |
7395 | <PRE> | |
7396 | %module foo | |
7397 | namespace foo { | |
7398 | void bar(int); | |
7399 | void spam(); | |
7400 | } | |
7401 | ||
7402 | namespace bar { | |
7403 | void blah(); | |
7404 | } | |
7405 | ||
7406 | </PRE> | |
7407 | </DIV> | |
7408 | <P> then SWIG simply creates three wrapper functions <TT>bar()</TT>, <TT> | |
7409 | spam()</TT>, and <TT>blah()</TT> in the target language. SWIG does not | |
7410 | prepend the names with a namespace prefix nor are the functions | |
7411 | packaged in any kind of nested scope.</P> | |
7412 | <P> There is some rationale for taking this approach. Since C++ | |
7413 | namespaces are often used to define modules in C++, there is a natural | |
7414 | correlation between the likely contents of a SWIG module and the | |
7415 | contents of a namespace. For instance, it would not be unreasonable to | |
7416 | assume that a programmer might make a separate extension module for | |
7417 | each C++ namespace. In this case, it would be redundant to prepend | |
7418 | everything with an additional namespace prefix when the module itself | |
7419 | already serves as a namespace in the target language. Or put another | |
7420 | way, if you want SWIG to keep namespaces separate, simply wrap each | |
7421 | namespace with its own SWIG interface.</P> | |
7422 | <P> Because namespaces are flattened, it is possible for symbols defined | |
7423 | in different namespaces to generate a name conflict in the target | |
7424 | language. For example:</P> | |
7425 | <DIV class="code"> | |
7426 | <PRE> | |
7427 | namespace A { | |
7428 | void foo(int); | |
7429 | } | |
7430 | namespace B { | |
7431 | void foo(double); | |
7432 | } | |
7433 | </PRE> | |
7434 | </DIV> | |
7435 | <P> When this conflict occurs, you will get an error message that | |
7436 | resembles this:</P> | |
7437 | <DIV class="shell"> | |
7438 | <PRE> | |
7439 | example.i:26. Error. 'foo' is multiply defined in the generated module. | |
7440 | example.i:23. Previous declaration of 'foo' | |
7441 | </PRE> | |
7442 | </DIV> | |
7443 | <P> To resolve this error, simply use <TT>%rename</TT> to disambiguate | |
7444 | the declarations. For example:</P> | |
7445 | <DIV class="code"> | |
7446 | <PRE> | |
7447 | %rename(B_foo) B::foo; | |
7448 | ... | |
7449 | namespace A { | |
7450 | void foo(int); | |
7451 | } | |
7452 | namespace B { | |
7453 | void foo(double); // Gets renamed to B_foo | |
7454 | } | |
7455 | </PRE> | |
7456 | </DIV> | |
7457 | <P> Similarly, <TT>%ignore</TT> can be used to ignore declarations.</P> | |
7458 | <P> <TT>using</TT> declarations do not have any effect on the generated | |
7459 | wrapper code. They are ignored by SWIG language modules and they do not | |
7460 | result in any code. However, these declarations<EM> are</EM> used by | |
7461 | the internal type system to track type-names. Therefore, if you have | |
7462 | code like this:</P> | |
7463 | <DIV class="code"> | |
7464 | <PRE> | |
7465 | namespace A { | |
7466 | typedef int Integer; | |
7467 | } | |
7468 | using namespace A; | |
7469 | void foo(Integer x); | |
7470 | </PRE> | |
7471 | </DIV> | |
7472 | <P> SWIG knows that <TT>Integer</TT> is the same as <TT>A::Integer</TT> | |
7473 | which is the same as <TT>int</TT>.</P> | |
7474 | <P> Namespaces may be combined with templates. If necessary, the <TT> | |
7475 | %template</TT> directive can be used to expand a template defined in a | |
7476 | different namespace. For example:</P> | |
7477 | <DIV class="code"> | |
7478 | <PRE> | |
7479 | namespace foo { | |
7480 | template<typename T> T max(T a, T b) { return a > b ? a : b; } | |
7481 | } | |
7482 | ||
7483 | using foo::max; | |
7484 | ||
7485 | %template(maxint) max<int>; // Okay. | |
7486 | %template(maxfloat) foo::max<float>; // Okay (qualified name). | |
7487 | ||
7488 | namespace bar { | |
7489 | using namespace foo; | |
7490 | %template(maxdouble) max<double>; // Okay. | |
7491 | } | |
7492 | </PRE> | |
7493 | </DIV> | |
7494 | <P> The combination of namespaces and other SWIG directives may | |
7495 | introduce subtle scope-related problems. The key thing to keep in mind | |
7496 | is that all SWIG generated wrappers are produced in the<EM> global</EM> | |
7497 | namespace. Symbols from other namespaces are always accessed using | |
7498 | fully qualified names---names are never imported into the global space | |
7499 | unless the interface happens to do so with a <TT>using</TT> | |
7500 | declaration. In almost all cases, SWIG adjusts typenames and symbols to | |
7501 | be fully qualified. However, this is not done in code fragments such as | |
7502 | function bodies, typemaps, exception handlers, and so forth. For | |
7503 | example, consider the following:</P> | |
7504 | <DIV class="code"> | |
7505 | <PRE> | |
7506 | namespace foo { | |
7507 | typedef int Integer; | |
7508 | class bar { | |
7509 | public: | |
7510 | ... | |
7511 | }; | |
7512 | } | |
7513 | ||
7514 | %extend foo::bar { | |
7515 | Integer add(Integer x, Integer y) { | |
7516 | Integer r = x + y; // Error. Integer not defined in this scope | |
7517 | return r; | |
7518 | } | |
7519 | }; | |
7520 | </PRE> | |
7521 | </DIV> | |
7522 | <P> In this case, SWIG correctly resolves the added method parameters | |
7523 | and return type to <TT>foo::Integer</TT>. However, since function | |
7524 | bodies aren't parsed and such code is emitted in the global namespace, | |
7525 | this code produces a compiler error about <TT>Integer</TT>. To fix the | |
7526 | problem, make sure you use fully qualified names. For example:</P> | |
7527 | <DIV class="code"> | |
7528 | <PRE> | |
7529 | %extend foo::bar { | |
7530 | Integer add(Integer x, Integer y) { | |
7531 | foo::Integer r = x + y; // Ok. | |
7532 | return r; | |
7533 | } | |
7534 | }; | |
7535 | </PRE> | |
7536 | </DIV> | |
7537 | <P><B> Note:</B> SWIG does<EM> not</EM> propagate <TT>using</TT> | |
7538 | declarations to the resulting wrapper code. If these declarations | |
7539 | appear in an interface, they should<EM> also</EM> appear in any header | |
7540 | files that might have been included in a <TT>%{ ... %}</TT> section. In | |
7541 | other words, don't insert extra <TT>using</TT> declarations into a SWIG | |
7542 | interface unless they also appear in the underlying C++ code.</P> | |
7543 | <P><B> Note:</B> Code inclusion directives such as <TT>%{ ... %}</TT> or | |
7544 | <TT>%inline %{ ... %}</TT> should not be placed inside a namespace | |
7545 | declaration. The code emitted by these directives will not be enclosed | |
7546 | in a namespace and you may get very strange results. If you need to use | |
7547 | namespaces with these directives, consider the following:</P> | |
7548 | <DIV class="code"> | |
7549 | <PRE> | |
7550 | // Good version | |
7551 | %inline %{ | |
7552 | namespace foo { | |
7553 | void bar(int) { ... } | |
7554 | ... | |
7555 | } | |
7556 | %} | |
7557 | ||
7558 | // Bad version. Emitted code not placed in namespace. | |
7559 | namespace foo { | |
7560 | %inline %{ | |
7561 | void bar(int) { ... } /* I'm bad */ | |
7562 | ... | |
7563 | %} | |
7564 | } | |
7565 | </PRE> | |
7566 | </DIV> | |
7567 | <P><B> Note:</B> When the <TT>%extend</TT> directive is used inside a | |
7568 | namespace, the namespace name is included in the generated functions. | |
7569 | For example, if you have code like this,</P> | |
7570 | <DIV class="code"> | |
7571 | <PRE> | |
7572 | namespace foo { | |
7573 | class bar { | |
7574 | public: | |
7575 | %extend { | |
7576 | int blah(int x); | |
7577 | }; | |
7578 | }; | |
7579 | } | |
7580 | </PRE> | |
7581 | </DIV> | |
7582 | <P> the added method <TT>blah()</TT> is mapped to a function <TT>int | |
7583 | foo_bar_blah(foo::bar *self, int x)</TT>. This function resides in the | |
7584 | global namespace.</P> | |
7585 | <P><B> Note:</B> Although namespaces are flattened in the target | |
7586 | language, the SWIG generated wrapper code observes the same namespace | |
7587 | conventions as used in the input file. Thus, if there are no symbol | |
7588 | conflicts in the input, there will be no conflicts in the generated | |
7589 | code.</P> | |
7590 | <P><B> Note:</B> Namespaces have a subtle effect on the wrapping of | |
7591 | conversion operators. For instance, suppose you had an interface like | |
7592 | this:</P> | |
7593 | <DIV class="code"> | |
7594 | <PRE> | |
7595 | namespace foo { | |
7596 | class bar; | |
7597 | class spam { | |
7598 | public: | |
7599 | ... | |
7600 | operator bar(); // Conversion of spam -> bar | |
7601 | ... | |
7602 | }; | |
7603 | } | |
7604 | </PRE> | |
7605 | </DIV> | |
7606 | <P> To wrap the conversion function, you might be inclined to write | |
7607 | this:</P> | |
7608 | <DIV class="code"> | |
7609 | <PRE> | |
7610 | %rename(tofoo) foo::spam::operator bar(); | |
7611 | </PRE> | |
7612 | </DIV> | |
7613 | <P> The only problem is that it doesn't work. The reason it doesn't work | |
7614 | is that <TT>bar</TT> is not defined in the global scope. Therefore, to | |
7615 | make it work, do this instead:</P> | |
7616 | <DIV class="code"> | |
7617 | <PRE> | |
7618 | %rename(tofoo) foo::spam::operator <B>foo::</B>bar(); | |
7619 | </PRE> | |
7620 | </DIV> | |
7621 | <P><B> Note:</B> The flattening of namespaces is only intended to serve | |
7622 | as a basic namespace implementation. Since namespaces are a new | |
7623 | addition to SWIG, none of the target language modules are currently | |
7624 | programmed with any namespace awareness. In the future, language | |
7625 | modules may or may not provide more advanced namespace support.</P> | |
7626 | <H2><A name="SWIGPlus_exception_specifications"></A>6.20 Exception | |
7627 | specifications</H2> | |
7628 | <P> When C++ programs utilize exceptions, exceptional behavior is | |
7629 | sometimes specified as part of a function or method declaration. For | |
7630 | example:</P> | |
7631 | <DIV class="code"> | |
7632 | <PRE> | |
7633 | class Error { }; | |
7634 | ||
7635 | class Foo { | |
7636 | public: | |
7637 | ... | |
7638 | void blah() throw(Error); | |
7639 | ... | |
7640 | }; | |
7641 | </PRE> | |
7642 | </DIV> | |
7643 | <P> If an exception specification is used, SWIG automatically generates | |
7644 | wrapper code for catching the indicated exception and converting it | |
7645 | into an error in the target language. In certain language modules, | |
7646 | wrapped exception classes themselves can be used to catch errors. For | |
7647 | example, in Python, you can write code like this:</P> | |
7648 | <DIV class="targetlang"> | |
7649 | <PRE> | |
7650 | f = Foo() | |
7651 | try: | |
7652 | f.blah() | |
7653 | except Error,e: | |
7654 | # e is a wrapped instance of "Error" | |
7655 | </PRE> | |
7656 | </DIV> | |
7657 | <P> Obviously, the exact details of how exceptions are handled depend on | |
7658 | the target language module.</P> | |
7659 | <P> Since exception specifications are sometimes only used sparingly, | |
7660 | this alone may not be enough to properly handle C++ exceptions. To do | |
7661 | that, a different set of special SWIG directives are used. Consult the | |
7662 | "<A href="#Customization">Customization features</A>" chapter for | |
7663 | details.</P> | |
7664 | <H2><A name="SWIGPlus_nn33"></A>6.21 Pointers to Members</H2> | |
7665 | <P> Starting with SWIG1.3.7, there is limited parsing support for | |
7666 | pointers to C++ class members. For example:</P> | |
7667 | <DIV class="code"> | |
7668 | <PRE> | |
7669 | double do_op(Object *o, double (Object::*callback)(double,double)); | |
7670 | extern double (Object::*fooptr)(double,double); | |
7671 | %constant double (Object::*FOO)(double,double) = &Object::foo; | |
7672 | </PRE> | |
7673 | </DIV> | |
7674 | <P> Although these kinds of pointers can be parsed and represented by | |
7675 | the SWIG type system, few language modules know how to handle them due | |
7676 | to implementation differences from standard C pointers. Readers are<EM> | |
7677 | strongly</EM> advised to consult an advanced text such as the "The | |
7678 | Annotated C++ Manual" for specific details.</P> | |
7679 | <P> When pointers to members are supported, the pointer value might | |
7680 | appear as a special string like this:</P> | |
7681 | <DIV class="targetlang"> | |
7682 | <PRE> | |
7683 | >>> print example.FOO | |
7684 | _ff0d54a800000000_m_Object__f_double_double__double | |
7685 | >>> | |
7686 | </PRE> | |
7687 | </DIV> | |
7688 | <P> In this case, the hexadecimal digits represent the entire value of | |
7689 | the pointer which is usually the contents of a small C++ structure on | |
7690 | most machines.</P> | |
7691 | <P> SWIG's type-checking mechanism is also more limited when working | |
7692 | with member pointers. Normally SWIG tries to keep track of inheritance | |
7693 | when checking types. However, no such support is currently provided for | |
7694 | member pointers.</P> | |
7695 | <H2><A name="SWIGPlus_nn34"></A>6.22 Smart pointers and operator->()</H2> | |
7696 | <P> In some C++ programs, objects are often encapsulated by | |
7697 | smart-pointers or proxy classes. This is sometimes done to implement | |
7698 | automatic memory management (reference counting) or persistence. | |
7699 | Typically a smart-pointer is defined by a template class where the <TT> | |
7700 | -></TT> operator has been overloaded. This class is then wrapped around | |
7701 | some other class. For example:</P> | |
7702 | <DIV class="code"> | |
7703 | <PRE> | |
7704 | // Smart-pointer class | |
7705 | template<class T> class SmartPtr { | |
7706 | T *pointee; | |
7707 | public: | |
7708 | ... | |
7709 | T *operator->() { | |
7710 | return pointee; | |
7711 | } | |
7712 | ... | |
7713 | }; | |
7714 | ||
7715 | // Ordinary class | |
7716 | class Foo_Impl { | |
7717 | public: | |
7718 | int x; | |
7719 | virtual void bar(); | |
7720 | ... | |
7721 | }; | |
7722 | ||
7723 | // Smart-pointer wrapper | |
7724 | typedef SmartPtr<Foo_Impl> Foo; | |
7725 | ||
7726 | // Create smart pointer Foo | |
7727 | Foo make_Foo() { | |
7728 | return SmartPtr(new Foo_Impl()); | |
7729 | } | |
7730 | ||
7731 | // Do something with smart pointer Foo | |
7732 | void do_something(Foo f) { | |
7733 | printf("x = %d\n", f->x); | |
7734 | f->bar(); | |
7735 | } | |
7736 | </PRE> | |
7737 | </DIV> | |
7738 | <P> A key feature of this approach is that by defining <TT>operator-></TT> | |
7739 | the methods and attributes of the object wrapped by a smart pointer are | |
7740 | transparently accessible. For example, expressions such as these (from | |
7741 | the previous example),</P> | |
7742 | <DIV class="code"> | |
7743 | <PRE> | |
7744 | f->x | |
7745 | f->bar() | |
7746 | </PRE> | |
7747 | </DIV> | |
7748 | <P> are transparently mapped to the following</P> | |
7749 | <DIV class="code"> | |
7750 | <PRE> | |
7751 | (f.operator->())->x; | |
7752 | (f.operator->())->bar(); | |
7753 | </PRE> | |
7754 | </DIV> | |
7755 | <P> When generating wrappers, SWIG tries to emulate this functionality | |
7756 | to the extent that it is possible. To do this, whenever <TT> | |
7757 | operator->()</TT> is encountered in a class, SWIG looks at its returned | |
7758 | type and uses it to generate wrappers for accessing attributes of the | |
7759 | underlying object. For example, wrapping the above code produces | |
7760 | wrappers like this:</P> | |
7761 | <DIV class="code"> | |
7762 | <PRE> | |
7763 | int Foo_x_get(Foo *f) { | |
7764 | return (*f)->x; | |
7765 | } | |
7766 | void Foo_x_set(Foo *f, int value) { | |
7767 | (*f)->x = value; | |
7768 | } | |
7769 | void Foo_bar(Foo *f) { | |
7770 | (*f)->bar(); | |
7771 | } | |
7772 | </PRE> | |
7773 | </DIV> | |
7774 | <P> These wrappers take a smart-pointer instance as an argument, but | |
7775 | dereference it in a way to gain access to the object returned by <TT> | |
7776 | operator->()</TT>. You should carefully compare these wrappers to those | |
7777 | in the first part of this chapter (they are slightly different).</P> | |
7778 | <P> The end result is that access looks very similar to C++. For | |
7779 | example, you could do this in Python:</P> | |
7780 | <DIV class="targetlang"> | |
7781 | <PRE> | |
7782 | >>> f = make_Foo() | |
7783 | >>> print f.x | |
7784 | 0 | |
7785 | >>> f.bar() | |
7786 | >>> | |
7787 | </PRE> | |
7788 | </DIV> | |
7789 | <P> When generating wrappers through a smart-pointer, SWIG tries to | |
7790 | generate wrappers for all methods and attributes that might be | |
7791 | accessible through <TT>operator->()</TT>. This includes any methods | |
7792 | that might be accessible through inheritance. However, there are a | |
7793 | number of restrictions:</P> | |
7794 | <UL> | |
7795 | <LI>Member variables and methods are wrapped through a smart pointer. | |
7796 | Enumerations, constructors, and destructors are not wrapped.</LI> | |
7797 | <LI> | |
7798 | <P>If the smart-pointer class and the underlying object both define a | |
7799 | method or variable of the same name, then the smart-pointer version has | |
7800 | precedence. For example, if you have this code</P> | |
7801 | <DIV class="code"> | |
7802 | <PRE> | |
7803 | class Foo { | |
7804 | public: | |
7805 | int x; | |
7806 | }; | |
7807 | ||
7808 | class Bar { | |
7809 | public: | |
7810 | int x; | |
7811 | Foo *operator->(); | |
7812 | }; | |
7813 | </PRE> | |
7814 | </DIV> | |
7815 | <P> then the wrapper for <TT>Bar::x</TT> accesses the <TT>x</TT> defined | |
7816 | in <TT>Bar</TT>, and not the <TT>x</TT> defined in <TT>Foo</TT>.</P> | |
7817 | </LI> | |
7818 | </UL> | |
7819 | <P> If your intent is to only expose the smart-pointer class in the | |
7820 | interface, it is not necessary to wrap both the smart-pointer class and | |
7821 | the class for the underlying object. However, you must still tell SWIG | |
7822 | about both classes if you want the technique described in this section | |
7823 | to work. To only generate wrappers for the smart-pointer class, you can | |
7824 | use the %ignore directive. For example:</P> | |
7825 | <DIV class="code"> | |
7826 | <PRE> | |
7827 | %ignore Foo; | |
7828 | class Foo { // Ignored | |
7829 | }; | |
7830 | ||
7831 | class Bar { | |
7832 | public: | |
7833 | Foo *operator->(); | |
7834 | ... | |
7835 | }; | |
7836 | </PRE> | |
7837 | </DIV> | |
7838 | <P> Alternatively, you can import the definition of <TT>Foo</TT> from a | |
7839 | separate file using <TT>%import</TT>.</P> | |
7840 | <P><B> Note:</B> When a class defines <TT>operator->()</TT>, the | |
7841 | operator itself is wrapped as a method <TT>__deref__()</TT>. For | |
7842 | example:</P> | |
7843 | <DIV class="targetlang"> | |
7844 | <PRE> | |
7845 | f = Foo() # Smart-pointer | |
7846 | p = f.__deref__() # Raw pointer from operator-> | |
7847 | </PRE> | |
7848 | </DIV> | |
7849 | <P><B> Note:</B> To disable the smart-pointer behavior, use <TT>%ignore</TT> | |
7850 | to ignore <TT>operator->()</TT>. For example:</P> | |
7851 | <DIV class="code"> | |
7852 | <PRE> | |
7853 | %ignore Bar::operator->; | |
7854 | </PRE> | |
7855 | </DIV> | |
7856 | <P><B> Note:</B> Smart pointer support was first added in SWIG-1.3.14.</P> | |
7857 | <H2><A name="SWIGPlus_nn35"></A>6.23 Using declarations and inheritance</H2> | |
7858 | <P> <TT>using</TT> declarations are sometimes used to adjust access to | |
7859 | members of base classes. For example:</P> | |
7860 | <DIV class="code"> | |
7861 | <PRE> | |
7862 | class Foo { | |
7863 | public: | |
7864 | int blah(int x); | |
7865 | }; | |
7866 | ||
7867 | class Bar { | |
7868 | public: | |
7869 | double blah(double x); | |
7870 | }; | |
7871 | ||
7872 | class FooBar : public Foo, public Bar { | |
7873 | public: | |
7874 | using Foo::blah; | |
7875 | using Bar::blah; | |
7876 | char *blah(const char *x); | |
7877 | }; | |
7878 | </PRE> | |
7879 | </DIV> | |
7880 | <P> In this example, the <TT>using</TT> declarations make different | |
7881 | versions of the overloaded <TT>blah()</TT> method accessible from the | |
7882 | derived class. For example:</P> | |
7883 | <DIV class="code"> | |
7884 | <PRE> | |
7885 | FooBar *f; | |
7886 | f->blah(3); // Ok. Invokes Foo::blah(int) | |
7887 | f->blah(3.5); // Ok. Invokes Bar::blah(double) | |
7888 | f->blah("hello"); // Ok. Invokes FooBar::blah(const char *); | |
7889 | </PRE> | |
7890 | </DIV> | |
7891 | <P> SWIG emulates the same functionality when creating wrappers. For | |
7892 | example, if you wrap this code in Python, the module works just like | |
7893 | you would expect:</P> | |
7894 | <DIV class="targetlang"> | |
7895 | <PRE> | |
7896 | >>> import example | |
7897 | >>> f = example.FooBar() | |
7898 | >>> f.blah(3) | |
7899 | >>> f.blah(3.5) | |
7900 | >>> f.blah("hello") | |
7901 | </PRE> | |
7902 | </DIV> | |
7903 | <P> <TT>using</TT> declarations can also be used to change access when | |
7904 | applicable. For example:</P> | |
7905 | <DIV class="code"> | |
7906 | <PRE> | |
7907 | class Foo { | |
7908 | protected: | |
7909 | int x; | |
7910 | int blah(int x); | |
7911 | }; | |
7912 | ||
7913 | class Bar : public Foo { | |
7914 | public: | |
7915 | using Foo::x; // Make x public | |
7916 | using Foo::blah; // Make blah public | |
7917 | }; | |
7918 | </PRE> | |
7919 | </DIV> | |
7920 | <P> This also works in SWIG---the exposed declarations will be wrapped | |
7921 | normally.</P> | |
7922 | <P> When <TT>using</TT> declarations are used as shown in these | |
7923 | examples, declarations from the base classes are copied into the | |
7924 | derived class and wrapped normally. When copied, the declarations | |
7925 | retain any properties that might have been attached using <TT>%rename</TT> | |
7926 | , <TT>%ignore</TT>, or <TT>%feature</TT>. Thus, if a method is ignored | |
7927 | in a base class, it will also be ignored by a <TT>using</TT> | |
7928 | declaration.</P> | |
7929 | <P> Because a <TT>using</TT> declaration does not provide fine-grained | |
7930 | control over the declarations that get imported, it may be difficult to | |
7931 | manage such declarations in applications that make heavy use of SWIG | |
7932 | customization features. If you can't get <TT>using</TT> to work | |
7933 | correctly, you can always change the interface to the following:</P> | |
7934 | <DIV class="code"> | |
7935 | <PRE> | |
7936 | ||
7937 | class FooBar : public Foo, public Bar { | |
7938 | public: | |
7939 | #ifndef SWIG | |
7940 | using Foo::blah; | |
7941 | using Bar::blah; | |
7942 | #else | |
7943 | int blah(int x); // explicitly tell SWIG about other declarations | |
7944 | double blah(double x); | |
7945 | #endif | |
7946 | ||
7947 | char *blah(const char *x); | |
7948 | }; | |
7949 | </PRE> | |
7950 | </DIV> | |
7951 | <P><B> Notes:</B></P> | |
7952 | <UL> | |
7953 | <LI> | |
7954 | <P>If a derived class redefines a method defined in a base class, then a | |
7955 | <TT>using</TT> declaration won't cause a conflict. For example:</P> | |
7956 | <DIV class="code"> | |
7957 | <PRE> | |
7958 | class Foo { | |
7959 | public: | |
7960 | int blah(int ); | |
7961 | double blah(double); | |
7962 | }; | |
7963 | ||
7964 | class Bar : public Foo { | |
7965 | public: | |
7966 | using Foo::blah; // Only imports blah(double); | |
7967 | int blah(int); | |
7968 | }; | |
7969 | </PRE> | |
7970 | </DIV></LI> | |
7971 | <LI> | |
7972 | <P>Resolving ambiguity in overloading may prevent declarations from | |
7973 | being imported by <TT>using</TT>. For example:</P> | |
7974 | <DIV class="code"> | |
7975 | <PRE> | |
7976 | %rename(blah_long) Foo::blah(long); | |
7977 | class Foo { | |
7978 | public: | |
7979 | int blah(int); | |
7980 | long blah(long); // Renamed to blah_long | |
7981 | }; | |
7982 | ||
7983 | class Bar : public Foo { | |
7984 | public: | |
7985 | using Foo::blah; // Only imports blah(int) | |
7986 | double blah(double x); | |
7987 | }; | |
7988 | </PRE> | |
7989 | </DIV></LI> | |
7990 | </UL> | |
7991 | <H2><A name="SWIGPlus_nn36"></A>6.24 Partial class definitions</H2> | |
7992 | <P> Since SWIG is still limited in its support of C++, it may be | |
7993 | necessary to use partial class information in an interface file. | |
7994 | However, since SWIG does not need the entire class specification to | |
7995 | work, conditional compilation can be used to comment out problematic | |
7996 | parts. For example, if you had a nested class definition, you might do | |
7997 | this:</P> | |
7998 | <DIV class="code"> | |
7999 | <PRE> | |
8000 | class Foo { | |
8001 | public: | |
8002 | #ifndef SWIG | |
8003 | class Bar { | |
8004 | public: | |
8005 | ... | |
8006 | }; | |
8007 | #endif | |
8008 | Foo(); | |
8009 | ~Foo(); | |
8010 | ... | |
8011 | }; | |
8012 | </PRE> | |
8013 | </DIV> | |
8014 | <P> Also, as a rule of thumb, SWIG should not be used on raw C++ source | |
8015 | files.</P> | |
8016 | <H2><A name="SWIGPlus_nn37"></A>6.25 A brief rant about | |
8017 | const-correctness</H2> | |
8018 | <P> A common issue when working with C++ programs is dealing with all | |
8019 | possible ways in which the <TT>const</TT> qualifier (or lack thereof) | |
8020 | will break your program, all programs linked against your program, and | |
8021 | all programs linked against those programs.</P> | |
8022 | <P> Although SWIG knows how to correctly deal with <TT>const</TT> in its | |
8023 | internal type system and it knows how to generate wrappers that are | |
8024 | free of const-related warnings, SWIG does not make any attempt to | |
8025 | preserve const-correctness in the target language. Thus, it is possible | |
8026 | to pass <TT>const</TT> qualified objects to non-const methods and | |
8027 | functions. For example, consider the following code in C++:</P> | |
8028 | <DIV class="code"> | |
8029 | <PRE> | |
8030 | const Object * foo(); | |
8031 | void bar(Object *); | |
8032 | ||
8033 | ... | |
8034 | // C++ code | |
8035 | void blah() { | |
8036 | bar(foo()); // Error: bar discards const | |
8037 | }; | |
8038 | </PRE> | |
8039 | </DIV> | |
8040 | <P> Now, consider the behavior when wrapped into a Python module:</P> | |
8041 | <DIV class="targetlang"> | |
8042 | <PRE> | |
8043 | >>> bar(foo()) # Okay | |
8044 | >>> | |
8045 | </PRE> | |
8046 | </DIV> | |
8047 | <P> Although this is clearly a violation of the C++ type-system, fixing | |
8048 | the problem doesn't seem to be worth the added implementation | |
8049 | complexity that would be required to support it in the SWIG run-time | |
8050 | type system. There are no plans to change this in future releases | |
8051 | (although we'll never rule anything out entirely).</P> | |
8052 | <P> The bottom line is that this particular issue does not appear to be | |
8053 | a problem for most SWIG projects. Of course, you might want to consider | |
8054 | using another tool if maintaining constness is the most important part | |
8055 | of your project.</P> | |
8056 | <H2><A name="SWIGPlus_nn38"></A>6.26 Proxy classes</H2> | |
8057 | <P> In order to provide a more natural API, SWIG's target languages wrap | |
8058 | C++ classes with special proxy classes. These proxy classes are | |
8059 | typically implemented in the target language itself. For example, if | |
8060 | you're building a Python module, each C++ class is wrapped by a Python | |
8061 | class. Or if you're building a Java module, each C++ class is wrapped | |
8062 | by a Java class.</P> | |
8063 | <H3><A name="SWIGPlus_nn39"></A>6.26.1 Construction of proxy classes</H3> | |
8064 | <P> Proxy classes are always constructed as an extra layer of wrapping | |
8065 | that uses the low-level accessor functions described in the previous | |
8066 | section. To illustrate, suppose you had a C++ class like this:</P> | |
8067 | <DIV class="code"> | |
8068 | <PRE> | |
8069 | class Foo { | |
8070 | public: | |
8071 | Foo(); | |
8072 | ~Foo(); | |
8073 | int bar(int x); | |
8074 | int x; | |
8075 | }; | |
8076 | </PRE> | |
8077 | </DIV> | |
8078 | <P> Using C++ as pseudocode, a proxy class looks something like this:</P> | |
8079 | <DIV class="code"> | |
8080 | <PRE> | |
8081 | class FooProxy { | |
8082 | private: | |
8083 | Foo *self; | |
8084 | public: | |
8085 | FooProxy() { | |
8086 | self = new_Foo(); | |
8087 | } | |
8088 | ~FooProxy() { | |
8089 | delete_Foo(self); | |
8090 | } | |
8091 | int bar(int x) { | |
8092 | return Foo_bar(self,x); | |
8093 | } | |
8094 | int x_get() { | |
8095 | return Foo_x_get(self); | |
8096 | } | |
8097 | void x_set(int x) { | |
8098 | Foo_x_set(self,x); | |
8099 | } | |
8100 | }; | |
8101 | </PRE> | |
8102 | </DIV> | |
8103 | <P> Of course, always keep in mind that the real proxy class is written | |
8104 | in the target language. For example, in Python, the proxy might look | |
8105 | roughly like this:</P> | |
8106 | <DIV class="targetlang"> | |
8107 | <PRE> | |
8108 | class Foo: | |
8109 | def __init__(self): | |
8110 | self.this = new_Foo() | |
8111 | def __del__(self): | |
8112 | delete_Foo(self.this) | |
8113 | def bar(self,x): | |
8114 | return Foo_bar(self.this,x) | |
8115 | def __getattr__(self,name): | |
8116 | if name == 'x': | |
8117 | return Foo_x_get(self.this) | |
8118 | ... | |
8119 | def __setattr__(self,name,value): | |
8120 | if name == 'x': | |
8121 | Foo_x_set(self.this,value) | |
8122 | ... | |
8123 | </PRE> | |
8124 | </DIV> | |
8125 | <P> Again, it's important to emphasize that the low-level accessor | |
8126 | functions are always used to construct the proxy classes.</P> | |
8127 | <P> Whenever possible, proxies try to take advantage of language | |
8128 | features that are similar to C++. This might include operator | |
8129 | overloading, exception handling, and other features.</P> | |
8130 | <H3><A name="SWIGPlus_nn40"></A>6.26.2 Resource management in proxies</H3> | |
8131 | <P> A major issue with proxies concerns the memory management of wrapped | |
8132 | objects. Consider the following C++ code:</P> | |
8133 | <DIV class="code"> | |
8134 | <PRE> | |
8135 | class Foo { | |
8136 | public: | |
8137 | Foo(); | |
8138 | ~Foo(); | |
8139 | int bar(int x); | |
8140 | int x; | |
8141 | }; | |
8142 | ||
8143 | class Spam { | |
8144 | public: | |
8145 | Foo *value; | |
8146 | ... | |
8147 | }; | |
8148 | </PRE> | |
8149 | </DIV> | |
8150 | <P> Now, consider some script code that uses these classes:</P> | |
8151 | <DIV class="targetlang"> | |
8152 | <PRE> | |
8153 | f = Foo() # Creates a new Foo | |
8154 | s = Spam() # Creates a new Spam | |
8155 | s.value = f # Stores a reference to f inside s | |
8156 | g = s.value # Returns stored reference | |
8157 | g = 4 # Reassign g to some other value | |
8158 | del f # Destroy f | |
8159 | </PRE> | |
8160 | </DIV> | |
8161 | <P> Now, ponder the resulting memory management issues. When objects are | |
8162 | created in the script, the objects are wrapped by newly created proxy | |
8163 | classes. That is, there is both a new proxy class instance and a new | |
8164 | instance of the underlying C++ class. In this example, both <TT>f</TT> | |
8165 | and <TT>s</TT> are created in this way. However, the statement <TT> | |
8166 | s.value</TT> is rather curious---when executed, a pointer to <TT>f</TT> | |
8167 | is stored inside another object. This means that the scripting proxy | |
8168 | class<EM> AND</EM> another C++ class share a reference to the same | |
8169 | object. To make matters even more interesting, consider the statement <TT> | |
8170 | g = s.value</TT>. When executed, this creates a new proxy class <TT>g</TT> | |
8171 | that provides a wrapper around the C++ object stored in <TT>s.value</TT> | |
8172 | . In general, there is no way to know where this object came from---it | |
8173 | could have been created by the script, but it could also have been | |
8174 | generated internally. In this particular example, the assignment of <TT> | |
8175 | g</TT> results in a second proxy class for <TT>f</TT>. In other words, a | |
8176 | reference to <TT>f</TT> is now shared by two proxy classes<EM> and</EM> | |
8177 | a C++ class.</P> | |
8178 | <P> Finally, consider what happens when objects are destroyed. In the | |
8179 | statement, <TT>g=4</TT>, the variable <TT>g</TT> is reassigned. In many | |
8180 | languages, this makes the old value of <TT>g</TT> available for garbage | |
8181 | collection. Therefore, this causes one of the proxy classes to be | |
8182 | destroyed. Later on, the statement <TT>del f</TT> destroys the other | |
8183 | proxy class. Of course, there is still a reference to the original | |
8184 | object stored inside another C++ object. What happens to it? Is it the | |
8185 | object still valid?</P> | |
8186 | <P> To deal with memory management problems, proxy classes always | |
8187 | provide an API for controlling ownership. In C++ pseudocode, ownership | |
8188 | control might look roughly like this:</P> | |
8189 | <DIV class="code"> | |
8190 | <PRE> | |
8191 | class FooProxy { | |
8192 | public: | |
8193 | Foo *self; | |
8194 | int thisown; | |
8195 | ||
8196 | FooProxy() { | |
8197 | self = new_Foo(); | |
8198 | thisown = 1; // Newly created object | |
8199 | } | |
8200 | ~FooProxy() { | |
8201 | if (thisown) delete_Foo(self); | |
8202 | } | |
8203 | ... | |
8204 | // Ownership control API | |
8205 | void disown() { | |
8206 | thisown = 0; | |
8207 | } | |
8208 | void acquire() { | |
8209 | thisown = 1; | |
8210 | } | |
8211 | }; | |
8212 | ||
8213 | class FooPtrProxy: public FooProxy { | |
8214 | public: | |
8215 | FooPtrProxy(Foo *s) { | |
8216 | self = s; | |
8217 | thisown = 0; | |
8218 | } | |
8219 | }; | |
8220 | ||
8221 | class SpamProxy { | |
8222 | ... | |
8223 | FooProxy *value_get() { | |
8224 | return FooPtrProxy(Spam_value_get(self)); | |
8225 | } | |
8226 | void value_set(FooProxy *v) { | |
8227 | Spam_value_set(self,v->self); | |
8228 | v->disown(); | |
8229 | } | |
8230 | ... | |
8231 | }; | |
8232 | </PRE> | |
8233 | </DIV> | |
8234 | <P> Looking at this code, there are a few central features:</P> | |
8235 | <UL> | |
8236 | <LI>Each proxy class keeps an extra flag to indicate ownership. C++ | |
8237 | objects are only destroyed if the ownership flag is set.</LI> | |
8238 | <LI>When new objects are created in the target language, the ownership | |
8239 | flag is set.</LI> | |
8240 | <LI>When a reference to an internal C++ object is returned, it is | |
8241 | wrapped by a proxy class, but the proxy class does not have ownership.</LI> | |
8242 | <LI>In certain cases, ownership is adjusted. For instance, when a value | |
8243 | is assigned to the member of a class, ownership is lost.</LI> | |
8244 | <LI>Manual ownership control is provided by special <TT>disown()</TT> | |
8245 | and <TT>acquire()</TT> methods.</LI> | |
8246 | </UL> | |
8247 | <P> Given the tricky nature of C++ memory management, it is impossible | |
8248 | for proxy classes to automatically handle every possible memory | |
8249 | management problem. However, proxies do provide a mechanism for manual | |
8250 | control that can be used (if necessary) to address some of the more | |
8251 | tricky memory management problems.</P> | |
8252 | <H3><A name="SWIGPlus_nn41"></A>6.26.3 Language specific details</H3> | |
8253 | <P> Language specific details on proxy classes are contained in the | |
8254 | chapters describing each target language. This chapter has merely | |
8255 | introduced the topic in a very general way.</P> | |
8256 | <H2><A name="SWIGPlus_nn42"></A>6.27 Where to go for more information</H2> | |
8257 | <P> If you're wrapping serious C++ code, you might want to pick up a | |
8258 | copy of "The Annotated C++ Reference Manual" by Ellis and Stroustrup. | |
8259 | This is the reference document we use to guide a lot of SWIG's C++ | |
8260 | support.</P> | |
8261 | ||
8262 | <!-- LocalWords: destructors Enums Namespaces const SWIG's STL OO adaptor tcl | |
8263 | --> | |
8264 | ||
8265 | <!-- LocalWords: debuggable cxx OBJS Wiki accessor nodefault makedefault | |
8266 | --> | |
8267 | ||
8268 | <!-- LocalWords: notabstract CopyFoo | |
8269 | --> | |
8270 | <HR NOSHADE> | |
8271 | <H1><A name="Preprocessor"></A>7 Preprocessing</H1> | |
8272 | ||
8273 | <!-- INDEX --> | |
8274 | <DIV class="sectiontoc"> | |
8275 | <UL> | |
8276 | <LI><A href="#Preprocessor_nn2">File inclusion</A></LI> | |
8277 | <LI><A href="#Preprocessor_nn3">File imports</A></LI> | |
8278 | <LI><A href="#Preprocessor_nn4">Conditional Compilation</A></LI> | |
8279 | <LI><A href="#Preprocessor_nn5">Macro Expansion</A></LI> | |
8280 | <LI><A href="#Preprocessor_nn6">SWIG Macros</A></LI> | |
8281 | <LI><A href="#Preprocessor_nn7">C99 and GNU Extensions</A></LI> | |
8282 | <LI><A href="#Preprocessor_nn8">Preprocessing and %{ ... %} blocks</A></LI> | |
8283 | <LI><A href="#Preprocessor_nn9">Preprocessing and { ... }</A></LI> | |
8284 | <LI><A href="#Preprocessor_nn10">Viewing preprocessor output</A></LI> | |
8285 | </UL> | |
8286 | </DIV> | |
8287 | <!-- INDEX --> | |
8288 | <P> SWIG includes its own enhanced version of the C preprocessor. The | |
8289 | preprocessor supports the standard preprocessor directives and macro | |
8290 | expansion rules. However, a number of modifications and enhancements | |
8291 | have been made. This chapter describes some of these modifications.</P> | |
8292 | <H2><A name="Preprocessor_nn2"></A>7.1 File inclusion</H2> | |
8293 | <P> To include another file into a SWIG interface, use the <TT>%include</TT> | |
8294 | directive like this:</P> | |
8295 | <DIV class="code"> | |
8296 | <PRE> | |
8297 | %include "pointer.i" | |
8298 | </PRE> | |
8299 | </DIV> | |
8300 | <P> Unlike, <TT>#include</TT>, <TT>%include</TT> includes each file once | |
8301 | (and will not reload the file on subsequent <TT>%include</TT> | |
8302 | declarations). Therefore, it is not necessary to use include-guards in | |
8303 | SWIG interfaces.</P> | |
8304 | <P> By default, the <TT>#include</TT> is ignored unless you run SWIG | |
8305 | with the <TT>-includeall</TT> option. The reason for ignoring | |
8306 | traditional includes is that you often don't want SWIG to try and wrap | |
8307 | everything included in standard header system headers and auxilliary | |
8308 | files.</P> | |
8309 | <H2><A name="Preprocessor_nn3"></A>7.2 File imports</H2> | |
8310 | <P> SWIG provides another file inclusion directive with the <TT>%import</TT> | |
8311 | directive. For example:</P> | |
8312 | <DIV class="code"> | |
8313 | <PRE> | |
8314 | %import "foo.i" | |
8315 | </PRE> | |
8316 | </DIV> | |
8317 | <P> The purpose of <TT>%import</TT> is to collect certain information | |
8318 | from another SWIG interface file or a header file without actually | |
8319 | generating any wrapper code. Such information generally includes type | |
8320 | declarations (e.g., <TT>typedef</TT>) as well as C++ classes that might | |
8321 | be used as base-classes for class declarations in the interface. The | |
8322 | use of <TT>%import</TT> is also important when SWIG is used to generate | |
8323 | extensions as a collection of related modules. This is an advanced | |
8324 | topic and is described in a later chapter.</P> | |
8325 | <P> The <TT>-importall</TT> directive tells SWIG to follow all <TT> | |
8326 | #include</TT> statements as imports. This might be useful if you want to | |
8327 | extract type definitions from system header files without generating | |
8328 | any wrappers.</P> | |
8329 | <H2><A name="Preprocessor_nn4"></A>7.3 Conditional Compilation</H2> | |
8330 | <P> SWIG fully supports the use of <TT>#if</TT>, <TT>#ifdef</TT>, <TT> | |
8331 | #ifndef</TT>, <TT>#else</TT>, <TT>#endif</TT> to conditionally include | |
8332 | parts of an interface. The following symbols are predefined by SWIG | |
8333 | when it is parsing the interface:</P> | |
8334 | <DIV class="code"> | |
8335 | <PRE> | |
8336 | SWIG Always defined when SWIG is processing a file | |
8337 | SWIGIMPORTED Defined when SWIG is importing a file with <TT>%import</TT> | |
8338 | SWIGMAC Defined when running SWIG on the Macintosh | |
8339 | SWIGWIN Defined when running SWIG under Windows | |
8340 | SWIG_VERSION Hexadecimal number containing SWIG version, | |
8341 | such as 0x010311 (corresponding to SWIG-1.3.11). | |
8342 | ||
8343 | SWIGCHICKEN Defined when using CHICKEN | |
8344 | SWIGCSHARP Defined when using C# | |
8345 | SWIGGUILE Defined when using Guile | |
8346 | SWIGJAVA Defined when using Java | |
8347 | SWIGMZSCHEME Defined when using Mzscheme | |
8348 | SWIGOCAML Defined when using Ocaml | |
8349 | SWIGPERL Defined when using Perl | |
8350 | SWIGPERL5 Defined when using Perl5 | |
8351 | SWIGPHP Defined when using PHP | |
8352 | SWIGPHP4 Defined when using PHP4 | |
8353 | SWIGPYTHON Defined when using Python | |
8354 | SWIGRUBY Defined when using Ruby | |
8355 | SWIGSEXP Defined when using S-expressions | |
8356 | SWIGTCL Defined when using Tcl | |
8357 | SWIGTCL8 Defined when using Tcl8.0 | |
8358 | SWIGXML Defined when using XML | |
8359 | </PRE> | |
8360 | </DIV> | |
8361 | <P> In addition, SWIG defines the following set of standard C/C++ | |
8362 | macros:</P> | |
8363 | <DIV class="code"> | |
8364 | <PRE> | |
8365 | __LINE__ Current line number | |
8366 | __FILE__ Current file name | |
8367 | __STDC__ Defined to indicate ANSI C | |
8368 | __cplusplus Defined when -c++ option used | |
8369 | </PRE> | |
8370 | </DIV> | |
8371 | <P> Interface files can look at these symbols as necessary to change the | |
8372 | way in which an interface is generated or to mix SWIG directives with C | |
8373 | code. These symbols are also defined within the C code generated by | |
8374 | SWIG (except for the symbol `<TT>SWIG</TT>' which is only defined | |
8375 | within the SWIG compiler).</P> | |
8376 | <H2><A name="Preprocessor_nn5"></A>7.4 Macro Expansion</H2> | |
8377 | <P> Traditional preprocessor macros can be used in SWIG interfaces. Be | |
8378 | aware that the <TT>#define</TT> statement is also used to try and | |
8379 | detect constants. Therefore, if you have something like this in your | |
8380 | file,</P> | |
8381 | <DIV class="code"> | |
8382 | <PRE> | |
8383 | #ifndef _FOO_H 1 | |
8384 | #define _FOO_H 1 | |
8385 | ... | |
8386 | #endif | |
8387 | </PRE> | |
8388 | </DIV> | |
8389 | <P> you may get some extra constants such as <TT>_FOO_H</TT> showing up | |
8390 | in the scripting interface.</P> | |
8391 | <P> More complex macros can be defined in the standard way. For example:</P> | |
8392 | <DIV class="code"> | |
8393 | <PRE> | |
8394 | #define EXTERN extern | |
8395 | #ifdef __STDC__ | |
8396 | #define _ANSI(args) (args) | |
8397 | #else | |
8398 | #define _ANSI(args) () | |
8399 | #endif | |
8400 | </PRE> | |
8401 | </DIV> | |
8402 | <P> The following operators can appear in macro definitions:</P> | |
8403 | <UL> | |
8404 | <LI><TT>#x</TT> | |
8405 | <BR> Converts macro argument <TT>x</TT> to a string surrounded by double | |
8406 | quotes ("x").</LI> | |
8407 | <LI><TT>x ## y</TT> | |
8408 | <BR> Concatenates x and y together to form <TT>xy</TT>.</LI> | |
8409 | <LI><TT>`x`</TT> | |
8410 | <BR> If <TT>x</TT> is a string surrounded by double quotes, do nothing. | |
8411 | Otherwise, turn into a string like <TT>#x</TT>. This is a non-standard | |
8412 | SWIG extension.</LI> | |
8413 | </UL> | |
8414 | <H2><A name="Preprocessor_nn6"></A>7.5 SWIG Macros</H2> | |
8415 | <P> SWIG provides an enhanced macro capability with the <TT>%define</TT> | |
8416 | and <TT>%enddef</TT> directives. For example:</P> | |
8417 | <DIV class="code"> | |
8418 | <PRE> | |
8419 | %define ARRAYHELPER(type,name) | |
8420 | %inline %{ | |
8421 | type *new_ ## name (int nitems) { | |
8422 | return (type *) malloc(sizeof(type)*nitems); | |
8423 | } | |
8424 | void delete_ ## name(type *t) { | |
8425 | free(t); | |
8426 | } | |
8427 | type name ## _get(type *t, int index) { | |
8428 | return t[index]; | |
8429 | } | |
8430 | void name ## _set(type *t, int index, type val) { | |
8431 | t[index] = val; | |
8432 | } | |
8433 | %} | |
8434 | %enddef | |
8435 | ||
8436 | ARRAYHELPER(int, IntArray) | |
8437 | ARRAYHELPER(double, DoubleArray) | |
8438 | </PRE> | |
8439 | </DIV> | |
8440 | <P> The primary purpose of <TT>%define</TT> is to define large macros of | |
8441 | code. Unlike normal C preprocessor macros, it is not necessary to | |
8442 | terminate each line with a continuation character (\)--the macro | |
8443 | definition extends to the first occurrence of <TT>%enddef</TT>. | |
8444 | Furthermore, when such macros are expanded, they are reparsed through | |
8445 | the C preprocessor. Thus, SWIG macros can contain all other | |
8446 | preprocessor directives except for nested <TT>%define</TT> statements.</P> | |
8447 | <P> The SWIG macro capability is a very quick and easy way to generate | |
8448 | large amounts of code. In fact, many of SWIG's advanced features and | |
8449 | libraries are built using this mechanism (such as C++ template | |
8450 | support).</P> | |
8451 | <H2><A name="Preprocessor_nn7"></A>7.6 C99 and GNU Extensions</H2> | |
8452 | <P> SWIG-1.3.12 and newer releases support variadic preprocessor macros. | |
8453 | For example:</P> | |
8454 | <DIV class="code"> | |
8455 | <PRE> | |
8456 | #define DEBUGF(fmt,...) fprintf(stderr,fmt,__VA_ARGS__) | |
8457 | </PRE> | |
8458 | </DIV> | |
8459 | <P> When used, any extra arguments to <TT>...</TT> are placed into the | |
8460 | special variable <TT>__VA_ARGS__</TT>. This also works with special | |
8461 | SWIG macros defined using <TT>%define</TT>.</P> | |
8462 | <P> SWIG allows a variable number of arguments to be empty. However, | |
8463 | this often results in an extra comma (,) and syntax error in the | |
8464 | resulting expansion. For example:</P> | |
8465 | <DIV class="code"> | |
8466 | <PRE> | |
8467 | DEBUGF("hello"); --> fprintf(stderr,"hello",); | |
8468 | </PRE> | |
8469 | </DIV> | |
8470 | <P> To get rid of the extra comma, use <TT>##</TT> like this:</P> | |
8471 | <DIV class="code"> | |
8472 | <PRE> | |
8473 | #define DEBUGF(fmt,...) fprintf(stderr,fmt, ##__VA_ARGS__) | |
8474 | </PRE> | |
8475 | </DIV> | |
8476 | <P> SWIG also supports GNU-style variadic macros. For example:</P> | |
8477 | <DIV class="code"> | |
8478 | <PRE> | |
8479 | #define DEBUGF(fmt, args...) fprintf(stdout,fmt,args) | |
8480 | </PRE> | |
8481 | </DIV> | |
8482 | <P><B> Comment:</B> It's not entirely clear how variadic macros might be | |
8483 | useful to interface building. However, they are used internally to | |
8484 | implement a number of SWIG directives and are provided to make SWIG | |
8485 | more compatible with C99 code.</P> | |
8486 | <H2><A name="Preprocessor_nn8"></A>7.7 Preprocessing and %{ ... %} | |
8487 | blocks</H2> | |
8488 | <P> The SWIG preprocessor does not process any text enclosed in a code | |
8489 | block %{ ... %}. Therefore, if you write code like this,</P> | |
8490 | <DIV class="code"> | |
8491 | <PRE> | |
8492 | %{ | |
8493 | #ifdef NEED_BLAH | |
8494 | int blah() { | |
8495 | ... | |
8496 | } | |
8497 | #endif | |
8498 | %} | |
8499 | </PRE> | |
8500 | </DIV> | |
8501 | <P> the contents of the <TT>%{ ... %}</TT> block are copied without | |
8502 | modification to the output (including all preprocessor directives).</P> | |
8503 | <H2><A name="Preprocessor_nn9"></A>7.8 Preprocessing and { ... }</H2> | |
8504 | <P> SWIG always runs the preprocessor on text appearing inside <TT>{ ... | |
8505 | }</TT>. However, sometimes it is desirable to make a preprocessor | |
8506 | directive pass through to the output file. For example:</P> | |
8507 | <DIV class="code"> | |
8508 | <PRE> | |
8509 | %extend Foo { | |
8510 | void bar() { | |
8511 | #ifdef DEBUG | |
8512 | printf("I'm in bar\n"); | |
8513 | #endif | |
8514 | } | |
8515 | } | |
8516 | </PRE> | |
8517 | </DIV> | |
8518 | <P> By default, SWIG will interpret the <TT>#ifdef DEBUG</TT> statement. | |
8519 | However, if you really wanted that code to actually go into the wrapper | |
8520 | file, prefix the preprocessor directives with <TT>%</TT> like this:</P> | |
8521 | <DIV class="code"> | |
8522 | <PRE> | |
8523 | %extend Foo { | |
8524 | void bar() { | |
8525 | %#ifdef DEBUG | |
8526 | printf("I'm in bar\n"); | |
8527 | %#endif | |
8528 | } | |
8529 | } | |
8530 | </PRE> | |
8531 | </DIV> | |
8532 | <P> SWIG will strip the extra <TT>%</TT> and leave the preprocessor | |
8533 | directive in the code.</P> | |
8534 | <H2><A name="Preprocessor_nn10"></A>7.9 Viewing preprocessor output</H2> | |
8535 | <P> Like many compilers, SWIG supports a <TT>-E</TT> command line option | |
8536 | to display the output from the preprocessor. When the <TT>-E</TT> | |
8537 | switch is used, SWIG will not generate any wrappers. Instead the | |
8538 | results after the preprocessor has run are displayed. This might be | |
8539 | useful as an aid to debugging and viewing the results of macro | |
8540 | expansions.</P> | |
8541 | <HR NOSHADE> | |
8542 | <H1><A name="Library"></A>8 SWIG library</H1> | |
8543 | ||
8544 | <!-- INDEX --> | |
8545 | <DIV class="sectiontoc"> | |
8546 | <UL> | |
8547 | <LI><A href="#Library_nn2">The %include directive and library search | |
8548 | path</A></LI> | |
8549 | <LI><A href="#Library_nn3">C Arrays and Pointers</A> | |
8550 | <UL> | |
8551 | <LI><A href="#Library_nn4">cpointer.i</A></LI> | |
8552 | <LI><A href="#Library_nn5">carrays.i</A></LI> | |
8553 | <LI><A href="#Library_nn6">cmalloc.i</A></LI> | |
8554 | <LI><A href="#Library_nn7">cdata.i</A></LI> | |
8555 | </UL> | |
8556 | </LI> | |
8557 | <LI><A href="#Library_nn8">C String Handling</A> | |
8558 | <UL> | |
8559 | <LI><A href="#Library_nn9">Default string handling</A></LI> | |
8560 | <LI><A href="#Library_nn10">Passing binary data</A></LI> | |
8561 | <LI><A href="#Library_nn11">Using %newobject to release memory</A></LI> | |
8562 | <LI><A href="#Library_nn12">cstring.i</A></LI> | |
8563 | </UL> | |
8564 | </LI> | |
8565 | <LI><A href="#Library_stl_cpp_library">STL/C++ Library</A> | |
8566 | <UL> | |
8567 | <LI><A href="#Library_nn14">std_string.i</A></LI> | |
8568 | <LI><A href="#Library_nn15">std_vector.i</A></LI> | |
8569 | <LI><A href="#Library_stl_exceptions">STL exceptions</A></LI> | |
8570 | </UL> | |
8571 | </LI> | |
8572 | <LI><A href="#Library_nn16">Utility Libraries</A> | |
8573 | <UL> | |
8574 | <LI><A href="#Library_nn17">exception.i</A></LI> | |
8575 | </UL> | |
8576 | </LI> | |
8577 | </UL> | |
8578 | </DIV> | |
8579 | <!-- INDEX --> | |
8580 | <P> To help build extension modules, SWIG is packaged with a library of | |
8581 | support files that you can include in your own interfaces. These files | |
8582 | often define new SWIG directives or provide utility functions that can | |
8583 | be used to access parts of the standard C and C++ libraries. This | |
8584 | chapter provides a reference to the current set of supported library | |
8585 | files.</P> | |
8586 | <P><B> Compatibility note:</B> Older versions of SWIG included a number | |
8587 | of library files for manipulating pointers, arrays, and other | |
8588 | structures. Most these files are now deprecated and have been removed | |
8589 | from the distribution. Alternative libraries provide similar | |
8590 | functionality. Please read this chapter carefully if you used the old | |
8591 | libraries.</P> | |
8592 | <H2><A name="Library_nn2"></A>8.1 The %include directive and library | |
8593 | search path</H2> | |
8594 | <P> Library files are included using the <TT>%include</TT> directive. | |
8595 | When searching for files, directories are searched in the following | |
8596 | order:</P> | |
8597 | <UL> | |
8598 | <LI>The current directory</LI> | |
8599 | <LI>Directories specified with the <TT>-I</TT> command line option</LI> | |
8600 | <LI>.<TT>/swig_lib</TT></LI> | |
8601 | <LI><TT>/usr/local/lib/swig_lib</TT> (or wherever you installed SWIG)</LI> | |
8602 | <LI>On Windows, SWIG also looks for the library relative to the location | |
8603 | of <TT>swig.exe</TT>.</LI> | |
8604 | </UL> | |
8605 | <P> Within each directory, SWIG first looks for a subdirectory | |
8606 | corresponding to a target language (e.g., <TT>python</TT>, <TT>tcl</TT> | |
8607 | , etc.). If found, SWIG will search the language specific directory | |
8608 | first. This allows for language-specific implementations of library | |
8609 | files.</P> | |
8610 | <P> You can override the location of the SWIG library by setting the <TT> | |
8611 | SWIG_LIB</TT> environment variable.</P> | |
8612 | <H2><A name="Library_nn3"></A>8.2 C Arrays and Pointers</H2> | |
8613 | <P> This section describes library modules for manipulating low-level C | |
8614 | arrays and pointers. The primary use of these modules is in supporting | |
8615 | C declarations that manipulate bare pointers such as <TT>int *</TT>, <TT> | |
8616 | double *</TT>, or <TT>void *</TT>. The modules can be used to allocate | |
8617 | memory, manufacture pointers, dereference memory, and wrap pointers as | |
8618 | class-like objects. Since these functions provide direct access to | |
8619 | memory, their use is potentially unsafe and you should exercise | |
8620 | caution.</P> | |
8621 | <H3><A name="Library_nn4"></A>8.2.1 cpointer.i</H3> | |
8622 | <P> The <TT>cpointer.i</TT> module defines macros that can be used to | |
8623 | used to generate wrappers around simple C pointers. The primary use of | |
8624 | this module is in generating pointers to primitive datatypes such as <TT> | |
8625 | int</TT> and <TT>double</TT>.</P> | |
8626 | <P><B> <TT>%pointer_functions(type,name)</TT></B></P> | |
8627 | <DIV class="indent"> | |
8628 | <P>Generates a collection of four functions for manipulating a pointer <TT> | |
8629 | type *</TT>:</P> | |
8630 | <P> <TT>type *new_name()</TT></P> | |
8631 | <DIV class="indent"> | |
8632 | <P> Creates a new object of type <TT>type</TT> and returns a pointer to | |
8633 | it. In C, the object is created using <TT>calloc()</TT>. In C++, <TT> | |
8634 | new</TT> is used.</P> | |
8635 | </DIV> | |
8636 | <P> <TT>type *copy_name(type value)</TT></P> | |
8637 | <DIV class="indent"> | |
8638 | <P> Creates a new object of type <TT>type</TT> and returns a pointer to | |
8639 | it. An initial value is set by copying it from <TT>value</TT>. In C, | |
8640 | the object is created using <TT>calloc()</TT>. In C++, <TT>new</TT> is | |
8641 | used.</P> | |
8642 | </DIV> | |
8643 | <P> <TT>type *delete_name(type *obj)</TT></P> | |
8644 | <DIV class="indent"> | |
8645 | <P> Deletes an object type <TT>type</TT>.</P> | |
8646 | </DIV> | |
8647 | <P> <TT>void name_assign(type *obj, type value)</TT></P> | |
8648 | <DIV class="indent"> | |
8649 | <P> Assigns <TT>*obj = value</TT>.</P> | |
8650 | </DIV> | |
8651 | <P> <TT>type name_value(type *obj)</TT></P> | |
8652 | <DIV class="indent"> | |
8653 | <P> Returns the value of <TT>*obj</TT>.</P> | |
8654 | </DIV> | |
8655 | <P> When using this macro, <TT>type</TT> may be any type and <TT>name</TT> | |
8656 | must be a legal identifier in the target language. <TT>name</TT> should | |
8657 | not correspond to any other name used in the interface file.</P> | |
8658 | <P> Here is a simple example of using <TT>%pointer_functions()</TT>:</P> | |
8659 | <DIV class="code"> | |
8660 | <PRE> | |
8661 | %module example | |
8662 | %include "cpointer.i" | |
8663 | ||
8664 | /* Create some functions for working with "int *" */ | |
8665 | %pointer_functions(int, intp); | |
8666 | ||
8667 | /* A function that uses an "int *" */ | |
8668 | void add(int x, int y, int *result); | |
8669 | </PRE> | |
8670 | </DIV> | |
8671 | <P> Now, in Python:</P> | |
8672 | <DIV class="targetlang"> | |
8673 | <PRE> | |
8674 | >>> import example | |
8675 | >>> c = example.new_intp() # Create an "int" for storing result | |
8676 | >>> example.add(3,4,c) # Call function | |
8677 | >>> example.intp_value(c) # Dereference | |
8678 | 7 | |
8679 | >>> example.delete_intp(c) # Delete | |
8680 | </PRE> | |
8681 | </DIV></DIV> | |
8682 | <P><B> <TT>%pointer_class(type,name)</TT></B></P> | |
8683 | <DIV class="indent"> | |
8684 | <P> Wraps a pointer of <TT>type *</TT> inside a class-based interface. | |
8685 | This interface is as follows:</P> | |
8686 | <DIV class="code"> | |
8687 | <PRE> | |
8688 | struct name { | |
8689 | name(); // Create pointer object | |
8690 | ~name(); // Delete pointer object | |
8691 | void assign(type value); // Assign value | |
8692 | type value(); // Get value | |
8693 | type *cast(); // Cast the pointer to original type | |
8694 | static name *frompointer(type *); // Create class wrapper from existing | |
8695 | // pointer | |
8696 | }; | |
8697 | </PRE> | |
8698 | </DIV> | |
8699 | <P> When using this macro, <TT>type</TT> is restricted to a simple type | |
8700 | name like <TT>int</TT>, <TT>float</TT>, or <TT>Foo</TT>. Pointers and | |
8701 | other complicated types are not allowed. <TT>name</TT> must be a valid | |
8702 | identifier not already in use. When a pointer is wrapped as a class, | |
8703 | the "class" may be transparently passed to any function that expects | |
8704 | the pointer.</P> | |
8705 | <P> If the target language does not support proxy classes, the use of | |
8706 | this macro will produce the example same functions as <TT> | |
8707 | %pointer_functions()</TT> macro.</P> | |
8708 | <P> It should be noted that the class interface does introduce a new | |
8709 | object or wrap a pointer inside a special structure. Instead, the raw | |
8710 | pointer is used directly.</P> | |
8711 | <P> Here is the same example using a class instead:</P> | |
8712 | <DIV class="code"> | |
8713 | <PRE> | |
8714 | %module example | |
8715 | %include "cpointer.i" | |
8716 | ||
8717 | /* Wrap a class interface around an "int *" */ | |
8718 | %pointer_class(int, intp); | |
8719 | ||
8720 | /* A function that uses an "int *" */ | |
8721 | void add(int x, int y, int *result); | |
8722 | </PRE> | |
8723 | </DIV> | |
8724 | <P> Now, in Python (using proxy classes)</P> | |
8725 | <DIV class="targetlang"> | |
8726 | <PRE> | |
8727 | >>> import example | |
8728 | >>> c = example.intp() # Create an "int" for storing result | |
8729 | >>> example.add(3,4,c) # Call function | |
8730 | >>> c.value() # Dereference | |
8731 | 7 | |
8732 | </PRE> | |
8733 | </DIV> | |
8734 | <P> Of the two macros, <TT>%pointer_class</TT> is probably the most | |
8735 | convenient when working with simple pointers. This is because the | |
8736 | pointers are access like objects and they can be easily garbage | |
8737 | collected (destruction of the pointer object destroys the underlying | |
8738 | object).</P> | |
8739 | </DIV> | |
8740 | <P><B> <TT>%pointer_cast(type1, type2, name)</TT></B></P> | |
8741 | <DIV class="indent"> | |
8742 | <P> Creates a casting function that converts <TT>type1</TT> to <TT>type2</TT> | |
8743 | . The name of the function is <TT>name</TT>. For example:</P> | |
8744 | <DIV class="code"> | |
8745 | <PRE> | |
8746 | %pointer_cast(int *, unsigned int *, int_to_uint); | |
8747 | </PRE> | |
8748 | </DIV> | |
8749 | <P> In this example, the function <TT>int_to_uint()</TT> would be used | |
8750 | to cast types in the target language.</P> | |
8751 | </DIV> | |
8752 | <P><B> Note:</B> None of these macros can be used to safely work with | |
8753 | strings (<TT>char *</TT> or <TT>char **</TT>).</P> | |
8754 | <P><B> Note:</B> When working with simple pointers, typemaps can often | |
8755 | be used to provide more seamless operation.</P> | |
8756 | <H3><A name="Library_nn5"></A>8.2.2 carrays.i</H3> | |
8757 | <P> This module defines macros that assist in wrapping ordinary C | |
8758 | pointers as arrays. The module does not provide any safety or an extra | |
8759 | layer of wrapping--it merely provides functionality for creating, | |
8760 | destroying, and modifying the contents of raw C array data.</P> | |
8761 | <P><B> <TT>%array_functions(type,name)</TT></B></P> | |
8762 | <DIV class="indent"> | |
8763 | <P>Creates four functions.</P> | |
8764 | <P> <TT>type *new_name(int nelements)</TT></P> | |
8765 | <DIV class="indent"> | |
8766 | <P> Creates a new array of objects of type <TT>type</TT>. In C, the | |
8767 | array is allocated using <TT>calloc()</TT>. In C++, <TT>new []</TT> is | |
8768 | used.</P> | |
8769 | </DIV> | |
8770 | <P> <TT>type *delete_name(type *ary)</TT></P> | |
8771 | <DIV class="indent"> | |
8772 | <P> Deletes an array. In C, <TT>free()</TT> is used. In C++, <TT>delete | |
8773 | []</TT> is used.</P> | |
8774 | </DIV> | |
8775 | <P> <TT>type name_getitem(type *ary, int index)</TT></P> | |
8776 | <DIV class="indent"> | |
8777 | <P> Returns the value <TT>ary[index]</TT>.</P> | |
8778 | </DIV> | |
8779 | <P> <TT>void name_setitem(type *ary, int index, type value)</TT></P> | |
8780 | <DIV class="indent"> | |
8781 | <P> Assigns <TT>ary[index] = value</TT>.</P> | |
8782 | </DIV> | |
8783 | <P> When using this macro, <TT>type</TT> may be any type and <TT>name</TT> | |
8784 | must be a legal identifier in the target language. <TT>name</TT> should | |
8785 | not correspond to any other name used in the interface file.</P> | |
8786 | <P> Here is an example of <TT>%array_functions()</TT>. Suppose you had a | |
8787 | function like this:</P> | |
8788 | <DIV class="code"> | |
8789 | <PRE> | |
8790 | void print_array(double x[10]) { | |
8791 | int i; | |
8792 | for (i = 0; i < 10; i++) { | |
8793 | printf("[%d] = %g\n", i, x[i]); | |
8794 | } | |
8795 | } | |
8796 | </PRE> | |
8797 | </DIV> | |
8798 | <P> To wrap it, you might write this:</P> | |
8799 | <DIV class="code"> | |
8800 | <PRE> | |
8801 | %module example | |
8802 | ||
8803 | %include "carrays.i" | |
8804 | %array_functions(double, doubleArray); | |
8805 | ||
8806 | void print_array(double x[10]); | |
8807 | </PRE> | |
8808 | </DIV> | |
8809 | <P> Now, in a scripting language, you might write this:</P> | |
8810 | <DIV class="code"> | |
8811 | <PRE> | |
8812 | a = new_doubleArray(10) # Create an array | |
8813 | for i in range(0,10): | |
8814 | doubleArray_setitem(a,i,2*i) # Set a value | |
8815 | print_array(a) # Pass to C | |
8816 | delete_doubleArray(a) # Destroy array | |
8817 | </PRE> | |
8818 | </DIV></DIV><B> <TT>%array_class(type,name)</TT></B><DIV class="indent"> | |
8819 | <P> Wraps a pointer of <TT>type *</TT> inside a class-based interface. | |
8820 | This interface is as follows:</P> | |
8821 | <DIV class="code"> | |
8822 | <PRE> | |
8823 | struct name { | |
8824 | name(int nelements); // Create an array | |
8825 | ~name(); // Delete array | |
8826 | type getitem(int index); // Return item | |
8827 | void setitem(int index, type value); // Set item | |
8828 | type *cast(); // Cast to original type | |
8829 | static name *frompointer(type *); // Create class wrapper from | |
8830 | // existing pointer | |
8831 | }; | |
8832 | </PRE> | |
8833 | </DIV> | |
8834 | <P> When using this macro, <TT>type</TT> is restricted to a simple type | |
8835 | name like <TT>int</TT> or <TT>float</TT>. Pointers and other | |
8836 | complicated types are not allowed. <TT>name</TT> must be a valid | |
8837 | identifier not already in use. When a pointer is wrapped as a class, it | |
8838 | can be transparently passed to any function that expects the pointer.</P> | |
8839 | <P> When combined with proxy classes, the <TT>%array_class()</TT> macro | |
8840 | can be especially useful. For example:</P> | |
8841 | <DIV class="code"> | |
8842 | <PRE> | |
8843 | %module example | |
8844 | %include "carrays.i" | |
8845 | %array_class(double, doubleArray); | |
8846 | ||
8847 | void print_array(double x[10]); | |
8848 | </PRE> | |
8849 | </DIV> | |
8850 | <P> Allows you to do this:</P> | |
8851 | <DIV class="code"> | |
8852 | <PRE> | |
8853 | import example | |
8854 | c = example.doubleArray(10) # Create double[10] | |
8855 | for i in range(0,10): | |
8856 | c[i] = 2*i # Assign values | |
8857 | example.print_array(c) # Pass to C | |
8858 | </PRE> | |
8859 | </DIV></DIV> | |
8860 | <P><B> Note:</B> These macros do not encapsulate C arrays inside a | |
8861 | special data structure or proxy. There is no bounds checking or safety | |
8862 | of any kind. If you want this, you should consider using a special | |
8863 | array object rather than a bare pointer.</P> | |
8864 | <P><B> Note:</B> <TT>%array_functions()</TT> and <TT>%array_class()</TT> | |
8865 | should not be used with types of <TT>char</TT> or <TT>char *</TT>.</P> | |
8866 | <H3><A name="Library_nn6"></A>8.2.3 cmalloc.i</H3> | |
8867 | <P> This module defines macros for wrapping the low-level C memory | |
8868 | allocation functions <TT>malloc()</TT>, <TT>calloc()</TT>, <TT> | |
8869 | realloc()</TT>, and <TT>free()</TT>.</P> | |
8870 | <P><B> <TT>%malloc(type [,name=type])</TT></B></P> | |
8871 | <DIV class="indent"> | |
8872 | <P> Creates a wrapper around <TT>malloc()</TT> with the following | |
8873 | prototype:</P> | |
8874 | <DIV class="code"> | |
8875 | <PRE> | |
8876 | <EM>type</EM> *malloc_<EM>name</EM>(int nbytes = sizeof(<EM>type</EM>)); | |
8877 | </PRE> | |
8878 | </DIV> | |
8879 | <P> If <TT>type</TT> is <TT>void</TT>, then the size parameter <TT> | |
8880 | nbytes</TT> is required. The <TT>name</TT> parameter only needs to be | |
8881 | specified when wrapping a type that is not a valid identifier (e.g., "<TT> | |
8882 | int *</TT>", "<TT>double **</TT>", etc.).</P> | |
8883 | </DIV> | |
8884 | <P><B> <TT>%calloc(type [,name=type])</TT></B></P> | |
8885 | <DIV class="indent"> | |
8886 | <P> Creates a wrapper around <TT>calloc()</TT> with the following | |
8887 | prototype:</P> | |
8888 | <DIV class="code"> | |
8889 | <PRE> | |
8890 | <EM>type</EM> *calloc_<EM>name</EM>(int nobj =1, int sz = sizeof(<EM>type</EM>)); | |
8891 | </PRE> | |
8892 | </DIV> | |
8893 | <P> If <TT>type</TT> is <TT>void</TT>, then the size parameter <TT>sz</TT> | |
8894 | is required.</P> | |
8895 | </DIV> | |
8896 | <P><B> <TT>%realloc(type [,name=type])</TT></B></P> | |
8897 | <DIV class="indent"> | |
8898 | <P> Creates a wrapper around <TT>realloc()</TT> with the following | |
8899 | prototype:</P> | |
8900 | <DIV class="code"> | |
8901 | <PRE> | |
8902 | <EM>type</EM> *realloc_<EM>name</EM>(<EM>type</EM> *ptr, int nitems); | |
8903 | </PRE> | |
8904 | </DIV> | |
8905 | <P> Note: unlike the C <TT>realloc()</TT>, the wrapper generated by this | |
8906 | macro implicitly includes the size of the corresponding type. For | |
8907 | example, <TT>realloc_int(p, 100)</TT> reallocates <TT>p</TT> so that it | |
8908 | holds 100 integers.</P> | |
8909 | </DIV> | |
8910 | <P><B> <TT>%free(type [,name=type])</TT></B></P> | |
8911 | <DIV class="indent"> | |
8912 | <P> Creates a wrapper around <TT>free()</TT> with the following | |
8913 | prototype:</P> | |
8914 | <DIV class="code"> | |
8915 | <PRE> | |
8916 | void free_<EM>name</EM>(<EM>type</EM> *ptr); | |
8917 | </PRE> | |
8918 | </DIV></DIV> | |
8919 | <P><B> <TT>%sizeof(type [,name=type])</TT></B></P> | |
8920 | <DIV class="indent"> | |
8921 | <P> Creates the constant:</P> | |
8922 | <DIV class="code"> | |
8923 | <PRE> | |
8924 | %constant int sizeof_<EM>name</EM> = sizeof(<EM>type</EM>); | |
8925 | </PRE> | |
8926 | </DIV></DIV> | |
8927 | <P><B> <TT>%allocators(type [,name=type])</TT></B></P> | |
8928 | <DIV class="indent"> | |
8929 | <P> Generates wrappers for all five of the above operations.</P> | |
8930 | </DIV> | |
8931 | <P> Here is a simple example that illustrates the use of these macros:</P> | |
8932 | <DIV class="code"> | |
8933 | <PRE> | |
8934 | // SWIG interface | |
8935 | %module example | |
8936 | %include "cmalloc.i" | |
8937 | ||
8938 | %malloc(int); | |
8939 | %free(int); | |
8940 | ||
8941 | %malloc(int *, intp); | |
8942 | %free(int *, intp); | |
8943 | ||
8944 | %allocators(double); | |
8945 | </PRE> | |
8946 | </DIV> | |
8947 | <P> Now, in a script:</P> | |
8948 | <DIV class="targetlang"> | |
8949 | <PRE> | |
8950 | >>> from example import * | |
8951 | >>> a = malloc_int() | |
8952 | >>> a | |
8953 | '_000efa70_p_int' | |
8954 | >>> free_int(a) | |
8955 | >>> b = malloc_intp() | |
8956 | >>> b | |
8957 | '_000efb20_p_p_int' | |
8958 | >>> free_intp(b) | |
8959 | >>> c = calloc_double(50) | |
8960 | >>> c | |
8961 | '_000fab98_p_double' | |
8962 | >>> c = realloc_double(100000) | |
8963 | >>> free_double(c) | |
8964 | >>> print sizeof_double | |
8965 | 8 | |
8966 | >>> | |
8967 | </PRE> | |
8968 | </DIV> | |
8969 | <H3><A name="Library_nn7"></A>8.2.4 cdata.i</H3> | |
8970 | <P> The <TT>cdata.i</TT> module defines functions for converting raw C | |
8971 | data to and from strings in the target language. The primary | |
8972 | applications of this module would be packing/unpacking of binary data | |
8973 | structures---for instance, if you needed to extract data from a buffer. | |
8974 | The target language must support strings with embedded binary data in | |
8975 | order for this to work.</P> | |
8976 | <P><B> <TT>char *cdata(void *ptr, int nbytes)</TT></B></P> | |
8977 | <DIV class="indent"> | |
8978 | <P> Converts <TT>nbytes</TT> of data at <TT>ptr</TT> into a string. <TT> | |
8979 | ptr</TT> can be any pointer.</P> | |
8980 | </DIV> | |
8981 | <P><B> <TT>void memmove(void *ptr, char *s)</TT></B></P> | |
8982 | <DIV class="indent"> | |
8983 | <P> Copies all of the string data in <TT>s</TT> into the memory pointed | |
8984 | to by <TT>ptr</TT>. The string may contain embedded NULL bytes. The | |
8985 | length of the string is implicitly determined in the underlying wrapper | |
8986 | code.</P> | |
8987 | </DIV> | |
8988 | <P> One use of these functions is packing and unpacking data from | |
8989 | memory. Here is a short example:</P> | |
8990 | <DIV class="code"> | |
8991 | <PRE> | |
8992 | // SWIG interface | |
8993 | %module example | |
8994 | %include "carrays.i" | |
8995 | %include "cdata.i" | |
8996 | ||
8997 | %array_class(int, intArray); | |
8998 | </PRE> | |
8999 | </DIV> | |
9000 | <P> Python example:</P> | |
9001 | <DIV class="targetlang"> | |
9002 | <PRE> | |
9003 | >>> a = intArray(10) | |
9004 | >>> for i in range(0,10): | |
9005 | ... a[i] = i | |
9006 | >>> b = cdata(a,40) | |
9007 | >>> b | |
9008 | '\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04 | |
9009 | \x00\x00\x00\x05\x00\x00\x00\x06\x00\x00\x00\x07\x00\x00\x00\x08\x00\x00\x00\t' | |
9010 | >>> c = intArray(10) | |
9011 | >>> memmove(c,b) | |
9012 | >>> print c[4] | |
9013 | 4 | |
9014 | >>> | |
9015 | </PRE> | |
9016 | </DIV> | |
9017 | <P> Since the size of data is not always known, the following macro is | |
9018 | also defined:</P> | |
9019 | <P><B> <TT>%cdata(type [,name=type])</TT></B></P> | |
9020 | <DIV class="indent"> | |
9021 | <P> Generates the following function for extracting C data for a given | |
9022 | type.</P> | |
9023 | <DIV class="code"> | |
9024 | <PRE> | |
9025 | char *cdata_<EM>name</EM>(type* ptr, int nitems) | |
9026 | </PRE> | |
9027 | </DIV> | |
9028 | <P> <TT>nitems</TT> is the number of items of the given type to extract.</P> | |
9029 | </DIV> | |
9030 | <P><B> Note:</B> These functions provide direct access to memory and can | |
9031 | be used to overwrite data. Clearly they are unsafe.</P> | |
9032 | <H2><A name="Library_nn8"></A>8.3 C String Handling</H2> | |
9033 | <P> A common problem when working with C programs is dealing with | |
9034 | functions that manipulate raw character data using <TT>char *</TT>. In | |
9035 | part, problems arise because there are different interpretations of <TT> | |
9036 | char *</TT>---it could be a NULL-terminated string or it could point to | |
9037 | binary data. Moreover, functions that manipulate raw strings may mutate | |
9038 | data, perform implicit memory allocations, or utilize fixed-sized | |
9039 | buffers.</P> | |
9040 | <P> The problems (and perils) of using <TT>char *</TT> are well-known. | |
9041 | However, SWIG is not in the business of enforcing morality. The modules | |
9042 | in this section provide basic functionality for manipulating raw C | |
9043 | strings.</P> | |
9044 | <H3><A name="Library_nn9"></A>8.3.1 Default string handling</H3> | |
9045 | <P> Suppose you have a C function with this prototype:</P> | |
9046 | <DIV class="code"> | |
9047 | <PRE> | |
9048 | char *foo(char *s); | |
9049 | </PRE> | |
9050 | </DIV> | |
9051 | <P> The default wrapping behavior for this function is to set <TT>s</TT> | |
9052 | to a raw <TT>char *</TT> that refers to the internal string data in the | |
9053 | target language. In other words, if you were using a language like Tcl, | |
9054 | and you wrote this,</P> | |
9055 | <DIV class="code"> | |
9056 | <PRE> | |
9057 | % foo Hello | |
9058 | </PRE> | |
9059 | </DIV> | |
9060 | <P> then <TT>s</TT> would point to the representation of "Hello" inside | |
9061 | the Tcl interpreter. When returning a <TT>char *</TT>, SWIG assumes | |
9062 | that it is a NULL-terminated string and makes a copy of it. This gives | |
9063 | the target language its own copy of the result.</P> | |
9064 | <P> There are obvious problems with the default behavior. First, since a | |
9065 | <TT>char *</TT> argument points to data inside the target language, it | |
9066 | is<B> NOT</B> safe for a function to modify this data (doing so may | |
9067 | corrupt the interpreter and lead to a crash). Furthermore, the default | |
9068 | behavior does not work well with binary data. Instead, strings are | |
9069 | assumed to be NULL-terminated.</P> | |
9070 | <H3><A name="Library_nn10"></A>8.3.2 Passing binary data</H3> | |
9071 | <P> If you have a function that expects binary data,</P> | |
9072 | <DIV class="code"> | |
9073 | <PRE> | |
9074 | int parity(char *str, int len, int initial); | |
9075 | </PRE> | |
9076 | </DIV> | |
9077 | <P> you can wrap the parameters <TT>(char *str, int len)</TT> as a | |
9078 | single argument using a typemap. Just do this:</P> | |
9079 | <DIV class="code"> | |
9080 | <PRE> | |
9081 | %apply (char *STRING, int LENGTH) { (char *str, int len) }; | |
9082 | ... | |
9083 | int parity(char *str, int len, int initial); | |
9084 | </PRE> | |
9085 | </DIV> | |
9086 | <P> Now, in the target language, you can use binary string data like | |
9087 | this:</P> | |
9088 | <DIV class="code"> | |
9089 | <PRE> | |
9090 | >>> s = "H\x00\x15eg\x09\x20" | |
9091 | >>> parity(s,0) | |
9092 | </PRE> | |
9093 | </DIV> | |
9094 | <P> In the wrapper function, the passed string will be expanded to a | |
9095 | pointer and length parameter.</P> | |
9096 | <H3><A name="Library_nn11"></A>8.3.3 Using %newobject to release memory</H3> | |
9097 | <P> If you have a function that allocates memory like this,</P> | |
9098 | <DIV class="code"> | |
9099 | <PRE> | |
9100 | char *foo() { | |
9101 | char *result = (char *) malloc(...); | |
9102 | ... | |
9103 | return result; | |
9104 | } | |
9105 | </PRE> | |
9106 | </DIV> | |
9107 | <P> then the SWIG generated wrappers will have a memory leak--the | |
9108 | returned data will be copied into a string object and the old contents | |
9109 | ignored.</P> | |
9110 | <P> To fix the memory leak, use the <TT>%newobject</TT> directive.</P> | |
9111 | <DIV class="code"> | |
9112 | <PRE> | |
9113 | %newobject foo; | |
9114 | ... | |
9115 | char *foo(); | |
9116 | </PRE> | |
9117 | </DIV> | |
9118 | <P> This will release the result.</P> | |
9119 | <H3><A name="Library_nn12"></A>8.3.4 cstring.i</H3> | |
9120 | <P> The <TT>cstring.i</TT> library file provides a collection of macros | |
9121 | for dealing with functions that either mutate string arguments or which | |
9122 | try to output string data through their arguments. An example of such a | |
9123 | function might be this rather questionable implementation:</P> | |
9124 | <DIV class="code"> | |
9125 | <PRE> | |
9126 | void get_path(char *s) { | |
9127 | // Potential buffer overflow---uh, oh. | |
9128 | sprintf(s,"%s/%s", base_directory, sub_directory); | |
9129 | } | |
9130 | ... | |
9131 | // Somewhere else in the C program | |
9132 | { | |
9133 | char path[1024]; | |
9134 | ... | |
9135 | get_path(path); | |
9136 | ... | |
9137 | } | |
9138 | </PRE> | |
9139 | </DIV> | |
9140 | <P> (Off topic rant: If your program really has functions like this, you | |
9141 | would be well-advised to replace them with safer alternatives involving | |
9142 | bounds checking).</P> | |
9143 | <P> The macros defined in this module all expand to various combinations | |
9144 | of typemaps. Therefore, the same pattern matching rules and ideas | |
9145 | apply.</P> | |
9146 | <P><B> %cstring_bounded_output(parm, maxsize)</B></P> | |
9147 | <DIV class="indent"> | |
9148 | <P> Turns parameter <TT><EM>parm</EM></TT> into an output value. The | |
9149 | output string is assumed to be NULL-terminated and smaller than <TT><EM> | |
9150 | maxsize</EM></TT> characters. Here is an example:</P> | |
9151 | <DIV class="code"> | |
9152 | <PRE> | |
9153 | %cstring_bounded_output(char *path, 1024); | |
9154 | ... | |
9155 | void get_path(char *path); | |
9156 | </PRE> | |
9157 | </DIV> | |
9158 | <P> In the target language:</P> | |
9159 | <DIV class="targetlang"> | |
9160 | <PRE> | |
9161 | >>> get_path() | |
9162 | /home/beazley/packages/Foo/Bar | |
9163 | >>> | |
9164 | </PRE> | |
9165 | </DIV> | |
9166 | <P> Internally, the wrapper function allocates a small buffer (on the | |
9167 | stack) of the requested size and passes it as the pointer value. Data | |
9168 | stored in the buffer is then returned as a function return value. If | |
9169 | the function already returns a value, then the return value and the | |
9170 | output string are returned together (multiple return values).<B> If | |
9171 | more than <TT><EM>maxsize</EM></TT> bytes are written, your program | |
9172 | will crash with a buffer overflow!</B></P> | |
9173 | </DIV> | |
9174 | <P><B> %cstring_chunk_output(parm, chunksize)</B></P> | |
9175 | <DIV class="indent"> | |
9176 | <P> Turns parameter <TT><EM>parm</EM></TT> into an output value. The | |
9177 | output string is always <TT><EM>chunksize</EM></TT> and may contain | |
9178 | binary data. Here is an example:</P> | |
9179 | <DIV class="code"> | |
9180 | <PRE> | |
9181 | %cstring_chunk_output(char *packet, PACKETSIZE); | |
9182 | ... | |
9183 | void get_packet(char *packet); | |
9184 | </PRE> | |
9185 | </DIV> | |
9186 | <P> In the target language:</P> | |
9187 | <DIV class="targetlang"> | |
9188 | <PRE> | |
9189 | >>> get_packet() | |
9190 | '\xa9Y:\xf6\xd7\xe1\x87\xdbH;y\x97\x7f"\xd3\x99\x14V\xec\x06\xea\xa2\x88' | |
9191 | >>> | |
9192 | </PRE> | |
9193 | </DIV> | |
9194 | <P> This macro is essentially identical to <TT>%cstring_bounded_output</TT> | |
9195 | . The only difference is that the result is always <TT><EM>chunksize</EM> | |
9196 | </TT> characters. Furthermore, the result can contain binary data.<B> If | |
9197 | more than <TT><EM>maxsize</EM></TT> bytes are written, your program | |
9198 | will crash with a buffer overflow!</B></P> | |
9199 | </DIV> | |
9200 | <P><B> %cstring_bounded_mutable(parm, maxsize)</B></P> | |
9201 | <DIV class="indent"> | |
9202 | <P> Turns parameter <TT><EM>parm</EM></TT> into a mutable string | |
9203 | argument. The input string is assumed to be NULL-terminated and smaller | |
9204 | than <TT><EM>maxsize</EM></TT> characters. The output string is also | |
9205 | assumed to be NULL-terminated and less than <TT><EM>maxsize</EM></TT> | |
9206 | characters.</P> | |
9207 | <DIV class="code"> | |
9208 | <PRE> | |
9209 | %cstring_bounded_mutable(char *ustr, 1024); | |
9210 | ... | |
9211 | void make_upper(char *ustr); | |
9212 | </PRE> | |
9213 | </DIV> | |
9214 | <P> In the target language:</P> | |
9215 | <DIV class="targetlang"> | |
9216 | <PRE> | |
9217 | >>> make_upper("hello world") | |
9218 | 'HELLO WORLD' | |
9219 | >>> | |
9220 | </PRE> | |
9221 | </DIV> | |
9222 | <P> Internally, this macro is almost exactly the same as <TT> | |
9223 | %cstring_bounded_output</TT>. The only difference is that the parameter | |
9224 | accepts an input value that is used to initialize the internal buffer. | |
9225 | It is important to emphasize that this function does not mutate the | |
9226 | string value passed---instead it makes a copy of the input value, | |
9227 | mutates it, and returns it as a result.<B> If more than <TT><EM>maxsize</EM> | |
9228 | </TT> bytes are written, your program will crash with a buffer overflow!</B> | |
9229 | </P> | |
9230 | </DIV> | |
9231 | <P><B> %cstring_mutable(parm [, expansion])</B></P> | |
9232 | <DIV class="indent"> | |
9233 | <P> Turns parameter <TT><EM>parm</EM></TT> into a mutable string | |
9234 | argument. The input string is assumed to be NULL-terminated. An | |
9235 | optional parameter <TT><EM>expansion</EM></TT> specifies the number of | |
9236 | extra characters by which the string might grow when it is modified. | |
9237 | The output string is assumed to be NULL-terminated and less than the | |
9238 | size of the input string plus any expansion characters.</P> | |
9239 | <DIV class="code"> | |
9240 | <PRE> | |
9241 | %cstring_mutable(char *ustr); | |
9242 | ... | |
9243 | void make_upper(char *ustr); | |
9244 | ||
9245 | %cstring_mutable(char *hstr, HEADER_SIZE); | |
9246 | ... | |
9247 | void attach_header(char *hstr); | |
9248 | </PRE> | |
9249 | </DIV> | |
9250 | <P> In the target language:</P> | |
9251 | <DIV class="targetlang"> | |
9252 | <PRE> | |
9253 | >>> make_upper("hello world") | |
9254 | 'HELLO WORLD' | |
9255 | >>> attach_header("Hello world") | |
9256 | 'header: Hello world' | |
9257 | >>> | |
9258 | </PRE> | |
9259 | </DIV> | |
9260 | <P> This macro differs from <TT>%cstring_bounded_mutable()</TT> in that | |
9261 | a buffer is dynamically allocated (on the heap using <TT>malloc/new</TT> | |
9262 | ). This buffer is always large enough to store a copy of the input value | |
9263 | plus any expansion bytes that might have been requested. It is | |
9264 | important to emphasize that this function does not directly mutate the | |
9265 | string value passed---instead it makes a copy of the input value, | |
9266 | mutates it, and returns it as a result.<B> If the function expands the | |
9267 | result by more than <TT><EM>expansion</EM></TT> extra bytes, then the | |
9268 | program will crash with a buffer overflow!</B></P> | |
9269 | </DIV> | |
9270 | <P><B> %cstring_output_maxsize(parm, maxparm)</B></P> | |
9271 | <DIV class="indent"> | |
9272 | <P> This macro is used to handle bounded character output functions | |
9273 | where both a <TT>char *</TT> and a maximum length parameter are | |
9274 | provided. As input, a user simply supplies the maximum length. The | |
9275 | return value is assumed to be a NULL-terminated string.</P> | |
9276 | <DIV class="code"> | |
9277 | <PRE> | |
9278 | %cstring_output_maxsize(char *path, int maxpath); | |
9279 | ... | |
9280 | void get_path(char *path, int maxpath); | |
9281 | </PRE> | |
9282 | </DIV> | |
9283 | <P> In the target language:</P> | |
9284 | <DIV class="targetlang"> | |
9285 | <PRE> | |
9286 | >>> get_path(1024) | |
9287 | '/home/beazley/Packages/Foo/Bar' | |
9288 | >>> | |
9289 | </PRE> | |
9290 | </DIV> | |
9291 | <P> This macro provides a safer alternative for functions that need to | |
9292 | write string data into a buffer. User supplied buffer size is used to | |
9293 | dynamically allocate memory on heap. Results are placed into that | |
9294 | buffer and returned as a string object.</P> | |
9295 | </DIV> | |
9296 | <P><B> %cstring_output_withsize(parm, maxparm)</B></P> | |
9297 | <DIV class="indent"> | |
9298 | <P> This macro is used to handle bounded character output functions | |
9299 | where both a <TT>char *</TT> and a pointer <TT>int *</TT> are passed. | |
9300 | Initially, the <TT>int *</TT> parameter points to a value containing | |
9301 | the maximum size. On return, this value is assumed to contain the | |
9302 | actual number of bytes. As input, a user simply supplies the maximum | |
9303 | length. The output value is a string that may contain binary data.</P> | |
9304 | <DIV class="code"> | |
9305 | <PRE> | |
9306 | %cstring_output_withsize(char *data, int *maxdata); | |
9307 | ... | |
9308 | void get_data(char *data, int *maxdata); | |
9309 | </PRE> | |
9310 | </DIV> | |
9311 | <P> In the target language:</P> | |
9312 | <DIV class="targetlang"> | |
9313 | <PRE> | |
9314 | >>> get_data(1024) | |
9315 | 'x627388912' | |
9316 | >>> get_data(1024) | |
9317 | 'xyzzy' | |
9318 | >>> | |
9319 | </PRE> | |
9320 | </DIV> | |
9321 | <P> This macro is a somewhat more powerful version of <TT> | |
9322 | %cstring_output_chunk()</TT>. Memory is dynamically allocated and can be | |
9323 | arbitrary large. Furthermore, a function can control how much data is | |
9324 | actually returned by changing the value of the <TT>maxparm</TT> | |
9325 | argument.</P> | |
9326 | </DIV> | |
9327 | <P><B> %cstring_output_allocate(parm, release)</B></P> | |
9328 | <DIV class="indent"> | |
9329 | <P> This macro is used to return strings that are allocated within the | |
9330 | program and returned in a parameter of type <TT>char **</TT>. For | |
9331 | example:</P> | |
9332 | <DIV class="code"> | |
9333 | <PRE> | |
9334 | void foo(char **s) { | |
9335 | *s = (char *) malloc(64); | |
9336 | sprintf(*s, "Hello world\n"); | |
9337 | } | |
9338 | </PRE> | |
9339 | </DIV> | |
9340 | <P> The returned string is assumed to be NULL-terminated. <TT><EM> | |
9341 | release</EM></TT> specifies how the allocated memory is to be released | |
9342 | (if applicable). Here is an example:</P> | |
9343 | <DIV class="code"> | |
9344 | <PRE> | |
9345 | %cstring_output_allocate(char **s, free(*$1)); | |
9346 | ... | |
9347 | void foo(char **s); | |
9348 | </PRE> | |
9349 | </DIV> | |
9350 | <P> In the target language:</P> | |
9351 | <DIV class="targetlang"> | |
9352 | <PRE> | |
9353 | >>> foo() | |
9354 | 'Hello world\n' | |
9355 | >>> | |
9356 | </PRE> | |
9357 | </DIV></DIV> | |
9358 | <P><B> %cstring_output_allocate_size(parm, szparm, release)</B></P> | |
9359 | <DIV class="indent"> | |
9360 | <P> This macro is used to return strings that are allocated within the | |
9361 | program and returned in two parameters of type <TT>char **</TT> and <TT> | |
9362 | int *</TT>. For example:</P> | |
9363 | <DIV class="code"> | |
9364 | <PRE> | |
9365 | void foo(char **s, int *sz) { | |
9366 | *s = (char *) malloc(64); | |
9367 | *sz = 64; | |
9368 | // Write some binary data | |
9369 | ... | |
9370 | } | |
9371 | </PRE> | |
9372 | </DIV> | |
9373 | <P> The returned string may contain binary data. <TT><EM>release</EM></TT> | |
9374 | specifies how the allocated memory is to be released (if applicable). | |
9375 | Here is an example:</P> | |
9376 | <DIV class="code"> | |
9377 | <PRE> | |
9378 | %cstring_output_allocate_size(char **s, int *slen, free(*$1)); | |
9379 | ... | |
9380 | void foo(char **s, int *slen); | |
9381 | </PRE> | |
9382 | </DIV> | |
9383 | <P> In the target language:</P> | |
9384 | <DIV class="targetlang"> | |
9385 | <PRE> | |
9386 | >>> foo() | |
9387 | '\xa9Y:\xf6\xd7\xe1\x87\xdbH;y\x97\x7f"\xd3\x99\x14V\xec\x06\xea\xa2\x88' | |
9388 | >>> | |
9389 | </PRE> | |
9390 | </DIV> | |
9391 | <P> This is the safest and most reliable way to return binary string | |
9392 | data in SWIG. If you have functions that conform to another prototype, | |
9393 | you might consider wrapping them with a helper function. For example, | |
9394 | if you had this:</P> | |
9395 | <DIV class="code"> | |
9396 | <PRE> | |
9397 | char *get_data(int *len); | |
9398 | </PRE> | |
9399 | </DIV> | |
9400 | <P> You could wrap it with a function like this:</P> | |
9401 | <DIV class="code"> | |
9402 | <PRE> | |
9403 | void my_get_data(char **result, int *len) { | |
9404 | *result = get_data(len); | |
9405 | } | |
9406 | </PRE> | |
9407 | </DIV></DIV> | |
9408 | <P><B> Comments:</B></P> | |
9409 | <UL> | |
9410 | <LI>Support for the <TT>cstring.i</TT> module depends on the target | |
9411 | language. Not all SWIG modules currently support this library.</LI> | |
9412 | <LI>Reliable handling of raw C strings is a delicate topic. There are | |
9413 | many ways to accomplish this in SWIG. This library provides support for | |
9414 | a few common techniques.</LI> | |
9415 | <LI>If used in C++, this library uses <TT>new</TT> and <TT>delete []</TT> | |
9416 | for memory allocation. If using ANSI C, the library uses <TT>malloc()</TT> | |
9417 | and <TT>free()</TT>.</LI> | |
9418 | <LI>Rather than manipulating <TT>char *</TT> directly, you might | |
9419 | consider using a special string structure or class instead.</LI> | |
9420 | </UL> | |
9421 | <H2><A name="Library_stl_cpp_library"></A>8.4 STL/C++ Library</H2> | |
9422 | <P> The library modules in this section provide access to parts of the | |
9423 | standard C++ library including the STL. SWIG support for the STL is an | |
9424 | ongoing effort. Support is quite comprehensive for some language | |
9425 | modules but some of the lesser used modules do not have quite as much | |
9426 | library code written.</P> | |
9427 | <P> The following table shows which C++ classes are supported and the | |
9428 | equivalent SWIG interface library file for the C++ library.</P> | |
9429 | <TABLE BORDER summary="SWIG C++ library files"> | |
9430 | <TR VALIGN="TOP"><TD><B>C++ class</B></TD><TD><B>C++ Library file</B></TD><TD> | |
9431 | <B>SWIG Interface library file</B></TD></TR> | |
9432 | <TR><TD>std::deque</TD><TD>deque</TD><TD>std_deque.i</TD></TR> | |
9433 | <TR><TD>std::list</TD><TD>list</TD><TD>std_list.i</TD></TR> | |
9434 | <TR><TD>std::map</TD><TD>map</TD><TD>std_map.i</TD></TR> | |
9435 | <TR><TD>std::pair</TD><TD>utility</TD><TD>std_pair.i</TD></TR> | |
9436 | <TR><TD>std::set</TD><TD>set</TD><TD>std_set.i</TD></TR> | |
9437 | <TR><TD>std::string</TD><TD>string</TD><TD>std_string.i</TD></TR> | |
9438 | <TR><TD>std::vector</TD><TD>vector</TD><TD>std_vector.i</TD></TR> | |
9439 | </TABLE> | |
9440 | <P> The list is by no means complete; some language modules support a | |
9441 | subset of the above and some support additional STL classes. Please | |
9442 | look for the library files in the appropriate language library | |
9443 | directory.</P> | |
9444 | <H3><A name="Library_nn14"></A>8.4.1 std_string.i</H3> | |
9445 | <P> The <TT>std_string.i</TT> library provides typemaps for converting | |
9446 | C++ <TT>std::string</TT> objects to and from strings in the target | |
9447 | scripting language. For example:</P> | |
9448 | <DIV class="code"> | |
9449 | <PRE> | |
9450 | %module example | |
9451 | %include "std_string.i" | |
9452 | ||
9453 | std::string foo(); | |
9454 | void bar(const std::string &x); | |
9455 | </PRE> | |
9456 | </DIV> | |
9457 | <P> In the target language:</P> | |
9458 | <DIV class="targetlang"> | |
9459 | <PRE> | |
9460 | x = foo(); # Returns a string object | |
9461 | bar("Hello World"); # Pass string as std::string | |
9462 | </PRE> | |
9463 | </DIV> | |
9464 | <P> This module only supports types <TT>std::string</TT> and <TT>const | |
9465 | std::string &</TT>. Pointers and non-const references are left | |
9466 | unmodified and returned as SWIG pointers.</P> | |
9467 | <P> This library file is fully aware of C++ namespaces. If you export <TT> | |
9468 | std::string</TT> or rename it with a typedef, make sure you include | |
9469 | those declarations in your interface. For example:</P> | |
9470 | <DIV class="code"> | |
9471 | <PRE> | |
9472 | %module example | |
9473 | %include "std_string.i" | |
9474 | ||
9475 | using namespace std; | |
9476 | typedef std::string String; | |
9477 | ... | |
9478 | void foo(string s, const String &t); // std_string typemaps still applied | |
9479 | </PRE> | |
9480 | </DIV> | |
9481 | <P><B> Note:</B> The <TT>std_string</TT> library is incompatible with | |
9482 | Perl on some platforms. We're looking into it.</P> | |
9483 | <H3><A name="Library_nn15"></A>8.4.2 std_vector.i</H3> | |
9484 | <P> The <TT>std_vector.i</TT> library provides support for the C++ <TT> | |
9485 | vector</TT> class in the STL. Using this library involves the use of the | |
9486 | <TT>%template</TT> directive. All you need to do is to instantiate | |
9487 | different versions of <TT>vector</TT> for the types that you want to | |
9488 | use. For example:</P> | |
9489 | <DIV class="code"> | |
9490 | <PRE> | |
9491 | %module example | |
9492 | %include "std_vector.i" | |
9493 | ||
9494 | namespace std { | |
9495 | %template(vectori) vector<int>; | |
9496 | %template(vectord) vector<double>; | |
9497 | }; | |
9498 | </PRE> | |
9499 | </DIV> | |
9500 | <P> When a template <TT>vector<X></TT> is instantiated a number of | |
9501 | things happen:</P> | |
9502 | <UL> | |
9503 | <LI>A class that exposes the C++ API is created in the target language . | |
9504 | This can be used to create objects, invoke methods, etc. This class is | |
9505 | currently a subset of the real STL vector class.</LI> | |
9506 | <LI>Input typemaps are defined for <TT>vector<X></TT>, <TT>const | |
9507 | vector<X> &</TT>, and <TT>const vector<X> *</TT>. For each of these, a | |
9508 | pointer <TT>vector<X> *</TT> may be passed or a native list object in | |
9509 | the target language.</LI> | |
9510 | <LI>An output typemap is defined for <TT>vector<X></TT>. In this case, | |
9511 | the values in the vector are expanded into a list object in the target | |
9512 | language.</LI> | |
9513 | <LI>For all other variations of the type, the wrappers expect to receive | |
9514 | a <TT>vector<X> *</TT> object in the usual manner.</LI> | |
9515 | <LI>An exception handler for <TT>std::out_of_range</TT> is defined.</LI> | |
9516 | <LI>Optionally, special methods for indexing, item retrieval, slicing, | |
9517 | and element assignment may be defined. This depends on the target | |
9518 | language.</LI> | |
9519 | </UL> | |
9520 | <P> To illustrate the use of this library, consider the following | |
9521 | functions:</P> | |
9522 | <DIV class="code"> | |
9523 | <PRE> | |
9524 | /* File : example.h */ | |
9525 | ||
9526 | #include <vector> | |
9527 | #include <algorithm> | |
9528 | #include <functional> | |
9529 | #include <numeric> | |
9530 | ||
9531 | double average(std::vector<int> v) { | |
9532 | return std::accumulate(v.begin(),v.end(),0.0)/v.size(); | |
9533 | } | |
9534 | ||
9535 | std::vector<double> half(const std::vector<double>& v) { | |
9536 | std::vector<double> w(v); | |
9537 | for (unsigned int i=0; i<w.size(); i++) | |
9538 | w[i] /= 2.0; | |
9539 | return w; | |
9540 | } | |
9541 | ||
9542 | void halve_in_place(std::vector<double>& v) { | |
9543 | std::transform(v.begin(),v.end(),v.begin(), | |
9544 | std::bind2nd(std::divides<double>(),2.0)); | |
9545 | } | |
9546 | </PRE> | |
9547 | </DIV> | |
9548 | <P> To wrap with SWIG, you might write the following:</P> | |
9549 | <DIV class="code"> | |
9550 | <PRE> | |
9551 | %module example | |
9552 | %{ | |
9553 | #include "example.h" | |
9554 | %} | |
9555 | ||
9556 | %include "std_vector.i" | |
9557 | // Instantiate templates used by example | |
9558 | namespace std { | |
9559 | %template(IntVector) vector<int>; | |
9560 | %template(DoubleVector) vector<double>; | |
9561 | } | |
9562 | ||
9563 | // Include the header file with above prototypes | |
9564 | %include "example.h" | |
9565 | </PRE> | |
9566 | </DIV> | |
9567 | <P> Now, to illustrate the behavior in the scripting interpreter, | |
9568 | consider this Python example:</P> | |
9569 | <DIV class="targetlang"> | |
9570 | <PRE> | |
9571 | >>> from example import * | |
9572 | >>> iv = IntVector(4) # Create an vector<int> | |
9573 | >>> for i in range(0,4): | |
9574 | ... iv[i] = i | |
9575 | >>> average(iv) # Call method | |
9576 | 1.5 | |
9577 | >>> average([0,1,2,3]) # Call with list | |
9578 | 1.5 | |
9579 | >>> half([1,2,3]) # Half a list | |
9580 | (0.5,1.0,1.5) | |
9581 | >>> halve_in_place([1,2,3]) # Oops | |
9582 | Traceback (most recent call last): | |
9583 | File "<stdin>", line 1, in ? | |
9584 | TypeError: Type error. Expected _p_std__vectorTdouble_t | |
9585 | >>> dv = DoubleVector(4) | |
9586 | >>> for i in range(0,4): | |
9587 | ... dv[i] = i | |
9588 | >>> halve_in_place(dv) # Ok | |
9589 | >>> for i in dv: | |
9590 | ... print i | |
9591 | ... | |
9592 | 0.0 | |
9593 | 0.5 | |
9594 | 1.0 | |
9595 | 1.5 | |
9596 | >>> dv[20] = 4.5 | |
9597 | Traceback (most recent call last): | |
9598 | File "<stdin>", line 1, in ? | |
9599 | File "example.py", line 81, in __setitem__ | |
9600 | def __setitem__(*args): return apply(examplec.DoubleVector___setitem__,args) | |
9601 | IndexError: vector index out of range | |
9602 | >>> | |
9603 | </PRE> | |
9604 | </DIV> | |
9605 | <P> This library module is fully aware of C++ namespaces. If you use | |
9606 | vectors with other names, make sure you include the appropriate <TT> | |
9607 | using</TT> or typedef directives. For example:</P> | |
9608 | <DIV class="code"> | |
9609 | <PRE> | |
9610 | %include "std_vector.i" | |
9611 | ||
9612 | namespace std { | |
9613 | %template(IntVector) vector<int>; | |
9614 | } | |
9615 | ||
9616 | using namespace std; | |
9617 | typedef std::vector Vector; | |
9618 | ||
9619 | void foo(vector<int> *x, const Vector &x); | |
9620 | </PRE> | |
9621 | </DIV> | |
9622 | <P><B> Note:</B> This module makes use of several advanced SWIG features | |
9623 | including templatized typemaps and template partial specialization. If | |
9624 | you are tring to wrap other C++ code with templates, you might look at | |
9625 | the code contained in <TT>std_vector.i</TT>. Alternatively, you can | |
9626 | show them the code if you want to make their head explode.</P> | |
9627 | <P><B> Note:</B> This module is defined for all SWIG target languages. | |
9628 | However argument conversion details and the public API exposed to the | |
9629 | interpreter vary.</P> | |
9630 | <P><B> Note:</B> <TT>std_vector.i</TT> was written by Luigi "The | |
9631 | Amazing" Ballabio.</P> | |
9632 | <H3><A name="Library_stl_exceptions"></A>8.4.3 STL exceptions</H3> | |
9633 | <P> Many of the STL wrapper functions add parameter checking and will | |
9634 | throw a language dependent error/exception should the values not be | |
9635 | valid. The classic example is array bounds checking. The library | |
9636 | wrappers are written to throw a C++ exception in the case of error. The | |
9637 | C++ exception in turn gets converted into an appropriate | |
9638 | error/exception for the target language. By and large this handling | |
9639 | should not need customising, however, customisation can easily be | |
9640 | achieved by supplying appropriate "throws" typemaps. For example:</P> | |
9641 | <DIV class="code"> | |
9642 | <PRE> | |
9643 | %module example | |
9644 | %include "std_vector.i" | |
9645 | %typemap(throws) std::out_of_range { | |
9646 | // custom exception handler | |
9647 | } | |
9648 | %template(VectInt) std::vector<int>; | |
9649 | </PRE> | |
9650 | </DIV> | |
9651 | <P> The custom exception handler might, for example, log the exception | |
9652 | then convert it into a specific error/exception for the target | |
9653 | language.</P> | |
9654 | <P> When using the STL it is advisable to add in an exception handler to | |
9655 | catch all STL exceptions. The <TT>%exception</TT> directive can be used | |
9656 | by placing the following code before any other methods or libraries to | |
9657 | be wrapped:</P> | |
9658 | <DIV class="code"> | |
9659 | <PRE> | |
9660 | %include "exception.i" | |
9661 | ||
9662 | %exception { | |
9663 | try { | |
9664 | $action | |
9665 | } catch (const std::exception& e) { | |
9666 | SWIG_exception(SWIG_RuntimeError, e.what()); | |
9667 | } | |
9668 | } | |
9669 | </PRE> | |
9670 | </DIV> | |
9671 | <P> Any thrown STL exceptions will then be gracefully handled instead of | |
9672 | causing a crash.</P> | |
9673 | <H2><A name="Library_nn16"></A>8.5 Utility Libraries</H2> | |
9674 | <H3><A name="Library_nn17"></A>8.5.1 exception.i</H3> | |
9675 | <P> The <TT>exception.i</TT> library provides a language-independent | |
9676 | function for raising a run-time exception in the target language. This | |
9677 | library is largely used by the SWIG library writers. If possible, use | |
9678 | the error handling scheme available to your target language as there is | |
9679 | greater flexibility in what errors/exceptions can be thrown.</P> | |
9680 | <P><B> <TT>SWIG_exception(int code, const char *message)</TT></B></P> | |
9681 | <DIV class="indent"> | |
9682 | <P> Raises an exception in the target language. <TT>code</TT> is one of | |
9683 | the following symbolic constants:</P> | |
9684 | <DIV class="code"> | |
9685 | <PRE> | |
9686 | SWIG_MemoryError | |
9687 | SWIG_IOError | |
9688 | SWIG_RuntimeError | |
9689 | SWIG_IndexError | |
9690 | SWIG_TypeError | |
9691 | SWIG_DivisionByZero | |
9692 | SWIG_OverflowError | |
9693 | SWIG_SyntaxError | |
9694 | SWIG_ValueError | |
9695 | SWIG_SystemError | |
9696 | </PRE> | |
9697 | </DIV> | |
9698 | <P> <TT>message</TT> is a string indicating more information about the | |
9699 | problem.</P> | |
9700 | </DIV> | |
9701 | <P> The primary use of this module is in writing language-independent | |
9702 | exception handlers. For example:</P> | |
9703 | <DIV class="code"> | |
9704 | <PRE> | |
9705 | %include "exception.i" | |
9706 | %exception std::vector::getitem { | |
9707 | try { | |
9708 | $action | |
9709 | } catch (std::out_of_range& e) { | |
9710 | SWIG_exception(SWIG_IndexError,const_cast<char*>(e.what())); | |
9711 | } | |
9712 | } | |
9713 | </PRE> | |
9714 | </DIV><HR NOSHADE> | |
9715 | <H1><A name="Arguments"></A>9 Argument Handling</H1> | |
9716 | ||
9717 | <!-- INDEX --> | |
9718 | <DIV class="sectiontoc"> | |
9719 | <UL> | |
9720 | <LI><A href="#Arguments_nn2">The typemaps.i library</A> | |
9721 | <UL> | |
9722 | <LI><A href="#Arguments_nn3">Introduction</A></LI> | |
9723 | <LI><A href="#Arguments_nn4">Input parameters</A></LI> | |
9724 | <LI><A href="#Arguments_nn5">Output parameters</A></LI> | |
9725 | <LI><A href="#Arguments_nn6">Input/Output parameters</A></LI> | |
9726 | <LI><A href="#Arguments_nn7">Using different names</A></LI> | |
9727 | </UL> | |
9728 | </LI> | |
9729 | <LI><A href="#Arguments_nn8">Applying constraints to input values</A> | |
9730 | <UL> | |
9731 | <LI><A href="#Arguments_nn9">Simple constraint example</A></LI> | |
9732 | <LI><A href="#Arguments_nn10">Constraint methods</A></LI> | |
9733 | <LI><A href="#Arguments_nn11">Applying constraints to new datatypes</A></LI> | |
9734 | </UL> | |
9735 | </LI> | |
9736 | </UL> | |
9737 | </DIV> | |
9738 | <!-- INDEX --> | |
9739 | <B> Disclaimer: This chapter is under construction.</B> | |
9740 | <P> In Chapter 3, SWIG's treatment of basic datatypes and pointers was | |
9741 | described. In particular, primitive types such as <TT>int</TT> and <TT> | |
9742 | double</TT> are mapped to corresponding types in the target language. | |
9743 | For everything else, pointers are used to refer to structures, classes, | |
9744 | arrays, and other user-defined datatypes. However, in certain | |
9745 | applications it is desirable to change SWIG's handling of a specific | |
9746 | datatype. For example, you might want to return multiple values through | |
9747 | the arguments of a function. This chapter describes some of the | |
9748 | techniques for doing this.</P> | |
9749 | <H2><A name="Arguments_nn2"></A>9.1 The typemaps.i library</H2> | |
9750 | <P> This section describes the <TT>typemaps.i</TT> library | |
9751 | file--commonly used to change certain properties of argument | |
9752 | conversion.</P> | |
9753 | <H3><A name="Arguments_nn3"></A>9.1.1 Introduction</H3> | |
9754 | <P> Suppose you had a C function like this:</P> | |
9755 | <DIV class="code"> | |
9756 | <PRE> | |
9757 | void add(double a, double b, double *result) { | |
9758 | *result = a + b; | |
9759 | } | |
9760 | </PRE> | |
9761 | </DIV> | |
9762 | <P> From reading the source code, it is clear that the function is | |
9763 | storing a value in the <TT>double *result</TT> parameter. However, | |
9764 | since SWIG does not examine function bodies, it has no way to know that | |
9765 | this is the underlying behavior.</P> | |
9766 | <P> One way to deal with this is to use the <TT>typemaps.i</TT> library | |
9767 | file and write interface code like this:</P> | |
9768 | <DIV class="code"> | |
9769 | <PRE> | |
9770 | // Simple example using typemaps | |
9771 | %module example | |
9772 | %include "typemaps.i" | |
9773 | ||
9774 | %apply double *OUTPUT { double *result }; | |
9775 | %inlne %{ | |
9776 | extern void add(double a, double b, double *result); | |
9777 | %} | |
9778 | </PRE> | |
9779 | </DIV> | |
9780 | <P> The <TT>%apply</TT> directive tells SWIG that you are going to apply | |
9781 | a special type handling rule to a type. The "<TT>double *OUTPUT</TT>" | |
9782 | specification is the name of a rule that defines how to return an | |
9783 | output value from an argument of type <TT>double *</TT>. This rule gets | |
9784 | applied to all of the datatypes listed in curly braces-- in this case "<TT> | |
9785 | double *result</TT>".</P> | |
9786 | <P> When the resulting module is created, you can now use the function | |
9787 | like this (shown for Python):</P> | |
9788 | <DIV class="targetlang"> | |
9789 | <PRE> | |
9790 | >>> a = add(3,4) | |
9791 | >>> print a | |
9792 | 7 | |
9793 | >>> | |
9794 | </PRE> | |
9795 | </DIV> | |
9796 | <P> In this case, you can see how the output value normally returned in | |
9797 | the third argument has magically been transformed into a function | |
9798 | return value. Clearly this makes the function much easier to use since | |
9799 | it is no longer necessary to manufacture a special <TT>double *</TT> | |
9800 | object and pass it to the function somehow.</P> | |
9801 | <P> Once a typemap has been applied to a type, it stays in effect for | |
9802 | all future occurrences of the type and name. For example, you could | |
9803 | write the following:</P> | |
9804 | <DIV class="code"> | |
9805 | <PRE> | |
9806 | %module example | |
9807 | %include "typemaps.i" | |
9808 | ||
9809 | %apply double *OUTPUT { double *result }; | |
9810 | ||
9811 | %inline %{ | |
9812 | extern void add(double a, double b, double *result); | |
9813 | extern void sub(double a, double b, double *result); | |
9814 | extern void mul(double a, double b, double *result); | |
9815 | extern void div(double a, double b, double *result); | |
9816 | %} | |
9817 | ... | |
9818 | </PRE> | |
9819 | </DIV> | |
9820 | <P> In this case, the <TT>double *OUTPUT</TT> rule is applied to all of | |
9821 | the functions that follow.</P> | |
9822 | <P> Typemap transformations can even be extended to multiple return | |
9823 | values. For example, consider this code:</P> | |
9824 | <DIV class="code"> | |
9825 | <PRE> | |
9826 | %include "typemaps.i" | |
9827 | %apply int *OUTPUT { int *width, int *height }; | |
9828 | ||
9829 | // Returns a pair (width,height) | |
9830 | void getwinsize(int winid, int *width, int *height); | |
9831 | </PRE> | |
9832 | </DIV> | |
9833 | <P> In this case, the function returns multiple values, allowing it to | |
9834 | be used like this:</P> | |
9835 | <DIV class="targetlang"> | |
9836 | <PRE> | |
9837 | >>> w,h = genwinsize(wid) | |
9838 | >>> print w | |
9839 | 400 | |
9840 | >>> print h | |
9841 | 300 | |
9842 | >>> | |
9843 | </PRE> | |
9844 | </DIV> | |
9845 | <P> It should also be noted that although the <TT>%apply</TT> directive | |
9846 | is used to associate typemap rules to datatypes, you can also use the | |
9847 | rule names directly in arguments. For example, you could write this:</P> | |
9848 | <DIV class="code"> | |
9849 | <PRE> | |
9850 | // Simple example using typemaps | |
9851 | %module example | |
9852 | %include "typemaps.i" | |
9853 | ||
9854 | %{ | |
9855 | extern void add(double a, double b, double *OUTPUT); | |
9856 | %} | |
9857 | extern void add(double a, double b, double *OUTPUT); | |
9858 | </PRE> | |
9859 | </DIV> | |
9860 | <P> Typemaps stay in effect until they are explicitly deleted or | |
9861 | redefined to something else. To clear a typemap, the <TT>%clear</TT> | |
9862 | directive should be used. For example:</P> | |
9863 | <DIV class="code"> | |
9864 | <PRE> | |
9865 | %clear double *result; // Remove all typemaps for double *result | |
9866 | </PRE> | |
9867 | </DIV> | |
9868 | <H3><A name="Arguments_nn4"></A>9.1.2 Input parameters</H3> | |
9869 | <P> The following typemaps instruct SWIG that a pointer really only | |
9870 | holds a single input value:</P> | |
9871 | <DIV class="code"> | |
9872 | <PRE> | |
9873 | int *INPUT | |
9874 | short *INPUT | |
9875 | long *INPUT | |
9876 | unsigned int *INPUT | |
9877 | unsigned short *INPUT | |
9878 | unsigned long *INPUT | |
9879 | double *INPUT | |
9880 | float *INPUT | |
9881 | </PRE> | |
9882 | </DIV> | |
9883 | <P> When used, it allows values to be passed instead of pointers. For | |
9884 | example, consider this function:</P> | |
9885 | <DIV class="code"> | |
9886 | <PRE> | |
9887 | double add(double *a, double *b) { | |
9888 | return *a+*b; | |
9889 | } | |
9890 | </PRE> | |
9891 | </DIV> | |
9892 | <P> Now, consider this SWIG interface:</P> | |
9893 | <DIV class="code"> | |
9894 | <PRE> | |
9895 | %module example | |
9896 | %include "typemaps.i" | |
9897 | ... | |
9898 | %{ | |
9899 | extern double add(double *, double *); | |
9900 | %} | |
9901 | extern double add(double *INPUT, double *INPUT); | |
9902 | ||
9903 | </PRE> | |
9904 | </DIV> | |
9905 | <P> When the function is used in the scripting language interpreter, it | |
9906 | will work like this:</P> | |
9907 | <DIV class="targetlang"> | |
9908 | <PRE> | |
9909 | result = add(3,4) | |
9910 | </PRE> | |
9911 | </DIV> | |
9912 | <H3><A name="Arguments_nn5"></A>9.1.3 Output parameters</H3> | |
9913 | <P> The following typemap rules tell SWIG that pointer is the output | |
9914 | value of a function. When used, you do not need to supply the argument | |
9915 | when calling the function. Instead, one or more output values are | |
9916 | returned.</P> | |
9917 | <DIV class="code"> | |
9918 | <PRE> | |
9919 | int *OUTPUT | |
9920 | short *OUTPUT | |
9921 | long *OUTPUT | |
9922 | unsigned int *OUTPUT | |
9923 | unsigned short *OUTPUT | |
9924 | unsigned long *OUTPUT | |
9925 | double *OUTPUT | |
9926 | float *OUTPUT | |
9927 | ||
9928 | </PRE> | |
9929 | </DIV> | |
9930 | <P> These methods can be used as shown in an earlier example. For | |
9931 | example, if you have this C function :</P> | |
9932 | <DIV class="code"> | |
9933 | <PRE> | |
9934 | void add(double a, double b, double *c) { | |
9935 | *c = a+b; | |
9936 | } | |
9937 | </PRE> | |
9938 | </DIV> | |
9939 | <P> A SWIG interface file might look like this :</P> | |
9940 | <DIV class="code"> | |
9941 | <PRE> | |
9942 | %module example | |
9943 | %include "typemaps.i" | |
9944 | ... | |
9945 | %inline %{ | |
9946 | extern void add(double a, double b, double *OUTPUT); | |
9947 | %} | |
9948 | ||
9949 | </PRE> | |
9950 | </DIV> | |
9951 | <P> In this case, only a single output value is returned, but this is | |
9952 | not a restriction. An arbitrary number of output values can be returned | |
9953 | by applying the output rules to more than one argument (as shown | |
9954 | previously).</P> | |
9955 | <P> If the function also returns a value, it is returned along with the | |
9956 | argument. For example, if you had this:</P> | |
9957 | <DIV class="code"> | |
9958 | <PRE> | |
9959 | extern int foo(double a, double b, double *OUTPUT); | |
9960 | </PRE> | |
9961 | </DIV> | |
9962 | <P> The function will return two values like this:</P> | |
9963 | <DIV class="targetlang"> | |
9964 | <PRE> | |
9965 | iresult, dresult = foo(3.5, 2) | |
9966 | </PRE> | |
9967 | </DIV> | |
9968 | <H3><A name="Arguments_nn6"></A>9.1.4 Input/Output parameters</H3> | |
9969 | <P> When a pointer serves as both an input and output value you can use | |
9970 | the following typemaps :</P> | |
9971 | <DIV class="code"> | |
9972 | <PRE> | |
9973 | int *INOUT | |
9974 | short *INOUT | |
9975 | long *INOUT | |
9976 | unsigned int *INOUT | |
9977 | unsigned short *INOUT | |
9978 | unsigned long *INOUT | |
9979 | double *INOUT | |
9980 | float *INOUT | |
9981 | ||
9982 | </PRE> | |
9983 | </DIV> | |
9984 | <P> A C function that uses this might be something like this:</P> | |
9985 | <DIV class="code"> | |
9986 | <PRE> | |
9987 | void negate(double *x) { | |
9988 | *x = -(*x); | |
9989 | } | |
9990 | ||
9991 | </PRE> | |
9992 | </DIV> | |
9993 | <P> To make x function as both and input and output value, declare the | |
9994 | function like this in an interface file :</P> | |
9995 | <DIV class="code"> | |
9996 | <PRE> | |
9997 | %module example | |
9998 | %include typemaps.i | |
9999 | ... | |
10000 | %{ | |
10001 | extern void negate(double *); | |
10002 | %} | |
10003 | extern void negate(double *INOUT); | |
10004 | ||
10005 | </PRE> | |
10006 | </DIV> | |
10007 | <P> Now within a script, you can simply call the function normally :</P> | |
10008 | <DIV class="targetlang"> | |
10009 | <PRE> | |
10010 | a = negate(3); # a = -3 after calling this | |
10011 | </PRE> | |
10012 | </DIV> | |
10013 | <P> One subtle point of the <TT>INOUT</TT> rule is that many scripting | |
10014 | languages enforce mutability constraints on primitive objects (meaning | |
10015 | that simple objects like integers and strings aren't supposed to | |
10016 | change). Because of this, you can't just modify the object's value in | |
10017 | place as the underlying C function does in this example. Therefore, the | |
10018 | <TT>INOUT</TT> rule returns the modified value as a new object rather | |
10019 | than directly overwriting the value of the original input object.</P> | |
10020 | <P><B> Compatibility note :</B> The <TT>INOUT</TT> rule used to be known | |
10021 | as <TT>BOTH</TT> in earlier versions of SWIG. Backwards compatibility | |
10022 | is preserved, but deprecated.</P> | |
10023 | <H3><A name="Arguments_nn7"></A>9.1.5 Using different names</H3> | |
10024 | <P> As previously shown, the <TT>%apply</TT> directive can be used to | |
10025 | apply the <TT>INPUT</TT>, <TT>OUTPUT</TT>, and <TT>INOUT</TT> typemaps | |
10026 | to different argument names. For example:</P> | |
10027 | <DIV class="code"> | |
10028 | <PRE> | |
10029 | // Make double *result an output value | |
10030 | %apply double *OUTPUT { double *result }; | |
10031 | ||
10032 | // Make Int32 *in an input value | |
10033 | %apply int *INPUT { Int32 *in }; | |
10034 | ||
10035 | // Make long *x inout | |
10036 | %apply long *INOUT {long *x}; | |
10037 | ||
10038 | </PRE> | |
10039 | </DIV> | |
10040 | <P> To clear a rule, the <TT>%clear</TT> directive is used:</P> | |
10041 | <DIV class="code"> | |
10042 | <PRE> | |
10043 | %clear double *result; | |
10044 | %clear Int32 *in, long *x; | |
10045 | </PRE> | |
10046 | </DIV> | |
10047 | <P> Typemap declarations are lexically scoped so a typemap takes effect | |
10048 | from the point of definition to the end of the file or a matching <TT> | |
10049 | %clear</TT> declaration.</P> | |
10050 | <H2><A name="Arguments_nn8"></A>9.2 Applying constraints to input values</H2> | |
10051 | <P> In addition to changing the handling of various input values, it is | |
10052 | also possible to use typemaps to apply constraints. For example, maybe | |
10053 | you want to insure that a value is positive, or that a pointer is | |
10054 | non-NULL. This can be accomplished including the <TT>constraints.i</TT> | |
10055 | library file.</P> | |
10056 | <H3><A name="Arguments_nn9"></A>9.2.1 Simple constraint example</H3> | |
10057 | <P> The constraints library is best illustrated by the following | |
10058 | interface file :</P> | |
10059 | <DIV class="code"> | |
10060 | <PRE> | |
10061 | // Interface file with constraints | |
10062 | %module example | |
10063 | %include "constraints.i" | |
10064 | ||
10065 | double exp(double x); | |
10066 | double log(double POSITIVE); // Allow only positive values | |
10067 | double sqrt(double NONNEGATIVE); // Non-negative values only | |
10068 | double inv(double NONZERO); // Non-zero values | |
10069 | void free(void *NONNULL); // Non-NULL pointers only | |
10070 | ||
10071 | </PRE> | |
10072 | </DIV> | |
10073 | <P> The behavior of this file is exactly as you would expect. If any of | |
10074 | the arguments violate the constraint condition, a scripting language | |
10075 | exception will be raised. As a result, it is possible to catch bad | |
10076 | values, prevent mysterious program crashes and so on.</P> | |
10077 | <H3><A name="Arguments_nn10"></A>9.2.2 Constraint methods</H3> | |
10078 | <P> The following constraints are currently available</P> | |
10079 | <DIV class="code"> | |
10080 | <PRE> | |
10081 | POSITIVE Any number > 0 (not zero) | |
10082 | NEGATIVE Any number < 0 (not zero) | |
10083 | NONNEGATIVE Any number >= 0 | |
10084 | NONPOSITIVE Any number <= 0 | |
10085 | NONZERO Nonzero number | |
10086 | NONNULL Non-NULL pointer (pointers only). | |
10087 | ||
10088 | </PRE> | |
10089 | </DIV> | |
10090 | <H3><A name="Arguments_nn11"></A>9.2.3 Applying constraints to new | |
10091 | datatypes</H3> | |
10092 | <P> The constraints library only supports the primitive C datatypes, but | |
10093 | it is easy to apply it to new datatypes using <TT>%apply</TT>. For | |
10094 | example :</P> | |
10095 | <DIV class="code"> | |
10096 | <PRE> | |
10097 | // Apply a constraint to a Real variable | |
10098 | %apply Number POSITIVE { Real in }; | |
10099 | ||
10100 | // Apply a constraint to a pointer type | |
10101 | %apply Pointer NONNULL { Vector * }; | |
10102 | ||
10103 | </PRE> | |
10104 | </DIV> | |
10105 | <P> The special types of "Number" and "Pointer" can be applied to any | |
10106 | numeric and pointer variable type respectively. To later remove a | |
10107 | constraint, the <TT>%clear</TT> directive can be used :</P> | |
10108 | <DIV class="code"> | |
10109 | <PRE> | |
10110 | %clear Real in; | |
10111 | %clear Vector *; | |
10112 | </PRE> | |
10113 | </DIV><HR NOSHADE> | |
10114 | <H1><A name="Typemaps"></A>10 Typemaps</H1> | |
10115 | ||
10116 | <!-- INDEX --> | |
10117 | <DIV class="sectiontoc"> | |
10118 | <UL> | |
10119 | <LI><A href="#Typemaps_nn2">Introduction</A> | |
10120 | <UL> | |
10121 | <LI><A href="#Typemaps_nn3">Type conversion</A></LI> | |
10122 | <LI><A href="#Typemaps_nn4">Typemaps</A></LI> | |
10123 | <LI><A href="#Typemaps_nn5">Pattern matching</A></LI> | |
10124 | <LI><A href="#Typemaps_nn6">Reusing typemaps</A></LI> | |
10125 | <LI><A href="#Typemaps_nn7">What can be done with typemaps?</A></LI> | |
10126 | <LI><A href="#Typemaps_nn8">What can't be done with typemaps?</A></LI> | |
10127 | <LI><A href="#Typemaps_nn9">The rest of this chapter</A></LI> | |
10128 | </UL> | |
10129 | </LI> | |
10130 | <LI><A href="#Typemaps_nn10">Typemap specifications</A> | |
10131 | <UL> | |
10132 | <LI><A href="#Typemaps_nn11">Defining a typemap</A></LI> | |
10133 | <LI><A href="#Typemaps_nn12">Typemap scope</A></LI> | |
10134 | <LI><A href="#Typemaps_nn13">Copying a typemap</A></LI> | |
10135 | <LI><A href="#Typemaps_nn14">Deleting a typemap</A></LI> | |
10136 | <LI><A href="#Typemaps_nn15">Placement of typemaps</A></LI> | |
10137 | </UL> | |
10138 | </LI> | |
10139 | <LI><A href="#Typemaps_nn16">Pattern matching rules</A> | |
10140 | <UL> | |
10141 | <LI><A href="#Typemaps_nn17">Basic matching rules</A></LI> | |
10142 | <LI><A href="#Typemaps_nn18">Typedef reductions</A></LI> | |
10143 | <LI><A href="#Typemaps_nn19">Default typemaps</A></LI> | |
10144 | <LI><A href="#Typemaps_mixed_default">Mixed default typemaps</A></LI> | |
10145 | <LI><A href="#Typemaps_nn20">Multi-arguments typemaps</A></LI> | |
10146 | </UL> | |
10147 | </LI> | |
10148 | <LI><A href="#Typemaps_nn21">Code generation rules</A> | |
10149 | <UL> | |
10150 | <LI><A href="#Typemaps_nn22">Scope</A></LI> | |
10151 | <LI><A href="#Typemaps_nn23">Declaring new local variables</A></LI> | |
10152 | <LI><A href="#Typemaps_nn24">Special variables</A></LI> | |
10153 | </UL> | |
10154 | </LI> | |
10155 | <LI><A href="#Typemaps_nn25">Common typemap methods</A> | |
10156 | <UL> | |
10157 | <LI><A href="#Typemaps_nn26">"in" typemap</A></LI> | |
10158 | <LI><A href="#Typemaps_nn27">"typecheck" typemap</A></LI> | |
10159 | <LI><A href="#Typemaps_nn28">"out" typemap</A></LI> | |
10160 | <LI><A href="#Typemaps_nn29">"arginit" typemap</A></LI> | |
10161 | <LI><A href="#Typemaps_nn30">"default" typemap</A></LI> | |
10162 | <LI><A href="#Typemaps_nn31">"check" typemap</A></LI> | |
10163 | <LI><A href="#Typemaps_nn32">"argout" typemap</A></LI> | |
10164 | <LI><A href="#Typemaps_nn33">"freearg" typemap</A></LI> | |
10165 | <LI><A href="#Typemaps_nn34">"newfree" typemap</A></LI> | |
10166 | <LI><A href="#Typemaps_nn35">"memberin" typemap</A></LI> | |
10167 | <LI><A href="#Typemaps_nn36">"varin" typemap</A></LI> | |
10168 | <LI><A href="#Typemaps_nn37">"varout" typemap</A></LI> | |
10169 | <LI><A href="#throws_typemap">"throws" typemap</A></LI> | |
10170 | </UL> | |
10171 | </LI> | |
10172 | <LI><A href="#Typemaps_nn39">Some typemap examples</A> | |
10173 | <UL> | |
10174 | <LI><A href="#Typemaps_nn40">Typemaps for arrays</A></LI> | |
10175 | <LI><A href="#Typemaps_nn41">Implementing constraints with typemaps</A></LI> | |
10176 | </UL> | |
10177 | </LI> | |
10178 | <LI><A href="#Typemaps_nn42">Multi-argument typemaps</A></LI> | |
10179 | <LI><A href="#runtime_type_checker">The run-time type checker</A> | |
10180 | <UL> | |
10181 | <LI><A href="#Typemaps_nn45">Implementation</A></LI> | |
10182 | <LI><A href="#Typemaps_nn46">Usage</A></LI> | |
10183 | </UL> | |
10184 | </LI> | |
10185 | <LI><A href="#Typemaps_overloading">Typemaps and overloading</A></LI> | |
10186 | <LI><A href="#Typemaps_nn48">More about <TT>%apply</TT> and <TT>%clear</TT> | |
10187 | </A></LI> | |
10188 | <LI><A href="#Typemaps_nn49">Reducing wrapper code size</A></LI> | |
10189 | <LI><A href="#Typemaps_nn47">Passing data between typemaps</A></LI> | |
10190 | <LI><A href="#Typemaps_nn51">Where to go for more information?</A></LI> | |
10191 | </UL> | |
10192 | </DIV> | |
10193 | <!-- INDEX --> | |
10194 | <P><B> Disclaimer: This chapter is under construction!</B></P> | |
10195 | <H2><A name="Typemaps_nn2"></A>10.1 Introduction</H2> | |
10196 | <P> Chances are, you are reading this chapter for one of two reasons; | |
10197 | you either want to customize SWIG's behavior or you overheard someone | |
10198 | mumbling some incomprehensible drivel about "typemaps" and you asked | |
10199 | yourself "typemaps, what are those?" That said, let's start with a | |
10200 | short disclaimer that "typemaps" are an advanced customization feature | |
10201 | that provide direct access to SWIG's low-level code generator. Not only | |
10202 | that, they are an integral part of the SWIG C++ type system (a | |
10203 | non-trivial topic of its own). Typemaps are generally<EM> not</EM> a | |
10204 | required part of using SWIG. Therefore, you might want to re-read the | |
10205 | earlier chapters if you have found your way to this chapter with only a | |
10206 | vaque idea of what SWIG already does by default.</P> | |
10207 | <H3><A name="Typemaps_nn3"></A>10.1.1 Type conversion</H3> | |
10208 | <P> One of the most important problems in wrapper code generation is the | |
10209 | conversion of datatypes between programming languages. Specifically, | |
10210 | for every C/C++ declaration, SWIG must somehow generate wrapper code | |
10211 | that allows values to be passed back and forth between languages. Since | |
10212 | every programming language represents data differently, this is not a | |
10213 | simple of matter of simply linking code together with the C linker. | |
10214 | Instead, SWIG has to know something about how data is represented in | |
10215 | each language and how it can be manipulated.</P> | |
10216 | <P> To illustrate, suppose you had a simple C function like this:</P> | |
10217 | <DIV class="code"> | |
10218 | <PRE> | |
10219 | int factorial(int n); | |
10220 | </PRE> | |
10221 | </DIV> | |
10222 | <P> To access this function from Python, a pair of Python API functions | |
10223 | are used to convert integer values. For example:</P> | |
10224 | <DIV class="code"> | |
10225 | <PRE> | |
10226 | long PyInt_AsLong(PyObject *obj); /* Python --> C */ | |
10227 | PyObject *PyInt_FromLong(long x); /* C --> Python */ | |
10228 | </PRE> | |
10229 | </DIV> | |
10230 | <P> The first function is used to convert the input argument from a | |
10231 | Python integer object to C <TT>long</TT>. The second function is used | |
10232 | to convert a value from C back into a Python integer object.</P> | |
10233 | <P> Inside the wrapper function, you might see these functions used like | |
10234 | this:</P> | |
10235 | <DIV class="code"> | |
10236 | <PRE> | |
10237 | PyObject *wrap_factorial(PyObject *self, PyObject *args) { | |
10238 | int arg1; | |
10239 | int result; | |
10240 | PyObject *obj1; | |
10241 | PyObject *resultobj; | |
10242 | ||
10243 | if (!PyArg_ParseTuple("O:factorial", &obj1)) return NULL; | |
10244 | <B>arg1 = PyInt_AsLong(obj1);</B> | |
10245 | result = factorial(arg1); | |
10246 | <B>resultobj = PyInt_FromLong(result);</B> | |
10247 | return resultobj; | |
10248 | } | |
10249 | </PRE> | |
10250 | </DIV> | |
10251 | <P> Every target language supported by SWIG has functions that work in a | |
10252 | similar manner. For example, in Perl, the following functions are used:</P> | |
10253 | <DIV class="code"> | |
10254 | <PRE> | |
10255 | IV SvIV(SV *sv); /* Perl --> C */ | |
10256 | void sv_setiv(SV *sv, IV val); /* C --> Perl */ | |
10257 | </PRE> | |
10258 | </DIV> | |
10259 | <P> In Tcl:</P> | |
10260 | <DIV class="code"> | |
10261 | <PRE> | |
10262 | int Tcl_GetLongFromObj(Tcl_Interp *interp, Tcl_Obj *obj, long *value); | |
10263 | Tcl_Obj *Tcl_NewIntObj(long value); | |
10264 | </PRE> | |
10265 | </DIV> | |
10266 | <P> The precise details are not so important. What is important is that | |
10267 | all of the underlying type conversion is handled by collections of | |
10268 | utility functions and short bits of C code like this---you simply have | |
10269 | to read the extension documentation for your favorite language to know | |
10270 | how it works (an exercise left to the reader).</P> | |
10271 | <H3><A name="Typemaps_nn4"></A>10.1.2 Typemaps</H3> | |
10272 | <P> Since type handling is so central to wrapper code generation, SWIG | |
10273 | allows it to be completely defined (or redefined) by the user. To do | |
10274 | this, a special <TT>%typemap</TT> directive is used. For example:</P> | |
10275 | <DIV class="code"> | |
10276 | <PRE> | |
10277 | /* Convert from Python --> C */ | |
10278 | %typemap(in) int { | |
10279 | $1 = PyInt_AsLong($input); | |
10280 | } | |
10281 | ||
10282 | /* Convert from C --> Python */ | |
10283 | %typemap(out) int { | |
10284 | $result = PyInt_FromLong($1); | |
10285 | } | |
10286 | </PRE> | |
10287 | </DIV> | |
10288 | <P> At first glance, this code will look a little confusing. However, | |
10289 | there is really not much to it. The first typemap (the "in" typemap) is | |
10290 | used to convert a value from the target language to C. The second | |
10291 | typemap (the "out" typemap) is used to convert in the other direction. | |
10292 | The content of each typemap is a small fragment of C code that is | |
10293 | inserted directly into the SWIG generated wrapper functions. Within | |
10294 | this code, a number of special variables prefixed with a $ are | |
10295 | expanded. These are really just placeholders for C variables that are | |
10296 | generated in the course of creating the wrapper function. In this case, | |
10297 | <TT>$input</TT> refers to an input object that needs to be converted to | |
10298 | C and <TT>$result</TT> refers to an object that is going to be returned | |
10299 | by a wrapper function. <TT>$1</TT> refers to a C variable that has the | |
10300 | same type as specified in the typemap declaration (an <TT>int</TT> in | |
10301 | this example).</P> | |
10302 | <P> A short example might make this a little more clear. If you were | |
10303 | wrapping a function like this:</P> | |
10304 | <DIV class="code"> | |
10305 | <PRE> | |
10306 | int gcd(int x, int y); | |
10307 | </PRE> | |
10308 | </DIV> | |
10309 | <P> A wrapper function would look approximately like this:</P> | |
10310 | <DIV class="code"> | |
10311 | <PRE> | |
10312 | PyObject *wrap_gcd(PyObject *self, PyObject *args) { | |
10313 | int arg1; | |
10314 | int arg2; | |
10315 | int result; | |
10316 | PyObject *obj1; | |
10317 | PyObject *obj2; | |
10318 | PyObject *resultobj; | |
10319 | ||
10320 | if (!PyArg_ParseTuple("OO:gcd", &obj1, &obj2)) return NULL; | |
10321 | ||
10322 | /* "in" typemap, argument 1 */<B> | |
10323 | { | |
10324 | arg1 = PyInt_AsLong(obj1); | |
10325 | } | |
10326 | </B> | |
10327 | /* "in" typemap, argument 2 */<B> | |
10328 | { | |
10329 | arg2 = PyInt_AsLong(obj2); | |
10330 | } | |
10331 | </B> | |
10332 | result = gcd(arg1,arg2); | |
10333 | ||
10334 | /* "out" typemap, return value */<B> | |
10335 | { | |
10336 | resultobj = PyInt_FromLong(result); | |
10337 | } | |
10338 | </B> | |
10339 | return resultobj; | |
10340 | } | |
10341 | </PRE> | |
10342 | </DIV> | |
10343 | <P> In this code, you can see how the typemap code has been inserted | |
10344 | into the function. You can also see how the special $ variables have | |
10345 | been expanded to match certain variable names inside the wrapper | |
10346 | function. This is really the whole idea behind typemaps--they simply | |
10347 | let you insert arbitrary code into different parts of the generated | |
10348 | wrapper functions. Because arbitrary code can be inserted, it possible | |
10349 | to completely change the way in which values are converted.</P> | |
10350 | <H3><A name="Typemaps_nn5"></A>10.1.3 Pattern matching</H3> | |
10351 | <P> As the name implies, the purpose of a typemap is to "map" C | |
10352 | datatypes to types in the target language. Once a typemap is defined | |
10353 | for a C datatype, it is applied to all future occurrences of that type | |
10354 | in the input file. For example:</P> | |
10355 | <DIV class="code"> | |
10356 | <PRE> | |
10357 | /* Convert from Perl --> C */ | |
10358 | %typemap(in) <B>int</B> { | |
10359 | $1 = SvIV($input); | |
10360 | } | |
10361 | ||
10362 | ... | |
10363 | int factorial(<B>int</B> n); | |
10364 | int gcd(<B>int</B> x, <B>int</B> y); | |
10365 | int count(char *s, char *t, <B>int</B> max); | |
10366 | </PRE> | |
10367 | </DIV> | |
10368 | <P> The matching of typemaps to C datatypes is more than a simple | |
10369 | textual match. In fact, typemaps are fully built into the underlying | |
10370 | type system. Therefore, typemaps are unaffected by <TT>typedef</TT>, | |
10371 | namespaces, and other declarations that might hide the underlying type. | |
10372 | For example, you could have code like this:</P> | |
10373 | <DIV class="code"> | |
10374 | <PRE> | |
10375 | /* Convert from Ruby--> C */ | |
10376 | %typemap(in) <B>int</B> { | |
10377 | $1 = NUM2INT($input); | |
10378 | } | |
10379 | ... | |
10380 | typedef int Integer; | |
10381 | namespace foo { | |
10382 | typedef Integer Number; | |
10383 | }; | |
10384 | ||
10385 | int foo(<B>int</B> x); | |
10386 | int bar(<B>Integer</B> y); | |
10387 | int spam(<B>foo::Number</B> a, <B>foo::Number</B> b); | |
10388 | </PRE> | |
10389 | </DIV> | |
10390 | <P> In this case, the typemap is still applied to the proper arguments | |
10391 | even though typenames don't always match the text "int". This ability | |
10392 | to track types is a critical part of SWIG--in fact, all of the target | |
10393 | language modules work merely define a set of typemaps for the basic | |
10394 | types. Yet, it is never necessary to write new typemaps for typenames | |
10395 | introduced by <TT>typedef</TT>.</P> | |
10396 | <P> In addition to tracking typenames, typemaps may also be specialized | |
10397 | to match against a specific argument name. For example, you could write | |
10398 | a typemap like this:</P> | |
10399 | <DIV class="code"> | |
10400 | <PRE> | |
10401 | %typemap(in) <B>double nonnegative</B> { | |
10402 | $1 = PyFloat_AsDouble($input); | |
10403 | if ($1 < 0) { | |
10404 | PyErr_SetString(PyExc_ValueError,"argument must be nonnegative."); | |
10405 | return NULL; | |
10406 | } | |
10407 | } | |
10408 | ||
10409 | ... | |
10410 | double sin(double x); | |
10411 | double cos(double x); | |
10412 | double sqrt(<B>double nonnegative</B>); | |
10413 | ||
10414 | typedef double Real; | |
10415 | double log(<B>Real nonnegative</B>); | |
10416 | ... | |
10417 | </PRE> | |
10418 | </DIV> | |
10419 | <P> For certain tasks such as input argument conversion, typemaps can be | |
10420 | defined for sequences of consecutive arguments. For example:</P> | |
10421 | <DIV class="code"> | |
10422 | <PRE> | |
10423 | %typemap(in) (<B>char *str, int len</B>) { | |
10424 | $1 = PyString_AsString($input); /* char *str */ | |
10425 | $2 = PyString_Size($input); /* int len */ | |
10426 | } | |
10427 | ... | |
10428 | int count(<B>char *str, int len</B>, char c); | |
10429 | </PRE> | |
10430 | </DIV> | |
10431 | <P> In this case, a single input object is expanded into a pair of C | |
10432 | arguments. This example also provides a hint to the unusual variable | |
10433 | naming scheme involving <TT>$1</TT>, <TT>$2</TT>, and so forth.</P> | |
10434 | <H3><A name="Typemaps_nn6"></A>10.1.4 Reusing typemaps</H3> | |
10435 | <P> Typemaps are normally defined for specific type and argument name | |
10436 | patterns. However, typemaps can also be copied and reused. One way to | |
10437 | do this is to use assignment like this:</P> | |
10438 | <DIV class="code"> | |
10439 | <PRE> | |
10440 | %typemap(in) Integer = int; | |
10441 | %typemap(in) (char *buffer, int size) = (char *str, int len); | |
10442 | </PRE> | |
10443 | </DIV> | |
10444 | <P> A more general form of copying is found in the <TT>%apply</TT> | |
10445 | directive like this:</P> | |
10446 | <DIV class="code"> | |
10447 | <PRE> | |
10448 | %typemap(in) int { | |
10449 | /* Convert an integer argument */ | |
10450 | ... | |
10451 | } | |
10452 | %typemap(out) int { | |
10453 | /* Return an integer value */ | |
10454 | ... | |
10455 | } | |
10456 | ||
10457 | /* Apply all of the integer typemaps to size_t */ | |
10458 | %apply int { size_t }; | |
10459 | </PRE> | |
10460 | </DIV> | |
10461 | <P> <TT>%apply</TT> merely takes<EM> all</EM> of the typemaps that are | |
10462 | defined for one type and applies them to other types. Note: you can | |
10463 | include a comma separated set of types in the <TT>{ ... }</TT> part of <TT> | |
10464 | %apply</TT>.</P> | |
10465 | <P> It should be noted that it is not necessary to copy typemaps for | |
10466 | types that are related by <TT>typedef</TT>. For example, if you have | |
10467 | this,</P> | |
10468 | <DIV class="code"> | |
10469 | <PRE> | |
10470 | typedef int size_t; | |
10471 | </PRE> | |
10472 | </DIV> | |
10473 | <P> then SWIG already knows that the <TT>int</TT> typemaps apply. You | |
10474 | don't have to do anything.</P> | |
10475 | <H3><A name="Typemaps_nn7"></A>10.1.5 What can be done with typemaps?</H3> | |
10476 | <P> The primary use of typemaps is for defining wrapper generation | |
10477 | behavior at the level of individual C/C++ datatypes. There are | |
10478 | currently six general categories of problems that typemaps address:</P> | |
10479 | <P><B> Argument handling</B></P> | |
10480 | <DIV class="code"> | |
10481 | <PRE> | |
10482 | int foo(<B>int x, double y, char *s</B>); | |
10483 | </PRE> | |
10484 | </DIV> | |
10485 | <UL> | |
10486 | <LI>Input argument conversion ("in" typemap).</LI> | |
10487 | <LI>Input argument type checking ("typecheck" typemap).</LI> | |
10488 | <LI>Output argument handling ("argout" typemap).</LI> | |
10489 | <LI>Input argument value checking ("check" typemap).</LI> | |
10490 | <LI>Input argument initialization ("arginit" typemap).</LI> | |
10491 | <LI>Default arguments ("default" typemap).</LI> | |
10492 | <LI>Input argument resource management ("freearg" typemap).</LI> | |
10493 | </UL> | |
10494 | <P><B> Return value handling</B></P> | |
10495 | <DIV class="code"> | |
10496 | <PRE> | |
10497 | <B>int</B> foo(int x, double y, char *s); | |
10498 | </PRE> | |
10499 | </DIV> | |
10500 | <UL> | |
10501 | <LI>Function return value conversion ("out" typemap).</LI> | |
10502 | <LI>Return value resource management ("ret" typemap).</LI> | |
10503 | <LI>Resource management for newly allocated objects ("newfree" typemap).</LI> | |
10504 | </UL> | |
10505 | <P><B> Exception handling</B></P> | |
10506 | <DIV class="code"> | |
10507 | <PRE> | |
10508 | <B>int</B> foo(int x, double y, char *s) throw(<B>MemoryError, IndexError</B>); | |
10509 | </PRE> | |
10510 | </DIV> | |
10511 | <UL> | |
10512 | <LI>Handling of C++ exception specifications. ("throw" typemap).</LI> | |
10513 | </UL> | |
10514 | <P><B> Global variables</B></P> | |
10515 | <DIV class="code"> | |
10516 | <PRE> | |
10517 | <B>int foo;</B> | |
10518 | </PRE> | |
10519 | </DIV> | |
10520 | <UL> | |
10521 | <LI>Assignment of a global variable. ("varin" typemap).</LI> | |
10522 | <LI>Reading a global variable. ("varout" typemap).</LI> | |
10523 | </UL> | |
10524 | <P><B> Member variables</B></P> | |
10525 | <DIV class="code"> | |
10526 | <PRE> | |
10527 | struct Foo { | |
10528 | <B>int x[20]</B>; | |
10529 | }; | |
10530 | </PRE> | |
10531 | </DIV> | |
10532 | <UL> | |
10533 | <LI>Assignment of data to a class/structure member. ("memberin" | |
10534 | typemap).</LI> | |
10535 | </UL> | |
10536 | <P><B> Constant creation</B></P> | |
10537 | <DIV class="code"> | |
10538 | <PRE> | |
10539 | #define FOO 3 | |
10540 | %constant int BAR = 42; | |
10541 | enum { ALE, LAGER, STOUT }; | |
10542 | </PRE> | |
10543 | </DIV> | |
10544 | <UL> | |
10545 | <LI>Creation of constant values. ("consttab" or "constcode" typemap).</LI> | |
10546 | </UL> | |
10547 | <P> Details of each of these typemaps will be covered shortly. Also, | |
10548 | certain language modules may define additional typemaps that expand | |
10549 | upon this list. For example, the Java module defines a variety of | |
10550 | typemaps for controlling additional aspects of the Java bindings. | |
10551 | Consult language specific documentation for further details.</P> | |
10552 | <H3><A name="Typemaps_nn8"></A>10.1.6 What can't be done with typemaps?</H3> | |
10553 | <P> Typemaps can't be used to define properties that apply to C/C++ | |
10554 | declarations as a whole. For example, suppose you had a declaration | |
10555 | like this,</P> | |
10556 | <DIV class="code"> | |
10557 | <PRE> | |
10558 | Foo *make_Foo(); | |
10559 | </PRE> | |
10560 | </DIV> | |
10561 | <P> and you wanted to tell SWIG that <TT>make_Foo()</TT> returned a | |
10562 | newly allocated object (for the purposes of providing better memory | |
10563 | management). Clearly, this property of <TT>make_Foo()</TT> is<EM> not</EM> | |
10564 | a property that would be associated with the datatype <TT>Foo *</TT> by | |
10565 | itself. Therefore, a completely different SWIG customization mechanism | |
10566 | (<TT>%feature</TT>) is used for this purpose. Consult the <A href="#Customization"> | |
10567 | Customization Features</A> chapter for more information about that.</P> | |
10568 | <P> Typemaps also can't be used to rearrange or transform the order of | |
10569 | arguments. For example, if you had a function like this:</P> | |
10570 | <DIV class="code"> | |
10571 | <PRE> | |
10572 | void foo(int, char *); | |
10573 | </PRE> | |
10574 | </DIV> | |
10575 | <P> you can't use typemaps to interchange the arguments, allowing you to | |
10576 | call the function like this:</P> | |
10577 | <DIV class="targetlang"> | |
10578 | <PRE> | |
10579 | foo("hello",3) # Reversed arguments | |
10580 | </PRE> | |
10581 | </DIV> | |
10582 | <P> If you want to change the calling conventions of a function, write a | |
10583 | helper function instead. For example:</P> | |
10584 | <DIV class="code"> | |
10585 | <PRE> | |
10586 | %rename(foo) wrap_foo; | |
10587 | %inline %{ | |
10588 | void wrap_foo(char *s, int x) { | |
10589 | foo(x,s); | |
10590 | } | |
10591 | %} | |
10592 | </PRE> | |
10593 | </DIV> | |
10594 | <H3><A name="Typemaps_nn9"></A>10.1.7 The rest of this chapter</H3> | |
10595 | <P> The rest of this chapter provides detailed information for people | |
10596 | who want to write new typemaps. This information is of particular | |
10597 | importance to anyone who intends to write a new SWIG target language | |
10598 | module. Power users can also use this information to write application | |
10599 | specific type conversion rules.</P> | |
10600 | <P> Since typemaps are strongly tied to the underlying C++ type system, | |
10601 | subsequent sections assume that you are reasonably familiar with the | |
10602 | basic details of values, pointers, references, arrays, type qualifiers | |
10603 | (e.g., <TT>const</TT>), structures, namespaces, templates, and memory | |
10604 | management in C/C++. If not, you would be well-advised to consult a | |
10605 | copy of "The C Programming Language" by Kernighan and Ritchie or "The | |
10606 | C++ Programming Language" by Stroustrup before going any further.</P> | |
10607 | <H2><A name="Typemaps_nn10"></A>10.2 Typemap specifications</H2> | |
10608 | <P> This section describes the behavior of the <TT>%typemap</TT> | |
10609 | directive itself.</P> | |
10610 | <H3><A name="Typemaps_nn11"></A>10.2.1 Defining a typemap</H3> | |
10611 | <P> New typemaps are defined using the <TT>%typemap</TT> declaration. | |
10612 | The general form of this declaration is as follows (parts enclosed in [ | |
10613 | ... ] are optional):</P> | |
10614 | <DIV class="code"> | |
10615 | <PRE> | |
10616 | %typemap(<EM>method</EM> [, <EM>modifiers</EM>]) <EM>typelist</EM> <EM>code</EM> ; | |
10617 | </PRE> | |
10618 | </DIV> | |
10619 | <P><EM> method</EM> is a simply a name that specifies what kind of | |
10620 | typemap is being defined. It is usually a name like <TT>"in"</TT>, <TT> | |
10621 | "out"</TT>, or <TT>"argout"</TT>. The purpose of these methods is | |
10622 | described later.</P> | |
10623 | <P><EM> modifiers</EM> is an optional comma separated list of <TT> | |
10624 | name="value"</TT> values. These are sometimes to attach extra | |
10625 | information to a typemap and is often target-language dependent.</P> | |
10626 | <P><EM> typelist</EM> is a list of the C++ type patterns that the | |
10627 | typemap will match. The general form of this list is as follows:</P> | |
10628 | <DIV class="diagram"> | |
10629 | <PRE> | |
10630 | typelist : typepattern [, typepattern, typepattern, ... ] ; | |
10631 | ||
10632 | typepattern : type [ (parms) ] | |
10633 | | type name [ (parms) ] | |
10634 | | ( typelist ) [ (parms) ] | |
10635 | ||
10636 | </PRE> | |
10637 | </DIV> | |
10638 | <P> Each type pattern is either a simple type, a simple type and | |
10639 | argument name, or a list of types in the case of multi-argument | |
10640 | typemaps. In addition, each type pattern can be parameterized with a | |
10641 | list of temporary variables (parms). The purpose of these variables | |
10642 | will be explained shortly.</P> | |
10643 | <P><EM>code</EM> specifies the C code used in the typemap. It can take | |
10644 | any one of the following forms:</P> | |
10645 | <DIV class="diagram"> | |
10646 | <PRE> | |
10647 | code : { ... } | |
10648 | | " ... " | |
10649 | | %{ ... %} | |
10650 | </PRE> | |
10651 | </DIV> | |
10652 | <P> Here are some examples of valid typemap specifications:</P> | |
10653 | <DIV class="code"> | |
10654 | <PRE> | |
10655 | /* Simple typemap declarations */ | |
10656 | %typemap(in) int { | |
10657 | $1 = PyInt_AsLong($input); | |
10658 | } | |
10659 | %typemap(in) int "$1 = PyInt_AsLong($input);"; | |
10660 | %typemap(in) int %{ | |
10661 | $1 = PyInt_AsLong($input); | |
10662 | %} | |
10663 | ||
10664 | /* Typemap with extra argument name */ | |
10665 | %typemap(in) int nonnegative { | |
10666 | ... | |
10667 | } | |
10668 | ||
10669 | /* Multiple types in one typemap */ | |
10670 | %typemap(in) int, short, long { | |
10671 | $1 = SvIV($input); | |
10672 | } | |
10673 | ||
10674 | /* Typemap with modifiers */ | |
10675 | %typemap(in,doc="integer") int "$1 = gh_scm2int($input);"; | |
10676 | ||
10677 | /* Typemap applied to patterns of multiple arguments */ | |
10678 | %typemap(in) (char *str, int len), | |
10679 | (char *buffer, int size) | |
10680 | { | |
10681 | $1 = PyString_AsString($input); | |
10682 | $2 = PyString_Size($input); | |
10683 | } | |
10684 | ||
10685 | /* Typemap with extra pattern parameters */ | |
10686 | %typemap(in, numinputs=0) int *output (int temp), | |
10687 | long *output (long temp) | |
10688 | { | |
10689 | $1 = &temp; | |
10690 | } | |
10691 | </PRE> | |
10692 | </DIV> | |
10693 | <P> Admittedly, it's not the most readable syntax at first glance. | |
10694 | However, the purpose of the individual pieces will become clear.</P> | |
10695 | <H3><A name="Typemaps_nn12"></A>10.2.2 Typemap scope</H3> | |
10696 | <P> Once defined, a typemap remains in effect for all of the | |
10697 | declarations that follow. A typemap may be redefined for different | |
10698 | sections of an input file. For example:</P> | |
10699 | <DIV class="code"> | |
10700 | <PRE> | |
10701 | // typemap1 | |
10702 | %typemap(in) int { | |
10703 | ... | |
10704 | } | |
10705 | ||
10706 | int fact(int); // typemap1 | |
10707 | int gcd(int x, int y); // typemap1 | |
10708 | ||
10709 | // typemap2 | |
10710 | %typemap(in) int { | |
10711 | ... | |
10712 | } | |
10713 | ||
10714 | int isprime(int); // typemap2 | |
10715 | </PRE> | |
10716 | </DIV> | |
10717 | <P> One exception to the typemap scoping rules pertains to the <TT> | |
10718 | %extend</TT> declaration. <TT>%extend</TT> is used to attach new | |
10719 | declarations to a class or structure definition. Because of this, all | |
10720 | of the declarations in an <TT>%extend</TT> block are subject to the | |
10721 | typemap rules that are in effect at the point where the class itself is | |
10722 | defined. For example:</P> | |
10723 | <DIV class="code"> | |
10724 | <PRE> | |
10725 | class Foo { | |
10726 | ... | |
10727 | }; | |
10728 | ||
10729 | %typemap(in) int { | |
10730 | ... | |
10731 | } | |
10732 | ||
10733 | %extend Foo { | |
10734 | int blah(int x); // typemap has no effect. Declaration is attached to Foo which | |
10735 | // appears before the %typemap declaration. | |
10736 | }; | |
10737 | </PRE> | |
10738 | </DIV> | |
10739 | <H3><A name="Typemaps_nn13"></A>10.2.3 Copying a typemap</H3> | |
10740 | <P> A typemap is copied by using assignment. For example:</P> | |
10741 | <DIV class="code"> | |
10742 | <PRE> | |
10743 | %typemap(in) Integer = int; | |
10744 | </PRE> | |
10745 | </DIV> | |
10746 | <P> or this:</P> | |
10747 | <DIV class="code"> | |
10748 | <PRE> | |
10749 | %typemap(in) Integer, Number, int32_t = int; | |
10750 | </PRE> | |
10751 | </DIV> | |
10752 | <P> Types are often managed by a collection of different typemaps. For | |
10753 | example:</P> | |
10754 | <DIV class="code"> | |
10755 | <PRE> | |
10756 | %typemap(in) int { ... } | |
10757 | %typemap(out) int { ... } | |
10758 | %typemap(varin) int { ... } | |
10759 | %typemap(varout) int { ... } | |
10760 | </PRE> | |
10761 | </DIV> | |
10762 | <P> To copy all of these typemaps to a new type, use <TT>%apply</TT>. | |
10763 | For example:</P> | |
10764 | <DIV class="code"> | |
10765 | <PRE> | |
10766 | %apply int { Integer }; // Copy all int typemaps to Integer | |
10767 | %apply int { Integer, Number }; // Copy all int typemaps to both Integer and Number | |
10768 | </PRE> | |
10769 | </DIV> | |
10770 | <P> The patterns for <TT>%apply</TT> follow the same rules as for <TT> | |
10771 | %typemap</TT>. For example:</P> | |
10772 | <DIV class="code"> | |
10773 | <PRE> | |
10774 | %apply int *output { Integer *output }; // Typemap with name | |
10775 | %apply (char *buf, int len) { (char *buffer, int size) }; // Multiple arguments | |
10776 | </PRE> | |
10777 | </DIV> | |
10778 | <H3><A name="Typemaps_nn14"></A>10.2.4 Deleting a typemap</H3> | |
10779 | <P> A typemap can be deleted by simply defining no code. For example:</P> | |
10780 | <DIV class="code"> | |
10781 | <PRE> | |
10782 | %typemap(in) int; // Clears typemap for int | |
10783 | %typemap(in) int, long, short; // Clears typemap for int, long, short | |
10784 | %typemap(in) int *output; | |
10785 | </PRE> | |
10786 | </DIV> | |
10787 | <P> The <TT>%clear</TT> directive clears all typemaps for a given type. | |
10788 | For example:</P> | |
10789 | <DIV class="code"> | |
10790 | <PRE> | |
10791 | %clear int; // Removes all types for int | |
10792 | %clear int *output, long *output; | |
10793 | </PRE> | |
10794 | </DIV> | |
10795 | <P><B> Note:</B> Since SWIG's default behavior is defined by typemaps, | |
10796 | clearing a fundamental type like <TT>int</TT> will make that type | |
10797 | unusable unless you also define a new set of typemaps immediately after | |
10798 | the clear operation.</P> | |
10799 | <H3><A name="Typemaps_nn15"></A>10.2.5 Placement of typemaps</H3> | |
10800 | <P> Typemap declarations can be declared in the global scope, within a | |
10801 | C++ namespace, and within a C++ class. For example:</P> | |
10802 | <DIV class="code"> | |
10803 | <PRE> | |
10804 | %typemap(in) int { | |
10805 | ... | |
10806 | } | |
10807 | ||
10808 | namespace std { | |
10809 | class string; | |
10810 | %typemap(in) string { | |
10811 | ... | |
10812 | } | |
10813 | } | |
10814 | ||
10815 | class Bar { | |
10816 | public: | |
10817 | typedef const int & const_reference; | |
10818 | %typemap(out) const_reference { | |
10819 | ... | |
10820 | } | |
10821 | }; | |
10822 | </PRE> | |
10823 | </DIV> | |
10824 | <P> When a typemap appears inside a namespace or class, it stays in | |
10825 | effect until the end of the SWIG input (just like before). However, the | |
10826 | typemap takes the local scope into account. Therefore, this code</P> | |
10827 | <DIV class="code"> | |
10828 | <PRE> | |
10829 | namespace std { | |
10830 | class string; | |
10831 | %typemap(in) string { | |
10832 | ... | |
10833 | } | |
10834 | } | |
10835 | </PRE> | |
10836 | </DIV> | |
10837 | <P> is really defining a typemap for the type <TT>std::string</TT>. You | |
10838 | could have code like this:</P> | |
10839 | <DIV class="code"> | |
10840 | <PRE> | |
10841 | namespace std { | |
10842 | class string; | |
10843 | %typemap(in) string { /* std::string */ | |
10844 | ... | |
10845 | } | |
10846 | } | |
10847 | ||
10848 | namespace Foo { | |
10849 | class string; | |
10850 | %typemap(in) string { /* Foo::string */ | |
10851 | ... | |
10852 | } | |
10853 | } | |
10854 | </PRE> | |
10855 | </DIV> | |
10856 | <P> In this case, there are two completely distinct typemaps that apply | |
10857 | to two completely different types (<TT>std::string</TT> and <TT> | |
10858 | Foo::string</TT>).</P> | |
10859 | <P> It should be noted that for scoping to work, SWIG has to know that <TT> | |
10860 | string</TT> is a typename defined within a particular namespace. In this | |
10861 | example, this is done using the class declaration <TT>class string</TT> | |
10862 | .</P> | |
10863 | <H2><A name="Typemaps_nn16"></A>10.3 Pattern matching rules</H2> | |
10864 | <P> The section describes the pattern matching rules by which C | |
10865 | datatypes are associated with typemaps.</P> | |
10866 | <H3><A name="Typemaps_nn17"></A>10.3.1 Basic matching rules</H3> | |
10867 | <P> Typemaps are matched using both a type and a name (typically the | |
10868 | name of a argument). For a given <TT>TYPE NAME</TT> pair, the following | |
10869 | rules are applied, in order, to find a match. The first typemap found | |
10870 | is used.</P> | |
10871 | <UL> | |
10872 | <LI>Typemaps that exactly match <TT>TYPE</TT> and <TT>NAME</TT>.</LI> | |
10873 | <LI>Typemaps that exactly match <TT>TYPE</TT> only.</LI> | |
10874 | </UL> | |
10875 | <P> If <TT>TYPE</TT> includes qualifiers (const, volatile, etc.), they | |
10876 | are stripped and the following checks are made:</P> | |
10877 | <UL> | |
10878 | <LI>Typemaps that match the stripped <TT>TYPE</TT> and <TT>NAME</TT>.</LI> | |
10879 | <LI>Typemaps that match the stripped <TT>TYPE</TT> only.</LI> | |
10880 | </UL> | |
10881 | <P> If <TT>TYPE</TT> is an array. The following transformation is made:</P> | |
10882 | <UL> | |
10883 | <LI>Replace all dimensions to <TT>[ANY]</TT> and look for a generic | |
10884 | array typemap.</LI> | |
10885 | </UL> | |
10886 | <P> To illustrate, suppose that you had a function like this:</P> | |
10887 | <DIV class="code"> | |
10888 | <PRE> | |
10889 | int foo(const char *s); | |
10890 | </PRE> | |
10891 | </DIV> | |
10892 | <P> To find a typemap for the argument <TT>const char *s</TT>, SWIG will | |
10893 | search for the following typemaps:</P> | |
10894 | <DIV class="diagram"> | |
10895 | <PRE> | |
10896 | const char *s Exact type and name match | |
10897 | const char * Exact type match | |
10898 | char *s Type and name match (stripped qualifiers) | |
10899 | char * Type match (stripped qualifiers) | |
10900 | </PRE> | |
10901 | </DIV> | |
10902 | <P> When more than one typemap rule might be defined, only the first | |
10903 | match found is actually used. Here is an example that shows how some of | |
10904 | the basic rules are applied:</P> | |
10905 | <DIV class="code"> | |
10906 | <PRE> | |
10907 | %typemap(in) int *x { | |
10908 | ... typemap 1 | |
10909 | } | |
10910 | ||
10911 | %typemap(in) int * { | |
10912 | ... typemap 2 | |
10913 | } | |
10914 | ||
10915 | %typemap(in) const int *z { | |
10916 | ... typemap 3 | |
10917 | } | |
10918 | ||
10919 | %typemap(in) int [4] { | |
10920 | ... typemap 4 | |
10921 | } | |
10922 | ||
10923 | %typemap(in) int [ANY] { | |
10924 | ... typemap 5 | |
10925 | } | |
10926 | ||
10927 | void A(int *x); // int *x rule (typemap 1) | |
10928 | void B(int *y); // int * rule (typemap 2) | |
10929 | void C(const int *x); // int *x rule (typemap 1) | |
10930 | void D(const int *z); // int * rule (typemap 3) | |
10931 | void E(int x[4]); // int [4] rule (typemap 4) | |
10932 | void F(int x[1000]); // int [ANY] rule (typemap 5) | |
10933 | </PRE> | |
10934 | </DIV> | |
10935 | <H3><A name="Typemaps_nn18"></A>10.3.2 Typedef reductions</H3> | |
10936 | <P> If no match is found using the rules in the previous section, SWIG | |
10937 | applies a typedef reduction to the type and repeats the typemap search | |
10938 | for the reduced type. To illustrate, suppose you had code like this:</P> | |
10939 | <DIV class="code"> | |
10940 | <PRE> | |
10941 | %typemap(in) int { | |
10942 | ... typemap 1 | |
10943 | } | |
10944 | ||
10945 | typedef int Integer; | |
10946 | void blah(Integer x); | |
10947 | </PRE> | |
10948 | </DIV> | |
10949 | <P> To find the typemap for <TT>Integer x</TT>, SWIG will first search | |
10950 | for the following typemaps:</P> | |
10951 | <DIV class="diagram"> | |
10952 | <PRE> | |
10953 | Integer x | |
10954 | Integer | |
10955 | </PRE> | |
10956 | </DIV> | |
10957 | <P> Finding no match, it then applies a reduction <TT>Integer -> int</TT> | |
10958 | to the type and repeats the search.</P> | |
10959 | <DIV class="diagram"> | |
10960 | <PRE> | |
10961 | int x | |
10962 | int --> match: typemap 1 | |
10963 | </PRE> | |
10964 | </DIV> | |
10965 | <P> Even though two types might be the same via typedef, SWIG allows | |
10966 | typemaps to be defined for each typename independently. This allows for | |
10967 | interesting customization possibilities based solely on the typename | |
10968 | itself. For example, you could write code like this:</P> | |
10969 | <DIV class="code"> | |
10970 | <PRE> | |
10971 | typedef double pdouble; // Positive double | |
10972 | ||
10973 | // typemap 1 | |
10974 | %typemap(in) double { | |
10975 | ... get a double ... | |
10976 | } | |
10977 | // typemap 2 | |
10978 | %typemap(in) pdouble { | |
10979 | ... get a positive double ... | |
10980 | } | |
10981 | double sin(double x); // typemap 1 | |
10982 | pdouble sqrt(pdouble x); // typemap 2 | |
10983 | </PRE> | |
10984 | </DIV> | |
10985 | <P> When reducing the type, only one typedef reduction is applied at a | |
10986 | time. The search process continues to apply reductions until a match is | |
10987 | found or until no more reductions can be made.</P> | |
10988 | <P> For complicated types, the reduction process can generate a long | |
10989 | list of patterns. Consider the following:</P> | |
10990 | <DIV class="code"> | |
10991 | <PRE> | |
10992 | typedef int Integer; | |
10993 | typedef Integer Row4[4]; | |
10994 | void foo(Row4 rows[10]); | |
10995 | </PRE> | |
10996 | </DIV> | |
10997 | <P> To find a match for the <TT>Row4 rows[10]</TT> argument, SWIG would | |
10998 | check the following patterns, stopping only when it found a match:</P> | |
10999 | <DIV class="code"> | |
11000 | <PRE> | |
11001 | Row4 rows[10] | |
11002 | Row4 [10] | |
11003 | Row4 rows[ANY] | |
11004 | Row4 [ANY] | |
11005 | ||
11006 | # Reduce Row4 --> Integer[4] | |
11007 | Integer rows[10][4] | |
11008 | Integer [10][4] | |
11009 | Integer rows[ANY][ANY] | |
11010 | Integer [ANY][ANY] | |
11011 | ||
11012 | # Reduce Integer --> int | |
11013 | int rows[10][4] | |
11014 | int [10][4] | |
11015 | int rows[ANY][ANY] | |
11016 | int [ANY][ANY] | |
11017 | </PRE> | |
11018 | </DIV> | |
11019 | <P> For parametized types like templates, the situation is even more | |
11020 | complicated. Suppose you had some declarations like this:</P> | |
11021 | <DIV class="code"> | |
11022 | <PRE> | |
11023 | typedef int Integer; | |
11024 | typedef foo<Integer,Integer> fooii; | |
11025 | void blah(fooii *x); | |
11026 | </PRE> | |
11027 | </DIV> | |
11028 | <P> In this case, the following typemap patterns are searched for the | |
11029 | argument <TT>fooii *x</TT>:</P> | |
11030 | <DIV class="code"> | |
11031 | <PRE> | |
11032 | fooii *x | |
11033 | fooii * | |
11034 | ||
11035 | # Reduce fooii --> foo<Integer,Integer> | |
11036 | foo<Integer,Integer> *x | |
11037 | foo<Integer,Integer> * | |
11038 | ||
11039 | # Reduce Integer -> int | |
11040 | foo<int, Integer> *x | |
11041 | foo<int, Integer> * | |
11042 | ||
11043 | # Reduce Integer -> int | |
11044 | foo<int, int> *x | |
11045 | foo<int, int> * | |
11046 | </PRE> | |
11047 | </DIV> | |
11048 | <P> Typemap reductions are always applied to the left-most type that | |
11049 | appears. Only when no reductions can be made to the left-most type are | |
11050 | reductions made to other parts of the type. This behavior means that | |
11051 | you could define a typemap for <TT>foo<int,Integer></TT>, but a typemap | |
11052 | for <TT>foo<Integer,int></TT> would never be matched. Admittedly, this | |
11053 | is rather esoteric--there's little practical reason to write a typemap | |
11054 | quite like that. Of course, you could rely on this to confuse your | |
11055 | coworkers even more.</P> | |
11056 | <H3><A name="Typemaps_nn19"></A>10.3.3 Default typemaps</H3> | |
11057 | <P> Most SWIG language modules use typemaps to define the default | |
11058 | behavior of the C primitive types. This is entirely straightforward. | |
11059 | For example, a set of typemaps are written like this:</P> | |
11060 | <DIV class="code"> | |
11061 | <PRE> | |
11062 | %typemap(in) int "convert an int"; | |
11063 | %typemap(in) short "convert a short"; | |
11064 | %typemap(in) float "convert a float"; | |
11065 | ... | |
11066 | </PRE> | |
11067 | </DIV> | |
11068 | <P> Since typemap matching follows all <TT>typedef</TT> declarations, | |
11069 | any sort of type that is mapped to a primitive type through <TT>typedef</TT> | |
11070 | will be picked up by one of these primitive typemaps.</P> | |
11071 | <P> The default behavior for pointers, arrays, references, and other | |
11072 | kinds of types are handled by specifying rules for variations of the | |
11073 | reserved <TT>SWIGTYPE</TT> type. For example:</P> | |
11074 | <DIV class="code"> | |
11075 | <PRE> | |
11076 | %typemap(in) SWIGTYPE * { ... default pointer handling ... } | |
11077 | %typemap(in) SWIGTYPE & { ... default reference handling ... } | |
11078 | %typemap(in) SWIGTYPE [] { ... default array handling ... } | |
11079 | %typemap(in) enum SWIGTYPE { ... default handling for enum values ... } | |
11080 | %typemap(in) SWIGTYPE (CLASS::*) { ... default pointer member handling ... } | |
11081 | </PRE> | |
11082 | </DIV> | |
11083 | <P> These rules match any kind of pointer, reference, or array--even | |
11084 | when multiple levels of indirection or multiple array dimensions are | |
11085 | used. Therefore, if you wanted to change SWIG's default handling for | |
11086 | all types of pointers, you would simply redefine the rule for <TT> | |
11087 | SWIGTYPE *</TT>.</P> | |
11088 | <P> Finally, the following typemap rule is used to match against simple | |
11089 | types that don't match any other rules:</P> | |
11090 | <DIV class="code"> | |
11091 | <PRE> | |
11092 | %typemap(in) SWIGTYPE { ... handle an unknown type ... } | |
11093 | </PRE> | |
11094 | </DIV> | |
11095 | <P> This typemap is important because it is the rule that gets triggered | |
11096 | when call or return by value is used. For instance, if you have a | |
11097 | declaration like this:</P> | |
11098 | <DIV class="code"> | |
11099 | <PRE> | |
11100 | double dot_product(Vector a, Vector b); | |
11101 | </PRE> | |
11102 | </DIV> | |
11103 | <P> The <TT>Vector</TT> type will usually just get matched against <TT> | |
11104 | SWIGTYPE</TT>. The default implementation of <TT>SWIGTYPE</TT> is to | |
11105 | convert the value into pointers (as described in chapter 3).</P> | |
11106 | <P> By redefining <TT>SWIGTYPE</TT> it may be possible to implement | |
11107 | other behavior. For example, if you cleared all typemaps for <TT> | |
11108 | SWIGTYPE</TT>, SWIG simply won't wrap any unknown datatype (which might | |
11109 | be useful for debugging). Alternatively, you might modify SWIGTYPE to | |
11110 | marshal objects into strings instead of converting them to pointers.</P> | |
11111 | <P> The best way to explore the default typemaps is to look at the ones | |
11112 | already defined for a particular language module. Typemaps definitions | |
11113 | are usually found in the SWIG library in a file such as <TT>python.swg</TT> | |
11114 | , <TT>tcl8.swg</TT>, etc.</P> | |
11115 | <H3><A name="Typemaps_mixed_default"></A>10.3.4 Mixed default typemaps</H3> | |
11116 | <P> The default typemaps described above can be mixed with <TT>const</TT> | |
11117 | and with each other. For example the <TT>SWIGTYPE *</TT> typemap is for | |
11118 | default pointer handling, but if a <TT>const SWIGTYPE *</TT> typemap is | |
11119 | defined it will be used instead for constant pointers. Some further | |
11120 | examples follow:</P> | |
11121 | <DIV class="code"> | |
11122 | <PRE> | |
11123 | %typemap(in) enum SWIGTYPE & { ... enum references ... } | |
11124 | %typemap(in) const enum SWIGTYPE & { ... const enum references ... } | |
11125 | %typemap(in) SWIGTYPE *& { ... pointers passed by reference ... } | |
11126 | %typemap(in) SWIGTYPE * const & { ... constant pointers passed by reference ... } | |
11127 | %typemap(in) SWIGTYPE[ANY][ANY] { ... 2D arrays ... } | |
11128 | </PRE> | |
11129 | </DIV> | |
11130 | <P> Note that the the typedef reduction described earlier is also used | |
11131 | with these mixed default typemaps. For example, say the following | |
11132 | typemaps are defined and SWIG is looking for the best match for the | |
11133 | enum shown below:</P> | |
11134 | <DIV class="code"> | |
11135 | <PRE> | |
11136 | %typemap(in) const Hello & { ... } | |
11137 | %typemap(in) const enum SWIGTYPE & { ... } | |
11138 | %typemap(in) enum SWIGTYPE & { ... } | |
11139 | %typemap(in) SWIGTYPE & { ... } | |
11140 | %typemap(in) SWIGTYPE { ... } | |
11141 | ||
11142 | enum Hello {}; | |
11143 | const Hello &hi; | |
11144 | </PRE> | |
11145 | </DIV> | |
11146 | <P> The typemap at the top of the list will be chosen, not because it is | |
11147 | defined first, but because it is the closest match for the type being | |
11148 | wrapped. If any of the typemaps in the above list were not defined, | |
11149 | then the next one on the list would have precedence. In other words the | |
11150 | typemap chosen is the closest explicit match.</P> | |
11151 | <P><B> Compatibility note:</B> The mixed default typemaps were | |
11152 | introduced in SWIG-1.3.23, but were not used much in this version. | |
11153 | Expect to see them being used more and more within the various | |
11154 | libraries in later versions of SWIG.</P> | |
11155 | <H3><A name="Typemaps_nn20"></A>10.3.5 Multi-arguments typemaps</H3> | |
11156 | <P> When multi-argument typemaps are specified, they take precedence | |
11157 | over any typemaps specified for a single type. For example:</P> | |
11158 | <DIV class="code"> | |
11159 | <PRE> | |
11160 | %typemap(in) (char *buffer, int len) { | |
11161 | // typemap 1 | |
11162 | } | |
11163 | ||
11164 | %typemap(in) char *buffer { | |
11165 | // typemap 2 | |
11166 | } | |
11167 | ||
11168 | void foo(char *buffer, int len, int count); // (char *buffer, int len) | |
11169 | void bar(char *buffer, int blah); // char *buffer | |
11170 | </PRE> | |
11171 | </DIV> | |
11172 | <P> Multi-argument typemaps are also more restrictive in the way that | |
11173 | they are matched. Currently, the first argument follows the matching | |
11174 | rules described in the previous section, but all subsequent arguments | |
11175 | must match exactly.</P> | |
11176 | <H2><A name="Typemaps_nn21"></A>10.4 Code generation rules</H2> | |
11177 | <P> This section describes rules by which typemap code is inserted into | |
11178 | the generated wrapper code.</P> | |
11179 | <H3><A name="Typemaps_nn22"></A>10.4.1 Scope</H3> | |
11180 | <P> When a typemap is defined like this:</P> | |
11181 | <DIV class="code"> | |
11182 | <PRE> | |
11183 | %typemap(in) int { | |
11184 | $1 = PyInt_AsLong($input); | |
11185 | } | |
11186 | </PRE> | |
11187 | </DIV> | |
11188 | <P> the typemap code is inserted into the wrapper function using a new | |
11189 | block scope. In other words, the wrapper code will look like this:</P> | |
11190 | <DIV class="code"> | |
11191 | <PRE> | |
11192 | wrap_whatever() { | |
11193 | ... | |
11194 | // Typemap code | |
11195 | { | |
11196 | arg1 = PyInt_AsLong(obj1); | |
11197 | } | |
11198 | ... | |
11199 | } | |
11200 | </PRE> | |
11201 | </DIV> | |
11202 | <P> Because the typemap code is enclosed in its own block, it is legal | |
11203 | to declare temporary variables for use during typemap execution. For | |
11204 | example:</P> | |
11205 | <DIV class="code"> | |
11206 | <PRE> | |
11207 | %typemap(in) short { | |
11208 | long temp; /* Temporary value */ | |
11209 | if (Tcl_GetLongFromObj(interp, $input, &temp) != TCL_OK) { | |
11210 | return TCL_ERROR; | |
11211 | } | |
11212 | $1 = (short) temp; | |
11213 | } | |
11214 | </PRE> | |
11215 | </DIV> | |
11216 | <P> Of course, any variables that you declare inside a typemap are | |
11217 | destroyed as soon as the typemap code has executed (they are not | |
11218 | visible to other parts of the wrapper function or other typemaps that | |
11219 | might use the same variable names).</P> | |
11220 | <P> Occasionally, typemap code will be specified using a few alternative | |
11221 | forms. For example:</P> | |
11222 | <DIV class="code"> | |
11223 | <PRE> | |
11224 | %typemap(in) int "$1 = PyInt_AsLong($input);"; | |
11225 | %typemap(in) int %{ | |
11226 | $1 = PyInt_AsLong($input); | |
11227 | %} | |
11228 | </PRE> | |
11229 | </DIV> | |
11230 | <P> These two forms are mainly used for cosmetics--the specified code is | |
11231 | not enclosed inside a block scope when it is emitted. This sometimes | |
11232 | results in a less complicated looking wrapper function.</P> | |
11233 | <H3><A name="Typemaps_nn23"></A>10.4.2 Declaring new local variables</H3> | |
11234 | <P> Sometimes it is useful to declare a new local variable that exists | |
11235 | within the scope of the entire wrapper function. A good example of this | |
11236 | might be an application in which you wanted to marshal strings. Suppose | |
11237 | you had a C++ function like this</P> | |
11238 | <DIV class="code"> | |
11239 | <PRE> | |
11240 | int foo(std::string *s); | |
11241 | </PRE> | |
11242 | </DIV> | |
11243 | <P> and you wanted to pass a native string in the target language as an | |
11244 | argument. For instance, in Perl, you wanted the function to work like | |
11245 | this:</P> | |
11246 | <DIV class="targetlang"> | |
11247 | <PRE> | |
11248 | $x = foo("Hello World"); | |
11249 | </PRE> | |
11250 | </DIV> | |
11251 | <P> To do this, you can't just pass a raw Perl string as the <TT> | |
11252 | std::string *</TT> argument. Instead, you have to create a temporary <TT> | |
11253 | std::string</TT> object, copy the Perl string data into it, and then | |
11254 | pass a pointer to the object. To do this, simply specify the typemap | |
11255 | with an extra parameter like this:</P> | |
11256 | <DIV class="code"> | |
11257 | <PRE> | |
11258 | %typemap(in) std::string * <B>(std::string temp)</B> { | |
11259 | unsigned int len; | |
11260 | char *s; | |
11261 | s = SvPV($input,len); /* Extract string data */ | |
11262 | temp.assign(s,len); /* Assign to temp */ | |
11263 | $1 = &temp; /* Set argument to point to temp */ | |
11264 | } | |
11265 | </PRE> | |
11266 | </DIV> | |
11267 | <P> In this case, <TT>temp</TT> becomes a local variable in the scope of | |
11268 | the entire wrapper function. For example:</P> | |
11269 | <DIV class="code"> | |
11270 | <PRE> | |
11271 | wrap_foo() { | |
11272 | std::string temp; <--- Declaration of temp goes here | |
11273 | ... | |
11274 | ||
11275 | /* Typemap code */ | |
11276 | { | |
11277 | ... | |
11278 | temp.assign(s,len); | |
11279 | ... | |
11280 | } | |
11281 | ... | |
11282 | } | |
11283 | </PRE> | |
11284 | </DIV> | |
11285 | <P> When you set <TT>temp</TT> to a value, it persists for the duration | |
11286 | of the wrapper function and gets cleaned up automatically on exit.</P> | |
11287 | <P> It is perfectly safe to use more than one typemap involving local | |
11288 | variables in the same declaration. For example, you could declare a | |
11289 | function as :</P> | |
11290 | <DIV class="code"> | |
11291 | <PRE> | |
11292 | void foo(std::string *x, std::string *y, std::string *z); | |
11293 | </PRE> | |
11294 | </DIV> | |
11295 | <P> This is safely handled because SWIG actually renames all local | |
11296 | variable references by appending an argument number suffix. Therefore, | |
11297 | the generated code would actually look like this:</P> | |
11298 | <DIV class="code"> | |
11299 | <PRE> | |
11300 | wrap_foo() { | |
11301 | int *arg1; /* Actual arguments */ | |
11302 | int *arg2; | |
11303 | int *arg3; | |
11304 | std::string temp1; /* Locals declared in the typemap */ | |
11305 | std::string temp2; | |
11306 | std::string temp3; | |
11307 | ... | |
11308 | { | |
11309 | char *s; | |
11310 | unsigned int len; | |
11311 | ... | |
11312 | temp1.assign(s,len); | |
11313 | arg1 = *temp1; | |
11314 | } | |
11315 | { | |
11316 | char *s; | |
11317 | unsigned int len; | |
11318 | ... | |
11319 | temp2.assign(s,len); | |
11320 | arg2 = &temp2; | |
11321 | } | |
11322 | { | |
11323 | char *s; | |
11324 | unsigned int len; | |
11325 | ... | |
11326 | temp3.assign(s,len); | |
11327 | arg3 = &temp3; | |
11328 | } | |
11329 | ... | |
11330 | } | |
11331 | </PRE> | |
11332 | </DIV> | |
11333 | <P> Some typemaps do not recognize local variables (or they may simply | |
11334 | not apply). At this time, only typemaps that apply to argument | |
11335 | conversion support this.</P> | |
11336 | <H3><A name="Typemaps_nn24"></A>10.4.3 Special variables</H3> | |
11337 | <P> Within all typemaps, the following special variables are expanded.</P> | |
11338 | <CENTER> | |
11339 | <TABLE border="1" summary="Typemap special variables"> | |
11340 | <TR><TH>Variable</TH><TH>Meaning</TH></TR> | |
11341 | <TR><TD>$<EM>n</EM></TD><TD> A C local variable corresponding to type<EM> | |
11342 | n</EM> in the typemap pattern.</TD></TR> | |
11343 | <TR><TD>$argnum</TD><TD>Argument number. Only available in typemaps | |
11344 | related to argument conversion</TD></TR> | |
11345 | <TR><TD>$<EM>n</EM>_name</TD><TD>Argument name</TD></TR> | |
11346 | <TR><TD>$<EM>n</EM>_type</TD><TD>Real C datatype of type<EM> n</EM>.</TD> | |
11347 | </TR> | |
11348 | <TR><TD>$<EM>n</EM>_ltype</TD><TD>ltype of type<EM> n</EM></TD></TR> | |
11349 | <TR><TD>$<EM>n</EM>_mangle</TD><TD>Mangled form of type<EM> n</EM>. For | |
11350 | example <TT>_p_Foo</TT></TD></TR> | |
11351 | <TR><TD>$<EM>n</EM>_descriptor</TD><TD>Type descriptor structure for | |
11352 | type<EM> n</EM>. For example <TT>SWIGTYPE_p_Foo</TT>. This is primarily | |
11353 | used when interacting with the run-time type checker (described later).</TD> | |
11354 | </TR> | |
11355 | <TR><TD>$*<EM>n</EM>_type</TD><TD>Real C datatype of type<EM> n</EM> | |
11356 | with one pointer removed.</TD></TR> | |
11357 | <TR><TD>$*<EM>n</EM>_ltype</TD><TD>ltype of type<EM> n</EM> with one | |
11358 | pointer removed.</TD></TR> | |
11359 | <TR><TD>$*<EM>n</EM>_mangle</TD><TD>Mangled form of type<EM> n</EM> with | |
11360 | one pointer removed.</TD></TR> | |
11361 | <TR><TD>$*<EM>n</EM>_descriptor</TD><TD>Type descriptor structure for | |
11362 | type<EM> n</EM> with one pointer removed.</TD></TR> | |
11363 | <TR><TD>$&<EM>n</EM>_type</TD><TD>Real C datatype of type<EM> n</EM> | |
11364 | with one pointer added.</TD></TR> | |
11365 | <TR><TD>$&<EM>n</EM>_ltype</TD><TD>ltype of type<EM> n</EM> with one | |
11366 | pointer added.</TD></TR> | |
11367 | <TR><TD>$&<EM>n</EM>_mangle</TD><TD>Mangled form of type<EM> n</EM> with | |
11368 | one pointer added.</TD></TR> | |
11369 | <TR><TD>$&<EM>n</EM>_descriptor</TD><TD>Type descriptor structure for | |
11370 | type<EM> n</EM> with one pointer added.</TD></TR> | |
11371 | <TR><TD>$<EM>n</EM>_basetype</TD><TD>Base typename with all pointers and | |
11372 | qualifiers stripped.</TD></TR> | |
11373 | </TABLE> | |
11374 | </CENTER> | |
11375 | <P> Within the table, $<EM>n</EM> refers to a specific type within the | |
11376 | typemap specification. For example, if you write this</P> | |
11377 | <DIV class="code"> | |
11378 | <PRE> | |
11379 | %typemap(in) int *INPUT { | |
11380 | ||
11381 | } | |
11382 | </PRE> | |
11383 | </DIV> | |
11384 | <P> then $1 refers to <TT>int *INPUT</TT>. If you have a typemap like | |
11385 | this,</P> | |
11386 | <DIV class="code"> | |
11387 | <PRE> | |
11388 | %typemap(in) (int argc, char *argv[]) { | |
11389 | ... | |
11390 | } | |
11391 | </PRE> | |
11392 | </DIV> | |
11393 | <P> then $1 refers to <TT>int argc</TT> and $2 refers to <TT>char | |
11394 | *argv[]</TT>.</P> | |
11395 | <P> Substitutions related to types and names always fill in values from | |
11396 | the actual code that was matched. This is useful when a typemap might | |
11397 | match multiple C datatype. For example:</P> | |
11398 | <DIV class="code"> | |
11399 | <PRE> | |
11400 | %typemap(in) int, short, long { | |
11401 | $1 = ($1_ltype) PyInt_AsLong($input); | |
11402 | } | |
11403 | </PRE> | |
11404 | </DIV> | |
11405 | <P> In this case, <TT>$1_ltype</TT> is replaced with the datatype that | |
11406 | is actually matched.</P> | |
11407 | <P> When typemap code is emitted, the C/C++ datatype of the special | |
11408 | variables <TT>$1</TT> and <TT>$2</TT> is always an "ltype." An "ltype" | |
11409 | is simply a type that can legally appear on the left-hand side of a C | |
11410 | assignment operation. Here are a few examples of types and ltypes:</P> | |
11411 | <DIV class="diagram"> | |
11412 | <PRE> | |
11413 | type ltype | |
11414 | ------ ---------------- | |
11415 | int int | |
11416 | const int int | |
11417 | conts int * int * | |
11418 | int [4] int * | |
11419 | int [4][5] int (*)[5] | |
11420 | </PRE> | |
11421 | </DIV> | |
11422 | <P> In most cases a ltype is simply the C datatype with qualifiers | |
11423 | stripped off. In addition, arrays are converted into pointers.</P> | |
11424 | <P> Variables such as <TT>$&1_type</TT> and <TT>$*1_type</TT> are used | |
11425 | to safely modify the type by removing or adding pointers. Although not | |
11426 | needed in most typemaps, these substitutions are sometimes needed to | |
11427 | properly work with typemaps that convert values between pointers and | |
11428 | values.</P> | |
11429 | <P> If necessary, type related substitutions can also be used when | |
11430 | declaring locals. For example:</P> | |
11431 | <DIV class="code"> | |
11432 | <PRE> | |
11433 | %typemap(in) int * ($*1_type temp) { | |
11434 | temp = PyInt_AsLong($input); | |
11435 | $1 = &temp; | |
11436 | } | |
11437 | </PRE> | |
11438 | </DIV> | |
11439 | <P> There is one word of caution about declaring local variables in this | |
11440 | manner. If you declare a local variable using a type substitution such | |
11441 | as <TT>$1_ltype temp</TT>, it won't work like you expect for arrays and | |
11442 | certain kinds of pointers. For example, if you wrote this,</P> | |
11443 | <DIV class="code"> | |
11444 | <PRE> | |
11445 | %typemap(in) int [10][20] { | |
11446 | $1_ltype temp; | |
11447 | } | |
11448 | </PRE> | |
11449 | </DIV> | |
11450 | <P> then the declaration of <TT>temp</TT> will be expanded as</P> | |
11451 | <DIV class="code"> | |
11452 | <PRE> | |
11453 | int (*)[20] temp; | |
11454 | </PRE> | |
11455 | </DIV> | |
11456 | <P> This is illegal C syntax and won't compile. There is currently no | |
11457 | straightforward way to work around this problem in SWIG due to the way | |
11458 | that typemap code is expanded and processed. However, one possible | |
11459 | workaround is to simply pick an alternative type such as <TT>void *</TT> | |
11460 | and use casts to get the correct type when needed. For example:</P> | |
11461 | <DIV class="code"> | |
11462 | <PRE> | |
11463 | %typemap(in) int [10][20] { | |
11464 | void *temp; | |
11465 | ... | |
11466 | (($1_ltype) temp)[i][j] = x; /* set a value */ | |
11467 | ... | |
11468 | } | |
11469 | </PRE> | |
11470 | </DIV> | |
11471 | <P> Another approach, which only works for arrays is to use the <TT> | |
11472 | $1_basetype</TT> substitution. For example:</P> | |
11473 | <DIV class="code"> | |
11474 | <PRE> | |
11475 | %typemap(in) int [10][20] { | |
11476 | $1_basetype temp[10][20]; | |
11477 | ... | |
11478 | temp[i][j] = x; /* set a value */ | |
11479 | ... | |
11480 | } | |
11481 | </PRE> | |
11482 | </DIV> | |
11483 | <H2><A name="Typemaps_nn25"></A>10.5 Common typemap methods</H2> | |
11484 | <P> The set of typemaps recognized by a language module may vary. | |
11485 | However, the following typemap methods are nearly universal:</P> | |
11486 | <H3><A name="Typemaps_nn26"></A>10.5.1 "in" typemap</H3> | |
11487 | <P> The "in" typemap is used to convert function arguments from the | |
11488 | target language to C. For example:</P> | |
11489 | <DIV class="code"> | |
11490 | <PRE> | |
11491 | %typemap(in) int { | |
11492 | $1 = PyInt_AsLong($input); | |
11493 | } | |
11494 | </PRE> | |
11495 | </DIV> | |
11496 | <P> The following special variables are available:</P> | |
11497 | <DIV class="code"> | |
11498 | <PRE> | |
11499 | $input - Input object holding value to be converted. | |
11500 | $symname - Name of function/method being wrapped | |
11501 | </PRE> | |
11502 | </DIV> | |
11503 | <P> This is probably the most commonly redefined typemap because it can | |
11504 | be used to implement customized conversions.</P> | |
11505 | <P> In addition, the "in" typemap allows the number of converted | |
11506 | arguments to be specified. For example:</P> | |
11507 | <DIV class="code"> | |
11508 | <PRE> | |
11509 | // Ignored argument. | |
11510 | %typemap(in, numinputs=0) int *out (int temp) { | |
11511 | $1 = &temp; | |
11512 | } | |
11513 | </PRE> | |
11514 | </DIV> | |
11515 | <P> At this time, only zero or one arguments may be converted.</P> | |
11516 | <P><B> Compatibility note:</B> Specifying <TT>numinputs=0</TT> is the | |
11517 | same as the old "ignore" typemap.</P> | |
11518 | <H3><A name="Typemaps_nn27"></A>10.5.2 "typecheck" typemap</H3> | |
11519 | <P> The "typecheck" typemap is used to support overloaded functions and | |
11520 | methods. It merely checks an argument to see whether or not it matches | |
11521 | a specific type. For example:</P> | |
11522 | <DIV class="code"> | |
11523 | <PRE> | |
11524 | %typemap(typecheck,precedence=SWIG_TYPECHECK_INTEGER) int { | |
11525 | $1 = PyInt_Check($input) ? 1 : 0; | |
11526 | } | |
11527 | </PRE> | |
11528 | </DIV> | |
11529 | <P> For typechecking, the $1 variable is always a simple integer that is | |
11530 | set to 1 or 0 depending on whether or not the input argument is the | |
11531 | correct type.</P> | |
11532 | <P> If you define new "in" typemaps<EM> and</EM> your program uses | |
11533 | overloaded methods, you should also define a collection of "typecheck" | |
11534 | typemaps. More details about this follow in a later section on | |
11535 | "Typemaps and Overloading."</P> | |
11536 | <H3><A name="Typemaps_nn28"></A>10.5.3 "out" typemap</H3> | |
11537 | <P> The "out" typemap is used to convert function/method return values | |
11538 | from C into the target language. For example:</P> | |
11539 | <DIV class="code"> | |
11540 | <PRE> | |
11541 | %typemap(out) int { | |
11542 | $result = PyInt_FromLong($1); | |
11543 | } | |
11544 | </PRE> | |
11545 | </DIV> | |
11546 | <P> The following special variables are available.</P> | |
11547 | <DIV class="code"> | |
11548 | <PRE> | |
11549 | $result - Result object returned to target language. | |
11550 | $symname - Name of function/method being wrapped | |
11551 | </PRE> | |
11552 | </DIV> | |
11553 | <H3><A name="Typemaps_nn29"></A>10.5.4 "arginit" typemap</H3> | |
11554 | <P> The "arginit" typemap is used to set the initial value of a function | |
11555 | argument--before any conversion has occurred. This is not normally | |
11556 | necessary, but might be useful in highly specialized applications. For | |
11557 | example:</P> | |
11558 | <DIV class="code"> | |
11559 | <PRE> | |
11560 | // Set argument to NULL before any conversion occurs | |
11561 | %typemap(arginit) int *data { | |
11562 | $1 = NULL; | |
11563 | } | |
11564 | </PRE> | |
11565 | </DIV> | |
11566 | <H3><A name="Typemaps_nn30"></A>10.5.5 "default" typemap</H3> | |
11567 | <P> The "default" typemap is used to turn an argument into a default | |
11568 | argument. For example:</P> | |
11569 | <DIV class="code"> | |
11570 | <PRE> | |
11571 | %typemap(default) int flags { | |
11572 | $1 = DEFAULT_FLAGS; | |
11573 | } | |
11574 | ... | |
11575 | int foo(int x, int y, int flags); | |
11576 | </PRE> | |
11577 | </DIV> | |
11578 | <P> The primary use of this typemap is to either change the wrapping of | |
11579 | default arguments or specify a default argument in a language where | |
11580 | they aren't supported (like C). Target languages that do not support | |
11581 | optional arguments, such as Java and C#, effecively ignore the value | |
11582 | specified by this typemap as all arguments must be given.</P> | |
11583 | <P> Once a default typemap has been applied to an argument, all | |
11584 | arguments that follow must have default values. See the <A href="#SWIG_default_args"> | |
11585 | Default/optional arguments</A> section for further information on | |
11586 | default argument wrapping.</P> | |
11587 | <H3><A name="Typemaps_nn31"></A>10.5.6 "check" typemap</H3> | |
11588 | <P> The "check" typemap is used to supply value checking code during | |
11589 | argument conversion. The typemap is applied<EM> after</EM> arguments | |
11590 | have been converted. For example:</P> | |
11591 | <DIV class="code"> | |
11592 | <PRE> | |
11593 | %typemap(check) int positive { | |
11594 | if ($1 <= 0) { | |
11595 | SWIG_exception(SWIG_ValueError,"Expected positive value."); | |
11596 | } | |
11597 | } | |
11598 | </PRE> | |
11599 | </DIV> | |
11600 | <H3><A name="Typemaps_nn32"></A>10.5.7 "argout" typemap</H3> | |
11601 | <P> The "argout" typemap is used to return values from arguments. This | |
11602 | is most commonly used to write wrappers for C/C++ functions that need | |
11603 | to return multiple values. The "argout" typemap is almost always | |
11604 | combined with an "in" typemap---possibly to ignore the input value. For | |
11605 | example:</P> | |
11606 | <DIV class="code"> | |
11607 | <PRE> | |
11608 | /* Set the input argument to point to a temporary variable */ | |
11609 | %typemap(in, numinputs=0) int *out (int temp) { | |
11610 | $1 = &temp; | |
11611 | } | |
11612 | ||
11613 | %typemap(argout) int *out { | |
11614 | // Append output value $1 to $result | |
11615 | ... | |
11616 | } | |
11617 | </PRE> | |
11618 | </DIV> | |
11619 | <P> The following special variables are available.</P> | |
11620 | <DIV class="diagram"> | |
11621 | <PRE> | |
11622 | $result - Result object returned to target language. | |
11623 | $input - The original input object passed. | |
11624 | $symname - Name of function/method being wrapped | |
11625 | </PRE> | |
11626 | </DIV> | |
11627 | <P> The code supplied to the "argout" typemap is always placed after the | |
11628 | "out" typemap. If multiple return values are used, the extra return | |
11629 | values are often appended to return value of the function.</P> | |
11630 | <P> See the <TT>typemaps.i</TT> library for examples.</P> | |
11631 | <H3><A name="Typemaps_nn33"></A>10.5.8 "freearg" typemap</H3> | |
11632 | <P> The "freearg" typemap is used to cleanup argument data. It is only | |
11633 | used when an argument might have allocated resources that need to be | |
11634 | cleaned up when the wrapper function exits. The "freearg" typemap | |
11635 | usually cleans up argument resources allocated by the "in" typemap. For | |
11636 | example:</P> | |
11637 | <DIV class="code"> | |
11638 | <PRE> | |
11639 | // Get a list of integers | |
11640 | %typemap(in) int *items { | |
11641 | int nitems = Length($input); | |
11642 | $1 = (int *) malloc(sizeof(int)*nitems); | |
11643 | } | |
11644 | // Free the list | |
11645 | %typemap(freearg) int *items { | |
11646 | free($1); | |
11647 | } | |
11648 | </PRE> | |
11649 | </DIV> | |
11650 | <P> The "freearg" typemap inserted at the end of the wrapper function, | |
11651 | just before control is returned back to the target language. This code | |
11652 | is also placed into a special variable <TT>$cleanup</TT> that may be | |
11653 | used in other typemaps whenever a wrapper function needs to abort | |
11654 | prematurely.</P> | |
11655 | <H3><A name="Typemaps_nn34"></A>10.5.9 "newfree" typemap</H3> | |
11656 | <P> The "newfree" typemap is used in conjunction with the <TT>%newobject</TT> | |
11657 | directive and is used to deallocate memory used by the return result of | |
11658 | a function. For example:</P> | |
11659 | <DIV class="code"> | |
11660 | <PRE> | |
11661 | %typemap(newfree) string * { | |
11662 | delete $1; | |
11663 | } | |
11664 | %typemap(out) string * { | |
11665 | $result = PyString_FromString($1->c_str()); | |
11666 | } | |
11667 | ... | |
11668 | ||
11669 | %newobject foo; | |
11670 | ... | |
11671 | string *foo(); | |
11672 | </PRE> | |
11673 | </DIV> | |
11674 | <H3><A name="Typemaps_nn35"></A>10.5.10 "memberin" typemap</H3> | |
11675 | <P> The "memberin" typemap is used to copy data from<EM> an already | |
11676 | converted input value</EM> into a structure member. It is typically | |
11677 | used to handle array members and other special cases. For example:</P> | |
11678 | <DIV class="code"> | |
11679 | <PRE> | |
11680 | %typemap(memberin) int [4] { | |
11681 | memmove($1, $input, 4*sizeof(int)); | |
11682 | } | |
11683 | </PRE> | |
11684 | </DIV> | |
11685 | <P> It is rarely necessary to write "memberin" typemaps---SWIG already | |
11686 | provides a default implementation for arrays, strings, and other | |
11687 | objects.</P> | |
11688 | <H3><A name="Typemaps_nn36"></A>10.5.11 "varin" typemap</H3> | |
11689 | <P> The "varin" typemap is used to convert objects in the target | |
11690 | language to C for the purposes of assigning to a C/C++ global variable. | |
11691 | This is implementation specific.</P> | |
11692 | <H3><A name="Typemaps_nn37"></A>10.5.12 "varout" typemap</H3> | |
11693 | <P> The "varout" typemap is used to convert a C/C++ object to an object | |
11694 | in the target language when reading a C/C++ global variable. This is | |
11695 | implementation specific.</P> | |
11696 | <H3><A name="throws_typemap"></A>10.5.13 "throws" typemap</H3> | |
11697 | <P> The "throws" typemap is only used when SWIG parses a C++ method with | |
11698 | an exception specification. It provides a default mechanism for | |
11699 | handling C++ methods that have declared the exceptions it will throw. | |
11700 | The purpose of this typemap is to convert a C++ exception into an error | |
11701 | or exception in the target language. It is slightly different to the | |
11702 | other typemaps as it is based around the exception type rather than the | |
11703 | type of a parameter or variable. For example:</P> | |
11704 | <DIV class="code"> | |
11705 | <PRE> | |
11706 | %typemap(throws) const char * %{ | |
11707 | PyErr_SetString(PyExc_RuntimeError, $1); | |
11708 | SWIG_fail; | |
11709 | %} | |
11710 | void bar() throw (const char *); | |
11711 | </PRE> | |
11712 | </DIV> | |
11713 | <P> As can be seen from the generated code below, SWIG generates an | |
11714 | exception handler with the catch block comprising the "throws" typemap | |
11715 | content.</P> | |
11716 | <DIV class="code"> | |
11717 | <PRE> | |
11718 | ... | |
11719 | try { | |
11720 | bar(); | |
11721 | } | |
11722 | catch(char const *_e) { | |
11723 | PyErr_SetString(PyExc_RuntimeError, _e); | |
11724 | SWIG_fail; | |
11725 | ||
11726 | } | |
11727 | ... | |
11728 | </PRE> | |
11729 | </DIV> | |
11730 | <P> Note that if your methods do not have an exception specification yet | |
11731 | they do throw exceptions, SWIG cannot know how to deal with them. For a | |
11732 | neat way to handle these, see the <A href="#exception">Exception | |
11733 | handling with %exception</A> section.</P> | |
11734 | <H2><A name="Typemaps_nn39"></A>10.6 Some typemap examples</H2> | |
11735 | <P> This section contains a few examples. Consult language module | |
11736 | documentation for more examples.</P> | |
11737 | <H3><A name="Typemaps_nn40"></A>10.6.1 Typemaps for arrays</H3> | |
11738 | <P> A common use of typemaps is to provide support for C arrays | |
11739 | appearing both as arguments to functions and as structure members.</P> | |
11740 | <P> For example, suppose you had a function like this:</P> | |
11741 | <DIV class="code"> | |
11742 | <PRE> | |
11743 | void set_vector(int type, float value[4]); | |
11744 | </PRE> | |
11745 | </DIV> | |
11746 | <P> If you wanted to handle <TT>float value[4]</TT> as a list of floats, | |
11747 | you might write a typemap similar to this:</P> | |
11748 | <DIV class="code"> | |
11749 | <PRE> | |
11750 | ||
11751 | %typemap(in) float value[4] (float temp[4]) { | |
11752 | int i; | |
11753 | if (!PySequence_Check($input)) { | |
11754 | PyErr_SetString(PyExc_ValueError,"Expected a sequence"); | |
11755 | return NULL; | |
11756 | } | |
11757 | if (PySequence_Length($input) != 4) { | |
11758 | PyErr_SetString(PyExc_ValueError,"Size mismatch. Expected 4 elements"); | |
11759 | return NULL; | |
11760 | } | |
11761 | for (i = 0; i < 4; i++) { | |
11762 | PyObject *o = PySequence_GetItem($input,i); | |
11763 | if (PyNumber_Check(o)) { | |
11764 | temp[i] = (float) PyFloat_AsDouble(o); | |
11765 | } else { | |
11766 | PyErr_SetString(PyExc_ValueError,"Sequence elements must be numbers"); | |
11767 | return NULL; | |
11768 | } | |
11769 | } | |
11770 | $1 = temp; | |
11771 | } | |
11772 | </PRE> | |
11773 | </DIV> | |
11774 | <P> In this example, the variable <TT>temp</TT> allocates a small array | |
11775 | on the C stack. The typemap then populates this array and passes it to | |
11776 | the underlying C function.</P> | |
11777 | <P> When used from Python, the typemap allows the following type of | |
11778 | function call:</P> | |
11779 | <DIV class="targetlang"> | |
11780 | <PRE> | |
11781 | >>> set_vector(type, [ 1, 2.5, 5, 20 ]) | |
11782 | </PRE> | |
11783 | </DIV> | |
11784 | <P> If you wanted to generalize the typemap to apply to arrays of all | |
11785 | dimensions you might write this:</P> | |
11786 | <DIV class="code"> | |
11787 | <PRE> | |
11788 | %typemap(in) float value[ANY] (float temp[$1_dim0]) { | |
11789 | int i; | |
11790 | if (!PySequence_Check($input)) { | |
11791 | PyErr_SetString(PyExc_ValueError,"Expected a sequence"); | |
11792 | return NULL; | |
11793 | } | |
11794 | if (PySequence_Length($input) != $1_dim0) { | |
11795 | PyErr_SetString(PyExc_ValueError,"Size mismatch. Expected $1_dim0 elements"); | |
11796 | return NULL; | |
11797 | } | |
11798 | for (i = 0; i < $1_dim0; i++) { | |
11799 | PyObject *o = PySequence_GetItem($input,i); | |
11800 | if (PyNumber_Check(o)) { | |
11801 | temp[i] = (float) PyFloat_AsDouble(o); | |
11802 | } else { | |
11803 | PyErr_SetString(PyExc_ValueError,"Sequence elements must be numbers"); | |
11804 | return NULL; | |
11805 | } | |
11806 | } | |
11807 | $1 = temp; | |
11808 | } | |
11809 | </PRE> | |
11810 | </DIV> | |
11811 | <P> In this example, the special variable <TT>$1_dim0</TT> is expanded | |
11812 | with the actual array dimensions. Multidimensional arrays can be | |
11813 | matched in a similar manner. For example:</P> | |
11814 | <DIV class="code"> | |
11815 | <PRE> | |
11816 | %typemap(python,in) float matrix[ANY][ANY] (float temp[$1_dim0][$1_dim1]) { | |
11817 | ... convert a 2d array ... | |
11818 | } | |
11819 | </PRE> | |
11820 | </DIV> | |
11821 | <P> For large arrays, it may be impractical to allocate storage on the | |
11822 | stack using a temporary variable as shown. To work with heap allocated | |
11823 | data, the following technique can be used.</P> | |
11824 | <DIV class="code"> | |
11825 | <PRE> | |
11826 | %typemap(in) float value[ANY] { | |
11827 | int i; | |
11828 | if (!PySequence_Check($input)) { | |
11829 | PyErr_SetString(PyExc_ValueError,"Expected a sequence"); | |
11830 | return NULL; | |
11831 | } | |
11832 | if (PySequence_Length($input) != $1_dim0) { | |
11833 | PyErr_SetString(PyExc_ValueError,"Size mismatch. Expected $1_dim0 elements"); | |
11834 | return NULL; | |
11835 | } | |
11836 | $1 = (float *) malloc($1_dim0*sizeof(float)); | |
11837 | for (i = 0; i < $1_dim0; i++) { | |
11838 | PyObject *o = PySequence_GetItem($input,i); | |
11839 | if (PyNumber_Check(o)) { | |
11840 | $1[i] = (float) PyFloat_AsDouble(o); | |
11841 | } else { | |
11842 | PyErr_SetString(PyExc_ValueError,"Sequence elements must be numbers"); | |
11843 | free($1); | |
11844 | return NULL; | |
11845 | } | |
11846 | } | |
11847 | } | |
11848 | %typemap(freearg) float value[ANY] { | |
11849 | if ($1) free($1); | |
11850 | } | |
11851 | </PRE> | |
11852 | </DIV> | |
11853 | <P> In this case, an array is allocated using <TT>malloc</TT>. The <TT> | |
11854 | freearg</TT> typemap is then used to release the argument after the | |
11855 | function has been called.</P> | |
11856 | <P> Another common use of array typemaps is to provide support for array | |
11857 | structure members. Due to subtle differences between pointers and | |
11858 | arrays in C, you can't just "assign" to a array structure member. | |
11859 | Instead, you have to explicitly copy elements into the array. For | |
11860 | example, suppose you had a structure like this:</P> | |
11861 | <DIV class="code"> | |
11862 | <PRE> | |
11863 | struct SomeObject { | |
11864 | float value[4]; | |
11865 | ... | |
11866 | }; | |
11867 | </PRE> | |
11868 | </DIV> | |
11869 | <P> When SWIG runs, it won't produce any code to set the <TT>vec</TT> | |
11870 | member. You may even get a warning message like this:</P> | |
11871 | <DIV class="shell"> | |
11872 | <PRE> | |
11873 | swig -python example.i | |
11874 | Generating wrappers for Python | |
11875 | example.i:10. Warning. Array member value will be read-only. | |
11876 | </PRE> | |
11877 | </DIV> | |
11878 | <P> These warning messages indicate that SWIG does not know how you want | |
11879 | to set the <TT>vec</TT> field.</P> | |
11880 | <P> To fix this, you can supply a special "memberin" typemap like this:</P> | |
11881 | <DIV class="code"> | |
11882 | <PRE> | |
11883 | %typemap(memberin) float [ANY] { | |
11884 | int i; | |
11885 | for (i = 0; i < $1_dim0; i++) { | |
11886 | $1[i] = $input[i]; | |
11887 | } | |
11888 | } | |
11889 | </PRE> | |
11890 | </DIV> | |
11891 | <P> The memberin typemap is used to set a structure member from data | |
11892 | that has already been converted from the target language to C. In this | |
11893 | case, <TT>$input</TT> is the local variable in which converted input | |
11894 | data is stored. This typemap then copies this data into the structure.</P> | |
11895 | <P> When combined with the earlier typemaps for arrays, the combination | |
11896 | of the "in" and "memberin" typemap allows the following usage:</P> | |
11897 | <DIV class="targetlang"> | |
11898 | <PRE> | |
11899 | >>> s = SomeObject() | |
11900 | >>> s.x = [1, 2.5, 5, 10] | |
11901 | </PRE> | |
11902 | </DIV> | |
11903 | <P> Related to structure member input, it may be desirable to return | |
11904 | structure members as a new kind of object. For example, in this | |
11905 | example, you will get very odd program behavior where the structure | |
11906 | member can be set nicely, but reading the member simply returns a | |
11907 | pointer:</P> | |
11908 | <DIV class="targetlang"> | |
11909 | <PRE> | |
11910 | >>> s = SomeObject() | |
11911 | >>> s.x = [1, 2.5, 5, 10] | |
11912 | >>> print s.x | |
11913 | _1008fea8_p_float | |
11914 | >>> | |
11915 | </PRE> | |
11916 | </DIV> | |
11917 | <P> To fix this, you can write an "out" typemap. For example:</P> | |
11918 | <DIV class="code"> | |
11919 | <PRE> | |
11920 | %typemap(out) float [ANY] { | |
11921 | int i; | |
11922 | $result = PyList_New($1_dim0); | |
11923 | for (i = 0; i < $1_dim0; i++) { | |
11924 | PyObject *o = PyFloat_FromDouble((double) $1[i]); | |
11925 | PyList_SetItem($result,i,o); | |
11926 | } | |
11927 | } | |
11928 | </PRE> | |
11929 | </DIV> | |
11930 | <P> Now, you will find that member access is quite nice:</P> | |
11931 | <DIV class="targetlang"> | |
11932 | <PRE> | |
11933 | >>> s = SomeObject() | |
11934 | >>> s.x = [1, 2.5, 5, 10] | |
11935 | >>> print s.x | |
11936 | [ 1, 2.5, 5, 10] | |
11937 | </PRE> | |
11938 | </DIV> | |
11939 | <P><B> Compatibility Note:</B> SWIG1.1 used to provide a special | |
11940 | "memberout" typemap. However, it was mostly useless and has since been | |
11941 | eliminated. To return structure members, simply use the "out" typemap.</P> | |
11942 | <H3><A name="Typemaps_nn41"></A>10.6.2 Implementing constraints with | |
11943 | typemaps</H3> | |
11944 | <P> One particularly interesting application of typemaps is the | |
11945 | implementation of argument constraints. This can be done with the | |
11946 | "check" typemap. When used, this allows you to provide code for | |
11947 | checking the values of function arguments. For example :</P> | |
11948 | <DIV class="code"> | |
11949 | <PRE> | |
11950 | %module math | |
11951 | ||
11952 | %typemap(check) double posdouble { | |
11953 | if ($1 < 0) { | |
11954 | croak("Expecting a positive number"); | |
11955 | } | |
11956 | } | |
11957 | ||
11958 | ... | |
11959 | double sqrt(double posdouble); | |
11960 | ||
11961 | </PRE> | |
11962 | </DIV> | |
11963 | <P> This provides a sanity check to your wrapper function. If a negative | |
11964 | number is passed to this function, a Perl exception will be raised and | |
11965 | your program terminated with an error message.</P> | |
11966 | <P> This kind of checking can be particularly useful when working with | |
11967 | pointers. For example :</P> | |
11968 | <DIV class="code"> | |
11969 | <PRE> | |
11970 | %typemap(check) Vector * { | |
11971 | if ($1 == 0) { | |
11972 | PyErr_SetString(PyExc_TypeError,"NULL Pointer not allowed"); | |
11973 | return NULL; | |
11974 | } | |
11975 | } | |
11976 | ||
11977 | </PRE> | |
11978 | </DIV> | |
11979 | <P> will prevent any function involving a <TT>Vector *</TT> from | |
11980 | accepting a NULL pointer. As a result, SWIG can often prevent a | |
11981 | potential segmentation faults or other run-time problems by raising an | |
11982 | exception rather than blindly passing values to the underlying C/C++ | |
11983 | program.</P> | |
11984 | <P> Note: A more advanced constraint checking system is in development. | |
11985 | Stay tuned.</P> | |
11986 | <H2><A name="Typemaps_nn42"></A>10.7 Multi-argument typemaps</H2> | |
11987 | <P> So far, the typemaps presented have focused on the problem of | |
11988 | dealing with single values. For example, converting a single input | |
11989 | object to a single argument in a function call. However, certain | |
11990 | conversion problems are difficult to handle in this manner. As an | |
11991 | example, consider the example at the very beginning of this chapter:</P> | |
11992 | <DIV class="code"> | |
11993 | <PRE> | |
11994 | int foo(int argc, char *argv[]); | |
11995 | </PRE> | |
11996 | </DIV> | |
11997 | <P> Suppose that you wanted to wrap this function so that it accepted a | |
11998 | single list of strings like this:</P> | |
11999 | <DIV class="targetlang"> | |
12000 | <PRE> | |
12001 | >>> foo(["ale","lager","stout"]) | |
12002 | </PRE> | |
12003 | </DIV> | |
12004 | <P> To do this, you not only need to map a list of strings to <TT>char | |
12005 | *argv[]</TT>, but the value of <TT>int argc</TT> is implicitly | |
12006 | determined by the length of the list. Using only simple typemaps, this | |
12007 | type of conversion is possible, but extremely painful. Therefore, | |
12008 | SWIG1.3 introduces the notion of multi-argument typemaps.</P> | |
12009 | <P> A multi-argument typemap is a conversion rule that specifies how to | |
12010 | convert a<EM> single</EM> object in the target language to set of | |
12011 | consecutive function arguments in C/C++. For example, the following | |
12012 | multi-argument maps perform the conversion described for the above | |
12013 | example:</P> | |
12014 | <DIV class="code"> | |
12015 | <PRE> | |
12016 | %typemap(in) (int argc, char *argv[]) { | |
12017 | int i; | |
12018 | if (!PyList_Check($input)) { | |
12019 | PyErr_SetString(PyExc_ValueError, "Expecting a list"); | |
12020 | return NULL; | |
12021 | } | |
12022 | $1 = PyList_Size($input); | |
12023 | $2 = (char **) malloc(($1+1)*sizeof(char *)); | |
12024 | for (i = 0; i < $1; i++) { | |
12025 | PyObject *s = PyList_GetItem($input,i); | |
12026 | if (!PyString_Check(s)) { | |
12027 | free($2); | |
12028 | PyErr_SetString(PyExc_ValueError, "List items must be strings"); | |
12029 | return NULL; | |
12030 | } | |
12031 | $2[i] = PyString_AsString(s); | |
12032 | } | |
12033 | $2[i] = 0; | |
12034 | } | |
12035 | ||
12036 | %typemap(freearg) (int argc, char *argv[]) { | |
12037 | if ($2) free($2); | |
12038 | } | |
12039 | </PRE> | |
12040 | </DIV> | |
12041 | <P> A multi-argument map is always specified by surrounding the | |
12042 | arguments with parentheses as shown. For example:</P> | |
12043 | <DIV class="code"> | |
12044 | <PRE> | |
12045 | %typemap(in) (int argc, char *argv[]) { ... } | |
12046 | </PRE> | |
12047 | </DIV> | |
12048 | <P> Within the typemap code, the variables <TT>$1</TT>, <TT>$2</TT>, and | |
12049 | so forth refer to each type in the map. All of the usual substitutions | |
12050 | apply--just use the appropriate <TT>$1</TT> or <TT>$2</TT> prefix on | |
12051 | the variable name (e.g., <TT>$2_type</TT>, <TT>$1_ltype</TT>, etc.)</P> | |
12052 | <P> Multi-argument typemaps always have precedence over simple typemaps | |
12053 | and SWIG always performs longest-match searching. Therefore, you will | |
12054 | get the following behavior:</P> | |
12055 | <DIV class="code"> | |
12056 | <PRE> | |
12057 | %typemap(in) int argc { ... typemap 1 ... } | |
12058 | %typemap(in) (int argc, char *argv[]) { ... typemap 2 ... } | |
12059 | %typemap(in) (int argc, char *argv[], char *env[]) { ... typemap 3 ... } | |
12060 | ||
12061 | int foo(int argc, char *argv[]); // Uses typemap 2 | |
12062 | int bar(int argc, int x); // Uses typemap 1 | |
12063 | int spam(int argc, char *argv[], char *env[]); // Uses typemap 3 | |
12064 | </PRE> | |
12065 | </DIV> | |
12066 | <P> It should be stressed that multi-argument typemaps can appear | |
12067 | anywhere in a function declaration and can appear more than once. For | |
12068 | example, you could write this:</P> | |
12069 | <DIV class="code"> | |
12070 | <PRE> | |
12071 | %typemap(in) (int scount, char *swords[]) { ... } | |
12072 | %typemap(in) (int wcount, char *words[]) { ... } | |
12073 | ||
12074 | void search_words(int scount, char *swords[], int wcount, char *words[], int maxcount); | |
12075 | </PRE> | |
12076 | </DIV> | |
12077 | <P> Other directives such as <TT>%apply</TT> and <TT>%clear</TT> also | |
12078 | work with multi-argument maps. For example:</P> | |
12079 | <DIV class="code"> | |
12080 | <PRE> | |
12081 | %apply (int argc, char *argv[]) { | |
12082 | (int scount, char *swords[]), | |
12083 | (int wcount, char *words[]) | |
12084 | }; | |
12085 | ... | |
12086 | %clear (int scount, char *swords[]), (int wcount, char *words[]); | |
12087 | ... | |
12088 | </PRE> | |
12089 | </DIV> | |
12090 | <P> Although multi-argument typemaps may seem like an exotic, little | |
12091 | used feature, there are several situations where they make sense. | |
12092 | First, suppose you wanted to wrap functions similar to the low-level <TT> | |
12093 | read()</TT> and <TT>write()</TT> system calls. For example:</P> | |
12094 | <DIV class="code"> | |
12095 | <PRE> | |
12096 | typedef unsigned int size_t; | |
12097 | ||
12098 | int read(int fd, void *rbuffer, size_t len); | |
12099 | int write(int fd, void *wbuffer, size_t len); | |
12100 | </PRE> | |
12101 | </DIV> | |
12102 | <P> As is, the only way to use the functions would be to allocate memory | |
12103 | and pass some kind of pointer as the second argument---a process that | |
12104 | might require the use of a helper function. However, using | |
12105 | multi-argument maps, the functions can be transformed into something | |
12106 | more natural. For example, you might write typemaps like this:</P> | |
12107 | <DIV class="code"> | |
12108 | <PRE> | |
12109 | // typemap for an outgoing buffer | |
12110 | %typemap(in) (void *wbuffer, size_t len) { | |
12111 | if (!PyString_Check($input)) { | |
12112 | PyErr_SetString(PyExc_ValueError, "Expecting a string"); | |
12113 | return NULL; | |
12114 | } | |
12115 | $1 = (void *) PyString_AsString($input); | |
12116 | $2 = PyString_Size($input); | |
12117 | } | |
12118 | ||
12119 | // typemap for an incoming buffer | |
12120 | %typemap(in) (void *rbuffer, size_t len) { | |
12121 | if (!PyInt_Check($input)) { | |
12122 | PyErr_SetString(PyExc_ValueError, "Expecting an integer"); | |
12123 | return NULL; | |
12124 | } | |
12125 | $2 = PyInt_AsLong($input); | |
12126 | if ($2 < 0) { | |
12127 | PyErr_SetString(PyExc_ValueError, "Positive integer expected"); | |
12128 | return NULL; | |
12129 | } | |
12130 | $1 = (void *) malloc($2); | |
12131 | } | |
12132 | ||
12133 | // Return the buffer. Discarding any previous return result | |
12134 | %typemap(argout) (void *rbuffer, size_t len) { | |
12135 | Py_XDECREF($result); /* Blow away any previous result */ | |
12136 | if (result < 0) { /* Check for I/O error */ | |
12137 | free($1); | |
12138 | PyErr_SetFromErrno(PyExc_IOError); | |
12139 | return NULL; | |
12140 | } | |
12141 | $result = PyString_FromStringAndSize($1,result); | |
12142 | free($1); | |
12143 | } | |
12144 | </PRE> | |
12145 | </DIV> | |
12146 | <P> (note: In the above example, <TT>$result</TT> and <TT>result</TT> | |
12147 | are two different variables. <TT>result</TT> is the real C datatype | |
12148 | that was returned by the function. <TT>$result</TT> is the scripting | |
12149 | language object being returned to the interpreter.).</P> | |
12150 | <P> Now, in a script, you can write code that simply passes buffers as | |
12151 | strings like this:</P> | |
12152 | <DIV class="targetlang"> | |
12153 | <PRE> | |
12154 | >>> f = example.open("Makefile") | |
12155 | >>> example.read(f,40) | |
12156 | 'TOP = ../..\nSWIG = $(TOP)/.' | |
12157 | >>> example.read(f,40) | |
12158 | './swig\nSRCS = example.c\nTARGET ' | |
12159 | >>> example.close(f) | |
12160 | 0 | |
12161 | >>> g = example.open("foo", example.O_WRONLY | example.O_CREAT, 0644) | |
12162 | >>> example.write(g,"Hello world\n") | |
12163 | 12 | |
12164 | >>> example.write(g,"This is a test\n") | |
12165 | 15 | |
12166 | >>> example.close(g) | |
12167 | 0 | |
12168 | >>> | |
12169 | </PRE> | |
12170 | </DIV> | |
12171 | <P> A number of multi-argument typemap problems also arise in libraries | |
12172 | that perform matrix-calculations--especially if they are mapped onto | |
12173 | low-level Fortran or C code. For example, you might have a function | |
12174 | like this:</P> | |
12175 | <DIV class="code"> | |
12176 | <PRE> | |
12177 | int is_symmetric(double *mat, int rows, int columns); | |
12178 | </PRE> | |
12179 | </DIV> | |
12180 | <P> In this case, you might want to pass some kind of higher-level | |
12181 | object as an matrix. To do this, you could write a multi-argument | |
12182 | typemap like this:</P> | |
12183 | <DIV class="code"> | |
12184 | <PRE> | |
12185 | %typemap(in) (double *mat, int rows, int columns) { | |
12186 | MatrixObject *a; | |
12187 | a = GetMatrixFromObject($input); /* Get matrix somehow */ | |
12188 | ||
12189 | /* Get matrix properties */ | |
12190 | $1 = GetPointer(a); | |
12191 | $2 = GetRows(a); | |
12192 | $3 = GetColumns(a); | |
12193 | } | |
12194 | </PRE> | |
12195 | </DIV> | |
12196 | <P> This kind of technique can be used to hook into scripting-language | |
12197 | matrix packages such as Numeric Python. However, it should also be | |
12198 | stressed that some care is in order. For example, when crossing | |
12199 | languages you may need to worry about issues such as row-major vs. | |
12200 | column-major ordering (and perform conversions if needed).</P> | |
12201 | <H2><A name="runtime_type_checker"></A>10.8 The run-time type checker</H2> | |
12202 | <P> Most scripting languages need type information at run-time. This | |
12203 | type information can include how to construct types, how to garbage | |
12204 | collect types, and the inheritance relationships between types. If the | |
12205 | language interface does not provide its own type information storage, | |
12206 | the generated SWIG code needs to provide it.</P> | |
12207 | <P> Requirements for the type system:</P> | |
12208 | <UL> | |
12209 | <LI>Store inheritance and type equivalence information and be able to | |
12210 | correctly re-create the type pointer.</LI> | |
12211 | <LI>Share type information between modules.</LI> | |
12212 | <LI>Modules can be loaded in any order, irregardless of actual type | |
12213 | dependency.</LI> | |
12214 | <LI>Avoid the use of dynamically allocated memory, and library/system | |
12215 | calls in general.</LI> | |
12216 | <LI>Provide a reasonably fast implementation, minimizing the lookup time | |
12217 | for all language modules.</LI> | |
12218 | <LI>Custom, language specific information can be attached to types.</LI> | |
12219 | <LI>Modules can be unloaded from the type system.</LI> | |
12220 | </UL> | |
12221 | <H3><A name="Typemaps_nn45"></A>10.8.1 Implementation</H3> | |
12222 | <P> The run-time type checker is used by many, but not all, of SWIG's | |
12223 | supported target languages. The run-time type checker features are not | |
12224 | required and are thus not used for strongly typed languages such as | |
12225 | Java and C#. The scripting and scheme based languages rely on it and it | |
12226 | forms a critical part of SWIG's operation for these languages.</P> | |
12227 | <P> When pointers, arrays, and objects are wrapped by SWIG, they are | |
12228 | normally converted into typed pointer objects. For example, an instance | |
12229 | of <TT>Foo *</TT> might be a string encoded like this:</P> | |
12230 | <DIV class="diagram"> | |
12231 | <PRE> | |
12232 | _108e688_p_Foo | |
12233 | </PRE> | |
12234 | </DIV> | |
12235 | <P> At a basic level, the type checker simply restores some type-safety | |
12236 | to extension modules. However, the type checker is also responsible for | |
12237 | making sure that wrapped C++ classes are handled correctly---especially | |
12238 | when inheritance is used. This is especially important when an | |
12239 | extension module makes use of multiple inheritance. For example:</P> | |
12240 | <DIV class="code"> | |
12241 | <PRE> | |
12242 | class Foo { | |
12243 | int x; | |
12244 | }; | |
12245 | ||
12246 | class Bar { | |
12247 | int y; | |
12248 | }; | |
12249 | ||
12250 | class FooBar : public Foo, public Bar { | |
12251 | int z; | |
12252 | }; | |
12253 | </PRE> | |
12254 | </DIV> | |
12255 | <P> When the class <TT>FooBar</TT> is organized in memory, it contains | |
12256 | the contents of the classes <TT>Foo</TT> and <TT>Bar</TT> as well as | |
12257 | its own data members. For example:</P> | |
12258 | <DIV class="diagram"> | |
12259 | <PRE> | |
12260 | FooBar --> | -----------| <-- Foo | |
12261 | | int x | | |
12262 | |------------| <-- Bar | |
12263 | | int y | | |
12264 | |------------| | |
12265 | | int z | | |
12266 | |------------| | |
12267 | </PRE> | |
12268 | </DIV> | |
12269 | <P> Because of the way that base class data is stacked together, the | |
12270 | casting of a <TT>Foobar *</TT> to either of the base classes may change | |
12271 | the actual value of the pointer. This means that it is generally not | |
12272 | safe to represent pointers using a simple integer or a bare <TT>void *</TT> | |
12273 | ---type tags are needed to implement correct handling of pointer values | |
12274 | (and to make adjustments when needed).</P> | |
12275 | <P> In the wrapper code generated for each language, pointers are | |
12276 | handled through the use of special type descriptors and conversion | |
12277 | functions. For example, if you look at the wrapper code for Python, you | |
12278 | will see code like this:</P> | |
12279 | <DIV class="code"> | |
12280 | <PRE> | |
12281 | if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_Foo,1)) == -1) return NULL; | |
12282 | </PRE> | |
12283 | </DIV> | |
12284 | <P> In this code, <TT>SWIGTYPE_p_Foo</TT> is the type descriptor that | |
12285 | describes <TT>Foo *</TT>. The type descriptor is actually a pointer to | |
12286 | a structure that contains information about the type name to use in the | |
12287 | target language, a list of equivalent typenames (via typedef or | |
12288 | inheritance), and pointer value handling information (if applicable). | |
12289 | The <TT>SWIG_ConvertPtr()</TT> function is simply a utility function | |
12290 | that takes a pointer object in the target language and a | |
12291 | type-descriptor objects and uses this information to generate a C++ | |
12292 | pointer. However, the exact name and calling conventions of the | |
12293 | conversion function depends on the target language (see language | |
12294 | specific chapters for details).</P> | |
12295 | <P> The actual type code is in swigrun.swg, and gets inserted near the | |
12296 | top of the generated swig wrapper file. The phrase "a type X that can | |
12297 | cast into a type Y" means that given a type X, it can be converted into | |
12298 | a type Y. In other words, X is a derived class of Y or X is a typedef | |
12299 | of Y. The structure to store type information looks like this:</P> | |
12300 | <DIV class="code"> | |
12301 | <PRE> | |
12302 | /* Structure to store information on one type */ | |
12303 | typedef struct swig_type_info { | |
12304 | const char *name; /* mangled name of this type */ | |
12305 | const char *str; /* human readable name for this type */ | |
12306 | swig_dycast_func dcast; /* dynamic cast function down a hierarchy */ | |
12307 | struct swig_cast_info *cast; /* Linked list of types that can cast into this type */ | |
12308 | void *clientdata; /* Language specific type data */ | |
12309 | } swig_type_info; | |
12310 | ||
12311 | /* Structure to store a type and conversion function used for casting */ | |
12312 | typedef struct swig_cast_info { | |
12313 | swig_type_info *type; /* pointer to type that is equivalent to this type */ | |
12314 | swig_converter_func converter; /* function to cast the void pointers */ | |
12315 | struct swig_cast_info *next; /* pointer to next cast in linked list */ | |
12316 | struct swig_cast_info *prev; /* pointer to the previous cast */ | |
12317 | } swig_cast_info; | |
12318 | </PRE> | |
12319 | </DIV> | |
12320 | <P> Each <TT>swig_type_info</TT> stores a linked list of types that it | |
12321 | is equivalent to. Each entry in this doubly linked list stores a | |
12322 | pointer back to another swig_type_info structure, along with a pointer | |
12323 | to a conversion function. This conversion function is used to solve the | |
12324 | above problem of the FooBar class, correctly returning a pointer to the | |
12325 | type we want.</P> | |
12326 | <P> The basic problem we need to solve is verifying and building | |
12327 | arguments passed to functions. So going back to the <TT> | |
12328 | SWIG_ConvertPtr()</TT> function example from above, we are expecting a <TT> | |
12329 | Foo *</TT> and need to check if <TT>obj0</TT> is in fact a <TT>Foo *</TT> | |
12330 | . From before, <TT>SWIGTYPE_p_Foo</TT> is just a pointer to the <TT> | |
12331 | swig_type_info</TT> structure describing <TT>Foo *</TT>. So we loop | |
12332 | though the linked list of <TT>swig_cast_info</TT> structures attached | |
12333 | to <TT>SWIGTYPE_p_Foo</TT>. If we see that the type of <TT>obj0</TT> is | |
12334 | in the linked list, we pass the object through the associated | |
12335 | conversion function and then return a positive. If we reach the end of | |
12336 | the linked list without a match, then <TT>obj0</TT> can not be | |
12337 | converted to a <TT>Foo *</TT> and an error is generated.</P> | |
12338 | <P> Another issue needing to be addressed is sharing type information | |
12339 | between multiple modules. More explicitly, we need to have ONE <TT> | |
12340 | swig_type_info</TT> for each type. If two modules both use the type, the | |
12341 | second module loaded must lookup and use the swig_type_info structure | |
12342 | from the module already loaded. Because no dynamic memory is used and | |
12343 | the circular dependencies of the casting information, loading the type | |
12344 | information is somewhat tricky, and not explained here. A complete | |
12345 | description is in the <TT>common.swg</TT> file (and near the top of any | |
12346 | generated file).</P> | |
12347 | <P> Each module has one swig_module_info structure which looks like | |
12348 | this:</P> | |
12349 | <DIV class="code"> | |
12350 | <PRE> | |
12351 | /* Structure used to store module information | |
12352 | * Each module generates one structure like this, and the runtime collects | |
12353 | * all of these structures and stores them in a circularly linked list.*/ | |
12354 | typedef struct swig_module_info { | |
12355 | swig_type_info **types; /* Array of pointers to swig_type_info structs in this module */ | |
12356 | int size; /* Number of types in this module */ | |
12357 | struct swig_module_info *next; /* Pointer to next element in circularly linked list */ | |
12358 | swig_type_info **type_initial; /* Array of initially generated type structures */ | |
12359 | swig_cast_info **cast_initial; /* Array of initially generated casting structures */ | |
12360 | void *clientdata; /* Language specific module data */ | |
12361 | } swig_module_info; | |
12362 | </PRE> | |
12363 | </DIV> | |
12364 | <P> Each module stores an array of pointers to <TT>swig_type_info</TT> | |
12365 | structures and the number of types in this module. So when a second | |
12366 | module is loaded, it finds the <TT>swig_module_info</TT> structure for | |
12367 | the first module and searches the array of types. If any of its own | |
12368 | types are in the first module and have already been loaded, it uses | |
12369 | those <TT>swig_type_info</TT> structures rather than creating new ones. | |
12370 | These <TT>swig_module_info</TT> structures are chained together in a | |
12371 | circularly linked list.</P> | |
12372 | <H3><A name="Typemaps_nn46"></A>10.8.2 Usage</H3> | |
12373 | <P>This section covers how to use these functions from typemaps. To | |
12374 | learn how to call these functions from external files (not the | |
12375 | generated _wrap.c file), see the <A href="#external_run_time">External | |
12376 | access to the run-time system</A> section.</P> | |
12377 | <P>When pointers are converted in a typemap, the typemap code often | |
12378 | looks similar to this:</P> | |
12379 | <DIV class="code"> | |
12380 | <PRE> | |
12381 | %typemap(in) Foo * { | |
12382 | if ((SWIG_ConvertPtr($input, (void **) &$1, $1_descriptor)) == -1) return NULL; | |
12383 | } | |
12384 | </PRE> | |
12385 | </DIV> | |
12386 | <P> The most critical part is the typemap is the use of the <TT> | |
12387 | $1_descriptor</TT> special variable. When placed in a typemap, this is | |
12388 | expanded into the <TT>SWIGTYPE_*</TT> type descriptor object above. As | |
12389 | a general rule, you should always use <TT>$1_descriptor</TT> instead of | |
12390 | trying to hard-code the type descriptor name directly.</P> | |
12391 | <P> There is another reason why you should always use the <TT> | |
12392 | $1_descriptor</TT> variable. When this special variable is expanded, | |
12393 | SWIG marks the corresponding type as "in use." When type-tables and | |
12394 | type information is emitted in the wrapper file, descriptor information | |
12395 | is only generated for those datatypes that were actually used in the | |
12396 | interface. This greatly reduces the size of the type tables and | |
12397 | improves efficiency.</P> | |
12398 | <P> Occassionally, you might need to write a typemap that needs to | |
12399 | convert pointers of other types. To handle this, a special macro | |
12400 | substition <TT>$descriptor(type)</TT> can be used to generate the SWIG | |
12401 | type descriptor name for any C datatype. For example:</P> | |
12402 | <DIV class="code"> | |
12403 | <PRE> | |
12404 | %typemap(in) Foo * { | |
12405 | if ((SWIG_ConvertPtr($input, (void **) &$1, $1_descriptor)) == -1) { | |
12406 | Bar *temp; | |
12407 | if ((SWIG_ConvertPtr($input, (void **) &temp, <B>$descriptor(Bar *)</B>) == -1) { | |
12408 | return NULL; | |
12409 | } | |
12410 | $1 = (Foo *) temp; | |
12411 | } | |
12412 | } | |
12413 | </PRE> | |
12414 | </DIV> | |
12415 | <P> The primary use of <TT>$descriptor(type)</TT> is when writing | |
12416 | typemaps for container objects and other complex data structures. There | |
12417 | are some restrictions on the argument---namely it must be a fully | |
12418 | defined C datatype. It can not be any of the special typemap variables.</P> | |
12419 | <P> In certain cases, SWIG may not generate type-descriptors like you | |
12420 | expect. For example, if you are converting pointers in some | |
12421 | non-standard way or working with an unusual combination of interface | |
12422 | files and modules, you may find that SWIG omits information for a | |
12423 | specific type descriptor. To fix this, you may need to use the <TT> | |
12424 | %types</TT> directive. For example:</P> | |
12425 | <DIV class="code"> | |
12426 | <PRE> | |
12427 | %types(int *, short *, long *, float *, double *); | |
12428 | </PRE> | |
12429 | </DIV> | |
12430 | <P> When <TT>%types</TT> is used, SWIG generates type-descriptor | |
12431 | information even if those datatypes never appear elsewhere in the | |
12432 | interface file.</P> | |
12433 | <P> A final problem related to the type-checker is the conversion of | |
12434 | types in code that is external to the SWIG wrapper file. This situation | |
12435 | is somewhat rare in practice, but occasionally a programmer may want to | |
12436 | convert a typed pointer object into a C++ pointer somewhere else in | |
12437 | their program. The only problem is that the SWIG type descriptor | |
12438 | objects are only defined in the wrapper code and not normally | |
12439 | accessible.</P> | |
12440 | <P> To correctly deal with this situation, the following technique can | |
12441 | be used:</P> | |
12442 | <DIV class="code"> | |
12443 | <PRE> | |
12444 | ||
12445 | /* Some non-SWIG file */ | |
12446 | ||
12447 | /* External declarations */ | |
12448 | extern void *SWIG_TypeQuery(const char *); | |
12449 | extern int SWIG_ConvertPtr(PyObject *, void **ptr, void *descr); | |
12450 | ||
12451 | void foo(PyObject *o) { | |
12452 | Foo *f; | |
12453 | static void *descr = 0; | |
12454 | if (!descr) { | |
12455 | descr = SWIG_TypeQuery("Foo *"); /* Get the type descriptor structure for Foo */ | |
12456 | assert(descr); | |
12457 | } | |
12458 | if ((SWIG_ConvertPtr(o,(void **) &f, descr) == -1)) { | |
12459 | abort(); | |
12460 | } | |
12461 | ... | |
12462 | } | |
12463 | </PRE> | |
12464 | </DIV> | |
12465 | <P> Further details about the run-time type checking can be found in the | |
12466 | documentation for individual language modules. Reading the source code | |
12467 | may also help. The file <TT>swigrun.swg</TT> in the SWIG library | |
12468 | contains all of the source code for type-checking. This code is also | |
12469 | included in every generated wrapped file so you probably just look at | |
12470 | the output of SWIG to get a better sense for how types are managed.</P> | |
12471 | <H2><A name="Typemaps_overloading"></A>10.9 Typemaps and overloading</H2> | |
12472 | <P> In many target languages, SWIG fully supports C++ overloaded methods | |
12473 | and functions. For example, if you have a collection of functions like | |
12474 | this:</P> | |
12475 | <DIV class="code"> | |
12476 | <PRE> | |
12477 | int foo(int x); | |
12478 | int foo(double x); | |
12479 | int foo(char *s, int y); | |
12480 | </PRE> | |
12481 | </DIV> | |
12482 | <P> You can access the functions in a normal way from the scripting | |
12483 | interpreter:</P> | |
12484 | <DIV class="targetlang"> | |
12485 | <PRE> | |
12486 | # Python | |
12487 | foo(3) # foo(int) | |
12488 | foo(3.5) # foo(double) | |
12489 | foo("hello",5) # foo(char *, int) | |
12490 | ||
12491 | # Tcl | |
12492 | foo 3 # foo(int) | |
12493 | foo 3.5 # foo(double) | |
12494 | foo hello 5 # foo(char *, int) | |
12495 | </PRE> | |
12496 | </DIV> | |
12497 | <P> To implement overloading, SWIG generates a separate wrapper function | |
12498 | for each overloaded method. For example, the above functions would | |
12499 | produce something roughly like this:</P> | |
12500 | <DIV class="code"> | |
12501 | <PRE> | |
12502 | // wrapper pseudocode | |
12503 | _wrap_foo_0(argc, args[]) { // foo(int) | |
12504 | int arg1; | |
12505 | int result; | |
12506 | ... | |
12507 | arg1 = FromInteger(args[0]); | |
12508 | result = foo(arg1); | |
12509 | return ToInteger(result); | |
12510 | } | |
12511 | ||
12512 | _wrap_foo_1(argc, args[]) { // foo(double) | |
12513 | double arg1; | |
12514 | int result; | |
12515 | ... | |
12516 | arg1 = FromDouble(args[0]); | |
12517 | result = foo(arg1); | |
12518 | return ToInteger(result); | |
12519 | } | |
12520 | ||
12521 | _wrap_foo_2(argc, args[]) { // foo(char *, int) | |
12522 | char *arg1; | |
12523 | int arg2; | |
12524 | int result; | |
12525 | ... | |
12526 | arg1 = FromString(args[0]); | |
12527 | arg2 = FromInteger(args[1]); | |
12528 | result = foo(arg1,arg2); | |
12529 | return ToInteger(result); | |
12530 | } | |
12531 | ||
12532 | </PRE> | |
12533 | </DIV> | |
12534 | <P> Next, a dynamic dispatch function is generated:</P> | |
12535 | <DIV class="code"> | |
12536 | <PRE> | |
12537 | _wrap_foo(argc, args[]) { | |
12538 | if (argc == 1) { | |
12539 | if (IsInteger(args[0])) { | |
12540 | return _wrap_foo_0(argc,args); | |
12541 | } | |
12542 | if (IsDouble(args[0])) { | |
12543 | return _wrap_foo_1(argc,args); | |
12544 | } | |
12545 | } | |
12546 | if (argc == 2) { | |
12547 | if (IsString(args[0]) && IsInteger(args[1])) { | |
12548 | return _wrap_foo_2(argc,args); | |
12549 | } | |
12550 | } | |
12551 | error("No matching function!\n"); | |
12552 | } | |
12553 | </PRE> | |
12554 | </DIV> | |
12555 | <P> The purpose of the dynamic dispatch function is to select the | |
12556 | appropriate C++ function based on argument types---a task that must be | |
12557 | performed at runtime in most of SWIG's target languages.</P> | |
12558 | <P> The generation of the dynamic dispatch function is a relatively | |
12559 | tricky affair. Not only must input typemaps be taken into account | |
12560 | (these typemaps can radically change the types of arguments accepted), | |
12561 | but overloaded methods must also be sorted and checked in a very | |
12562 | specific order to resolve potential ambiguity. A high-level overview of | |
12563 | this ranking process is found in the "<A href="#SWIGPlus">SWIG and C++</A> | |
12564 | " chapter. What isn't mentioned in that chapter is the mechanism by | |
12565 | which it is implemented---as a collection of typemaps.</P> | |
12566 | <P> To support dynamic dispatch, SWIG first defines a general purpose | |
12567 | type hierarchy as follows:</P> | |
12568 | <DIV class="diagram"> | |
12569 | <PRE> | |
12570 | Symbolic Name Precedence Value | |
12571 | ------------------------------ ------------------ | |
12572 | SWIG_TYPECHECK_POINTER 0 | |
12573 | SWIG_TYPECHECK_VOIDPTR 10 | |
12574 | SWIG_TYPECHECK_BOOL 15 | |
12575 | SWIG_TYPECHECK_UINT8 20 | |
12576 | SWIG_TYPECHECK_INT8 25 | |
12577 | SWIG_TYPECHECK_UINT16 30 | |
12578 | SWIG_TYPECHECK_INT16 35 | |
12579 | SWIG_TYPECHECK_UINT32 40 | |
12580 | SWIG_TYPECHECK_INT32 45 | |
12581 | SWIG_TYPECHECK_UINT64 50 | |
12582 | SWIG_TYPECHECK_INT64 55 | |
12583 | SWIG_TYPECHECK_UINT128 60 | |
12584 | SWIG_TYPECHECK_INT128 65 | |
12585 | SWIG_TYPECHECK_INTEGER 70 | |
12586 | SWIG_TYPECHECK_FLOAT 80 | |
12587 | SWIG_TYPECHECK_DOUBLE 90 | |
12588 | SWIG_TYPECHECK_COMPLEX 100 | |
12589 | SWIG_TYPECHECK_UNICHAR 110 | |
12590 | SWIG_TYPECHECK_UNISTRING 120 | |
12591 | SWIG_TYPECHECK_CHAR 130 | |
12592 | SWIG_TYPECHECK_STRING 140 | |
12593 | SWIG_TYPECHECK_BOOL_ARRAY 1015 | |
12594 | SWIG_TYPECHECK_INT8_ARRAY 1025 | |
12595 | SWIG_TYPECHECK_INT16_ARRAY 1035 | |
12596 | SWIG_TYPECHECK_INT32_ARRAY 1045 | |
12597 | SWIG_TYPECHECK_INT64_ARRAY 1055 | |
12598 | SWIG_TYPECHECK_INT128_ARRAY 1065 | |
12599 | SWIG_TYPECHECK_FLOAT_ARRAY 1080 | |
12600 | SWIG_TYPECHECK_DOUBLE_ARRAY 1090 | |
12601 | SWIG_TYPECHECK_CHAR_ARRAY 1130 | |
12602 | SWIG_TYPECHECK_STRING_ARRAY 1140 | |
12603 | </PRE> | |
12604 | </DIV> | |
12605 | <P> (These precedence levels are defined in <TT>swig.swg</TT>, a library | |
12606 | file that's included by all target language modules.)</P> | |
12607 | <P> In this table, the precedence-level determines the order in which | |
12608 | types are going to be checked. Low values are always checked before | |
12609 | higher values. For example, integers are checked before floats, single | |
12610 | values are checked before arrays, and so forth.</P> | |
12611 | <P> Using the above table as a guide, each target language defines a | |
12612 | collection of "typecheck" typemaps. The follow excerpt from the Python | |
12613 | module illustrates this:</P> | |
12614 | <DIV class="code"> | |
12615 | <PRE> | |
12616 | /* Python type checking rules */ | |
12617 | /* Note: %typecheck(X) is a macro for %typemap(typecheck,precedence=X) */ | |
12618 | ||
12619 | %typecheck(SWIG_TYPECHECK_INTEGER) | |
12620 | int, short, long, | |
12621 | unsigned int, unsigned short, unsigned long, | |
12622 | signed char, unsigned char, | |
12623 | long long, unsigned long long, | |
12624 | const int &, const short &, const long &, | |
12625 | const unsigned int &, const unsigned short &, const unsigned long &, | |
12626 | const long long &, const unsigned long long &, | |
12627 | enum SWIGTYPE, | |
12628 | bool, const bool & | |
12629 | { | |
12630 | $1 = (PyInt_Check($input) || PyLong_Check($input)) ? 1 : 0; | |
12631 | } | |
12632 | ||
12633 | %typecheck(SWIG_TYPECHECK_DOUBLE) | |
12634 | float, double, | |
12635 | const float &, const double & | |
12636 | { | |
12637 | $1 = (PyFloat_Check($input) || PyInt_Check($input) || PyLong_Check($input)) ? 1 : 0; | |
12638 | } | |
12639 | ||
12640 | %typecheck(SWIG_TYPECHECK_CHAR) char { | |
12641 | $1 = (PyString_Check($input) && (PyString_Size($input) == 1)) ? 1 : 0; | |
12642 | } | |
12643 | ||
12644 | %typecheck(SWIG_TYPECHECK_STRING) char * { | |
12645 | $1 = PyString_Check($input) ? 1 : 0; | |
12646 | } | |
12647 | ||
12648 | %typecheck(SWIG_TYPECHECK_POINTER) SWIGTYPE *, SWIGTYPE &, SWIGTYPE [] { | |
12649 | void *ptr; | |
12650 | if (SWIG_ConvertPtr($input, (void **) &ptr, $1_descriptor, 0) == -1) { | |
12651 | $1 = 0; | |
12652 | PyErr_Clear(); | |
12653 | } else { | |
12654 | $1 = 1; | |
12655 | } | |
12656 | } | |
12657 | ||
12658 | %typecheck(SWIG_TYPECHECK_POINTER) SWIGTYPE { | |
12659 | void *ptr; | |
12660 | if (SWIG_ConvertPtr($input, (void **) &ptr, $&1_descriptor, 0) == -1) { | |
12661 | $1 = 0; | |
12662 | PyErr_Clear(); | |
12663 | } else { | |
12664 | $1 = 1; | |
12665 | } | |
12666 | } | |
12667 | ||
12668 | %typecheck(SWIG_TYPECHECK_VOIDPTR) void * { | |
12669 | void *ptr; | |
12670 | if (SWIG_ConvertPtr($input, (void **) &ptr, 0, 0) == -1) { | |
12671 | $1 = 0; | |
12672 | PyErr_Clear(); | |
12673 | } else { | |
12674 | $1 = 1; | |
12675 | } | |
12676 | } | |
12677 | ||
12678 | %typecheck(SWIG_TYPECHECK_POINTER) PyObject * | |
12679 | { | |
12680 | $1 = ($input != 0); | |
12681 | } | |
12682 | </PRE> | |
12683 | </DIV> | |
12684 | <P> It might take a bit of contemplation, but this code has merely | |
12685 | organized all of the basic C++ types, provided some simple | |
12686 | type-checking code, and assigned each type a precedence value.</P> | |
12687 | <P> Finally, to generate the dynamic dispatch function, SWIG uses the | |
12688 | following algorithm:</P> | |
12689 | <UL> | |
12690 | <LI>Overloaded methods are first sorted by the number of required | |
12691 | arguments.</LI> | |
12692 | <LI>Methods with the same number of arguments are then sorted by | |
12693 | precedence values of argument types.</LI> | |
12694 | <LI>Typecheck typemaps are then emitted to produce a dispatch function | |
12695 | that checks arguments in the correct order.</LI> | |
12696 | </UL> | |
12697 | <P> If you haven't written any typemaps of your own, it is unnecessary | |
12698 | to worry about the typechecking rules. However, if you have written new | |
12699 | input typemaps, you might have to supply a typechecking rule as well. | |
12700 | An easy way to do this is to simply copy one of the existing | |
12701 | typechecking rules. Here is an example,</P> | |
12702 | <DIV class="code"> | |
12703 | <PRE> | |
12704 | // Typemap for a C++ string | |
12705 | %typemap(in) std::string { | |
12706 | if (PyString_Check($input)) { | |
12707 | $1 = std::string(PyString_AsString($input)); | |
12708 | } else { | |
12709 | SWIG_exception(SWIG_TypeError, "string expected"); | |
12710 | } | |
12711 | } | |
12712 | // Copy the typecheck code for "char *". | |
12713 | %typemap(typecheck) std::string = char *; | |
12714 | </PRE> | |
12715 | </DIV> | |
12716 | <P> The bottom line: If you are writing new typemaps and you are using | |
12717 | overloaded methods, you will probably have to write typecheck code or | |
12718 | copy existing code. Since this is a relatively new SWIG feature, there | |
12719 | are few examples to work with. However, you might look at some of the | |
12720 | existing library files likes 'typemaps.i' for a guide.</P> | |
12721 | <P><B> Notes:</B></P> | |
12722 | <UL> | |
12723 | <LI>Typecheck typemaps are not used for non-overloaded methods. Because | |
12724 | of this, it is still always necessary to check types in any "in" | |
12725 | typemaps.</LI> | |
12726 | <LI>The dynamic dispatch process is only meant to be a heuristic. There | |
12727 | are many corner cases where SWIG simply can't disambiguate types to the | |
12728 | same degree as C++. The only way to resolve this ambiguity is to use | |
12729 | the %rename directive to rename one of the overloaded methods | |
12730 | (effectively eliminating overloading).</LI> | |
12731 | <LI> Typechecking may be partial. For example, if working with arrays, | |
12732 | the typecheck code might simply check the type of the first array | |
12733 | element and use that to dispatch to the correct function. Subsequent | |
12734 | "in" typemaps would then perform more extensive type-checking.</LI> | |
12735 | <LI>Make sure you read the section on overloading in the "<A href="#SWIGPlus"> | |
12736 | SWIG and C++</A>" chapter.</LI> | |
12737 | </UL> | |
12738 | <H2><A name="Typemaps_nn48"></A>10.10 More about <TT>%apply</TT> and <TT> | |
12739 | %clear</TT></H2> | |
12740 | <P> In order to implement certain kinds of program behavior, it is | |
12741 | sometimes necessary to write sets of typemaps. For example, to support | |
12742 | output arguments, one often writes a set of typemaps like this:</P> | |
12743 | <DIV class="code"> | |
12744 | <PRE> | |
12745 | %typemap(in,numinputs=0) int *OUTPUT (int temp) { | |
12746 | $1 = &temp; | |
12747 | } | |
12748 | %typemap(argout) int *OUTPUT { | |
12749 | // return value somehow | |
12750 | } | |
12751 | </PRE> | |
12752 | </DIV> | |
12753 | <P> To make it easier to apply the typemap to different argument types | |
12754 | and names, the <TT>%apply</TT> directive performs a copy of all | |
12755 | typemaps from one type to another. For example, if you specify this,</P> | |
12756 | <DIV class="code"> | |
12757 | <PRE> | |
12758 | %apply int *OUTPUT { int *retvalue, int32 *output }; | |
12759 | </PRE> | |
12760 | </DIV> | |
12761 | <P> then all of the <TT>int *OUTPUT</TT> typemaps are copied to <TT>int | |
12762 | *retvalue</TT> and <TT>int32 *output</TT>.</P> | |
12763 | <P> However, there is a subtle aspect of <TT>%apply</TT> that needs more | |
12764 | description. Namely, <TT>%apply</TT> does not overwrite a typemap rule | |
12765 | if it is already defined for the target datatype. This behavior allows | |
12766 | you to do two things:</P> | |
12767 | <UL> | |
12768 | <LI>You can specialize parts of a complex typemap rule by first defining | |
12769 | a few typemaps and then using <TT>%apply</TT> to incorporate the | |
12770 | remaining pieces.</LI> | |
12771 | <LI>Sets of different typemaps can be applied to the same datatype using | |
12772 | repeated <TT>%apply</TT> directives.</LI> | |
12773 | </UL> | |
12774 | <P> For example:</P> | |
12775 | <DIV class="code"> | |
12776 | <PRE> | |
12777 | %typemap(in) int *INPUT (int temp) { | |
12778 | temp = ... get value from $input ...; | |
12779 | $1 = &temp; | |
12780 | } | |
12781 | ||
12782 | %typemap(check) int *POSITIVE { | |
12783 | if (*$1 <= 0) { | |
12784 | SWIG_exception(SWIG_ValueError,"Expected a positive number!\n"); | |
12785 | return NULL; | |
12786 | } | |
12787 | } | |
12788 | ||
12789 | ... | |
12790 | %apply int *INPUT { int *invalue }; | |
12791 | %apply int *POSITIVE { int *invalue }; | |
12792 | </PRE> | |
12793 | </DIV> | |
12794 | <P> Since <TT>%apply</TT> does not overwrite or replace any existing | |
12795 | rules, the only way to reset behavior is to use the <TT>%clear</TT> | |
12796 | directive. <TT>%clear</TT> removes all typemap rules defined for a | |
12797 | specific datatype. For example:</P> | |
12798 | <DIV class="code"> | |
12799 | <PRE> | |
12800 | %clear int *invalue; | |
12801 | </PRE> | |
12802 | </DIV> | |
12803 | <H2><A name="Typemaps_nn49"></A>10.11 Reducing wrapper code size</H2> | |
12804 | <P> Since the code supplied to a typemap is inlined directly into | |
12805 | wrapper functions, typemaps can result in a tremendous amount of code | |
12806 | bloat. For example, consider this typemap for an array:</P> | |
12807 | <DIV class="code"> | |
12808 | <PRE> | |
12809 | %typemap(in) float [ANY] { | |
12810 | int i; | |
12811 | if (!PySequence_Check($input)) { | |
12812 | PyErr_SetString(PyExc_ValueError,"Expected a sequence"); | |
12813 | return NULL; | |
12814 | } | |
12815 | if (PySequence_Length($input) != $1_dim0) { | |
12816 | PyErr_SetString(PyExc_ValueError,"Size mismatch. Expected $1_dim0 elements"); | |
12817 | return NULL; | |
12818 | } | |
12819 | $1 = (float) malloc($1_dim0*sizeof(float)); | |
12820 | for (i = 0; i < $1_dim0; i++) { | |
12821 | PyObject *o = PySequence_GetItem($input,i); | |
12822 | if (PyNumber_Check(o)) { | |
12823 | $1[i] = (float) PyFloat_AsDouble(o); | |
12824 | } else { | |
12825 | PyErr_SetString(PyExc_ValueError,"Sequence elements must be numbers"); | |
12826 | free(result); | |
12827 | return NULL; | |
12828 | } | |
12829 | } | |
12830 | } | |
12831 | </PRE> | |
12832 | </DIV> | |
12833 | <P> If you had a large interface with hundreds of functions all | |
12834 | accepting array parameters, this typemap would be replicated | |
12835 | repeatedly--generating a huge amount of code. A better approach might | |
12836 | be to consolidate some of the typemap into a function. For example:</P> | |
12837 | <DIV class="code"> | |
12838 | <PRE> | |
12839 | %{ | |
12840 | /* Define a helper function */ | |
12841 | static float * | |
12842 | convert_float_array(PyObject *input, int size) { | |
12843 | int i; | |
12844 | float *result; | |
12845 | if (!PySequence_Check(input)) { | |
12846 | PyErr_SetString(PyExc_ValueError,"Expected a sequence"); | |
12847 | return NULL; | |
12848 | } | |
12849 | if (PySequence_Length(input) != size) { | |
12850 | PyErr_SetString(PyExc_ValueError,"Size mismatch. "); | |
12851 | return NULL; | |
12852 | } | |
12853 | result = (float) malloc(size*sizeof(float)); | |
12854 | for (i = 0; i < size; i++) { | |
12855 | PyObject *o = PySequence_GetItem(input,i); | |
12856 | if (PyNumber_Check(o)) { | |
12857 | result[i] = (float) PyFloat_AsDouble(o); | |
12858 | } else { | |
12859 | PyErr_SetString(PyExc_ValueError,"Sequence elements must be numbers"); | |
12860 | free(result); | |
12861 | return NULL; | |
12862 | } | |
12863 | } | |
12864 | return result; | |
12865 | } | |
12866 | %} | |
12867 | ||
12868 | %typemap(in) float [ANY] { | |
12869 | $1 = convert_float_array($input, $1_dim0); | |
12870 | if (!$1) return NULL; | |
12871 | } | |
12872 | %} | |
12873 | </PRE> | |
12874 | </DIV> | |
12875 | <H2><A name="Typemaps_nn47"></A>10.12 Passing data between typemaps</H2> | |
12876 | <P> It is also important to note that the primary use of local variables | |
12877 | is to create stack-allocated objects for temporary use inside a wrapper | |
12878 | function (this is faster and less-prone to error than allocating data | |
12879 | on the heap). In general, the variables are not intended to pass | |
12880 | information between different types of typemaps. However, this can be | |
12881 | done if you realize that local names have the argument number appended | |
12882 | to them. For example, you could do this:</P> | |
12883 | <DIV class="code"> | |
12884 | <PRE> | |
12885 | %typemap(in) int *(int temp) { | |
12886 | temp = (int) PyInt_AsLong($input); | |
12887 | $1 = &temp; | |
12888 | } | |
12889 | ||
12890 | %typemap(argout) int * { | |
12891 | PyObject *o = PyInt_FromLong(temp$argnum); | |
12892 | ... | |
12893 | } | |
12894 | </PRE> | |
12895 | </DIV> | |
12896 | <P> In this case, the <TT>$argnum</TT> variable is expanded into the | |
12897 | argument number. Therefore, the code will reference the appropriate | |
12898 | local such as <TT>temp1</TT> and <TT>temp2</TT>. It should be noted | |
12899 | that there are plenty of opportunities to break the universe here and | |
12900 | that accessing locals in this manner should probably be avoided. At the | |
12901 | very least, you should make sure that the typemaps sharing information | |
12902 | have exactly the same types and names.</P> | |
12903 | <H2><A name="Typemaps_nn51"></A>10.13 Where to go for more information?</H2> | |
12904 | <P> The best place to find out more information about writing typemaps | |
12905 | is to look in the SWIG library. Most language modules define all of | |
12906 | their default behavior using typemaps. These are found in files such as | |
12907 | <TT>python.swg</TT>, <TT>perl5.swg</TT>, <TT>tcl8.swg</TT> and so | |
12908 | forth. The <TT>typemaps.i</TT> file in the library also contains | |
12909 | numerous examples. You should look at these files to get a feel for how | |
12910 | to define typemaps of your own. Some of the language modules support | |
12911 | additional typemaps and further information is available in the | |
12912 | individual chapters for each target language.</P> | |
12913 | <HR NOSHADE> | |
12914 | <H1><A name="Customization"></A>11 Customization Features</H1> | |
12915 | ||
12916 | <!-- INDEX --> | |
12917 | <DIV class="sectiontoc"> | |
12918 | <UL> | |
12919 | <LI><A href="#exception">Exception handling with %exception</A> | |
12920 | <UL> | |
12921 | <LI><A href="#Customization_nn3">Handling exceptions in C code</A></LI> | |
12922 | <LI><A href="#Customization_nn4">Exception handling with longjmp()</A></LI> | |
12923 | <LI><A href="#Customization_nn5">Handling C++ exceptions</A></LI> | |
12924 | <LI><A href="#Customization_nn6">Defining different exception handlers</A> | |
12925 | </LI> | |
12926 | <LI><A href="#Customization_nn7">Using The SWIG exception library</A></LI> | |
12927 | </UL> | |
12928 | </LI> | |
12929 | <LI><A href="#ownership">Object ownership and %newobject</A></LI> | |
12930 | <LI><A href="#features">Features and the %feature directive</A> | |
12931 | <UL> | |
12932 | <LI><A href="#Customization_feature_flags">Feature flags</A></LI> | |
12933 | <LI><A href="#Customization_clearing_features">Clearing features</A></LI> | |
12934 | <LI><A href="#Customization_features_default_args">Features and default | |
12935 | arguments</A></LI> | |
12936 | <LI><A href="#features_example">Feature example</A></LI> | |
12937 | </UL> | |
12938 | </LI> | |
12939 | </UL> | |
12940 | </DIV> | |
12941 | <!-- INDEX --> | |
12942 | <P> In many cases, it is desirable to change the default wrapping of | |
12943 | particular declarations in an interface. For example, you might want to | |
12944 | provide hooks for catching C++ exceptions, add assertions, or provide | |
12945 | hints to the underlying code generator. This chapter describes some of | |
12946 | these customization techniques. First, a discussion of exception | |
12947 | handling is presented. Then, a more general-purpose customization | |
12948 | mechanism known as "features" is described.</P> | |
12949 | <H2><A name="exception"></A>11.1 Exception handling with %exception</H2> | |
12950 | <P> The <TT>%exception</TT> directive allows you to define a general | |
12951 | purpose exception handler. For example, you can specify the following:</P> | |
12952 | <DIV class="code"> | |
12953 | <PRE> | |
12954 | %exception { | |
12955 | try { | |
12956 | $action | |
12957 | } | |
12958 | catch (RangeError) { | |
12959 | PyErr_SetString(PyExc_IndexError,"index out-of-bounds"); | |
12960 | return NULL; | |
12961 | } | |
12962 | } | |
12963 | </PRE> | |
12964 | </DIV> | |
12965 | <P> When defined, the code enclosed in braces is inserted directly into | |
12966 | the low-level wrapper functions. The special symbol <TT>$action</TT> | |
12967 | gets replaced with the actual operation to be performed (a function | |
12968 | call, method invocation, attribute access, etc.). An exception handler | |
12969 | remains in effect until it is explicitly deleted. This is done by using | |
12970 | either <TT>%exception</TT> or <TT>%noexception</TT> with no code. For | |
12971 | example:</P> | |
12972 | <DIV class="code"> | |
12973 | <PRE> | |
12974 | %exception; // Deletes any previously defined handler | |
12975 | </PRE> | |
12976 | </DIV> | |
12977 | <P><B> Compatibility note:</B> Previous versions of SWIG used a special | |
12978 | directive <TT>%except</TT> for exception handling. That directive is | |
12979 | deprecated--<TT>%exception</TT> provides the same functionality, but is | |
12980 | substantially more flexible.</P> | |
12981 | <H3><A name="Customization_nn3"></A>11.1.1 Handling exceptions in C code</H3> | |
12982 | <P> C has no formal exception handling mechanism so there are several | |
12983 | approaches that might be used. A somewhat common technique is to simply | |
12984 | set a special error code. For example:</P> | |
12985 | <DIV class="code"> | |
12986 | <PRE> | |
12987 | /* File : except.c */ | |
12988 | ||
12989 | static char error_message[256]; | |
12990 | static int error_status = 0; | |
12991 | ||
12992 | void throw_exception(char *msg) { | |
12993 | strncpy(error_message,msg,256); | |
12994 | error_status = 1; | |
12995 | } | |
12996 | ||
12997 | void clear_exception() { | |
12998 | error_status = 0; | |
12999 | } | |
13000 | char *check_exception() { | |
13001 | if (error_status) return error_message; | |
13002 | else return NULL; | |
13003 | } | |
13004 | ||
13005 | </PRE> | |
13006 | </DIV> | |
13007 | <P> To use these functions, functions simply call <TT>throw_exception()</TT> | |
13008 | to indicate an error occurred. For example :</P> | |
13009 | <DIV class="code"> | |
13010 | <PRE> | |
13011 | double inv(double x) { | |
13012 | if (x != 0) return 1.0/x; | |
13013 | else { | |
13014 | throw_exception("Division by zero"); | |
13015 | return 0; | |
13016 | } | |
13017 | } | |
13018 | ||
13019 | </PRE> | |
13020 | </DIV> | |
13021 | <P> To catch the exception, you can write a simple exception handler | |
13022 | such as the following (shown for Perl5) :</P> | |
13023 | <DIV class="code"> | |
13024 | <PRE> | |
13025 | %exception { | |
13026 | char *err; | |
13027 | clear_exception(); | |
13028 | $action | |
13029 | if ((err = check_exception())) { | |
13030 | croak(err); | |
13031 | } | |
13032 | } | |
13033 | </PRE> | |
13034 | </DIV> | |
13035 | <P> In this case, when an error occurs, it is translated into a Perl | |
13036 | error. Each target language has its own approach to creating a runtime | |
13037 | error/exception in and for Perl it is the <TT>croak</TT> method shown | |
13038 | above.</P> | |
13039 | <H3><A name="Customization_nn4"></A>11.1.2 Exception handling with | |
13040 | longjmp()</H3> | |
13041 | <P> Exception handling can also be added to C code using the <TT> | |
13042 | <setjmp.h></TT> library. Here is a minimalistic implementation that | |
13043 | relies on the C preprocessor :</P> | |
13044 | <DIV class="code"> | |
13045 | <PRE> | |
13046 | /* File : except.c | |
13047 | Just the declaration of a few global variables we're going to use */ | |
13048 | ||
13049 | #include <setjmp.h> | |
13050 | jmp_buf exception_buffer; | |
13051 | int exception_status; | |
13052 | ||
13053 | /* File : except.h */ | |
13054 | #include <setjmp.h> | |
13055 | extern jmp_buf exception_buffer; | |
13056 | extern int exception_status; | |
13057 | ||
13058 | #define try if ((exception_status = setjmp(exception_buffer)) == 0) | |
13059 | #define catch(val) else if (exception_status == val) | |
13060 | #define throw(val) longjmp(exception_buffer,val) | |
13061 | #define finally else | |
13062 | ||
13063 | /* Exception codes */ | |
13064 | ||
13065 | #define RangeError 1 | |
13066 | #define DivisionByZero 2 | |
13067 | #define OutOfMemory 3 | |
13068 | ||
13069 | </PRE> | |
13070 | </DIV> | |
13071 | <P> Now, within a C program, you can do the following :</P> | |
13072 | <DIV class="code"> | |
13073 | <PRE> | |
13074 | double inv(double x) { | |
13075 | if (x) return 1.0/x; | |
13076 | else throw(DivisionByZero); | |
13077 | } | |
13078 | ||
13079 | </PRE> | |
13080 | </DIV> | |
13081 | <P> Finally, to create a SWIG exception handler, write the following :</P> | |
13082 | <DIV class="code"> | |
13083 | <PRE> | |
13084 | %{ | |
13085 | #include "except.h" | |
13086 | %} | |
13087 | ||
13088 | %exception { | |
13089 | try { | |
13090 | $action | |
13091 | } catch(RangeError) { | |
13092 | croak("Range Error"); | |
13093 | } catch(DivisionByZero) { | |
13094 | croak("Division by zero"); | |
13095 | } catch(OutOfMemory) { | |
13096 | croak("Out of memory"); | |
13097 | } finally { | |
13098 | croak("Unknown exception"); | |
13099 | } | |
13100 | } | |
13101 | </PRE> | |
13102 | </DIV> | |
13103 | <P> Note: This implementation is only intended to illustrate the general | |
13104 | idea. To make it work better, you'll need to modify it to handle nested | |
13105 | <TT>try</TT> declarations.</P> | |
13106 | <H3><A name="Customization_nn5"></A>11.1.3 Handling C++ exceptions</H3> | |
13107 | <P> Handling C++ exceptions is also straightforward. For example:</P> | |
13108 | <DIV class="code"> | |
13109 | <PRE> | |
13110 | %exception { | |
13111 | try { | |
13112 | $action | |
13113 | } catch(RangeError) { | |
13114 | croak("Range Error"); | |
13115 | } catch(DivisionByZero) { | |
13116 | croak("Division by zero"); | |
13117 | } catch(OutOfMemory) { | |
13118 | croak("Out of memory"); | |
13119 | } catch(...) { | |
13120 | croak("Unknown exception"); | |
13121 | } | |
13122 | } | |
13123 | ||
13124 | </PRE> | |
13125 | </DIV> | |
13126 | <P> The exception types need to be declared as classes elsewhere, | |
13127 | possibly in a header file :</P> | |
13128 | <DIV class="code"> | |
13129 | <PRE> | |
13130 | class RangeError {}; | |
13131 | class DivisionByZero {}; | |
13132 | class OutOfMemory {}; | |
13133 | </PRE> | |
13134 | </DIV> | |
13135 | <H3><A name="Customization_nn6"></A>11.1.4 Defining different exception | |
13136 | handlers</H3> | |
13137 | <P> By default, the <TT>%exception</TT> directive creates an exception | |
13138 | handler that is used for all wrapper functions that follow it. Unless | |
13139 | there is a well-defined (and simple) error handling mechanism in place, | |
13140 | defining one universal exception handler may be unwieldy and result in | |
13141 | excessive code bloat since the handler is inlined into each wrapper | |
13142 | function.</P> | |
13143 | <P> To fix this, you can be more selective about how you use the <TT> | |
13144 | %exception</TT> directive. One approach is to only place it around | |
13145 | critical pieces of code. For example:</P> | |
13146 | <DIV class="code"> | |
13147 | <PRE> | |
13148 | %exception { | |
13149 | ... your exception handler ... | |
13150 | } | |
13151 | /* Define critical operations that can throw exceptions here */ | |
13152 | ||
13153 | %exception; | |
13154 | ||
13155 | /* Define non-critical operations that don't throw exceptions */ | |
13156 | </PRE> | |
13157 | </DIV> | |
13158 | <P> More precise control over exception handling can be obtained by | |
13159 | attaching an exception handler to specific declaration name. For | |
13160 | example:</P> | |
13161 | <DIV class="code"> | |
13162 | <PRE> | |
13163 | %exception allocate { | |
13164 | try { | |
13165 | $action | |
13166 | } | |
13167 | catch (MemoryError) { | |
13168 | croak("Out of memory"); | |
13169 | } | |
13170 | } | |
13171 | </PRE> | |
13172 | </DIV> | |
13173 | <P> In this case, the exception handler is only attached to declarations | |
13174 | named "allocate". This would include both global and member functions. | |
13175 | The names supplied to <TT>%exception</TT> follow the same rules as for <TT> | |
13176 | %rename</TT> described in the section on <A href="#ambiguity_resolution_renaming"> | |
13177 | Ambiguity resolution and renaming</A>. For example, if you wanted to | |
13178 | define an exception handler for a specific class, you might write this:</P> | |
13179 | <DIV class="code"> | |
13180 | <PRE> | |
13181 | %exception Object::allocate { | |
13182 | try { | |
13183 | $action | |
13184 | } | |
13185 | catch (MemoryError) { | |
13186 | croak("Out of memory"); | |
13187 | } | |
13188 | } | |
13189 | </PRE> | |
13190 | </DIV> | |
13191 | <P> When a class prefix is supplied, the exception handler is applied to | |
13192 | the corresponding declaration in the specified class as well as for | |
13193 | identically named functions appearing in derived classes.</P> | |
13194 | <P> <TT>%exception</TT> can even be used to pinpoint a precise | |
13195 | declaration when overloading is used. For example:</P> | |
13196 | <DIV class="code"> | |
13197 | <PRE> | |
13198 | %exception Object::allocate(int) { | |
13199 | try { | |
13200 | $action | |
13201 | } | |
13202 | catch (MemoryError) { | |
13203 | croak("Out of memory"); | |
13204 | } | |
13205 | } | |
13206 | </PRE> | |
13207 | </DIV> | |
13208 | <P> Attaching exceptions to specific declarations is a good way to | |
13209 | reduce code bloat. It can also be a useful way to attach exceptions to | |
13210 | specific parts of a header file. For example:</P> | |
13211 | <DIV class="code"> | |
13212 | <PRE> | |
13213 | %module example | |
13214 | %{ | |
13215 | #include "someheader.h" | |
13216 | %} | |
13217 | ||
13218 | // Define a few exception handlers for specific declarations | |
13219 | %exception Object::allocate(int) { | |
13220 | try { | |
13221 | $action | |
13222 | } | |
13223 | catch (MemoryError) { | |
13224 | croak("Out of memory"); | |
13225 | } | |
13226 | } | |
13227 | ||
13228 | %exception Object::getitem { | |
13229 | try { | |
13230 | $action | |
13231 | } | |
13232 | catch (RangeError) { | |
13233 | croak("Index out of range"); | |
13234 | } | |
13235 | } | |
13236 | ... | |
13237 | // Read a raw header file | |
13238 | %include "someheader.h" | |
13239 | </PRE> | |
13240 | </DIV> | |
13241 | <P><B> Compatibility note:</B> The <TT>%exception</TT> directive | |
13242 | replaces the functionality provided by the deprecated "except" typemap. | |
13243 | The typemap would allow exceptions to be thrown in the target language | |
13244 | based on the return type of a function and was intended to be a | |
13245 | mechanism for pinpointing specific declarations. However, it never | |
13246 | really worked that well and the new %exception directive is much | |
13247 | better.</P> | |
13248 | <H3><A name="Customization_nn7"></A>11.1.5 Using The SWIG exception | |
13249 | library</H3> | |
13250 | <P> The <TT>exception.i</TT> library file provides support for creating | |
13251 | language independent exceptions in your interfaces. To use it, simply | |
13252 | put an "<TT>%include exception.i</TT>" in your interface file. This | |
13253 | creates a function <TT>SWIG_exception()</TT> that can be used to raise | |
13254 | common scripting language exceptions in a portable manner. For example | |
13255 | :</P> | |
13256 | <DIV class="code"> | |
13257 | <PRE> | |
13258 | // Language independent exception handler | |
13259 | %include exception.i | |
13260 | ||
13261 | %exception { | |
13262 | try { | |
13263 | $action | |
13264 | } catch(RangeError) { | |
13265 | SWIG_exception(SWIG_ValueError, "Range Error"); | |
13266 | } catch(DivisionByZero) { | |
13267 | SWIG_exception(SWIG_DivisionByZero, "Division by zero"); | |
13268 | } catch(OutOfMemory) { | |
13269 | SWIG_exception(SWIG_MemoryError, "Out of memory"); | |
13270 | } catch(...) { | |
13271 | SWIG_exception(SWIG_RuntimeError,"Unknown exception"); | |
13272 | } | |
13273 | } | |
13274 | ||
13275 | </PRE> | |
13276 | </DIV> | |
13277 | <P> As arguments, <TT>SWIG_exception()</TT> takes an error type code (an | |
13278 | integer) and an error message string. The currently supported error | |
13279 | types are :</P> | |
13280 | <DIV class="diagram"> | |
13281 | <PRE> | |
13282 | SWIG_MemoryError | |
13283 | SWIG_IOError | |
13284 | SWIG_RuntimeError | |
13285 | SWIG_IndexError | |
13286 | SWIG_TypeError | |
13287 | SWIG_DivisionByZero | |
13288 | SWIG_OverflowError | |
13289 | SWIG_SyntaxError | |
13290 | SWIG_ValueError | |
13291 | SWIG_SystemError | |
13292 | SWIG_UnknownError | |
13293 | </PRE> | |
13294 | </DIV> | |
13295 | <P> Since the <TT>SWIG_exception()</TT> function is defined at the | |
13296 | C-level it can be used elsewhere in SWIG. This includes typemaps and | |
13297 | helper functions.</P> | |
13298 | <H2><A name="ownership"></A>11.2 Object ownership and %newobject</H2> | |
13299 | <P> A common problem in some applications is managing proper ownership | |
13300 | of objects. For example, consider a function like this:</P> | |
13301 | <DIV class="code"> | |
13302 | <PRE> | |
13303 | Foo *blah() { | |
13304 | Foo *f = new Foo(); | |
13305 | return f; | |
13306 | } | |
13307 | </PRE> | |
13308 | </DIV> | |
13309 | <P> If you wrap the function <TT>blah()</TT>, SWIG has no idea that the | |
13310 | return value is a newly allocated object. As a result, the resulting | |
13311 | extension module may produce a memory leak (SWIG is conservative and | |
13312 | will never delete objects unless it knows for certain that the returned | |
13313 | object was newly created).</P> | |
13314 | <P> To fix this, you can provide an extra hint to the code generator | |
13315 | using the <TT>%newobject</TT> directive. For example:</P> | |
13316 | <DIV class="code"> | |
13317 | <PRE> | |
13318 | %newobject blah; | |
13319 | Foo *blah(); | |
13320 | </PRE> | |
13321 | </DIV> | |
13322 | <P> <TT>%newobject</TT> works exactly like <TT>%rename</TT> and <TT> | |
13323 | %exception</TT>. In other words, you can attach it to class members and | |
13324 | parameterized declarations as before. For example:</P> | |
13325 | <DIV class="code"> | |
13326 | <PRE> | |
13327 | %newobject ::blah(); // Only applies to global blah | |
13328 | %newobject Object::blah(int,double); // Only blah(int,double) in Object | |
13329 | %newobject *::copy; // Copy method in all classes | |
13330 | ... | |
13331 | </PRE> | |
13332 | </DIV> | |
13333 | <P> When <TT>%newobject</TT> is supplied, many language modules will | |
13334 | arrange to take ownership of the return value. This allows the value to | |
13335 | be automatically garbage-collected when it is no longer in use. | |
13336 | However, this depends entirely on the target language (a language | |
13337 | module may also choose to ignore the <TT>%newobject</TT> directive).</P> | |
13338 | <P> Closely related to <TT>%newobject</TT> is a special typemap. The | |
13339 | "newfree" typemap can be used to deallocate a newly allocated return | |
13340 | value. It is only available on methods for which <TT>%newobject</TT> | |
13341 | has been applied and is commonly used to clean-up string results. For | |
13342 | example:</P> | |
13343 | <DIV class="code"> | |
13344 | <PRE> | |
13345 | %typemap(newfree) char * "free($1);"; | |
13346 | ... | |
13347 | %newobject strdup; | |
13348 | ... | |
13349 | char *strdup(const char *s); | |
13350 | </PRE> | |
13351 | </DIV> | |
13352 | <P> In this case, the result of the function is a string in the target | |
13353 | language. Since this string is a copy of the original result, the data | |
13354 | returned by <TT>strdup()</TT> is no longer needed. The "newfree" | |
13355 | typemap in the example simply releases this memory.</P> | |
13356 | <P><B> Compatibility note:</B> Previous versions of SWIG had a special <TT> | |
13357 | %new</TT> directive. However, unlike <TT>%newobject</TT>, it only | |
13358 | applied to the next declaration. For example:</P> | |
13359 | <DIV class="code"> | |
13360 | <PRE> | |
13361 | %new char *strdup(const char *s); | |
13362 | </PRE> | |
13363 | </DIV> | |
13364 | <P> For now this is still supported but is deprecated.</P> | |
13365 | <P><B> How to shoot yourself in the foot:</B> The <TT>%newobject</TT> | |
13366 | directive is not a declaration modifier like the old <TT>%new</TT> | |
13367 | directive. Don't write code like this:</P> | |
13368 | <DIV class="code"> | |
13369 | <PRE> | |
13370 | %newobject | |
13371 | char *strdup(const char *s); | |
13372 | </PRE> | |
13373 | </DIV> | |
13374 | <P> The results might not be what you expect.</P> | |
13375 | <H2><A name="features"></A>11.3 Features and the %feature directive</H2> | |
13376 | <P> Both <TT>%exception</TT> and <TT>%newobject</TT> are examples of a | |
13377 | more general purpose customization mechanism known as "features." A | |
13378 | feature is simply a user-definable property that is attached to | |
13379 | specific declarations. Features are attached using the <TT>%feature</TT> | |
13380 | directive. For example:</P> | |
13381 | <DIV class="code"> | |
13382 | <PRE> | |
13383 | %feature("except") Object::allocate { | |
13384 | try { | |
13385 | $action | |
13386 | } | |
13387 | catch (MemoryError) { | |
13388 | croak("Out of memory"); | |
13389 | } | |
13390 | } | |
13391 | ||
13392 | %feature("new","1") *::copy; | |
13393 | </PRE> | |
13394 | </DIV> | |
13395 | <P> In fact, the <TT>%exception</TT> and <TT>%newobject</TT> directives | |
13396 | are really nothing more than macros involving <TT>%feature</TT>:</P> | |
13397 | <DIV class="code"> | |
13398 | <PRE> | |
13399 | #define %exception %feature("except") | |
13400 | #define %newobject %feature("new","1") | |
13401 | </PRE> | |
13402 | </DIV> | |
13403 | <P> The name matching rules outlined in the <A href="#ambiguity_resolution_renaming"> | |
13404 | Ambiguity resolution and renaming</A> section applies to all <TT> | |
13405 | %feature</TT> directives. In fact the the <TT>%rename</TT> directive is | |
13406 | just a special form of <TT>%feature</TT>. The matching rules mean that | |
13407 | features are very flexible and can be applied with pinpoint accuracy to | |
13408 | specific declarations if needed. Additionally, if no declaration name | |
13409 | is given, a global feature is said to be defined. This feature is then | |
13410 | attached to<EM> every</EM> declaration that follows. This is how global | |
13411 | exception handlers are defined. For example:</P> | |
13412 | <DIV class="code"> | |
13413 | <PRE> | |
13414 | /* Define a global exception handler */ | |
13415 | %feature("except") { | |
13416 | try { | |
13417 | $action | |
13418 | } | |
13419 | ... | |
13420 | } | |
13421 | ||
13422 | ... bunch of declarations ... | |
13423 | </PRE> | |
13424 | </DIV> | |
13425 | <P> The <TT>%feature</TT> directive can be used with different syntax. | |
13426 | The following are all equivalent:</P> | |
13427 | <DIV class="code"> | |
13428 | <PRE> | |
13429 | %feature("except") Object::method { $action }; | |
13430 | %feature("except") Object::method %{ $action %}; | |
13431 | %feature("except") Object::method " $action "; | |
13432 | %feature("except","$action") Object::method; | |
13433 | </PRE> | |
13434 | </DIV> | |
13435 | <P> The syntax in the first variation will generate the <TT>{ }</TT> | |
13436 | delimiters used whereas the other variations will not. The <TT>%feature</TT> | |
13437 | directive also accepts XML style attributes in the same way that | |
13438 | typemaps will. Any number of attributes can be specified. The following | |
13439 | is the generic syntax for features:</P> | |
13440 | <DIV class="code"> | |
13441 | <PRE> | |
13442 | %feature("name","value", attribute1="AttributeValue1") symbol; | |
13443 | %feature("name", attribute1="AttributeValue1") symbol {value}; | |
13444 | %feature("name", attribute1="AttributeValue1") symbol %{value%}; | |
13445 | %feature("name", attribute1="AttributeValue1") symbol "value"; | |
13446 | </PRE> | |
13447 | </DIV> | |
13448 | <P> More than one attribute can be specified using a comma separated | |
13449 | list. The Java module is an example that uses attributes in <TT> | |
13450 | %feature("except")</TT>. The <TT>throws</TT> attribute specifies the | |
13451 | name of a Java class to add to a proxy method's throws clause. In the | |
13452 | following example, <TT>MyExceptionClass</TT> is the name of the Java | |
13453 | class for adding to the throws clause.</P> | |
13454 | <DIV class="code"> | |
13455 | <PRE> | |
13456 | %feature("except", throws="MyExceptionClass") Object::method { | |
13457 | try { | |
13458 | $action | |
13459 | } catch (...) { | |
13460 | ... code to throw a MyExceptionClass Java exception ... | |
13461 | } | |
13462 | }; | |
13463 | </PRE> | |
13464 | </DIV> | |
13465 | <P> Further details can be obtained from the <A href="#exception_handling"> | |
13466 | Java exception handling</A> section.</P> | |
13467 | <H3><A name="Customization_feature_flags"></A>11.3.1 Feature flags</H3> | |
13468 | <P> Feature flags are used to enable or disable a particular feature. | |
13469 | Feature flags are a common but simple usage of <TT>%feature</TT> and | |
13470 | the feature value should be either <TT>1</TT> to enable or <TT>0</TT> | |
13471 | to disable the feature.</P> | |
13472 | <DIV class="code"> | |
13473 | <PRE> | |
13474 | %feature("name") // enables feature | |
13475 | %feature("name", "1") // enables feature | |
13476 | %feature("name", "x") // enables feature | |
13477 | %feature("name", "0") // disables feature | |
13478 | %feature("name", "") // clears feature | |
13479 | </PRE> | |
13480 | </DIV> | |
13481 | <P> Actually any value other than zero will enable the feature. Note | |
13482 | that if the value is omitted completely, the default value becomes <TT> | |
13483 | 1</TT>, thereby enabling the feature. A feature is cleared by specifying | |
13484 | no value, see <A href="#Customization_clearing_features">Clearing | |
13485 | features</A>. The <TT>%immutable</TT> directive described in the <A href="#SWIG_readonly_variables"> | |
13486 | Creating read-only variables</A> section, is just a macro for <TT> | |
13487 | %feature("immutable")</TT>, and can be used to demonstrates feature | |
13488 | flags:</P> | |
13489 | <DIV class="code"> | |
13490 | <PRE> | |
13491 | // features are disabled by default | |
13492 | int red; // mutable | |
13493 | ||
13494 | %feature("immutable"); // global enable | |
13495 | int orange; // immutable | |
13496 | ||
13497 | %feature("immutable","0"); // global disable | |
13498 | int yellow; // mutable | |
13499 | ||
13500 | %feature("immutable","1"); // another form of global enable | |
13501 | int green; // immutable | |
13502 | ||
13503 | %feature("immutable",""); // clears the global feature | |
13504 | int blue; // mutable | |
13505 | </PRE> | |
13506 | </DIV> | |
13507 | <P> Note that features are disabled by default and must be explicitly | |
13508 | enabled either globally or by specifying a targeted declaration. The | |
13509 | above intersperses SWIG directives with C code. Of course you can | |
13510 | target features explicitly, so the above could also be rewritten as:</P> | |
13511 | <DIV class="code"> | |
13512 | <PRE> | |
13513 | %feature("immutable","1") orange; | |
13514 | %feature("immutable","1") green; | |
13515 | int red; // mutable | |
13516 | int orange; // immutable | |
13517 | int yellow; // mutable | |
13518 | int green; // immutable | |
13519 | int blue; // mutable | |
13520 | </PRE> | |
13521 | </DIV> | |
13522 | <P> The above approach allows for the C declarations to be separated | |
13523 | from the SWIG directives for when the C declarations are parsed from a | |
13524 | C header file. The logic above can of course be inverted and rewritten | |
13525 | as:</P> | |
13526 | <DIV class="code"> | |
13527 | <PRE> | |
13528 | %feature("immutable","1"); | |
13529 | %feature("immutable","0") red; | |
13530 | %feature("immutable","0") yellow; | |
13531 | %feature("immutable","0") blue; | |
13532 | int red; // mutable | |
13533 | int orange; // immutable | |
13534 | int yellow; // mutable | |
13535 | int green; // immutable | |
13536 | int blue; // mutable | |
13537 | </PRE> | |
13538 | </DIV> | |
13539 | <H3><A name="Customization_clearing_features"></A>11.3.2 Clearing | |
13540 | features</H3> | |
13541 | <P> A feature stays in effect until it is explicitly cleared. A feature | |
13542 | is cleared by supplying a <TT>%feature</TT> directive with no value. | |
13543 | For example <TT>%feature("name","")</TT>. A cleared feature means that | |
13544 | any feature exactly matching any previously defined feature is no | |
13545 | longer used in the name matching rules. So if a feature is cleared, it | |
13546 | might mean that another name matching rule will apply. To clarify, | |
13547 | let's consider the <TT>except</TT> feature again (<TT>%exception</TT>):</P> | |
13548 | <DIV class="code"> | |
13549 | <PRE> | |
13550 | // Define global exception handler | |
13551 | %feature("except") { | |
13552 | try { | |
13553 | $action | |
13554 | } catch (...) { | |
13555 | croak("Unknown C++ exception"); | |
13556 | } | |
13557 | } | |
13558 | ||
13559 | // Define exception handler for all clone methods to log the method calls | |
13560 | %feature("except") *::clone() { | |
13561 | try { | |
13562 | logger.info("$action"); | |
13563 | $action | |
13564 | } catch (...) { | |
13565 | croak("Unknown C++ exception"); | |
13566 | } | |
13567 | } | |
13568 | ||
13569 | ... initial set of class declarations with clone methods ... | |
13570 | ||
13571 | // clear the previously defined feature | |
13572 | %feature("except","") *::clone(); | |
13573 | ||
13574 | ... final set of class declarations with clone methods ... | |
13575 | </PRE> | |
13576 | </DIV> | |
13577 | <P> In the above scenario, the initial set of clone methods will log all | |
13578 | method invocations from the target language. This specific feature is | |
13579 | cleared for the final set of clone methods. However, these clone | |
13580 | methods will still have an exception handler (without logging) as the | |
13581 | next best feature match for them is the global exception handler.</P> | |
13582 | <P> Note that clearing a feature is not always the same as disabling it. | |
13583 | Clearing the feature above with <TT>%feature("except","") *::clone()</TT> | |
13584 | is not the same as specifying <TT>%feature("except","0") *::clone()</TT> | |
13585 | . The former will disable the feature for clone methods - the feature is | |
13586 | still a better match than the global feature. If on the other hand, no | |
13587 | global exception handler had been defined at all, then clearing the | |
13588 | feature would be the same as disabling it as no other feature would | |
13589 | have matched.</P> | |
13590 | <P> Note that the feature must match exactly for it to be cleared by any | |
13591 | previously defined feature. For example the following attempt to clear | |
13592 | the initial feature will not work:</P> | |
13593 | <DIV class="code"> | |
13594 | <PRE> | |
13595 | %feature("except") clone() { logger.info("$action"); $action } | |
13596 | %feature("except","") *::clone(); | |
13597 | </PRE> | |
13598 | </DIV> | |
13599 | <P> but this will:</P> | |
13600 | <DIV class="code"> | |
13601 | <PRE> | |
13602 | %feature("except") clone() { logger.info("$action"); $action } | |
13603 | %feature("except","") clone(); | |
13604 | </PRE> | |
13605 | </DIV> | |
13606 | <H3><A name="Customization_features_default_args"></A>11.3.3 Features | |
13607 | and default arguments</H3> | |
13608 | <P> SWIG treats methods with default arguments as separate overloaded | |
13609 | methods as detailed in the <A href="#SWIGPlus_default_args">default | |
13610 | arguments</A> section. Any <TT>%feature</TT> targeting a method with | |
13611 | default arguments will apply to all the extra overloaded methods that | |
13612 | SWIG generates if the default arguments are specified in the feature. | |
13613 | If the default arguments are not specified in the feature, then the | |
13614 | feature will match that exact wrapper method only and not the extra | |
13615 | overloaded methods that SWIG generates. For example:</P> | |
13616 | <DIV class="code"> | |
13617 | <PRE> | |
13618 | %feature("except") void hello(int i=0, double d=0.0) { ... } | |
13619 | void hello(int i=0, double d=0.0); | |
13620 | </PRE> | |
13621 | </DIV> | |
13622 | <P> will apply the feature to all three wrapper methods, that is:</P> | |
13623 | <DIV class="code"> | |
13624 | <PRE> | |
13625 | void hello(int i, double d); | |
13626 | void hello(int i); | |
13627 | void hello(); | |
13628 | </PRE> | |
13629 | </DIV> | |
13630 | <P> If the default arguments are not specified in the feature:</P> | |
13631 | <DIV class="code"> | |
13632 | <PRE> | |
13633 | %feature("except") void hello(int i, double d) { ... } | |
13634 | void hello(int i=0, double d=0.0); | |
13635 | </PRE> | |
13636 | </DIV> | |
13637 | <P> then the feature will only apply to this wrapper method:</P> | |
13638 | <DIV class="code"> | |
13639 | <PRE> | |
13640 | void hello(int i, double d); | |
13641 | </PRE> | |
13642 | </DIV> | |
13643 | <P> and not these wrapper methods:</P> | |
13644 | <DIV class="code"> | |
13645 | <PRE> | |
13646 | void hello(int i); | |
13647 | void hello(); | |
13648 | </PRE> | |
13649 | </DIV> | |
13650 | <P> If <A href="#SWIGPlus_default_args">compactdefaultargs</A> are being | |
13651 | used, then the difference between specifying or not specifying default | |
13652 | arguments in a feature is not applicable as just one wrapper is | |
13653 | generated.</P> | |
13654 | <P><B> Compatibility note:</B> The different behaviour of features | |
13655 | specified with or without default arguments was introduced in | |
13656 | SWIG-1.3.23 when the approach to wrapping methods with default | |
13657 | arguments was changed.</P> | |
13658 | <H3><A name="features_example"></A>11.3.4 Feature example</H3> | |
13659 | <P> As has been shown earlier, the intended use for the <TT>%feature</TT> | |
13660 | directive is as a highly flexible customization mechanism that can be | |
13661 | used to annotate declarations with additional information for use by | |
13662 | specific target language modules. Another example is in the Python | |
13663 | module. You might use <TT>%feature</TT> to rewrite proxy/shadow class | |
13664 | code as follows:</P> | |
13665 | <DIV class="code"> | |
13666 | <PRE> | |
13667 | %module example | |
13668 | %rename(bar_id) bar(int,double); | |
13669 | ||
13670 | // Rewrite bar() to allow some nice overloading | |
13671 | ||
13672 | %feature("shadow") Foo::bar(int) %{ | |
13673 | def bar(*args): | |
13674 | if len(args) == 3: | |
13675 | return apply(examplec.Foo_bar_id,args) | |
13676 | return apply(examplec.Foo_bar,args) | |
13677 | %} | |
13678 | ||
13679 | class Foo { | |
13680 | public: | |
13681 | int bar(int x); | |
13682 | int bar(int x, double y); | |
13683 | } | |
13684 | </PRE> | |
13685 | </DIV> | |
13686 | <P> Further details of <TT>%feature</TT> usage is described in the | |
13687 | documentation for specific language modules.</P> | |
13688 | <HR NOSHADE> | |
13689 | <H1><A name="Contract"></A>12 Contracts</H1> | |
13690 | ||
13691 | <!-- INDEX --> | |
13692 | <DIV class="sectiontoc"> | |
13693 | <UL> | |
13694 | <LI><A href="#Contract_nn2">The %contract directive</A></LI> | |
13695 | <LI><A href="#Contract_nn3">%contract and classes</A></LI> | |
13696 | <LI><A href="#Contract_nn4">Constant aggregation and %aggregate_check</A> | |
13697 | </LI> | |
13698 | <LI><A href="#Contract_nn5">Notes</A></LI> | |
13699 | </UL> | |
13700 | </DIV> | |
13701 | <!-- INDEX --> | |
13702 | <P> A common problem that arises when wrapping C libraries is that of | |
13703 | maintaining reliability and checking for errors. The fact of the matter | |
13704 | is that many C programs are notorious for not providing error checks. | |
13705 | Not only that, when you expose the internals of an application as a | |
13706 | library, it often becomes possible to crash it simply by providing bad | |
13707 | inputs or using it in a way that wasn't intended.</P> | |
13708 | <P> This chapter describes SWIG's support for software contracts. In the | |
13709 | context of SWIG, a contract can be viewed as a runtime constraint that | |
13710 | is attached to a declaration. For example, you can easily attach | |
13711 | argument checking rules, check the output values of a function and | |
13712 | more. When one of the rules is violated by a script, a runtime | |
13713 | exception is generated rather than having the program continue to | |
13714 | execute.</P> | |
13715 | <H2><A name="Contract_nn2"></A>12.1 The %contract directive</H2> | |
13716 | <P> Contracts are added to a declaration using the %contract directive. | |
13717 | Here is a simple example:</P> | |
13718 | <DIV class="code"> | |
13719 | <PRE> | |
13720 | %contract sqrt(double x) { | |
13721 | require: | |
13722 | x >= 0; | |
13723 | ensure: | |
13724 | sqrt >= 0; | |
13725 | } | |
13726 | ||
13727 | ... | |
13728 | double sqrt(double); | |
13729 | </PRE> | |
13730 | </DIV> | |
13731 | <P> In this case, a contract is being added to the <TT>sqrt()</TT> | |
13732 | function. The <TT>%contract</TT> directive must always appear before | |
13733 | the declaration in question. Within the contract there are two | |
13734 | sections, both of which are optional. The <TT>require:</TT> section | |
13735 | specifies conditions that must hold before the function is called. | |
13736 | Typically, this is used to check argument values. The <TT>ensure:</TT> | |
13737 | section specifies conditions that must hold after the function is | |
13738 | called. This is often used to check return values or the state of the | |
13739 | program. In both cases, the conditions that must hold must be specified | |
13740 | as boolean expressions.</P> | |
13741 | <P> In the above example, we're simply making sure that sqrt() returns a | |
13742 | non-negative number (if it didn't, then it would be broken in some | |
13743 | way).</P> | |
13744 | <P> Once a contract has been specified, it modifies the behavior of the | |
13745 | resulting module. For example:</P> | |
13746 | <DIV class="shell"> | |
13747 | <PRE> | |
13748 | >>> example.sqrt(2) | |
13749 | 1.4142135623730951 | |
13750 | >>> example.sqrt(-2) | |
13751 | Traceback (most recent call last): | |
13752 | File "<stdin>", line 1, in ? | |
13753 | RuntimeError: Contract violation: require: (arg1>=0) | |
13754 | >>> | |
13755 | </PRE> | |
13756 | </DIV> | |
13757 | <H2><A name="Contract_nn3"></A>12.2 %contract and classes</H2> | |
13758 | <P> The <TT>%contract</TT> directive can also be applied to class | |
13759 | methods and constructors. For example:</P> | |
13760 | <DIV class="code"> | |
13761 | <PRE> | |
13762 | %contract Foo::bar(int x, int y) { | |
13763 | require: | |
13764 | x > 0; | |
13765 | ensure: | |
13766 | bar > 0; | |
13767 | } | |
13768 | ||
13769 | %contract Foo::Foo(int a) { | |
13770 | require: | |
13771 | a > 0; | |
13772 | } | |
13773 | ||
13774 | class Foo { | |
13775 | public: | |
13776 | Foo(int); | |
13777 | int bar(int, int); | |
13778 | }; | |
13779 | </PRE> | |
13780 | </DIV> | |
13781 | <P> The way in which <TT>%contract</TT> is applied is exactly the same | |
13782 | as the <TT>%feature</TT> directive. Thus, any contract that you | |
13783 | specified for a base class will also be attached to inherited methods. | |
13784 | For example:</P> | |
13785 | <DIV class="code"> | |
13786 | <PRE> | |
13787 | class Spam : public Foo { | |
13788 | public: | |
13789 | int bar(int,int); // Gets contract defined for Foo::bar(int,int) | |
13790 | }; | |
13791 | </PRE> | |
13792 | </DIV> | |
13793 | <P> In addition to this, separate contracts can be applied to both the | |
13794 | base class and a derived class. For example:</P> | |
13795 | <DIV class="code"> | |
13796 | <PRE> | |
13797 | %contract Foo::bar(int x, int) { | |
13798 | require: | |
13799 | x > 0; | |
13800 | } | |
13801 | ||
13802 | %contract Spam::bar(int, int y) { | |
13803 | require: | |
13804 | y > 0; | |
13805 | } | |
13806 | ||
13807 | class Foo { | |
13808 | public: | |
13809 | int bar(int,int); // Gets Foo::bar contract. | |
13810 | }; | |
13811 | ||
13812 | class Spam : public Foo { | |
13813 | public: | |
13814 | int bar(int,int); // Gets Foo::bar and Spam::bar contract | |
13815 | }; | |
13816 | </PRE> | |
13817 | </DIV> | |
13818 | <P> When more than one contract is applied, the conditions specified in | |
13819 | a "require:" section are combined together using a logical-AND | |
13820 | operation. In other words conditions specified for the base class and | |
13821 | conditions specified for the derived class all must hold. In the above | |
13822 | example, this means that both the arguments to <TT>Spam::bar</TT> must | |
13823 | be positive.</P> | |
13824 | <H2><A name="Contract_nn4"></A>12.3 Constant aggregation and | |
13825 | %aggregate_check</H2> | |
13826 | <P> Consider an interface file that contains the following code:</P> | |
13827 | <DIV class="code"> | |
13828 | <PRE> | |
13829 | #define UP 1 | |
13830 | #define DOWN 2 | |
13831 | #define RIGHT 3 | |
13832 | #define LEFT 4 | |
13833 | ||
13834 | void move(SomeObject *, int direction, int distance); | |
13835 | </PRE> | |
13836 | </DIV> | |
13837 | <P> One thing you might want to do is impose a constraint on the | |
13838 | direction parameter to make sure it's one of a few accepted values. To | |
13839 | do that, SWIG provides an easy to use macro %aggregate_check() that | |
13840 | works like this:</P> | |
13841 | <DIV class="code"> | |
13842 | <PRE> | |
13843 | %aggregate_check(int, check_direction, UP, DOWN, LEFT, RIGHT); | |
13844 | </PRE> | |
13845 | </DIV> | |
13846 | <P> This merely defines a utility function of the form</P> | |
13847 | <DIV class="code"> | |
13848 | <PRE> | |
13849 | int check_direction(int x); | |
13850 | </PRE> | |
13851 | </DIV> | |
13852 | <P> That checks the argument x to see if it is one of the values listed. | |
13853 | This utility function can be used in contracts. For example:</P> | |
13854 | <DIV class="code"> | |
13855 | <PRE> | |
13856 | %aggregate_check(int, check_direction, UP, DOWN, RIGHT, LEFT); | |
13857 | ||
13858 | %contract move(SomeObject *, int direction, in) { | |
13859 | require: | |
13860 | check_direction(direction); | |
13861 | } | |
13862 | ||
13863 | #define UP 1 | |
13864 | #define DOWN 2 | |
13865 | #define RIGHT 3 | |
13866 | #define LEFT 4 | |
13867 | ||
13868 | void move(SomeObject *, int direction, int distance); | |
13869 | </PRE> | |
13870 | </DIV> | |
13871 | <P> Alternatively, it can be used in typemaps and other directives. For | |
13872 | example:</P> | |
13873 | <DIV class="code"> | |
13874 | <PRE> | |
13875 | %aggregate_check(int, check_direction, UP, DOWN, RIGHT, LEFT); | |
13876 | ||
13877 | %typemap(check) int direction { | |
13878 | if (!check_direction($1)) SWIG_exception(SWIG_ValueError, "Bad direction"); | |
13879 | } | |
13880 | ||
13881 | #define UP 1 | |
13882 | #define DOWN 2 | |
13883 | #define RIGHT 3 | |
13884 | #define LEFT 4 | |
13885 | ||
13886 | void move(SomeObject *, int direction, int distance); | |
13887 | </PRE> | |
13888 | </DIV> | |
13889 | <P> Regrettably, there is no automatic way to perform similar checks | |
13890 | with enums values. Maybe in a future release.</P> | |
13891 | <H2><A name="Contract_nn5"></A>12.4 Notes</H2> | |
13892 | <P> Contract support was implemented by Songyan (Tiger) Feng and first | |
13893 | appeared in SWIG-1.3.20.</P> | |
13894 | <HR NOSHADE> | |
13895 | <H1><A name="Varargs"></A>13 Variable Length Arguments</H1> | |
13896 | ||
13897 | <!-- INDEX --> | |
13898 | <DIV class="sectiontoc"> | |
13899 | <UL> | |
13900 | <LI><A href="#Varargs_nn2">Introduction</A></LI> | |
13901 | <LI><A href="#Varargs_nn3">The Problem</A></LI> | |
13902 | <LI><A href="#Varargs_nn4">Default varargs support</A></LI> | |
13903 | <LI><A href="#Varargs_nn5">Argument replacement using %varargs</A></LI> | |
13904 | <LI><A href="#Varargs_nn6">Varargs and typemaps</A></LI> | |
13905 | <LI><A href="#Varargs_nn7">Varargs wrapping with libffi</A></LI> | |
13906 | <LI><A href="#Varargs_nn8">Wrapping of va_list</A></LI> | |
13907 | <LI><A href="#Varargs_nn9">C++ Issues</A></LI> | |
13908 | <LI><A href="#Varargs_nn10">Discussion</A></LI> | |
13909 | </UL> | |
13910 | </DIV> | |
13911 | <!-- INDEX --> | |
13912 | <P><B> (a.k.a, "The horror. The horror.")</B></P> | |
13913 | <P> This chapter describes the problem of wrapping functions that take a | |
13914 | variable number of arguments. For instance, generating wrappers for the | |
13915 | C <TT>printf()</TT> family of functions.</P> | |
13916 | <P> This topic is sufficiently advanced to merit its own chapter. In | |
13917 | fact, support for varargs is an often requested feature that was first | |
13918 | added in SWIG-1.3.12. Most other wrapper generation tools have wisely | |
13919 | chosen to avoid this issue.</P> | |
13920 | <H2><A name="Varargs_nn2"></A>13.1 Introduction</H2> | |
13921 | <P> Some C and C++ programs may include functions that accept a variable | |
13922 | number of arguments. For example, most programmers are familiar with | |
13923 | functions from the C library such as the following:</P> | |
13924 | <DIV class="code"> | |
13925 | <PRE> | |
13926 | int printf(const char *fmt, ...) | |
13927 | int fprintf(FILE *, const char *fmt, ...); | |
13928 | int sprintf(char *s, const char *fmt, ...); | |
13929 | </PRE> | |
13930 | </DIV> | |
13931 | <P> Although there is probably little practical purpose in wrapping | |
13932 | these specific C library functions in a scripting language (what would | |
13933 | be the point?), a library may include its own set of special functions | |
13934 | based on a similar API. For example:</P> | |
13935 | <DIV class="code"> | |
13936 | <PRE> | |
13937 | int traceprintf(const char *fmt, ...); | |
13938 | </PRE> | |
13939 | </DIV> | |
13940 | <P> In this case, you may want to have some kind of access from the | |
13941 | target language.</P> | |
13942 | <P> Before describing the SWIG implementation, it is important to | |
13943 | discuss the common uses of varargs that you are likely to encounter in | |
13944 | real programs. Obviously, there are the <TT>printf()</TT> style output | |
13945 | functions as shown. Closely related to this would be <TT>scanf()</TT> | |
13946 | style input functions that accept a format string and a list of | |
13947 | pointers into which return values are placed. However, variable length | |
13948 | arguments are also sometimes used to write functions that accept a | |
13949 | NULL-terminated list of pointers. A good example of this would be a | |
13950 | function like this:</P> | |
13951 | <DIV class="code"> | |
13952 | <PRE> | |
13953 | int execlp(const char *path, const char *arg1, ...); | |
13954 | ... | |
13955 | ||
13956 | /* Example */ | |
13957 | execlp("ls","ls","-l",NULL); | |
13958 | </PRE> | |
13959 | </DIV> | |
13960 | <P> In addition, varargs is sometimes used to fake default arguments in | |
13961 | older C libraries. For instance, the low level <TT>open()</TT> system | |
13962 | call is often declared as a varargs function so that it will accept two | |
13963 | or three arguments:</P> | |
13964 | <DIV class="code"> | |
13965 | <PRE> | |
13966 | int open(const char *path, int oflag, ...); | |
13967 | ... | |
13968 | ||
13969 | /* Examples */ | |
13970 | f = open("foo", O_RDONLY); | |
13971 | g = open("bar", O_WRONLY | O_CREAT, 0644); | |
13972 | </PRE> | |
13973 | </DIV> | |
13974 | <P> Finally, to implement a varargs function, recall that you have to | |
13975 | use the C library functions defined in <TT><stdarg.h></TT>. For | |
13976 | example:</P> | |
13977 | <DIV class="code"> | |
13978 | <PRE> | |
13979 | List make_list(const char *s, ...) { | |
13980 | va_list ap; | |
13981 | List x; | |
13982 | ... | |
13983 | va_start(ap, s); | |
13984 | while (s) { | |
13985 | x.append(s); | |
13986 | s = va_arg(ap, const char *); | |
13987 | } | |
13988 | va_end(ap); | |
13989 | return x; | |
13990 | } | |
13991 | </PRE> | |
13992 | </DIV> | |
13993 | <H2><A name="Varargs_nn3"></A>13.2 The Problem</H2> | |
13994 | <P> Generating wrappers for a variable length argument function presents | |
13995 | a number of special challenges. Although C provides support for | |
13996 | implementing functions that receive variable length arguments, there | |
13997 | are no functions that can go in the other direction. Specifically, you | |
13998 | can't write a function that dynamically creates a list of arguments and | |
13999 | which invokes a varargs function on your behalf.</P> | |
14000 | <P> Although it is possible to write functions that accept the special | |
14001 | type <TT>va_list</TT>, this is something entirely different. You can't | |
14002 | take a <TT>va_list</TT> structure and pass it in place of the variable | |
14003 | length arguments to another varargs function. It just doesn't work.</P> | |
14004 | <P> The reason this doesn't work has to do with the way that function | |
14005 | calls get compiled. For example, suppose that your program has a | |
14006 | function call like this:</P> | |
14007 | <DIV class="code"> | |
14008 | <PRE> | |
14009 | printf("Hello %s. Your number is %d\n", name, num); | |
14010 | </PRE> | |
14011 | </DIV> | |
14012 | <P> When the compiler looks at this, it knows that you are calling <TT> | |
14013 | printf()</TT> with exactly three arguments. Furthermore, it knows that | |
14014 | the number of arguments as well are their types and sizes is<EM> never</EM> | |
14015 | going to change during program execution. Therefore, this gets turned | |
14016 | to machine code that sets up a three-argument stack frame followed by a | |
14017 | call to <TT>printf()</TT>.</P> | |
14018 | <P> In contrast, suppose you attempted to make some kind of wrapper | |
14019 | around <TT>printf()</TT> using code like this:</P> | |
14020 | <DIV class="code"> | |
14021 | <PRE> | |
14022 | int wrap_printf(const char *fmt, ...) { | |
14023 | va_list ap; | |
14024 | va_start(ap,fmt); | |
14025 | ... | |
14026 | printf(fmt,ap); | |
14027 | ... | |
14028 | va_end(ap); | |
14029 | }; | |
14030 | </PRE> | |
14031 | </DIV> | |
14032 | <P> Athough this code might compile, it won't do what you expect. This | |
14033 | is because the call to <TT>printf()</TT> is compiled as a procedure | |
14034 | call involving only two arguments. However, clearly a two-argument | |
14035 | configuration of the call stack is completely wrong if your intent is | |
14036 | to pass an arbitrary number of arguments to the real <TT>printf()</TT>. | |
14037 | Needless to say, it won't work.</P> | |
14038 | <P> Unfortunately, the situation just described is exactly the problem | |
14039 | faced by wrapper generation tools. In general, the number of passed | |
14040 | arguments will not be known until run-time. To make matters even worse, | |
14041 | you won't know the types and sizes of arguments until run-time as well. | |
14042 | Needless to say, there is no obvious way to make the C compiler | |
14043 | generate code for a function call involving an unknown number of | |
14044 | arguments of unknown types.</P> | |
14045 | <P> In theory, it<EM> is</EM> possible to write a wrapper that does the | |
14046 | right thing. However, this involves knowing the underlying ABI for the | |
14047 | target platform and language as well as writing special purpose code | |
14048 | that manually constructed the call stack before making a procedure | |
14049 | call. Unfortunately, both of these tasks require the use of inline | |
14050 | assembly code. Clearly, that's the kind of solution you would much | |
14051 | rather avoid.</P> | |
14052 | <P> With this nastiness in mind, SWIG provides a number of solutions to | |
14053 | the varargs wrapping problem. Most of these solutions are compromises | |
14054 | that provide limited varargs support without having to resort to | |
14055 | assembly language. However, SWIG can also support real varargs wrapping | |
14056 | (with stack-frame manipulation) if you are willing to get hands dirty. | |
14057 | Keep reading.</P> | |
14058 | <H2><A name="Varargs_nn4"></A>13.3 Default varargs support</H2> | |
14059 | <P> When variable length arguments appear in an interface, the default | |
14060 | behavior is to drop the variable argument list entirely, replacing them | |
14061 | with a single NULL pointer. For example, if you had this function,</P> | |
14062 | <DIV class="code"> | |
14063 | <PRE> | |
14064 | void traceprintf(const char *fmt, ...); | |
14065 | </PRE> | |
14066 | </DIV> | |
14067 | <P> it would be wrapped as if it had been declared as follows:</P> | |
14068 | <DIV class="code"> | |
14069 | <PRE> | |
14070 | void traceprintf(const char *fmt); | |
14071 | </PRE> | |
14072 | </DIV> | |
14073 | <P> When the function is called inside the wrappers, it is called as | |
14074 | follows:</P> | |
14075 | <DIV class="code"> | |
14076 | <PRE> | |
14077 | traceprintf(arg1, NULL); | |
14078 | </PRE> | |
14079 | </DIV> | |
14080 | <P> Arguably, this approach seems to defeat the whole point of variable | |
14081 | length arguments. However, this actually provides enough support for | |
14082 | many simple kinds of varargs functions to still be useful. For | |
14083 | instance, you could make function calls like this (in Python):</P> | |
14084 | <DIV class="targetlang"> | |
14085 | <PRE> | |
14086 | >>> traceprintf("Hello World") | |
14087 | >>> traceprintf("Hello %s. Your number is %d\n" % (name, num)) | |
14088 | </PRE> | |
14089 | </DIV> | |
14090 | <P> Notice how string formatting is being done in Python instead of C.</P> | |
14091 | <H2><A name="Varargs_nn5"></A>13.4 Argument replacement using %varargs</H2> | |
14092 | <P> Instead of dropping the variable length arguments, an alternative | |
14093 | approach is to replace <TT>(...)</TT> with a set of suitable arguments. | |
14094 | SWIG provides a special <TT>%varargs</TT> directive that can be used to | |
14095 | do this. For example,</P> | |
14096 | <DIV class="code"> | |
14097 | <PRE> | |
14098 | %varargs(int mode = 0) open; | |
14099 | ... | |
14100 | int open(const char *path, int oflags, ...); | |
14101 | </PRE> | |
14102 | </DIV> | |
14103 | <P> is equivalent to this:</P> | |
14104 | <DIV class="code"> | |
14105 | <PRE> | |
14106 | int open(const char *path, int oflags, int mode = 0); | |
14107 | </PRE> | |
14108 | </DIV> | |
14109 | <P> In this case, <TT>%varargs</TT> is simply providing more specific | |
14110 | information about the extra arguments that might be passed to a | |
14111 | function. If the parameters to a varargs function are of uniform type, <TT> | |
14112 | %varargs</TT> can also accept a numerical argument count as follows:</P> | |
14113 | <DIV class="code"> | |
14114 | <PRE> | |
14115 | %varargs(10,char *arg = NULL) execlp; | |
14116 | ... | |
14117 | int execlp(const char *path, const char *arg1, ...); | |
14118 | </PRE> | |
14119 | </DIV> | |
14120 | <P> This would wrap <TT>execlp()</TT> as a function that accepted up to | |
14121 | 10 optional arguments. Depending on the application, this may be more | |
14122 | than enough for practical purposes.</P> | |
14123 | <P> Argument replacement is most appropriate in cases where the types of | |
14124 | the extra arguments is uniform and the maximum number of arguments is | |
14125 | known. When replicated argument replacement is used, at least one extra | |
14126 | argument is added to the end of the arguments when making the function | |
14127 | call. This argument serves as a sentinel to make sure the list is | |
14128 | properly terminated. It has the same value as that supplied to the <TT> | |
14129 | %varargs</TT> directive.</P> | |
14130 | <P> Argument replacement is not as useful when working with functions | |
14131 | that accept mixed argument types such as <TT>printf()</TT>. Providing | |
14132 | general purpose wrappers to such functions presents special problems | |
14133 | (covered shortly).</P> | |
14134 | <H2><A name="Varargs_nn6"></A>13.5 Varargs and typemaps</H2> | |
14135 | <P> Variable length arguments may be used in typemap specifications. For | |
14136 | example:</P> | |
14137 | <DIV class="code"> | |
14138 | <PRE> | |
14139 | %typemap(in) (...) { | |
14140 | // Get variable length arguments (somehow) | |
14141 | ... | |
14142 | } | |
14143 | ||
14144 | %typemap(in) (const char *fmt, ...) { | |
14145 | // Multi-argument typemap | |
14146 | } | |
14147 | </PRE> | |
14148 | </DIV> | |
14149 | <P> However, this immediately raises the question of what "type" is | |
14150 | actually used to represent <TT>(...)</TT>. For lack of a better | |
14151 | alternative, the type of <TT>(...)</TT> is set to <TT>void *</TT>. | |
14152 | Since there is no way to dynamically pass arguments to a varargs | |
14153 | function (as previously described), the <TT>void *</TT> argument value | |
14154 | is intended to serve as a place holder for storing some kind of | |
14155 | information about the extra arguments (if any). In addition, the | |
14156 | default behavior of SWIG is to pass the <TT>void *</TT> value as an | |
14157 | argument to the function. Therefore, you could use the pointer to hold | |
14158 | a valid argument value if you wanted.</P> | |
14159 | <P> To illustrate, here is a safer version of wrapping <TT>printf()</TT> | |
14160 | in Python:</P> | |
14161 | <DIV class="code"> | |
14162 | <PRE> | |
14163 | %typemap(in) (const char *fmt, ...) { | |
14164 | $1 = "%s"; /* Fix format string to %s */ | |
14165 | $2 = (void *) PyString_AsString($input); /* Get string argument */ | |
14166 | }; | |
14167 | ... | |
14168 | int printf(const char *fmt, ...); | |
14169 | </PRE> | |
14170 | </DIV> | |
14171 | <P> In this example, the format string is implicitly set to <TT>"%s"</TT> | |
14172 | . This prevents a program from passing a bogus format string to the | |
14173 | extension. Then, the passed input object is decoded and placed in the <TT> | |
14174 | void *</TT> argument defined for the <TT>(...)</TT> argument. When the | |
14175 | actual function call is made, the underlying wrapper code will look | |
14176 | roughly like this:</P> | |
14177 | <DIV class="code"> | |
14178 | <PRE> | |
14179 | wrap_printf() { | |
14180 | char *arg1; | |
14181 | void *arg2; | |
14182 | int result; | |
14183 | ||
14184 | arg1 = "%s"; | |
14185 | arg2 = (void *) PyString_AsString(arg2obj); | |
14186 | ... | |
14187 | result = printf(arg1,arg2); | |
14188 | ... | |
14189 | } | |
14190 | </PRE> | |
14191 | </DIV> | |
14192 | <P> Notice how both arguments are passed to the function and it does | |
14193 | what you would expect.</P> | |
14194 | <P> The next example illustrates a more advanced kind of varargs | |
14195 | typemap. Disclaimer: this requires special support in the target | |
14196 | language module and is not guaranteed to work with all SWIG modules at | |
14197 | this time. It also starts to illustrate some of the more fundamental | |
14198 | problems with supporting varargs in more generality.</P> | |
14199 | <P> If a typemap is defined for any form of <TT>(...)</TT>, many SWIG | |
14200 | modules will generate wrappers that accept a variable number of | |
14201 | arguments as input and will make these arguments available in some | |
14202 | form. The precise details of this depends on the language module being | |
14203 | used (consult the appropriate chapter for more details). However, | |
14204 | suppose that you wanted to create a Python wrapper for the <TT>execlp()</TT> | |
14205 | function shown earlier. To do this using a typemap instead of using <TT> | |
14206 | %varargs</TT>, you might first write a typemap like this:</P> | |
14207 | <DIV class="code"> | |
14208 | <PRE> | |
14209 | %typemap(in) (...)(char *args[10]) { | |
14210 | int i; | |
14211 | int argc; | |
14212 | for (i = 0; i < 10; i++) args[i] = 0; | |
14213 | argc = PyTuple_Size(varargs); | |
14214 | if (argc > 10) { | |
14215 | PyErr_SetString(PyExc_ValueError,"Too many arguments"); | |
14216 | return NULL; | |
14217 | } | |
14218 | for (i = 0; i < argc; i++) { | |
14219 | PyObject *o = PyTuple_GetItem(varargs,i); | |
14220 | if (!PyString_Check(o)) { | |
14221 | PyErr_SetString(PyExc_ValueError,"Expected a string"); | |
14222 | return NULL; | |
14223 | } | |
14224 | args[i] = PyString_AsString(o); | |
14225 | } | |
14226 | $1 = (void *) args; | |
14227 | } | |
14228 | </PRE> | |
14229 | </DIV> | |
14230 | <P> In this typemap, the special variable <TT>varargs</TT> is a tuple | |
14231 | holding all of the extra arguments passed (this is specific to the | |
14232 | Python module). The typemap then pulls this apart and sticks the values | |
14233 | into the array of strings <TT>args</TT>. Then, the array is assigned to | |
14234 | <TT>$1</TT> (recall that this is the <TT>void *</TT> variable | |
14235 | corresponding to <TT>(...)</TT>). However, this assignment is only half | |
14236 | of the picture----clearly this alone is not enough to make the function | |
14237 | work. To patch everything up, you have to rewrite the underlying action | |
14238 | code using the <TT>%feature</TT> directive like this:</P> | |
14239 | <DIV class="code"> | |
14240 | <PRE> | |
14241 | %feature("action") execlp { | |
14242 | char *args = (char **) arg3; | |
14243 | result = execlp(arg1, arg2, args[0], args[1], args[2], args[3], args[4], | |
14244 | args[5],args[6],args[7],args[8],args[9], NULL); | |
14245 | } | |
14246 | ||
14247 | int execlp(const char *path, const char *arg, ...); | |
14248 | </PRE> | |
14249 | </DIV> | |
14250 | <P> This patches everything up and creates a function that more or less | |
14251 | works. However, don't try explaining this to your coworkers unless you | |
14252 | know for certain that they've had several cups of coffee. If you really | |
14253 | want to elevate your guru status and increase your job security, | |
14254 | continue to the next section.</P> | |
14255 | <H2><A name="Varargs_nn7"></A>13.6 Varargs wrapping with libffi</H2> | |
14256 | <P> All of the previous examples have relied on features of SWIG that | |
14257 | are portable and which don't rely upon any low-level machine-level | |
14258 | details. In many ways, they have all dodged the real issue of variable | |
14259 | length arguments by recasting a varargs function into some weaker | |
14260 | variation with a fixed number of arguments of known types. In many | |
14261 | cases, this works perfectly fine. However, if you want more generality | |
14262 | than this, you need to bring out some bigger guns.</P> | |
14263 | <P> One way to do this is to use a special purpose library such as | |
14264 | libffi (<A href="http://sources.redhat.com/libffi/"> | |
14265 | http://sources.redhat.com/libffi</A>). libffi is a library that allows | |
14266 | you to dynamically construct call-stacks and invoke procedures in a | |
14267 | relatively platform independent manner. Details about the library can | |
14268 | be found in the libffi distribution and are not repeated here.</P> | |
14269 | <P> To illustrate the use of libffi, suppose that you<EM> really</EM> | |
14270 | wanted to create a wrapper for <TT>execlp()</TT> that accepted<EM> any</EM> | |
14271 | number of arguments. To do this, you might make a few adjustments to | |
14272 | the previous example. For example:</P> | |
14273 | <DIV class="code"> | |
14274 | <PRE> | |
14275 | /* Take an arbitrary number of extra arguments and place into an array | |
14276 | of strings */ | |
14277 | ||
14278 | %typemap(in) (...) { | |
14279 | char **argv; | |
14280 | int argc; | |
14281 | int i; | |
14282 | ||
14283 | argc = PyTuple_Size(varargs); | |
14284 | argv = (char **) malloc(sizeof(char *)*(argc+1)); | |
14285 | for (i = 0; i < argc; i++) { | |
14286 | PyObject *o = PyTuple_GetItem(varargs,i); | |
14287 | if (!PyString_Check(o)) { | |
14288 | PyErr_SetString(PyExc_ValueError,"Expected a string"); | |
14289 | free(argv); | |
14290 | return NULL; | |
14291 | } | |
14292 | argv[i] = PyString_AsString(o); | |
14293 | } | |
14294 | argv[i] = NULL; | |
14295 | $1 = (void *) argv; | |
14296 | } | |
14297 | ||
14298 | /* Rewrite the function call, using libffi */ | |
14299 | ||
14300 | %feature("action") execlp { | |
14301 | int i, vc; | |
14302 | ffi_cif cif; | |
14303 | ffi_type **types; | |
14304 | void **values; | |
14305 | char **args; | |
14306 | ||
14307 | vc = PyTuple_Size(varargs); | |
14308 | types = (ffi_type **) malloc((vc+3)*sizeof(ffi_type *)); | |
14309 | values = (void **) malloc((vc+3)*sizeof(void *)); | |
14310 | args = (char **) arg3; | |
14311 | ||
14312 | /* Set up path parameter */ | |
14313 | types[0] = &ffi_type_pointer; | |
14314 | values[0] = &arg1; | |
14315 | ||
14316 | /* Set up first argument */ | |
14317 | types[1] = &ffi_type_pointer; | |
14318 | values[1] = &arg2; | |
14319 | ||
14320 | /* Set up rest of parameters */ | |
14321 | for (i = 0; i <= vc; i++) { | |
14322 | types[2+i] = &ffi_type_pointer; | |
14323 | values[2+i] = &args[i]; | |
14324 | } | |
14325 | if (ffi_prep_cif(&cif, FFI_DEFAULT_ABI, vc+3, | |
14326 | &ffi_type_uint, types) == FFI_OK) { | |
14327 | ffi_call(&cif, (void (*)()) execlp, &result, values); | |
14328 | } else { | |
14329 | PyErr_SetString(PyExc_RuntimeError, "Whoa!!!!!"); | |
14330 | free(types); | |
14331 | free(values); | |
14332 | free(arg3); | |
14333 | return NULL; | |
14334 | } | |
14335 | free(types); | |
14336 | free(values); | |
14337 | free(arg3); | |
14338 | } | |
14339 | ||
14340 | /* Declare the function. Whew! */ | |
14341 | int execlp(const char *path, const char *arg1, ...); | |
14342 | </PRE> | |
14343 | </DIV> | |
14344 | <P> Looking at this example, you may start to wonder if SWIG is making | |
14345 | life any easier. Given the amount of code involved, you might also | |
14346 | wonder why you didn't just write a hand-crafted wrapper! Either that or | |
14347 | you're wondering "why in the hell am I trying to wrap this varargs | |
14348 | function in the first place?!?" Obviously, those are questions you'll | |
14349 | have to answer for yourself.</P> | |
14350 | <P> As a more extreme example of libffi, here is some code that attempts | |
14351 | to wrap <TT>printf()</TT>,</P> | |
14352 | <DIV class="code"> | |
14353 | <PRE> | |
14354 | /* A wrapper for printf() using libffi */ | |
14355 | ||
14356 | %{ | |
14357 | /* Structure for holding passed arguments after conversion */ | |
14358 | typedef struct { | |
14359 | int type; | |
14360 | union { | |
14361 | int ivalue; | |
14362 | double dvalue; | |
14363 | void *pvalue; | |
14364 | } val; | |
14365 | } vtype; | |
14366 | enum { VT_INT, VT_DOUBLE, VT_POINTER }; | |
14367 | %} | |
14368 | ||
14369 | %typemap(in) (const char *fmt, ...) { | |
14370 | vtype *argv; | |
14371 | int argc; | |
14372 | int i; | |
14373 | ||
14374 | /* Format string */ | |
14375 | $1 = PyString_AsString($input); | |
14376 | ||
14377 | /* Variable length arguments */ | |
14378 | argc = PyTuple_Size(varargs); | |
14379 | argv = (vtype *) malloc(argc*sizeof(vtype)); | |
14380 | for (i = 0; i < argc; i++) { | |
14381 | PyObject *o = PyTuple_GetItem(varargs,i); | |
14382 | if (PyInt_Check(o)) { | |
14383 | argv[i].type = VT_INT; | |
14384 | argv[i].val.ivalue = PyInt_AsLong(o); | |
14385 | } else if (PyFloat_Check(o)) { | |
14386 | argv[i].type = VT_DOUBLE; | |
14387 | argv[i].val.dvalue = PyFloat_AsDouble(o); | |
14388 | } else if (PyString_Check(o)) { | |
14389 | argv[i].type = VT_POINTER; | |
14390 | argv[i].val.pvalue = (void *) PyString_AsString(o); | |
14391 | } else { | |
14392 | PyErr_SetString(PyExc_ValueError,"Unsupported argument type"); | |
14393 | free(argv); | |
14394 | return NULL; | |
14395 | } | |
14396 | } | |
14397 | $2 = (void *) argv; | |
14398 | } | |
14399 | ||
14400 | /* Rewrite the function call using libffi */ | |
14401 | %feature("action") printf { | |
14402 | int i, vc; | |
14403 | ffi_cif cif; | |
14404 | ffi_type **types; | |
14405 | void **values; | |
14406 | vtype *args; | |
14407 | ||
14408 | vc = PyTuple_Size(varargs); | |
14409 | types = (ffi_type **) malloc((vc+1)*sizeof(ffi_type *)); | |
14410 | values = (void **) malloc((vc+1)*sizeof(void *)); | |
14411 | args = (vtype *) arg2; | |
14412 | ||
14413 | /* Set up fmt parameter */ | |
14414 | types[0] = &ffi_type_pointer; | |
14415 | values[0] = &arg1; | |
14416 | ||
14417 | /* Set up rest of parameters */ | |
14418 | for (i = 0; i < vc; i++) { | |
14419 | switch(args[i].type) { | |
14420 | case VT_INT: | |
14421 | types[1+i] = &ffi_type_uint; | |
14422 | values[1+i] = &args[i].val.ivalue; | |
14423 | break; | |
14424 | case VT_DOUBLE: | |
14425 | types[1+i] = &ffi_type_double; | |
14426 | values[1+i] = &args[i].val.dvalue; | |
14427 | break; | |
14428 | case VT_POINTER: | |
14429 | types[1+i] = &ffi_type_pointer; | |
14430 | values[1+i] = &args[i].val.pvalue; | |
14431 | break; | |
14432 | default: | |
14433 | abort(); /* Whoa! We're seriously hosed */ | |
14434 | break; | |
14435 | } | |
14436 | } | |
14437 | if (ffi_prep_cif(&cif, FFI_DEFAULT_ABI, vc+1, | |
14438 | &ffi_type_uint, types) == FFI_OK) { | |
14439 | ffi_call(&cif, (void (*)()) printf, &result, values); | |
14440 | } else { | |
14441 | PyErr_SetString(PyExc_RuntimeError, "Whoa!!!!!"); | |
14442 | free(types); | |
14443 | free(values); | |
14444 | free(args); | |
14445 | return NULL; | |
14446 | } | |
14447 | free(types); | |
14448 | free(values); | |
14449 | free(args); | |
14450 | } | |
14451 | ||
14452 | /* The function */ | |
14453 | int printf(const char *fmt, ...); | |
14454 | </PRE> | |
14455 | </DIV> | |
14456 | <P> Much to your amazement, it even seems to work if you try it:</P> | |
14457 | <DIV class="targetlang"> | |
14458 | <PRE> | |
14459 | >>> import example | |
14460 | >>> example.printf("Grade: %s %d/60 = %0.2f%%\n", "Dave", 47, 47.0*100/60) | |
14461 | Grade: Dave 47/60 = 78.33% | |
14462 | >>> | |
14463 | </PRE> | |
14464 | </DIV> | |
14465 | <P> Of course, there are still some limitations to consider:</P> | |
14466 | <DIV class="targetlang"> | |
14467 | <PRE> | |
14468 | >>> example.printf("la de da de da %s", 42) | |
14469 | Segmentation fault (core dumped) | |
14470 | </PRE> | |
14471 | </DIV> | |
14472 | <P> And, on this note, we leave further exploration of libffi to the | |
14473 | reader as an exercise. Although Python has been used as an example, | |
14474 | most of the techniques in this section can be extrapolated to other | |
14475 | language modules with a bit of work. The only details you need to know | |
14476 | is how the extra arguments are accessed in each target language. For | |
14477 | example, in the Python module, we used the special <TT>varargs</TT> | |
14478 | variable to get these arguments. Modules such as Tcl8 and Perl5 simply | |
14479 | provide an argument number for the first extra argument. This can be | |
14480 | used to index into an array of passed arguments to get values. Please | |
14481 | consult the chapter on each language module for more details.</P> | |
14482 | <H2><A name="Varargs_nn8"></A>13.7 Wrapping of va_list</H2> | |
14483 | <P> Closely related to variable length argument wrapping, you may | |
14484 | encounter functions that accept a parameter of type <TT>va_list</TT>. | |
14485 | For example:</P> | |
14486 | <DIV class="code"> | |
14487 | <PRE> | |
14488 | int vfprintf(FILE *f, const char *fmt, va_list ap); | |
14489 | </PRE> | |
14490 | </DIV> | |
14491 | <P> As far as we know, there is no obvious way to wrap these functions | |
14492 | with SWIG. This is because there is no documented way to assemble the | |
14493 | proper va_list structure (there are no C library functions to do it and | |
14494 | the contents of va_list are opaque). Not only that, the contents of a <TT> | |
14495 | va_list</TT> structure are closely tied to the underlying call-stack. | |
14496 | It's not clear that exporting a <TT>va_list</TT> would have any use or | |
14497 | that it would work at all.</P> | |
14498 | <H2><A name="Varargs_nn9"></A>13.8 C++ Issues</H2> | |
14499 | <P> Wrapping of C++ member functions that accept a variable number of | |
14500 | arguments presents a number of challenges. By far, the easiest way to | |
14501 | handle this is to use the <TT>%varargs</TT> directive. This is portable | |
14502 | and it fully supports classes much like the <TT>%rename</TT> directive. | |
14503 | For example:</P> | |
14504 | <DIV class="code"> | |
14505 | <PRE> | |
14506 | %varargs (10, char * = NULL) Foo::bar; | |
14507 | ||
14508 | class Foo { | |
14509 | public: | |
14510 | virtual void bar(char *arg, ...); // gets varargs above | |
14511 | }; | |
14512 | ||
14513 | class Spam: public Foo { | |
14514 | public: | |
14515 | virtual void bar(char *arg, ...); // gets varargs above | |
14516 | }; | |
14517 | </PRE> | |
14518 | </DIV> | |
14519 | <P> <TT>%varargs</TT> also works with constructors, operators, and any | |
14520 | other C++ programming construct that accepts variable arguments.</P> | |
14521 | <P> Doing anything more advanced than this is likely to involve a | |
14522 | serious world of pain. In order to use a library like libffi, you will | |
14523 | need to know the underlying calling conventions and details of the C++ | |
14524 | ABI. For instance, the details of how <TT>this</TT> is passed to member | |
14525 | functions as well as any hidden arguments that might be used to pass | |
14526 | additional information. These details are implementation specific and | |
14527 | may differ between compilers and even different versions of the same | |
14528 | compiler. Also, be aware that invoking a member function is further | |
14529 | complicated if it is a virtual method. In this case, invocation might | |
14530 | require a table lookup to obtain the proper function address (although | |
14531 | you might be able to obtain an address by casting a bound pointer to a | |
14532 | pointer to function as described in the C++ ARM section 18.3.4).</P> | |
14533 | <P> If you do decide to change the underlying action code, be aware that | |
14534 | SWIG always places the <TT>this</TT> pointer in <TT>arg1</TT>. Other | |
14535 | arguments are placed in <TT>arg2</TT>, <TT>arg3</TT>, and so forth. For | |
14536 | example:</P> | |
14537 | <DIV class="code"> | |
14538 | <PRE> | |
14539 | %feature("action") Foo::bar { | |
14540 | ... | |
14541 | result = arg1->bar(arg2, arg3, etc.); | |
14542 | ... | |
14543 | } | |
14544 | </PRE> | |
14545 | </DIV> | |
14546 | <P> Given the potential to shoot yourself in the foot, it is probably | |
14547 | easier to reconsider your design or to provide an alternative interface | |
14548 | using a helper function than it is to create a fully general wrapper to | |
14549 | a varargs C++ member function.</P> | |
14550 | <H2><A name="Varargs_nn10"></A>13.9 Discussion</H2> | |
14551 | <P> This chapter has provided a number of techniques that can be used to | |
14552 | address the problem of variable length argument wrapping. If you care | |
14553 | about portability and ease of use, the <TT>%varargs</TT> directive is | |
14554 | probably the easiest way to tackle the problem. However, using | |
14555 | typemaps, it is possible to do some very advanced kinds of wrapping.</P> | |
14556 | <P> One point of discussion concerns the structure of the libffi | |
14557 | examples in the previous section. Looking at that code, it is not at | |
14558 | all clear that this is the easiest way to solve the problem. However, | |
14559 | there are a number of subtle aspects of the solution to | |
14560 | consider--mostly concerning the way in which the problem has been | |
14561 | decomposed. First, the example is structured in a way that tries to | |
14562 | maintain separation between wrapper-specific information and the | |
14563 | declaration of the function itself. The idea here is that you might | |
14564 | structure your interface like this:</P> | |
14565 | <DIV class="code"> | |
14566 | <PRE> | |
14567 | %typemap(const char *fmt, ...) { | |
14568 | ... | |
14569 | } | |
14570 | %feature("action") traceprintf { | |
14571 | ... | |
14572 | } | |
14573 | ||
14574 | /* Include some header file with traceprintf in it */ | |
14575 | %include "someheader.h" | |
14576 | </PRE> | |
14577 | </DIV> | |
14578 | <P> Second, careful scrutiny will reveal that the typemaps involving <TT> | |
14579 | (...)</TT> have nothing whatsoever to do with the libffi library. In | |
14580 | fact, they are generic with respect to the way in which the function is | |
14581 | actually called. This decoupling means that it will be much easier to | |
14582 | consider other library alternatives for making the function call. For | |
14583 | instance, if libffi wasn't supported on a certain platform, you might | |
14584 | be able to use something else instead. You could use conditional | |
14585 | compilation to control this:</P> | |
14586 | <DIV class="code"> | |
14587 | <PRE> | |
14588 | #ifdef USE_LIBFFI | |
14589 | %feature("action") printf { | |
14590 | ... | |
14591 | } | |
14592 | #endif | |
14593 | #ifdef USE_OTHERFFI | |
14594 | %feature("action") printf { | |
14595 | ... | |
14596 | } | |
14597 | #endif | |
14598 | </PRE> | |
14599 | </DIV> | |
14600 | <P> Finally, even though you might be inclined to just write a | |
14601 | hand-written wrapper for varargs functions, the techniques used in the | |
14602 | previous section have the advantage of being compatible with all other | |
14603 | features of SWIG such as exception handling.</P> | |
14604 | <P> As a final word, some C programmers seem to have the assumption that | |
14605 | the wrapping of variable length argument functions is an easily solved | |
14606 | problem. However, this section has hopefully dispelled some of these | |
14607 | myths. All things being equal, you are better off avoiding variable | |
14608 | length arguments if you can. If you can't avoid them, please consider | |
14609 | some of the simple solutions first. If you can't live with a simple | |
14610 | solution, proceed with caution. At the very least, make sure you | |
14611 | carefully read the section "A7.3.2 Function Calls" in Kernighan and | |
14612 | Ritchie and make sure you fully understand the parameter passing | |
14613 | conventions used for varargs. Also, be aware of the platform | |
14614 | dependencies and reliability issues that this will introduce. Good | |
14615 | luck.</P> | |
14616 | <HR NOSHADE> | |
14617 | <H1><A name="Warnings"></A>14 Warning Messages</H1> | |
14618 | ||
14619 | <!-- INDEX --> | |
14620 | <DIV class="sectiontoc"> | |
14621 | <UL> | |
14622 | <LI><A href="#Warnings_nn2">Introduction</A></LI> | |
14623 | <LI><A href="#Warnings_nn3">Warning message suppression</A></LI> | |
14624 | <LI><A href="#Warnings_nn4">Enabling additional warnings</A></LI> | |
14625 | <LI><A href="#Warnings_nn5">Issuing a warning message</A></LI> | |
14626 | <LI><A href="#Warnings_nn6">Commentary</A></LI> | |
14627 | <LI><A href="#Warnings_nn7">Warnings as errors</A></LI> | |
14628 | <LI><A href="#Warnings_nn8">Message output format</A></LI> | |
14629 | <LI><A href="#Warnings_nn9">Warning number reference</A> | |
14630 | <UL> | |
14631 | <LI><A href="#Warnings_nn10">Deprecated features (100-199)</A></LI> | |
14632 | <LI><A href="#Warnings_nn11">Preprocessor (200-299)</A></LI> | |
14633 | <LI><A href="#Warnings_nn12">C/C++ Parser (300-399)</A></LI> | |
14634 | <LI><A href="#Warnings_nn13">Types and typemaps (400-499)</A></LI> | |
14635 | <LI><A href="#Warnings_nn14">Code generation (500-599)</A></LI> | |
14636 | <LI><A href="#Warnings_nn15">Language module specific (800-899)</A></LI> | |
14637 | <LI><A href="#Warnings_nn16">User defined (900-999)</A></LI> | |
14638 | </UL> | |
14639 | </LI> | |
14640 | <LI><A href="#Warnings_nn17">History</A></LI> | |
14641 | </UL> | |
14642 | </DIV> | |
14643 | <!-- INDEX --> | |
14644 | <H2><A name="Warnings_nn2"></A>14.1 Introduction</H2> | |
14645 | <P> During compilation, SWIG may generate a variety of warning messages. | |
14646 | For example:</P> | |
14647 | <DIV class="shell"> | |
14648 | <PRE> | |
14649 | example.i:16: Warning(501): Overloaded declaration ignored. bar(double) | |
14650 | example.i:15: Warning(501): Previous declaration is bar(int) | |
14651 | </PRE> | |
14652 | </DIV> | |
14653 | <P> Typically, warning messages indicate non-fatal problems with the | |
14654 | input where the generated wrapper code will probably compile, but it | |
14655 | may not work like you expect.</P> | |
14656 | <H2><A name="Warnings_nn3"></A>14.2 Warning message suppression</H2> | |
14657 | <P> All warning messages have a numeric code that is shown in the | |
14658 | warning message itself. To suppress the printing of a warning message, | |
14659 | a number of techniques can be used. First, you can run SWIG with the <TT> | |
14660 | -w</TT> command line option. For example:</P> | |
14661 | <DIV class="shell"> | |
14662 | <PRE> | |
14663 | % swig -python -w501 example.i | |
14664 | % swig -python -w501,505,401 example.i | |
14665 | </PRE> | |
14666 | </DIV> | |
14667 | <P> Alternatively, warnings can be suppressed by inserting a special | |
14668 | preprocessor pragma into the input file:</P> | |
14669 | <DIV class="code"> | |
14670 | <PRE> | |
14671 | %module example | |
14672 | #pragma SWIG nowarn=501 | |
14673 | #pragma SWIG nowarn=501,505,401 | |
14674 | </PRE> | |
14675 | </DIV> | |
14676 | <P> Finally, code-generation warnings can be disabled on a declaration | |
14677 | by declaration basis using the <TT>%warnfilter</TT> directive. For | |
14678 | example:</P> | |
14679 | <DIV class="code"> | |
14680 | <PRE> | |
14681 | %module example | |
14682 | %warnfilter(501) foo; | |
14683 | ... | |
14684 | int foo(int); | |
14685 | int foo(double); // Silently ignored. | |
14686 | </PRE> | |
14687 | </DIV> | |
14688 | <P> The <TT>%warnfilter</TT> directive has the same semantics as other | |
14689 | declaration modifiers like <TT>%rename</TT>, <TT>%ignore</TT>, and <TT> | |
14690 | %feature</TT>. For example, if you wanted to suppress a warning for a | |
14691 | method in a class hierarchy, you could do this:</P> | |
14692 | <DIV class="code"> | |
14693 | <PRE> | |
14694 | %warnfilter(501) Object::foo; | |
14695 | class Object { | |
14696 | public: | |
14697 | int foo(int); | |
14698 | int foo(double); // Silently ignored | |
14699 | ... | |
14700 | }; | |
14701 | ||
14702 | class Derived : public Object { | |
14703 | public: | |
14704 | int foo(int); | |
14705 | int foo(double); // Silently ignored | |
14706 | ... | |
14707 | }; | |
14708 | </PRE> | |
14709 | </DIV> | |
14710 | <P> Warnings can be suppressed for an entire class by supplying a class | |
14711 | name. For example:</P> | |
14712 | <DIV class="code"> | |
14713 | <PRE> | |
14714 | %warnfilter(501) Object; | |
14715 | ||
14716 | class Object { | |
14717 | public: | |
14718 | ... // All 501 warnings ignored in class | |
14719 | }; | |
14720 | </PRE> | |
14721 | </DIV> | |
14722 | <P> There is no option to suppress all SWIG warning messages. The | |
14723 | warning messages are there for a reason---to tell you that something | |
14724 | may be<EM> broken</EM> in your interface. Ignore the warning messages | |
14725 | at your own peril.</P> | |
14726 | <H2><A name="Warnings_nn4"></A>14.3 Enabling additional warnings</H2> | |
14727 | <P> Some warning messages are disabled by default and are generated only | |
14728 | to provide additional diagnostics. All warning messages can be enabled | |
14729 | using the <TT>-Wall</TT> option. For example:</P> | |
14730 | <DIV class="shell"> | |
14731 | <PRE> | |
14732 | % swig -Wall -python example.i | |
14733 | </PRE> | |
14734 | </DIV> | |
14735 | <P> When <TT>-Wall</TT> is used, all other warning filters are disabled.</P> | |
14736 | <P> To selectively turn on extra warning messages, you can use the | |
14737 | directives and options in the previous section--simply add a "+" to all | |
14738 | warning numbers. For example:</P> | |
14739 | <DIV class="shell"> | |
14740 | <PRE> | |
14741 | % swig -w+309,+452 example.i | |
14742 | </PRE> | |
14743 | </DIV> | |
14744 | <P> or</P> | |
14745 | <DIV class="code"> | |
14746 | <PRE> | |
14747 | #pragma SWIG nowarn=+309,+452 | |
14748 | </PRE> | |
14749 | </DIV> | |
14750 | <P> or</P> | |
14751 | <DIV class="code"> | |
14752 | <PRE> | |
14753 | %warnfilter(+309,+452) foo; | |
14754 | </PRE> | |
14755 | </DIV> | |
14756 | <P> Note: selective enabling of warnings with <TT>%warnfilter</TT> | |
14757 | overrides any global settings you might have made using <TT>-w</TT> or <TT> | |
14758 | #pragma</TT>.</P> | |
14759 | <H2><A name="Warnings_nn5"></A>14.4 Issuing a warning message</H2> | |
14760 | <P> Warning messages can be issued from an interface file using a number | |
14761 | of directives. The <TT>%warn</TT> directive is the most simple:</P> | |
14762 | <DIV class="code"> | |
14763 | <PRE> | |
14764 | %warn "750:This is your last warning!" | |
14765 | </PRE> | |
14766 | </DIV> | |
14767 | <P> All warning messages are optionally prefixed by the warning number | |
14768 | to use. If you are generating your own warnings, make sure you don't | |
14769 | use numbers defined in the table at the end of this section.</P> | |
14770 | <P> The <TT>%ignorewarn</TT> directive is the same as <TT>%ignore</TT> | |
14771 | except that it issues a warning message whenever a matching declaration | |
14772 | is found. For example:</P> | |
14773 | <DIV class="code"> | |
14774 | <PRE> | |
14775 | %ignorewarn("362:operator= ignored") operator=; | |
14776 | </PRE> | |
14777 | </DIV> | |
14778 | <P> Warning messages can be associated with typemaps using the <TT> | |
14779 | warning</TT> attribute of a typemap declaration. For example:</P> | |
14780 | <DIV class="code"> | |
14781 | <PRE> | |
14782 | %typemap(in, warning="751:You are really going to regret this") blah * { | |
14783 | ... | |
14784 | } | |
14785 | </PRE> | |
14786 | </DIV> | |
14787 | <P> In this case, the warning message will be printed whenever the | |
14788 | typemap is actually used.</P> | |
14789 | <H2><A name="Warnings_nn6"></A>14.5 Commentary</H2> | |
14790 | <P> The ability to suppress warning messages is really only provided for | |
14791 | advanced users and is not recommended in normal use. There are no plans | |
14792 | to provide symbolic names or options that identify specific types or | |
14793 | groups of warning messages---the numbers must be used explicitly.</P> | |
14794 | <P> Certain types of SWIG problems are errors. These usually arise due | |
14795 | to parsing errors (bad syntax) or semantic problems for which there is | |
14796 | no obvious recovery. There is no mechanism for suppressing error | |
14797 | messages.</P> | |
14798 | <H2><A name="Warnings_nn7"></A>14.6 Warnings as errors</H2> | |
14799 | <P> Warnings can be handled as errors by using the <TT>-Werror</TT> | |
14800 | command line option. This will cause SWIG to exit with a non successful | |
14801 | exit code if a warning is encountered.</P> | |
14802 | <H2><A name="Warnings_nn8"></A>14.7 Message output format</H2> | |
14803 | <P> The output format for both warnings and errors can be selected for | |
14804 | integration with your favourite IDE/editor. Editors and IDEs can | |
14805 | usually parse error messages and if in the appropriate format will | |
14806 | easily take you directly to the source of the error. The standard | |
14807 | format is used by default except on Windows where the Microsoft format | |
14808 | is used by default. These can be overridden using command line options, | |
14809 | for example:</P> | |
14810 | <DIV class="shell"> | |
14811 | <PRE> | |
14812 | $ swig -python -Fstandard example.i | |
14813 | example.i:4: Syntax error in input. | |
14814 | $ swig -python -Fmicrosoft example.i | |
14815 | example.i(4): Syntax error in input. | |
14816 | </PRE> | |
14817 | </DIV> | |
14818 | <H2><A name="Warnings_nn9"></A>14.8 Warning number reference</H2> | |
14819 | <H3><A name="Warnings_nn10"></A>14.8.1 Deprecated features (100-199)</H3> | |
14820 | <UL> | |
14821 | <LI>101. Deprecated <TT>%extern</TT> directive.</LI> | |
14822 | <LI>102. Deprecated <TT>%val</TT> directive.</LI> | |
14823 | <LI>103. Deprecated <TT>%out</TT> directive.</LI> | |
14824 | <LI>104. Deprecated <TT>%disabledoc</TT> directive.</LI> | |
14825 | <LI>105. Deprecated <TT>%enabledoc</TT> directive.</LI> | |
14826 | <LI>106. Deprecated <TT>%doconly</TT> directive.</LI> | |
14827 | <LI>107. Deprecated <TT>%style</TT> directive.</LI> | |
14828 | <LI>108. Deprecated <TT>%localstyle</TT> directive.</LI> | |
14829 | <LI>109. Deprecated <TT>%title</TT> directive.</LI> | |
14830 | <LI>110. Deprecated <TT>%section</TT> directive.</LI> | |
14831 | <LI>111. Deprecated <TT>%subsection</TT> directive.</LI> | |
14832 | <LI>112. Deprecated <TT>%subsubsection</TT> directive.</LI> | |
14833 | <LI>113. Deprecated <TT>%addmethods</TT> directive.</LI> | |
14834 | <LI>114. Deprecated <TT>%readonly</TT> directive.</LI> | |
14835 | <LI>115. Deprecated <TT>%readwrite</TT> directive.</LI> | |
14836 | <LI>116. Deprecated <TT>%except</TT> directive.</LI> | |
14837 | <LI>117. Deprecated <TT>%new</TT> directive.</LI> | |
14838 | <LI>118. Deprecated <TT>%typemap(except)</TT>.</LI> | |
14839 | <LI>119. Deprecated <TT>%typemap(ignore)</TT>.</LI> | |
14840 | <LI>120. Deprecated command line option (-c).</LI> | |
14841 | <LI>121. Deprecated <TT>%name</TT> directive.</LI> | |
14842 | </UL> | |
14843 | <H3><A name="Warnings_nn11"></A>14.8.2 Preprocessor (200-299)</H3> | |
14844 | <UL> | |
14845 | <LI>201. Unable to find 'filename'.</LI> | |
14846 | <LI>202. Could not evaluate 'expr'.</LI> | |
14847 | </UL> | |
14848 | <H3><A name="Warnings_nn12"></A>14.8.3 C/C++ Parser (300-399)</H3> | |
14849 | <UL> | |
14850 | <LI>301. <TT>class</TT> keyword used, but not in C++ mode.</LI> | |
14851 | <LI>302. Identifier '<EM>name</EM>' redefined (ignored).</LI> | |
14852 | <LI>303. <TT>%extend</TT> defined for an undeclared class '<EM>name</EM> | |
14853 | '.</LI> | |
14854 | <LI>304. Unsupported constant value (ignored).</LI> | |
14855 | <LI>305. Bad constant value (ignored).</LI> | |
14856 | <LI>306. '<EM>identifier</EM>' is private in this context.</LI> | |
14857 | <LI>307. Can't set default argument value (ignored)</LI> | |
14858 | <LI>308. Namespace alias '<EM>name</EM>' not allowed here. Assuming '<EM> | |
14859 | name</EM>'</LI> | |
14860 | <LI>309. [private | protected] inheritance ignored.</LI> | |
14861 | <LI>310. Template '<EM>name</EM>' was already wrapped as '<EM>name</EM>' | |
14862 | (ignored)</LI> | |
14863 | <LI>311. Template partial specialization not supported.</LI> | |
14864 | <LI>312. Nested classes not currently supported (ignored).</LI> | |
14865 | <LI>313. Unrecognized extern type "<EM>name</EM>" (ignored).</LI> | |
14866 | <LI>314. '<EM>identifier</EM>' is a<EM> lang</EM> keyword.</LI> | |
14867 | <LI>315. Nothing known about '<EM>identifier</EM>'.</LI> | |
14868 | <LI>316. Repeated %module directive.</LI> | |
14869 | <LI>317. Specialization of non-template '<EM>name</EM>'.</LI> | |
14870 | <LI>318. Instantiation of template<EM> name</EM> is ambiguous. Using<EM> | |
14871 | templ</EM> at<EM> file</EM>:<EM>line</EM></LI> | |
14872 | <LI>319. No access specifier given for base class<EM> name</EM> | |
14873 | (ignored).</LI> | |
14874 | <LI>320. Explicit template instantiation ignored.</LI> | |
14875 | <LI>321.<EM> identifier</EM> conflicts with a built-in name.</LI> | |
14876 | <LI>322. Redundant redeclaration of '<EM>name</EM>'.</LI> | |
14877 | <LI>350. operator new ignored.</LI> | |
14878 | <LI>351. operator delete ignored.</LI> | |
14879 | <LI>352. operator+ ignored.</LI> | |
14880 | <LI>353. operator- ignored.</LI> | |
14881 | <LI>354. operator* ignored.</LI> | |
14882 | <LI>355. operator/ ignored.</LI> | |
14883 | <LI>356. operator% ignored.</LI> | |
14884 | <LI>357. operator^ ignored.</LI> | |
14885 | <LI>358. operator& ignored.</LI> | |
14886 | <LI>359. operator| ignored.</LI> | |
14887 | <LI>360. operator~ ignored.</LI> | |
14888 | <LI>361. operator! ignored.</LI> | |
14889 | <LI>362. operator= ignored.</LI> | |
14890 | <LI>363. operator< ignored.</LI> | |
14891 | <LI>364. operator> ignored.</LI> | |
14892 | <LI>365. operator+= ignored.</LI> | |
14893 | <LI>366. operator-= ignored.</LI> | |
14894 | <LI>367. operator*= ignored.</LI> | |
14895 | <LI>368. operator/= ignored.</LI> | |
14896 | <LI>369. operator%= ignored.</LI> | |
14897 | <LI>370. operator^= ignored.</LI> | |
14898 | <LI>371. operator&= ignored.</LI> | |
14899 | <LI>372. operator|= ignored.</LI> | |
14900 | <LI>373. operator<< ignored.</LI> | |
14901 | <LI>374. operator>>ignored.</LI> | |
14902 | <LI>375. operator<<= ignored.</LI> | |
14903 | <LI>376. operator>>= ignored.</LI> | |
14904 | <LI>377. operator== ignored.</LI> | |
14905 | <LI>378. operator!= ignored.</LI> | |
14906 | <LI>379. operator<= ignored.</LI> | |
14907 | <LI>380. operator>= ignored.</LI> | |
14908 | <LI>381. operator&& ignored.</LI> | |
14909 | <LI>382. operator|| ignored.</LI> | |
14910 | <LI>383. operator++ ignored.</LI> | |
14911 | <LI>384. operator-- ignored.</LI> | |
14912 | <LI>385. operator, ignored.</LI> | |
14913 | <LI>386. operator-<* ignored.</LI> | |
14914 | <LI>387. operator-< ignored.</LI> | |
14915 | <LI>388. operator() ignored.</LI> | |
14916 | <LI>389. operator[] ignored.</LI> | |
14917 | <LI>390. operator+ ignored (unary).</LI> | |
14918 | <LI>391. operator- ignored (unary).</LI> | |
14919 | <LI>392. operator* ignored (unary).</LI> | |
14920 | <LI>393. operator& ignored (unary).</LI> | |
14921 | <LI>394. operator new[] ignored.</LI> | |
14922 | <LI>395. operator delete[] ignored.</LI> | |
14923 | </UL> | |
14924 | <H3><A name="Warnings_nn13"></A>14.8.4 Types and typemaps (400-499)</H3> | |
14925 | <UL> | |
14926 | <LI>401. Nothing known about class 'name'. Ignored.</LI> | |
14927 | <LI>402. Base class 'name' is incomplete.</LI> | |
14928 | <LI>403. Class 'name' might be abstract.</LI> | |
14929 | <LI>450. Deprecated typemap feature ($source/$target).</LI> | |
14930 | <LI>451. Setting const char * variable may leak memory.</LI> | |
14931 | <LI>452. Reserved</LI> | |
14932 | <LI>453. Can't apply (pattern). No typemaps are defined.</LI> | |
14933 | <LI>460. Unable to use type<EM> type</EM> as a function argument.</LI> | |
14934 | <LI>461. Unable to use return type<EM> type</EM> in function<EM> name</EM> | |
14935 | .</LI> | |
14936 | <LI>462. Unable to set variable of type<EM> type</EM>.</LI> | |
14937 | <LI>463. Unable to read variable of type<EM> type</EM>.</LI> | |
14938 | <LI>464. Unsupported constant value.</LI> | |
14939 | <LI>465. Unable to handle type<EM> type</EM>.</LI> | |
14940 | <LI>466. Unsupported variable type<EM> type</EM>.</LI> | |
14941 | <LI>467. Overloaded<EM> declaration</EM> not supported (no type checking | |
14942 | rule for '<EM>type</EM>')</LI> | |
14943 | <LI>468. No 'throw' typemap defined for exception type<EM> type</EM></LI> | |
14944 | <LI>469. No or improper directorin typemap defined for<EM> type</EM></LI> | |
14945 | <LI>470. Thread/reentrant unsafe wrapping, consider returning by value | |
14946 | instead.</LI> | |
14947 | <LI>471. Unable to use return type<EM> type</EM> in director method</LI> | |
14948 | </UL> | |
14949 | <H3><A name="Warnings_nn14"></A>14.8.5 Code generation (500-599)</H3> | |
14950 | <UL> | |
14951 | <LI>501. Overloaded declaration ignored.<EM> decl</EM></LI> | |
14952 | <LI>502. Overloaded constructor ignored.<EM> decl</EM></LI> | |
14953 | <LI>503. Can't wrap '<EM>identifier</EM>' unless renamed to a valid | |
14954 | identifier.</LI> | |
14955 | <LI>504. Function<EM> name</EM> must have a return type.</LI> | |
14956 | <LI>505. Variable length arguments discarded.</LI> | |
14957 | <LI>506. Can't wrap varargs with keyword arguments enabled.</LI> | |
14958 | <LI>507. Adding native function<EM> name</EM> not supported (ignored).</LI> | |
14959 | <LI>508. Declaration of '<EM>name</EM>' shadows declaration accessible | |
14960 | via operator->() at<EM> file:line</EM>.</LI> | |
14961 | <LI>509. Overloaded<EM> declaration</EM> is shadowed by<EM> declaration</EM> | |
14962 | at<EM> file</EM>:<EM>line</EM>.</LI> | |
14963 | <LI>510. Friend function '<EM>name</EM>' ignored.</LI> | |
14964 | <LI>511. Can't use keyword arguments with overloaded functions.</LI> | |
14965 | <LI>512. Overloaded<EM> declaration</EM> const ignored. Non-const method | |
14966 | at<EM> file</EM>:<EM>line</EM> used.</LI> | |
14967 | <LI>513. Can't generate wrappers for unnamed struct/class.</LI> | |
14968 | <LI>514.</LI> | |
14969 | <LI>515.</LI> | |
14970 | <LI>516. Overloaded method<EM> declaration</EM> ignored. Method<EM> | |
14971 | declaration</EM> at<EM> file</EM>:<EM>line</EM> used.</LI> | |
14972 | </UL> | |
14973 | <H3><A name="Warnings_nn15"></A>14.8.6 Language module specific | |
14974 | (800-899)</H3> | |
14975 | <UL> | |
14976 | <LI>801. Wrong name (corrected to '<EM>name</EM>'). (Ruby).</LI> | |
14977 | </UL> | |
14978 | <UL> | |
14979 | <LI>810. No jni typemap defined for<EM> type</EM> (Java).</LI> | |
14980 | <LI>811. No jtype typemap defined for<EM> type</EM> (Java).</LI> | |
14981 | <LI>812. No jstype typemap defined for<EM> type</EM> (Java).</LI> | |
14982 | <LI>813. Warning for<EM> classname</EM>: Base<EM> baseclass</EM> | |
14983 | ignored. Multiple inheritance is not supported in Java. (Java).</LI> | |
14984 | <LI>814.</LI> | |
14985 | <LI>815. No javafinalize typemap defined for<EM> type</EM> (Java).</LI> | |
14986 | <LI>816. No javabody typemap defined for<EM> type</EM> (Java).</LI> | |
14987 | <LI>817. No javaout typemap defined for<EM> type</EM> (Java).</LI> | |
14988 | <LI>818. No javain typemap defined for<EM> type</EM> (Java).</LI> | |
14989 | <LI>819. No javadirectorin typemap defined for<EM> type</EM> (Java).</LI> | |
14990 | <LI>820. No javadirectorout typemap defined for<EM> type</EM> (Java).</LI> | |
14991 | <LI>821.</LI> | |
14992 | <LI>822. Covariant return types not supported in Java. Proxy method will | |
14993 | return<EM> basetype</EM> (Java).</LI> | |
14994 | <LI>823. No javaconstruct typemap defined for<EM> type</EM> (Java).</LI> | |
14995 | <LI>824. Missing JNI descriptor in directorin typemap defined for<EM> | |
14996 | type</EM> (Java).</LI> | |
14997 | </UL> | |
14998 | <UL> | |
14999 | <LI>830. No ctype typemap defined for<EM> type</EM> (C#).</LI> | |
15000 | <LI>831. No cstype typemap defined for<EM> type</EM> (C#).</LI> | |
15001 | <LI>832. No cswtype typemap defined for<EM> type</EM> (C#).</LI> | |
15002 | <LI>833. Warning for<EM> classname</EM>: Base<EM> baseclass</EM> | |
15003 | ignored. Multiple inheritance is not supported in C#. (C#).</LI> | |
15004 | <LI>834.</LI> | |
15005 | <LI>835. No csfinalize typemap defined for<EM> type</EM> (C#).</LI> | |
15006 | <LI>836. No csbody typemap defined for<EM> type</EM> (C#).</LI> | |
15007 | <LI>837. No csout typemap defined for<EM> type</EM> (C#).</LI> | |
15008 | <LI>838. No csin typemap defined for<EM> type</EM> (C#).</LI> | |
15009 | <LI>839.</LI> | |
15010 | <LI>840.</LI> | |
15011 | <LI>841.</LI> | |
15012 | <LI>842. Covariant return types not supported in C#. Proxy method will | |
15013 | return<EM> basetype</EM> (C#).</LI> | |
15014 | <LI>843. No csconstruct typemap defined for<EM> type</EM> (C#).</LI> | |
15015 | <LI>844. C# exception may not be thrown - no $excode or excode attribute | |
15016 | in<EM> typemap</EM> typemap. (C#).</LI> | |
15017 | <LI>845. Unmanaged code contains a call to a | |
15018 | SWIG_CSharpSetPendingException method and C# code does not handle | |
15019 | pending exceptions via the canthrow attribute. (C#).</LI> | |
15020 | </UL> | |
15021 | <UL> | |
15022 | <LI>870. Warning for<EM> classname</EM>: Base<EM> baseclass</EM> | |
15023 | ignored. Multiple inheritance is not supported in Php4. (Php4).</LI> | |
15024 | </UL> | |
15025 | <H3><A name="Warnings_nn16"></A>14.8.7 User defined (900-999)</H3> | |
15026 | <P> These numbers can be used by your own application.</P> | |
15027 | <H2><A name="Warnings_nn17"></A>14.9 History</H2> | |
15028 | <P> The ability to control warning messages was first added to | |
15029 | SWIG-1.3.12.</P> | |
15030 | <HR NOSHADE> | |
15031 | <H1><A name="Modules"></A>15 Working with Modules</H1> | |
15032 | ||
15033 | <!-- INDEX --> | |
15034 | <DIV class="sectiontoc"> | |
15035 | <UL> | |
15036 | <LI><A href="#Modules_nn2">The SWIG runtime code</A></LI> | |
15037 | <LI><A href="#external_run_time">External access to the runtime</A></LI> | |
15038 | <LI><A href="#Modules_nn4">A word of caution about static libraries</A></LI> | |
15039 | <LI><A href="#Modules_nn5">References</A></LI> | |
15040 | <LI><A href="#Modules_nn6">Reducing the wrapper file size</A></LI> | |
15041 | </UL> | |
15042 | </DIV> | |
15043 | <!-- INDEX --> | |
15044 | <P> When first working with SWIG, users commonly start by creating a | |
15045 | single module. That is, you might define a single SWIG interface that | |
15046 | wraps some set of C/C++ code. You then compile all of the generated | |
15047 | wrapper code into a module and use it. For large applications, however, | |
15048 | this approach is problematic---the size of the generated wrapper code | |
15049 | can be rather large. Moreover, it is probably easier to manage the | |
15050 | target language interface when it is broken up into smaller pieces.</P> | |
15051 | <P> This chapter describes the problem of using SWIG in programs where | |
15052 | you want to create a collection of modules.</P> | |
15053 | <H2><A name="Modules_nn2"></A>15.1 The SWIG runtime code</H2> | |
15054 | <P> Many of SWIG's target languages generate a set of functions commonly | |
15055 | known as the "SWIG runtime." These functions are primarily related to | |
15056 | the runtime type system which checks pointer types and performs other | |
15057 | tasks such as proper casting of pointer values in C++. As a general | |
15058 | rule, the statically typed target languages, such as Java, use the | |
15059 | language's built in static type checking and have no need for a SWIG | |
15060 | runtime. All the dynamically typed / interpreted languages rely on the | |
15061 | SWIG runtime.</P> | |
15062 | <P> The runtime functions are private to each SWIG-generated module. | |
15063 | That is, the runtime functions are declared with "static" linkage and | |
15064 | are visible only to the wrapper functions defined in that module. The | |
15065 | only problem with this approach is that when more than one SWIG module | |
15066 | is used in the same application, those modules often need to share type | |
15067 | information. This is especially true for C++ programs where SWIG must | |
15068 | collect and share information about inheritance relationships that | |
15069 | cross module boundaries.</P> | |
15070 | <P> To solve the problem of sharing information across modules, a | |
15071 | pointer to the type information is stored in a global variable in the | |
15072 | target language namespace. During module initialization, type | |
15073 | information is loaded into the global data structure of type | |
15074 | information from all modules.</P> | |
15075 | <P> This can present a problem with threads. If two modules try and load | |
15076 | at the same time, the type information can become corrupt. SWIG | |
15077 | currently does not provide any locking, and if you use threads, you | |
15078 | must make sure that modules are loaded serially. Be careful if you use | |
15079 | threads and the automatic module loading that some scripting languages | |
15080 | provide. One solution is to load all modules before spawning any | |
15081 | threads.</P> | |
15082 | <H2><A name="external_run_time"></A>15.2 External access to the runtime</H2> | |
15083 | <P>As described in <A href="#runtime_type_checker">The run-time type | |
15084 | checker</A>, the functions <TT>SWIG_TypeQuery</TT>, <TT> | |
15085 | SWIG_NewPointerObj</TT>, and others sometimes need to be called. Calling | |
15086 | these functions from a typemap is supported, since the typemap code is | |
15087 | embedded into the <TT>_wrap.c</TT> file, which has those declerations | |
15088 | available. If you need to call the SWIG run-time functions from another | |
15089 | C file, there is one header you need to include. To generate the header | |
15090 | that needs to be included, run the following command:<DIV class="code"> | |
15091 | <PRE> | |
15092 | $ swig -python -external-runtime <filename> | |
15093 | </PRE> | |
15094 | </DIV></P> | |
15095 | <P>The filename argument is optional and if it is not passed, then the | |
15096 | default filename will be something like <TT>swigpyrun.h</TT>, depending | |
15097 | on the language. This header file should be treated like any of the | |
15098 | other _wrap.c output files, and should be regenerated when the _wrap | |
15099 | files are. After including this header, your code will be able to call <TT> | |
15100 | SWIG_TypeQuery</TT>, <TT>SWIG_NewPointerObj</TT>, <TT>SWIG_ConvertPtr</TT> | |
15101 | and others. The exact argument paramaters for these functions might | |
15102 | differ between language modules; please check the language module | |
15103 | chapters for more information.</P> | |
15104 | <P>Inside this header the functions are declared static and are included | |
15105 | inline into the file, and thus the file does not need to be linked | |
15106 | against any SWIG libraries or code (you might still need to link | |
15107 | against the language libraries like libpython-2.3). Data is shared | |
15108 | between this file and the _wrap.c files through a global variable in | |
15109 | the scripting language. It is also possible to copy this header file | |
15110 | along with the generated wrapper files into your own package, so that | |
15111 | you can distribute a package that can be compiled without SWIG | |
15112 | installed (this works because the header file is self contained, and | |
15113 | does not need to link with anything).</P> | |
15114 | <H2><A name="Modules_nn4"></A>15.3 A word of caution about static | |
15115 | libraries</H2> | |
15116 | <P> When working with multiple SWIG modules, you should take care not to | |
15117 | use static libraries. For example, if you have a static library <TT> | |
15118 | libfoo.a</TT> and you link a collection of SWIG modules with that | |
15119 | library, each module will get its own private copy of the library code | |
15120 | inserted into it. This is very often<B> NOT</B> what you want and it | |
15121 | can lead to unexpected or bizarre program behavior. When working with | |
15122 | dynamically loadable modules, you should try to work exclusively with | |
15123 | shared libaries.</P> | |
15124 | <H2><A name="Modules_nn5"></A>15.4 References</H2> | |
15125 | <P> Due to the complexity of working with shared libraries and multiple | |
15126 | modules, it might be a good idea to consult an outside reference. John | |
15127 | Levine's "Linkers and Loaders" is highly recommended.</P> | |
15128 | <H2><A name="Modules_nn6"></A>15.5 Reducing the wrapper file size</H2> | |
15129 | <P> Using multiple modules with the <TT>%import</TT> directive is the | |
15130 | most common approach to modularising large projects. In this way a | |
15131 | number of different wrapper files can be generated, thereby avoiding | |
15132 | the generation of a single large wrapper file. There are a couple of | |
15133 | alternative solutions for reducing the size of a wrapper file through | |
15134 | the use of command line options and features.</P> | |
15135 | <P><B> -fcompact</B> | |
15136 | <BR> This command line option will compact the size of the wrapper file | |
15137 | without changing the code generated into the wrapper file. It simply | |
15138 | removes blank lines and joins lines of code together. This is useful | |
15139 | for compilers that have a maximum file size that can be handled.</P> | |
15140 | <P><B> -fvirtual</B> | |
15141 | <BR> This command line option will remove the generation of superfluous | |
15142 | virtual method wrappers. Consider the following inheritance hierarchy:</P> | |
15143 | <DIV class="code"> | |
15144 | <PRE> | |
15145 | struct Base { | |
15146 | virtual void method(); | |
15147 | ... | |
15148 | }; | |
15149 | ||
15150 | struct Derived : Base { | |
15151 | virtual void method(); | |
15152 | ... | |
15153 | }; | |
15154 | </PRE> | |
15155 | </DIV> | |
15156 | <P> Normally wrappers are generated for both methods, whereas this | |
15157 | command line option will suppress the generation of a wrapper for <TT> | |
15158 | Derived::method</TT>. Normal polymorphic behaviour remains as <TT> | |
15159 | Derived::method</TT> will still be called should you have a <TT>Derived</TT> | |
15160 | instance and call the wrapper for <TT>Base::method</TT>.</P> | |
15161 | <P><B> %feature("compactdefaultargs")</B> | |
15162 | <BR> This feature can reduce the number of wrapper methods when wrapping | |
15163 | methods with default arguments. The section on <A href="#SWIGPlus_default_args"> | |
15164 | default arguments</A> discusses the feature and it's limitations.</P> | |
15165 | <HR NOSHADE> | |
15166 | <H1><A name="CSharp"></A>16 SWIG and C#</H1> | |
15167 | ||
15168 | <!-- INDEX --> | |
15169 | <DIV class="sectiontoc"> | |
15170 | <UL> | |
15171 | <LI><A href="#csharp_introduction">Introduction</A></LI> | |
15172 | <LI><A href="#csharp_differences_java">Differences to the Java module</A> | |
15173 | </LI> | |
15174 | <LI><A href="#csharp_exceptions">C# Exceptions</A> | |
15175 | <UL> | |
15176 | <LI><A href="#csharp_exception_example_check_typemap">C# exception | |
15177 | example using "check" typemap</A></LI> | |
15178 | <LI><A href="#csharp_exception_example_percent_exception">C# exception | |
15179 | example using %exception</A></LI> | |
15180 | <LI><A href="#csharp_exception_example_exception_specifications">C# | |
15181 | exception example using exception specifications</A></LI> | |
15182 | <LI><A href="#csharp_custom_application_exception">Custom C# | |
15183 | ApplicationException example</A></LI> | |
15184 | </UL> | |
15185 | </LI> | |
15186 | </UL> | |
15187 | </DIV> | |
15188 | <!-- INDEX --> | |
15189 | <H2><A name="csharp_introduction"></A>16.1 Introduction</H2> | |
15190 | <P> The purpose of the C# module is to offer an automated way of | |
15191 | accessing existing C/C++ code from .NET languages. The wrapper code | |
15192 | implementation uses C# and the Platform Invoke (PInvoke) interface to | |
15193 | access natively compiled C/C++ code. The PInvoke interface has been | |
15194 | chosen over Microsoft's Managed C++ interface as it is portable to both | |
15195 | Microsoft Windows and non-Microsoft platforms. PInvoke is part of the | |
15196 | ECMA/ISO C# specification. It is also better suited for robust | |
15197 | 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"> | |
15198 | Mixed DLL Loading Problem</A>. Swig C# works equally well on | |
15199 | non-Microsoft operating systems such as Linux, Solaris and Apple Mac | |
15200 | using <A href="http://www.mono-project.com/">Mono</A> and <A href="http://www.dotgnu.org/pnet.html"> | |
15201 | Portable.NET</A>.</P> | |
15202 | <P> To get the most out of this chapter an understanding of interop is | |
15203 | required. The <A href="http://msdn.microsoft.com">Microsoft Developer | |
15204 | Network (MSDN)</A> has a good reference guide in a section titled | |
15205 | "Interop Marshaling". Monodoc, available from the Mono project, has a | |
15206 | very useful section titled <A href="http://www.mono-project.com/Interop_with_Native_Libraries"> | |
15207 | Interop with native libraries</A>.</P> | |
15208 | <H2><A name="csharp_differences_java"></A>16.2 Differences to the Java | |
15209 | module</H2> | |
15210 | <P> The C# module is very similar to the Java module, so until some more | |
15211 | complete documentation has been written, please use the <A href="#Java"> | |
15212 | Java documentation</A> as a guide to using SWIG with C#. The rest of | |
15213 | this section should be read in conjunction with the Java documentation | |
15214 | as it lists the main differences.</P> | |
15215 | <P> Director support (virtual method callbacks into C#) has not yet been | |
15216 | implemented and is the main missing feature compared to Java. Less of | |
15217 | the STL is supported and there are also a few minor utility typemaps in | |
15218 | the various.i library which are missing.</P> | |
15219 | <P> The most noteable differences to Java are the following:</P> | |
15220 | <UL> | |
15221 | <LI> When invoking SWIG use the <TT>-csharp</TT> command line option | |
15222 | instead of <TT>-java</TT>.</LI> | |
15223 | <LI> The <TT>-package</TT> command line option does not exist.</LI> | |
15224 | <LI> The <TT>-namespace <name></TT> commandline option will generate all | |
15225 | code into the namespace specified by <TT><name></TT>.</LI> | |
15226 | <LI> The <TT>-dllimport <name></TT> commandline option specifies the | |
15227 | name of the DLL for the <TT>DllImport</TT> attribute for every PInvoke | |
15228 | method. If this commandline option is not given, the <TT>DllImport</TT> | |
15229 | DLL name is the same as the module name. This option is useful for when | |
15230 | one wants to invoke SWIG multiple times on different modules, yet | |
15231 | compile all the resulting code into a single DLL.</LI> | |
15232 | <LI> C/C++ variables are wrapped with C# properties and not JavaBean | |
15233 | style getters and setters.</LI> | |
15234 | <LI> Global constants are generated into the module class. There is no | |
15235 | constants interface.</LI> | |
15236 | <LI> There is no implementation for type unsafe enums - not deemed | |
15237 | necessary.</LI> | |
15238 | <LI> The default enum wrapping approach is proper C# enums, not typesafe | |
15239 | enums. | |
15240 | <BR> Note that %csconst(0) will be ignored when wrapping C/C++ enums | |
15241 | with proper C# enums. This is because C# enum items must be initialised | |
15242 | from a compile time constant. If an enum item has an initialiser and | |
15243 | the initialiser doesn't compile as C# code, then the %csconstvalue | |
15244 | directive must be used as %csconst(0) will have no effect. If it was | |
15245 | used, it would generate an illegal runtime initialisation via a PInvoke | |
15246 | call.</LI> | |
15247 | <LI> C# doesn't support the notion of throws clauses. Therefore there is | |
15248 | no 'throws' typemap attribute support for adding exception classes to a | |
15249 | throws clause. Likewise there is no need for an equivalent to <TT> | |
15250 | %javaexception</TT>. In fact, throwing C# exceptions works quite | |
15251 | differently, see <A href="#csharp_exceptions">C# Exceptions></A> below.</LI> | |
15252 | <LI> | |
15253 | <P>Typemap equivalent names:</P> | |
15254 | <DIV class="code"> | |
15255 | <PRE> | |
15256 | jni -> ctype | |
15257 | jtype -> imtype | |
15258 | jstype -> cstype | |
15259 | javain -> csin | |
15260 | javaout -> csout | |
15261 | javainterfaces -> csinterfaces and csinterfaces_derived | |
15262 | javabase -> csbase | |
15263 | javaclassmodifiers -> csclassmodifiers | |
15264 | javacode -> cscode | |
15265 | javaimports -> csimports | |
15266 | javabody -> csbody | |
15267 | javafinalize -> csfinalize | |
15268 | javadestruct -> csdestruct | |
15269 | javadestruct_derived -> csdestruct_derived | |
15270 | </PRE> | |
15271 | </DIV></LI> | |
15272 | <LI> | |
15273 | <P>Additional typemaps:</P> | |
15274 | <DIV class="code"> | |
15275 | <PRE> | |
15276 | csvarin C# code property set typemap | |
15277 | csvarout C# code property get typemap | |
15278 | csattributes C# attributes for attaching to proxy classes/enums | |
15279 | </PRE> | |
15280 | </DIV></LI> | |
15281 | <LI> | |
15282 | <P>Feature equivalent names:</P> | |
15283 | <DIV class="code"> | |
15284 | <PRE> | |
15285 | %javaconst -> %csconst | |
15286 | %javaconstvalue -> %csconstvalue | |
15287 | %javamethodmodifiers -> %csmethodmodifiers | |
15288 | </PRE> | |
15289 | </DIV></LI> | |
15290 | <LI> | |
15291 | <P>Pragma equivalent names:</P> | |
15292 | <DIV class="code"> | |
15293 | <PRE> | |
15294 | %pragma(java) -> %pragma(csharp) | |
15295 | jniclassbase -> imclassbase | |
15296 | jniclassclassmodifiers -> imclassclassmodifiers | |
15297 | jniclasscode -> imclasscode | |
15298 | jniclassimports -> imclassimports | |
15299 | jniclassinterfaces -> imclassinterfaces | |
15300 | </PRE> | |
15301 | </DIV></LI> | |
15302 | <LI> | |
15303 | <P>Special variable equivalent names:</P> | |
15304 | <DIV class="code"> | |
15305 | <PRE> | |
15306 | $javaclassname -> $csclassname | |
15307 | $javainput -> $csinput | |
15308 | $jnicall -> $imcall | |
15309 | </PRE> | |
15310 | </DIV></LI> | |
15311 | <LI> | |
15312 | <P> The intermediary classname has <TT>PINVOKE</TT> appended after the | |
15313 | module name instead of <TT>JNI</TT>, for example <TT>modulenamePINVOKE</TT> | |
15314 | .</P> | |
15315 | </LI> | |
15316 | <LI> | |
15317 | <P> Support for asymmetric type marshalling. The 'ctype', 'imtype' and | |
15318 | 'cstype' typemaps support an optional <TT>out</TT> attribute which is | |
15319 | used for output types. If this typemap attribute is specified, then the | |
15320 | type specified in the attribute is used for output types and the type | |
15321 | specified in the typemap itself is used for the input type. If this | |
15322 | typemap attribute is not specified, then the type used for both input | |
15323 | and output is the type specified in the typemap. An example shows that <TT> | |
15324 | char *</TT> could be marshalled in different ways,</P> | |
15325 | <DIV class="code"> | |
15326 | <PRE> | |
15327 | %typemap(imtype, out="IntPtr") char * "string" | |
15328 | char * function(char *); | |
15329 | </PRE> | |
15330 | </DIV> | |
15331 | <P> The output type is thus IntPtr and the input type is string. The | |
15332 | resulting intermediary C# code is:</P> | |
15333 | <DIV class="code"> | |
15334 | <PRE> | |
15335 | public static extern IntPtr function(string jarg1); | |
15336 | </PRE> | |
15337 | </DIV></LI> | |
15338 | <LI> | |
15339 | <P> Support for type attributes. The 'imtype' and 'cstype' typemaps can | |
15340 | have an optional <TT>inattributes</TT> and <TT>outattributes</TT> | |
15341 | typemap attribute. There are C# attributes and typemap attributes, | |
15342 | don't get confused!! The C# attributes specified in these typemap | |
15343 | attributes are generated wherever the type is used in the C# wrappers. | |
15344 | These can be used to specify any C# attribute associated with a C/C++ | |
15345 | type, but are more typically used for the C# <TT>MarshalAs</TT> | |
15346 | attribute. For example:</P> | |
15347 | <DIV class="code"> | |
15348 | <PRE> | |
15349 | %typemap(imtype, | |
15350 | inattributes="[MarshalAs(UnmanagedType.LPStr)]", | |
15351 | outattributes="[return: MarshalAs(UnmanagedType.LPStr)]") const char * "String" | |
15352 | ||
15353 | const char * GetMsg() {} | |
15354 | void SetMsg(const char *msg) {} | |
15355 | </PRE> | |
15356 | </DIV> | |
15357 | <P> The intermediary class will then have the marshalling as specified | |
15358 | by everything in the 'imtype' typemap:</P> | |
15359 | <DIV class="code"> | |
15360 | <PRE> | |
15361 | class examplePINVOKE { | |
15362 | ... | |
15363 | [DllImport("example", EntryPoint="CSharp_GetMsg")] | |
15364 | [return: MarshalAs(UnmanagedType.LPStr)] | |
15365 | public static extern String GetMsg(); | |
15366 | ||
15367 | [DllImport("example", EntryPoint="CSharp_SetMsg")] | |
15368 | public static extern void SetMsg([MarshalAs(UnmanagedType.LPStr)]String jarg1); | |
15369 | } | |
15370 | </PRE> | |
15371 | </DIV> | |
15372 | <P> Note that the <TT>DllImport</TT> attribute is always generated, | |
15373 | irrespective of any additional attributes specified.</P> | |
15374 | <P> These attributes are associated with the C/C++ parameter type or | |
15375 | return type, which is subtely different to the attribute features and | |
15376 | typemaps covered next. Note that all these different C# attributes can | |
15377 | be combined so that a method has more than one attribute.</P> | |
15378 | </LI> | |
15379 | <LI> | |
15380 | <P> Support for attaching C# attributes to wrapped methods and | |
15381 | variables. This is done using the <TT>%csattributes</TT> feature, see <A | |
15382 | href="#features">%feature directives</A>. Note that C# attributes are | |
15383 | attached to proxy classes and enums using the <TT>csattributes</TT> | |
15384 | typemap. For example, imagine we have a custom attribute class, <TT> | |
15385 | ThreadSafeAttribute</TT>, for labelling thread safety. The following | |
15386 | SWIG code shows how to attach this C# attribute to some methods and the | |
15387 | class declaration itself:</P> | |
15388 | <DIV class="code"> | |
15389 | <PRE> | |
15390 | %typemap(csattributes) AClass "[ThreadSafe]" | |
15391 | %csattributes AClass::AClass(double d) "[ThreadSafe(false)]" | |
15392 | %csattributes AClass::AMethod() "[ThreadSafe(true)]" | |
15393 | ||
15394 | %inline %{ | |
15395 | class AClass { | |
15396 | public: | |
15397 | AClass(double a) {} | |
15398 | void AMethod() {} | |
15399 | }; | |
15400 | %} | |
15401 | </PRE> | |
15402 | </DIV> | |
15403 | <P> will generate a C# proxy class:</P> | |
15404 | <DIV class="code"> | |
15405 | <PRE> | |
15406 | [ThreadSafe] | |
15407 | public class AClass : IDisposable { | |
15408 | ... | |
15409 | [ThreadSafe(false)] | |
15410 | public AClass(double a) ... | |
15411 | ||
15412 | [ThreadSafe(true)] | |
15413 | public void AMethod() ... | |
15414 | } | |
15415 | </PRE> | |
15416 | </DIV> | |
15417 | <P> If C# attributes need adding to the <TT>set</TT> or <TT>get</TT> | |
15418 | part of C# properties, when wrapping C/C++ variables, they can be added | |
15419 | using the 'csvarin' and 'csvarout' typemaps respectively.</P> | |
15420 | </LI> | |
15421 | <LI> | |
15422 | <P> The <TT>%csmethodmodifiers</TT> feature can also be applied to | |
15423 | variables as well as methods. In addition to the default <TT>public</TT> | |
15424 | modifier that SWIG generates when <TT>%csmethodmodifiers</TT> is not | |
15425 | specified, the feature will also replace the <TT>virtual</TT>/<TT>new</TT> | |
15426 | /<TT>override</TT> modifiers that SWIG thinks is appropriate. This | |
15427 | feature is useful for some obscure cases where SWIG might get the <TT> | |
15428 | virtual</TT>/<TT>new</TT>/<TT>override</TT> modifiers incorrect, for | |
15429 | example with multiple inheritance.</P> | |
15430 | </LI> | |
15431 | </UL> | |
15432 | <P><B> <TT>$dllimport</TT></B> | |
15433 | <BR> This is a C# only special variable that can be used in typemaps, | |
15434 | pragmas, features etc. The special variable will get translated into | |
15435 | the value specified by the <TT>-dllimport</TT> commandline option if | |
15436 | specified, otherwise it is equivalent to the<B> $module</B> special | |
15437 | variable.</P> | |
15438 | <P> The directory <TT>Examples/csharp</TT> has a number of simple | |
15439 | examples. Visual Studio .NET 2003 solution and project files are | |
15440 | available for compiling with the Microsoft .NET C# compiler on Windows. | |
15441 | If your SWIG installation went well on a Unix environment and your C# | |
15442 | compiler was detected, you should be able to type <TT>make</TT> in each | |
15443 | example directory, then <TT>ilrun runme.exe</TT> (Portable.NET C# | |
15444 | compiler) or <TT>mono runme.exe</TT> (Mono C# compiler) to run the | |
15445 | examples. Windows users can also get the examples working using a <A href="http://www.cygwin.com"> | |
15446 | Cygwin</A> or <A href="http://www.mingw.org">MinGW</A> environment for | |
15447 | automatic configuration of the example makefiles. Any one of the three | |
15448 | C# compilers (Portable.NET, Mono or Microsoft) can be detected from | |
15449 | within a Cygwin or Mingw environment if installed in your path.</P> | |
15450 | <H2><A name="csharp_exceptions"></A>16.3 C# Exceptions</H2> | |
15451 | <P> It is possible to throw a C# Exception from C/C++ code. SWIG already | |
15452 | provides the framework for throwing C# exceptions if it is able to | |
15453 | detect that a C++ exception could be thrown. Automatically detecting | |
15454 | that a C++ exception could be thrown is only possible when a C++ | |
15455 | exception specification is used, see <A href="#SWIGPlus_exception_specifications"> | |
15456 | Exception specifications</A>. The <A href="#exception">Exception | |
15457 | handling with %exception</A> section details the <TT>%exception</TT> | |
15458 | feature. Customised code for handling exceptions with or without a C++ | |
15459 | exception specification is possible and the details follow. However | |
15460 | anyone wishing to do this should be familiar with the contents of the | |
15461 | sections referred to above.</P> | |
15462 | <P> Unfortunately a C# exception cannot simply be thrown from unmanaged | |
15463 | code for a variety of reasons. Most noteably being that throwing a C# | |
15464 | exception results in exceptions being thrown across the C PInvoke | |
15465 | interface and C does not understand exceptions. The design revolves | |
15466 | around a C# exception being constructed and stored as a pending | |
15467 | exception, to be thrown only when the unmanaged code has completed. | |
15468 | Implementing this is a tad involved and there are thus some unusual | |
15469 | typemap constructs. Some practical examples follow and they should be | |
15470 | read in conjunction with the rest of this section.</P> | |
15471 | <P> First some details about the design that must be followed. Each | |
15472 | typemap or feature that generates<B> unmanaged code</B> supports an | |
15473 | attribute called <TT>canthrow</TT>. This is simply a flag which when | |
15474 | set indicates that the code in the typemap/feature has code which might | |
15475 | want to throw a C# exception. The code in the typemap/feature can then | |
15476 | raise a C# exception by calling one of the C functions, <TT> | |
15477 | SWIG_CSharpSetPendingException()</TT> or <TT> | |
15478 | SWIG_CSharpSetPendingExceptionArgument()</TT>. When called, the function | |
15479 | makes a callback into the managed world via a delegate. The callback | |
15480 | creates and stores an exception ready for throwing when the unmanaged | |
15481 | code has finished. The typemap/feature unmanaged code is then expected | |
15482 | to force an immediate return from the unmanaged wrapper function, so | |
15483 | that the pending managed exception can then be thrown. The support code | |
15484 | has been carefully designed to be efficient as well as thread-safe. | |
15485 | However to achieve the goal of efficiency requires some optional code | |
15486 | generation in the<B> managed code</B> typemaps. Code to check for | |
15487 | pending exceptions is generated if and only if the unmanaged code has | |
15488 | code to set a pending exception, that is if the <TT>canthrow</TT> | |
15489 | attribute is set. The optional managed code is generated using the <TT> | |
15490 | excode</TT> typemap attribute and <TT>$excode</TT> special variable in | |
15491 | the relevant managed code typemaps. Simply, if any relevant unmanaged | |
15492 | code has the <TT>canthrow</TT> attribute set, then any occurrences of <TT> | |
15493 | $excode</TT> is replaced with the code in the <TT>excode</TT> attribute. | |
15494 | If the <TT>canthrow</TT> attribute is not set, then any occurrences of <TT> | |
15495 | $excode</TT> are replaced with nothing.</P> | |
15496 | <P> The prototypes for the <TT>SWIG_CSharpSetPendingException()</TT> and | |
15497 | <TT>SWIG_CSharpSetPendingExceptionArgument()</TT> functions are</P> | |
15498 | <DIV class="code"> | |
15499 | <PRE> | |
15500 | static void SWIG_CSharpSetPendingException(SWIG_CSharpExceptionCodes code, | |
15501 | const char *msg); | |
15502 | ||
15503 | static void SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpExceptionArgumentCodes code, | |
15504 | const char *msg, | |
15505 | const char *param_name); | |
15506 | </PRE> | |
15507 | </DIV> | |
15508 | <P> The first parameter defines which .NET exceptions can be thrown:</P> | |
15509 | <DIV class="code"> | |
15510 | <PRE> | |
15511 | typedef enum { | |
15512 | SWIG_CSharpApplicationException, | |
15513 | SWIG_CSharpArithmeticException, | |
15514 | SWIG_CSharpDivideByZeroException, | |
15515 | SWIG_CSharpIndexOutOfRangeException, | |
15516 | SWIG_CSharpInvalidOperationException, | |
15517 | SWIG_CSharpIOException, | |
15518 | SWIG_CSharpNullReferenceException, | |
15519 | SWIG_CSharpOutOfMemoryException, | |
15520 | SWIG_CSharpOverflowException, | |
15521 | SWIG_CSharpSystemException | |
15522 | } SWIG_CSharpExceptionCodes; | |
15523 | ||
15524 | typedef enum { | |
15525 | SWIG_CSharpArgumentException, | |
15526 | SWIG_CSharpArgumentNullException, | |
15527 | SWIG_CSharpArgumentOutOfRangeException, | |
15528 | } SWIG_CSharpExceptionArgumentCodes; | |
15529 | </PRE> | |
15530 | </DIV> | |
15531 | <P> where, for example, <TT>SWIG_CSharpApplicationException</TT> | |
15532 | corresponds to the .NET exception, <TT>ApplicationException</TT>. The <TT> | |
15533 | msg</TT> and <TT>param_name</TT> parameters contain the C# exception | |
15534 | message and parameter name associated with the exception.</P> | |
15535 | <P> The <TT>%exception</TT> feature in C# has the <TT>canthrow</TT> | |
15536 | attribute set. The <TT>%csnothrowexception</TT> feature is like <TT> | |
15537 | %exception</TT>, but it does not have the <TT>canthrow</TT> attribute | |
15538 | set so should only be used when a C# exception is not created.</P> | |
15539 | <H3><A name="csharp_exception_example_check_typemap"></A>16.3.1 C# | |
15540 | exception example using "check" typemap</H3> | |
15541 | <P> Lets say we have the following simple C++ method:</P> | |
15542 | <DIV class="code"> | |
15543 | <PRE> | |
15544 | void positivesonly(int number); | |
15545 | </PRE> | |
15546 | </DIV> | |
15547 | <P> and we want to check that the input <TT>number</TT> is always | |
15548 | positive and if not throw a C# <TT>ArgumentOutOfRangeException</TT>. | |
15549 | The "check" typemap is designed for checking input parameters. Below | |
15550 | you will see the <TT>canthrow</TT> attribute is set because the code | |
15551 | contains a call to <TT>SWIG_CSharpSetPendingExceptionArgument()</TT>. | |
15552 | The full example follows:</P> | |
15553 | <DIV class="code"> | |
15554 | <PRE> | |
15555 | %module example | |
15556 | ||
15557 | %typemap(check, canthrow=1) int number %{ | |
15558 | if ($1 < 0) { | |
15559 | SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentOutOfRangeException, | |
15560 | "only positive numbers accepted", "number"); | |
15561 | return $null; | |
15562 | } | |
15563 | // SWIGEXCODE is a macro used by many other csout typemaps | |
15564 | %define SWIGEXCODE | |
15565 | "\n if ($modulePINVOKE.SWIGPendingException.Pending)" | |
15566 | "\n throw $modulePINVOKE.SWIGPendingException.Retrieve();" | |
15567 | %enddef | |
15568 | %typemap(csout, excode=SWIGEXCODE) void { | |
15569 | $imcall;$excode | |
15570 | } | |
15571 | %} | |
15572 | ||
15573 | %inline %{ | |
15574 | ||
15575 | void positivesonly(int number) { | |
15576 | } | |
15577 | ||
15578 | %} | |
15579 | </PRE> | |
15580 | </DIV> | |
15581 | <P> When the following C# code is executed:</P> | |
15582 | <DIV class="code"> | |
15583 | <PRE> | |
15584 | public class runme { | |
15585 | static void Main() { | |
15586 | example.positivesonly(-1); | |
15587 | } | |
15588 | } | |
15589 | </PRE> | |
15590 | </DIV> | |
15591 | <P> The exception is thrown:</P> | |
15592 | <DIV class="code"> | |
15593 | <PRE> | |
15594 | Unhandled Exception: System.ArgumentOutOfRangeException: only positive numbers accepted | |
15595 | Parameter name: number | |
15596 | in <0x00034> example:positivesonly (int) | |
15597 | in <0x0000c> runme:Main () | |
15598 | </PRE> | |
15599 | </DIV> | |
15600 | <P> Now let's analyse the generated code to gain a fuller understanding | |
15601 | of the typemaps. The generated unmanaged C++ code is:</P> | |
15602 | <DIV class="code"> | |
15603 | <PRE> | |
15604 | SWIGEXPORT void SWIGSTDCALL CSharp_positivesonly(int jarg1) { | |
15605 | int arg1 ; | |
15606 | ||
15607 | arg1 = (int)jarg1; | |
15608 | ||
15609 | if (arg1 < 0) { | |
15610 | SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentOutOfRangeException, | |
15611 | "only positive numbers accepted", "number"); | |
15612 | return ; | |
15613 | } | |
15614 | ||
15615 | positivesonly(arg1); | |
15616 | ||
15617 | } | |
15618 | </PRE> | |
15619 | </DIV> | |
15620 | <P> This largely comes from the "check" typemap. The managed code in the | |
15621 | module class is:</P> | |
15622 | <DIV class="code"> | |
15623 | <PRE> | |
15624 | public class example { | |
15625 | public static void positivesonly(int number) { | |
15626 | examplePINVOKE.positivesonly(number); | |
15627 | if (examplePINVOKE.SWIGPendingException.Pending) | |
15628 | throw examplePINVOKE.SWIGPendingException.Retrieve(); | |
15629 | } | |
15630 | ||
15631 | } | |
15632 | </PRE> | |
15633 | </DIV> | |
15634 | <P> This comes largely from the "csout" typemap.</P> | |
15635 | <P> The "csout" typemap is the same as the default void "csout" typemap | |
15636 | so is not strictly necessary for the example. However, it is shown to | |
15637 | demonstrate what managed output code typemaps should contain, that is, | |
15638 | a <TT>$excode</TT> special variable and an <TT>excode</TT> attribute. | |
15639 | Also note that <TT>$excode</TT> is expanded into the code held in the <TT> | |
15640 | excode</TT> attribute. The <TT>$imcall</TT> as always expands into <TT> | |
15641 | examplePINVOKE.positivesonly(number)</TT>. The exception support code in | |
15642 | the intermediary class, <TT>examplePINVOKE</TT>, is not shown, but is | |
15643 | contained within the inner classes, <TT>SWIGPendingException</TT> and <TT> | |
15644 | SWIGExceptionHelper</TT> and is always generated. These classes can be | |
15645 | seen in any of the generated wrappers. However, all that is required of | |
15646 | a user is as demonstrated in the "csin" typemap above. That is, is to | |
15647 | check <TT>SWIGPendingException.Pending</TT> and to throw the exception | |
15648 | returned by <TT>SWIGPendingException.Retrieve()</TT>.</P> | |
15649 | <P> If the "check" typemap did not exist, then the following module | |
15650 | class would instead be generated:</P> | |
15651 | <DIV class="code"> | |
15652 | <PRE> | |
15653 | public class example { | |
15654 | public static void positivesonly(int number) { | |
15655 | examplePINVOKE.positivesonly(number); | |
15656 | } | |
15657 | ||
15658 | } | |
15659 | </PRE> | |
15660 | </DIV> | |
15661 | <P> Here we see the pending exception checking code is omitted. In fact, | |
15662 | the code above would be generated if the <TT>canthrow</TT> attribute | |
15663 | was not in the "check" typemap, such as:</P> | |
15664 | <DIV class="code"> | |
15665 | <PRE> | |
15666 | %typemap(check) int number %{ | |
15667 | if ($1 < 0) { | |
15668 | SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentOutOfRangeException, | |
15669 | "only positive numbers accepted", "number"); | |
15670 | return $null; | |
15671 | } | |
15672 | %} | |
15673 | </PRE> | |
15674 | </DIV> | |
15675 | <P> Note that if SWIG detects you have used <TT> | |
15676 | SWIG_CSharpSetPendingException()</TT> or <TT> | |
15677 | SWIG_CSharpSetPendingExceptionArgument()</TT> without setting the <TT> | |
15678 | canthrow</TT> attribute you will get a warning message similar to</P> | |
15679 | <DIV class="code"> | |
15680 | <PRE> | |
15681 | example.i:21: Warning(845): Unmanaged code contains a call to a SWIG_CSharpSetPendingException | |
15682 | method and C# code does not handle pending exceptions via the canthrow attribute. | |
15683 | </PRE> | |
15684 | </DIV> | |
15685 | <P> Actually it will issue this warning for any function beginning with <TT> | |
15686 | SWIG_CSharpSetPendingException</TT>.</P> | |
15687 | <H3><A name="csharp_exception_example_percent_exception"></A>16.3.2 C# | |
15688 | exception example using %exception</H3> | |
15689 | <P> Let's consider a similar, but more common example that throws a C++ | |
15690 | exception from within a wrapped function. We can use <TT>%exception</TT> | |
15691 | as mentioned in <A href="#exception">Exception handling with %exception</A> | |
15692 | .</P> | |
15693 | <DIV class="code"> | |
15694 | <PRE> | |
15695 | %exception negativesonly(int value) %{ | |
15696 | try { | |
15697 | $action | |
15698 | } catch (std::out_of_range e) { | |
15699 | SWIG_CSharpSetPendingException(SWIG_CSharpApplicationException, e.what()); | |
15700 | } | |
15701 | %} | |
15702 | ||
15703 | %inline %{ | |
15704 | #include <stdexcept> | |
15705 | void negativesonly(int value) { | |
15706 | if (value >= 0) | |
15707 | throw std::out_of_range("number should be negative"); | |
15708 | } | |
15709 | %} | |
15710 | </PRE> | |
15711 | </DIV> | |
15712 | <P> The generated unmanaged code this time catches the C++ exception and | |
15713 | converts it into a C# <TT>ApplicationException</TT>.</P> | |
15714 | <DIV class="code"> | |
15715 | <PRE> | |
15716 | SWIGEXPORT void SWIGSTDCALL CSharp_negativesonly(int jarg1) { | |
15717 | int arg1 ; | |
15718 | ||
15719 | arg1 = (int)jarg1; | |
15720 | ||
15721 | try { | |
15722 | negativesonly(arg1); | |
15723 | ||
15724 | } catch (std::out_of_range e) { | |
15725 | SWIG_CSharpSetPendingException(SWIG_CSharpApplicationException, e.what()); | |
15726 | return ; | |
15727 | } | |
15728 | ||
15729 | } | |
15730 | </PRE> | |
15731 | </DIV> | |
15732 | <P> The managed code generated does check for the pending exception as | |
15733 | mentioned earlier as the C# version of <TT>%exception</TT> has the <TT> | |
15734 | canthrow</TT> attribute set by default:</P> | |
15735 | <DIV class="code"> | |
15736 | <PRE> | |
15737 | public static void negativesonly(int value) { | |
15738 | examplePINVOKE.negativesonly(value); | |
15739 | if (examplePINVOKE.SWIGPendingException.Pending) | |
15740 | throw examplePINVOKE.SWIGPendingException.Retrieve(); | |
15741 | } | |
15742 | </PRE> | |
15743 | </DIV> | |
15744 | <H3><A name="csharp_exception_example_exception_specifications"></A> | |
15745 | 16.3.3 C# exception example using exception specifications</H3> | |
15746 | <P> When C++ exception specifications are used, SWIG is able to detect | |
15747 | that the method might throw an exception. By default SWIG will | |
15748 | automatically generate code to catch the exception and convert it into | |
15749 | a managed <TT>ApplicationException</TT>, as defined by the default | |
15750 | "throws" typemaps. The following example has a user supplied "throws" | |
15751 | typemap which is used whenever an exception specification contains a <TT> | |
15752 | std::out_of_range</TT>, such as the <TT>evensonly</TT> method below.</P> | |
15753 | <DIV class="code"> | |
15754 | <PRE> | |
15755 | %typemap(throws, canthrow=1) std::out_of_range { | |
15756 | SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentException, $1.what(), NULL); | |
15757 | return $null; | |
15758 | } | |
15759 | ||
15760 | %inline %{ | |
15761 | #include <stdexcept> | |
15762 | void evensonly(int input) throw (std::out_of_range) { | |
15763 | if (input%2 != 0) | |
15764 | throw std::out_of_range("number is not even"); | |
15765 | } | |
15766 | %} | |
15767 | </PRE> | |
15768 | </DIV> | |
15769 | <P> Note that the type for the throws typemap is the type in the | |
15770 | exception specification. SWIG generates a try catch block with the | |
15771 | throws typemap code in the catch handler.</P> | |
15772 | <DIV class="code"> | |
15773 | <PRE> | |
15774 | SWIGEXPORT void SWIGSTDCALL CSharp_evensonly(int jarg1) { | |
15775 | int arg1 ; | |
15776 | ||
15777 | arg1 = (int)jarg1; | |
15778 | try { | |
15779 | evensonly(arg1); | |
15780 | } | |
15781 | catch(std::out_of_range &_e) { | |
15782 | { | |
15783 | SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentException, (&_e)->what(), NULL); | |
15784 | return ; | |
15785 | } | |
15786 | } | |
15787 | ||
15788 | } | |
15789 | </PRE> | |
15790 | </DIV> | |
15791 | <P> Multiple catch handlers are generated should there be more than one | |
15792 | exception specifications declared.</P> | |
15793 | <H3><A name="csharp_custom_application_exception"></A>16.3.4 Custom C# | |
15794 | ApplicationException example</H3> | |
15795 | <P> This example involves a user defined exception. The conventional | |
15796 | .NET exception handling approach is to create a custom <TT> | |
15797 | ApplicationException</TT> and throw it in your application. The goal in | |
15798 | this example is to convert the STL <TT>std::out_of_range</TT> exception | |
15799 | into one of these custom .NET exceptions.</P> | |
15800 | <P> The default exception handling is quite easy to use as the <TT> | |
15801 | SWIG_CSharpSetPendingException()</TT> and <TT> | |
15802 | SWIG_CSharpSetPendingExceptionArgument()</TT> methods are provided by | |
15803 | SWIG. However, for a custom C# exception, the boiler plate code that | |
15804 | supports these functions needs replicating. In essence this consists of | |
15805 | some C/C++ code and C# code. The C/C++ code can be generated into the | |
15806 | wrapper file using the <TT>%insert(runtime)</TT> directive and the C# | |
15807 | code can be generated into the intermediary class using the <TT> | |
15808 | imclasscode</TT> pragma as follows:</P> | |
15809 | <DIV class="code"> | |
15810 | <PRE> | |
15811 | %insert(runtime) %{ | |
15812 | // Code to handle throwing of C# CustomApplicationException from C/C++ code. | |
15813 | // The equivalent delegate to the callback, CSharpExceptionCallback_t, is CustomExceptionDelegate | |
15814 | // and the equivalent customExceptionCallback instance is customDelegate | |
15815 | typedef void (SWIGSTDCALL* CSharpExceptionCallback_t)(const char *); | |
15816 | CSharpExceptionCallback_t customExceptionCallback = NULL; | |
15817 | ||
15818 | extern "C" SWIGEXPORT | |
15819 | void SWIGSTDCALL CustomExceptionRegisterCallback(CSharpExceptionCallback_t customCallback) { | |
15820 | customExceptionCallback = customCallback; | |
15821 | } | |
15822 | ||
15823 | // Note that SWIG detects any method calls named starting with | |
15824 | // SWIG_CSharpSetPendingException for warning 845 | |
15825 | static void SWIG_CSharpSetPendingExceptionCustom(const char *msg) { | |
15826 | customExceptionCallback(msg); | |
15827 | } | |
15828 | %} | |
15829 | ||
15830 | %pragma(csharp) imclasscode=%{ | |
15831 | class CustomExceptionHelper { | |
15832 | // C# delegate for the C/C++ customExceptionCallback | |
15833 | public delegate void CustomExceptionDelegate(string message); | |
15834 | static CustomExceptionDelegate customDelegate = | |
15835 | new CustomExceptionDelegate(SetPendingCustomException); | |
15836 | ||
15837 | [DllImport("$dllimport", EntryPoint="CustomExceptionRegisterCallback")] | |
15838 | public static extern | |
15839 | void CustomExceptionRegisterCallback(CustomExceptionDelegate customCallback); | |
15840 | ||
15841 | static void SetPendingCustomException(string message) { | |
15842 | SWIGPendingException.Set(new CustomApplicationException(message)); | |
15843 | } | |
15844 | ||
15845 | static CustomExceptionHelper() { | |
15846 | CustomExceptionRegisterCallback(customDelegate); | |
15847 | } | |
15848 | } | |
15849 | static CustomExceptionHelper exceptionHelper = new CustomExceptionHelper(); | |
15850 | %} | |
15851 | </PRE> | |
15852 | </DIV> | |
15853 | <P> The method stored in the C# delegate instance, <TT>customDelegate</TT> | |
15854 | is what gets called by the C/C++ callback. However, the equivalent to | |
15855 | the C# delegate, that is the C/C++ callback, needs to be assigned | |
15856 | before any unmanaged code is executed. This is achieved by putting the | |
15857 | initialisation code in the intermediary class. Recall that the | |
15858 | intermediary class contains all the PInvoke methods, so the static | |
15859 | variables in the intermediary class will be initialised before any of | |
15860 | the PInvoke methods in this class are called. The <TT>exceptionHelper</TT> | |
15861 | static variable ensures the C/C++ callback is initialised with the | |
15862 | value in <TT>customDelegate</TT> by calling the <TT> | |
15863 | CustomExceptionRegisterCallback</TT> method in the <TT> | |
15864 | CustomExceptionHelper</TT> static constructor. Once this has been done, | |
15865 | unmanaged code can make callbacks into the managed world as <TT> | |
15866 | customExceptionCallback</TT> will be initialised with a valid | |
15867 | callback/delegate. Any calls to <TT> | |
15868 | SWIG_CSharpSetPendingExceptionCustom()</TT> will make the callback to | |
15869 | create the pending exception in the same way that <TT> | |
15870 | SWIG_CSharpSetPendingException()</TT> and <TT> | |
15871 | SWIG_CSharpSetPendingExceptionArgument()</TT> does. In fact the method | |
15872 | has been similarly named so that SWIG can issue the warning about | |
15873 | missing <TT>canthrow</TT> attributes as discussed earlier. It is an | |
15874 | invaluable warning as it is easy to forget the <TT>canthrow</TT> | |
15875 | attribute when writing typemaps/features.</P> | |
15876 | <P> The <TT>SWIGPendingException</TT> helper class is not shown, but is | |
15877 | generated as an inner class into the intermediary class. It stores the | |
15878 | pending exception in Thread Local Storage so that the exception | |
15879 | handling mechanism is thread safe.</P> | |
15880 | <P> The boiler plate code above must be used in addition to a | |
15881 | handcrafted <TT>CustomApplicationException</TT>:</P> | |
15882 | <DIV class="code"> | |
15883 | <PRE> | |
15884 | // Custom C# Exception | |
15885 | class CustomApplicationException : System.ApplicationException { | |
15886 | public CustomApplicationException(string message) | |
15887 | : base(message) { | |
15888 | } | |
15889 | } | |
15890 | </PRE> | |
15891 | </DIV> | |
15892 | <P> and the SWIG interface code:</P> | |
15893 | <DIV class="code"> | |
15894 | <PRE> | |
15895 | %typemap(throws, canthrow=1) std::out_of_range { | |
15896 | SWIG_CSharpSetPendingExceptionCustom($1.what()); | |
15897 | return $null; | |
15898 | } | |
15899 | ||
15900 | %inline %{ | |
15901 | void oddsonly(int input) throw (std::out_of_range) { | |
15902 | if (input%2 != 1) | |
15903 | throw std::out_of_range("number is not odd"); | |
15904 | } | |
15905 | %} | |
15906 | </PRE> | |
15907 | </DIV> | |
15908 | <P> The "throws" typemap now simply calls our new <TT> | |
15909 | SWIG_CSharpSetPendingExceptionCustom()</TT> function so that the | |
15910 | exception can be caught, as such:</P> | |
15911 | <DIV class="code"> | |
15912 | <PRE> | |
15913 | try { | |
15914 | example.oddsonly(2); | |
15915 | } catch (CustomApplicationException e) { | |
15916 | ... | |
15917 | } | |
15918 | </PRE> | |
15919 | </DIV><HR NOSHADE> | |
15920 | ||
15921 | <!-- Hand-written HTML --> | |
15922 | <H1><A name="Chicken"></A>17 SWIG and Chicken</H1> | |
15923 | ||
15924 | <!-- INDEX --> | |
15925 | <DIV class="sectiontoc"> | |
15926 | <UL> | |
15927 | <LI><A href="#Chicken_nn2">Preliminaries</A> | |
15928 | <UL> | |
15929 | <LI><A href="#Chicken_nn3">Running SWIG in C mode</A></LI> | |
15930 | <LI><A href="#Chicken_nn4">Running SWIG in C++ mode</A></LI> | |
15931 | </UL> | |
15932 | </LI> | |
15933 | <LI><A href="#Chicken_nn5">Code Generation</A> | |
15934 | <UL> | |
15935 | <LI><A href="#Chicken_nn6">Naming Conventions</A></LI> | |
15936 | <LI><A href="#Chicken_nn7">Modules</A></LI> | |
15937 | <LI><A href="#Chicken_nn8">Constants and Variables</A></LI> | |
15938 | <LI><A href="#Chicken_nn9">Functions</A></LI> | |
15939 | <LI><A href="#Chicken_nn10">Exceptions</A></LI> | |
15940 | </UL> | |
15941 | </LI> | |
15942 | <LI><A href="#Chicken_nn11">TinyCLOS</A></LI> | |
15943 | <LI><A href="#Chicken_nn12">Linkage</A> | |
15944 | <UL> | |
15945 | <LI><A href="#Chicken_nn13">Static binary or shared library linked at | |
15946 | compile time</A></LI> | |
15947 | <LI><A href="#Chicken_nn14">Building chicken extension libraries</A></LI> | |
15948 | <LI><A href="#Chicken_nn15">Linking multiple SWIG modules with TinyCLOS</A> | |
15949 | </LI> | |
15950 | </UL> | |
15951 | </LI> | |
15952 | <LI><A href="#Chicken_nn16">Typemaps</A></LI> | |
15953 | <LI><A href="#Chicken_nn17">Pointers</A> | |
15954 | <UL> | |
15955 | <LI><A href="#collection">Garbage collection</A></LI> | |
15956 | </UL> | |
15957 | </LI> | |
15958 | <LI><A href="#Chicken_nn18">Unsupported features and known problems</A></LI> | |
15959 | </UL> | |
15960 | </DIV> | |
15961 | <!-- INDEX --> | |
15962 | <P> This chapter describes SWIG's support of CHICKEN. CHICKEN is a | |
15963 | Scheme-to-C compiler supporting most of the language features as | |
15964 | defined in the<I> Revised^5 Report on Scheme</I>. Its main attributes | |
15965 | are that it</P> | |
15966 | <OL> | |
15967 | <LI>generates portable C code</LI> | |
15968 | <LI>includes a customizable interpreter</LI> | |
15969 | <LI>links to C libraries with a simple Foreign Function Interface</LI> | |
15970 | <LI>supports full tail-recursion and first-class continuations</LI> | |
15971 | </OL> | |
15972 | <P> When confronted with a large C library, CHICKEN users can use SWIG | |
15973 | to generate CHICKEN wrappers for the C library. However, the real | |
15974 | advantages of using SWIG with CHICKEN are its<STRONG> support for C++</STRONG> | |
15975 | -- object-oriented code is difficult to wrap by hand in CHICKEN -- and | |
15976 | its<STRONG> typed pointer representation</STRONG>, essential for C and | |
15977 | C++ libraries involving structures or classes.</P> | |
15978 | <H2><A name="Chicken_nn2"></A>17.1 Preliminaries</H2> | |
15979 | <P> CHICKEN support was introduced to SWIG in version 1.3.18. SWIG | |
15980 | relies on some recent additions to CHICKEN, which are only present in | |
15981 | releases of CHICKEN with version number<STRONG> greater than or equal | |
15982 | to 1.89</STRONG>. To use a chicken version between 1.40 and 1.89, see | |
15983 | the <A href="#collection">Garbage collection</A> section below.</P> | |
15984 | <P> You may want to look at any of the examples in Examples/chicken/ or | |
15985 | Examples/GIFPlot/Chicken for the basic steps to run SWIG CHICKEN.</P> | |
15986 | <H3><A name="Chicken_nn3"></A>17.1.1 Running SWIG in C mode</H3> | |
15987 | <P> To run SWIG CHICKEN in C mode, use the -chicken option.</P> | |
15988 | <DIV class="shell"> | |
15989 | <PRE>% swig -chicken example.i</PRE> | |
15990 | </DIV> | |
15991 | <P> To allow the wrapper to take advantage of future CHICKEN code | |
15992 | generation improvements, part of the wrapper is direct CHICKEN function | |
15993 | calls (<TT>example_wrap.c</TT>) and part is CHICKEN Scheme (<TT> | |
15994 | example.scm</TT>). The basic Scheme code must be compiled to C using | |
15995 | your system's CHICKEN compiler or both files can be compiled directly | |
15996 | using the much simpler <TT>csc</TT>.</P> | |
15997 | <DIV class="shell"> | |
15998 | <PRE> | |
15999 | % chicken example.scm -output-file oexample.c | |
16000 | </PRE> | |
16001 | </DIV> | |
16002 | <P> So for the C mode of SWIG CHICKEN, <TT>example_wrap.c</TT> and <TT> | |
16003 | oexample.c</TT> are the files that must be compiled to object files and | |
16004 | linked into your project.</P> | |
16005 | <H3><A name="Chicken_nn4"></A>17.1.2 Running SWIG in C++ mode</H3> | |
16006 | <P> To run SWIG CHICKEN in C++ mode, use the -chicken -c++ option.</P> | |
16007 | <DIV class="shell"> | |
16008 | <PRE>% swig -chicken -c++ example.i</PRE> | |
16009 | </DIV> | |
16010 | <P> This will generate <TT>example_wrap.cxx</TT> and <TT>example.scm</TT> | |
16011 | . The basic Scheme code must be compiled to C using your system's | |
16012 | CHICKEN compiler or both files can be compiled directly using the much | |
16013 | simpler <TT>csc</TT>.</P> | |
16014 | <DIV class="shell"> | |
16015 | <PRE>% chicken example.scm -output-file oexample.c</PRE> | |
16016 | </DIV> | |
16017 | <P> So for the C++ mode of SWIG CHICKEN, <TT>example_wrap.cxx</TT> and <TT> | |
16018 | oexample.c</TT> are the files that must be compiled to object files and | |
16019 | linked into your project.</P> | |
16020 | <H2><A name="Chicken_nn5"></A>17.2 Code Generation</H2> | |
16021 | <H3><A name="Chicken_nn6"></A>17.2.1 Naming Conventions</H3> | |
16022 | <P> Given a C variable, function or constant declaration named <TT> | |
16023 | Foo_Bar</TT>, the declaration will be available in CHICKEN as an | |
16024 | identifier ending with <TT>Foo-Bar</TT>. That is, an underscore is | |
16025 | converted to a dash.</P> | |
16026 | <P> You may control what the CHICKEN identifier will be by using the <TT> | |
16027 | %rename</TT> SWIG directive in the SWIG interface file.</P> | |
16028 | <H3><A name="Chicken_nn7"></A>17.2.2 Modules</H3> | |
16029 | <P> The name of the module must be declared one of two ways:</P> | |
16030 | <UL> | |
16031 | <LI>Placing <TT>%module example</TT> in the SWIG interface file.</LI> | |
16032 | <LI>Using <TT>-module example</TT> on the SWIG command line.</LI> | |
16033 | </UL> | |
16034 | <P> The generated example.scm file then exports <CODE>(declare (unit | |
16035 | modulename))</CODE>. If you do not want SWIG to export the <CODE> | |
16036 | (declare (unit modulename))</CODE>, pass the -nounit option to SWIG.</P> | |
16037 | <P> CHICKEN will be able to access the module using the <CODE>(declare | |
16038 | (uses<I> modulename</I>))</CODE> CHICKEN Scheme form.</P> | |
16039 | <H3><A name="Chicken_nn8"></A>17.2.3 Constants and Variables</H3> | |
16040 | <P> Constants may be created using any of the four constructs in the | |
16041 | interface file:</P> | |
16042 | <OL> | |
16043 | <LI><CODE>#define MYCONSTANT1 ...</CODE></LI> | |
16044 | <LI><CODE>%constant int MYCONSTANT2 = ...</CODE></LI> | |
16045 | <LI><CODE>const int MYCONSTANT3 = ...</CODE></LI> | |
16046 | <LI><CODE>enum { MYCONSTANT4 = ... };</CODE></LI> | |
16047 | </OL> | |
16048 | <P> In all cases, the constants may be accessed from within CHICKEN | |
16049 | using the form <TT>(MYCONSTANT1)</TT>; that is, the constants may be | |
16050 | accessed using the read-only parameter form.</P> | |
16051 | <P> Variables are accessed using the full parameter form. For example, | |
16052 | to set the C variable "int my_variable;", use the Scheme form <TT> | |
16053 | (my-variable 2345)</TT>. To get the C variable, use <TT>(my-variable)</TT> | |
16054 | .</P> | |
16055 | <H3><A name="Chicken_nn9"></A>17.2.4 Functions</H3> | |
16056 | <P> C functions declared in the SWIG interface file will have | |
16057 | corresponding CHICKEN Scheme procedures. For example, the C function | |
16058 | "int sqrt(double x);" will be available using the Scheme form <TT>(sqrt | |
16059 | 2345.0)</TT>. A <CODE>void</CODE> return value will give | |
16060 | C_SCHEME_UNDEFINED as a result.</P> | |
16061 | <P> A function may return more than one value by using the <CODE>OUTPUT</CODE> | |
16062 | specifier (see Lib/chicken/typemaps.i). They will be returned as | |
16063 | multiple values using <CODE>(values)</CODE> if there is more than one | |
16064 | result (that is, a non-void return value and at least one argout | |
16065 | parameter, or a void return value and at least two argout parameters). | |
16066 | The return values can then be accessed with <CODE>(call-with-values)</CODE> | |
16067 | .</P> | |
16068 | <H3><A name="Chicken_nn10"></A>17.2.5 Exceptions</H3> | |
16069 | <P>The SWIG chicken module has support for exceptions thrown from C or | |
16070 | C++ code to be caught in scheme. See <A href="#exception">Exception | |
16071 | handling with %exception</A> for more information about declaring | |
16072 | exceptions in the interface file.</P> | |
16073 | <P>Chicken supports both the <CODE>SWIG_exception(int code, const char | |
16074 | *msg)</CODE> interface as well as a <CODE>SWIG_ThrowException(C_word | |
16075 | val)</CODE> function for throwing exceptions from inside the %exception | |
16076 | blocks. <CODE>SWIG_exception</CODE> will throw a list consisting of the | |
16077 | code (as an integer) and the message. Both of these will throw an | |
16078 | exception using <CODE>(abort)</CODE>, which can be handled by <CODE> | |
16079 | (handle-exceptions)</CODE>. See <A href="http://www.call-with-current-continuation.org/manual/Exceptions.html#Exceptions"> | |
16080 | Chicken manual on Exceptions</A> and <A href="http://srfi.schemers.org/srfi-12/srfi-12.html"> | |
16081 | SFRI-12</A>. Since the exception values are thrown directly, if <CODE> | |
16082 | (condition-case)</CODE> is used to catch an exception the exception will | |
16083 | come through in the <CODE>val ()</CODE> case.</P> | |
16084 | <P>The following simple module</P> | |
16085 | <DIV class="code"> | |
16086 | <PRE> | |
16087 | %module exception_test | |
16088 | ||
16089 | %inline %{ | |
16090 | void test_throw(int i) throws (int) { | |
16091 | if (i == 1) throw 15; | |
16092 | } | |
16093 | %} | |
16094 | </PRE> | |
16095 | </DIV> | |
16096 | <P>could be run with</P> | |
16097 | <DIV class="targetlang"> | |
16098 | <PRE> | |
16099 | (handle-exceptions exvar | |
16100 | (if (= exvar 15) | |
16101 | (print "Correct!") | |
16102 | (print "Threw something else " exvar)) | |
16103 | (test-throw 1)) | |
16104 | </PRE> | |
16105 | </DIV> | |
16106 | <H2><A name="Chicken_nn11"></A>17.3 TinyCLOS</H2> | |
16107 | <P> The author of TinyCLOS, Gregor Kiczales, describes TinyCLOS as: | |
16108 | "Tiny CLOS is a Scheme implementation of a `kernelized' CLOS, with a | |
16109 | metaobject protocol. The implementation is even simpler than the simple | |
16110 | CLOS found in `The Art of the Metaobject Protocol,' weighing in at | |
16111 | around 850 lines of code, including (some) comments and documentation."</P> | |
16112 | <P> Almost all good Scheme books describe how to use metaobjects and | |
16113 | generic procedures to implement an object-oriented Scheme system. | |
16114 | Please consult a Scheme book if you are unfamiliar with the concept.</P> | |
16115 | <P> CHICKEN has a modified version of TinyCLOS, which SWIG CHICKEN uses | |
16116 | if the -proxy argument is given. If -proxy is passed, then the | |
16117 | generated example.scm file will contain TinyCLOS class definitions. A | |
16118 | class named Foo is declared as <Foo>, and each member variable is | |
16119 | allocated a slot. Member functions are exported as generic functions.</P> | |
16120 | <P> Primitive symbols and functions (the interface that would be | |
16121 | presented if -proxy was not passed) are hidden and no longer | |
16122 | accessable. If the -unhideprimitive command line argument is passed to | |
16123 | SWIG, then the primitive symbols will be available, but each will be | |
16124 | prefixed by the string "primitive:"</P> | |
16125 | <P> The exported symbol names can be controlled with the -closprefix and | |
16126 | -useclassprefix arguments. If -useclassprefix is passed to SWIG, every | |
16127 | member function will be generated with the class name as a prefix. If | |
16128 | the -closprefix mymod: argument is passed to SWIG, then the exported | |
16129 | functions will be prefixed by the string "mymod:". If -useclassprefix | |
16130 | is passed, -closprefix is ignored.</P> | |
16131 | <H2><A name="Chicken_nn12"></A>17.4 Linkage</H2> | |
16132 | <P> Please refer to<EM> CHICKEN - A practical and portable Scheme system | |
16133 | - User's manual</EM> for detailed help on how to link object files to | |
16134 | create a CHICKEN Scheme program. Briefly, to link object files, be sure | |
16135 | to add <TT>`chicken-config -extra-libs -libs`</TT> or <TT> | |
16136 | `chicken-config -shared -extra-libs -libs`</TT>to your linker options. | |
16137 | Use the <TT>-shared</TT> option if you want to create a dynamically | |
16138 | loadable module. You might also want to use the much simpler <TT>csc</TT> | |
16139 | or <TT>csc.bat</TT>.</P> | |
16140 | <P>Each scheme file that is generated by SWIG contains <CODE>(declare | |
16141 | (uses<I> modname</I>))</CODE>. This means that to load the module from | |
16142 | scheme code, the code must include <CODE>(declare (uses<I> modname</I> | |
16143 | ))</CODE>.</P> | |
16144 | <H3><A name="Chicken_nn13"></A>17.4.1 Static binary or shared library | |
16145 | linked at compile time</H3> | |
16146 | <P>We can easily use csc to build a static binary.</P> | |
16147 | <DIV class="shell"> | |
16148 | <PRE> | |
16149 | $ swig -chicken example.i | |
16150 | $ csc -v example.scm example_impl.c example_wrap.c test_script.scm -o example | |
16151 | $ ./example | |
16152 | </PRE> | |
16153 | </DIV> | |
16154 | <P>Similar to the above, any number of <TT>module.scm</TT> files could | |
16155 | be compiled into a shared library, and then that shared library linked | |
16156 | when compiling the main application.</P> | |
16157 | <DIV class="shell"> | |
16158 | <PRE> | |
16159 | $ swig -chicken example.i | |
16160 | $ csc -sv example.scm example_wrap.c example_impl.c -o example.so | |
16161 | </PRE> | |
16162 | </DIV> | |
16163 | <P>The <TT>exmaple.so</TT> file can then linked with <TT>test_script.scm</TT> | |
16164 | when it is compiled, in which case <TT>test_script.scm</TT> must have <CODE> | |
16165 | (declare (uses example))</CODE>. Multiple SWIG modules could have been | |
16166 | linked into <TT>example.so</TT> and each one accessed with a <CODE> | |
16167 | (declare (uses ... ))</CODE>.</P> | |
16168 | <DIV class="shell"> | |
16169 | <PRE> | |
16170 | $ csc -v test_script.scm -lexample | |
16171 | </PRE> | |
16172 | </DIV> | |
16173 | <P>An alternative is that the test_script.scm can have the code <CODE> | |
16174 | (load-library 'example "example.so")</CODE>, in which case the test | |
16175 | script does not need to be linked with example.so. The test_script.scm | |
16176 | file can then be run with <TT>csi</TT>.</P> | |
16177 | <H3><A name="Chicken_nn14"></A>17.4.2 Building chicken extension | |
16178 | libraries</H3> | |
16179 | <P>Building a shared library like in the above section only works if the | |
16180 | library is linked at compile time with a script containing <CODE> | |
16181 | (declare (uses ...))</CODE> or is loaded explicitly with <CODE> | |
16182 | (load-library 'example "example.so")</CODE>. It is not the format that | |
16183 | CHICKEN expects for extension libraries and eggs. The problem is the <CODE> | |
16184 | (declare (unit<I> modname</I>))</CODE> inside the <TT>modname.scm</TT> | |
16185 | file. There are two possible solutions to this.</P> | |
16186 | <P>First, SWIG accepts a <TT>-nounit</TT> argument, in which case the <CODE> | |
16187 | (declare (unit<I> modname</I>))</CODE> is not generated. Then, the <TT> | |
16188 | modname.scm</TT> and <TT>modname_wrap.c</TT> files<B> must</B> be | |
16189 | compiled into their own shared library.</P> | |
16190 | <DIV class="shell"> | |
16191 | <PRE> | |
16192 | $ csc -sv modname.scm modname_wrap.c modname_impl.c -o modname.so | |
16193 | </PRE> | |
16194 | </DIV> | |
16195 | <P>This library can then be loaded by scheme code with the <CODE> | |
16196 | (require 'modname)</CODE> function. See <A href="http://www.call-with-current-continuation.org/manual/Loading-extension-libraries.html"> | |
16197 | Loading-extension-libraries</A> in the eval unit inside the CHICKEN | |
16198 | manual for more information.</P> | |
16199 | <P>Another alternative is to run SWIG normally and create a scheme file | |
16200 | that contains <CODE>(declare (uses<I> modname</I>))</CODE> and then | |
16201 | compile that file into the shared library as well. For example, inside | |
16202 | the <TT>mod_load.scm</TT> file,</P> | |
16203 | <DIV class="targetlang"> | |
16204 | <PRE> | |
16205 | (declare (uses mod1)) | |
16206 | (declare (uses mod2)) | |
16207 | </PRE> | |
16208 | </DIV> | |
16209 | <P>Which would then be compiled with</P> | |
16210 | <DIV class="shell"> | |
16211 | <PRE> | |
16212 | $ swig -chicken mod1.i | |
16213 | $ swig -chicken mod2.i | |
16214 | $ csc -sv mod_load.scm mod1.scm mod2.scm mod1_wrap.c mod2_wrap.c mod1_impl.c mod2_impl.c -o mod.so | |
16215 | </PRE> | |
16216 | </DIV> | |
16217 | <P>Then the extension library can be loaded with <CODE>(require 'mod)</CODE> | |
16218 | . As we can see here, <TT>mod_load.scm</TT> contains the code that gets | |
16219 | exectued when the module is loaded. All this code does is load both | |
16220 | mod1 and mod2. As we can see, this technique is more useful when you | |
16221 | want to combine a few SWIG modules into one chicken extension library, | |
16222 | especially if modules are related by <CODE>%import</CODE></P> | |
16223 | <P>In either method, the files that are compiled into the shared library | |
16224 | could also be packaged into an egg. The <TT>mod1_wrap.c</TT> and <TT> | |
16225 | mod2_wrap.c</TT> files that are created by SWIG are stand alone and do | |
16226 | not need SWIG to be installed to be compiled. Thus the egg could be | |
16227 | distributed and used by anyone, even if SWIG is not installed.</P> | |
16228 | <P>See the <TT>Examples/chicken/egg</TT> directory in the SWIG source | |
16229 | for an example that builds two eggs, one using the first method and one | |
16230 | using the second method.</P> | |
16231 | <H3><A name="Chicken_nn15"></A>17.4.3 Linking multiple SWIG modules with | |
16232 | TinyCLOS</H3> | |
16233 | <P>Linking together multiple modules that share type information using | |
16234 | the <CODE>%import</CODE> directive while also using <TT>-proxy</TT> is | |
16235 | more complicated. For example, if <TT>mod2.i</TT> imports <TT>mod1.i</TT> | |
16236 | , then the <TT>mod2.scm</TT> file contains references to symbols | |
16237 | declared in <TT>mod1.scm</TT>, and thus a <CODE>(declare (uses<I> mod1</I> | |
16238 | ))</CODE> or <CODE>(require '<I>mod1</I>)</CODE> must be exported to the | |
16239 | top of <TT>mod2.scm</TT>. By default, when SWIG encounters an <CODE> | |
16240 | %import "modname.i"</CODE> directive, it exports <CODE>(declare (uses<I> | |
16241 | modname</I>))</CODE> into the scm file. This works fine unless mod1 was | |
16242 | compiled with the <TT>-nounit</TT> argument or was compiled into an | |
16243 | extension library with other modules under a different name.</P> | |
16244 | <P>One option is to override the automatic generation of <CODE>(declare | |
16245 | (uses mod1))</CODE> by passing the <TT>-noclosuses</TT> option to SWIG | |
16246 | when compiling <TT>mod2.i</TT>. SWIG then provides the <CODE> | |
16247 | %insert(closprefix) %{ %}</CODE> directive. Any scheme code inside that | |
16248 | directive is inserted into the generated .scm file, and if <TT>mod1</TT> | |
16249 | was compiled with <TT>-nounit</TT>, the directive should contain <CODE> | |
16250 | (require 'mod1)</CODE>. This option allows for mixed loading as well, | |
16251 | where some modules are imported with <CODE>(declare (uses<I> modname</I> | |
16252 | ))</CODE> (which means they were compiled without -nounit) and some are | |
16253 | imported with <CODE>(require 'modname)</CODE>.</P> | |
16254 | <P>The other option is to use the second idea in the above section. | |
16255 | Compile all the modules normally, without any <CODE>%insert(closprefix)</CODE> | |
16256 | , <TT>-nounit</TT>, or <TT>-noclosuses</TT>. Then the modules will | |
16257 | import each other correctly with <CODE>(declare (uses ...))</CODE>. To | |
16258 | create an extension library or an egg, just create a <TT> | |
16259 | module_load.scm</TT> file that <CODE>(declare (uses ...))</CODE> all the | |
16260 | modules.</P> | |
16261 | <H2><A name="Chicken_nn16"></A>17.5 Typemaps</H2> | |
16262 | <P> The Chicken module handles all types via typemaps. This information | |
16263 | is read from <CODE>Lib/chicken/typemaps.i</CODE> and <CODE> | |
16264 | Lib/chicken/chicken.swg</CODE>.</P> | |
16265 | <H2><A name="Chicken_nn17"></A>17.6 Pointers</H2> | |
16266 | <P> For pointer types, SWIG uses CHICKEN tagged pointers. A tagged | |
16267 | pointer is an ordinary CHICKEN pointer with an extra slot for a void *. | |
16268 | With SWIG CHICKEN, this void * is a pointer to a type-info structure. | |
16269 | So each pointer used as input or output from the SWIG-generated CHICKEN | |
16270 | wrappers will have type information attached to it. This will let the | |
16271 | wrappers correctly determine which method should be called according to | |
16272 | the object type hierarchy exposed in the SWIG interface files.</P> | |
16273 | <P> To construct a Scheme object from a C pointer, the wrapper code | |
16274 | calls the function <CODE>SWIG_NewPointerObj(void *ptr, swig_type_info | |
16275 | *type, int owner)</CODE>, The function that calls <CODE> | |
16276 | SWIG_NewPointerObj</CODE> must have a variable declared <CODE>C_word | |
16277 | *known_space = C_alloc(C_SIZEOF_SWIG_POINTER);</CODE> It is ok to call <CODE> | |
16278 | SWIG_NewPointerObj</CODE> more than once, just make sure known_space has | |
16279 | enough space for all the created pointers.</P> | |
16280 | <P> To get the pointer represented by a CHICKEN tagged pointer, the | |
16281 | wrapper code calls the function <CODE>SWIG_ConvertPtr(C_word s, void | |
16282 | **result, swig_type_info *type, int flags)</CODE>, passing a pointer to | |
16283 | a struct representing the expected pointer type. flags is either zero | |
16284 | or SWIG_POINTER_DISOWN (see below).</P> | |
16285 | <H3><A name="collection"></A>17.6.1 Garbage collection</H3> | |
16286 | <P>If the owner flag passed to <CODE>SWIG_NewPointerObj</CODE> is 1, <CODE> | |
16287 | NewPointerObj</CODE> will add a finalizer to the type which will call | |
16288 | the destructor or delete method of that type. The destructor and delete | |
16289 | functions are no longer exported for use in scheme code, instead SWIG | |
16290 | and chicken manage pointers. In situations where SWIG knows that a | |
16291 | function is returning a type that should be garbage collected, SWIG | |
16292 | will automaticly set the owner flag to 1. For other functions, the <CODE> | |
16293 | %newobject</CODE> directive must be specified for functions whose return | |
16294 | values should be garbage collected. See <A href="#ownership">Object | |
16295 | ownership and %newobject</A> for more information.</P> | |
16296 | <P>In situations where a C or C++ function will assume ownership of a | |
16297 | pointer, and thus chicken should no longer garbage collect it, SWIG | |
16298 | provides the <CODE>DISOWN</CODE> input typemap. After applying this | |
16299 | typemap (see the <A href="Typemaps.html">Typemaps chapter</A> for more | |
16300 | information on how to apply typemaps), any pointer that gets passed in | |
16301 | will no longer be garbage collected. An object is disowned by passing | |
16302 | the <CODE>SWIG_POINTER_DISOWN</CODE> flag to <CODE>SWIG_ConvertPtr</CODE> | |
16303 | .<B> Warning:</B> Since the lifetime of the object is now controlled by | |
16304 | the underlying code, the object might get deleted while the scheme code | |
16305 | still holds a pointer to it. Further use of this pointer can lead to a | |
16306 | crash.</P> | |
16307 | <P>Adding a finalizer function from C code was added to chicken in the | |
16308 | 1.89 release, so garbage collection does not work for chicken versions | |
16309 | below 1.89. If you would like the SWIG generated code to work with | |
16310 | chicken 1.40 to 1.89, pass the <CODE>-nocollection</CODE> argument to | |
16311 | SWIG. This will not export code inside the _wrap.c file to register | |
16312 | finalizers, and will then export destructor functions which must be | |
16313 | called manually.</P> | |
16314 | <H2><A name="Chicken_nn18"></A>17.7 Unsupported features and known | |
16315 | problems</H2> | |
16316 | <UL> | |
16317 | <LI>No director support.</LI> | |
16318 | <LI>No support for c++ standard types like std::vector.</LI> | |
16319 | <LI>The TinyCLOS wrappers for overloaded functions will not work | |
16320 | correctly when using <A href="#SWIGPlus_default_args"> | |
16321 | %feature(compactdefaultargs)</A>.</LI> | |
16322 | </UL> | |
16323 | <P>TinyCLOS has a limitation such that generic methods do not properly | |
16324 | work on methods with different number of specializers: TinyCLOS assumes | |
16325 | that every method added to a generic function will have the same number | |
16326 | of specializers. SWIG generates functions with different lengths of | |
16327 | specializers when C/C++ functions are overloaded. For example, the code</P> | |
16328 | <DIV class="code"> | |
16329 | <PRE> | |
16330 | class Foo {}; | |
16331 | int foo(int a, Foo *b); | |
16332 | int foo(int a); | |
16333 | </PRE> | |
16334 | </DIV> | |
16335 | <P>will produce scheme code</P> | |
16336 | <DIV class="targetlang"> | |
16337 | <PRE> | |
16338 | (define-method (foo (arg0 <top>) (arg1 <Foo>)) (<I>call primitive function</I>)) | |
16339 | (define-method (foo (arg0 <top>)) (<I>call primitive function</I>)) | |
16340 | </PRE> | |
16341 | </DIV> | |
16342 | <P>Using unpatched TinyCLOS, the second <CODE>(define-method)</CODE> | |
16343 | will replace the first one, so calling <CODE>(foo 3 f)</CODE> will | |
16344 | produce an error.</P> | |
16345 | <P>There are two solutions to this: the file <TT> | |
16346 | Lib/chicken/tinyclos-multi-generic.patch</TT> in the SWIG source | |
16347 | contains a patch against tinyclos.scm inside the chicken source to add | |
16348 | support into TinyCLOS for multi-argument generics. This requires | |
16349 | chicken to be rebuilt and custom install of chicken. An alternative is | |
16350 | the <TT>Lib/chicken/multi-generic.scm</TT> file in the SWIG source. | |
16351 | This file can be loaded after TinyCLOS is loaded, and it will override | |
16352 | some functions inside TinyCLOS to correctly support multi-argument | |
16353 | generics. This solution will work on any install of chicken. Please see | |
16354 | the comments at the top of both files for more information.</P> | |
16355 | <HR NOSHADE> | |
16356 | ||
16357 | <!-- Hand-written HTML --> | |
16358 | <H1><A name="Guile"></A>18 SWIG and Guile</H1> | |
16359 | ||
16360 | <!-- INDEX --> | |
16361 | <DIV class="sectiontoc"> | |
16362 | <UL> | |
16363 | <LI><A href="#Guile_nn2">Meaning of "Module"</A></LI> | |
16364 | <LI><A href="#Guile_nn3">Using the SCM or GH Guile API</A></LI> | |
16365 | <LI><A href="#Guile_nn4">Linkage</A> | |
16366 | <UL> | |
16367 | <LI><A href="#Guile_nn5">Simple Linkage</A></LI> | |
16368 | <LI><A href="#Guile_nn6">Passive Linkage</A></LI> | |
16369 | <LI><A href="#Guile_nn7">Native Guile Module Linkage</A></LI> | |
16370 | <LI><A href="#Guile_nn8">Old Auto-Loading Guile Module Linkage</A></LI> | |
16371 | <LI><A href="#Guile_nn9">Hobbit4D Linkage</A></LI> | |
16372 | </UL> | |
16373 | </LI> | |
16374 | <LI><A href="#Guile_nn10">Underscore Folding</A></LI> | |
16375 | <LI><A href="#Guile_nn11">Typemaps</A></LI> | |
16376 | <LI><A href="#Guile_nn12">Representation of pointers as smobs</A> | |
16377 | <UL> | |
16378 | <LI><A href="#Guile_nn13">GH Smobs</A></LI> | |
16379 | <LI><A href="#Guile_nn14">SCM Smobs</A></LI> | |
16380 | <LI><A href="#Guile_nn15">Garbage Collection</A></LI> | |
16381 | </UL> | |
16382 | </LI> | |
16383 | <LI><A href="#Guile_nn16">Exception Handling</A></LI> | |
16384 | <LI><A href="#Guile_nn17">Procedure documentation</A></LI> | |
16385 | <LI><A href="#Guile_nn18">Procedures with setters</A></LI> | |
16386 | <LI><A href="#Guile_nn19">GOOPS Proxy Classes</A> | |
16387 | <UL> | |
16388 | <LI><A href="#Guile_nn20">Naming Issues</A></LI> | |
16389 | <LI><A href="#Guile_nn21">Linking</A></LI> | |
16390 | </UL> | |
16391 | </LI> | |
16392 | </UL> | |
16393 | </DIV> | |
16394 | <!-- INDEX --> | |
16395 | <P> This section details guile-specific support in SWIG.</P> | |
16396 | <H2><A name="Guile_nn2"></A>18.1 Meaning of "Module"</H2> | |
16397 | <P> There are three different concepts of "module" involved, defined | |
16398 | separately for SWIG, Guile, and Libtool. To avoid horrible confusion, | |
16399 | we explicitly prefix the context, e.g., "guile-module".</P> | |
16400 | <H2><A name="Guile_nn3"></A>18.2 Using the SCM or GH Guile API</H2> | |
16401 | <P>The guile module can currently export wrapper files that use the | |
16402 | guile GH interface or the SCM interface. This is controlled by an | |
16403 | argument passed to swig. The "-gh" argument causes swig to output GH | |
16404 | code, and the "-scm" argument causes swig to output SCM code. Right now | |
16405 | the "-scm" argument is the default. The "-scm" wrapper generation | |
16406 | assumes a guile version >= 1.6 and has several advantages over the | |
16407 | "-gh" wrapper generation including garbage collection and GOOPS | |
16408 | support. The "-gh" wrapper generation can be used for older versions of | |
16409 | guile. The guile GH wrapper code generation is depreciated and the SCM | |
16410 | interface is the default. The SCM and GH interface differ greatly in | |
16411 | how they store pointers and have completely different run-time code. | |
16412 | See below for more info.</P> | |
16413 | <P>The GH interface to guile is deprecated. Read more about why in the <A | |
16414 | href="http://www.gnu.org/software/guile/docs/guile-ref/GH-deprecation.html"> | |
16415 | Guile manual</A>. The idea of the GH interface was to provide a high | |
16416 | level API that other languages and projects could adopt. This was a | |
16417 | good idea, but didn't pan out well for general development. But for the | |
16418 | specific, minimal uses that the SWIG typemaps put the GH interface to | |
16419 | use is ideal for using a high level API. So even though the GH | |
16420 | interface is depreciated, SWIG will continue to use the GH interface | |
16421 | and provide mappings from the GH interface to whatever API we need. We | |
16422 | can maintain this mapping where guile failed because SWIG uses a small | |
16423 | subset of all the GH functions which map easily. All the guile typemaps | |
16424 | like typemaps.i and std_vector.i will continue to use the GH functions | |
16425 | to do things like create lists of values, convert strings to integers, | |
16426 | etc. Then every language module will define a mapping between the GH | |
16427 | interface and whatever custom API the language uses. This is currently | |
16428 | implemented by the guile module to use the SCM guile API rather than | |
16429 | the GH guile API. For example, here are some of the current mapping | |
16430 | file for the SCM API</P> | |
16431 | <DIV class="code"> | |
16432 | <PRE> | |
16433 | ||
16434 | #define gh_append2(a, b) scm_append(scm_listify(a, b, SCM_UNDEFINED)) | |
16435 | #define gh_apply(a, b) scm_apply(a, b, SCM_EOL) | |
16436 | #define gh_bool2scm SCM_BOOL | |
16437 | #define gh_boolean_p SCM_BOOLP | |
16438 | #define gh_car SCM_CAR | |
16439 | #define gh_cdr SCM_CDR | |
16440 | #define gh_cons scm_cons | |
16441 | #define gh_double2scm scm_make_real | |
16442 | ... | |
16443 | </PRE> | |
16444 | </DIV> | |
16445 | <P>This file is parsed by SWIG at wrapper generation time, so every | |
16446 | reference to a gh_ function is replaced by a scm_ function in the | |
16447 | wrapper file. Thus the gh_ function calls will never be seen in the | |
16448 | wrapper; the wrapper will look exactly like it was generated for the | |
16449 | specific API. Currently only the guile language module has created a | |
16450 | mapping policy from gh_ to scm_, but there is no reason other languages | |
16451 | (like mzscheme or chicken) couldn't also use this. If that happens, | |
16452 | there is A LOT less code duplication in the standard typemaps.</P> | |
16453 | <H2><A name="Guile_nn4"></A>18.3 Linkage</H2> | |
16454 | <P> Guile support is complicated by a lack of user community | |
16455 | cohesiveness, which manifests in multiple shared-library usage | |
16456 | conventions. A set of policies implementing a usage convention is | |
16457 | called a<B> linkage</B>.</P> | |
16458 | <H3><A name="Guile_nn5"></A>18.3.1 Simple Linkage</H3> | |
16459 | <P> The default linkage is the simplest; nothing special is done. In | |
16460 | this case the function <CODE>SWIG_init()</CODE> is exported. Simple | |
16461 | linkage can be used in several ways:</P> | |
16462 | <UL> | |
16463 | <LI><B>Embedded Guile, no modules.</B> You want to embed a Guile | |
16464 | interpreter into your program; all bindings made by SWIG shall show up | |
16465 | in the root module. Then call <CODE>SWIG_init()</CODE> in the <CODE> | |
16466 | inner_main()</CODE> function. See the "simple" and "matrix" examples | |
16467 | under <CODE>Examples/guile</CODE>.</LI> | |
16468 | <LI> | |
16469 | <P><B>Dynamic module mix-in.</B> You want to create a Guile module using | |
16470 | <CODE>define-module</CODE>, containing both Scheme code and bindings | |
16471 | made by SWIG; you want to load the SWIG modules as shared libraries | |
16472 | into Guile.</P> | |
16473 | <DIV class="targetlang"> | |
16474 | <PRE> | |
16475 | (define-module (my module)) | |
16476 | (define my-so (dynamic-link "./example.so")) | |
16477 | (dynamic-call "SWIG_init" my-so) ; make SWIG bindings | |
16478 | ;; Scheme definitions can go here | |
16479 | </PRE> | |
16480 | </DIV> | |
16481 | <P> Newer Guile versions provide a shorthand for <CODE>dynamic-link</CODE> | |
16482 | and <CODE>dynamic-call</CODE>:</P> | |
16483 | <DIV class="targetlang"> | |
16484 | <PRE> | |
16485 | (load-extension "./example.so" "SWIG_init") | |
16486 | </PRE> | |
16487 | </DIV> | |
16488 | <P> You need to explicitly export those bindings made by SWIG that you | |
16489 | want to import into other modules:</P> | |
16490 | <DIV class="targetlang"> | |
16491 | <PRE> | |
16492 | (export foo bar) | |
16493 | </PRE> | |
16494 | </DIV> | |
16495 | <P> In this example, the procedures <CODE>foo</CODE> and <CODE>bar</CODE> | |
16496 | would be exported. Alternatively, you can export all bindings with the | |
16497 | following module-system hack:</P> | |
16498 | <DIV class="targetlang"> | |
16499 | <PRE> | |
16500 | (module-map (lambda (sym var) | |
16501 | (module-export! (current-module) (list sym))) | |
16502 | (current-module)) | |
16503 | </PRE> | |
16504 | </DIV> | |
16505 | <P>SWIG can also generate this Scheme stub (from <CODE>define-module</CODE> | |
16506 | up to <CODE>export</CODE>) semi-automagically if you pass it the | |
16507 | command-line argument <CODE>-scmstub</CODE>. The code will be exported | |
16508 | in a file called <CODE><I>module</I>.scm</CODE> in the directory | |
16509 | specified by <CODE>-outdir</CODE> or the current directory if <CODE> | |
16510 | -outdir</CODE> is not specified. Since SWIG doesn't know how to load | |
16511 | your extension module (with <CODE>dynamic-link</CODE> or <CODE> | |
16512 | load-extension</CODE>), you need to supply this information by including | |
16513 | a directive like this in the interface file:</P> | |
16514 | <DIV class="code"> | |
16515 | <PRE> | |
16516 | %scheme %{ (load-extension "./example.so" "SWIG_init") %} | |
16517 | </PRE> | |
16518 | </DIV> | |
16519 | <P> (The <CODE>%scheme</CODE> directive allows to insert arbitrary | |
16520 | Scheme code into the generated file <CODE><VAR>module.scm</VAR></CODE>; | |
16521 | it is placed between the <CODE>define-module</CODE> form and the <CODE> | |
16522 | export</CODE> form.)</P> | |
16523 | </LI> | |
16524 | </UL> | |
16525 | <P>If you want to include several SWIG modules, you would need to rename | |
16526 | <CODE>SWIG_init</CODE> via a preprocessor define to avoid symbol | |
16527 | clashes. For this case, however, passive linkage is available.</P> | |
16528 | <H3><A name="Guile_nn6"></A>18.3.2 Passive Linkage</H3> | |
16529 | <P>Passive linkage is just like simple linkage, but it generates an | |
16530 | initialization function whose name is derived from the module and | |
16531 | package name (see below).</P> | |
16532 | <P>You should use passive linkage rather than simple linkage when you | |
16533 | are using multiple modules.</P> | |
16534 | <H3><A name="Guile_nn7"></A>18.3.3 Native Guile Module Linkage</H3> | |
16535 | <P>SWIG can also generate wrapper code that does all the Guile module | |
16536 | declarations on its own if you pass it the <CODE>-Linkage module</CODE> | |
16537 | command-line option. This requires Guile 1.5.0 or later.</P> | |
16538 | <P>The module name is set with the <CODE>-package</CODE> and <CODE> | |
16539 | -module</CODE> command-line options. Suppose you want to define a module | |
16540 | with name <CODE>(my lib foo)</CODE>; then you would have to pass the | |
16541 | options <CODE>-package<VAR> my</VAR>/<VAR>lib</VAR> -module<VAR> foo</VAR> | |
16542 | </CODE>. Note that the last part of the name can also be set via the | |
16543 | SWIG directive <CODE>%module</CODE>.</P> | |
16544 | <P>You can use this linkage in several ways:</P> | |
16545 | <UL> | |
16546 | <LI><B>Embedded Guile with SWIG modules.</B> You want to embed a Guile | |
16547 | interpreter into your program; the SWIG bindings shall be put into | |
16548 | different modules. Simply call the function <CODE>scm_init_<VAR>my</VAR> | |
16549 | _<VAR>modules</VAR>_<VAR>foo</VAR>_module</CODE> in the <CODE> | |
16550 | inner_main()</CODE> function.</LI> | |
16551 | <LI><B>Dynamic Guile modules.</B> You want to load the SWIG modules as | |
16552 | shared libraries into Guile; all bindings are automatically put in | |
16553 | newly created Guile modules.<DIV class="targetlang"> | |
16554 | <PRE> | |
16555 | (define my-so (dynamic-link "./foo.so")) | |
16556 | ;; create new module and put bindings there: | |
16557 | (dynamic-call "scm_init_my_modules_foo_module" my-so) | |
16558 | </PRE> | |
16559 | </DIV> Newer Guile versions have a shorthand procedure for this:<DIV class="targetlang"> | |
16560 | <PRE> | |
16561 | (load-extension "./foo.so" "scm_init_my_modules_foo_module") | |
16562 | </PRE> | |
16563 | </DIV></LI> | |
16564 | </UL> | |
16565 | <H3><A name="Guile_nn8"></A>18.3.4 Old Auto-Loading Guile Module Linkage</H3> | |
16566 | <P>Guile used to support an autoloading facility for object-code | |
16567 | modules. This support has been marked deprecated in version 1.4.1 and | |
16568 | is going to disappear sooner or later. SWIG still supports building | |
16569 | auto-loading modules if you pass it the <CODE>-Linkage ltdlmod</CODE> | |
16570 | command-line option.</P> | |
16571 | <P>Auto-loading worked like this: Suppose a module with name <CODE>(my | |
16572 | lib foo)</CODE> is required and not loaded yet. Guile will then search | |
16573 | all directories in its search path for a Scheme file <CODE> | |
16574 | my/modules/foo.scm</CODE> or a shared library <CODE><VAR>my</VAR>/<VAR> | |
16575 | modules</VAR>/lib<VAR>foo</VAR>.so</CODE> (or <CODE><VAR>my</VAR>/<VAR> | |
16576 | modules</VAR>/lib<VAR>foo</VAR>.la</CODE>; see the GNU libtool | |
16577 | documentation). If a shared library is found that contains the symbol <CODE> | |
16578 | scm_init_<VAR>my</VAR>_<VAR>modules</VAR>_<VAR>foo</VAR>_module</CODE>, | |
16579 | the library is loaded, and the function at that symbol is called with | |
16580 | no arguments in order to initialize the module.</P> | |
16581 | <P>When invoked with the <CODE>-Linkage ltdlmod</CODE> command-line | |
16582 | option, SWIG generates an exported module initialization function with | |
16583 | an appropriate name.</P> | |
16584 | <H3><A name="Guile_nn9"></A>18.3.5 Hobbit4D Linkage</H3> | |
16585 | <P> The only other linkage supported at this time creates shared object | |
16586 | libraries suitable for use by hobbit's <CODE>(hobbit4d link)</CODE> | |
16587 | guile module. This is called the "hobbit" linkage, and requires also | |
16588 | using the "-package" command line option to set the part of the module | |
16589 | name before the last symbol. For example, both command lines:</P> | |
16590 | <DIV class="shell"> | |
16591 | <PRE> | |
16592 | swig -guile -package my/lib foo.i | |
16593 | swig -guile -package my/lib -module foo foo.i | |
16594 | </PRE> | |
16595 | </DIV> | |
16596 | <P> would create module <CODE>(my lib foo)</CODE> (assuming in the first | |
16597 | case foo.i declares the module to be "foo"). The installed files are | |
16598 | my/lib/libfoo.so.X.Y.Z and friends. This scheme is still very | |
16599 | experimental; the (hobbit4d link) conventions are not well understood.</P> | |
16600 | <H2><A name="Guile_nn10"></A>18.4 Underscore Folding</H2> | |
16601 | <P> Underscores are converted to dashes in identifiers. Guile support | |
16602 | may grow an option to inhibit this folding in the future, but no one | |
16603 | has complained so far.</P> | |
16604 | <P>You can use the SWIG directives <CODE>%name</CODE> and <CODE>%rename</CODE> | |
16605 | to specify the Guile name of the wrapped functions and variables (see | |
16606 | CHANGES).</P> | |
16607 | <H2><A name="Guile_nn11"></A>18.5 Typemaps</H2> | |
16608 | <P> The Guile module handles all types via typemaps. This information is | |
16609 | read from <CODE>Lib/guile/typemaps.i</CODE>. Some non-standard typemap | |
16610 | substitutions are supported:</P> | |
16611 | <UL> | |
16612 | <LI><CODE>$descriptor</CODE> expands to a type descriptor for use with | |
16613 | the <CODE>SWIG_NewPointerObj()</CODE> and <CODE>SWIG_ConvertPtr</CODE> | |
16614 | functions.</LI> | |
16615 | <LI>For pointer types, <CODE>$*descriptor</CODE> expands to a descriptor | |
16616 | for the direct base type (i.e., one pointer is stripped), whereas <CODE> | |
16617 | $basedescriptor</CODE> expands to a descriptor for the base type (i.e., | |
16618 | all pointers are stripped).</LI> | |
16619 | </UL> | |
16620 | <P>A function returning <CODE>void</CODE> (more precisely, a function | |
16621 | whose <CODE>out</CODE> typemap returns <CODE>SCM_UNSPECIFIED</CODE>) is | |
16622 | treated as returning no values. In <CODE>argout</CODE> typemaps, one | |
16623 | can use the macro <CODE>GUILE_APPEND_RESULT</CODE> in order to append a | |
16624 | value to the list of function return values.</P> | |
16625 | <P>Multiple values can be passed up to Scheme in one of three ways:</P> | |
16626 | <UL> | |
16627 | <LI> | |
16628 | <P><EM>Multiple values as lists.</EM> By default, if more than one value | |
16629 | is to be returned, a list of the values is created and returned; to | |
16630 | switch back to this behavior, use</P> | |
16631 | <DIV class="code"> | |
16632 | <PRE> | |
16633 | %values_as_list;</PRE> | |
16634 | </DIV></LI> | |
16635 | <LI> | |
16636 | <P><EM>Multiple values as vectors.</EM> By issuing</P> | |
16637 | <DIV class="code"> | |
16638 | <PRE> | |
16639 | %values_as_vector;</PRE> | |
16640 | </DIV> | |
16641 | <P> vectors instead of lists will be used.</P> | |
16642 | </LI> | |
16643 | <LI> | |
16644 | <P><EM>Multiple values for multiple-value continuations.</EM><STRONG> | |
16645 | This is the most elegant way.</STRONG> By issuing</P> | |
16646 | <DIV class="code"> | |
16647 | <PRE> | |
16648 | %multiple_values;</PRE> | |
16649 | </DIV> | |
16650 | <P> multiple values are passed to the multiple-value continuation, as | |
16651 | created by <CODE>call-with-values</CODE> or the convenience macro <CODE> | |
16652 | receive</CODE>. The latter is available if you issue <CODE>(use-modules | |
16653 | (srfi srfi-8))</CODE>. Assuming that your <CODE>divide</CODE> function | |
16654 | wants to return two values, a quotient and a remainder, you can write:</P> | |
16655 | <DIV class="targetlang"> | |
16656 | <PRE> | |
16657 | (receive (quotient remainder) | |
16658 | (divide 35 17) | |
16659 | <VAR>body</VAR>...) | |
16660 | </PRE> | |
16661 | </DIV> | |
16662 | <P> In <CODE><VAR>body</VAR></CODE>, the first result of <CODE>divide</CODE> | |
16663 | will be bound to the variable <CODE>quotient</CODE>, and the second | |
16664 | result to <CODE>remainder</CODE>.</P> | |
16665 | </LI> | |
16666 | </UL> | |
16667 | <P> See also the "multivalue" example.</P> | |
16668 | <H2><A name="Guile_nn12"></A>18.6 Representation of pointers as smobs</H2> | |
16669 | <P> For pointer types, SWIG uses Guile smobs. SWIG smobs print like | |
16670 | this: <CODE>#<swig struct xyzzy * 0x1234affe></CODE> Two of them are <CODE> | |
16671 | equal?</CODE> if and only if they have the same type and value.</P> | |
16672 | <P> To construct a Scheme object from a C pointer, the wrapper code | |
16673 | calls the function <CODE>SWIG_NewPointerObj()</CODE>, passing a pointer | |
16674 | to a struct representing the pointer type. The type index to store in | |
16675 | the upper half of the CAR is read from this struct. To get the pointer | |
16676 | represented by a smob, the wrapper code calls the function <CODE> | |
16677 | SWIG_ConvertPtr()</CODE>, passing a pointer to a struct representing the | |
16678 | expected pointer type. See also <A href="#runtime_type_checker">The | |
16679 | run-time type checker</A>. If the Scheme object passed was not a SWIG | |
16680 | smob representing a compatible pointer, a <CODE>wrong-type-arg</CODE> | |
16681 | exception is raised.</P> | |
16682 | <H3><A name="Guile_nn13"></A>18.6.1 GH Smobs</H3> | |
16683 | <P> In earlier versions of SWIG, C pointers were represented as Scheme | |
16684 | strings containing a hexadecimal rendering of the pointer value and a | |
16685 | mangled type name. As Guile allows registering user types, so-called | |
16686 | "smobs" (small objects), a much cleaner representation has been | |
16687 | implemented now. The details will be discussed in the following.</P> | |
16688 | <P> A smob is a cons cell where the lower half of the CAR contains the | |
16689 | smob type tag, while the upper half of the CAR and the whole CDR are | |
16690 | available. Every module creates its own smob type in the clientdata | |
16691 | field of the module. So the lower 16 bits of the car of the smob store | |
16692 | the tag and the upper 16 bits store the index this type is in the | |
16693 | array. We can then, given a smob, find its swig_type_info struct by | |
16694 | using the tag (lower 16 bits of car) to find which module this type is | |
16695 | in (since each tag is unique for the module). Then we use the upper 16 | |
16696 | bits to index into the array of types attached to this module. Looking | |
16697 | up the module from the tag is worst case O(# of modules) but average | |
16698 | case O(1). This is because the modules are stored in a circularly | |
16699 | linked list, and when we start searching the modules for the tag, we | |
16700 | start looking with the module that the function doing the lookup is in. | |
16701 | SWIG_Guile_ConvertPtr() takes as its first argument the | |
16702 | swig_module_info * of the calling function, which is where we start | |
16703 | comparing tags. Most types will be looked up in the same module that | |
16704 | created them, so the first module we check will most likely be correct. | |
16705 | Once we have a swig_type_info structure, we loop through the linked | |
16706 | list of casts, using pointer comparisons.</P> | |
16707 | <H3><A name="Guile_nn14"></A>18.6.2 SCM Smobs</H3> | |
16708 | <P>The SCM interface (using the "-scm" argument to swig) uses | |
16709 | swigrun.swg. The whole type system, when it is first initialized, | |
16710 | creates two smobs named "swig" and "collected_swig". The swig smob is | |
16711 | used for non-garbage collected smobs, while the collected_swig smob is | |
16712 | used as described below. Each smob has the same format, which is a | |
16713 | double cell created by SCM_NEWSMOB2() The first word of data is the | |
16714 | pointer to the object and the second word of data is the swig_type_info | |
16715 | * structure describing this type. This is a lot easier than the GH | |
16716 | interface above because we can store a pointer to the type info | |
16717 | structure right in the type. With the GH interface, there was not | |
16718 | enough room in the smob to store two whole words of data so we needed | |
16719 | to store part of the "swig_type_info address" in the smob tag. If a | |
16720 | generated GOOPS module has been loaded, smobs will be wrapped by the | |
16721 | corresponding GOOPS class.</P> | |
16722 | <H3><A name="Guile_nn15"></A>18.6.3 Garbage Collection</H3> | |
16723 | <P>Garbage collection is a feature of the new SCM interface, and it is | |
16724 | automatically included if you pass the "-scm" flag to swig. Thus the | |
16725 | swig garbage collection support requires guile >1.6. Garbage collection | |
16726 | works like this. Every swig_type_info structure stores in its | |
16727 | clientdata field a pointer to the destructor for this type. The | |
16728 | destructor is the generated wrapper around the delete function. So swig | |
16729 | still exports a wrapper for the destructor, it just does not call | |
16730 | scm_c_define_gsubr() for the wrapped delete function. So the only way | |
16731 | to delete an object is from the garbage collector, since the delete | |
16732 | function is not available to scripts. How swig determines if a type | |
16733 | should be garbage collected is exactly like described in <A href="#ownership"> | |
16734 | Object ownership and %newobject</A> in the SWIG manual. All typemaps | |
16735 | use an $owner var, and the guile module replaces $owner with 0 or 1 | |
16736 | depending on feature:new.</P> | |
16737 | <H2><A name="Guile_nn16"></A>18.7 Exception Handling</H2> | |
16738 | <P> SWIG code calls <CODE>scm_error</CODE> on exception, using the | |
16739 | following mapping:<DIV class="code"> | |
16740 | <PRE> | |
16741 | MAP(SWIG_MemoryError, "swig-memory-error"); | |
16742 | MAP(SWIG_IOError, "swig-io-error"); | |
16743 | MAP(SWIG_RuntimeError, "swig-runtime-error"); | |
16744 | MAP(SWIG_IndexError, "swig-index-error"); | |
16745 | MAP(SWIG_TypeError, "swig-type-error"); | |
16746 | MAP(SWIG_DivisionByZero, "swig-division-by-zero"); | |
16747 | MAP(SWIG_OverflowError, "swig-overflow-error"); | |
16748 | MAP(SWIG_SyntaxError, "swig-syntax-error"); | |
16749 | MAP(SWIG_ValueError, "swig-value-error"); | |
16750 | MAP(SWIG_SystemError, "swig-system-error"); | |
16751 | </PRE> | |
16752 | </DIV></P> | |
16753 | <P> The default when not specified here is to use "swig-error". See | |
16754 | Lib/exception.i for details.</P> | |
16755 | <H2><A name="Guile_nn17"></A>18.8 Procedure documentation</H2> | |
16756 | <P>If invoked with the command-line option <CODE>-procdoc<VAR> file</VAR> | |
16757 | </CODE>, SWIG creates documentation strings for the generated wrapper | |
16758 | functions, describing the procedure signature and return value, and | |
16759 | writes them to<VAR> file</VAR>. You need Guile 1.4 or later to make use | |
16760 | of the documentation files.</P> | |
16761 | <P>SWIG can generate documentation strings in three formats, which are | |
16762 | selected via the command-line option <CODE>-procdocformat<VAR> format</VAR> | |
16763 | </CODE>:</P> | |
16764 | <UL> | |
16765 | <LI><CODE>guile-1.4</CODE> (default): Generates a format suitable for | |
16766 | Guile 1.4.</LI> | |
16767 | <LI><CODE>plain</CODE>: Generates a format suitable for Guile 1.4.1 and | |
16768 | later.</LI> | |
16769 | <LI><CODE>texinfo</CODE>: Generates texinfo source, which must be run | |
16770 | through texinfo in order to get a format suitable for Guile 1.4.1 and | |
16771 | later.</LI> | |
16772 | </UL> | |
16773 | <P>You need to register the generated documentation file with Guile like | |
16774 | this:<DIV class="targetlang"> | |
16775 | <PRE> | |
16776 | (use-modules (ice-9 documentation)) | |
16777 | (set! documentation-files | |
16778 | (cons "<VAR>file</VAR>" documentation-files)) | |
16779 | </PRE> | |
16780 | </DIV></P> | |
16781 | <P>Documentation strings can be configured using the Guile-specific | |
16782 | typemap argument <CODE>doc</CODE>. See <CODE>Lib/guile/typemaps.i</CODE> | |
16783 | for details.</P> | |
16784 | <H2><A name="Guile_nn18"></A>18.9 Procedures with setters</H2> | |
16785 | <P>For global variables, SWIG creates a single wrapper procedure <CODE>(<VAR> | |
16786 | variable</VAR> :optional value)</CODE>, which is used for both getting | |
16787 | and setting the value. For struct members, SWIG creates two wrapper | |
16788 | procedures <CODE>(<VAR>struct</VAR>-<VAR>member</VAR>-get pointer)</CODE> | |
16789 | and <CODE>(<VAR>struct-member</VAR>-set pointer value)</CODE>.</P> | |
16790 | <P>If invoked with the command-line option <CODE>-emit-setters</CODE> (<EM> | |
16791 | recommended</EM>), SWIG will additionally create procedures with | |
16792 | setters. For global variables, the procedure-with-setter <CODE><VAR> | |
16793 | variable</VAR></CODE> is created, so you can use <CODE>(<VAR>variable</VAR> | |
16794 | )</CODE> to get the value and <CODE>(set! (<VAR>variable</VAR>)<VAR> | |
16795 | value</VAR>)</CODE> to set it. For struct members, the | |
16796 | procedure-with-setter <CODE><VAR>struct</VAR>-<VAR>member</VAR></CODE> | |
16797 | is created, so you can use <CODE>(<VAR>struct</VAR>-<VAR>member</VAR><VAR> | |
16798 | pointer</VAR>)</CODE> to get the value and <CODE>(set! (<VAR>struct</VAR> | |
16799 | -<VAR>member</VAR><VAR> pointer</VAR>)<VAR> value</VAR>)</CODE> to set | |
16800 | it.</P> | |
16801 | <P>If invoked with the command-line option <CODE>-only-setters</CODE>, | |
16802 | SWIG will<EM> only</EM> create procedures with setters, i.e., for | |
16803 | struct members, the procedures <CODE>(<VAR>struct</VAR>-<VAR>member</VAR> | |
16804 | -get pointer)</CODE> and <CODE>(<VAR>struct-member</VAR>-set pointer | |
16805 | value)</CODE> are<EM> not</EM> generated.</P> | |
16806 | <H2><A name="Guile_nn19"></A>18.10 GOOPS Proxy Classes</H2> | |
16807 | <P>SWIG can also generate classes and generic functions for use with | |
16808 | Guile's Object-Oriented Programming System (GOOPS). GOOPS is a | |
16809 | sophisticated object system in the spirit of the Common Lisp Object | |
16810 | System (CLOS).</P> | |
16811 | <P>GOOPS support is only available with the new SCM interface (enabled | |
16812 | with the <CODE>-scm</CODE> command-line option of SWIG). To enable | |
16813 | GOOPS support, pass the <CODE>-proxy</CODE> argument to swig. This will | |
16814 | export the GOOPS wrapper definitions into the <CODE><I>module</I>.scm</CODE> | |
16815 | file in the directory specified by -outdir or the current directory. | |
16816 | GOOPS support requires either passive or module linkage.</P> | |
16817 | <P>The generated file will contain definitions of GOOPS classes | |
16818 | mimicking the C++ class hierarchy.</P> | |
16819 | <P>Enabling GOOPS support implies <CODE>-emit-setters</CODE>.</P> | |
16820 | <P>If <CODE>-emit-slot-accessors</CODE> is also passed as an argument, | |
16821 | then the generated file will contain accessor methods for all the slots | |
16822 | in the classes and for global variables. The input class</P> | |
16823 | <DIV class="code"> | |
16824 | <PRE> | |
16825 | class Foo { | |
16826 | public: | |
16827 | Foo(int i) : a(i) {} | |
16828 | int a; | |
16829 | int getMultBy(int i) { return a * i; } | |
16830 | Foo getFooMultBy(int i) { return Foo(a * i); } | |
16831 | }; | |
16832 | Foo getFooPlus(int i) { return Foo(a + i); } | |
16833 | </PRE> | |
16834 | </DIV> | |
16835 | <P> will produce (if <CODE>-emit-slot-accessors</CODE> is not passed as | |
16836 | a parameter)</P> | |
16837 | <DIV class="targetlang"> | |
16838 | <PRE> | |
16839 | (define-class <Foo> (<swig>) | |
16840 | (a #:allocation #:swig-virtual | |
16841 | #:slot-ref primitive:Foo-a-get | |
16842 | #:slot-set! primitive:Foo-a-set) | |
16843 | #:metaclass <swig-metaclass> | |
16844 | #:new-function primitive:new-Foo | |
16845 | ) | |
16846 | (define-method (getMultBy (swig_smob <Foo>) i) | |
16847 | (primitive:Foo-getMultBy (slot-ref swig_smob 'smob) i)) | |
16848 | (define-method (getFooMultBy (swig_smob <Foo>) i) | |
16849 | (make <Foo> #:init-smob (primitive:Foo-getFooMultBy (slot-ref swig_smob 'smob) i))) | |
16850 | ||
16851 | (define-method (getFooPlus i) | |
16852 | (make <Foo> #:init-smob (primitive:getFooPlus i))) | |
16853 | ||
16854 | (export <Foo> getMultBy getFooMultBy getFooPlus ) | |
16855 | </PRE> | |
16856 | </DIV> | |
16857 | <P> and will produce (if <CODE>-emit-slot-accessors</CODE> is passed as | |
16858 | a parameter)</P> | |
16859 | <DIV class="targetlang"> | |
16860 | <PRE> | |
16861 | (define-class <Foo> (<swig>) | |
16862 | (a #:allocation #:swig-virtual | |
16863 | #:slot-ref primitive:Foo-a-get | |
16864 | #:slot-set! primitive:Foo-a-set | |
16865 | <B>#:accessor a</B>) | |
16866 | #:metaclass <swig-metaclass> | |
16867 | #:new-function primitive:new-Foo | |
16868 | ) | |
16869 | (define-method (getMultBy (swig_smob <Foo>) i) | |
16870 | (primitive:Foo-getMultBy (slot-ref swig_smob 'smob) i)) | |
16871 | (define-method (getFooMultBy (swig_smob <Foo>) i) | |
16872 | (make <Foo> #:init-smob (primitive:Foo-getFooMultBy (slot-ref swig_smob 'smob) i))) | |
16873 | ||
16874 | (define-method (getFooPlus i) | |
16875 | (make <Foo> #:init-smob (primitive:getFooPlus i))) | |
16876 | ||
16877 | (export <Foo> <B>a</B> getMultBy getFooMultBy getFooPlus ) | |
16878 | </PRE> | |
16879 | </DIV> | |
16880 | <P> which can then be used by this code</P> | |
16881 | <DIV class="targetlang"> | |
16882 | <PRE> | |
16883 | ;; not using getters and setters | |
16884 | (define foo (make <Foo> #:args '(45))) | |
16885 | (slot-ref foo 'a) | |
16886 | (slot-set! foo 'a 3) | |
16887 | (getMultBy foo 4) | |
16888 | (define foo2 (getFooMultBy foo 7)) | |
16889 | (slot-ref foo 'a) | |
16890 | (slot-ref (getFooPlus foo 4) 'a) | |
16891 | ||
16892 | ;; using getters and setters | |
16893 | (define foo (make <Foo> #:args '(45))) | |
16894 | (a foo) | |
16895 | (set! (a foo) 5) | |
16896 | (getMultBy foo 4) | |
16897 | (a (getFooMultBy foo 7)) | |
16898 | </PRE> | |
16899 | </DIV> | |
16900 | <P>Notice that constructor arguments are passed as a list after the <CODE> | |
16901 | #:args</CODE> keyword. Hopefully in the future the following will be | |
16902 | valid <CODE>(make <Foo> #:a 5 #:b 4)</CODE></P> | |
16903 | <P>Also note that the order the declarations occur in the .i file make a | |
16904 | difference. For example,</P> | |
16905 | <DIV class="code"> | |
16906 | <PRE> | |
16907 | %module test | |
16908 | ||
16909 | %{ #include "foo.h" %} | |
16910 | ||
16911 | %inline %{ | |
16912 | int someFunc(Foo &a) { | |
16913 | ... | |
16914 | } | |
16915 | %} | |
16916 | ||
16917 | %include "foo.h" | |
16918 | </PRE> | |
16919 | </DIV> | |
16920 | <P> This is a valid SWIG file it will work as you think it will for | |
16921 | primitive support, but the generated GOOPS file will be broken. Since | |
16922 | the <CODE>someFunc</CODE> definition is parsed by SWIG before all the | |
16923 | declarations in foo.h, the generated GOOPS file will contain the | |
16924 | definition of <CODE>someFunc()</CODE> before the definition of <Foo>. | |
16925 | The generated GOOPS file would look like</P> | |
16926 | <DIV class="targetlang"> | |
16927 | <PRE> | |
16928 | ;;... | |
16929 | ||
16930 | (define-method (someFunc (swig_smob <Foo>)) | |
16931 | (primitive:someFunc (slot-ref swig_smob 'smob))) | |
16932 | ||
16933 | ;;... | |
16934 | ||
16935 | (define-class <Foo> (<swig>) | |
16936 | ;;... | |
16937 | ) | |
16938 | ||
16939 | ;;... | |
16940 | </PRE> | |
16941 | </DIV> | |
16942 | <P> Notice that <Foo> is used before it is defined. The fix is to just | |
16943 | put the <CODE>%import "foo.h"</CODE> before the <CODE>%inline</CODE> | |
16944 | block.</P> | |
16945 | <H3><A name="Guile_nn20"></A>18.10.1 Naming Issues</H3> | |
16946 | <P>As you can see in the example above, there are potential naming | |
16947 | conflicts. The default exported accessor for the <CODE>Foo::a</CODE> | |
16948 | variable is named <CODE>a</CODE>. The name of the wrapper global | |
16949 | function is <CODE>getFooPlus</CODE>. If the <CODE>-useclassprefix</CODE> | |
16950 | option is passed to swig, the name of all accessors and member | |
16951 | functions will be prepended with the class name. So the accessor will | |
16952 | be called <CODE>Foo-a</CODE> and the member functions will be called <CODE> | |
16953 | Foo-getMultBy</CODE>. Also, if the <CODE>-goopsprefix goops:</CODE> | |
16954 | argument is passed to swig, every identifier will be prefixed by <CODE> | |
16955 | goops:</CODE></P> | |
16956 | <P>Two guile-modules are created by SWIG. The first module contains the | |
16957 | primitive definitions of all the wrapped functions and variables, and | |
16958 | is located either in the _wrap.cxx file (with <CODE>-Linkage module</CODE> | |
16959 | ) or in the scmstub file (if <CODE>-Linkage passive -scmstub</CODE>). | |
16960 | The name of this guile-module is the swig-module name (given on the | |
16961 | command line with the -module argument or with the %module directive) | |
16962 | concatenated with the string "-primitive". For example, if <CODE> | |
16963 | %module Test</CODE> is set in the swig interface file, the name of the | |
16964 | guile-module in the scmstub or <CODE>-Linkage module</CODE> will be <CODE> | |
16965 | Test-primitive</CODE>. Also, the scmstub file will be named <CODE> | |
16966 | Test-primitive.scm</CODE>. The string "primitive" can be changed by the <CODE> | |
16967 | -primsuffix</CODE> swig argument. So the same interface, with the <CODE> | |
16968 | -primsuffix base</CODE> will produce a module called <CODE>Test-base</CODE> | |
16969 | . The second generated guile-module contains all the GOOPS class | |
16970 | definitions and is located in a file named<I> module</I>.scm in the | |
16971 | directory specified with -outdir or the current directory. The name of | |
16972 | this guile-module is the name of the swig-module (given on the command | |
16973 | line or with the <CODE>%module</CODE> directive). In the previous | |
16974 | example, the GOOPS definitions will be in a file named Test.scm.</P> | |
16975 | <P>Because of the naming conflicts, you can't in general use both the <CODE> | |
16976 | -primitive</CODE> and the GOOPS guile-modules at the same time. To do | |
16977 | this, you need to rename the exported symbols from one or both | |
16978 | guile-modules. For example,</P> | |
16979 | <DIV class="targetlang"> | |
16980 | <PRE> | |
16981 | (use-modules ((Test-primitive) #:renamer (symbol-prefix-proc 'primitive:))) | |
16982 | (use-modules ((Test) #:renamer (symbol-prefix-proc 'goops:))) | |
16983 | </PRE> | |
16984 | </DIV> | |
16985 | <P>TODO: Renaming class name prefixes?</P> | |
16986 | <H3><A name="Guile_nn21"></A>18.10.2 Linking</H3> | |
16987 | <P>The guile-modules generated above all need to be linked together. | |
16988 | GOOPS support requires either passive or module linkage. The exported | |
16989 | GOOPS guile-module will be the name of the swig-module and should be | |
16990 | located in a file called<I> Module</I>.scm. This should be installed on | |
16991 | the autoload path for guile, so that <CODE>(use-modules (<I>Package | |
16992 | Module</I>))</CODE> will load everything needed. Thus, the top of the | |
16993 | GOOPS guile-module will contain code to load everything needed by the | |
16994 | interface (the shared library, the scmstub module, etc.). The <CODE> | |
16995 | %goops</CODE> directive inserts arbitrary code into the generated GOOPS | |
16996 | guile-module, and should be used to load the dependent libraries.</P> | |
16997 | <P>This breaks up into three cases</P> | |
16998 | <UL> | |
16999 | <LI><B>Passive Linkage without -scmstub</B>: Note that this linkage | |
17000 | style has the potential for naming conflicts, since the primitive | |
17001 | exported function and variable names are not wrapped in a guile-module | |
17002 | and might conflict with names from the GOOPS guile-module (see above). | |
17003 | Pass the -goopsprefix argument to solve this problem. If the <CODE> | |
17004 | -exportprimitive</CODE> option is passed to SWIG the <CODE>(export ...)</CODE> | |
17005 | code that would be exported into the scmstub file is exported at the | |
17006 | bottom of the generated GOOPS guile-module. The <CODE>%goops</CODE> | |
17007 | directive should contain code to load the .so library.<DIV class="code"> | |
17008 | <PRE> | |
17009 | %goops %{ (load-extension "./foo.so" "scm_init_my_modules_foo_module") %} | |
17010 | </PRE> | |
17011 | </DIV> | |
17012 | <P> Produces the following code at the top of the generated GOOPS | |
17013 | guile-module (with the <CODE>-package my/modules -module foo</CODE> | |
17014 | command line arguments)</P> | |
17015 | <DIV class="targetlang"> | |
17016 | <PRE> | |
17017 | (define-module (my modules foo)) | |
17018 | ||
17019 | ;; %goops directive goes here | |
17020 | (load-extension "./foo.so" "scm_init_my_modules_foo_module") | |
17021 | ||
17022 | (use-modules (oop goops) (Swig common)) | |
17023 | </PRE> | |
17024 | </DIV></LI> | |
17025 | <LI> | |
17026 | <P><B>Passive Linkage with -scmstub</B>: Here, the name of the scmstub | |
17027 | file should be <CODE>Module-primitive.scm</CODE> (with<I> primitive</I> | |
17028 | replaced with whatever is given with the <CODE>-primsuffix</CODE> | |
17029 | argument. The code to load the <CODE>.so</CODE> library should be | |
17030 | located in the <CODE>%scheme</CODE> directive, which will then be added | |
17031 | to the scmstub file. Swig will automatically generate the line <CODE> | |
17032 | (use-modules (<I>Package</I><I> Module-primitive</I>))</CODE> into the | |
17033 | GOOPS guile-module. So if<I> Module-primitive.scm</I> is on the | |
17034 | autoload path for guile, the <CODE>%goops</CODE> directive can be | |
17035 | empty. Otherwise, the <CODE>%goops</CODE> directive should contain | |
17036 | whatever code is needed to load the<I> Module-primitive.scm</I> file | |
17037 | into guile.</P> | |
17038 | <DIV class="targetlang"> | |
17039 | <PRE> | |
17040 | %scheme %{ (load-extension "./foo.so" "scm_init_my_modules_foo_module") %} | |
17041 | // only include the following definition if (my modules foo) cannot | |
17042 | // be loaded automatically | |
17043 | %goops %{ | |
17044 | (primitive-load "/path/to/foo-primitive.scm") | |
17045 | (primitive-load "/path/to/Swig/common.scm") | |
17046 | %} | |
17047 | </PRE> | |
17048 | </DIV> | |
17049 | <P> Produces the following code at the top of the generated GOOPS | |
17050 | guile-module</P> | |
17051 | <DIV class="targetlang"> | |
17052 | <PRE> | |
17053 | (define-module (my modules foo)) | |
17054 | ||
17055 | ;; %goops directive goes here (if any) | |
17056 | (primitive-load "/path/to/foo-primitive.scm") | |
17057 | (primitive-load "/path/to/Swig/common.scm") | |
17058 | ||
17059 | (use-modules (oop goops) (Swig common)) | |
17060 | (use-modules ((my modules foo-primitive) :renamer (symbol-prefix-proc | |
17061 | 'primitive:))) | |
17062 | ||
17063 | </PRE> | |
17064 | </DIV></LI> | |
17065 | <LI> | |
17066 | <P><B>Module Linkage</B>: This is very similar to passive linkage with a | |
17067 | scmstub file. Swig will also automatically generate the line <CODE> | |
17068 | (use-modules (<I>Package</I><I> Module-primitive</I>))</CODE> into the | |
17069 | GOOPS guile-module. Again the <CODE>%goops</CODE> directive should | |
17070 | contain whatever code is needed to get that module loaded into guile.</P> | |
17071 | <DIV class="code"> | |
17072 | <PRE> | |
17073 | %goops %{ (load-extension "./foo.so" "scm_init_my_modules_foo_module") %} | |
17074 | </PRE> | |
17075 | </DIV> | |
17076 | <P> Produces the following code at the top of the generated GOOPS | |
17077 | guile-module</P> | |
17078 | <DIV class="targetlang"> | |
17079 | <PRE> | |
17080 | (define-module (my modules foo)) | |
17081 | ||
17082 | ;; %goops directive goes here (if any) | |
17083 | (load-extension "./foo.so" "scm_init_my_modules_foo_module") | |
17084 | ||
17085 | (use-modules (oop goops) (Swig common)) | |
17086 | (use-modules ((my modules foo-primitive) :renamer (symbol-prefix-proc | |
17087 | 'primitive:))) | |
17088 | ||
17089 | </PRE> | |
17090 | </DIV></LI> | |
17091 | </UL> | |
17092 | <P><B>(Swig common)</B>: The generated GOOPS guile-module also imports | |
17093 | definitions from the (Swig common) guile-module. This module is | |
17094 | included with SWIG and should be installed by SWIG into the autoload | |
17095 | path for guile (based on the configure script and whatever arguments | |
17096 | are passed). If it is not, then the <CODE>%goops</CODE> directive also | |
17097 | needs to contain code to load the <CODE>common.scm</CODE> file into | |
17098 | guile. Also note that if you are trying to install the generated | |
17099 | wrappers on a computer without SWIG installed, you will need to include | |
17100 | the common.swg file along with the install.</P> | |
17101 | <P><B>Multiple Modules</B>: Type dependencies between modules is | |
17102 | supported. For example, if <CODE>mod1</CODE> includes definitions of | |
17103 | some classes, and <CODE>mod2</CODE> includes some classes derived from | |
17104 | classes in <CODE>mod1</CODE>, the generated GOOPS file for <CODE>mod2</CODE> | |
17105 | will declare the correct superclasses. The only problem is that since <CODE> | |
17106 | mod2</CODE> uses symbols from <CODE>mod1</CODE>, the <CODE>mod2</CODE> | |
17107 | GOOPS file must include a <CODE>(use-modules (mod2))</CODE>. Currently, | |
17108 | SWIG does not automatically export this line; it must be included in | |
17109 | the <CODE>%goops</CODE> directive of <CODE>mod2</CODE>. Maybe in the | |
17110 | future SWIG can detect dependencies and export this line. (how do other | |
17111 | language modules handle this problem?)</P> | |
17112 | <HR NOSHADE> | |
17113 | <H1><A name="Java"></A>19 SWIG and Java</H1> | |
17114 | ||
17115 | <!-- INDEX --> | |
17116 | <DIV class="sectiontoc"> | |
17117 | <UL> | |
17118 | <LI><A href="#java_overview">Overview</A></LI> | |
17119 | <LI><A href="#java_preliminaries">Preliminaries</A> | |
17120 | <UL> | |
17121 | <LI><A href="#running_swig">Running SWIG</A></LI> | |
17122 | <LI><A href="#java_commandline">Additional Commandline Options</A></LI> | |
17123 | <LI><A href="#getting_right_headers">Getting the right header files</A></LI> | |
17124 | <LI><A href="#compiling_dynamic">Compiling a dynamic module</A></LI> | |
17125 | <LI><A href="#using_module">Using your module</A></LI> | |
17126 | <LI><A href="#dynamic_linking_problems">Dynamic linking problems</A></LI> | |
17127 | <LI><A href="#compilation_problems_cpp">Compilation problems and | |
17128 | compiling with C++</A></LI> | |
17129 | <LI><A href="#building_windows">Building on Windows</A> | |
17130 | <UL> | |
17131 | <LI><A href="#visual_studio">Running SWIG from Visual Studio</A></LI> | |
17132 | <LI><A href="#nmake">Using NMAKE</A></LI> | |
17133 | </UL> | |
17134 | </LI> | |
17135 | </UL> | |
17136 | </LI> | |
17137 | <LI><A href="#java_basic_tour">A tour of basic C/C++ wrapping</A> | |
17138 | <UL> | |
17139 | <LI><A href="#module_packages_classes">Modules, packages and generated | |
17140 | Java classes</A></LI> | |
17141 | <LI><A href="#functions">Functions</A></LI> | |
17142 | <LI><A href="#global_variables">Global variables</A></LI> | |
17143 | <LI><A href="#constants">Constants</A></LI> | |
17144 | <LI><A href="#enumerations">Enumerations</A> | |
17145 | <UL> | |
17146 | <LI><A href="#anonymous_enums">Anonymous enums</A></LI> | |
17147 | <LI><A href="#typesafe_enums">Typesafe enums</A></LI> | |
17148 | <LI><A href="#proper_enums">Proper Java enums</A></LI> | |
17149 | <LI><A href="#typeunsafe_enums">Type unsafe enums</A></LI> | |
17150 | <LI><A href="#simple_enums">Simple enums</A></LI> | |
17151 | </UL> | |
17152 | </LI> | |
17153 | <LI><A href="#pointers">Pointers</A></LI> | |
17154 | <LI><A href="#structures">Structures</A></LI> | |
17155 | <LI><A href="#classes">C++ classes</A></LI> | |
17156 | <LI><A href="#inheritance">C++ inheritance</A></LI> | |
17157 | <LI><A href="#pointers_refs_arrays">Pointers, references, arrays and | |
17158 | pass by value</A> | |
17159 | <UL> | |
17160 | <LI><A href="#null_pointers">Null pointers</A></LI> | |
17161 | </UL> | |
17162 | </LI> | |
17163 | <LI><A href="#overloaded_functions">C++ overloaded functions</A></LI> | |
17164 | <LI><A href="#java_default_arguments">C++ default arguments</A></LI> | |
17165 | <LI><A href="#namespaces">C++ namespaces</A></LI> | |
17166 | <LI><A href="#templates">C++ templates</A></LI> | |
17167 | <LI><A href="#smart_pointers">C++ Smart Pointers</A></LI> | |
17168 | </UL> | |
17169 | </LI> | |
17170 | <LI><A href="#further_details">Further details on the generated Java | |
17171 | classes</A> | |
17172 | <UL> | |
17173 | <LI><A href="#imclass">The intermediary JNI class</A> | |
17174 | <UL> | |
17175 | <LI><A href="#imclass_pragmas">The intermediary JNI class pragmas</A></LI> | |
17176 | </UL> | |
17177 | </LI> | |
17178 | <LI><A href="#java_module_class">The Java module class</A> | |
17179 | <UL> | |
17180 | <LI><A href="#module_class_pragmas">The Java module class pragmas</A></LI> | |
17181 | </UL> | |
17182 | </LI> | |
17183 | <LI><A href="#java_proxy_classes">Java proxy classes</A> | |
17184 | <UL> | |
17185 | <LI><A href="#memory_management">Memory management</A></LI> | |
17186 | <LI><A href="#inheritance_mirroring">Inheritance</A></LI> | |
17187 | <LI><A href="#proxy_classes_gc">Proxy classes and garbage collection</A></LI> | |
17188 | </UL> | |
17189 | </LI> | |
17190 | <LI><A href="#type_wrapper_classes">Type wrapper classes</A></LI> | |
17191 | <LI><A href="#enum_classes">Enum classes</A> | |
17192 | <UL> | |
17193 | <LI><A href="#typesafe_enums_classes">Typesafe enum classes</A></LI> | |
17194 | <LI><A href="#proper_enums_classes">Proper Java enum classes</A></LI> | |
17195 | <LI><A href="#typeunsafe_enums_classes">Type unsafe enum classes</A></LI> | |
17196 | </UL> | |
17197 | </LI> | |
17198 | </UL> | |
17199 | </LI> | |
17200 | <LI><A href="#java_directors">Cross language polymorphism using | |
17201 | directors (experimental)</A> | |
17202 | <UL> | |
17203 | <LI><A href="#java_enabling_directors">Enabling directors</A></LI> | |
17204 | <LI><A href="#java_directors_classes">Director classes</A></LI> | |
17205 | <LI><A href="#java_directors_overhead">Overhead and code bloat</A></LI> | |
17206 | <LI><A href="#java_directors_example">Simple directors example</A></LI> | |
17207 | </UL> | |
17208 | </LI> | |
17209 | <LI><A href="#common_customization">Common customization features</A> | |
17210 | <UL> | |
17211 | <LI><A href="#helper_functions">C/C++ helper functions</A></LI> | |
17212 | <LI><A href="#class_extension">Class extension with %extend</A></LI> | |
17213 | <LI><A href="#exception_handling">Exception handling with %exception and | |
17214 | %javaexception</A></LI> | |
17215 | <LI><A href="#method_access">Method access with %javamethodmodifiers</A></LI> | |
17216 | </UL> | |
17217 | </LI> | |
17218 | <LI><A href="#tips_techniques">Tips and techniques</A> | |
17219 | <UL> | |
17220 | <LI><A href="#input_output_parameters">Input and output parameters using | |
17221 | primitive pointers and references</A></LI> | |
17222 | <LI><A href="#simple_pointers">Simple pointers</A></LI> | |
17223 | <LI><A href="#c_arrays">Wrapping C arrays with Java arrays</A></LI> | |
17224 | <LI><A href="#unbounded_c_arrays">Unbounded C Arrays</A></LI> | |
17225 | </UL> | |
17226 | </LI> | |
17227 | <LI><A href="#java_typemaps">Java typemaps</A> | |
17228 | <UL> | |
17229 | <LI><A href="#default_primitive_type_mappings">Default primitive type | |
17230 | mappings</A></LI> | |
17231 | <LI><A href="#jvm64">Sixty four bit JVMs</A></LI> | |
17232 | <LI><A href="#what_is_typemap">What is a typemap?</A></LI> | |
17233 | <LI><A href="#typemaps_c_to_java_types">Typemaps for mapping C/C++ types | |
17234 | to Java types</A></LI> | |
17235 | <LI><A href="#typemap_attributes">Java typemap attributes</A></LI> | |
17236 | <LI><A href="#special_variables">Java special variables</A></LI> | |
17237 | <LI><A href="#typemaps_for_c_and_c++">Typemaps for both C and C++ | |
17238 | compilation</A></LI> | |
17239 | <LI><A href="#java_code_typemaps">Java code typemaps</A></LI> | |
17240 | <LI><A href="#java_directors_typemaps">Director specific typemaps</A></LI> | |
17241 | </UL> | |
17242 | </LI> | |
17243 | <LI><A href="#typemap_examples">Typemap Examples</A> | |
17244 | <UL> | |
17245 | <LI><A href="#simpler_enum_classes">Simpler Java enums for enums without | |
17246 | initializers</A></LI> | |
17247 | <LI><A href="#exception_typemap">Handling C++ exception specifications | |
17248 | as Java exceptions</A></LI> | |
17249 | <LI><A href="#nan_exception_typemap">NaN Exception - exception handling | |
17250 | for a particular type</A></LI> | |
17251 | <LI><A href="#converting_java_string_arrays">Converting Java String | |
17252 | arrays to char **</A></LI> | |
17253 | <LI><A href="#expanding_java_object">Expanding a Java object to multiple | |
17254 | arguments</A></LI> | |
17255 | <LI><A href="#using_typemaps_return_arguments">Using typemaps to return | |
17256 | arguments</A></LI> | |
17257 | <LI><A href="#adding_downcasts">Adding Java downcasts to polymorphic | |
17258 | return types</A></LI> | |
17259 | <LI><A href="#adding_equals_method">Adding an equals method to the Java | |
17260 | classes</A></LI> | |
17261 | <LI><A href="#void_pointers">Void pointers and a common Java base class</A> | |
17262 | </LI> | |
17263 | <LI><A href="#struct_pointer_pointer">Struct pointer to pointer</A></LI> | |
17264 | </UL> | |
17265 | </LI> | |
17266 | <LI><A href="#java_directors_faq">Living with Java Directors</A></LI> | |
17267 | <LI><A href="#odds_ends">Odds and ends</A> | |
17268 | <UL> | |
17269 | <LI><A href="#javadoc_comments">JavaDoc comments</A></LI> | |
17270 | <LI><A href="#functional_interface">Functional interface without proxy | |
17271 | classes</A></LI> | |
17272 | <LI><A href="#using_own_jni_functions">Using your own JNI functions</A></LI> | |
17273 | <LI><A href="#performance">Performance concerns and hints</A></LI> | |
17274 | </UL> | |
17275 | </LI> | |
17276 | <LI><A href="#java_examples">Examples</A></LI> | |
17277 | </UL> | |
17278 | </DIV> | |
17279 | <!-- INDEX --> | |
17280 | <P> This chapter describes SWIG's support of Java. It covers most SWIG | |
17281 | features, but certain low-level details are covered in less depth than | |
17282 | in earlier chapters.</P> | |
17283 | <H2><A name="java_overview"></A>19.1 Overview</H2> | |
17284 | <P> The 100% Pure Java effort is a commendable concept, however in the | |
17285 | real world programmers often either need to re-use their existing code | |
17286 | or in some situations want to take advantage of Java but are forced | |
17287 | into using some native (C/C++) code. The Java extension to SWIG makes | |
17288 | it very easy to plumb in existing C/C++ code for access from Java, as | |
17289 | SWIG writes the Java Native Interface (JNI) code for you. It is | |
17290 | different to using the 'javah' tool as SWIG will wrap existing C/C++ | |
17291 | code, whereas javah takes 'native' Java function declarations and | |
17292 | creates C/C++ function prototypes. SWIG wraps C/C++ code using Java | |
17293 | proxy classes and is very useful if you want to have access to large | |
17294 | amounts of C/C++ code from Java. If only one or two JNI functions are | |
17295 | needed then using SWIG may be overkill. SWIG enables a Java program to | |
17296 | easily call into C/C++ code from Java. Historically, SWIG was not able | |
17297 | to generate any code to call into Java code from C++. However, SWIG now | |
17298 | supports full cross language polymorphism and code is generated to call | |
17299 | up from C++ to Java when wrapping C++ virtual methods.</P> | |
17300 | <P> Java is one of the few non-scripting language modules in SWIG. As | |
17301 | SWIG utilizes the type safety that the Java language offers, it takes a | |
17302 | somewhat different approach to that used for scripting languages. In | |
17303 | particular runtime type checking and the runtime library are not used | |
17304 | by Java. This should be borne in mind when reading the rest of the SWIG | |
17305 | documentation. This chapter on Java is relatively self contained and | |
17306 | will provide you with nearly everything you need for using SWIG and | |
17307 | Java. However, the "<A href="#SWIG">SWIG Basics</A>" chapter will be a | |
17308 | useful read in conjunction with this one.</P> | |
17309 | <P> This chapter starts with a few practicalities on running SWIG and | |
17310 | compiling the generated code. If you are looking for the minimum amount | |
17311 | to read, have a look at the sections up to and including the <A href="#java_basic_tour"> | |
17312 | tour of basic C/C++ wrapping</A> section which explains how to call the | |
17313 | various C/C++ code constructs from Java. Following this section are | |
17314 | details of the C/C++ code and Java classes that SWIG generates. Due to | |
17315 | the complexities of C and C++ there are different ways in which C/C++ | |
17316 | code could be wrapped and called from Java. SWIG is a powerful tool and | |
17317 | the rest of the chapter details how the default code wrapping can be | |
17318 | tailored. Various customisation tips and techniques using SWIG | |
17319 | directives are covered. The latter sections cover the advanced | |
17320 | techniques of using typemaps for complete control of the wrapping | |
17321 | process.</P> | |
17322 | <H2><A name="java_preliminaries"></A>19.2 Preliminaries</H2> | |
17323 | <P> SWIG 1.1 works with JDKs from JDK 1.1 to JDK1.4 (Java 2 SDK1.4) and | |
17324 | should also work with any later versions. Given the choice, you should | |
17325 | probably use the latest version of Sun's JDK. The SWIG Java module is | |
17326 | known to work using Sun's JVM on Solaris, Linux and the various | |
17327 | flavours of Microsoft Windows including Cygwin. The Kaffe JVM is known | |
17328 | to give a few problems and at the time of writing was not a fully | |
17329 | fledged JVM with full JNI support. The generated code is also known to | |
17330 | work on vxWorks using WindRiver's PJava 3.1. The best way to determine | |
17331 | whether your combination of operating system and JDK will work is to | |
17332 | test the examples and test-suite that comes with SWIG. Run <TT>make -k | |
17333 | check</TT> from the SWIG root directory after installing SWIG on Unix | |
17334 | systems.</P> | |
17335 | <P> The Java module requires your system to support shared libraries and | |
17336 | dynamic loading. This is the commonly used method to load JNI code so | |
17337 | your system will more than likely support this.</P> | |
17338 | <H3><A name="running_swig"></A>19.2.1 Running SWIG</H3> | |
17339 | <P> Suppose that you defined a SWIG module such as the following:</P> | |
17340 | <DIV class="code"> | |
17341 | <PRE> | |
17342 | %module example | |
17343 | %{ | |
17344 | #include "header.h" | |
17345 | %} | |
17346 | int fact(int n); | |
17347 | </PRE> | |
17348 | </DIV> | |
17349 | <P> To build a Java module, run SWIG using the <TT>-java</TT> option :</P> | |
17350 | <DIV class="code"> | |
17351 | <PRE> | |
17352 | %swig -java example.i | |
17353 | </PRE> | |
17354 | </DIV> | |
17355 | <P> If building C++, add the <TT>-c++</TT> option:</P> | |
17356 | <DIV class="code"> | |
17357 | <PRE> | |
17358 | $ swig -c++ -java example.i | |
17359 | </PRE> | |
17360 | </DIV> | |
17361 | <P> This creates two different files; a C/C++ source file <TT> | |
17362 | example_wrap.c</TT> or <TT>example_wrap.cxx</TT> and numerous Java | |
17363 | files. The generated C/C++ source file contains the JNI wrapper code | |
17364 | that needs to be compiled and linked with the rest of your C/C++ | |
17365 | application.</P> | |
17366 | <P> The name of the wrapper file is derived from the name of the input | |
17367 | file. For example, if the input file is <TT>example.i</TT>, the name of | |
17368 | the wrapper file is <TT>example_wrap.c</TT>. To change this, you can | |
17369 | use the <TT>-o</TT> option. It is also possible to change the <A href="#output"> | |
17370 | output directory</A> that the Java files are generated into using <TT> | |
17371 | -outdir</TT>.</P> | |
17372 | <H3><A name="java_commandline"></A>19.2.2 Additional Commandline Options</H3> | |
17373 | <P> The following table list the additional commandline options | |
17374 | available for the Java module. They can also be seen by using:</P> | |
17375 | <DIV class="code"> | |
17376 | <PRE> | |
17377 | swig -java -help | |
17378 | </PRE> | |
17379 | </DIV> | |
17380 | <TABLE summary="Java specific options"> | |
17381 | <TR><TH>Java specific options</TH></TR> | |
17382 | <TR><TD>-package <name></TD><TD>set name of the Java package to <name></TD> | |
17383 | </TR> | |
17384 | <TR><TD>-noproxy</TD><TD>generate the low-level functional interface | |
17385 | instead of proxy classes</TD></TR> | |
17386 | </TABLE> | |
17387 | <P> Their use will become clearer by the time you have finished reading | |
17388 | this section on SWIG and Java.</P> | |
17389 | <H3><A name="getting_right_headers"></A>19.2.3 Getting the right header | |
17390 | files</H3> | |
17391 | <P> In order to compile the C/C++ wrappers, the compiler needs the <TT> | |
17392 | jni.h</TT> and <TT>jni_md.h</TT> header files which are part of the JDK. | |
17393 | They are usually in directories like this:</P> | |
17394 | <DIV class="code"> | |
17395 | <PRE> | |
17396 | /usr/java/include | |
17397 | /usr/java/include/<operating_system> | |
17398 | </PRE> | |
17399 | </DIV> | |
17400 | <P> The exact location may vary on your machine, but the above locations | |
17401 | are typical.</P> | |
17402 | <H3><A name="compiling_dynamic"></A>19.2.4 Compiling a dynamic module</H3> | |
17403 | <P> The JNI code exists in a dynamic module or shared library (DLL on | |
17404 | Windows) and gets loaded by the JVM. To build a shared library file, | |
17405 | you need to compile your module in a manner similar to the following | |
17406 | (shown for Solaris):</P> | |
17407 | <DIV class="code"> | |
17408 | <PRE> | |
17409 | $ swig -java example.i | |
17410 | $ gcc -c example_wrap.c -I/usr/java/include -I/usr/java/include/solaris | |
17411 | $ ld -G example_wrap.o -o libexample.so | |
17412 | </PRE> | |
17413 | </DIV> | |
17414 | <P> The exact commands for doing this vary from platform to platform. | |
17415 | However, SWIG tries to guess the right options when it is installed. | |
17416 | Therefore, you may want to start with one of the examples in the <TT> | |
17417 | Examples/java</TT> directory. If that doesn't work, you will need to | |
17418 | read the man-pages for your compiler and linker to get the right set of | |
17419 | options. You might also check the <A href="http://swig.cs.uchicago.edu/cgi-bin/wiki.pl"> | |
17420 | SWIG Wiki</A> for additional information.</P> | |
17421 | <P> The name of the shared library output file is important. If the name | |
17422 | of your SWIG module is "<TT>example</TT>", the name of the | |
17423 | corresponding shared library file should be "<TT>libexample.so</TT>" | |
17424 | (or equivalent depending on your machine, see <A href="#dynamic_linking_problems"> | |
17425 | Dynamic linking problems</A> for more information). The name of the | |
17426 | module is specified using the <TT>%module</TT> directive or <TT>-module</TT> | |
17427 | command line option.</P> | |
17428 | <H3><A name="using_module"></A>19.2.5 Using your module</H3> | |
17429 | <P> To load your shared native library module in Java, simply use Java's | |
17430 | <TT>System.loadLibrary</TT> method in a Java class:</P> | |
17431 | <DIV class="code"> | |
17432 | <PRE> | |
17433 | // main.java | |
17434 | ||
17435 | public class main { | |
17436 | static { | |
17437 | System.loadLibrary("example"); | |
17438 | } | |
17439 | ||
17440 | public static void main(String argv[]) { | |
17441 | System.out.println(example.fact(4)); | |
17442 | } | |
17443 | } | |
17444 | </PRE> | |
17445 | </DIV> | |
17446 | <P> Compile all the Java files and run:</P> | |
17447 | <DIV class="code"> | |
17448 | <PRE> | |
17449 | $ javac *.java | |
17450 | $ java main | |
17451 | 24 | |
17452 | $ | |
17453 | </PRE> | |
17454 | </DIV> | |
17455 | <P> If it doesn't work have a look at the following section which | |
17456 | discusses problems loading the shared library.</P> | |
17457 | <H3><A name="dynamic_linking_problems"></A>19.2.6 Dynamic linking | |
17458 | problems</H3> | |
17459 | <P> As shown in the previous section the code to load a native library | |
17460 | (shared library) is <TT>System.loadLibrary("name")</TT>. This can fail | |
17461 | with an UnsatisfiedLinkError exception and can be due to a number of | |
17462 | reasons.</P> | |
17463 | <P> You may get an exception similar to this:</P> | |
17464 | <DIV class="code"> | |
17465 | <PRE> | |
17466 | $ java main | |
17467 | Exception in thread "main" java.lang.UnsatisfiedLinkError: no example in java.library.path | |
17468 | at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1312) | |
17469 | at java.lang.Runtime.loadLibrary0(Runtime.java:749) | |
17470 | at java.lang.System.loadLibrary(System.java:820) | |
17471 | at main.<clinit>(main.java:5) | |
17472 | </PRE> | |
17473 | </DIV> | |
17474 | <P> The most common cause for this is an incorrect naming of the native | |
17475 | library for the name passed to the <TT>loadLibrary</TT> function. The | |
17476 | string passed to the <TT>loadLibrary</TT> function must not include the | |
17477 | file extension name in the string, that is<I> .dll</I> or<I> .so</I>. | |
17478 | The string must be<I> name</I> and not<I> libname</I> for all | |
17479 | platforms. On Windows the native library must then be called<I> | |
17480 | name.dll</I> and on most Unix systems it must be called<I> libname.so</I> | |
17481 | .</P> | |
17482 | <P> Another common reason for the native library not loading is because | |
17483 | it is not in your path. On Windows make sure the<I> path</I> | |
17484 | environment variable contains the path to the native library. On Unix | |
17485 | make sure that your<I> LD_LIBRARY_PATH</I> contains the path to the | |
17486 | native library. Adding paths to<I> LD_LIBRARY_PATH</I> can slow down | |
17487 | other programs on your system so you may want to consider alternative | |
17488 | approaches. For example you could recompile your native library with | |
17489 | extra path information using <TT>-rpath</TT> if you're using GNU, see | |
17490 | the GNU linker documentation (<TT>ld</TT> man page). You could use a | |
17491 | command such as <TT>ldconfig</TT> (Linux) or <TT>crle</TT> (Solaris) to | |
17492 | add additional search paths to the default system configuration (this | |
17493 | requires root access and you will need to read the man pages).</P> | |
17494 | <P> The native library will also not load if there are any unresolved | |
17495 | symbols in the compiled C/C++ code. The following exception is | |
17496 | indicative of this:</P> | |
17497 | <DIV class="code"> | |
17498 | <PRE> | |
17499 | $ java main | |
17500 | Exception in thread "main" java.lang.UnsatisfiedLinkError: libexample.so: undefined | |
17501 | symbol: fact | |
17502 | at java.lang.ClassLoader$NativeLibrary.load(Native Method) | |
17503 | at java.lang.ClassLoader.loadLibrary0(ClassLoader.java, Compiled Code) | |
17504 | at java.lang.ClassLoader.loadLibrary(ClassLoader.java, Compiled Code) | |
17505 | at java.lang.Runtime.loadLibrary0(Runtime.java, Compiled Code) | |
17506 | at java.lang.System.loadLibrary(System.java, Compiled Code) | |
17507 | at main.<clinit>(main.java:5) | |
17508 | $ | |
17509 | </PRE> | |
17510 | </DIV> | |
17511 | <P> This error usually indicates that you forgot to include some object | |
17512 | files or libraries in the linking of the native library file. Make sure | |
17513 | you compile both the SWIG wrapper file and the code you are wrapping | |
17514 | into the native library file. Also make sure you pass all of the | |
17515 | required libraries to the linker. The <TT>java -verbose:jni</TT> | |
17516 | commandline switch is also a great way to get more information on | |
17517 | unresolved symbols. One last piece of advice is to beware of the common | |
17518 | faux pas of having more than one native library version in your path.</P> | |
17519 | <P> In summary, ensure that you are using the correct C/C++ compiler and | |
17520 | linker combination and options for successful native library loading. | |
17521 | If you are using the examples that ship with SWIG, then the | |
17522 | Examples/Makefile must have these set up correctly for your system. The | |
17523 | SWIG installation package makes a best attempt at getting these correct | |
17524 | but does not get it right 100% of the time. The <A href="http://swig.cs.uchicago.edu/cgi-bin/wiki.pl"> | |
17525 | SWIG Wiki</A> also has some settings for commonly used compiler and | |
17526 | operating system combinations. The following section also contains some | |
17527 | C++ specific linking problems and solutions.</P> | |
17528 | <H3><A name="compilation_problems_cpp"></A>19.2.7 Compilation problems | |
17529 | and compiling with C++</H3> | |
17530 | <P> On most machines, shared library files should be linked using the | |
17531 | C++ compiler. For example:</P> | |
17532 | <DIV class="code"> | |
17533 | <PRE> | |
17534 | % swig -c++ -java example.i | |
17535 | % g++ -c -fpic example.cxx | |
17536 | % g++ -c -fpic example_wrap.cxx -I/usr/java/j2sdk1.4.1/include -I/usr/java/ | |
17537 | j2sdk1.4.1/include/linux | |
17538 | % g++ -shared example.o example_wrap.o -o libexample.so | |
17539 | </PRE> | |
17540 | </DIV> | |
17541 | <P> In addition to this, you may need to include additional library | |
17542 | files to make it work. For example, if you are using the Sun C++ | |
17543 | compiler on Solaris, you often need to add an extra library <TT>-lCrun</TT> | |
17544 | like this:</P> | |
17545 | <DIV class="code"> | |
17546 | <PRE> | |
17547 | % swig -c++ -java example.i | |
17548 | % CC -c example.cxx | |
17549 | % CC -c example_wrap.cxx -I/usr/java/include -I/usr/java/include/solaris | |
17550 | % CC -G example.o example_wrap.o -L/opt/SUNWspro/lib -o libexample.so -lCrun | |
17551 | </PRE> | |
17552 | </DIV> | |
17553 | <P> If you aren't entirely sure about the linking for C++, you might | |
17554 | look at an existing C++ program. On many Unix machines, the <TT>ldd</TT> | |
17555 | command will list library dependencies. This should give you some clues | |
17556 | about what you might have to include when you link your shared library. | |
17557 | For example:</P> | |
17558 | <DIV class="code"> | |
17559 | <PRE> | |
17560 | $ ldd swig | |
17561 | libstdc++-libc6.1-1.so.2 => /usr/lib/libstdc++-libc6.1-1.so.2 (0x40019000) | |
17562 | libm.so.6 => /lib/libm.so.6 (0x4005b000) | |
17563 | libc.so.6 => /lib/libc.so.6 (0x40077000) | |
17564 | /lib/ld-linux.so.2 => /lib/ld-linux.so.2 (0x40000000) | |
17565 | $ | |
17566 | </PRE> | |
17567 | </DIV> | |
17568 | <P> Finally make sure the version of JDK header files matches the | |
17569 | version of Java that you are running as incompatibilities could lead to | |
17570 | compilation problems or unpredictable behaviour.</P> | |
17571 | <H3><A name="building_windows"></A>19.2.8 Building on Windows</H3> | |
17572 | <P> Building on Windows is roughly similar to the process used with | |
17573 | Unix. You will want to produce a DLL that can be loaded by the Java | |
17574 | Virtual Machine. This section covers the process of using SWIG with | |
17575 | Microsoft Visual C++ 6 although the procedure may be similar with other | |
17576 | compilers. In order for everything to work, you will need to have a JDK | |
17577 | installed on your machine in order to read the JNI header files.</P> | |
17578 | <H4><A name="visual_studio"></A>19.2.8.1 Running SWIG from Visual Studio</H4> | |
17579 | <P> If you are developing your application within Microsoft Visual | |
17580 | studio, SWIG can be invoked as a custom build option. The Examples\java | |
17581 | directory has a few <A href="#examples">Windows Examples</A> containing | |
17582 | Visual Studio project (.dsp) files. The process to re-create the | |
17583 | project files for a C project are roughly:</P> | |
17584 | <UL> | |
17585 | <LI>Open up a new workspace and use the AppWizard to select a DLL | |
17586 | project.</LI> | |
17587 | <LI>Add both the SWIG interface file (the .i file), any supporting C | |
17588 | files, and the name of the wrapper file that will be created by SWIG | |
17589 | (ie. <TT>example_wrap.c</TT>). Don't worry if the wrapper file doesn't | |
17590 | exist yet--Visual Studio will keep a reference to it.</LI> | |
17591 | <LI>Select the SWIG interface file and go to the settings menu. Under | |
17592 | settings, select the "Custom Build" option.</LI> | |
17593 | <LI>Enter "SWIG" in the description field.</LI> | |
17594 | <LI>Enter "<TT>swig -java -o $(ProjDir)\$(InputName)_wrap.c $(InputPath)</TT> | |
17595 | " in the "Build command(s) field"</LI> | |
17596 | <LI>Enter "<TT>$(ProjDir)\$(InputName)_wrap.c</TT>" in the "Output | |
17597 | files(s) field".</LI> | |
17598 | <LI>Next, select the settings for the entire project and go to C/C++ tab | |
17599 | and select the Preprocessor category . Add the include directories to | |
17600 | the JNI header files under "Additional include directories", eg | |
17601 | "C:\jdk1.3\include,C:\jdk1.3\include\win32".</LI> | |
17602 | <LI>Next, select the settings for the entire project and go to Link tab | |
17603 | and select the General category. Set the name of the output file to | |
17604 | match the name of your Java module (ie. example.dll).</LI> | |
17605 | <LI>Next, select the example.c and example_wrap.c files and go to the | |
17606 | C/C++ tab and select the Precompiled Headers tab in the project | |
17607 | settings. Disabling precompiled headers for these files will overcome | |
17608 | any precompiled header errors while building.</LI> | |
17609 | <LI>Finally, add the java compilation as a post build rule in the | |
17610 | Post-build step tab in project settings, eg, "c:\jdk1.3\bin\javac | |
17611 | *.java"</LI> | |
17612 | <LI>Build your project.</LI> | |
17613 | </UL> | |
17614 | <P> Note: If using C++, choose a C++ suffix for the wrapper file, for | |
17615 | example <TT>example_wrap.cxx</TT>. Use <TT>_wrap.cxx</TT> instead of <TT> | |
17616 | _wrap.c</TT> in the instructions above and add -c++ when invoking swig.</P> | |
17617 | <P> Now, assuming all went well, SWIG will be automatically invoked when | |
17618 | you build your project. When doing a build, any changes made to the | |
17619 | interface file will result in SWIG being automatically invoked to | |
17620 | produce a new version of the wrapper file.</P> | |
17621 | <P> The Java classes that SWIG output should also be compiled into | |
17622 | .class files. To run the native code in the DLL (example.dll), make | |
17623 | sure that it is in your path then run your Java program which uses it, | |
17624 | as described in the previous section. If the library fails to load have | |
17625 | a look at <A href="#dynamic_linking_problems">Dynamic linking problems</A> | |
17626 | .</P> | |
17627 | <H4><A name="nmake"></A>19.2.8.2 Using NMAKE</H4> | |
17628 | <P> Alternatively, a Makefile for use by NMAKE can be written. Make sure | |
17629 | the environment variables for MSVC++ are available and the MSVC++ tools | |
17630 | are in your path. Now, just write a short Makefile like this :</P> | |
17631 | <DIV class="code"> | |
17632 | <PRE> | |
17633 | # Makefile for using SWIG and Java for C code | |
17634 | ||
17635 | SRCS = example.c | |
17636 | IFILE = example | |
17637 | INTERFACE = $(IFILE).i | |
17638 | WRAPFILE = $(IFILE)_wrap.c | |
17639 | ||
17640 | # Location of the Visual C++ tools (32 bit assumed) | |
17641 | ||
17642 | TOOLS = c:\msdev | |
17643 | TARGET = example.dll | |
17644 | CC = $(TOOLS)\bin\cl.exe | |
17645 | LINK = $(TOOLS)\bin\link.exe | |
17646 | INCLUDE32 = -I$(TOOLS)\include | |
17647 | MACHINE = IX86 | |
17648 | ||
17649 | # C Library needed to build a DLL | |
17650 | ||
17651 | DLLIBC = msvcrt.lib oldnames.lib | |
17652 | ||
17653 | # Windows libraries that are apparently needed | |
17654 | WINLIB = kernel32.lib advapi32.lib user32.lib gdi32.lib comdlg32.lib winspool.lib | |
17655 | ||
17656 | # Libraries common to all DLLs | |
17657 | LIBS = $(DLLIBC) $(WINLIB) | |
17658 | ||
17659 | # Linker options | |
17660 | LOPT = -debug:full -debugtype:cv /NODEFAULTLIB /RELEASE /NOLOGO \ | |
17661 | /MACHINE:$(MACHINE) -entry:_DllMainCRTStartup@12 -dll | |
17662 | ||
17663 | # C compiler flags | |
17664 | ||
17665 | CFLAGS = /Z7 /Od /c /nologo | |
17666 | JAVA_INCLUDE = -ID:\jdk1.3\include -ID:\jdk1.3\include\win32 | |
17667 | ||
17668 | java:: | |
17669 | swig -java -o $(WRAPFILE) $(INTERFACE) | |
17670 | $(CC) $(CFLAGS) $(JAVA_INCLUDE) $(SRCS) $(WRAPFILE) | |
17671 | set LIB=$(TOOLS)\lib | |
17672 | $(LINK) $(LOPT) -out:example.dll $(LIBS) example.obj example_wrap.obj | |
17673 | javac *.java | |
17674 | </PRE> | |
17675 | </DIV> | |
17676 | <P> To build the DLL and compile the java code, run NMAKE (you may need | |
17677 | to run <TT>vcvars32</TT> first). This is a pretty simplistic Makefile, | |
17678 | but hopefully its enough to get you started. Of course you may want to | |
17679 | make changes for it to work for C++ by adding in the -c++ command line | |
17680 | switch for swig and replacing .c with .cxx.</P> | |
17681 | <H2><A name="java_basic_tour"></A>19.3 A tour of basic C/C++ wrapping</H2> | |
17682 | <P> By default, SWIG attempts to build a natural Java interface to your | |
17683 | C/C++ code. Functions are wrapped as functions, classes are wrapped as | |
17684 | classes, variables are wrapped with JavaBean type getters and setters | |
17685 | and so forth. This section briefly covers the essential aspects of this | |
17686 | wrapping.</P> | |
17687 | <H3><A name="module_packages_classes"></A>19.3.1 Modules, packages and | |
17688 | generated Java classes</H3> | |
17689 | <P> The SWIG <TT>%module</TT> directive specifies the name of the Java | |
17690 | module. When you specify `<TT>%module example</TT>', the<I> module name</I> | |
17691 | determines the name of some of the generated files in the module. The | |
17692 | generated code consists of a<I> module class</I> file <TT>example.java</TT> | |
17693 | , an<I> intermediary JNI class</I> file, <TT>exampleJNI.java</TT> as | |
17694 | well as numerous other Java<I> proxy class</I> files. Each proxy class | |
17695 | is named after the structs, unions and classes you are wrapping. You | |
17696 | may also get a<I> constants interface</I> file if you are wrapping any | |
17697 | unnamed enumerations or constants, for example <TT> | |
17698 | exampleConstants.java</TT>. When choosing a module name, make sure you | |
17699 | don't use the same name as one of the generated proxy class files nor a | |
17700 | Java keyword. Sometimes a C/C++ type cannot be wrapped by a proxy | |
17701 | class, for example a pointer to a primitive type. In these situations a<I> | |
17702 | type wrapper class</I> is generated. Wrapping an enum generates an<I> | |
17703 | enum class</I>, either a proper Java enum or a Java class that | |
17704 | simulates the enums pattern. Details of all these generated classes | |
17705 | will unfold as you read this section.</P> | |
17706 | <P> The JNI (C/C++) code is generated into a file which also contains | |
17707 | the module name, for example <TT>example_wrap.cxx</TT> or <TT> | |
17708 | example_wrap.c</TT>. These C or C++ files complete the contents of the | |
17709 | module.</P> | |
17710 | <P> The generated Java classes can be placed into a Java package by | |
17711 | using the <TT>-package</TT> commandline option. This is often combined | |
17712 | with the <TT>-outdir</TT> to specify a package directory for generating | |
17713 | the Java files.</P> | |
17714 | <DIV class="code"> | |
17715 | <PRE> | |
17716 | swig -java -package com.bloggs.swig -outdir com/bloggs/swig example.i | |
17717 | </PRE> | |
17718 | </DIV> SWIG won't create the directory, so make sure it exists | |
17719 | beforehand. | |
17720 | <H3><A name="functions"></A>19.3.2 Functions</H3> | |
17721 | <P> There is no such thing as a global Java function so global C | |
17722 | functions are wrapped as static methods in the module class. For | |
17723 | example,</P> | |
17724 | <DIV class="code"> | |
17725 | <PRE> | |
17726 | %module example | |
17727 | int fact(int n); | |
17728 | ||
17729 | </PRE> | |
17730 | </DIV> | |
17731 | <P> creates a static function that works exactly like you think it | |
17732 | might:</P> | |
17733 | <DIV class="code"> | |
17734 | <PRE> | |
17735 | public class example { | |
17736 | public static int fact(int n) { | |
17737 | // makes call using JNI to the C function | |
17738 | } | |
17739 | } | |
17740 | </PRE> | |
17741 | </DIV> | |
17742 | <P> The Java class <TT>example</TT> is the<I> module class</I>. The | |
17743 | function can be used as follows from Java:</P> | |
17744 | <DIV class="code"> | |
17745 | <PRE> | |
17746 | System.out.println(example.fact(4)); | |
17747 | </PRE> | |
17748 | </DIV> | |
17749 | <H3><A name="global_variables"></A>19.3.3 Global variables</H3> | |
17750 | <P> C/C++ global variables are fully supported by SWIG. Java does not | |
17751 | allow the overriding of the dot operator so all variables are accessed | |
17752 | through getters and setters. Again because there is no such thing as a | |
17753 | Java global variable, access to C/C++ global variables is done through | |
17754 | static getter and setter functions in the module class.</P> | |
17755 | <DIV class="code"> | |
17756 | <PRE> | |
17757 | // SWIG interface file with global variables | |
17758 | %module example | |
17759 | ... | |
17760 | %inline %{ | |
17761 | extern int My_variable; | |
17762 | extern double density; | |
17763 | %} | |
17764 | ... | |
17765 | </PRE> | |
17766 | </DIV> | |
17767 | <P> Now in Java :</P> | |
17768 | <DIV class="code"> | |
17769 | <PRE> | |
17770 | // Print out value of a C global variable | |
17771 | System.out.println("My_variable = " + example.getMy_variable()); | |
17772 | // Set the value of a C global variable | |
17773 | example.setDensity(0.8442); | |
17774 | </PRE> | |
17775 | </DIV> | |
17776 | <P> The value returned by the getter will always be up to date even if | |
17777 | the value is changed in C. Note that the getters and setters produced | |
17778 | follow the JavaBean property design pattern. That is the first letter | |
17779 | of the variable name is capitalized and preceded with set or get. If | |
17780 | you have the misfortune of wrapping two variables that differ only in | |
17781 | the capitalization of their first letters, use %rename to change one of | |
17782 | the variable names. For example:</P> | |
17783 | <DIV class="code"> | |
17784 | <PRE> | |
17785 | %rename Clash RenamedClash; | |
17786 | float Clash; | |
17787 | int clash; | |
17788 | </PRE> | |
17789 | </DIV> | |
17790 | <P> If a variable is declared as <TT>const</TT>, it is wrapped as a | |
17791 | read-only variable. That is only a getter is produced.</P> | |
17792 | <P> To make ordinary variables read-only, you can use the <TT>%immutable</TT> | |
17793 | directive. For example:</P> | |
17794 | <DIV class="code"> | |
17795 | <PRE> | |
17796 | %{ | |
17797 | extern char *path; | |
17798 | %} | |
17799 | %immutable; | |
17800 | extern char *path; | |
17801 | %mutable; | |
17802 | </PRE> | |
17803 | </DIV> | |
17804 | <P> The <TT>%immutable</TT> directive stays in effect until it is | |
17805 | explicitly disabled or cleared using <TT>%mutable</TT>. See the <A href="#SWIG_readonly_variables"> | |
17806 | Creatng read-only variables</A> section for further details.</P> | |
17807 | <P> If you just want to make a specific variable immutable, supply a | |
17808 | declaration name. For example:</P> | |
17809 | <DIV class="code"> | |
17810 | <PRE> | |
17811 | %{ | |
17812 | extern char *path; | |
17813 | %} | |
17814 | %immutable path; | |
17815 | ... | |
17816 | extern char *path; // Read-only (due to %immutable) | |
17817 | </PRE> | |
17818 | </DIV> | |
17819 | <H3><A name="constants"></A>19.3.4 Constants</H3> | |
17820 | <P> C/C++ constants are wrapped as Java static final variables. To | |
17821 | create a constant, use <TT>#define</TT> or the <TT>%constant</TT> | |
17822 | directive. For example:</P> | |
17823 | <DIV class="code"> | |
17824 | <PRE> | |
17825 | #define PI 3.14159 | |
17826 | #define VERSION "1.0" | |
17827 | %constant int FOO = 42; | |
17828 | %constant const char *path = "/usr/local"; | |
17829 | </PRE> | |
17830 | </DIV> | |
17831 | <P> By default the generated static final variables are initialized by | |
17832 | making a JNI call to get their value. The constants are generated into | |
17833 | the constants interface and look like this:</P> | |
17834 | <DIV class="code"> | |
17835 | <PRE> | |
17836 | public interface exampleConstants { | |
17837 | public final static double PI = exampleJNI.PI_get(); | |
17838 | public final static String VERSION = exampleJNI.VERSION_get(); | |
17839 | public final static int FOO = exampleJNI.FOO_get(); | |
17840 | public final static String path = exampleJNI.path_get(); | |
17841 | } | |
17842 | </PRE> | |
17843 | </DIV> | |
17844 | <P> Note that SWIG has inferred the C type and used an appropriate Java | |
17845 | type that will fit the range of all possible values for the C type. By | |
17846 | default SWIG generates<B> runtime constants</B>. They are not<B> | |
17847 | compiler constants</B> that can, for example, be used in a switch | |
17848 | statement. This can be changed by using the <TT>%javaconst(flag)</TT> | |
17849 | directive. It works like all the other <A href="#features">%feature | |
17850 | directives</A>. The default is <TT>%javaconst(0)</TT>. It is possible | |
17851 | to initialize all wrapped constants from pure Java code by placing a <TT> | |
17852 | %javaconst(1)</TT><B> before</B> SWIG parses the constants. Putting it | |
17853 | at the top of your interface file would ensure this. Here is an | |
17854 | example:</P> | |
17855 | <DIV class="code"> | |
17856 | <PRE> | |
17857 | %javaconst(1); | |
17858 | %javaconst(0) BIG; | |
17859 | %javaconst(0) LARGE; | |
17860 | ||
17861 | #define EXPRESSION (0x100+5) | |
17862 | #define BIG 1000LL | |
17863 | #define LARGE 2000ULL | |
17864 | </PRE> | |
17865 | </DIV> | |
17866 | <P> generates:</P> | |
17867 | <DIV class="code"> | |
17868 | <PRE> | |
17869 | public interface exampleConstants { | |
17870 | public final static int EXPRESSION = (0x100+5); | |
17871 | public final static long BIG = exampleJNI.BIG_get(); | |
17872 | public final static java.math.BigInteger LARGE = exampleJNI.LARGE_get(); | |
17873 | } | |
17874 | </PRE> | |
17875 | </DIV> | |
17876 | <P> Note that SWIG has inferred the C <TT>long long</TT> type from <TT> | |
17877 | BIG</TT> and used an appropriate Java type (<TT>long</TT>) as a Java <TT> | |
17878 | long</TT> is the smallest sized Java type that will take all possible | |
17879 | values for a C <TT>long long</TT>. Similarly for <TT>LARGE</TT>.</P> | |
17880 | <P> Be careful using the <TT>%javaconst(1)</TT> directive as not all C | |
17881 | code will compile as Java code. For example neither the <TT>1000LL</TT> | |
17882 | value for <TT>BIG</TT> nor <TT>2000ULL</TT> for <TT>LARGE</TT> above | |
17883 | would generate valid Java code. The example demonstrates how you can | |
17884 | target particular constants (<TT>BIG</TT> and <TT>LARGE</TT>) with <TT> | |
17885 | %javaconst</TT>. SWIG doesn't use <TT>%javaconst(1)</TT> as the default | |
17886 | as it tries to generate code that will always compile. However, using a | |
17887 | <TT>%javaconst(1)</TT> at the top of your interface file is strongly | |
17888 | recommended as the preferred compile time constants will be generated | |
17889 | and most C constants will compile as Java code and in anycase the odd | |
17890 | constant that doesn't can be fixed using <TT>%javaconst(0)</TT>.</P> | |
17891 | <P> There is an alternative directive which can be used for these rare | |
17892 | constant values that won't compile as Java code. This is the <TT> | |
17893 | %javaconstvalue(value)</TT> directive, where <TT>value</TT> is a Java | |
17894 | code replacement for the C constant and can be either a string or a | |
17895 | number. This is useful if you do not want to use either the parsed C | |
17896 | value nor a JNI call, such as when the C parsed value will not compile | |
17897 | as Java code and a compile time constant is required. The same example | |
17898 | demonstrates this:</P> | |
17899 | <DIV class="code"> | |
17900 | <PRE> | |
17901 | %javaconst(1); | |
17902 | %javaconstvalue("new java.math.BigInteger(\"2000\")") LARGE; | |
17903 | %javaconstvalue(1000) BIG; | |
17904 | ||
17905 | #define EXPRESSION (0x100+5) | |
17906 | #define BIG 1000LL | |
17907 | #define LARGE 2000ULL | |
17908 | </PRE> | |
17909 | </DIV> | |
17910 | <P> Note the string quotes for <TT>"2000"</TT> are escaped. The | |
17911 | following is then generated:</P> | |
17912 | <DIV class="code"> | |
17913 | <PRE> | |
17914 | public interface exampleConstants { | |
17915 | public final static int EXPRESSION = (0x100+5); | |
17916 | public final static long BIG = 1000; | |
17917 | public final static java.math.BigInteger LARGE = new java.math.BigInteger("2000"); | |
17918 | } | |
17919 | </PRE> | |
17920 | </DIV> | |
17921 | <P> Note: declarations declared as <TT>const</TT> are wrapped as | |
17922 | read-only variables and will be accessed using a getter as described in | |
17923 | the previous section. They are not wrapped as constants.</P> | |
17924 | <P><B> Compatibility Note:</B> In SWIG-1.3.19 and earlier releases, the | |
17925 | constants were generated into the module class and the constants | |
17926 | interface didn't exist. Backwards compatibility is maintained as the | |
17927 | module class implements the constants interface (even though some | |
17928 | consider this type of interface implementation to be bad practice):</P> | |
17929 | <DIV class="code"> | |
17930 | <PRE> | |
17931 | public class example implements exampleConstants { | |
17932 | } | |
17933 | </PRE> | |
17934 | </DIV> | |
17935 | <P> You thus have the choice of accessing these constants from either | |
17936 | the module class or the constants interface, for example, <TT> | |
17937 | example.EXPRESSION</TT> or <TT>exampleConstants.EXPRESSION</TT>. Or if | |
17938 | you decide this practice isn't so bad and your own class implements <TT> | |
17939 | exampleConstants</TT>, you can of course just use <TT>EXPRESSION</TT>.</P> | |
17940 | <H3><A name="enumerations"></A>19.3.5 Enumerations</H3> | |
17941 | <P> SWIG handles both named and unnamed (anonymous) enumerations. There | |
17942 | is a choice of approaches to wrapping named C/C++ enums. This is due to | |
17943 | historical reasons as SWIG's initial support for enums was limited and | |
17944 | Java did not originally have support for enums. Each approach has | |
17945 | advantages and disadvantages and it is important for the user to decide | |
17946 | which is the most appropriate solution. There are four approaches of | |
17947 | which the first is the default approach based on the so called Java | |
17948 | typesafe enum pattern. The second generates proper Java enums. The | |
17949 | final two approaches use simple integers for each enum item. Before | |
17950 | looking at the various approaches for wrapping named C/C++ enums, | |
17951 | anonymous enums are considered.</P> | |
17952 | <H4><A name="anonymous_enums"></A>19.3.5.1 Anonymous enums</H4> | |
17953 | <P> There is no name for anonymous enums and so they are handled like | |
17954 | constants. For example:</P> | |
17955 | <DIV class="code"> | |
17956 | <PRE> | |
17957 | enum { ALE, LAGER=10, STOUT, PILSNER }; | |
17958 | </PRE> | |
17959 | </DIV> | |
17960 | <P> is wrapped into the constants interface, in a similar manner as | |
17961 | constants (see previous section):</P> | |
17962 | <DIV class="code"> | |
17963 | <PRE> | |
17964 | public interface exampleConstants { | |
17965 | public final static int ALE = exampleJNI.ALE_get(); | |
17966 | public final static int LAGER = exampleJNI.LAGER_get(); | |
17967 | public final static int STOUT = exampleJNI.STOUT_get(); | |
17968 | public final static int PILSNER = exampleJNI.PILSNER_get(); | |
17969 | } | |
17970 | </PRE> | |
17971 | </DIV> | |
17972 | <P> The <TT>%javaconst(flag)</TT> and <TT>%javaconstvalue(value)</TT> | |
17973 | directive introduced in the previous section on constants can also be | |
17974 | used with enums. As is the case for constants, the default is <TT> | |
17975 | %javaconst(0)</TT> as not all C values will compile as Java code. | |
17976 | However, it is strongly recommended to add in a <TT>%javaconst(1)</TT> | |
17977 | directive at the top of your interface file as it is only on very rare | |
17978 | occasions that this will produce code that won't compile under Java. | |
17979 | Using <TT>%javaconst(1)</TT> will ensure compile time constants are | |
17980 | generated, thereby allowing the enum values to be used in Java switch | |
17981 | statements. Example usage:</P> | |
17982 | <DIV class="code"> | |
17983 | <PRE> | |
17984 | %javaconst(1); | |
17985 | %javaconst(0) PILSNER; | |
17986 | enum { ALE, LAGER=10, STOUT, PILSNER }; | |
17987 | </PRE> | |
17988 | </DIV> | |
17989 | <P> generates:</P> | |
17990 | <DIV class="code"> | |
17991 | <PRE> | |
17992 | public interface exampleConstants { | |
17993 | public final static int ALE = 0; | |
17994 | public final static int LAGER = 10; | |
17995 | public final static int STOUT = LAGER+1; | |
17996 | public final static int PILSNER = exampleJNI.PILSNER_get(); | |
17997 | } | |
17998 | </PRE> | |
17999 | </DIV> | |
18000 | <P> As in the case of constants, you can access them through either the | |
18001 | module class or the constants interface, for example, <TT>example.ALE</TT> | |
18002 | or <TT>exampleConstants.ALE</TT>.</P> | |
18003 | <H4><A name="typesafe_enums"></A>19.3.5.2 Typesafe enums</H4> | |
18004 | <P> This is the default approach to wrapping named enums. The typesafe | |
18005 | enum pattern is a relatively well known construct to work around the | |
18006 | lack of enums in versions of Java prior to Java 2 SDK 1.5. It basically | |
18007 | defines a class for the enumeration and permits a limited number of | |
18008 | final static instances of the class. Each instance equates to an enum | |
18009 | item within the enumeration. The implementation is in the | |
18010 | "enumtypesafe.swg" file. Let's look at an example:</P> | |
18011 | <DIV class="code"> | |
18012 | <PRE> | |
18013 | %include "enumtypesafe.swg" // optional as typesafe enums are the default | |
18014 | enum Beverage { ALE, LAGER=10, STOUT, PILSNER }; | |
18015 | </PRE> | |
18016 | </DIV> | |
18017 | <P>will generate:</P> | |
18018 | <DIV class="code"> | |
18019 | <PRE> | |
18020 | public final class Beverage { | |
18021 | public final static Beverage ALE = new Beverage("ALE"); | |
18022 | public final static Beverage LAGER = new Beverage("LAGER", exampleJNI.LAGER_get()); | |
18023 | public final static Beverage STOUT = new Beverage("STOUT"); | |
18024 | public final static Beverage PILSNER = new Beverage("PILSNER"); | |
18025 | [... additional support methods omitted for brevity ...] | |
18026 | } | |
18027 | </PRE> | |
18028 | </DIV> | |
18029 | <P> See <A href="#typesafe_enums_classes">Typesafe enum classes</A> to | |
18030 | see the omitted support methods. Note that the enum item with an | |
18031 | initializer (LAGER) is initialized with the enum value obtained via a | |
18032 | JNI call. However, as with anonymous enums and constants, use of the <TT> | |
18033 | %javaconst</TT> directive is strongly recommended to change this | |
18034 | behaviour:</P> | |
18035 | <DIV class="code"> | |
18036 | <PRE> | |
18037 | %include "enumtypesafe.swg" // optional as typesafe enums are the default | |
18038 | %javaconst(1); | |
18039 | enum Beverage { ALE, LAGER=10, STOUT, PILSNER }; | |
18040 | </PRE> | |
18041 | </DIV> | |
18042 | <P> will generate:</P> | |
18043 | <DIV class="code"> | |
18044 | <PRE> | |
18045 | public final class Beverage { | |
18046 | public final static Beverage ALE = new Beverage("ALE"); | |
18047 | public final static Beverage LAGER = new Beverage("LAGER", 10); | |
18048 | public final static Beverage STOUT = new Beverage("STOUT"); | |
18049 | public final static Beverage PILSNER = new Beverage("PILSNER"); | |
18050 | [... additional support methods omitted for brevity ...] | |
18051 | } | |
18052 | </PRE> | |
18053 | </DIV> | |
18054 | <P> The generated code is easier to read and more efficient as a true | |
18055 | constant is used instead of a JNI call. As is the case for constants, | |
18056 | the default is <TT>%javaconst(0)</TT> as not all C values will compile | |
18057 | as Java code. However, it is recommended to add in a <TT>%javaconst(1)</TT> | |
18058 | directive at the top of your interface file as it is only on very rare | |
18059 | occasions that this will produce code that won't compile under Java. | |
18060 | The <TT>%javaconstvalue(value)</TT> directive can also be used for | |
18061 | typesafe enums. Note that global enums are generated into a Java class | |
18062 | within whatever package you are using. C++ enums defined within a C++ | |
18063 | class are generated into a static final inner Java class within the | |
18064 | Java proxy class.</P> | |
18065 | <P> Typesafe enums have their advantages over using plain integers in | |
18066 | that they they can be used in a typesafe manner. However, there are | |
18067 | limitations. For example, they cannot be used in switch statements and | |
18068 | serialization is an issue. Please look at the following references for | |
18069 | further information: <A href="http://java.sun.com/developer/Books/shiftintojava/page1.html#replaceenums"> | |
18070 | Replace Enums with Classes</A> in<I> Effective Java Programming</I> on | |
18071 | the Sun website, <A href="http://www.javaworld.com/javaworld/jw-07-1997/jw-07-enumerated.html"> | |
18072 | Create enumerated constants in Java</A> JavaWorld article, <A href="http://www.javaworld.com/javaworld/javatips/jw-javatip133.html"> | |
18073 | Java Tip 133: More on typesafe enums</A> and <A href="http://www.javaworld.com/javaworld/javatips/jw-javatip122.html"> | |
18074 | Java Tip 122: Beware of Java typesafe enumerations</A> JavaWorld tips.</P> | |
18075 | <P> Note that the syntax required for using typesafe enums is the same | |
18076 | as that for proper Java enums. This is useful during the period that a | |
18077 | project has to support legacy versions of Java. When upgrading to J2SDK | |
18078 | 1.5 or later, proper Java enums could be used instead, without users | |
18079 | having to change their code. The following section details proper Java | |
18080 | enum generation.</P> | |
18081 | <H4><A name="proper_enums"></A>19.3.5.3 Proper Java enums</H4> | |
18082 | <P> Proper Java enums were only introduced in Java 2 SDK 1.5 so this | |
18083 | approach is only compatible with more recent versions of Java. Java | |
18084 | enums have been designed to overcome all the limitations of both | |
18085 | typesafe and type unsafe enums and should be the choice solution, | |
18086 | provided older versions of Java do not have to be supported. In this | |
18087 | approach, each named C/C++ enum is wrapped by a Java enum. Java enums, | |
18088 | by default, do not support enums with initializers. Java enums are in | |
18089 | many respects similar to Java classes in that they can be customised | |
18090 | with additional methods. SWIG takes advantage of this feature to | |
18091 | facilitate wrapping C/C++ enums that have initializers. In order to | |
18092 | wrap all possible C/C++ enums using proper Java enums, the "enums.swg" | |
18093 | file must be used. Let's take a look at an example.</P> | |
18094 | <DIV class="code"> | |
18095 | <PRE> | |
18096 | %include "enums.swg" | |
18097 | %javaconst(1); | |
18098 | enum Beverage { ALE, LAGER=10, STOUT, PILSNER }; | |
18099 | </PRE> | |
18100 | </DIV> | |
18101 | <P> will generate:</P> | |
18102 | <DIV class="code"> | |
18103 | <PRE> | |
18104 | public enum Beverage { | |
18105 | ALE, | |
18106 | LAGER(10), | |
18107 | STOUT, | |
18108 | PILSNER; | |
18109 | [... additional support methods omitted for brevity ...] | |
18110 | } | |
18111 | </PRE> | |
18112 | </DIV> | |
18113 | <P> See <A href="#proper_enums_classes">Proper Java enum classes</A> to | |
18114 | see the omitted support methods. The generated Java enum has numerous | |
18115 | additional methods to support enums with initializers, such as <TT> | |
18116 | LAGER</TT> above. Note that as with the typesafe enum pattern, enum | |
18117 | items with initializers are by default initialized with the enum value | |
18118 | obtained via a JNI call. However, this is not the case above as we have | |
18119 | used the recommended <TT>%javaconst(1)</TT> to avoid the JNI call. The <TT> | |
18120 | %javaconstvalue(value)</TT> directive covered in the <A href="#constants"> | |
18121 | Constants</A> section can also be used for proper Java enums.</P> | |
18122 | <P> The additional support methods need not be generated if none of the | |
18123 | enum items have initializers and this is covered later in the <A href="#simpler_enum_classes"> | |
18124 | Simpler Java enums for enums without initializers</A> section.</P> | |
18125 | <H4><A name="typeunsafe_enums"></A>19.3.5.4 Type unsafe enums</H4> | |
18126 | <P> In this approach each enum item in a named enumeration is wrapped as | |
18127 | a static final integer in a class named after the C/C++ enum name. This | |
18128 | is a commonly used pattern in Java to simulate C/C++ enums, but it is | |
18129 | not typesafe. However, the main advantage over the typesafe enum | |
18130 | pattern is enum items can be used in switch statements. In order to use | |
18131 | this approach, the "enumtypeunsafe.swg" file must be used. Let's take a | |
18132 | look at an example.</P> | |
18133 | <DIV class="code"> | |
18134 | <PRE> | |
18135 | %include "enumtypeunsafe.swg" | |
18136 | %javaconst(1); | |
18137 | enum Beverage { ALE, LAGER=10, STOUT, PILSNER }; | |
18138 | </PRE> | |
18139 | </DIV> | |
18140 | <P> will generate:</P> | |
18141 | <DIV class="code"> | |
18142 | <PRE> | |
18143 | public final class Beverage { | |
18144 | public final static int ALE = 0; | |
18145 | public final static int LAGER = 10; | |
18146 | public final static int STOUT = LAGER + 1; | |
18147 | public final static int PILSNER = STOUT + 1; | |
18148 | } | |
18149 | </PRE> | |
18150 | </DIV> | |
18151 | <P> As is the case previously, the default is <TT>%javaconst(0)</TT> as | |
18152 | not all C/C++ values will compile as Java code. However, again it is | |
18153 | recommended to add in a <TT>%javaconst(1)</TT> directive. and the <TT> | |
18154 | %javaconstvalue(value)</TT> directive covered in the <A href="#constants"> | |
18155 | Constants</A> section can also be used for type unsafe enums. Note that | |
18156 | global enums are generated into a Java class within whatever package | |
18157 | you are using. C++ enums defined within a C++ class are generated into | |
18158 | a static final inner Java class within the Java proxy class.</P> | |
18159 | <P> Note that unlike typesafe enums, this approach requires users to | |
18160 | mostly use different syntax compared with proper Java enums. Thus the | |
18161 | upgrade path to proper enums provided in J2SDK 1.5 is more painful.</P> | |
18162 | <H4><A name="simple_enums"></A>19.3.5.5 Simple enums</H4> | |
18163 | <P> This approach is similar to the type unsafe approach. Each enum item | |
18164 | is also wrapped as a static final integer. However, these integers are | |
18165 | not generated into a class named after the C/C++ enum. Instead, global | |
18166 | enums are generated into the constants interface. Also, enums defined | |
18167 | in a C++ class have their enum items generated directly into the Java | |
18168 | proxy class rather than an inner class within the Java proxy class. In | |
18169 | fact, this approach is effectively wrapping the enums as if they were | |
18170 | anonymous enums and the resulting code is as per <A href="#anonymous_enums"> | |
18171 | anonymous enums</A>. The implementation is in the "enumsimple.swg" file.</P> | |
18172 | <P><B> Compatibility Note:</B> SWIG-1.3.21 and earlier versions wrapped | |
18173 | all enums using this approach. The type unsafe approach is preferable | |
18174 | to this one and this simple approach is only included for backwards | |
18175 | compatibility with these earlier versions of SWIG.</P> | |
18176 | <H3><A name="pointers"></A>19.3.6 Pointers</H3> | |
18177 | <P> C/C++ pointers are fully supported by SWIG. Furthermore, SWIG has no | |
18178 | problem working with incomplete type information. Here is a rather | |
18179 | simple interface:</P> | |
18180 | <DIV class="code"> | |
18181 | <PRE> | |
18182 | %module example | |
18183 | ||
18184 | FILE *fopen(const char *filename, const char *mode); | |
18185 | int fputs(const char *, FILE *); | |
18186 | int fclose(FILE *); | |
18187 | </PRE> | |
18188 | </DIV> | |
18189 | <P> When wrapped, you will be able to use the functions in a natural way | |
18190 | from Java. For example:</P> | |
18191 | <DIV class="code"> | |
18192 | <PRE> | |
18193 | SWIGTYPE_p_FILE f = example.fopen("junk","w"); | |
18194 | example.fputs("Hello World\n", f); | |
18195 | example.fclose(f); | |
18196 | </PRE> | |
18197 | </DIV> | |
18198 | <P> C pointers in the Java module are stored in a Java <TT>long</TT> and | |
18199 | cross the JNI boundary held within this 64 bit number. Many other SWIG | |
18200 | language modules use an encoding of the pointer in a string. These | |
18201 | scripting languages use the SWIG runtime type checker for dynamic type | |
18202 | checking as they do not support static type checking by a compiler. In | |
18203 | order to implement static type checking of pointers within Java, they | |
18204 | are wrapped by a simple Java class. In the example above the <TT>FILE *</TT> | |
18205 | pointer is wrapped with a<I> type wrapper class</I> called <TT> | |
18206 | SWIGTYPE_p_FILE</TT>.</P> | |
18207 | <P> Once obtained, a type wrapper object can be freely passed around to | |
18208 | different C functions that expect to receive an object of that type. | |
18209 | The only thing you can't do is dereference the pointer from Java. Of | |
18210 | course, that isn't much of a concern in this example.</P> | |
18211 | <P> As much as you might be inclined to modify a pointer value directly | |
18212 | from Java, don't. The value is not necessarily the same as the logical | |
18213 | memory address of the underlying object. The value will vary depending | |
18214 | on the native byte-ordering of the platform (i.e., big-endian vs. | |
18215 | little-endian). Most JVMs are 32 bit applications so any JNI code must | |
18216 | also be compiled as 32 bit. The net result is pointers in JNI code are | |
18217 | also 32 bits and are stored in the high order 4 bytes on big-endian | |
18218 | machines and in the low order 4 bytes on little-endian machines. By | |
18219 | design it is also not possible to manually cast a pointer to a new type | |
18220 | by using Java casts as it is particularly dangerous especially when | |
18221 | casting C++ objects. If you need to cast a pointer or change its value, | |
18222 | consider writing some helper functions instead. For example:</P> | |
18223 | <DIV class="code"> | |
18224 | <PRE> | |
18225 | %inline %{ | |
18226 | /* C-style cast */ | |
18227 | Bar *FooToBar(Foo *f) { | |
18228 | return (Bar *) f; | |
18229 | } | |
18230 | ||
18231 | /* C++-style cast */ | |
18232 | Foo *BarToFoo(Bar *b) { | |
18233 | return dynamic_cast<Foo*>(b); | |
18234 | } | |
18235 | ||
18236 | Foo *IncrFoo(Foo *f, int i) { | |
18237 | return f+i; | |
18238 | } | |
18239 | %} | |
18240 | </PRE> | |
18241 | </DIV> | |
18242 | <P> Also, if working with C++, you should always try to use the new C++ | |
18243 | style casts. For example, in the above code, the C-style cast may | |
18244 | return a bogus result whereas as the C++-style cast will return a NULL | |
18245 | pointer if the conversion can't be performed.</P> | |
18246 | <H3><A name="structures"></A>19.3.7 Structures</H3> | |
18247 | <P> If you wrap a C structure, it is wrapped by a Java class with | |
18248 | getters and setters for access to the member variables. For example,</P> | |
18249 | <DIV class="code"> | |
18250 | <PRE> | |
18251 | struct Vector { | |
18252 | double x,y,z; | |
18253 | }; | |
18254 | ||
18255 | </PRE> | |
18256 | </DIV> | |
18257 | <P> is used as follows:</P> | |
18258 | <DIV class="code"> | |
18259 | <PRE> | |
18260 | Vector v = new Vector(); | |
18261 | v.setX(3.5); | |
18262 | v.setY(7.2); | |
18263 | double x = v.getX(); | |
18264 | double y = v.getY(); | |
18265 | </PRE> | |
18266 | </DIV> | |
18267 | <P> The variable setters and getters are also based on the JavaBean | |
18268 | design pattern already covered under the Global variables section. | |
18269 | Similar access is provided for unions and the public data members of | |
18270 | C++ classes.</P> | |
18271 | <P> This object is actually an instance of a Java class that has been | |
18272 | wrapped around a pointer to the C structure. This instance doesn't | |
18273 | actually do anything--it just serves as a proxy. The pointer to the C | |
18274 | object is held in the Java proxy class in much the same way as pointers | |
18275 | are held by type wrapper classes. Further details about Java proxy | |
18276 | classes are covered a little later.</P> | |
18277 | <P> <TT>const</TT> members of a structure are read-only. Data members | |
18278 | can also be forced to be read-only using the <TT>%immutable</TT> | |
18279 | directive. For example:</P> | |
18280 | <DIV class="code"> | |
18281 | <PRE> | |
18282 | struct Foo { | |
18283 | ... | |
18284 | %immutable; | |
18285 | int x; /* Read-only members */ | |
18286 | char *name; | |
18287 | %mutable; | |
18288 | ... | |
18289 | }; | |
18290 | </PRE> | |
18291 | </DIV> | |
18292 | <P> When <TT>char *</TT> members of a structure are wrapped, the | |
18293 | contents are assumed to be dynamically allocated using <TT>malloc</TT> | |
18294 | or <TT>new</TT> (depending on whether or not SWIG is run with the -c++ | |
18295 | option). When the structure member is set, the old contents will be | |
18296 | released and a new value created. If this is not the behavior you want, | |
18297 | you will have to use a typemap (described later).</P> | |
18298 | <P> If a structure contains arrays, access to those arrays is managed | |
18299 | through pointers. For example, consider this:</P> | |
18300 | <DIV class="code"> | |
18301 | <PRE> | |
18302 | struct Bar { | |
18303 | int x[16]; | |
18304 | }; | |
18305 | </PRE> | |
18306 | </DIV> | |
18307 | <P> If accessed in Java, you will see behavior like this:</P> | |
18308 | <DIV class="code"> | |
18309 | <PRE> | |
18310 | Bar b = new Bar(); | |
18311 | SWIGTYPE_p_int x = b.getX(); | |
18312 | </PRE> | |
18313 | </DIV> | |
18314 | <P> This pointer can be passed around to functions that expect to | |
18315 | receive an <TT>int *</TT> (just like C). You can also set the value of | |
18316 | an array member using another pointer. For example:</P> | |
18317 | <DIV class="code"> | |
18318 | <PRE> | |
18319 | Bar b = new Bar(); | |
18320 | SWIGTYPE_p_int x = b.getX(); | |
18321 | Bar c = new Bar(); | |
18322 | c.setX(x); // Copy contents of b.x to c.x | |
18323 | </PRE> | |
18324 | </DIV> | |
18325 | <P> For array assignment (setters not getters), SWIG copies the entire | |
18326 | contents of the array starting with the data pointed to by <TT>b.x</TT> | |
18327 | . In this example, 16 integers would be copied. Like C, SWIG makes no | |
18328 | assumptions about bounds checking---if you pass a bad pointer, you may | |
18329 | get a segmentation fault or access violation. The default wrapping | |
18330 | makes it hard to set or get just one element of the array and so array | |
18331 | access from Java is somewhat limited. This can be changed easily though | |
18332 | by using the approach outlined later in the <A href="#c_arrays"> | |
18333 | Wrapping C arrays with Java arrays</A> and <A href="#unbounded_c_arrays"> | |
18334 | Unbounded C Arrays</A> sections.</P> | |
18335 | <P> When a member of a structure is itself a structure, it is handled as | |
18336 | a pointer. For example, suppose you have two structures like this:</P> | |
18337 | <DIV class="code"> | |
18338 | <PRE> | |
18339 | struct Foo { | |
18340 | int a; | |
18341 | }; | |
18342 | ||
18343 | struct Bar { | |
18344 | Foo f; | |
18345 | }; | |
18346 | </PRE> | |
18347 | </DIV> | |
18348 | <P> Now, suppose that you access the <TT>f</TT> member of <TT>Bar</TT> | |
18349 | like this:</P> | |
18350 | <DIV class="code"> | |
18351 | <PRE> | |
18352 | Bar b = new Bar(); | |
18353 | Foo x = b.getF(); | |
18354 | </PRE> | |
18355 | </DIV> | |
18356 | <P> In this case, <TT>x</TT> is a pointer that points to the <TT>Foo</TT> | |
18357 | that is inside <TT>b</TT>. This is the same value as generated by this | |
18358 | C code:</P> | |
18359 | <DIV class="code"> | |
18360 | <PRE> | |
18361 | Bar b; | |
18362 | Foo *x = &b->f; /* Points inside b */ | |
18363 | </PRE> | |
18364 | </DIV> | |
18365 | <P> Because the pointer points inside the structure, you can modify the | |
18366 | contents and everything works just like you would expect. For example:</P> | |
18367 | <DIV class="code"> | |
18368 | <PRE> | |
18369 | Bar b = new Bar(); | |
18370 | b.getF().setA(3); // Modify b.f.a | |
18371 | Foo x = b.getF(); | |
18372 | x.setA(3); // Modify x.a - this is the same as b.f.a | |
18373 | </PRE> | |
18374 | </DIV> | |
18375 | <H3><A name="classes"></A>19.3.8 C++ classes</H3> | |
18376 | <P> C++ classes are wrapped by Java classes as well. For example, if you | |
18377 | have this class,</P> | |
18378 | <DIV class="code"> | |
18379 | <PRE> | |
18380 | class List { | |
18381 | public: | |
18382 | List(); | |
18383 | ~List(); | |
18384 | int search(char *item); | |
18385 | void insert(char *item); | |
18386 | void remove(char *item); | |
18387 | char *get(int n); | |
18388 | int length; | |
18389 | }; | |
18390 | </PRE> | |
18391 | </DIV> | |
18392 | <P> you can use it in Java like this:</P> | |
18393 | <DIV class="code"> | |
18394 | <PRE> | |
18395 | List l = new List(); | |
18396 | l.insert("Ale"); | |
18397 | l.insert("Stout"); | |
18398 | l.insert("Lager"); | |
18399 | String item = l.get(2); | |
18400 | int length = l.getLength(); | |
18401 | </PRE> | |
18402 | </DIV> | |
18403 | <P> Class data members are accessed in the same manner as C structures.</P> | |
18404 | <P> Static class members are unsurprisingly wrapped as static members of | |
18405 | the Java class:</P> | |
18406 | <DIV class="code"> | |
18407 | <PRE> | |
18408 | class Spam { | |
18409 | public: | |
18410 | static void foo(); | |
18411 | static int bar; | |
18412 | }; | |
18413 | </PRE> | |
18414 | </DIV> | |
18415 | <P> The static members work like any other Java static member:</P> | |
18416 | <DIV class="code"> | |
18417 | <PRE> | |
18418 | Spam.foo(); | |
18419 | int bar = Spam.getBar(); | |
18420 | </PRE> | |
18421 | </DIV> | |
18422 | <H3><A name="inheritance"></A>19.3.9 C++ inheritance</H3> | |
18423 | <P> SWIG is fully aware of issues related to C++ inheritance. Therefore, | |
18424 | if you have classes like this</P> | |
18425 | <DIV class="code"> | |
18426 | <PRE> | |
18427 | class Foo { | |
18428 | ... | |
18429 | }; | |
18430 | ||
18431 | class Bar : public Foo { | |
18432 | ... | |
18433 | }; | |
18434 | </PRE> | |
18435 | </DIV> | |
18436 | <P> those classes are wrapped into a hierarchy of Java classes that | |
18437 | reflect the same inheritance structure:</P> | |
18438 | <DIV class="code"> | |
18439 | <PRE> | |
18440 | Bar b = new Bar(); | |
18441 | Class c = b.getClass(); | |
18442 | System.out.println(c.getSuperclass().getName()); | |
18443 | </PRE> | |
18444 | </DIV> | |
18445 | <P> will of course display:</P> | |
18446 | <DIV class="code"> | |
18447 | <PRE> | |
18448 | Foo | |
18449 | </PRE> | |
18450 | </DIV> | |
18451 | <P> Furthermore, if you have functions like this</P> | |
18452 | <DIV class="code"> | |
18453 | <PRE> | |
18454 | void spam(Foo *f); | |
18455 | </PRE> | |
18456 | </DIV> | |
18457 | <P> then the Java function <TT>spam()</TT> accepts instances of <TT>Foo</TT> | |
18458 | or instances of any other proxy classes derived from <TT>Foo</TT>.</P> | |
18459 | <P> Note that Java does not support multiple inheritance so any multiple | |
18460 | inheritance in the C++ code is not going to work. A warning is given | |
18461 | when multiple inheritance is detected and only the first base class is | |
18462 | used.</P> | |
18463 | <H3><A name="pointers_refs_arrays"></A>19.3.10 Pointers, references, | |
18464 | arrays and pass by value</H3> | |
18465 | <P> In C++, there are many different ways a function might receive and | |
18466 | manipulate objects. For example:</P> | |
18467 | <DIV class="code"> | |
18468 | <PRE> | |
18469 | void spam1(Foo *x); // Pass by pointer | |
18470 | void spam2(Foo &x); // Pass by reference | |
18471 | void spam3(Foo x); // Pass by value | |
18472 | void spam4(Foo x[]); // Array of objects | |
18473 | </PRE> | |
18474 | </DIV> | |
18475 | <P> In Java, there is no detailed distinction like this--specifically, | |
18476 | there are only instances of classes. There are no pointers nor | |
18477 | references. Because of this, SWIG unifies all of these types together | |
18478 | in the wrapper code. For instance, if you actually had the above | |
18479 | functions, it is perfectly legal to do this from Java:</P> | |
18480 | <DIV class="code"> | |
18481 | <PRE> | |
18482 | Foo f = new Foo(); // Create a Foo | |
18483 | example.spam1(f); // Ok. Pointer | |
18484 | example.spam2(f); // Ok. Reference | |
18485 | example.spam3(f); // Ok. Value. | |
18486 | example.spam4(f); // Ok. Array (1 element) | |
18487 | </PRE> | |
18488 | </DIV> | |
18489 | <P> Similar behavior occurs for return values. For example, if you had | |
18490 | functions like this,</P> | |
18491 | <DIV class="code"> | |
18492 | <PRE> | |
18493 | Foo *spam5(); | |
18494 | Foo &spam6(); | |
18495 | Foo spam7(); | |
18496 | </PRE> | |
18497 | </DIV> | |
18498 | <P> then all three functions will return a pointer to some <TT>Foo</TT> | |
18499 | object. Since the third function (spam7) returns a value, newly | |
18500 | allocated memory is used to hold the result and a pointer is returned | |
18501 | (Java will release this memory when the returned object's finalizer is | |
18502 | run by the garbage collector).</P> | |
18503 | <H4><A name="null_pointers"></A>19.3.10.1 Null pointers</H4> | |
18504 | <P> Working with null pointers is easy. A Java <TT>null</TT> can be used | |
18505 | whenever a method expects a proxy class or typewrapper class. However, | |
18506 | it is not possible to pass null to C/C++ functions that take parameters | |
18507 | by value or by reference. If you try you will get a | |
18508 | NullPointerException.</P> | |
18509 | <DIV class="code"> | |
18510 | <PRE> | |
18511 | example.spam1(null); // Pointer - ok | |
18512 | example.spam2(null); // Reference - NullPointerException | |
18513 | example.spam3(null); // Value - NullPointerException | |
18514 | example.spam4(null); // Array - ok | |
18515 | </PRE> | |
18516 | </DIV> | |
18517 | <P> For <TT>spam1</TT> and <TT>spam4</TT> above the Java <TT>null</TT> | |
18518 | gets translated into a NULL pointer for passing to the C/C++ function. | |
18519 | The converse also occurs, that is, NULL pointers are translated into <TT> | |
18520 | null</TT> Java objects when returned from a C/C++ function.</P> | |
18521 | <H3><A name="overloaded_functions"></A>19.3.11 C++ overloaded functions</H3> | |
18522 | <P> C++ overloaded functions, methods, and constructors are mostly | |
18523 | supported by SWIG. For example, if you have two functions like this:</P> | |
18524 | <DIV class="code"> | |
18525 | <PRE> | |
18526 | %module example | |
18527 | ||
18528 | void foo(int); | |
18529 | void foo(char *c); | |
18530 | </PRE> | |
18531 | </DIV> | |
18532 | <P> You can use them in Java in a straightforward manner:</P> | |
18533 | <DIV class="code"> | |
18534 | <PRE> | |
18535 | example.foo(3); // foo(int) | |
18536 | example.foo("Hello"); // foo(char *c) | |
18537 | </PRE> | |
18538 | </DIV> | |
18539 | <P> Similarly, if you have a class like this,</P> | |
18540 | <DIV class="code"> | |
18541 | <PRE> | |
18542 | class Foo { | |
18543 | public: | |
18544 | Foo(); | |
18545 | Foo(const Foo &); | |
18546 | ... | |
18547 | }; | |
18548 | </PRE> | |
18549 | </DIV> | |
18550 | <P> you can write Java code like this:</P> | |
18551 | <DIV class="code"> | |
18552 | <PRE> | |
18553 | Foo f = new Foo(); // Create a Foo | |
18554 | Foo g = new Foo(f); // Copy f | |
18555 | </PRE> | |
18556 | </DIV> | |
18557 | <P> Overloading support is not quite as flexible as in C++. Sometimes | |
18558 | there are methods that SWIG cannot disambiguate as there can be more | |
18559 | than one C++ type mapping onto a single Java type. For example:</P> | |
18560 | <DIV class="code"> | |
18561 | <PRE> | |
18562 | void spam(int); | |
18563 | void spam(unsigned short); | |
18564 | </PRE> | |
18565 | </DIV> | |
18566 | <P> Here both int and unsigned short map onto a Java int. Here is | |
18567 | another example:</P> | |
18568 | <DIV class="code"> | |
18569 | <PRE> | |
18570 | void foo(Bar *b); | |
18571 | void foo(Bar &b); | |
18572 | </PRE> | |
18573 | </DIV> | |
18574 | <P> If declarations such as these appear, you will get a warning message | |
18575 | like this:</P> | |
18576 | <DIV class="code"> | |
18577 | <PRE> | |
18578 | example.i:12: Warning(515): Overloaded method spam(unsigned short) ignored. | |
18579 | Method spam(int) at example.i:11 used. | |
18580 | </PRE> | |
18581 | </DIV> | |
18582 | <P> To fix this, you either need to ignore or rename one of the methods. | |
18583 | For example:</P> | |
18584 | <DIV class="code"> | |
18585 | <PRE> | |
18586 | %rename(spam_short) spam(short); | |
18587 | ... | |
18588 | void spam(int); | |
18589 | void spam(short); // Accessed as spam_short | |
18590 | </PRE> | |
18591 | </DIV> | |
18592 | <P> or</P> | |
18593 | <DIV class="code"> | |
18594 | <PRE> | |
18595 | %ignore spam(short); | |
18596 | ... | |
18597 | void spam(int); | |
18598 | void spam(short); // Ignored | |
18599 | </PRE> | |
18600 | </DIV> | |
18601 | <H3><A name="java_default_arguments"></A>19.3.12 C++ default arguments</H3> | |
18602 | <P> Any function with a default argument is wrapped by generating an | |
18603 | additional function for each argument that is defaulted. For example, | |
18604 | if we have the following C++:</P> | |
18605 | <DIV class="code"> | |
18606 | <PRE> | |
18607 | %module example | |
18608 | ||
18609 | void defaults(double d=10.0, int i=0); | |
18610 | </PRE> | |
18611 | </DIV> | |
18612 | <P> The following methods are generated in the Java module class:</P> | |
18613 | <DIV class="code"> | |
18614 | <PRE> | |
18615 | public class example { | |
18616 | public static void defaults(double d, int i) { ... } | |
18617 | public static void defaults(double d) { ... } | |
18618 | public static void defaults() { ... } | |
18619 | } | |
18620 | </PRE> | |
18621 | </DIV> | |
18622 | <P> It is as if SWIG had parsed three separate overloaded methods. The | |
18623 | same approach is taken for static methods, constructors and member | |
18624 | methods.</P> | |
18625 | <P><B> Compatibility note:</B> Versions of SWIG prior to SWIG-1.3.23 | |
18626 | wrapped these with a single wrapper method and so the default values | |
18627 | could not be taken advantage of from Java. Further details on default | |
18628 | arguments and how to restore this approach are given in the more | |
18629 | general <A href="#SWIGPlus_default_args">Default arguments</A> section.</P> | |
18630 | <H3><A name="namespaces"></A>19.3.13 C++ namespaces</H3> | |
18631 | <P> SWIG is aware of C++ namespaces, but namespace names do not appear | |
18632 | in the module nor do namespaces result in a module that is broken up | |
18633 | into submodules or packages. For example, if you have a file like this,</P> | |
18634 | <DIV class="code"> | |
18635 | <PRE> | |
18636 | %module example | |
18637 | ||
18638 | namespace foo { | |
18639 | int fact(int n); | |
18640 | struct Vector { | |
18641 | double x,y,z; | |
18642 | }; | |
18643 | }; | |
18644 | </PRE> | |
18645 | </DIV> | |
18646 | <P> it works in Java as follows:</P> | |
18647 | <DIV class="code"> | |
18648 | <PRE> | |
18649 | int f = example.fact(3); | |
18650 | Vector v = new Vector(); | |
18651 | v.setX(3.4); | |
18652 | double y = v.getY(); | |
18653 | </PRE> | |
18654 | </DIV> | |
18655 | <P> If your program has more than one namespace, name conflicts (if any) | |
18656 | can be resolved using <TT>%rename</TT> For example:</P> | |
18657 | <DIV class="code"> | |
18658 | <PRE> | |
18659 | %rename(Bar_spam) Bar::spam; | |
18660 | ||
18661 | namespace Foo { | |
18662 | int spam(); | |
18663 | } | |
18664 | ||
18665 | namespace Bar { | |
18666 | int spam(); | |
18667 | } | |
18668 | </PRE> | |
18669 | </DIV> | |
18670 | <P> If you have more than one namespace and you want to keep their | |
18671 | symbols separate, consider wrapping them as separate SWIG modules. Each | |
18672 | SWIG module can be placed into a separate package.</P> | |
18673 | <H3><A name="templates"></A>19.3.14 C++ templates</H3> | |
18674 | <P> C++ templates don't present a huge problem for SWIG. However, in | |
18675 | order to create wrappers, you have to tell SWIG to create wrappers for | |
18676 | a particular template instantiation. To do this, you use the <TT> | |
18677 | %template</TT> directive. For example:</P> | |
18678 | <DIV class="code"> | |
18679 | <PRE> | |
18680 | %module example | |
18681 | %{ | |
18682 | #include "pair.h" | |
18683 | %} | |
18684 | ||
18685 | template<class T1, class T2> | |
18686 | struct pair { | |
18687 | typedef T1 first_type; | |
18688 | typedef T2 second_type; | |
18689 | T1 first; | |
18690 | T2 second; | |
18691 | pair(); | |
18692 | pair(const T1&, const T2&); | |
18693 | ~pair(); | |
18694 | }; | |
18695 | ||
18696 | %template(pairii) pair<int,int>; | |
18697 | </PRE> | |
18698 | </DIV> | |
18699 | <P> In Java:</P> | |
18700 | <DIV class="code"> | |
18701 | <PRE> | |
18702 | pairii p = new pairii(3,4); | |
18703 | int first = p.getFirst(); | |
18704 | int second = p.getSecond(); | |
18705 | </PRE> | |
18706 | </DIV> | |
18707 | <P> Obviously, there is more to template wrapping than shown in this | |
18708 | example. More details can be found in the <A href="#SWIGPlus">SWIG and | |
18709 | C++</A> chapter.</P> | |
18710 | <H3><A name="smart_pointers"></A>19.3.15 C++ Smart Pointers</H3> | |
18711 | <P> In certain C++ programs, it is common to use classes that have been | |
18712 | wrapped by so-called "smart pointers." Generally, this involves the use | |
18713 | of a template class that implements <TT>operator->()</TT> like this:</P> | |
18714 | <DIV class="code"> | |
18715 | <PRE> | |
18716 | template<class T> class SmartPtr { | |
18717 | ... | |
18718 | T *operator->(); | |
18719 | ... | |
18720 | } | |
18721 | </PRE> | |
18722 | </DIV> | |
18723 | <P> Then, if you have a class like this,</P> | |
18724 | <DIV class="code"> | |
18725 | <PRE> | |
18726 | class Foo { | |
18727 | public: | |
18728 | int x; | |
18729 | int bar(); | |
18730 | }; | |
18731 | </PRE> | |
18732 | </DIV> | |
18733 | <P> A smart pointer would be used in C++ as follows:</P> | |
18734 | <DIV class="code"> | |
18735 | <PRE> | |
18736 | SmartPtr<Foo> p = CreateFoo(); // Created somehow (not shown) | |
18737 | ... | |
18738 | p->x = 3; // Foo::x | |
18739 | int y = p->bar(); // Foo::bar | |
18740 | </PRE> | |
18741 | </DIV> | |
18742 | <P> To wrap this in Java, simply tell SWIG about the <TT>SmartPtr</TT> | |
18743 | class and the low-level <TT>Foo</TT> object. Make sure you instantiate <TT> | |
18744 | SmartPtr</TT> using <TT>%template</TT> if necessary. For example:</P> | |
18745 | <DIV class="code"> | |
18746 | <PRE> | |
18747 | %module example | |
18748 | ... | |
18749 | %template(SmartPtrFoo) SmartPtr<Foo>; | |
18750 | ... | |
18751 | </PRE> | |
18752 | </DIV> | |
18753 | <P> Now, in Java, everything should just "work":</P> | |
18754 | <DIV class="code"> | |
18755 | <PRE> | |
18756 | SmartPtrFoo p = example.CreateFoo(); // Create a smart-pointer somehow | |
18757 | p.setX(3); // Foo::x | |
18758 | int y = p.bar(); // Foo::bar | |
18759 | </PRE> | |
18760 | </DIV> | |
18761 | <P> If you ever need to access the underlying pointer returned by <TT> | |
18762 | operator->()</TT> itself, simply use the <TT>__deref__()</TT> method. | |
18763 | For example:</P> | |
18764 | <DIV class="code"> | |
18765 | <PRE> | |
18766 | Foo f = p.__deref__(); // Returns underlying Foo * | |
18767 | </PRE> | |
18768 | </DIV> | |
18769 | <H2><A name="further_details"></A>19.4 Further details on the generated | |
18770 | Java classes</H2> | |
18771 | <P> In the previous section, a high-level view of Java wrapping was | |
18772 | presented. A key component of this wrapping is that structures and | |
18773 | classes are wrapped by Java proxy classes and type wrapper classes are | |
18774 | used in situations where no proxies are generated. This provides a very | |
18775 | natural, type safe Java interface to the C/C++ code and fits in with | |
18776 | the Java programing paradigm. However, a number of low-level details | |
18777 | were omitted. This section provides a brief overview of how the proxy | |
18778 | classes work and then covers the type wrapper classes. Finally enum | |
18779 | classes are covered. First, the crucial intermediary JNI class is | |
18780 | considered.</P> | |
18781 | <H3><A name="imclass"></A>19.4.1 The intermediary JNI class</H3> | |
18782 | <P> In the <A href="#SWIG">"SWIG basics"</A> and <A href="#SWIGPlus"> | |
18783 | "SWIG and C++"</A> chapters, details of low-level structure and class | |
18784 | wrapping are described. To summarize those chapters, if you have a | |
18785 | global function and class like this</P> | |
18786 | <DIV class="code"> | |
18787 | <PRE> | |
18788 | class Foo { | |
18789 | public: | |
18790 | int x; | |
18791 | int spam(int num, Foo* foo); | |
18792 | }; | |
18793 | void egg(Foo* chips); | |
18794 | </PRE> | |
18795 | </DIV> | |
18796 | <P> then SWIG transforms the class into a set of low-level procedural | |
18797 | wrappers. These procedural wrappers essentially perform the equivalent | |
18798 | of this C++ code:</P> | |
18799 | <DIV class="code"> | |
18800 | <PRE> | |
18801 | Foo *new_Foo() { | |
18802 | return new Foo(); | |
18803 | } | |
18804 | void delete_Foo(Foo *f) { | |
18805 | delete f; | |
18806 | } | |
18807 | int Foo_x_get(Foo *f) { | |
18808 | return f->x; | |
18809 | } | |
18810 | void Foo_x_set(Foo *f, int value) { | |
18811 | f->x = value; | |
18812 | } | |
18813 | int Foo_spam(Foo *f, int num, Foo* foo) { | |
18814 | return f->spam(num, foo); | |
18815 | } | |
18816 | </PRE> | |
18817 | </DIV> | |
18818 | <P> These procedural function names don't actually exist, but their | |
18819 | functionality appears inside the generated JNI functions. The JNI | |
18820 | functions have to follow a particular naming convention so the function | |
18821 | names are actually:</P> | |
18822 | <DIV class="code"> | |
18823 | <PRE> | |
18824 | JNIEXPORT jlong JNICALL Java_exampleJNI_new_1Foo(JNIEnv *jenv, jclass jcls); | |
18825 | JNIEXPORT void JNICALL Java_exampleJNI_delete_1Foo(JNIEnv *jenv, jclass jcls, | |
18826 | jlong jarg1); | |
18827 | JNIEXPORT void JNICALL Java_exampleJNI_Foo_1x_1set(JNIEnv *jenv, jclass jcls, | |
18828 | jlong jarg1, jint jarg2); | |
18829 | JNIEXPORT jint JNICALL Java_exampleJNI_Foo_1x_1get(JNIEnv *jenv, jclass jcls, | |
18830 | jlong jarg1); | |
18831 | JNIEXPORT jint JNICALL Java_exampleJNI_Foo_1spam(JNIEnv *jenv, jclass jcls, | |
18832 | jlong jarg1, jint jarg2, jlong jarg3); | |
18833 | JNIEXPORT void JNICALL Java_exampleJNI_egg(JNIEnv *jenv, jclass jcls, jlong jarg1); | |
18834 | </PRE> | |
18835 | </DIV> | |
18836 | <P> For every JNI C function there has to be a static native Java | |
18837 | function. These appear in the intermediary JNI class:</P> | |
18838 | <DIV class="code"> | |
18839 | <PRE> | |
18840 | class exampleJNI { | |
18841 | public final static native long new_Foo(); | |
18842 | public final static native void delete_Foo(long jarg1); | |
18843 | public final static native void Foo_x_set(long jarg1, int jarg2); | |
18844 | public final static native int Foo_x_get(long jarg1); | |
18845 | public final static native int Foo_spam(long jarg1, int jarg2, long jarg3); | |
18846 | public final static native void egg(long jarg1); | |
18847 | } | |
18848 | </PRE> | |
18849 | </DIV> | |
18850 | <P> This class contains the complete Java - C/C++ interface so all | |
18851 | function calls go via this class. As this class acts as a go-between | |
18852 | for all JNI calls to C/C++ code from the Java <A href="#java_proxy_classes"> | |
18853 | proxy classes</A>, <A href="#type_wrapper_classes">type wrapper classes</A> | |
18854 | and <A href="#java_module_class">module class</A>, it is known as the | |
18855 | intermediary JNI class.</P> | |
18856 | <P> You may notice that SWIG uses a Java long wherever a pointer or | |
18857 | class object needs traversing the Java-C/C++ boundary. This approach | |
18858 | leads to minimal JNI code which makes for better performance as JNI | |
18859 | code involves a lot of string manipulation. SWIG uses Java code | |
18860 | wherever possible as it is compiled into byte code which requires fewer | |
18861 | string operations.</P> | |
18862 | <P> The functions in the intermediary JNI class cannot be accessed | |
18863 | outside of its package. Access to them is gained through the module | |
18864 | class for globals otherwise the appropriate proxy class.</P> | |
18865 | <P> The name of the intermediary JNI class can be changed from its | |
18866 | default, that is, the module name with JNI appended after it. The | |
18867 | module directive attribute <TT>jniclassname</TT> is used to achieve | |
18868 | this:</P> | |
18869 | <DIV class="code"> | |
18870 | <PRE> | |
18871 | %module (jniclassname="name") modulename | |
18872 | </PRE> | |
18873 | </DIV> | |
18874 | <P> If <TT>name</TT> is the same as <TT>modulename</TT> then the module | |
18875 | class name gets changed from <TT>modulename</TT> to <TT> | |
18876 | modulenameModule</TT>.</P> | |
18877 | <H4><A name="imclass_pragmas"></A>19.4.1.1 The intermediary JNI class | |
18878 | pragmas</H4> | |
18879 | <P> The intermediary JNI class can be tailored through the use of | |
18880 | pragmas, but is not commonly done. The pragmas for this class are:</P> | |
18881 | <TABLE BORDER summary="Intermediary JNI class pragmas"> | |
18882 | <TR VALIGN="TOP"><TD><B>Pragma</B></TD><TD><B>Description</B></TD></TR> | |
18883 | <TR><TD>jniclassbase</TD><TD>Base class for the intermediary JNI class</TD> | |
18884 | </TR> | |
18885 | <TR><TD>jniclassclassmodifiers</TD><TD>Class modifiers and class type | |
18886 | for the intermediary JNI class</TD></TR> | |
18887 | <TR><TD>jniclasscode</TD><TD>Java code is copied verbatim into the | |
18888 | intermediary JNI class</TD></TR> | |
18889 | <TR><TD>jniclassimports</TD><TD>Java code, usually one or more import | |
18890 | statements, placed before the intermediary JNI class definition</TD></TR> | |
18891 | <TR><TD>jniclassinterfaces</TD><TD>Comma separated interface classes for | |
18892 | the intermediary JNI class</TD></TR> | |
18893 | </TABLE> | |
18894 | <P> The pragma code appears in the generated intermediary JNI class | |
18895 | where you would expect:</P> | |
18896 | <DIV class="code"> | |
18897 | <PRE> | |
18898 | [ jniclassimports pragma ] | |
18899 | [ jniclassmodifiers pragma ] jniclassname extends [ jniclassbase pragma ] | |
18900 | implements [ jniclassinterfaces pragma ] { | |
18901 | [ jniclasscode pragma ] | |
18902 | ... SWIG generated native methods ... | |
18903 | } | |
18904 | </PRE> | |
18905 | </DIV> | |
18906 | <P> The <TT>jniclasscode</TT> pragma is quite useful for adding in a | |
18907 | static block for loading the shared library / dynamic link library and | |
18908 | demonstrates how pragmas work:</P> | |
18909 | <DIV class="code"> | |
18910 | <PRE> | |
18911 | %pragma(java) jniclasscode=%{ | |
18912 | static { | |
18913 | try { | |
18914 | System.loadLibrary("example"); | |
18915 | } catch (UnsatisfiedLinkError e) { | |
18916 | System.err.println("Native code library failed to load. \n" + e); | |
18917 | System.exit(1); | |
18918 | } | |
18919 | } | |
18920 | %} | |
18921 | </PRE> | |
18922 | </DIV> | |
18923 | <P> Pragmas will take either <TT>""</TT> or <TT>%{ %}</TT> as | |
18924 | delimeters. For example, let's change the intermediary JNI class access | |
18925 | to public.</P> | |
18926 | <DIV class="code"> | |
18927 | <PRE> | |
18928 | %pragma(java) jniclassclassmodifiers="public class" | |
18929 | </PRE> | |
18930 | </DIV> | |
18931 | <P> All the methods in the intermediary JNI class will then be callable | |
18932 | outside of the package as the method modifiers are public by default.</P> | |
18933 | <H3><A name="java_module_class"></A>19.4.2 The Java module class</H3> | |
18934 | <P> All global functions and variable getters/setters appear in the | |
18935 | module class. For our example, there is just one function:</P> | |
18936 | <DIV class="code"> | |
18937 | <PRE> | |
18938 | public class example { | |
18939 | public static void egg(Foo chips) { | |
18940 | exampleJNI.egg(Foo.getCPtr(chips)); | |
18941 | } | |
18942 | } | |
18943 | </PRE> | |
18944 | </DIV> | |
18945 | <P> The module class is necessary as there is no such thing as a global | |
18946 | in Java so all the C globals are put into this class. They are | |
18947 | generated as static functions and so must be accessed as such by using | |
18948 | the module name in the static function call:</P> | |
18949 | <DIV class="code"> | |
18950 | <PRE> | |
18951 | example.egg(new Foo()); | |
18952 | </PRE> | |
18953 | </DIV> | |
18954 | <P> The primary reason for having the module class wrapping the calls in | |
18955 | the intermediary JNI class is to implement static type checking. In | |
18956 | this case only a <TT>Foo</TT> can be passed to the <TT>egg</TT> | |
18957 | function, whereas any <TT>long</TT> can be passed to the <TT>egg</TT> | |
18958 | function in the intermediary JNI class.</P> | |
18959 | <H4><A name="module_class_pragmas"></A>19.4.2.1 The Java module class | |
18960 | pragmas</H4> | |
18961 | <P> The module class can be tailored through the use of pragmas, in the | |
18962 | same manner as the intermediary JNI class. The pragmas are similarly | |
18963 | named and are used in the same way. The complete list follows:</P> | |
18964 | <TABLE BORDER summary="Java module class pragmas"> | |
18965 | <TR VALIGN="TOP"><TD><B>Pragma</B></TD><TD><B>Description</B></TD></TR> | |
18966 | <TR><TD>modulebase</TD><TD>Base class for the module class</TD></TR> | |
18967 | <TR><TD>moduleclassmodifiers</TD><TD>Class modifiers and class type for | |
18968 | the module class</TD></TR> | |
18969 | <TR><TD>modulecode</TD><TD>Java code is copied verbatim into the module | |
18970 | class</TD></TR> | |
18971 | <TR><TD>moduleimports</TD><TD>Java code, usually one or more import | |
18972 | statements, placed before the module class definition</TD></TR> | |
18973 | <TR><TD>moduleinterfaces</TD><TD>Comma separated interface classes for | |
18974 | the module class</TD></TR> | |
18975 | </TABLE> | |
18976 | <P> The pragma code appears in the generated module class like this:</P> | |
18977 | <DIV class="code"> | |
18978 | <PRE> | |
18979 | [ moduleimports pragma ] | |
18980 | [ modulemodifiers pragma ] modulename extends [ modulebase pragma ] | |
18981 | implements [ moduleinterfaces pragma ] { | |
18982 | [ modulecode pragma ] | |
18983 | ... SWIG generated wrapper functions ... | |
18984 | } | |
18985 | </PRE> | |
18986 | </DIV> | |
18987 | <P> See <A href="#imclass_pragmas">The intermediary JNI class pragmas</A> | |
18988 | section for further details on using pragmas.</P> | |
18989 | <H3><A name="java_proxy_classes"></A>19.4.3 Java proxy classes</H3> | |
18990 | <P> A Java proxy class is generated for each structure, union or C++ | |
18991 | class that is wrapped. The default proxy class for our previous example | |
18992 | looks like this:</P> | |
18993 | <DIV class="code"> | |
18994 | <PRE> | |
18995 | public class Foo { | |
18996 | private long swigCPtr; | |
18997 | protected boolean swigCMemOwn; | |
18998 | ||
18999 | protected Foo(long cPtr, boolean cMemoryOwn) { | |
19000 | swigCMemOwn = cMemoryOwn; | |
19001 | swigCPtr = cPtr; | |
19002 | } | |
19003 | ||
19004 | protected static long getCPtr(Foo obj) { | |
19005 | return obj.swigCPtr; | |
19006 | } | |
19007 | ||
19008 | protected void finalize() { | |
19009 | delete(); | |
19010 | } | |
19011 | ||
19012 | public void delete() { | |
19013 | if(swigCPtr != 0 && swigCMemOwn) { | |
19014 | exampleJNI.delete_Foo(swigCPtr); | |
19015 | swigCMemOwn = false; | |
19016 | } | |
19017 | swigCPtr = 0; | |
19018 | } | |
19019 | ||
19020 | public void setX(int x) { | |
19021 | exampleJNI.Foo_x_set(swigCPtr, x); | |
19022 | } | |
19023 | ||
19024 | public int getX() { | |
19025 | return exampleJNI.Foo_x_get(swigCPtr); | |
19026 | } | |
19027 | ||
19028 | public int spam(int num, Foo foo) { | |
19029 | return exampleJNI.Foo_spam(swigCPtr, num, Foo.getCPtr(foo)); | |
19030 | } | |
19031 | ||
19032 | public Foo() { | |
19033 | this(exampleJNI.new_Foo(), true); | |
19034 | } | |
19035 | } | |
19036 | </PRE> | |
19037 | </DIV> | |
19038 | <P> This class merely holds a pointer to the underlying C++ object (<TT> | |
19039 | swigCPtr</TT>). It also contains all the methods in the C++ class it is | |
19040 | proxying plus getters and setters for public member variables. These | |
19041 | functions call the native methods in the intermediary JNI class. The | |
19042 | advantage of having this extra layer is the type safety that the proxy | |
19043 | class functions offer. It adds static type checking which leads to | |
19044 | fewer surprises at runtime. For example, you can see that if you | |
19045 | attempt to use the <TT>spam()</TT> function it will only compile when | |
19046 | the parameters passed are an <TT>int</TT> and a <TT>Foo</TT>. From a | |
19047 | user's point of view, it makes the class work as if it were a Java | |
19048 | class:</P> | |
19049 | <DIV class="code"> | |
19050 | <PRE> | |
19051 | Foo f = new Foo(); | |
19052 | f.setX(3); | |
19053 | int y = f.spam(5, new Foo()); | |
19054 | </PRE> | |
19055 | </DIV> | |
19056 | <H4><A name="memory_management"></A>19.4.3.1 Memory management</H4> | |
19057 | <P> Each proxy class has an ownership flag <TT>swigCMemOwn</TT>. The | |
19058 | value of this flag determines who is responsible for deleting the | |
19059 | underlying C++ object. If set to <TT>true</TT>, the proxy class's | |
19060 | finalizer will destroy the C++ object when the proxy class is garbage | |
19061 | collected. If set to false, then the destruction of the proxy class has | |
19062 | no effect on the C++ object.</P> | |
19063 | <P> When an object is created by a constructor or returned by value, | |
19064 | Java automatically takes ownership of the result. On the other hand, | |
19065 | when pointers or references are returned to Java, there is often no way | |
19066 | to know where they came from. Therefore, the ownership is set to false. | |
19067 | For example:</P> | |
19068 | <DIV class="code"> | |
19069 | <PRE> | |
19070 | class Foo { | |
19071 | public: | |
19072 | Foo(); | |
19073 | Foo bar1(); | |
19074 | Foo &bar2(); | |
19075 | Foo *bar2(); | |
19076 | }; | |
19077 | </PRE> | |
19078 | </DIV> | |
19079 | <P> In Java:</P> | |
19080 | <DIV class="code"> | |
19081 | <PRE> | |
19082 | Foo f = new Foo(); // f.swigCMemOwn = true | |
19083 | Foo f1 = f.bar1(); // f1.swigCMemOwn = true | |
19084 | Foo f2 = f.bar2(); // f2.swigCMemOwn = false | |
19085 | Foo f3 = f.bar3(); // f3.swigCMemOwn = false | |
19086 | </PRE> | |
19087 | </DIV> | |
19088 | <P> This behavior for pointers and references is especially important | |
19089 | for classes that act as containers. For example, if a method returns a | |
19090 | pointer to an object that is contained inside another object, you | |
19091 | definitely don't want Java to assume ownership and destroy it!</P> | |
19092 | <P> For the most part, memory management issues remain hidden. However, | |
19093 | there are situations where you might have to manually change the | |
19094 | ownership of an object. For instance, consider code like this:</P> | |
19095 | <DIV class="code"> | |
19096 | <PRE> | |
19097 | class Obj {}; | |
19098 | class Node { | |
19099 | Obj *value; | |
19100 | public: | |
19101 | void set_value(Obj *v) { value = v; } | |
19102 | }; | |
19103 | </PRE> | |
19104 | </DIV> | |
19105 | <P> Now, consider the following Java code:</P> | |
19106 | <DIV class="code"> | |
19107 | <PRE> | |
19108 | Node n = new Node(); // Create a node | |
19109 | { | |
19110 | Obj o = new Obj(); // Create an object | |
19111 | n.set_value(o); // Set value | |
19112 | } // o goes out of scope | |
19113 | </PRE> | |
19114 | </DIV> | |
19115 | <P> In this case, the Node <TT>n</TT> is holding a reference to <TT>o</TT> | |
19116 | internally. However, SWIG has no way to know that this has occurred. | |
19117 | The Java proxy class still thinks that it has ownership of <TT>o</TT>. | |
19118 | As <TT>o</TT> has gone out of scope, it could be garbage collected in | |
19119 | which case the C++ destructor will be invoked and <TT>n</TT> will then | |
19120 | be holding a stale-pointer to <TT>o</TT>. If you're lucky, you will | |
19121 | only get a segmentation fault.</P> | |
19122 | <P> To work around this, the ownership flag of <TT>o</TT> needs changing | |
19123 | to <TT>false</TT>. The ownership flag is a private member variable of | |
19124 | the proxy class so this is not possible without some customization of | |
19125 | the proxy class. This is achieved using a typemap to add pure Java code | |
19126 | to the proxy class and is detailed later in the section on typemaps.</P> | |
19127 | <P> Sometimes a function will create memory and return a pointer to a | |
19128 | newly allocated object. SWIG has no way of knowing this so by default | |
19129 | the proxy class does not manage the returned object. However, you can | |
19130 | tell the proxy class to manage the memory if you specify the <TT> | |
19131 | %newobject</TT> directive. Consider:</P> | |
19132 | <DIV class="code"> | |
19133 | <PRE> | |
19134 | class Obj {...}; | |
19135 | class Factory { | |
19136 | public: | |
19137 | static Obj *createObj() { return new Obj(); } | |
19138 | }; | |
19139 | </PRE> | |
19140 | </DIV> | |
19141 | <P> If we call the factory function, then we have to manually delete the | |
19142 | memory:</P> | |
19143 | <DIV class="code"> | |
19144 | <PRE> | |
19145 | Obj obj = Factory.createObj(); // obj.swigCMemOwn = false | |
19146 | ... | |
19147 | obj.delete(); | |
19148 | </PRE> | |
19149 | </DIV> | |
19150 | <P> Now add in the %newobject directive:</P> | |
19151 | <DIV class="code"> | |
19152 | <PRE> | |
19153 | %newobject Factory::createObj(); | |
19154 | ||
19155 | class Obj {...}; | |
19156 | class Factory { | |
19157 | public: | |
19158 | static Obj *createObj() { return new Obj(); } | |
19159 | }; | |
19160 | </PRE> | |
19161 | </DIV> | |
19162 | <P> A call to <TT>delete()</TT> is no longer necessary as the garbage | |
19163 | collector will make the C++ destructor call because <TT>swigCMemOwn</TT> | |
19164 | is now true.</P> | |
19165 | <DIV class="code"> | |
19166 | <PRE> | |
19167 | Obj obj = Factory.createObj(); // obj.swigCMemOwn = true; | |
19168 | ... | |
19169 | </PRE> | |
19170 | </DIV> | |
19171 | <H4><A name="inheritance_mirroring"></A>19.4.3.2 Inheritance</H4> | |
19172 | <P> Java proxy classes will mirror C++ inheritance chains. For example, | |
19173 | given the base class <TT>Base</TT> and its derived class <TT>Derived</TT> | |
19174 | :</P> | |
19175 | <DIV class="code"> | |
19176 | <PRE> | |
19177 | class Base { | |
19178 | public: | |
19179 | virtual double foo(); | |
19180 | }; | |
19181 | ||
19182 | class Derived : public Base { | |
19183 | public: | |
19184 | virtual double foo(); | |
19185 | }; | |
19186 | </PRE> | |
19187 | </DIV> | |
19188 | <P> The base class is generated much like any other proxy class seen so | |
19189 | far:</P> | |
19190 | <DIV class="code"> | |
19191 | <PRE> | |
19192 | public class Base { | |
19193 | private long swigCPtr; | |
19194 | protected boolean swigCMemOwn; | |
19195 | ||
19196 | protected Base(long cPtr, boolean cMemoryOwn) { | |
19197 | swigCMemOwn = cMemoryOwn; | |
19198 | swigCPtr = cPtr; | |
19199 | } | |
19200 | ||
19201 | protected static long getCPtr(Base obj) { | |
19202 | return obj.swigCPtr; | |
19203 | } | |
19204 | ||
19205 | protected void finalize() { | |
19206 | delete(); | |
19207 | } | |
19208 | ||
19209 | public void delete() { | |
19210 | if(swigCPtr != 0 && swigCMemOwn) { | |
19211 | exampleJNI.delete_Base(swigCPtr); | |
19212 | swigCMemOwn = false; | |
19213 | } | |
19214 | swigCPtr = 0; | |
19215 | } | |
19216 | ||
19217 | public double foo() { | |
19218 | return exampleJNI.Base_foo(swigCPtr); | |
19219 | } | |
19220 | ||
19221 | public Base() { | |
19222 | this(exampleJNI.new_Base(), true); | |
19223 | } | |
19224 | } | |
19225 | </PRE> | |
19226 | </DIV> | |
19227 | <P> The <TT>Derived</TT> class extends <TT>Base</TT> mirroring the C++ | |
19228 | class inheritance hierarchy.</P> | |
19229 | <DIV class="code"> | |
19230 | <PRE> | |
19231 | public class Derived extends Base { | |
19232 | private long swigCPtr; | |
19233 | ||
19234 | protected Derived(long cPtr, boolean cMemoryOwn) { | |
19235 | super(exampleJNI.SWIGDerivedUpcast(cPtr), cMemoryOwn); | |
19236 | swigCPtr = cPtr; | |
19237 | } | |
19238 | ||
19239 | protected static long getCPtr(Derived obj) { | |
19240 | return obj.swigCPtr; | |
19241 | } | |
19242 | ||
19243 | protected void finalize() { | |
19244 | delete(); | |
19245 | } | |
19246 | ||
19247 | public void delete() { | |
19248 | if(swigCPtr != 0 && swigCMemOwn) { | |
19249 | exampleJNI.delete_Derived(swigCPtr); | |
19250 | swigCMemOwn = false; | |
19251 | } | |
19252 | swigCPtr = 0; | |
19253 | super.delete(); | |
19254 | } | |
19255 | ||
19256 | public double foo() { | |
19257 | return exampleJNI.Derived_foo(swigCPtr); | |
19258 | } | |
19259 | ||
19260 | public Derived() { | |
19261 | this(exampleJNI.new_Derived(), true); | |
19262 | } | |
19263 | } | |
19264 | </PRE> | |
19265 | </DIV> | |
19266 | <P> Note the memory ownership is controlled by the base class. However | |
19267 | each class in the inheritance hierarchy has its own pointer value which | |
19268 | is obtained during construction. The <TT>SWIGDerivedUpcast()</TT> call | |
19269 | converts the pointer from a <TT>Derived *</TT> to a <TT>Base *</TT>. | |
19270 | This is a necessity as C++ compilers are free to implement pointers in | |
19271 | the inheritance hierarchy with different values.</P> | |
19272 | <P> It is of course possible to extend <TT>Base</TT> using your own Java | |
19273 | classes. If <TT>Derived</TT> is provided by the C++ code, you could for | |
19274 | example add in a pure Java class <TT>Extended</TT> derived from <TT> | |
19275 | Base</TT>. There is a caveat and that is any C++ code will not know | |
19276 | about your pure Java class <TT>Extended</TT> so this type of derivation | |
19277 | is restricted. However, true cross language polymorphism can be | |
19278 | achieved using the <A href="#java_directors">directors</A> feature.</P> | |
19279 | <H4><A name="proxy_classes_gc"></A>19.4.3.3 Proxy classes and garbage | |
19280 | collection</H4> | |
19281 | <P> By default each proxy class has a <TT>delete()</TT> and a <TT> | |
19282 | finalize()</TT> method. The <TT>finalize()</TT> method calls <TT> | |
19283 | delete()</TT> which frees any malloc'd memory for wrapped C structs or | |
19284 | calls the C++ class destructors. The idea is for <TT>delete()</TT> to | |
19285 | be called when you have finished with the C/C++ object. Ideally you | |
19286 | need not call <TT>delete()</TT>, but rather leave it to the garbage | |
19287 | collector to call it from the finalizer. The unfortunate thing is that | |
19288 | Sun, in their wisdom, do not guarantee that the finalizers will be | |
19289 | called. When a program exits, the garbage collector does not always | |
19290 | call the finalizers. Depending on what the finalizers do and which | |
19291 | operating system you use, this may or may not be a problem.</P> | |
19292 | <P> If the <TT>delete()</TT> call into JNI code is just for memory | |
19293 | handling, there is not a problem when run on most operating systems, | |
19294 | for example Windows and Unix. Say your JNI code creates memory on the | |
19295 | heap which your finalizers should clean up, the finalizers may or may | |
19296 | not be called before the program exits. In Windows and Unix all memory | |
19297 | that a process uses is returned to the system on exit, so this isn't a | |
19298 | problem. This is not the case in some operating systems like vxWorks. | |
19299 | If however, your finalizer calls into JNI code invoking the C++ | |
19300 | destructor which in turn releases a TCP/IP socket for example, there is | |
19301 | no guarantee that it will be released. Note that with long running | |
19302 | programs the garbage collector will eventually run, thereby calling any | |
19303 | unreferenced object's finalizers.</P> | |
19304 | <P> Some not so ideal solutions are:</P> | |
19305 | <OL> | |
19306 | <LI> | |
19307 | <P> Call the <TT>System.runFinalizersOnExit(true)</TT> or <TT> | |
19308 | Runtime.getRuntime().runFinalizersOnExit(true)</TT> to ensure the | |
19309 | finalizers are called before the program exits. The catch is that this | |
19310 | is a deprecated function call as the documenation says:</P> | |
19311 | <DIV class="code"><I> This method is inherently unsafe. It may result in | |
19312 | finalizers being called on live objects while other threads are | |
19313 | concurrently manipulating those objects, resulting in erratic behavior | |
19314 | or deadlock.</I></DIV> | |
19315 | <P>In many cases you will be lucky and find that it works, but it is not | |
19316 | to be advocated. Have a look at <A href="http://java.sun.com">Sun's | |
19317 | Java web site</A> and search for <TT>runFinalizersOnExit</TT>.</P> | |
19318 | </LI> | |
19319 | <LI> | |
19320 | <P> From jdk1.3 onwards a new function, <TT>addShutdownHook()</TT>, was | |
19321 | introduced which is guaranteed to be called when your program exits. | |
19322 | You can encourage the garbage collector to call the finalizers, for | |
19323 | example, add this static block to the class that has the <TT>main()</TT> | |
19324 | function:</P> | |
19325 | <DIV class="code"> | |
19326 | <PRE> | |
19327 | static { | |
19328 | Runtime.getRuntime().addShutdownHook( | |
19329 | new Thread() { | |
19330 | public void run() { System.gc(); System.runFinalization(); } | |
19331 | } | |
19332 | ); | |
19333 | } | |
19334 | </PRE> | |
19335 | </DIV> | |
19336 | <P>Although this usually works, the documentation doesn't guarantee that | |
19337 | <TT>runFinalization()</TT> will actually call the finalizers. As the | |
19338 | the shutdown hook is guaranteed you could also make a JNI call to clean | |
19339 | up any resources that are being tracked by the C/C++ code.</P> | |
19340 | </LI> | |
19341 | <LI> | |
19342 | <P>Call the <TT>delete()</TT> function manually which will immediately | |
19343 | invoke the C++ destructor. As a suggestion it may be a good idea to set | |
19344 | the object to null so that should the object be inadvertantly used | |
19345 | again a Java null pointer exception is thrown, the alternative would | |
19346 | crash the JVM by using a null C pointer. For example given a SWIG | |
19347 | generated class A:</P> | |
19348 | <DIV class="code"> | |
19349 | <PRE> | |
19350 | A myA = new A(); | |
19351 | // use myA ... | |
19352 | myA.delete(); | |
19353 | // any use of myA here would crash the JVM | |
19354 | myA=null; | |
19355 | // any use of myA here would cause a Java null pointer exception to be thrown | |
19356 | </PRE> | |
19357 | </DIV> | |
19358 | <P> The SWIG generated code ensures that the memory is not deleted | |
19359 | twice, in the event the finalizers get called in addition to the manual | |
19360 | <TT>delete()</TT> call.</P> | |
19361 | </LI> | |
19362 | <LI> Write your own object manager in Java. You could derive all SWIG | |
19363 | classes from a single base class which could track which objects have | |
19364 | had their finalizers run, then call the rest of them on program | |
19365 | termination. The section on <A href="#java_typemaps">Java typemaps</A> | |
19366 | details how to specify a pure Java base class.</LI> | |
19367 | </OL> | |
19368 | <H3><A name="type_wrapper_classes"></A>19.4.4 Type wrapper classes</H3> | |
19369 | <P> The generated type wrapper class, for say an <TT>int *</TT>, looks | |
19370 | like this:</P> | |
19371 | <DIV class="code"> | |
19372 | <PRE> | |
19373 | public class SWIGTYPE_p_int { | |
19374 | private long swigCPtr; | |
19375 | ||
19376 | protected SWIGTYPE_p_int(long cPtr, boolean bFutureUse) { | |
19377 | swigCPtr = cPtr; | |
19378 | } | |
19379 | ||
19380 | protected SWIGTYPE_p_int() { | |
19381 | swigCPtr = 0; | |
19382 | } | |
19383 | ||
19384 | protected static long getCPtr(SWIGTYPE_p_int obj) { | |
19385 | return obj.swigCPtr; | |
19386 | } | |
19387 | } | |
19388 | </PRE> | |
19389 | </DIV> | |
19390 | <P> The methods do not have public access, so by default it is | |
19391 | impossible to do anything with objects of this class other than pass | |
19392 | them around. The methods in the class are part of the inner workings of | |
19393 | SWIG. If you need to mess around with pointers you will have to use | |
19394 | some typemaps specific to the Java module to achieve this. The section | |
19395 | on <A href="#java_typemaps">Java typemaps</A> details how to modify the | |
19396 | generated code.</P> | |
19397 | <P> Note that if you use a pointer or reference to a proxy class in a | |
19398 | function then no type wrapper class is generated because the proxy | |
19399 | class can be used as the function parameter. If however, you need | |
19400 | anything more complicated like a pointer to a pointer to a proxy class | |
19401 | then a typewrapper class is generated for your use.</P> | |
19402 | <P> Note that SWIG generates a type wrapper class and not a proxy class | |
19403 | when it has not parsed the definition of a type that gets used. For | |
19404 | example, say SWIG has not parsed the definition of <TT>class Snazzy</TT> | |
19405 | because it is in a header file that you may have forgotten to use the <TT> | |
19406 | %include</TT> directive on. Should SWIG parse <TT>Snazzy *</TT> being | |
19407 | used in a function parameter, it will then generates a type wrapper | |
19408 | class around a <TT>Snazzy</TT> pointer. Also recall from earlier that | |
19409 | SWIG will use a pointer when a class is passed by value or by | |
19410 | reference:</P> | |
19411 | <DIV class="code"> | |
19412 | <PRE> | |
19413 | void spam(Snazzy *x, Snazzy &y, Snazzy z); | |
19414 | </PRE> | |
19415 | </DIV> | |
19416 | <P> Should SWIG not know anything about <TT>Snazzy</TT> then a <TT> | |
19417 | SWIGTYPE_p_Snazzy</TT> must be used for all 3 parameters in the <TT>spam</TT> | |
19418 | function. The Java function generated is:</P> | |
19419 | <DIV class="code"> | |
19420 | <PRE> | |
19421 | public static void spam(SWIGTYPE_p_Snazzy x, SWIGTYPE_p_Snazzy y, SWIGTYPE_p_Snazzy z) { | |
19422 | ... | |
19423 | } | |
19424 | </PRE> | |
19425 | </DIV> | |
19426 | <P> Note that typedefs are tracked by SWIG and the typedef name is used | |
19427 | to construct the type wrapper class name. For example, consider the | |
19428 | case where <TT>Snazzy</TT> is a typedef to an <TT>int</TT> which SWIG | |
19429 | does parse:</P> | |
19430 | <DIV class="code"> | |
19431 | <PRE> | |
19432 | typedef int Snazzy; | |
19433 | void spam(Snazzy *x, Snazzy &y, Snazzy z); | |
19434 | </PRE> | |
19435 | </DIV> | |
19436 | <P> Because the typedefs have been tracked the Java function generated | |
19437 | is:</P> | |
19438 | <DIV class="code"> | |
19439 | <PRE> | |
19440 | public static void spam(SWIGTYPE_p_int x, SWIGTYPE_p_int y, int z) { ... } | |
19441 | </PRE> | |
19442 | </DIV> | |
19443 | <H3><A name="enum_classes"></A>19.4.5 Enum classes</H3> | |
19444 | <P> SWIG can generate three types of enum classes. The <A href="#enumerations"> | |
19445 | Enumerations</A> section discussed these but omitted all the details. | |
19446 | The following sub-sections detail the various types of enum classes | |
19447 | that can be generated.</P> | |
19448 | <H4><A name="typesafe_enums_classes"></A>19.4.5.1 Typesafe enum classes</H4> | |
19449 | <P> The following example demonstrates the typesafe enum classes which | |
19450 | SWIG generates:</P> | |
19451 | <DIV class="code"> | |
19452 | <PRE> | |
19453 | %include "enumtypesafe.swg" | |
19454 | %javaconst(1); | |
19455 | enum Beverage { ALE, LAGER=10, STOUT, PILSNER }; | |
19456 | </PRE> | |
19457 | </DIV> | |
19458 | <P> The following is what SWIG generates:</P> | |
19459 | <DIV class="code"> | |
19460 | <PRE> | |
19461 | public final class Beverage { | |
19462 | public final static Beverage ALE = new Beverage("ALE"); | |
19463 | public final static Beverage LAGER = new Beverage("LAGER", 10); | |
19464 | public final static Beverage STOUT = new Beverage("STOUT"); | |
19465 | public final static Beverage PILSNER = new Beverage("PILSNER"); | |
19466 | ||
19467 | public final int swigValue() { | |
19468 | return swigValue; | |
19469 | } | |
19470 | ||
19471 | public String toString() { | |
19472 | return swigName; | |
19473 | } | |
19474 | ||
19475 | public static Beverage swigToEnum(int swigValue) { | |
19476 | if (swigValue < swigValues.length && swigValue >= 0 && | |
19477 | swigValues[swigValue].swigValue == swigValue) | |
19478 | return swigValues[swigValue]; | |
19479 | for (int i = 0; i < swigValues.length; i++) | |
19480 | if (swigValues[i].swigValue == swigValue) | |
19481 | return swigValues[i]; | |
19482 | throw new IllegalArgumentException("No enum " + Beverage.class + " with value " + | |
19483 | swigValue); | |
19484 | } | |
19485 | ||
19486 | private Beverage(String swigName) { | |
19487 | this.swigName = swigName; | |
19488 | this.swigValue = swigNext++; | |
19489 | } | |
19490 | ||
19491 | private Beverage(String swigName, int swigValue) { | |
19492 | this.swigName = swigName; | |
19493 | this.swigValue = swigValue; | |
19494 | swigNext = swigValue+1; | |
19495 | } | |
19496 | ||
19497 | private static Beverage[] swigValues = { ALE, LAGER, STOUT, PILSNER }; | |
19498 | private static int swigNext = 0; | |
19499 | private final int swigValue; | |
19500 | private final String swigName; | |
19501 | } | |
19502 | </PRE> | |
19503 | </DIV> | |
19504 | <P> As can be seen, there a fair number of support methods for the | |
19505 | typesafe enum pattern. The typesafe enum pattern involves creating a | |
19506 | fixed number of static instances of the enum class. The constructors | |
19507 | are private to enforce this. Two constructors are available - one for | |
19508 | C/C++ enums with an initializer and one for those without an | |
19509 | initializer. In order to use one of these typesafe enums, the <TT> | |
19510 | swigToEnum</TT> static method must be called to return a reference to | |
19511 | one of the static instances. The JNI layer returns the enum value from | |
19512 | the C/C++ world as an integer and this method is used to find the | |
19513 | appropriate Java enum static instance. The <TT>swigValue</TT> method is | |
19514 | used for marshalling in the other direction. The <TT>toString</TT> | |
19515 | method is overridden so that the enum name is available.</P> | |
19516 | <H4><A name="proper_enums_classes"></A>19.4.5.2 Proper Java enum classes</H4> | |
19517 | <P> The following example demonstrates the Java enums approach:</P> | |
19518 | <DIV class="code"> | |
19519 | <PRE> | |
19520 | %include "enums.swg" | |
19521 | %javaconst(1); | |
19522 | enum Beverage { ALE, LAGER=10, STOUT, PILSNER }; | |
19523 | </PRE> | |
19524 | </DIV> | |
19525 | <P> SWIG will generate the following Java enum:</P> | |
19526 | <DIV class="code"> | |
19527 | <PRE> | |
19528 | public enum Beverage { | |
19529 | ALE, | |
19530 | LAGER(10), | |
19531 | STOUT, | |
19532 | PILSNER; | |
19533 | ||
19534 | public final int swigValue() { | |
19535 | return swigValue; | |
19536 | } | |
19537 | ||
19538 | public static Beverage swigToEnum(int swigValue) { | |
19539 | Beverage[] swigValues = Beverage.class.getEnumConstants(); | |
19540 | if (swigValue < swigValues.length && swigValue >= 0 && | |
19541 | swigValues[swigValue].swigValue == swigValue) | |
19542 | return swigValues[swigValue]; | |
19543 | for (Beverage swigEnum : swigValues) | |
19544 | if (swigEnum.swigValue == swigValue) | |
19545 | return swigEnum; | |
19546 | throw new IllegalArgumentException("No enum " + Beverage.class + | |
19547 | " with value " + swigValue); | |
19548 | } | |
19549 | ||
19550 | private Beverage() { | |
19551 | this.swigValue = SwigNext.next++; | |
19552 | } | |
19553 | ||
19554 | private Beverage(int swigValue) { | |
19555 | this.swigValue = swigValue; | |
19556 | SwigNext.next = swigValue+1; | |
19557 | } | |
19558 | ||
19559 | private final int swigValue; | |
19560 | ||
19561 | private static class SwigNext { | |
19562 | private static int next = 0; | |
19563 | } | |
19564 | } | |
19565 | </PRE> | |
19566 | </DIV> | |
19567 | <P> The enum items appear first. Like the typesafe enum pattern, the | |
19568 | constructors are private. The constructors are required to handle C/C++ | |
19569 | enums with initializers. The <TT>next</TT> variable is in the <TT> | |
19570 | SwigNext</TT> inner class rather than in the enum class as static | |
19571 | primitive variables cannot be modified from within enum constructors. | |
19572 | Marshalling between Java enums and the C/C++ enum integer value is | |
19573 | handled via the <TT>swigToEnum</TT> and <TT>swigValue</TT> methods. All | |
19574 | the constructors and methods in the Java enum are required just to | |
19575 | handle C/C++ enums with initializers. These needn't be generated if the | |
19576 | enum being wrapped does not have any initializers and the <A href="#simpler_enum_classes"> | |
19577 | Simpler Java enums for enums without initializers</A> section describes | |
19578 | how typemaps can be used to achieve this.</P> | |
19579 | <H4><A name="typeunsafe_enums_classes"></A>19.4.5.3 Type unsafe enum | |
19580 | classes</H4> | |
19581 | <P> The following example demonstrates type unsafe enums:</P> | |
19582 | <DIV class="code"> | |
19583 | <PRE> | |
19584 | %include "enumtypeunsafe.swg" | |
19585 | %javaconst(1); | |
19586 | enum Beverage { ALE, LAGER=10, STOUT, PILSNER }; | |
19587 | </PRE> | |
19588 | </DIV> | |
19589 | <P> SWIG will generate the following simple class:</P> | |
19590 | <DIV class="code"> | |
19591 | <PRE> | |
19592 | public final class Beverage { | |
19593 | public final static int ALE = 0; | |
19594 | public final static int LAGER = 10; | |
19595 | public final static int STOUT = LAGER + 1; | |
19596 | public final static int PILSNER = STOUT + 1; | |
19597 | } | |
19598 | </PRE> | |
19599 | </DIV> | |
19600 | <H2><A name="java_directors"></A>19.5 Cross language polymorphism using | |
19601 | directors (experimental)</H2> | |
19602 | <P> Proxy classes provide a natural, object-oriented way to wrap C++ | |
19603 | classes. as described earlier, each proxy instance has an associated | |
19604 | C++ instance, and method calls from Java to the proxy are passed to the | |
19605 | C++ instance transparently via C wrapper functions.</P> | |
19606 | <P> This arrangement is asymmetric in the sense that no corresponding | |
19607 | mechanism exists to pass method calls down the inheritance chain from | |
19608 | C++ to Java. In particular, if a C++ class has been extended in Java | |
19609 | (by deriving from the proxy class), these classes will not be visible | |
19610 | from C++ code. Virtual method calls from C++ are thus not able to | |
19611 | access the lowest implementation in the inheritance chain.</P> | |
19612 | <P> SWIG can address this problem and make the relationship between C++ | |
19613 | classes and proxy classes more symmetric. To achieve this goal, new | |
19614 | classes called directors are introduced at the bottom of the C++ | |
19615 | inheritance chain. The job of the directors is to route method calls | |
19616 | correctly, either to C++ implementations higher in the inheritance | |
19617 | chain or to Java implementations lower in the inheritance chain. The | |
19618 | upshot is that C++ classes can be extended in Java and from C++ these | |
19619 | extensions look exactly like native C++ classes. Neither C++ code nor | |
19620 | Java code needs to know where a particular method is implemented: the | |
19621 | combination of proxy classes, director classes, and C wrapper functions | |
19622 | transparently takes care of all the cross-language method routing.</P> | |
19623 | <H3><A name="java_enabling_directors"></A>19.5.1 Enabling directors</H3> | |
19624 | <P> The director feature is disabled by default. To use directors you | |
19625 | must make two changes to the interface file. First, add the "directors" | |
19626 | option to the %module directive, like this:</P> | |
19627 | <DIV class="code"> | |
19628 | <PRE> | |
19629 | %module(directors="1") modulename | |
19630 | </PRE> | |
19631 | </DIV> | |
19632 | <P> Without this option no director code will be generated. Second, you | |
19633 | must use the %feature("director") directive to tell SWIG which classes | |
19634 | and methods should get directors. The %feature directive can be applied | |
19635 | globally, to specific classes, and to specific methods, like this:</P> | |
19636 | <DIV class="code"> | |
19637 | <PRE> | |
19638 | // generate directors for all classes that have virtual methods | |
19639 | %feature("director"); | |
19640 | ||
19641 | // generate directors for all virtual methods in class Foo | |
19642 | %feature("director") Foo; | |
19643 | ||
19644 | // generate a director for just Foo::bar() | |
19645 | %feature("director") Foo::bar; | |
19646 | </PRE> | |
19647 | </DIV> | |
19648 | <P> You can use the %feature("nodirector") directive to turn off | |
19649 | directors for specific classes or methods. So for example,</P> | |
19650 | <DIV class="code"> | |
19651 | <PRE> | |
19652 | %feature("director") Foo; | |
19653 | %feature("nodirector") Foo::bar; | |
19654 | </PRE> | |
19655 | </DIV> | |
19656 | <P> will generate directors for all virtual methods of class Foo except | |
19657 | bar().</P> | |
19658 | <P> Directors can also be generated implicitly through inheritance. In | |
19659 | the following, class Bar will get a director class that handles the | |
19660 | methods one() and two() (but not three()):</P> | |
19661 | <DIV class="code"> | |
19662 | <PRE> | |
19663 | %feature("director") Foo; | |
19664 | class Foo { | |
19665 | public: | |
19666 | virtual void one(); | |
19667 | virtual void two(); | |
19668 | }; | |
19669 | ||
19670 | class Bar: public Foo { | |
19671 | public: | |
19672 | virtual void three(); | |
19673 | }; | |
19674 | </PRE> | |
19675 | </DIV> | |
19676 | <H3><A name="java_directors_classes"></A>19.5.2 Director classes</H3> | |
19677 | <P> For each class that has directors enabled, SWIG generates a new | |
19678 | class that derives from both the class in question and a special <TT> | |
19679 | Swig::Director</TT> class. These new classes, referred to as director | |
19680 | classes, can be loosely thought of as the C++ equivalent of the Java | |
19681 | proxy classes. The director classes store a pointer to their underlying | |
19682 | Java proxy classes.</P> | |
19683 | <P> For simplicity let's ignore the <TT>Swig::Director</TT> class and | |
19684 | refer to the original C++ class as the director's base class. By | |
19685 | default, a director class extends all virtual methods in the | |
19686 | inheritance chain of its base class (see the preceding section for how | |
19687 | to modify this behavior). Thus all virtual method calls, whether they | |
19688 | originate in C++ or in Java via proxy classes, eventually end up in at | |
19689 | the implementation in the director class. The job of the director | |
19690 | methods is to route these method calls to the appropriate place in the | |
19691 | inheritance chain. By "appropriate place" we mean the method that would | |
19692 | have been called if the C++ base class and its Java derived classes | |
19693 | were seamlessly integrated. That seamless integration is exactly what | |
19694 | the director classes provide, transparently skipping over all the messy | |
19695 | JNI glue code that binds the two languages together.</P> | |
19696 | <P> In reality, the "appropriate place" is one of only two | |
19697 | possibilities: C++ or Java. Once this decision is made, the rest is | |
19698 | fairly easy. If the correct implementation is in C++, then the lowest | |
19699 | implementation of the method in the C++ inheritance chain is called | |
19700 | explicitly. If the correct implementation is in Java, the Java API is | |
19701 | used to call the method of the underlying Java object (after which the | |
19702 | usual virtual method resolution in Java automatically finds the right | |
19703 | implementation).</P> | |
19704 | <H3><A name="java_directors_overhead"></A>19.5.3 Overhead and code bloat</H3> | |
19705 | <P> Enabling directors for a class will generate a new director method | |
19706 | for every virtual method in the class' inheritance chain. This alone | |
19707 | can generate a lot of code bloat for large hierarchies. Method | |
19708 | arguments that require complex conversions to and from Java types can | |
19709 | result in large director methods. For this reason it is recommended | |
19710 | that directors are selectively enabled only for specific classes that | |
19711 | are likely to be extended in Java and used in C++.</P> | |
19712 | <P> Although directors make it natural to mix native C++ objects with | |
19713 | Java objects (as director objects), one should be aware of the obvious | |
19714 | fact that method calls to Java objects from C++ will be much slower | |
19715 | than calls to C++ objects. Additionally, compared to classes that do | |
19716 | not use directors, the call routing in the director methods adds a | |
19717 | small overhead. This situation can be optimized by selectively enabling | |
19718 | director methods (using the %feature directive) for only those methods | |
19719 | that are likely to be extended in Java.</P> | |
19720 | <H3><A name="java_directors_example"></A>19.5.4 Simple directors example</H3> | |
19721 | <P> Consider the following SWIG interface file:</P> | |
19722 | <DIV class="code"> | |
19723 | <PRE> | |
19724 | %module(directors="1") example; | |
19725 | ||
19726 | %feature("director") DirectorBase; | |
19727 | ||
19728 | class DirectorBase { | |
19729 | public: | |
19730 | virtual ~DirectorBase() {} | |
19731 | virtual void upcall_method() {} | |
19732 | }; | |
19733 | ||
19734 | void callup(DirectorBase *director) { | |
19735 | director->upcall_method(); | |
19736 | } | |
19737 | </PRE> | |
19738 | </DIV> | |
19739 | <P> The following <CODE>directorDerived</CODE> Java class is derived | |
19740 | from the Java proxy class <CODE>DirectorBase</CODE> and overrides <CODE> | |
19741 | upcall_method()</CODE>. When C++ code invokes <CODE>upcall_method()</CODE> | |
19742 | , the SWIG-generated C++ code redirects the call via JNI to the Java <CODE> | |
19743 | directorDerived</CODE> subclass. Naturally, the SWIG generated C++ code | |
19744 | and the generated Java intermediate class marshall and convert | |
19745 | arguments between C++ and Java when needed.</P> | |
19746 | <DIV class="code"> | |
19747 | <PRE> | |
19748 | public class directorDerived extends DirectorBase { | |
19749 | public directorDerived() { | |
19750 | } | |
19751 | ||
19752 | public void upcall_method() { | |
19753 | System.out.println("directorDerived::upcall_method() invoked."); | |
19754 | } | |
19755 | } | |
19756 | </PRE> | |
19757 | </DIV> | |
19758 | <P> Running the following Java code</P> | |
19759 | <DIV class="code"> | |
19760 | <PRE> | |
19761 | directorDerived director = new directorDerived(); | |
19762 | example.callup(director); | |
19763 | </PRE> | |
19764 | </DIV> | |
19765 | <P> will result in the following being output:</P> | |
19766 | <DIV class="code"> | |
19767 | <PRE> | |
19768 | directorDerived::upcall_method() invoked. | |
19769 | </PRE> | |
19770 | </DIV> | |
19771 | <H2><A name="common_customization"></A>19.6 Common customization | |
19772 | features</H2> | |
19773 | <P> An earlier section presented the absolute basics of C/C++ wrapping. | |
19774 | If you do nothing but feed SWIG a header file, you will get an | |
19775 | interface that mimics the behavior described. However, sometimes this | |
19776 | isn't enough to produce a nice module. Certain types of functionality | |
19777 | might be missing or the interface to certain functions might be | |
19778 | awkward. This section describes some common SWIG features that are used | |
19779 | to improve the interface to existing C/C++ code.</P> | |
19780 | <H3><A name="helper_functions"></A>19.6.1 C/C++ helper functions</H3> | |
19781 | <P> Sometimes when you create a module, it is missing certain bits of | |
19782 | functionality. For example, if you had a function like this</P> | |
19783 | <DIV class="code"> | |
19784 | <PRE> | |
19785 | typedef struct Image {...}; | |
19786 | void set_transform(Image *im, double m[4][4]); | |
19787 | </PRE> | |
19788 | </DIV> | |
19789 | <P> it would be accessible from Java, but there may be no easy way to | |
19790 | call it. The problem here is that a type wrapper class is generated for | |
19791 | the two dimensional array parameter so there is no easy way to | |
19792 | construct and manipulate a suitable <TT>double [4][4]</TT> value. To | |
19793 | fix this, you can write some extra C helper functions. Just use the <TT> | |
19794 | %inline</TT> directive. For example:</P> | |
19795 | <DIV class="code"> | |
19796 | <PRE> | |
19797 | %inline %{ | |
19798 | /* Note: double[4][4] is equivalent to a pointer to an array double (*)[4] */ | |
19799 | double (*new_mat44())[4] { | |
19800 | return (double (*)[4]) malloc(16*sizeof(double)); | |
19801 | } | |
19802 | void free_mat44(double (*x)[4]) { | |
19803 | free(x); | |
19804 | } | |
19805 | void mat44_set(double x[4][4], int i, int j, double v) { | |
19806 | x[i][j] = v; | |
19807 | } | |
19808 | double mat44_get(double x[4][4], int i, int j) { | |
19809 | return x[i][j]; | |
19810 | } | |
19811 | %} | |
19812 | </PRE> | |
19813 | </DIV> | |
19814 | <P> From Java, you could then write code like this:</P> | |
19815 | <DIV class="code"> | |
19816 | <PRE> | |
19817 | Image im = new Image(); | |
19818 | SWIGTYPE_p_a_4__double a = example.new_mat44(); | |
19819 | example.mat44_set(a,0,0,1.0); | |
19820 | example.mat44_set(a,1,1,1.0); | |
19821 | example.mat44_set(a,2,2,1.0); | |
19822 | ... | |
19823 | example.set_transform(im,a); | |
19824 | example.free_mat44(a); | |
19825 | </PRE> | |
19826 | </DIV> | |
19827 | <P> Admittedly, this is not the most elegant looking approach. However, | |
19828 | it works and it wasn't too hard to implement. It is possible to improve | |
19829 | on this using Java code, typemaps, and other customization features as | |
19830 | covered in later sections, but sometimes helper functions are a quick | |
19831 | and easy solution to difficult cases.</P> | |
19832 | <H3><A name="class_extension"></A>19.6.2 Class extension with %extend</H3> | |
19833 | <P> One of the more interesting features of SWIG is that it can extend | |
19834 | structures and classes with new methods or constructors. Here is a | |
19835 | simple example:</P> | |
19836 | <DIV class="code"> | |
19837 | <PRE> | |
19838 | %module example | |
19839 | %{ | |
19840 | #include "someheader.h" | |
19841 | %} | |
19842 | ||
19843 | struct Vector { | |
19844 | double x,y,z; | |
19845 | }; | |
19846 | ||
19847 | %extend Vector { | |
19848 | char *toString() { | |
19849 | static char tmp[1024]; | |
19850 | sprintf(tmp,"Vector(%g,%g,%g)", self->x,self->y,self->z); | |
19851 | return tmp; | |
19852 | } | |
19853 | Vector(double x, double y, double z) { | |
19854 | Vector *v = (Vector *) malloc(sizeof(Vector)); | |
19855 | v->x = x; | |
19856 | v->y = y; | |
19857 | v->z = z; | |
19858 | return v; | |
19859 | } | |
19860 | }; | |
19861 | </PRE> | |
19862 | </DIV> | |
19863 | <P> Now, in Java</P> | |
19864 | <DIV class="code"> | |
19865 | <PRE> | |
19866 | Vector v = new Vector(2,3,4); | |
19867 | System.out.println(v); | |
19868 | </PRE> | |
19869 | </DIV> | |
19870 | <P> will display</P> | |
19871 | <DIV class="code"> | |
19872 | <PRE> | |
19873 | Vector(2,3,4) | |
19874 | </PRE> | |
19875 | </DIV> | |
19876 | <P> <TT>%extend</TT> works with both C and C++ code. It does not modify | |
19877 | the underlying object in any way---the extensions only show up in the | |
19878 | Java interface.</P> | |
19879 | <H3><A name="exception_handling"></A>19.6.3 Exception handling with | |
19880 | %exception and %javaexception</H3> | |
19881 | <P> If a C or C++ function throws an error, you may want to convert that | |
19882 | error into a Java exception. To do this, you can use the <TT>%exception</TT> | |
19883 | directive. The <TT>%exception</TT> directive simply lets you rewrite | |
19884 | part of the generated wrapper code to include an error check. It is | |
19885 | detailed in full in the <A href="#exception">Exception handling with | |
19886 | %exception</A> section.</P> | |
19887 | <P> In C, a function often indicates an error by returning a status code | |
19888 | (a negative number or a NULL pointer perhaps). Here is a simple example | |
19889 | of how you might handle that:</P> | |
19890 | <DIV class="code"> | |
19891 | <PRE> | |
19892 | %exception malloc { | |
19893 | $action | |
19894 | if (!result) { | |
19895 | jclass clazz = (*jenv)->FindClass(jenv, "java/lang/OutOfMemoryError"); | |
19896 | (*jenv)->ThrowNew(jenv, clazz, "Not enough memory"); | |
19897 | return $null; | |
19898 | } | |
19899 | } | |
19900 | void *malloc(size_t nbytes); | |
19901 | </PRE> | |
19902 | </DIV> | |
19903 | <P> In Java,</P> | |
19904 | <DIV class="code"> | |
19905 | <PRE> | |
19906 | SWIGTYPE_p_void a = example.malloc(2000000000); | |
19907 | </PRE> | |
19908 | </DIV> | |
19909 | <P> will produce a familiar looking Java exception:</P> | |
19910 | <DIV class="code"> | |
19911 | <PRE> | |
19912 | Exception in thread "main" java.lang.OutOfMemoryError: Not enough memory | |
19913 | at exampleJNI.malloc(Native Method) | |
19914 | at example.malloc(example.java:16) | |
19915 | at main.main(main.java:112) | |
19916 | </PRE> | |
19917 | </DIV> | |
19918 | <P> If a library provides some kind of general error handling framework, | |
19919 | you can also use that. For example:</P> | |
19920 | <DIV class="code"> | |
19921 | <PRE> | |
19922 | %exception malloc { | |
19923 | $action | |
19924 | if (err_occurred()) { | |
19925 | jclass clazz = (*jenv)->FindClass(jenv, "java/lang/OutOfMemoryError"); | |
19926 | (*jenv)->ThrowNew(jenv, clazz, "Not enough memory"); | |
19927 | return $null; | |
19928 | } | |
19929 | } | |
19930 | void *malloc(size_t nbytes); | |
19931 | </PRE> | |
19932 | </DIV> | |
19933 | <P> No declaration name is given to <TT>%exception</TT>, it is applied | |
19934 | to all wrapper functions. The <TT>$action</TT> is a SWIG special | |
19935 | variable and is replaced by the C/C++ function call being wrapped. The <TT> | |
19936 | return $null;</TT> handles all native method return types, namely those | |
19937 | that have a void return and those that do not. This is useful for | |
19938 | typemaps that will be used in native method returning all return types. | |
19939 | See the section on <A href="#special_variables">Java special variables</A> | |
19940 | for further explanation.</P> | |
19941 | <P> C++ exceptions are also easy to handle. We can catch the C++ | |
19942 | exception and rethrow it as a Java exception like this:</P> | |
19943 | <DIV class="code"> | |
19944 | <PRE> | |
19945 | %exception getitem { | |
19946 | try { | |
19947 | $action | |
19948 | } catch (std::out_of_range &e) { | |
19949 | jclass clazz = jenv->FindClass("java/lang/Exception"); | |
19950 | jenv->ThrowNew(clazz, "Range error"); | |
19951 | return $null; | |
19952 | } | |
19953 | } | |
19954 | ||
19955 | class FooClass { | |
19956 | public: | |
19957 | FooClass *getitem(int index); // Might throw std::out_of_range exception | |
19958 | ... | |
19959 | }; | |
19960 | </PRE> | |
19961 | </DIV> | |
19962 | <P> In the example above, <TT>java.lang.Exception</TT> is a checked | |
19963 | exception class and so ought to be declared in the throws clause of <TT> | |
19964 | getitem</TT>. Classes can be specified for adding to the throws clause | |
19965 | using <TT>%javaexception(classes)</TT> instead of <TT>%exception</TT>, | |
19966 | where <TT>classes</TT> is a string containing one or more comma | |
19967 | separated Java classes. The <TT>%nojavaexception</TT> feature is the | |
19968 | equivalent to <TT>%noexception</TT> and clears previously declared | |
19969 | exception handlers.</P> | |
19970 | <DIV class="code"> | |
19971 | <PRE> | |
19972 | %javaexception("java.lang.Exception") getitem { | |
19973 | try { | |
19974 | $action | |
19975 | } catch (std::out_of_range &e) { | |
19976 | jclass clazz = jenv->FindClass("java/lang/Exception"); | |
19977 | jenv->ThrowNew(clazz, "Range error"); | |
19978 | return $null; | |
19979 | } | |
19980 | } | |
19981 | ||
19982 | class FooClass { | |
19983 | public: | |
19984 | FooClass *getitem(int index); // Might throw std::out_of_range exception | |
19985 | ... | |
19986 | }; | |
19987 | </PRE> | |
19988 | </DIV> | |
19989 | <P> The generated proxy method now generates a throws clause containing <TT> | |
19990 | java.lang.Exception</TT>:</P> | |
19991 | <DIV class="code"> | |
19992 | <PRE> | |
19993 | public class FooClass { | |
19994 | ... | |
19995 | public FooClass getitem(int index) throws java.lang.Exception { ... } | |
19996 | ... | |
19997 | } | |
19998 | </PRE> | |
19999 | </DIV> | |
20000 | <P> The examples above first use the C JNI calling syntax then the C++ | |
20001 | JNI calling syntax. The C++ calling syntax will not compile as C and | |
20002 | also visa versa. It is however possible to write JNI calls which will | |
20003 | compile under both C and C++ and is covered in the <A href="#typemaps_for_c_and_c++"> | |
20004 | Typemaps for both C and C++ compilation</A> section.</P> | |
20005 | <P> The language-independent <TT>exception.i</TT> library file can also | |
20006 | be used to raise exceptions. See the <A href="#Library">SWIG Library</A> | |
20007 | chapter. The typemap example <A href="#exception_typemap">Handling C++ | |
20008 | exception specifications as Java exceptions</A> provides further | |
20009 | exception handling capabilities.</P> | |
20010 | <H3><A name="method_access"></A>19.6.4 Method access with | |
20011 | %javamethodmodifiers</H3> | |
20012 | <P> A Java feature called <TT>%javamethodmodifiers</TT> can be used to | |
20013 | change the method modifiers from the default <TT>public</TT>. It | |
20014 | applies to both module class methods and proxy class methods. For | |
20015 | example:</P> | |
20016 | <DIV class="code"> | |
20017 | <PRE> | |
20018 | %javamethodmodifiers protect_me() "protected"; | |
20019 | void protect_me(); | |
20020 | </PRE> | |
20021 | </DIV> | |
20022 | <P> Will produce the method in the module class with protected access.</P> | |
20023 | <DIV class="code"> | |
20024 | <PRE> | |
20025 | protected static void protect_me() { | |
20026 | exampleJNI.protect_me(); | |
20027 | } | |
20028 | </PRE> | |
20029 | </DIV> | |
20030 | <H2><A name="tips_techniques"></A>19.7 Tips and techniques</H2> | |
20031 | <P> Although SWIG is largely automatic, there are certain types of | |
20032 | wrapping problems that require additional user input. Examples include | |
20033 | dealing with output parameters, strings and arrays. This chapter | |
20034 | discusses the common techniques for solving these problems.</P> | |
20035 | <H3><A name="input_output_parameters"></A>19.7.1 Input and output | |
20036 | parameters using primitive pointers and references</H3> | |
20037 | <P> A common problem in some C programs is handling parameters passed as | |
20038 | simple pointers or references. For example:</P> | |
20039 | <DIV class="code"> | |
20040 | <PRE> | |
20041 | void add(int x, int y, int *result) { | |
20042 | *result = x + y; | |
20043 | } | |
20044 | </PRE> | |
20045 | </DIV> | |
20046 | <P> or perhaps</P> | |
20047 | <DIV class="code"> | |
20048 | <PRE> | |
20049 | int sub(int *x, int *y) { | |
20050 | return *x-*y; | |
20051 | } | |
20052 | </PRE> | |
20053 | </DIV> | |
20054 | <P> The <TT>typemaps.i</TT> library file will help in these situations. | |
20055 | For example:</P> | |
20056 | <DIV class="code"> | |
20057 | <PRE> | |
20058 | %module example | |
20059 | %include "typemaps.i" | |
20060 | ||
20061 | void add(int, int, int *OUTPUT); | |
20062 | int sub(int *INPUT, int *INPUT); | |
20063 | </PRE> | |
20064 | </DIV> | |
20065 | <P> In Java, this allows you to pass simple values. For example:</P> | |
20066 | <DIV class="code"> | |
20067 | <PRE> | |
20068 | int result = example.sub(7,4); | |
20069 | System.out.println("7 - 4 = " + result); | |
20070 | int[] sum = {0}; | |
20071 | example.add(3,4,sum); | |
20072 | System.out.println("3 + 4 = " + sum[0]); | |
20073 | </PRE> | |
20074 | </DIV> | |
20075 | <P> Which will display:</P> | |
20076 | <DIV class="code"> | |
20077 | <PRE> | |
20078 | 7 - 4 = 3 | |
20079 | 3 + 4 = 7 | |
20080 | </PRE> | |
20081 | </DIV> | |
20082 | <P> Notice how the <TT>INPUT</TT> parameters allow integer values to be | |
20083 | passed instead of pointers and how the <TT>OUTPUT</TT> parameter will | |
20084 | return the result in the first element of the integer array.</P> | |
20085 | <P> If you don't want to use the names <TT>INPUT</TT> or <TT>OUTPUT</TT> | |
20086 | , use the <TT>%apply</TT> directive. For example:</P> | |
20087 | <DIV class="code"> | |
20088 | <PRE> | |
20089 | %module example | |
20090 | %include "typemaps.i" | |
20091 | ||
20092 | %apply int *OUTPUT { int *result }; | |
20093 | %apply int *INPUT { int *x, int *y}; | |
20094 | ||
20095 | void add(int x, int y, int *result); | |
20096 | int sub(int *x, int *y); | |
20097 | </PRE> | |
20098 | </DIV> | |
20099 | <P> If a function mutates one of its parameters like this,</P> | |
20100 | <DIV class="code"> | |
20101 | <PRE> | |
20102 | void negate(int *x) { | |
20103 | *x = -(*x); | |
20104 | } | |
20105 | </PRE> | |
20106 | </DIV> | |
20107 | <P> you can use <TT>INOUT</TT> like this:</P> | |
20108 | <DIV class="code"> | |
20109 | <PRE> | |
20110 | %include "typemaps.i" | |
20111 | ... | |
20112 | void negate(int *INOUT); | |
20113 | </PRE> | |
20114 | </DIV> | |
20115 | <P> In Java, the input parameter is the first element in a 1 element | |
20116 | array and is replaced by the output of the function. For example:</P> | |
20117 | <DIV class="code"> | |
20118 | <PRE> | |
20119 | int[] neg = {3}; | |
20120 | example.negate(neg); | |
20121 | System.out.println("Negative of 3 = " + neg[0]); | |
20122 | </PRE> | |
20123 | </DIV> | |
20124 | <P> And no prizes for guessing the output:</P> | |
20125 | <DIV class="code"> | |
20126 | <PRE> | |
20127 | Negative of 3 = -3 | |
20128 | </PRE> | |
20129 | </DIV> | |
20130 | <P> These typemaps can also be applied to C++ references. The above | |
20131 | examples would work the same if they had been defined using references | |
20132 | instead of pointers. For example, the Java code to use the <TT>negate</TT> | |
20133 | function would be the same if it were defined either as it is above:</P> | |
20134 | <DIV class="code"> | |
20135 | <PRE> | |
20136 | void negate(int *INOUT); | |
20137 | </PRE> | |
20138 | </DIV> | |
20139 | <P> or using a reference:</P> | |
20140 | <DIV class="code"> | |
20141 | <PRE> | |
20142 | void negate(int &INOUT); | |
20143 | </PRE> | |
20144 | </DIV> | |
20145 | <P> Note: Since most Java primitive types are immutable and are passed | |
20146 | by value, it is not possible to perform in-place modification of a type | |
20147 | passed as a parameter.</P> | |
20148 | <P> Be aware that the primary purpose of the <TT>typemaps.i</TT> file is | |
20149 | to support primitive datatypes. Writing a function like this</P> | |
20150 | <DIV class="code"> | |
20151 | <PRE> | |
20152 | void foo(Bar *OUTPUT); | |
20153 | </PRE> | |
20154 | </DIV> | |
20155 | <P> will not have the intended effect since <TT>typemaps.i</TT> does not | |
20156 | define an OUTPUT rule for <TT>Bar</TT>.</P> | |
20157 | <H3><A name="simple_pointers"></A>19.7.2 Simple pointers</H3> | |
20158 | <P> If you must work with simple pointers such as <TT>int *</TT> or <TT> | |
20159 | double *</TT> another approach to using <TT>typemaps.i</TT> is to use | |
20160 | the <TT>cpointer.i</TT> pointer library file. For example:</P> | |
20161 | <DIV class="code"> | |
20162 | <PRE> | |
20163 | %module example | |
20164 | %include "cpointer.i" | |
20165 | ||
20166 | %inline %{ | |
20167 | extern void add(int x, int y, int *result); | |
20168 | %} | |
20169 | ||
20170 | %pointer_functions(int, intp); | |
20171 | </PRE> | |
20172 | </DIV> | |
20173 | <P> The <TT>%pointer_functions(type,name)</TT> macro generates five | |
20174 | helper functions that can be used to create, destroy, copy, assign, and | |
20175 | dereference a pointer. In this case, the functions are as follows:</P> | |
20176 | <DIV class="code"> | |
20177 | <PRE> | |
20178 | int *new_intp(); | |
20179 | int *copy_intp(int *x); | |
20180 | void delete_intp(int *x); | |
20181 | void intp_assign(int *x, int value); | |
20182 | int intp_value(int *x); | |
20183 | </PRE> | |
20184 | </DIV> | |
20185 | <P> In Java, you would use the functions like this:</P> | |
20186 | <DIV class="code"> | |
20187 | <PRE> | |
20188 | SWIGTYPE_p_int intPtr = example.new_intp(); | |
20189 | example.add(3,4,intPtr); | |
20190 | int result = example.intp_value(intPtr); | |
20191 | System.out.println("3 + 4 = " + result); | |
20192 | </PRE> | |
20193 | </DIV> | |
20194 | <P> If you replace <TT>%pointer_functions(int,intp)</TT> by <TT> | |
20195 | %pointer_class(int,intp)</TT>, the interface is more class-like.</P> | |
20196 | <DIV class="code"> | |
20197 | <PRE> | |
20198 | intp intPtr = new intp(); | |
20199 | example.add(3,4,intPtr.cast()); | |
20200 | int result = intPtr.value(); | |
20201 | System.out.println("3 + 4 = " + result); | |
20202 | </PRE> | |
20203 | </DIV> | |
20204 | <P> See the <A href="#Library">SWIG Library</A> chapter for further | |
20205 | details.</P> | |
20206 | <H3><A name="c_arrays"></A>19.7.3 Wrapping C arrays with Java arrays</H3> | |
20207 | <P> SWIG can wrap arrays in a more natural Java manner than the default | |
20208 | by using the <TT>arrays_java.i</TT> library file. Let's consider an | |
20209 | example:</P> | |
20210 | <DIV class="code"> | |
20211 | <PRE> | |
20212 | %include "arrays_java.i"; | |
20213 | int array[4]; | |
20214 | void populate(int x[]) { | |
20215 | int i; | |
20216 | for (i=0; i | |
20217 | <!--4; i++) | |
20218 | x[i] = 100 + i; | |
20219 | } | |
20220 | </pre--> | |
20221 | ||
20222 | </PRE> | |
20223 | </DIV> | |
20224 | <P> These one dimensional arrays can then be used as if they were Java | |
20225 | arrays:</P> | |
20226 | <DIV class="code"> | |
20227 | <PRE> | |
20228 | int[] array = new int[4]; | |
20229 | example.populate(array); | |
20230 | ||
20231 | System.out.print("array: "); | |
20232 | for (int i=0; i<array.length; i++) | |
20233 | System.out.print(array[i] + " "); | |
20234 | ||
20235 | example.setArray(array); | |
20236 | ||
20237 | int[] global_array = example.getArray(); | |
20238 | ||
20239 | System.out.print("\nglobal_array: "); | |
20240 | for (int i=0; i<array.length; i++) | |
20241 | System.out.print(global_array[i] + " "); | |
20242 | </PRE> | |
20243 | </DIV> | |
20244 | <P> Java arrays are always passed by reference, so any changes a | |
20245 | function makes to the array will be seen by the calling function. Here | |
20246 | is the output after running this code:</P> | |
20247 | <DIV class="code"> | |
20248 | <PRE> | |
20249 | array: 100 101 102 103 | |
20250 | global_array: 100 101 102 103 | |
20251 | </PRE> | |
20252 | </DIV> | |
20253 | <P> Note that for assigning array variables the length of the C variable | |
20254 | is used, so it is possible to use a Java array that is bigger than the | |
20255 | C code will cope with. Only the number of elements in the C array will | |
20256 | be used. However, if the Java array is not large enough then you are | |
20257 | likely to get a segmentation fault or access violation, just like you | |
20258 | would in C. When arrays are used in functions like <TT>populate</TT>, | |
20259 | the size of the C array passed to the function is determined by the | |
20260 | size of the Java array.</P> | |
20261 | <P> Please be aware that the typemaps in this library are not efficient | |
20262 | as all the elements are copied from the Java array to a C array | |
20263 | whenever the array is passed to and from JNI code. There is an | |
20264 | alternative approach using the SWIG array library and this is covered | |
20265 | in the next section.</P> | |
20266 | <H3><A name="unbounded_c_arrays"></A>19.7.4 Unbounded C Arrays</H3> | |
20267 | <P> Sometimes a C function expects an array to be passed as a pointer. | |
20268 | For example,</P> | |
20269 | <DIV class="code"> | |
20270 | <PRE> | |
20271 | int sumitems(int *first, int nitems) { | |
20272 | int i, sum = 0; | |
20273 | for (i = 0; i < nitems; i++) { | |
20274 | sum += first[i]; | |
20275 | } | |
20276 | return sum; | |
20277 | } | |
20278 | </PRE> | |
20279 | </DIV> | |
20280 | <P> One of the ways to wrap this is to apply the Java array typemaps | |
20281 | that come in the <TT>arrays_java.i</TT> library file:</P> | |
20282 | <DIV class="code"> | |
20283 | <PRE> | |
20284 | %include "arrays_java.i" | |
20285 | %apply int[] {int *}; | |
20286 | </PRE> | |
20287 | </DIV> | |
20288 | <P> The <TT>ANY</TT> size will ensure the typemap is applied to arrays | |
20289 | of all sizes. You could narrow the typemap matching rules by specifying | |
20290 | a particular array size. Now you can use a pure Java array and pass it | |
20291 | to the C code:</P> | |
20292 | <DIV class="code"> | |
20293 | <PRE> | |
20294 | int[] array = new int[10000000]; // Array of 10-million integers | |
20295 | for (int i=0; i<array.length; i++) { // Set some values | |
20296 | array[i] = i; | |
20297 | } | |
20298 | int sum = example.sumitems(array,10000); | |
20299 | System.out.println("Sum = " + sum); | |
20300 | </PRE> | |
20301 | </DIV> | |
20302 | <P> and the sum would be displayed:</P> | |
20303 | <DIV class="code"> | |
20304 | <PRE> | |
20305 | Sum = 49995000 | |
20306 | </PRE> | |
20307 | </DIV> | |
20308 | <P> This approach is probably the most natural way to use arrays. | |
20309 | However, it suffers from performance problems when using large arrays | |
20310 | as a lot of copying of the elements occurs in transferring the array | |
20311 | from the Java world to the C++ world. An alternative approach to using | |
20312 | Java arrays for C arrays is to use an alternative SWIG library file <TT> | |
20313 | carrays.i</TT>. This approach can be more efficient for large arrays as | |
20314 | the array is accessed one element at a time. For example:</P> | |
20315 | <DIV class="code"> | |
20316 | <PRE> | |
20317 | %include "carrays.i" | |
20318 | %array_functions(int, intArray); | |
20319 | </PRE> | |
20320 | </DIV> | |
20321 | <P> The <TT>%array_functions(type,name)</TT> macro generates four helper | |
20322 | functions that can be used to create and destroy arrays and operate on | |
20323 | elements. In this case, the functions are as follows:</P> | |
20324 | <DIV class="code"> | |
20325 | <PRE> | |
20326 | int *new_intArray(int nelements); | |
20327 | void delete_intArray(int *x); | |
20328 | int intArray_getitem(int *x, int index); | |
20329 | void intArray_setitem(int *x, int index, int value); | |
20330 | </PRE> | |
20331 | </DIV> | |
20332 | <P> In Java, you would use the functions like this:</P> | |
20333 | <DIV class="code"> | |
20334 | <PRE> | |
20335 | SWIGTYPE_p_int array = example.new_intArray(10000000); // Array of 10-million integers | |
20336 | for (int i=0; i | |
20337 | <!--10000; i++) { // Set some values | |
20338 | example.intArray_setitem(array,i,i); | |
20339 | } | |
20340 | int sum = example.sumitems(array,10000); | |
20341 | System.out.println("Sum = " + sum); | |
20342 | </pre--> | |
20343 | ||
20344 | </PRE> | |
20345 | </DIV> | |
20346 | <P> If you replace <TT>%array_functions(int,intp)</TT> by <TT> | |
20347 | %array_class(int,intp)</TT>, the interface is more class-like and a | |
20348 | couple more helper functions are available for casting between the | |
20349 | array and the type wrapper class.</P> | |
20350 | <DIV class="code"> | |
20351 | <PRE> | |
20352 | %include "carrays.i" | |
20353 | %array_class(int, intArray); | |
20354 | </PRE> | |
20355 | </DIV> | |
20356 | <P> The <TT>%array_class(type, name)</TT> macro creates wrappers for an | |
20357 | unbounded array object that can be passed around as a simple pointer | |
20358 | like <TT>int *</TT> or <TT>double *</TT>. For instance, you will be | |
20359 | able to do this in Java:</P> | |
20360 | <DIV class="code"> | |
20361 | <PRE> | |
20362 | intArray array = new intArray(10000000); // Array of 10-million integers | |
20363 | for (int i=0; i | |
20364 | <!--10000; i++) { // Set some values | |
20365 | array.setitem(i,i); | |
20366 | } | |
20367 | int sum = example.sumitems(array.cast(),10000); | |
20368 | System.out.println("Sum = " + sum); | |
20369 | </pre--> | |
20370 | ||
20371 | </PRE> | |
20372 | </DIV> | |
20373 | <P> The array "object" created by <TT>%array_class()</TT> does not | |
20374 | encapsulate pointers inside a special array object. In fact, there is | |
20375 | no bounds checking or safety of any kind (just like in C). Because of | |
20376 | this, the arrays created by this library are extremely low-level | |
20377 | indeed. You can't iterate over them nor can you even query their | |
20378 | length. In fact, any valid memory address can be accessed if you want | |
20379 | (negative indices, indices beyond the end of the array, etc.). Needless | |
20380 | to say, this approach is not going to suit all applications. On the | |
20381 | other hand, this low-level approach is extremely efficient and well | |
20382 | suited for applications in which you need to create buffers, package | |
20383 | binary data, etc.</P> | |
20384 | <H2><A name="java_typemaps"></A>19.8 Java typemaps</H2> | |
20385 | <P> This section describes how you can modify SWIG's default wrapping | |
20386 | behavior for various C/C++ datatypes using the <TT>%typemap</TT> | |
20387 | directive. You are advised to be familiar with the the material in the | |
20388 | "<A href="#Typemaps">Typemaps</A>" chapter. While not absolutely | |
20389 | essential knowledge, this section assumes some familiarity with the | |
20390 | Java Native Interface (JNI). JNI documentation can be consulted either | |
20391 | online at <A href="http://java.sun.com">Sun's Java web site</A> or from | |
20392 | a good JNI book. The following two books are recommended:</P> | |
20393 | <UL> | |
20394 | <LI> Title: 'Essential JNI: Java Native Interface.' Author: Rob Gordon. | |
20395 | Publisher: Prentice Hall. ISBN: 0-13-679895-0.</LI> | |
20396 | <LI> Title: 'The Java Native Interface: Programmer's Guide and | |
20397 | Specification.' Author: Sheng Liang. Publisher: Addison-Wesley. ISBN: | |
20398 | 0-201-32577-2.</LI> | |
20399 | </UL> | |
20400 | <P> Before proceeding, it should be stressed that typemaps are not a | |
20401 | required part of using SWIG---the default wrapping behavior is enough | |
20402 | in most cases. Typemaps are only used if you want to change some aspect | |
20403 | of the generated code.</P> | |
20404 | <H3><A name="default_primitive_type_mappings"></A>19.8.1 Default | |
20405 | primitive type mappings</H3> | |
20406 | <P> The following table lists the default type mapping from Java to | |
20407 | C/C++.</P> | |
20408 | <TABLE BORDER summary="Default primitive type mappings"> | |
20409 | <TR><TD><B>C/C++ type</B></TD><TD><B>Java type</B></TD><TD><B>JNI type</B> | |
20410 | </TD></TR> | |
20411 | <TR><TD>bool | |
20412 | <BR> const bool &</TD><TD>boolean</TD><TD>jboolean</TD></TR> | |
20413 | <TR><TD>char | |
20414 | <BR>const char &</TD><TD>char</TD><TD>jchar</TD></TR> | |
20415 | <TR><TD>signed char | |
20416 | <BR>const signed char &</TD><TD>byte</TD><TD>jbyte</TD></TR> | |
20417 | <TR><TD>unsigned char | |
20418 | <BR>const unsigned char &</TD><TD>short</TD><TD>jshort</TD></TR> | |
20419 | <TR><TD>short | |
20420 | <BR>const short &</TD><TD>short</TD><TD>jshort</TD></TR> | |
20421 | <TR><TD>unsigned short | |
20422 | <BR> const unsigned short &</TD><TD>int</TD><TD>jint</TD></TR> | |
20423 | <TR><TD>int | |
20424 | <BR> const int &</TD><TD>int</TD><TD>jint</TD></TR> | |
20425 | <TR><TD>unsigned int | |
20426 | <BR> const unsigned int &</TD><TD>long</TD><TD>jlong</TD></TR> | |
20427 | <TR><TD>long | |
20428 | <BR>const long &</TD><TD>int</TD><TD>jint</TD></TR> | |
20429 | <TR><TD>unsigned long | |
20430 | <BR>const unsigned long &</TD><TD>long</TD><TD>jlong</TD></TR> | |
20431 | <TR><TD>long long | |
20432 | <BR> const long long &</TD><TD>long</TD><TD>jlong</TD></TR> | |
20433 | <TR><TD>unsigned long long | |
20434 | <BR>const unsigned long long &</TD><TD>java.math.BigInteger</TD><TD> | |
20435 | jobject</TD></TR> | |
20436 | <TR><TD>float | |
20437 | <BR>const float &</TD><TD>float</TD><TD>jfloat</TD></TR> | |
20438 | <TR><TD>double | |
20439 | <BR> const double &</TD><TD>double</TD><TD>jdouble</TD></TR> | |
20440 | <TR><TD>char * | |
20441 | <BR>char []</TD><TD>String</TD><TD>jstring</TD></TR> | |
20442 | </TABLE> | |
20443 | <P> Note that SWIG wraps the C <TT>char</TT> type as a character. | |
20444 | Pointers and arrays of this type are wrapped as strings. The <TT>signed | |
20445 | char</TT> type can be used if you want to treat <TT>char</TT> as a | |
20446 | signed number rather than a character. Also note that all const | |
20447 | references to primitive types are treated as if they are passed by | |
20448 | value.</P> | |
20449 | <P> Given the following C function:</P> | |
20450 | <DIV class="code"> | |
20451 | <PRE> | |
20452 | void func(unsigned short a, char *b, const long &c, unsigned long long d); | |
20453 | </PRE> | |
20454 | </DIV> | |
20455 | <P> The module class method would be:</P> | |
20456 | <DIV class="code"> | |
20457 | <PRE> | |
20458 | public static void func(int a, String b, int c, java.math.BigInteger d) {...} | |
20459 | </PRE> | |
20460 | </DIV> | |
20461 | <P> The intermediary JNI class would use the same types:</P> | |
20462 | <DIV class="code"> | |
20463 | <PRE> | |
20464 | public final static native void func(int jarg1, String jarg2, int jarg3, | |
20465 | java.math.BigInteger jarg4); | |
20466 | </PRE> | |
20467 | </DIV> | |
20468 | <P> and the JNI function would look like this:</P> | |
20469 | <DIV class="code"> | |
20470 | <PRE> | |
20471 | JNIEXPORT void JNICALL Java_exampleJNI_func(JNIEnv *jenv, jclass jcls, | |
20472 | jint jarg1, jstring jarg2, jint jarg3, jobject jarg4) {...} | |
20473 | </PRE> | |
20474 | </DIV> | |
20475 | <P> The mappings for C <TT>int</TT> and C <TT>long</TT> are appropriate | |
20476 | for 32 bit applications which are used in the 32 bit JVMs. There is no | |
20477 | perfect mapping between Java and C as Java doesn't support all the | |
20478 | unsigned C data types. However, the mappings allow the full range of | |
20479 | values for each C type from Java.</P> | |
20480 | <H3><A name="jvm64"></A>19.8.2 Sixty four bit JVMs</H3> | |
20481 | <P> If you are using a 64 bit JVM you may have to override the C long, | |
20482 | but probably not C int default mappings. Mappings will be system | |
20483 | dependent, for example long will need remapping on Unix LP64 systems | |
20484 | (long, pointer 64 bits, int 32 bits), but not on Microsoft 64 bit | |
20485 | Windows which will be using a P64 IL32 (pointer 64 bits and int, long | |
20486 | 32 bits) model. This may be automated in a future version of SWIG. Note | |
20487 | that the Java write once run anywhere philosophy holds true for all | |
20488 | pure Java code when moving to a 64 bit JVM. Unfortunately it won't of | |
20489 | course hold true for JNI code.</P> | |
20490 | <H3><A name="what_is_typemap"></A>19.8.3 What is a typemap?</H3> | |
20491 | <P> A typemap is nothing more than a code generation rule that is | |
20492 | attached to a specific C datatype. For example, to convert integers | |
20493 | from Java to C, you might define a typemap like this:</P> | |
20494 | <DIV class="code"> | |
20495 | <PRE> | |
20496 | %module example | |
20497 | ||
20498 | %typemap(in) int { | |
20499 | $1 = $input; | |
20500 | printf("Received an integer : %d\n", $1); | |
20501 | } | |
20502 | %inline %{ | |
20503 | extern int fact(int nonnegative); | |
20504 | %} | |
20505 | </PRE> | |
20506 | </DIV> | |
20507 | <P> Typemaps are always associated with some specific aspect of code | |
20508 | generation. In this case, the "in" method refers to the conversion of | |
20509 | input arguments to C/C++. The datatype <TT>int</TT> is the datatype to | |
20510 | which the typemap will be applied. The supplied C code is used to | |
20511 | convert values. In this code a number of special variables prefaced by | |
20512 | a <TT>$</TT> are used. The <TT>$1</TT> variable is a placeholder for a | |
20513 | local variable of type <TT>int</TT>. The <TT>$input</TT> variable | |
20514 | contains the Java data, the JNI <TT>jint</TT> in this case.</P> | |
20515 | <P> When this example is compiled into a Java module, it can be used as | |
20516 | follows:</P> | |
20517 | <DIV class="code"> | |
20518 | <PRE> | |
20519 | System.out.println(example.fact(6)); | |
20520 | </PRE> | |
20521 | </DIV> | |
20522 | <P> and the output will be:</P> | |
20523 | <DIV class="code"> | |
20524 | <PRE> | |
20525 | Received an integer : 6 | |
20526 | 720 | |
20527 | </PRE> | |
20528 | </DIV> | |
20529 | <P> In this example, the typemap is applied to all occurrences of the <TT> | |
20530 | int</TT> datatype. You can refine this by supplying an optional | |
20531 | parameter name. For example:</P> | |
20532 | <DIV class="code"> | |
20533 | <PRE> | |
20534 | %module example | |
20535 | ||
20536 | %typemap(in) int nonnegative { | |
20537 | $1 = $input; | |
20538 | printf("Received an integer : %d\n", $1); | |
20539 | } | |
20540 | ||
20541 | %inline %{ | |
20542 | extern int fact(int nonnegative); | |
20543 | %} | |
20544 | </PRE> | |
20545 | </DIV> | |
20546 | <P> In this case, the typemap code is only attached to arguments that | |
20547 | exactly match <TT>int nonnegative</TT>.</P> | |
20548 | <P> The application of a typemap to specific datatypes and argument | |
20549 | names involves more than simple text-matching--typemaps are fully | |
20550 | integrated into the SWIG C++ type-system. When you define a typemap for | |
20551 | <TT>int</TT>, that typemap applies to <TT>int</TT> and qualified | |
20552 | variations such as <TT>const int</TT>. In addition, the typemap system | |
20553 | follows <TT>typedef</TT> declarations. For example:</P> | |
20554 | <DIV class="code"> | |
20555 | <PRE> | |
20556 | %typemap(in) int nonnegative { | |
20557 | $1 = $input; | |
20558 | printf("Received an integer : %d\n", $1); | |
20559 | } | |
20560 | %inline %{ | |
20561 | typedef int Integer; | |
20562 | extern int fact(Integer nonnegative); // Above typemap is applied | |
20563 | %} | |
20564 | </PRE> | |
20565 | </DIV> | |
20566 | <P> However, the matching of <TT>typedef</TT> only occurs in one | |
20567 | direction. If you defined a typemap for <TT>Integer</TT>, it is not | |
20568 | applied to arguments of type <TT>int</TT>.</P> | |
20569 | <P> Typemaps can also be defined for groups of consecutive arguments. | |
20570 | For example:</P> | |
20571 | <DIV class="code"> | |
20572 | <PRE> | |
20573 | %typemap(in) (char *str, int len) { | |
20574 | ... | |
20575 | }; | |
20576 | ||
20577 | int count(char c, char *str, int len); | |
20578 | </PRE> | |
20579 | </DIV> | |
20580 | <P> When a multi-argument typemap is defined, the arguments are always | |
20581 | handled as a single Java parameter. This allows the function to be used | |
20582 | like this (notice how the length parameter is omitted):</P> | |
20583 | <DIV class="code"> | |
20584 | <PRE> | |
20585 | int c = example.count('e',"Hello World"); | |
20586 | </PRE> | |
20587 | </DIV> | |
20588 | <H3><A name="typemaps_c_to_java_types"></A>19.8.4 Typemaps for mapping | |
20589 | C/C++ types to Java types</H3> | |
20590 | <P> The typemaps available to the Java module include the common | |
20591 | typemaps listed in the main typemaps section. There are a number of | |
20592 | additional typemaps which are necessary for using SWIG with Java. The | |
20593 | most important of these implement the mapping of C/C++ types to Java | |
20594 | types:</P> | |
20595 | <BR> | |
20596 | <TABLE BORDER summary="Typemap mappings for C/C++ types to Java types"> | |
20597 | <TR><TD><B>Typemap</B></TD><TD><B>Description</B></TD></TR> | |
20598 | <TR><TD>jni</TD><TD>JNI C types. These provide the default mapping of | |
20599 | types from C/C++ to JNI for use in the JNI (C/C++) code.</TD></TR> | |
20600 | <TR><TD>jtype</TD><TD>Java intermediary types. These provide the default | |
20601 | mapping of types from C/C++ to Java for use in the native functions in | |
20602 | the intermediary JNI class. The type must be the equivalent Java type | |
20603 | for the JNI C type specified in the "jni" typemap.</TD></TR> | |
20604 | <TR><TD>jstype</TD><TD>Java types. These provide the default mapping of | |
20605 | types from C/C++ to Java for use in the Java module class, proxy | |
20606 | classes and type wrapper classes.</TD></TR> | |
20607 | <TR><TD>javain</TD><TD>Conversion from jstype to jtype. These are Java | |
20608 | code typemaps which transform the type used in the Java module class, | |
20609 | proxy classes and type wrapper classes (as specified in the "jstype" | |
20610 | typemap) to the type used in the Java intermediary JNI class (as | |
20611 | specified in the "jtype" typemap). In other words the typemap provides | |
20612 | the conversion to the native method call parameter types.</TD></TR> | |
20613 | <TR><TD>javaout</TD><TD>Conversion from jtype to jstype. These are Java | |
20614 | code typemaps which transform the type used in the Java intermediary | |
20615 | JNI class (as specified in the "jtype" typemap) to the Java type used | |
20616 | in the Java module class, proxy classes and type wrapper classes (as | |
20617 | specified in the "jstype" typemap). In other words the typemap provides | |
20618 | the conversion from the native method call return type.</TD></TR> | |
20619 | <TR><TD>javadirectorin</TD><TD>Conversion from jtype to jstype for | |
20620 | director methods. These are Java code typemaps which transform the type | |
20621 | used in the Java intermediary JNI class (as specified in the "jtype" | |
20622 | typemap) to the Java type used in the Java module class, proxy classes | |
20623 | and type wrapper classes (as specified in the "jstype" typemap). This | |
20624 | typemap provides the conversion for the parameters in the director | |
20625 | methods when calling up from C++ to Java. See <A href="#java_directors_typemaps"> | |
20626 | Director typemaps</A>.</TD></TR> | |
20627 | <TR><TD>javadirectorout</TD><TD>Conversion from jstype to jtype for | |
20628 | director methods. These are Java code typemaps which transform the type | |
20629 | used in the Java module class, proxy classes and type wrapper classes | |
20630 | (as specified in the "jstype" typemap) to the type used in the Java | |
20631 | intermediary JNI class (as specified in the "jtype" typemap). This | |
20632 | typemap provides the conversion for the return type in the director | |
20633 | methods when returning from the C++ to Java upcall. See <A href="#java_directors_typemaps"> | |
20634 | Director typemaps</A>.</TD></TR> | |
20635 | <TR><TD>directorin</TD><TD>Conversion from C++ type to jni type for | |
20636 | director methods. These are C++ typemaps which converts the parameters | |
20637 | used in the C++ director method to the appropriate JNI intermediary | |
20638 | type. The conversion is done in JNI code prior to calling the Java | |
20639 | function from the JNI code. See <A href="#java_directors_typemaps"> | |
20640 | Director typemaps</A>.</TD></TR> | |
20641 | </TABLE> | |
20642 | <P> If you are writing your own typemaps to handle a particular type, | |
20643 | you will normally have to write a collection of them. The default | |
20644 | typemaps are in "<TT>java.swg</TT>" and so might be a good place for | |
20645 | finding typemaps to base any new ones on.</P> | |
20646 | <P> The "jni", "jtype" and "jstype" typemaps are usually defined | |
20647 | together to handle the Java to C/C++ type mapping. An "in" typemap | |
20648 | should be accompanied by a "javain" typemap and likewise an "out" | |
20649 | typemap by a "javaout" typemap. If an "in" typemap is written, a | |
20650 | "freearg" and "argout" typemap may also need to be written as some | |
20651 | types have a default "freearg" and/or "argout" typemap which may need | |
20652 | overriding. The "freearg" typemap sometimes releases memory allocated | |
20653 | by the "in" typemap. The "argout" typemap sometimes sets values in | |
20654 | function parameters which are passed by reference in Java.</P> | |
20655 | <P> The default code generated by SWIG for the Java module comes from | |
20656 | the typemaps in the "<TT>java.swg</TT>" library file which implements | |
20657 | the <A href="#default_primitive_type_mappings">Default primitive type | |
20658 | mappings</A> covered earlier. There are other type mapping typemaps in | |
20659 | the Java library. These are listed below:</P> | |
20660 | <BR> | |
20661 | <TABLE BORDER summary="Java library typemap mappings"> | |
20662 | <TR VALIGN="TOP"><TD><B>C Type</B></TD><TD><B>Typemap</B></TD><TD><B> | |
20663 | File</B></TD><TD><B>Kind</B></TD><TD><B>Java Type</B></TD><TD><B> | |
20664 | Function</B></TD></TR> | |
20665 | <TR><TD>primitive pointers and references</TD><TD>INPUT</TD><TD> | |
20666 | typemaps.i</TD><TD>input</TD><TD>Java basic types</TD><TD>Allows values | |
20667 | to be used for C functions taking pointers for data input.</TD></TR> | |
20668 | <TR><TD>primitive pointers and references</TD><TD>OUTPUT</TD><TD> | |
20669 | typemaps.i</TD><TD>output</TD><TD>Java basic type arrays</TD><TD>Allows | |
20670 | values held within an array to be used for C functions taking pointers | |
20671 | for data output.</TD></TR> | |
20672 | <TR><TD>primitive pointers and references</TD><TD>INOUT</TD><TD> | |
20673 | typemaps.i</TD><TD>input | |
20674 | <BR>output</TD><TD>Java basic type arrays</TD><TD>Allows values held | |
20675 | within an array to be used for C functions taking pointers for data | |
20676 | input and output.</TD></TR> | |
20677 | <TR><TD>string | |
20678 | <BR> wstring</TD><TD>[unnamed]</TD><TD>std_string.i</TD><TD>input | |
20679 | <BR> output</TD><TD>String</TD><TD>Use for std::string mapping to Java | |
20680 | String.</TD></TR> | |
20681 | <TR><TD>arrays of primitive types</TD><TD>[unnamed]</TD><TD> | |
20682 | arrays_java.i</TD><TD>input | |
20683 | <BR> output</TD><TD>arrays of primitive Java types</TD><TD>Use for | |
20684 | mapping C arrays to Java arrays.</TD></TR> | |
20685 | <TR><TD>arrays of classes/structs/unions</TD><TD>JAVA_ARRAYSOFCLASSES | |
20686 | macro</TD><TD>arrays_java.i</TD><TD>input | |
20687 | <BR> output</TD><TD>arrays of proxy classes</TD><TD>Use for mapping C | |
20688 | arrays to Java arrays.</TD></TR> | |
20689 | <TR><TD>arrays of enums</TD><TD>ARRAYSOFENUMS</TD><TD>arrays_java.i</TD><TD> | |
20690 | input | |
20691 | <BR> output</TD><TD>int[]</TD><TD>Use for mapping C arrays to Java | |
20692 | arrays (typeunsafe and simple enum wrapping approaches only).</TD></TR> | |
20693 | <TR VALIGN="TOP"><TD>char *</TD><TD>BYTE</TD><TD>various.i</TD><TD>input</TD><TD> | |
20694 | byte[]</TD><TD VALIGN="TOP">Java byte array is converted to char array</TD> | |
20695 | </TR> | |
20696 | <TR><TD>char **</TD><TD>STRING_ARRAY</TD><TD>various.i</TD><TD>input | |
20697 | <BR> output</TD><TD>String[]</TD><TD>Use for mapping NULL terminated | |
20698 | arrays of C strings to Java String arrays</TD></TR> | |
20699 | </TABLE> | |
20700 | <H3><A name="typemap_attributes"></A>19.8.5 Java typemap attributes</H3> | |
20701 | <P> There is an additional typemap attribute that the Java module | |
20702 | supports. This is the 'throws' attribute. The throws attribute is | |
20703 | optional and specified after the typemap name and contains one or more | |
20704 | comma separated classes for adding to the throws clause for any methods | |
20705 | that use that typemap. It is analogous to the <A href="#exception_handling"> | |
20706 | %javaexception</A> feature's throws attribute.</P> | |
20707 | <DIV class="code"> | |
20708 | <PRE> | |
20709 | %typemap(typemapname, throws="ExceptionClass1, ExceptionClass2") type { ... } | |
20710 | </PRE> | |
20711 | </DIV> | |
20712 | <P> The attribute is necessary for supporting Java checked exceptions | |
20713 | and can be added to just about any typemap. The list of typemaps | |
20714 | include all the C/C++ (JNI) typemaps in the "<A href="#Typemaps"> | |
20715 | Typemaps</A>" chapter and the Java specific typemaps listed in <A href="#typemaps_c_to_java_types"> | |
20716 | the previous section</A>, barring the "jni", "jtype" and "jstype" | |
20717 | typemaps as they could never contain code to throw an exception.</P> | |
20718 | <P> The throws clause is generated for the proxy method as well as the | |
20719 | JNI method in the JNI intermediary class. If a method uses more than | |
20720 | one typemap and each of those typemaps have classes specified in the | |
20721 | throws clause, the union of the exception classes is added to the | |
20722 | throws clause ensuring there are no duplicate classes. See the <A href="#nan_exception_typemap"> | |
20723 | NaN exception example</A> for further usage.</P> | |
20724 | <H3><A name="special_variables"></A>19.8.6 Java special variables</H3> | |
20725 | <P> The standard SWIG special variables are available for use within | |
20726 | typemaps as described in the <A href="#Typemaps">Typemaps documentation</A> | |
20727 | , for example <TT>$1</TT>, <TT>$input</TT>,<TT>$result</TT> etc.</P> | |
20728 | <P> The Java module uses a few additional special variables:</P> | |
20729 | <P><B> <TT>$javaclassname</TT></B> | |
20730 | <BR> <TT>$javaclassname</TT> is similar to <TT>$1_type</TT>. It expands | |
20731 | to the class name for use in Java. When wrapping a union, struct or | |
20732 | class, it expands to the Java proxy class name. Otherwise it expands to | |
20733 | the type wrapper class name. For example, <TT>$javaclassname</TT> is | |
20734 | replaced by <TT>Foo</TT> when the wrapping a <TT>struct Foo</TT> or <TT> | |
20735 | struct Foo *</TT> and <TT>SWIGTYPE_p_unsigned_short</TT> is used for <TT> | |
20736 | unsigned short *</TT>.</P> | |
20737 | <P><B> <TT>$null</TT></B> | |
20738 | <BR> Used in input typemaps to return early from JNI functions that have | |
20739 | either void or a non-void return type. Example:</P> | |
20740 | <DIV class="code"> | |
20741 | <PRE> | |
20742 | %typemap(check) int * %{ | |
20743 | if (error) { | |
20744 | SWIG_JavaThrowException(jenv, SWIG_JavaIndexOutOfBoundsException, "Array element error"); | |
20745 | return $null; | |
20746 | } | |
20747 | %} | |
20748 | </PRE> | |
20749 | </DIV> | |
20750 | <P> If the typemap gets put into a function with void as return, $null | |
20751 | will expand to nothing:</P> | |
20752 | <DIV class="code"> | |
20753 | <PRE> | |
20754 | JNIEXPORT void JNICALL Java_jnifn(...) { | |
20755 | if (error) { | |
20756 | SWIG_JavaThrowException(jenv, SWIG_JavaIndexOutOfBoundsException, "Array element error"); | |
20757 | return ; | |
20758 | } | |
20759 | ... | |
20760 | } | |
20761 | </PRE> | |
20762 | </DIV> | |
20763 | <P> otherwise $null expands to<I> NULL</I></P> | |
20764 | <DIV class="code"> | |
20765 | <PRE> | |
20766 | JNIEXPORT jobject JNICALL Java_jnifn(...) { | |
20767 | if (error) { | |
20768 | SWIG_JavaThrowException(jenv, SWIG_JavaIndexOutOfBoundsException, "Array element error"); | |
20769 | return NULL; | |
20770 | } | |
20771 | ... | |
20772 | } | |
20773 | </PRE> | |
20774 | </DIV> | |
20775 | <P><B> <TT>$javainput, $jnicall and $owner</TT></B> | |
20776 | <BR> The $javainput special variable is used in "javain" typemaps and | |
20777 | $jnicall and $owner are used in "javaout" typemaps. $jnicall is | |
20778 | analogous to $action in %exception. It is replaced by the call to the | |
20779 | native method in the intermediary JNI class. $owner is replaced by | |
20780 | either <TT>true</TT> if %newobject has been used, otherwise <TT>false</TT> | |
20781 | . $javainput is analogous to the $input special variable. It is replaced | |
20782 | by the parameter name.</P> | |
20783 | <P> Here is an example:</P> | |
20784 | <DIV class="code"> | |
20785 | <PRE> | |
20786 | %typemap(javain) Class "Class.getCPtr($javainput)" | |
20787 | %typemap(javain) unsigned short "$javainput" | |
20788 | %typemap(javaout) Class * { | |
20789 | return new Class($jnicall, $owner); | |
20790 | } | |
20791 | ||
20792 | %inline %{ | |
20793 | class Class {...}; | |
20794 | Class * bar(Class cls, unsigned short ush) { return new Class(); }; | |
20795 | %} | |
20796 | </PRE> | |
20797 | </DIV> | |
20798 | <P> The generated proxy code is then:</P> | |
20799 | <DIV class="code"> | |
20800 | <PRE> | |
20801 | public static Class bar(Class cls, int ush) { | |
20802 | return new Class(exampleJNI.bar(Class.getCPtr(cls), ush), false); | |
20803 | } | |
20804 | </PRE> | |
20805 | </DIV> | |
20806 | <P> Here $javainput has been replaced by <TT>cls</TT> and <TT>ush</TT>. | |
20807 | $jnicall has been replaced by the native method call, <TT> | |
20808 | exampleJNI.bar(...)</TT> and $owner has been replaced by <TT>false</TT>. | |
20809 | If %newobject is used by adding the following at the beginning of our | |
20810 | example:</P> | |
20811 | <DIV class="code"> | |
20812 | <PRE> | |
20813 | %newobject bar(Class cls, unsigned short ush); | |
20814 | </PRE> | |
20815 | </DIV> | |
20816 | <P> The generated code constructs the return type using <TT>true</TT> | |
20817 | indicating the proxy class <TT>Class</TT> is responsible for destroying | |
20818 | the C++ memory allocated for it in <TT>bar</TT>:</P> | |
20819 | <DIV class="code"> | |
20820 | <PRE> | |
20821 | public static Class bar(Class cls, int ush) { | |
20822 | return new Class(exampleJNI.bar(Class.getCPtr(cls), ush), true); | |
20823 | } | |
20824 | </PRE> | |
20825 | </DIV> | |
20826 | <P><B> <TT>$static</TT></B> | |
20827 | <BR> This special variable expands to either<I> static</I> or nothing | |
20828 | depending on whether the class is an inner Java class or not. It is | |
20829 | used in the "javaclassmodifiers" typemap so that global classes can be | |
20830 | wrapped as Java proxy classes and nested C++ classes/enums can be | |
20831 | wrapped with the Java equivalent, that is, static inner proxy classes.</P> | |
20832 | <P><B> <TT>$jniinput, $javacall and $packagepath</TT></B> | |
20833 | <BR> These special variables are used in the directors typemaps. See <A href="#java_directors_typemaps"> | |
20834 | Director specific typemaps</A> for details.</P> | |
20835 | <P><B> <TT>$module</TT></B> | |
20836 | <BR> This special variable expands to the module name, as specified by <TT> | |
20837 | %module</TT> or the <TT>-module</TT> commandline option. Useful for | |
20838 | constructing the intermediary classname, which is just <TT>$moduleJNI</TT> | |
20839 | .</P> | |
20840 | <H3><A name="typemaps_for_c_and_c++"></A>19.8.7 Typemaps for both C and | |
20841 | C++ compilation</H3> | |
20842 | <P> JNI calls must be written differently depending on whether the code | |
20843 | is being compiled as C or C++. For example C compilation requires the | |
20844 | pointer to a function pointer struct member syntax like</P> | |
20845 | <DIV class="code"> | |
20846 | <PRE> | |
20847 | const jclass clazz = (*jenv)->FindClass(jenv, "java/lang/String"); | |
20848 | </PRE> | |
20849 | </DIV> | |
20850 | <P> whereas C++ code compilation of the same function call is a member | |
20851 | function call using a class pointer like</P> | |
20852 | <DIV class="code"> | |
20853 | <PRE> | |
20854 | const jclass clazz = jenv->FindClass("java/lang/String"); | |
20855 | </PRE> | |
20856 | </DIV> | |
20857 | <P> To enable typemaps to be used for either C or C++ compilation, a set | |
20858 | of JCALLx macros have been defined in Lib/java/javahead.swg, where x is | |
20859 | the number of arguments in the C++ version of the JNI call. The above | |
20860 | JNI calls would be written in a typemap like this</P> | |
20861 | <DIV class="code"> | |
20862 | <PRE> | |
20863 | const jclass clazz = JCALL1(FindClass, jenv, "java/lang/String"); | |
20864 | </PRE> | |
20865 | </DIV> | |
20866 | <P> Note that the SWIG preprocessor expands these into the appropriate C | |
20867 | or C++ JNI calling convention. The C calling convention is emitted by | |
20868 | default and the C++ calling convention is emitted when using the -c++ | |
20869 | SWIG commandline option. If you do not intend your code to be targeting | |
20870 | both C and C++ then your typemaps can use the appropriate JNI calling | |
20871 | convention and need not use the JCALLx macros.</P> | |
20872 | <H3><A name="java_code_typemaps"></A>19.8.8 Java code typemaps</H3> | |
20873 | <P> Most of SWIG's typemaps are used for the generation of C/C++ code. | |
20874 | The typemaps in this section are used solely for the generation of Java | |
20875 | code. Elements of proxy classes and type wrapper classes come from the | |
20876 | following typemaps (the defaults).</P> | |
20877 | <P><TT>%typemap(javabase)</TT></P> | |
20878 | <DIV class="indent"> base (extends) for Java class: empty default</DIV> | |
20879 | <P><TT>%typemap(javabody)</TT></P> | |
20880 | <DIV class="indent"> the essential support body for proxy classes (proxy | |
20881 | base classes only), typewrapper classes and enum classes. Default | |
20882 | contains extra constructors, memory ownership control member variables | |
20883 | (<TT>swigCMemOwn</TT>, <TT>swigCPtr</TT>), the <TT>getCPtr</TT> method | |
20884 | etc.</DIV> | |
20885 | <P><TT>%typemap(javabody_derived)</TT></P> | |
20886 | <DIV class="indent"> the essential support body for proxy classes | |
20887 | (derived classes only). Same as "javabody" typemap, but only used for | |
20888 | proxy derived classes.</DIV> | |
20889 | <P><TT>%typemap(javaclassmodifiers)</TT></P> | |
20890 | <DIV class="indent"> class modifiers for the Java class: default is | |
20891 | "public class"</DIV> | |
20892 | <P><TT>%typemap(javacode)</TT></P> | |
20893 | <DIV class="indent"> Java code is copied verbatim to the Java class: | |
20894 | empty default</DIV> | |
20895 | <P><TT>%typemap(javadestruct, methodname="delete")</TT> | |
20896 | <BR></P> | |
20897 | <DIV class="indent"> destructor wrapper - the <TT>delete()</TT> method | |
20898 | (proxy classes only), used for all proxy classes except those which | |
20899 | have a base class : default calls C++ destructor (or frees C memory) | |
20900 | and resets <TT>swigCPtr</TT> and <TT>swigCMemOwn</TT> flags | |
20901 | <BR> | |
20902 | <BR> Note that the <TT>delete()</TT> method name is configurable and is | |
20903 | specified by the <TT>methodname</TT> attribute.</DIV> | |
20904 | <P><TT>%typemap(javadestruct_derived, methodname="delete")</TT></P> | |
20905 | <DIV class="indent"> destructor wrapper - the <TT>delete()</TT> method | |
20906 | (proxy classes only), same as "javadestruct" but only used for derived | |
20907 | proxy classes : default calls C++ destructor (or frees C memory) and | |
20908 | resets <TT>swigCPtr</TT> and <TT>swigCMemOwn</TT> flags | |
20909 | <BR> | |
20910 | <BR> Note that the <TT>delete()</TT> method name is configurable and is | |
20911 | specified by the <TT>methodname</TT> attribute.</DIV> | |
20912 | <P><TT>%typemap(javaimports)</TT></P> | |
20913 | <DIV class="indent"> import statements for Java class: empty default</DIV> | |
20914 | <P><TT>%typemap(javainterfaces)</TT></P> | |
20915 | <DIV class="indent"> interfaces (extends) for Java class: empty default</DIV> | |
20916 | <P><TT>%typemap(javafinalize)</TT></P> | |
20917 | <DIV class="indent"> the <TT>finalize()</TT> method (proxy classes | |
20918 | only): default calls the <TT>delete()</TT> method</DIV> | |
20919 | <P><B> Compatibility Note:</B> In SWIG-1.3.21 and earlier releases, | |
20920 | typemaps called "javagetcptr" and "javaptrconstructormodifiers" were | |
20921 | available. These are deprecated and the "javabody" typemap can be used | |
20922 | instead.</P> | |
20923 | <P> In summary the contents of the typemaps make up a proxy class like | |
20924 | this:</P> | |
20925 | <DIV class="code"> | |
20926 | <PRE> | |
20927 | [ javaimports typemap ] | |
20928 | [ javaclassmodifiers typemap ] javaclassname extends [ javabase typemap ] | |
20929 | implements [ javainterfaces typemap ] { | |
20930 | [ javabody or javabody_derived typemap ] | |
20931 | [ javafinalize typemap ] | |
20932 | public void <I>delete</I>() [ javadestruct OR javadestruct_derived typemap ] | |
20933 | [ javacode typemap ] | |
20934 | ... proxy functions ... | |
20935 | } | |
20936 | </PRE> | |
20937 | </DIV> | |
20938 | <P> Note the <TT><I>delete</I>()</TT> methodname is configurable, see | |
20939 | "javadestruct" and "javadestruct_derived" typemaps above.</P> | |
20940 | <P> The type wrapper class is similar in construction:</P> | |
20941 | <DIV class="code"> | |
20942 | <PRE> | |
20943 | [ javaimports typemap ] | |
20944 | [ javaclassmodifiers typemap ] javaclassname extends [ javabase typemap ] | |
20945 | implements [ javainterfaces typemap ] { | |
20946 | [ javabody typemap ] | |
20947 | [ javacode typemap ] | |
20948 | } | |
20949 | </PRE> | |
20950 | </DIV> | |
20951 | <P>The enum class is also similar in construction:</P> | |
20952 | <DIV class="code"> | |
20953 | <PRE> | |
20954 | [ javaimports typemap ] | |
20955 | [ javaclassmodifiers typemap ] javaclassname extends [ javabase typemap ] | |
20956 | implements [ javainterfaces typemap ] { | |
20957 | ... Enum values ... | |
20958 | [ javabody typemap ] | |
20959 | [ javacode typemap ] | |
20960 | } | |
20961 | </PRE> | |
20962 | </DIV> | |
20963 | <P> The "javaimports" typemap is ignored if the enum class is wrapped by | |
20964 | an inner Java class, that is when wrapping an enum declared within a | |
20965 | C++ class.</P> | |
20966 | <P> The defaults can be overridden to tailor these classes. Here is an | |
20967 | example which will change the <TT>getCPtr</TT> method and constructor | |
20968 | from the default protected access to public access. This has a | |
20969 | practical application if you are invoking SWIG more than once and | |
20970 | generating the wrapped classes into different packages in each | |
20971 | invocation. If the classes in one package are using the classes in | |
20972 | another package, then these methods need to be public.</P> | |
20973 | <DIV class="code"> | |
20974 | <PRE> | |
20975 | %typemap(javabody) SWIGTYPE %{ | |
20976 | private long swigCPtr; | |
20977 | protected boolean swigCMemOwn; | |
20978 | ||
20979 | public $javaclassname(long cPtr, boolean cMemoryOwn) { | |
20980 | swigCMemOwn = cMemoryOwn; | |
20981 | swigCPtr = cPtr; | |
20982 | } | |
20983 | ||
20984 | public static long getCPtr($javaclassname obj) { | |
20985 | return (obj == null) ? 0 : obj.swigCPtr; | |
20986 | } | |
20987 | %} | |
20988 | </PRE> | |
20989 | </DIV> | |
20990 | <P> The typemap code is the same that is in "<TT>java.swg</TT>", barring | |
20991 | the two method modifiers. Note that <TT>SWIGTYPE</TT> will target all | |
20992 | proxy classes, but not the type wrapper classes. Also the above typemap | |
20993 | is only used for proxy classes that are potential base classes. To | |
20994 | target proxy classes that are derived from a wrapped class as well, the | |
20995 | "javabody_derived" typemap should also be overridden.</P> | |
20996 | <P> For the typemap to be used in all type wrapper classes, all the | |
20997 | different types that type wrapper classes could be used for should be | |
20998 | targeted:</P> | |
20999 | <DIV class="code"> | |
21000 | <PRE> | |
21001 | %typemap(javabody) SWIGTYPE *, SWIGTYPE &, SWIGTYPE [], SWIGTYPE (CLASS::*) %{ | |
21002 | private long swigCPtr; | |
21003 | ||
21004 | public $javaclassname(long cPtr, boolean bFutureUse) { | |
21005 | swigCPtr = cPtr; | |
21006 | } | |
21007 | ||
21008 | protected $javaclassname() { | |
21009 | swigCPtr = 0; | |
21010 | } | |
21011 | ||
21012 | public static long getCPtr($javaclassname obj) { | |
21013 | return (obj == null) ? 0 : obj.swigCPtr; | |
21014 | } | |
21015 | %} | |
21016 | </PRE> | |
21017 | </DIV> | |
21018 | <P> Again this is the same that is in "<TT>java.swg</TT>", barring the | |
21019 | method modifier for <TT>getCPtr</TT>.</P> | |
21020 | <H3><A name="java_directors_typemaps"></A>19.8.9 Director specific | |
21021 | typemaps</H3> | |
21022 | <P> The Java directors feature requires the "javadirectorin", | |
21023 | "javadirectorout" and the "directorin" typemaps in order to work | |
21024 | properly. The "javapackage" typemap is an optional typemap used to | |
21025 | identify the Java package path for individual SWIG generated proxy | |
21026 | classes.</P> | |
21027 | <P><TT>%typemap(directorin)</TT></P> | |
21028 | <DIV class="indent"> | |
21029 | <P> The "directorin" typemap is used for converting arguments in the C++ | |
21030 | director class to the appropriate JNI type before the upcall to Java. | |
21031 | This typemap also specifies the JNI field descriptor for the type in | |
21032 | the "descriptor" attribute. For example, integers are converted as | |
21033 | follows:</P> | |
21034 | <DIV class="code"> | |
21035 | <PRE> | |
21036 | %typemap(directorin,descriptor="I") int "$input = (jint) $1;" | |
21037 | </PRE> | |
21038 | </DIV> | |
21039 | <P> <CODE>$input</CODE> is the SWIG name of the JNI temporary variable | |
21040 | passed to Java in the upcall. The <CODE>descriptor="I"</CODE> will put | |
21041 | an <CODE>I</CODE> into the JNI field descriptor that identifies the | |
21042 | Java method that will be called from C++. For more about JNI field | |
21043 | descriptors and their importance, refer to the <A href="#java_typemaps"> | |
21044 | JNI documentation mentioned earlier</A>. A typemap for C character | |
21045 | strings is:</P> | |
21046 | <DIV class="code"> | |
21047 | <PRE> | |
21048 | %typemap(directorin,descriptor="Ljava/lang/String;") char * | |
21049 | %{ $input = jenv->NewStringUTF($1); %} | |
21050 | </PRE> | |
21051 | </DIV> | |
21052 | <P> User-defined types have the default "descriptor" attribute "<CODE> | |
21053 | L$packagepath/$javaclassname;</CODE>" where <CODE>$packagepath</CODE> is | |
21054 | the package name passed from the SWIG command line and <CODE> | |
21055 | $javaclassname</CODE> is the Java proxy class' name. If the <TT>-package</TT> | |
21056 | commandline option is not used to specify the package, then | |
21057 | '$packagepath/' will be removed from the resulting output JNI field | |
21058 | descriptor.<B> Do not forget the terminating ';' for JNI field | |
21059 | descriptors starting with 'L'.</B> If the ';' is left out, Java will | |
21060 | generate a "method not found" runtime error.</P> | |
21061 | </DIV> | |
21062 | <P><TT>%typemap(javadirectorin)</TT></P> | |
21063 | <DIV class="indent"> | |
21064 | <P> Conversion from jtype to jstype for director methods. These are Java | |
21065 | code typemaps which transform the type used in the Java intermediary | |
21066 | JNI class (as specified in the "jtype" typemap) to the Java type used | |
21067 | in the Java module class, proxy classes and type wrapper classes (as | |
21068 | specified in the "jstype" typemap). This typemap provides the | |
21069 | conversion for the parameters in the director methods when calling up | |
21070 | from C++ to Java.</P> | |
21071 | <P> For primitive types, this typemap is usually specified as:</P> | |
21072 | <DIV class="code"> | |
21073 | <PRE> | |
21074 | %typemap(javadirectorin) int "$jniinput" | |
21075 | </PRE> | |
21076 | </DIV> | |
21077 | <P> The <CODE>$jniinput</CODE> special variable is analogous to <CODE> | |
21078 | $javainput</CODE> special variable. It is replaced by the input | |
21079 | parameter name.</P> | |
21080 | </DIV> | |
21081 | <P><TT>%typemap(javadirectorout)</TT></P> | |
21082 | <DIV class="indent"> | |
21083 | <P> Conversion from jstype to jtype for director methods. These are Java | |
21084 | code typemaps which transform the type used in the Java module class, | |
21085 | proxy classes and type wrapper classes (as specified in the "jstype" | |
21086 | typemap) to the type used in the Java intermediary JNI class (as | |
21087 | specified in the "jtype" typemap). This typemap provides the conversion | |
21088 | for the return type in the director methods when returning from the C++ | |
21089 | to Java upcall.</P> | |
21090 | <P> For primitive types, this typemap is usually specified as:</P> | |
21091 | <DIV class="code"> | |
21092 | <PRE> | |
21093 | %typemap(javadirectorout) int "$javacall" | |
21094 | </PRE> | |
21095 | </DIV> | |
21096 | <P> The <CODE>$javacall</CODE> special variable is analogous to the <CODE> | |
21097 | $jnicall</CODE> special variable. It is replaced by the call to the | |
21098 | target Java method. The target method is the method in the Java proxy | |
21099 | class which overrides the virtual C++ method in the C++ base class.</P> | |
21100 | </DIV> | |
21101 | <P><TT>%typemap(javapackage)</TT></P> | |
21102 | <DIV class="indent"> | |
21103 | <P> The "javapackage" typemap is optional; it serves to identify a | |
21104 | class's Java package. This typemap should be used in conjunction with | |
21105 | classes that are defined outside of the current SWIG interface file. | |
21106 | For example:</P> | |
21107 | <DIV class="code"> | |
21108 | <PRE> | |
21109 | // class Foo is handled in a different interface file: | |
21110 | %import "Foo.i" | |
21111 | ||
21112 | %feature("director") Example; | |
21113 | ||
21114 | %inline { | |
21115 | class Bar { }; | |
21116 | ||
21117 | class Example { | |
21118 | public: | |
21119 | virtual ~Example(); | |
21120 | void ping(Foo *arg1, Bar *arg2); | |
21121 | }; | |
21122 | } | |
21123 | </PRE> | |
21124 | </DIV> | |
21125 | <P> Assume that the Foo class is part of the Java package<I> | |
21126 | com.wombat.foo</I> but the above interface file is part of the Java | |
21127 | package<I> com.wombat.example</I>. Without the "javapackage" typemap, | |
21128 | SWIG will assume that the Foo class belongs to<I> com.wombat.example</I> | |
21129 | class. The corrected interface file looks like:</P> | |
21130 | <DIV class="code"> | |
21131 | <PRE> | |
21132 | // class Foo is handled in a different interface file: | |
21133 | %import "Foo.i" | |
21134 | %typemap("javapackage") Foo, Foo *, Foo & "com.wombat.foo"; | |
21135 | %feature("director") Example; | |
21136 | ||
21137 | %inline { | |
21138 | class Bar { }; | |
21139 | ||
21140 | class Example { | |
21141 | public: | |
21142 | virtual ~Example(); | |
21143 | void ping(Foo *arg1, Bar *arg2); | |
21144 | }; | |
21145 | } | |
21146 | </PRE> | |
21147 | </DIV> | |
21148 | <P> SWIG looks up the package based on the<B> actual</B> type (plain | |
21149 | Foo, Foo pointer and Foo reference), so it is important to associate | |
21150 | all three types with the desired package. Practically speaking, you | |
21151 | should create a separate SWIG interface file, which is %import-ed into | |
21152 | each SWIG interface file, when you have multiple Java packages. Note | |
21153 | the helper macros below, <CODE>OTHER_PACKAGE_SPEC</CODE> and <CODE> | |
21154 | ANOTHER_PACKAGE_SPEC</CODE>, which reduce the amount of extra typing. "<CODE> | |
21155 | TYPE...</CODE>" is useful when passing templated types to the macro, | |
21156 | since multiargument template types appear to the SWIG preprocessor as | |
21157 | multiple macro arguments.</P> | |
21158 | <DIV class="code"> | |
21159 | <PRE> | |
21160 | %typemap("javapackage") SWIGTYPE, SWIGTYPE *, SWIGTYPE & | |
21161 | "package.for.most.classes"; | |
21162 | ||
21163 | %define OTHER_PACKAGE_SPEC(TYPE...) | |
21164 | %typemap("javapackage") TYPE, TYPE *, TYPE & "package.for.other.classes"; | |
21165 | %enddef | |
21166 | ||
21167 | %define ANOTHER_PACKAGE_SPEC(TYPE...) | |
21168 | %typemap("javapackage") TYPE, TYPE *, TYPE & "package.for.another.set"; | |
21169 | %enddef | |
21170 | ||
21171 | OTHER_PACKAGE_SPEC(Package_2_class_one) | |
21172 | ANOTHER_PACKAGE_SPEC(Package_3_class_two) | |
21173 | /* etc */ | |
21174 | </PRE> | |
21175 | </DIV> | |
21176 | <P> The basic strategy here is to provide a default package typemap for | |
21177 | the majority of the classes, only providing "javapackage" typemaps for | |
21178 | the exceptions.</P> | |
21179 | </DIV> | |
21180 | <H2><A name="typemap_examples"></A>19.9 Typemap Examples</H2> | |
21181 | <P> This section includes a few examples of typemaps. For more examples, | |
21182 | you might look at the files "<TT>java.swg</TT>" and "<TT>typemaps.i</TT> | |
21183 | " in the SWIG library.</P> | |
21184 | <H3><A name="simpler_enum_classes"></A>19.9.1 Simpler Java enums for | |
21185 | enums without initializers</H3> | |
21186 | <P> The default <A href="#proper_enums_classes">Proper Java enums</A> | |
21187 | approach to wrapping enums is somewhat verbose. This is to handle all | |
21188 | possible C/C++ enums, in particular enums with initializers. The | |
21189 | generated code can be simplified if the enum being wrapped does not | |
21190 | have any initializers.</P> | |
21191 | <P> The following shows how to remove the support methods that are | |
21192 | generated by default and instead use the methods in the Java enum base | |
21193 | class <TT>java.lang.Enum</TT> and <TT>java.lang.Class</TT> for | |
21194 | marshalling enums between C/C++ and Java. The type used for the | |
21195 | typemaps below is <TT>enum SWIGTYPE</TT> which is the default type used | |
21196 | for all enums. The "enums.swg" file should be examined in order to see | |
21197 | the original overridden versions of the typemaps.</P> | |
21198 | <DIV class="code"> | |
21199 | <PRE> | |
21200 | %include "enums.swg" | |
21201 | ||
21202 | %typemap(javain) enum SWIGTYPE "$javainput.ordinal()" | |
21203 | %typemap(javaout) enum SWIGTYPE { | |
21204 | return $javaclassname.class.getEnumConstants()[$jnicall]; | |
21205 | } | |
21206 | %typemap(javabody) enum SWIGTYPE "" | |
21207 | ||
21208 | %inline %{ | |
21209 | enum HairType { blonde, ginger, brunette }; | |
21210 | void setHair(HairType h); | |
21211 | HairType getHair(); | |
21212 | %} | |
21213 | </PRE> | |
21214 | </DIV> | |
21215 | <P> SWIG will generate the following Java enum, which is somewhat | |
21216 | simpler than the default:</P> | |
21217 | <DIV class="code"> | |
21218 | <PRE> | |
21219 | public enum HairType { | |
21220 | blonde, | |
21221 | ginger, | |
21222 | brunette; | |
21223 | } | |
21224 | </PRE> | |
21225 | </DIV> | |
21226 | <P> and the two Java proxy methods will be:</P> | |
21227 | <DIV class="code"> | |
21228 | <PRE> | |
21229 | public static void setHair(HairType h) { | |
21230 | exampleJNI.setHair(h.ordinal()); | |
21231 | } | |
21232 | ||
21233 | public static HairType getHair() { | |
21234 | return HairType.class.getEnumConstants()[exampleJNI.getHair()]; | |
21235 | } | |
21236 | </PRE> | |
21237 | </DIV> | |
21238 | <P> For marshalling Java enums to C/C++ enums, the <TT>ordinal</TT> | |
21239 | method is used to convert the Java enum into an integer value for | |
21240 | passing to the JNI layer, see the "javain" typemap. For marshalling | |
21241 | C/C++ enums to Java enums, the C/C++ enum value is cast to an integer | |
21242 | in the C/C++ typemaps (not shown). This integer value is then used to | |
21243 | index into the array of enum constants that the Java language provides. | |
21244 | See the <TT>getEnumConstants</TT> method in the "javaout" typemap.</P> | |
21245 | <P> These typemaps can often be used as the default for wrapping enums | |
21246 | as in many cases there won't be any enum initializers. In fact a good | |
21247 | strategy is to always use these typemaps and to specifically handle | |
21248 | enums with initializers using %apply. This would be done by using the | |
21249 | original versions of these typemaps in "enums.swg" under another | |
21250 | typemap name for applying using %apply.</P> | |
21251 | <H3><A name="exception_typemap"></A>19.9.2 Handling C++ exception | |
21252 | specifications as Java exceptions</H3> | |
21253 | <P> This example demonstrates various ways in which C++ exceptions can | |
21254 | be tailored and converted into Java exceptions. Let's consider a simple | |
21255 | file class <TT>SimpleFile</TT> and an exception class <TT>FileException</TT> | |
21256 | which it may throw on error:</P> | |
21257 | <DIV class="code"> | |
21258 | <PRE> | |
21259 | %include "std_string.i" // for std::string typemaps | |
21260 | #include <string> | |
21261 | ||
21262 | class FileException { | |
21263 | std::string message; | |
21264 | public: | |
21265 | FileException(const std::string& msg) : message(msg) {} | |
21266 | std::string what() { | |
21267 | return message; | |
21268 | } | |
21269 | }; | |
21270 | ||
21271 | class SimpleFile { | |
21272 | std::string filename; | |
21273 | public: | |
21274 | SimpleFile(const std::string& filename) : filename(filename) {} | |
21275 | void open() throw(FileException) { | |
21276 | ... | |
21277 | } | |
21278 | }; | |
21279 | </PRE> | |
21280 | </DIV> | |
21281 | <P> As the <TT>open</TT> method has a C++ exception specification, SWIG | |
21282 | will parse this and know that the method can throw an exception. The <A href="#throws_typemap"> | |
21283 | "throws" typemap</A> is then used when SWIG encounters an exception | |
21284 | specification. The default generic "throws" typemap looks like this:</P> | |
21285 | <DIV class="code"> | |
21286 | <PRE> | |
21287 | %typemap(throws) SWIGTYPE, SWIGTYPE &, SWIGTYPE *, SWIGTYPE [ANY] %{ | |
21288 | SWIG_JavaThrowException(jenv, SWIG_JavaRuntimeException, | |
21289 | "C++ $1_type exception thrown"); | |
21290 | return $null; | |
21291 | %} | |
21292 | </PRE> | |
21293 | </DIV> | |
21294 | <P> Basically SWIG will generate a C++ try catch block and the body of | |
21295 | the "throws" typemap constitutes the catch block. The above typemap | |
21296 | calls a SWIG supplied method which throws a <TT> | |
21297 | java.lang.RuntimeException</TT>. This exception class is a runtime | |
21298 | exception and therefore not a checked exception. If, however, we wanted | |
21299 | to throw a checked exception, say <TT>java.io.IOException</TT>, then we | |
21300 | could use the following typemap:</P> | |
21301 | <DIV class="code"> | |
21302 | <PRE> | |
21303 | %typemap(throws, throws="java.io.IOException") FileException { | |
21304 | jclass excep = jenv->FindClass("java/io/IOException"); | |
21305 | if (excep) | |
21306 | jenv->ThrowNew(excep, $1.what().c_str()); | |
21307 | return $null; | |
21308 | } | |
21309 | </PRE> | |
21310 | </DIV> | |
21311 | <P> Note that this typemap uses the 'throws' <A href="#typemap_attributes"> | |
21312 | typemap attribute</A> to ensure a throws clause is generated. The | |
21313 | generated proxy method then specifies the checked exception by | |
21314 | containing <TT>java.io.IOException</TT> in the throws clause:</P> | |
21315 | <DIV class="code"> | |
21316 | <PRE> | |
21317 | public class SimpleFile { | |
21318 | ... | |
21319 | public void open() throws java.io.IOException { ... } | |
21320 | } | |
21321 | </PRE> | |
21322 | </DIV> | |
21323 | <P> Lastly, if you don't want to map your C++ exception into one of the | |
21324 | standard Java exceptions, the C++ class can be wrapped and turned into | |
21325 | a custom Java exception class. If we go back to our example, the first | |
21326 | thing we must do is get SWIG to wrap <TT>FileException</TT> and ensure | |
21327 | that it derives from <TT>java.lang.Exception</TT>. Additionally, we | |
21328 | might want to override the <TT>java.lang.Exception.getMessage()</TT> | |
21329 | method. The typemaps to use then are as follows:</P> | |
21330 | <DIV class="code"> | |
21331 | <PRE> | |
21332 | %typemap(javabase) FileException "java.lang.Exception"; | |
21333 | %typemap(javacode) FileException %{ | |
21334 | public String getMessage() { | |
21335 | return what(); | |
21336 | } | |
21337 | %} | |
21338 | </PRE> | |
21339 | </DIV> | |
21340 | <P> This generates:</P> | |
21341 | <DIV class="code"> | |
21342 | <PRE> | |
21343 | public class FileException extends java.lang.Exception { | |
21344 | ... | |
21345 | public String getMessage() { | |
21346 | return what(); | |
21347 | } | |
21348 | ||
21349 | public FileException(String msg) { ... } | |
21350 | ||
21351 | public String what() { | |
21352 | return exampleJNI.FileException_what(swigCPtr); | |
21353 | } | |
21354 | } | |
21355 | </PRE> | |
21356 | </DIV> | |
21357 | <P> We could alternatively have used <TT>%rename</TT> to rename <TT> | |
21358 | what()</TT> into <TT>getMessage()</TT>.</P> | |
21359 | <H3><A name="nan_exception_typemap"></A>19.9.3 NaN Exception - exception | |
21360 | handling for a particular type</H3> | |
21361 | <P> A Java exception can be thrown from any Java or JNI code. Therefore, | |
21362 | as most typemaps contain either Java or JNI code, just about any | |
21363 | typemap could throw an exception. The following example demonstrates | |
21364 | exception handling on a type by type basis by checking for 'Not a | |
21365 | number' (NaN) whenever a parameter of type <TT>float</TT> is wrapped.</P> | |
21366 | <P> Consider the following C++ code:</P> | |
21367 | <DIV class="code"> | |
21368 | <PRE> | |
21369 | bool calculate(float first, float second); | |
21370 | </PRE> | |
21371 | </DIV> | |
21372 | <P> To validate every <TT>float</TT> being passed to C++, we could | |
21373 | preceed the code being wrapped by the following typemap which throws a | |
21374 | runtime exception whenever the <TT>float</TT> is 'Not a Number':</P> | |
21375 | <DIV class="code"> | |
21376 | <PRE> | |
21377 | %module example | |
21378 | %typemap(javain) float "$module.CheckForNaN($javainput)" | |
21379 | %pragma(java) modulecode=%{ | |
21380 | /** Simply returns the input value unless it is not a number, | |
21381 | whereupon an exception is thrown. */ | |
21382 | static protected float CheckForNaN(float num) { | |
21383 | if (Float.isNaN(num)) | |
21384 | throw new RuntimeException("Not a number"); | |
21385 | return num; | |
21386 | } | |
21387 | %} | |
21388 | </PRE> | |
21389 | </DIV> | |
21390 | <P> Note that the <TT>CheckForNaN</TT> support method has been added to | |
21391 | the module class using the <TT>modulecode</TT> pragma. The following | |
21392 | shows the generated code of interest:</P> | |
21393 | <DIV class="code"> | |
21394 | <PRE> | |
21395 | public class example { | |
21396 | ... | |
21397 | ||
21398 | /** Simply returns the input value unless it is not a number, | |
21399 | whereupon an exception is thrown. */ | |
21400 | static protected float CheckForNaN(float num) { | |
21401 | if (Float.isNaN(num)) | |
21402 | throw new RuntimeException("Not a number"); | |
21403 | return num; | |
21404 | } | |
21405 | ||
21406 | public static boolean calculate(float first, float second) { | |
21407 | return exampleJNI.calculate(example.CheckForNaN(first), example.CheckForNaN(second)); | |
21408 | } | |
21409 | } | |
21410 | </PRE> | |
21411 | </DIV> | |
21412 | <P> Note that the "javain" typemap is used for every occurrence of a <TT> | |
21413 | float</TT> being used as an input. Of course, we could have targetted | |
21414 | the typemap at a particular parameter by using <TT>float first</TT>, | |
21415 | say, instead of just <TT>float</TT>. If we decide that what we actually | |
21416 | want is a checked exception instead of a runtime exception, we can | |
21417 | change this easily enough. The proxy method that uses <TT>float</TT> as | |
21418 | an input, must then add the exception class to the throws clause. SWIG | |
21419 | can handle this as it supports the 'throws' <A href="#typemap_attributes"> | |
21420 | typemap attribute</A> for specifying classes for the throws clause. Thus | |
21421 | we can modify the pragma and the typemap for the throws clause:</P> | |
21422 | <DIV class="code"> | |
21423 | <PRE> | |
21424 | %typemap(javain, throws="java.lang.Exception") float "$module.CheckForNaN($javainput)" | |
21425 | %pragma(java) modulecode=%{ | |
21426 | /** Simply returns the input value unless it is not a number, | |
21427 | whereupon an exception is thrown. */ | |
21428 | static protected float CheckForNaN(float num) throws java.lang.Exception { | |
21429 | if (Float.isNaN(num)) | |
21430 | throw new RuntimeException("Not a number"); | |
21431 | return num; | |
21432 | } | |
21433 | %} | |
21434 | </PRE> | |
21435 | </DIV> | |
21436 | <P> The <TT>calculate</TT> method now has a throws clause and even | |
21437 | though the typemap is used twice for both <TT>float first</TT> and <TT> | |
21438 | float second</TT>, the throws clause contains a single instance of <TT> | |
21439 | java.lang.Exception</TT>:</P> | |
21440 | <DIV class="code"> | |
21441 | <PRE> | |
21442 | public class example { | |
21443 | ... | |
21444 | ||
21445 | /** Simply returns the input value unless it is not a number, | |
21446 | whereupon an exception is thrown. */ | |
21447 | static protected float CheckForNaN(float num) throws java.lang.Exception { | |
21448 | if (Float.isNaN(num)) | |
21449 | throw new RuntimeException("Not a number"); | |
21450 | return num; | |
21451 | } | |
21452 | ||
21453 | public static boolean calculate(float first, float second) throws java.lang.Exception { | |
21454 | return exampleJNI.calculate(example.CheckForNaN(first), example.CheckForNaN(second)); | |
21455 | } | |
21456 | } | |
21457 | </PRE> | |
21458 | </DIV> | |
21459 | <P> If we were a martyr to the JNI cause, we could replace the succinct | |
21460 | code within the "javain" typemap with a few pages of JNI code. If we | |
21461 | had, we would have put it in the "in" typemap which, like all JNI and | |
21462 | Java typemaps, also supports the 'throws' attribute.</P> | |
21463 | <H3><A name="converting_java_string_arrays"></A>19.9.4 Converting Java | |
21464 | String arrays to char **</H3> | |
21465 | <P> A common problem in many C programs is the processing of command | |
21466 | line arguments, which are usually passed in an array of NULL terminated | |
21467 | strings. The following SWIG interface file allows a Java String array | |
21468 | to be used as a <TT>char **</TT> object.</P> | |
21469 | <DIV class="code"> | |
21470 | <PRE> | |
21471 | %module example | |
21472 | ||
21473 | /* This tells SWIG to treat char ** as a special case when used as a parameter | |
21474 | in a function call */ | |
21475 | %typemap(in) char ** (jint size) { | |
21476 | int i = 0; | |
21477 | size = (*jenv)->GetArrayLength(jenv, $input); | |
21478 | $1 = (char **) malloc((size+1)*sizeof(char *)); | |
21479 | /* make a copy of each string */ | |
21480 | for (i = 0; i<size; i++) { | |
21481 | jstring j_string = (jstring)(*jenv)->GetObjectArrayElement(jenv, $input, i); | |
21482 | const char * c_string = (*jenv)->GetStringUTFChars(jenv, j_string, 0); | |
21483 | $1[i] = malloc(strlen((c_string)+1)*sizeof(const char *)); | |
21484 | strcpy($1[i], c_string); | |
21485 | (*jenv)->ReleaseStringUTFChars(jenv, j_string, c_string); | |
21486 | (*jenv)->DeleteLocalRef(jenv, j_string); | |
21487 | } | |
21488 | $1[i] = 0; | |
21489 | } | |
21490 | ||
21491 | /* This cleans up the memory we malloc'd before the function call */ | |
21492 | %typemap(freearg) char ** { | |
21493 | int i; | |
21494 | for (i=0; i<size$argnum-1; i++) | |
21495 | free($1[i]); | |
21496 | free($1); | |
21497 | } | |
21498 | ||
21499 | /* This allows a C function to return a char ** as a Java String array */ | |
21500 | %typemap(out) char ** { | |
21501 | int i; | |
21502 | int len=0; | |
21503 | jstring temp_string; | |
21504 | const jclass clazz = (*jenv)->FindClass(jenv, "java/lang/String"); | |
21505 | ||
21506 | while ($1[len]) len++; | |
21507 | jresult = (*jenv)->NewObjectArray(jenv, len, clazz, NULL); | |
21508 | /* exception checking omitted */ | |
21509 | ||
21510 | for (i=0; i<len; i++) { | |
21511 | temp_string = (*jenv)->NewStringUTF(jenv, *result++); | |
21512 | (*jenv)->SetObjectArrayElement(jenv, jresult, i, temp_string); | |
21513 | (*jenv)->DeleteLocalRef(jenv, temp_string); | |
21514 | } | |
21515 | } | |
21516 | ||
21517 | /* These 3 typemaps tell SWIG what JNI and Java types to use */ | |
21518 | %typemap(jni) char ** "jobjectArray" | |
21519 | %typemap(jtype) char ** "String[]" | |
21520 | %typemap(jstype) char ** "String[]" | |
21521 | ||
21522 | /* These 2 typemaps handle the conversion of the jtype to jstype typemap type | |
21523 | and visa versa */ | |
21524 | %typemap(javain) char ** "$javainput" | |
21525 | %typemap(javaout) char ** { | |
21526 | return $jnicall; | |
21527 | } | |
21528 | ||
21529 | /* Now a few test functions */ | |
21530 | %inline %{ | |
21531 | ||
21532 | int print_args(char **argv) { | |
21533 | int i = 0; | |
21534 | while (argv[i]) { | |
21535 | printf("argv[%d] = %s\n", i, argv[i]); | |
21536 | i++; | |
21537 | } | |
21538 | return i; | |
21539 | } | |
21540 | ||
21541 | char **get_args() { | |
21542 | static char *values[] = { "Dave", "Mike", "Susan", "John", "Michelle", 0}; | |
21543 | return &values[0]; | |
21544 | } | |
21545 | ||
21546 | %} | |
21547 | </PRE> | |
21548 | </DIV> | |
21549 | <P> Note that the 'C' JNI calling convention is used. Checking for any | |
21550 | thrown exceptions after JNI function calls has been omitted. When this | |
21551 | module is compiled, our wrapped C functions can be used by the | |
21552 | following Java program:</P> | |
21553 | <DIV class="code"> | |
21554 | <PRE> | |
21555 | // File main.java | |
21556 | ||
21557 | public class main { | |
21558 | ||
21559 | static { | |
21560 | try { | |
21561 | System.loadLibrary("example"); | |
21562 | } catch (UnsatisfiedLinkError e) { | |
21563 | System.err.println("Native code library failed to load. " + e); | |
21564 | System.exit(1); | |
21565 | } | |
21566 | } | |
21567 | ||
21568 | public static void main(String argv[]) { | |
21569 | String animals[] = {"Cat","Dog","Cow","Goat"}; | |
21570 | example.print_args(animals); | |
21571 | String args[] = example.get_args(); | |
21572 | for (int i=0; i<args.length; i++) | |
21573 | System.out.println(i + ":" + args[i]); | |
21574 | } | |
21575 | } | |
21576 | </PRE> | |
21577 | </DIV> | |
21578 | <P> When compiled and run we get:</P> | |
21579 | <DIV class="code"> | |
21580 | <PRE> | |
21581 | $ java main | |
21582 | argv[0] = Cat | |
21583 | argv[1] = Dog | |
21584 | argv[2] = Cow | |
21585 | argv[3] = Goat | |
21586 | 0:Dave | |
21587 | 1:Mike | |
21588 | 2:Susan | |
21589 | 3:John | |
21590 | 4:Michelle | |
21591 | </PRE> | |
21592 | </DIV> | |
21593 | <P> In the example, a few different typemaps are used. The "in" typemap | |
21594 | is used to receive an input argument and convert it to a C array. Since | |
21595 | dynamic memory allocation is used to allocate memory for the array, the | |
21596 | "freearg" typemap is used to later release this memory after the | |
21597 | execution of the C function. The "out" typemap is used for function | |
21598 | return values. Lastly the "jni", "jtype" and "jstype" typemaps are also | |
21599 | required to specify what Java types to use.</P> | |
21600 | <H3><A name="expanding_java_object"></A>19.9.5 Expanding a Java object | |
21601 | to multiple arguments</H3> | |
21602 | <P> Suppose that you had a collection of C functions with arguments such | |
21603 | as the following:</P> | |
21604 | <DIV class="code"> | |
21605 | <PRE> | |
21606 | int foo(int argc, char **argv); | |
21607 | </PRE> | |
21608 | </DIV> | |
21609 | <P> In the previous example, a typemap was written to pass a Java String | |
21610 | array as the <TT>char **argv</TT>. This allows the function to be used | |
21611 | from Java as follows:</P> | |
21612 | <DIV class="code"> | |
21613 | <PRE> | |
21614 | example.foo(4, new String[]{"red", "green", "blue", "white"}); | |
21615 | </PRE> | |
21616 | </DIV> | |
21617 | <P> Although this works, it's a little awkward to specify the argument | |
21618 | count. To fix this, a multi-argument typemap can be defined. This is | |
21619 | not very difficult--you only have to make slight modifications to the | |
21620 | previous example's typemaps:</P> | |
21621 | <DIV class="code"> | |
21622 | <PRE> | |
21623 | %typemap(in) (int argc, char **argv) { | |
21624 | int i = 0; | |
21625 | $1 = (*jenv)->GetArrayLength(jenv, $input); | |
21626 | $2 = (char **) malloc(($1+1)*sizeof(char *)); | |
21627 | /* make a copy of each string */ | |
21628 | for (i = 0; i<$1; i++) { | |
21629 | jstring j_string = (jstring)(*jenv)->GetObjectArrayElement(jenv, $input, i); | |
21630 | const char * c_string = (*jenv)->GetStringUTFChars(jenv, j_string, 0); | |
21631 | $2[i] = malloc(strlen((c_string)+1)*sizeof(const char *)); | |
21632 | strcpy($2[i], c_string); | |
21633 | (*jenv)->ReleaseStringUTFChars(jenv, j_string, c_string); | |
21634 | (*jenv)->DeleteLocalRef(jenv, j_string); | |
21635 | } | |
21636 | $2[i] = 0; | |
21637 | } | |
21638 | ||
21639 | %typemap(freearg) (int argc, char **argv) { | |
21640 | int i; | |
21641 | for (i=0; i<$1-1; i++) | |
21642 | free($2[i]); | |
21643 | free($2); | |
21644 | } | |
21645 | ||
21646 | %typemap(jni) (int argc, char **argv) "jobjectArray" | |
21647 | %typemap(jtype) (int argc, char **argv) "String[]" | |
21648 | %typemap(jstype) (int argc, char **argv) "String[]" | |
21649 | ||
21650 | %typemap(javain) (int argc, char **argv) "$javainput" | |
21651 | </PRE> | |
21652 | </DIV> | |
21653 | <P> When writing a multiple-argument typemap, each of the types is | |
21654 | referenced by a variable such as <TT>$1</TT> or <TT>$2</TT>. The | |
21655 | typemap code simply fills in the appropriate values from the supplied | |
21656 | Java parameter.</P> | |
21657 | <P> With the above typemap in place, you will find it no longer | |
21658 | necessary to supply the argument count. This is automatically set by | |
21659 | the typemap code. For example:</P> | |
21660 | <DIV class="code"> | |
21661 | <PRE> | |
21662 | example.foo(new String[]{"red", "green", "blue", "white"}); | |
21663 | </PRE> | |
21664 | </DIV> | |
21665 | <H3><A name="using_typemaps_return_arguments"></A>19.9.6 Using typemaps | |
21666 | to return arguments</H3> | |
21667 | <P> A common problem in some C programs is that values may be returned | |
21668 | in function parameters rather than in the return value of a function. | |
21669 | The <TT>typemaps.i</TT> file defines INPUT, OUTPUT and INOUT typemaps | |
21670 | which can be used to solve some instances of this problem. This library | |
21671 | file uses an array as a means of moving data to and from Java when | |
21672 | wrapping a C function that takes non const pointers or non const | |
21673 | references as parameters.</P> | |
21674 | <P> Now we are going to outline an alternative approach to using arrays | |
21675 | for C pointers. The INOUT typemap uses a <TT>double[]</TT> array for | |
21676 | receiving and returning the <TT>double*</TT> parameters. In this | |
21677 | approach we are able to use a Java class <TT>myDouble</TT> instead of <TT> | |
21678 | double[]</TT> arrays where the C pointer <TT>double*</TT> is required.</P> | |
21679 | <P> Here is our example function:</P> | |
21680 | <DIV class="code"> | |
21681 | <PRE> | |
21682 | /* Returns a status value and two values in out1 and out2 */ | |
21683 | int spam(double a, double b, double *out1, double *out2); | |
21684 | </PRE> | |
21685 | </DIV> | |
21686 | <P> If we define a structure <TT>MyDouble</TT> containing a <TT>double</TT> | |
21687 | member variable and use some typemaps we can solve this problem. For | |
21688 | example we could put the following through SWIG:</P> | |
21689 | <DIV class="code"> | |
21690 | <PRE> | |
21691 | %module example | |
21692 | ||
21693 | /* Define a new structure to use instead of double * */ | |
21694 | %inline %{ | |
21695 | typedef struct { | |
21696 | double value; | |
21697 | } MyDouble; | |
21698 | %} | |
21699 | ||
21700 | ||
21701 | %{ | |
21702 | /* Returns a status value and two values in out1 and out2 */ | |
21703 | int spam(double a, double b, double *out1, double *out2) { | |
21704 | int status = 1; | |
21705 | *out1 = a*10.0; | |
21706 | *out2 = b*100.0; | |
21707 | return status; | |
21708 | }; | |
21709 | %} | |
21710 | ||
21711 | /* | |
21712 | This typemap will make any double * function parameters with name <TT>OUTVALUE</TT> take an | |
21713 | argument of MyDouble instead of double *. This will | |
21714 | allow the calling function to read the double * value after returning from the function. | |
21715 | */ | |
21716 | %typemap(in) double *OUTVALUE { | |
21717 | jclass clazz = jenv->FindClass("MyDouble"); | |
21718 | jfieldID fid = jenv->GetFieldID(clazz, "swigCPtr", "J"); | |
21719 | jlong cPtr = jenv->GetLongField($input, fid); | |
21720 | MyDouble *pMyDouble = NULL; | |
21721 | *(MyDouble **)&pMyDouble = *(MyDouble **)&cPtr; | |
21722 | $1 = &pMyDouble->value; | |
21723 | } | |
21724 | ||
21725 | %typemap(jtype) double *OUTVALUE "MyDouble" | |
21726 | %typemap(jstype) double *OUTVALUE "MyDouble" | |
21727 | %typemap(jni) double *OUTVALUE "jobject" | |
21728 | ||
21729 | %typemap(javain) double *OUTVALUE "$javainput" | |
21730 | ||
21731 | /* Now we apply the typemap to the named variables */ | |
21732 | %apply double *OUTVALUE { double *out1, double *out2 }; | |
21733 | int spam(double a, double b, double *out1, double *out2); | |
21734 | </PRE> | |
21735 | </DIV> | |
21736 | <P> Note that the C++ JNI calling convention has been used this time and | |
21737 | so must be compiled as C++ and the -c++ commandline must be passed to | |
21738 | SWIG. JNI error checking has been omitted for clarity.</P> | |
21739 | <P> What the typemaps do are make the named <TT>double*</TT> function | |
21740 | parameters use our new <TT>MyDouble</TT> wrapper structure. The "in" | |
21741 | typemap takes this structure, gets the C++ pointer to it, takes the <TT> | |
21742 | double value</TT> member variable and passes it to the C++ <TT>spam</TT> | |
21743 | function. In Java, when the function returns, we use the SWIG created <TT> | |
21744 | getValue()</TT> function to get the output value. The following Java | |
21745 | program demonstrates this:</P> | |
21746 | <DIV class="code"> | |
21747 | <PRE> | |
21748 | // File: main.java | |
21749 | ||
21750 | public class main { | |
21751 | ||
21752 | static { | |
21753 | try { | |
21754 | System.loadLibrary("example"); | |
21755 | } catch (UnsatisfiedLinkError e) { | |
21756 | System.err.println("Native code library failed to load. " + e); | |
21757 | System.exit(1); | |
21758 | } | |
21759 | } | |
21760 | ||
21761 | public static void main(String argv[]) { | |
21762 | MyDouble out1 = new MyDouble(); | |
21763 | MyDouble out2 = new MyDouble(); | |
21764 | int ret = example.spam(1.2, 3.4, out1, out2); | |
21765 | System.out.println(ret + " " + out1.getValue() + " " + out2.getValue()); | |
21766 | } | |
21767 | } | |
21768 | </PRE> | |
21769 | </DIV> | |
21770 | <P> When compiled and run we get:</P> | |
21771 | <DIV class="code"> | |
21772 | <PRE> | |
21773 | $ java main | |
21774 | 1 12.0 340.0 | |
21775 | </PRE> | |
21776 | </DIV> | |
21777 | <H3><A name="adding_downcasts"></A>19.9.7 Adding Java downcasts to | |
21778 | polymorphic return types</H3> | |
21779 | <P> SWIG support for polymorphism works in that the appropriate virtual | |
21780 | function is called. However, the default generated code does not allow | |
21781 | for downcasting. Let's examine this with the following code:</P> | |
21782 | <DIV class="code"> | |
21783 | <PRE> | |
21784 | %include "std_string.i" | |
21785 | ||
21786 | #include <iostream> | |
21787 | using namespace std; | |
21788 | class Vehicle { | |
21789 | public: | |
21790 | virtual void start() = 0; | |
21791 | ... | |
21792 | }; | |
21793 | ||
21794 | class Ambulance : public Vehicle { | |
21795 | string vol; | |
21796 | public: | |
21797 | Ambulance(string volume) : vol(volume) {} | |
21798 | virtual void start() { | |
21799 | cout << "Ambulance started" << endl; | |
21800 | } | |
21801 | void sound_siren() { | |
21802 | cout << vol << " siren sounded!" << endl; | |
21803 | } | |
21804 | ... | |
21805 | }; | |
21806 | ||
21807 | Vehicle *vehicle_factory() { | |
21808 | return new Ambulance("Very loud"); | |
21809 | } | |
21810 | </PRE> | |
21811 | </DIV> | |
21812 | <P> If we execute the following Java code:</P> | |
21813 | <DIV class="code"> | |
21814 | <PRE> | |
21815 | Vehicle vehicle = example.vehicle_factory(); | |
21816 | vehicle.start(); | |
21817 | ||
21818 | Ambulance ambulance = (Ambulance)vehicle; | |
21819 | ambulance.sound_siren(); | |
21820 | </PRE> | |
21821 | </DIV> | |
21822 | <P> We get:</P> | |
21823 | <DIV class="code"> | |
21824 | <PRE> | |
21825 | Ambulance started | |
21826 | java.lang.ClassCastException | |
21827 | at main.main(main.java:16) | |
21828 | </PRE> | |
21829 | </DIV> | |
21830 | <P> Even though we know from examination of the C++ code that <TT> | |
21831 | vehicle_factory</TT> returns an object of type <TT>Ambulance</TT>, we | |
21832 | are not able to use this knowledge to perform the downcast in Java. | |
21833 | This occurs because the runtime type information is not completely | |
21834 | passed from C++ to Java when returning the type from <TT> | |
21835 | vehicle_factory()</TT>. Usually this is not a problem as virtual | |
21836 | functions do work by default, such as in the case of <TT>start()</TT>. | |
21837 | There are a few solutions to getting downcasts to work.</P> | |
21838 | <P> The first is not to use a Java cast but a call to C++ to make the | |
21839 | cast. Add this to your code:</P> | |
21840 | <DIV class="code"> | |
21841 | <PRE> | |
21842 | %exception Ambulance::dynamic_cast(Vehicle *vehicle) { | |
21843 | $action | |
21844 | if (!result) { | |
21845 | jclass excep = jenv->FindClass("java/lang/ClassCastException"); | |
21846 | if (excep) { | |
21847 | jenv->ThrowNew(excep, "dynamic_cast exception"); | |
21848 | } | |
21849 | } | |
21850 | } | |
21851 | %extend Ambulance { | |
21852 | static Ambulance *dynamic_cast(Vehicle *vehicle) { | |
21853 | return dynamic_cast<Ambulance *>(vehicle); | |
21854 | } | |
21855 | }; | |
21856 | </PRE> | |
21857 | </DIV> | |
21858 | <P> It would then be used from Java like this</P> | |
21859 | <DIV class="code"> | |
21860 | <PRE> | |
21861 | Ambulance ambulance = Ambulance.dynamic_cast(vehicle); | |
21862 | ambulance.sound_siren(); | |
21863 | </PRE> | |
21864 | </DIV> | |
21865 | <P> Should <TT>vehicle</TT> not be of type <TT>ambulance</TT> then a | |
21866 | Java <TT>ClassCastException</TT> is thrown. The next solution is a | |
21867 | purer solution in that Java downcasts can be performed on the types. | |
21868 | Add the following before the definition of <TT>vehicle_factory</TT>:</P> | |
21869 | <DIV class="code"> | |
21870 | <PRE> | |
21871 | %typemap(out) Vehicle * { | |
21872 | Ambulance *downcast = dynamic_cast<Ambulance *>($1); | |
21873 | *(Ambulance **)&$result = downcast; | |
21874 | } | |
21875 | ||
21876 | %typemap(javaout) Vehicle * { | |
21877 | return new Ambulance($jnicall, $owner); | |
21878 | } | |
21879 | </PRE> | |
21880 | </DIV> | |
21881 | <P> Here we are using our knowledge that <TT>vehicle_factory</TT> always | |
21882 | returns type <TT>Ambulance</TT> so that the Java proxy is created as a | |
21883 | type <TT>Ambulance</TT>. If <TT>vehicle_factory</TT> can manufacture | |
21884 | any type of <TT>Vehicle</TT> and we want to be able to downcast using | |
21885 | Java casts for any of these types, then a different approach is needed. | |
21886 | Consider expanding our example with a new Vehicle type and a more | |
21887 | flexible factory function:</P> | |
21888 | <DIV class="code"> | |
21889 | <PRE> | |
21890 | class FireEngine : public Vehicle { | |
21891 | public: | |
21892 | FireEngine() {} | |
21893 | virtual void start() { | |
21894 | cout << "FireEngine started" << endl; | |
21895 | } | |
21896 | void roll_out_hose() { | |
21897 | cout << "Hose rolled out" << endl; | |
21898 | } | |
21899 | ... | |
21900 | }; | |
21901 | Vehicle *vehicle_factory(int vehicle_number) { | |
21902 | if (vehicle_number == 0) | |
21903 | return new Ambulance("Very loud"); | |
21904 | else | |
21905 | return new FireEngine(); | |
21906 | } | |
21907 | </PRE> | |
21908 | </DIV> | |
21909 | <P> To be able to downcast with this sort of Java code:</P> | |
21910 | <DIV class="code"> | |
21911 | <PRE> | |
21912 | FireEngine fireengine = (FireEngine)example.vehicle_factory(1); | |
21913 | fireengine.roll_out_hose(); | |
21914 | Ambulance ambulance = (Ambulance)example.vehicle_factory(0); | |
21915 | ambulance.sound_siren(); | |
21916 | </PRE> | |
21917 | </DIV> | |
21918 | <P> the following typemaps targeted at the <TT>vehicle_factory</TT> | |
21919 | function will achieve this. Note that in this case, the Java class is | |
21920 | constructed using JNI code rather than passing a pointer across the JNI | |
21921 | boundary in a Java long for construction in Java code.</P> | |
21922 | <DIV class="code"> | |
21923 | <PRE> | |
21924 | %typemap(jni) Vehicle *vehicle_factory "jobject" | |
21925 | %typemap(jtype) Vehicle *vehicle_factory "Vehicle" | |
21926 | %typemap(jstype) Vehicle *vehicle_factory "Vehicle" | |
21927 | %typemap(javaout) Vehicle *vehicle_factory { | |
21928 | return $jnicall; | |
21929 | } | |
21930 | ||
21931 | %typemap(out) Vehicle *vehicle_factory { | |
21932 | Ambulance *ambulance = dynamic_cast<Ambulance *>($1); | |
21933 | FireEngine *fireengine = dynamic_cast<FireEngine *>($1); | |
21934 | if (ambulance) { | |
21935 | // call the Ambulance(long cPtr, boolean cMemoryOwn) constructor | |
21936 | jclass clazz = jenv->FindClass("Ambulance"); | |
21937 | if (clazz) { | |
21938 | jmethodID mid = jenv->GetMethodID(clazz, "<init>", "(JZ)V"); | |
21939 | if (mid) { | |
21940 | jlong cptr = 0; | |
21941 | *(Ambulance **)&cptr = ambulance; | |
21942 | $result = jenv->NewObject(clazz, mid, cptr, false); | |
21943 | } | |
21944 | } | |
21945 | } else if (fireengine) { | |
21946 | // call the FireEngine(long cPtr, boolean cMemoryOwn) constructor | |
21947 | jclass clazz = jenv->FindClass("FireEngine"); | |
21948 | if (clazz) { | |
21949 | jmethodID mid = jenv->GetMethodID(clazz, "<init>", "(JZ)V"); | |
21950 | if (mid) { | |
21951 | jlong cptr = 0; | |
21952 | *(FireEngine **)&cptr = fireengine; | |
21953 | $result = jenv->NewObject(clazz, mid, cptr, false); | |
21954 | } | |
21955 | } | |
21956 | } | |
21957 | else { | |
21958 | cout << "Unexpected type " << endl; | |
21959 | } | |
21960 | ||
21961 | if (!$result) | |
21962 | cout << "Failed to create new java object" << endl; | |
21963 | } | |
21964 | </PRE> | |
21965 | </DIV> | |
21966 | <P> Better error handling would need to be added into this code. There | |
21967 | are other solutions to this problem, but this last example demonstrates | |
21968 | some more involved JNI code. SWIG usually generates code which | |
21969 | constructs the proxy classes using Java code as it is easier to handle | |
21970 | error conditions and is faster. Note that the JNI code above uses a | |
21971 | number of string lookups to call a constructor, whereas this would not | |
21972 | occur using byte compiled Java code.</P> | |
21973 | <H3><A name="adding_equals_method"></A>19.9.8 Adding an equals method to | |
21974 | the Java classes</H3> | |
21975 | <P> When a pointer is returned from a JNI function, it is wrapped using | |
21976 | a new Java proxy class or type wrapper class. Even when the pointers | |
21977 | are the same, it will not be possible to know that the two Java classes | |
21978 | containing those pointers are actually the same object. It is common in | |
21979 | Java to use the <TT>equals()</TT> method to check whether two objects | |
21980 | are equivalent. An equals method is easily added to all proxy classes. | |
21981 | For example:</P> | |
21982 | <DIV class="code"> | |
21983 | <PRE> | |
21984 | %typemap(javacode) SWIGTYPE %{ | |
21985 | public boolean equals(Object obj) { | |
21986 | boolean equal = false; | |
21987 | if (obj instanceof $javaclassname) | |
21988 | equal = ((($javaclassname)obj).swigCPtr == this.swigCPtr); | |
21989 | return equal; | |
21990 | } | |
21991 | %} | |
21992 | ||
21993 | class Foo { }; | |
21994 | Foo* returnFoo(Foo *foo) { return foo; } | |
21995 | </PRE> | |
21996 | </DIV> | |
21997 | <P> The following would display <TT>false</TT> without the <TT>javacode</TT> | |
21998 | typemap above. With the typemap defining the <TT>equals</TT> method the | |
21999 | result is <TT>true</TT>.</P> | |
22000 | <DIV class="code"> | |
22001 | <PRE> | |
22002 | Foo foo1 = new Foo(); | |
22003 | Foo foo2 = example.returnFoo(foo1); | |
22004 | System.out.println("foo1? " + foo1.equals(foo2)); | |
22005 | </PRE> | |
22006 | </DIV> | |
22007 | <H3><A name="void_pointers"></A>19.9.9 Void pointers and a common Java | |
22008 | base class</H3> | |
22009 | <P> One might wonder why the common code that SWIG emits for the proxy | |
22010 | and type wrapper classes is not pushed into a base class. The reason is | |
22011 | that although <TT>swigCPtr</TT> could be put into a common base class | |
22012 | for all classes wrapping C structures, it would not work for C++ | |
22013 | classes involved in an inheritance chain. Each class derived from a | |
22014 | base needs a separate <TT>swigCPtr</TT> because C++ compilers sometimes | |
22015 | use a different pointer value when casting a derived class to a base. | |
22016 | Additionally as Java only supports single inheritance, it would not be | |
22017 | possible to derive wrapped classes from your own pure Java classes if | |
22018 | the base class has been 'used up' by SWIG. However, you may want to | |
22019 | move some of the common code into a base class. Here is an example | |
22020 | which uses a common base class for all proxy classes and type wrapper | |
22021 | classes:</P> | |
22022 | <DIV class="code"> | |
22023 | <PRE> | |
22024 | %typemap(javabase) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE [], | |
22025 | SWIGTYPE (CLASS::*) "SWIG" | |
22026 | ||
22027 | %typemap(javacode) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE [], | |
22028 | SWIGTYPE (CLASS::*) %{ | |
22029 | protected long getPointer() { | |
22030 | return swigCPtr; | |
22031 | } | |
22032 | %} | |
22033 | </PRE> | |
22034 | </DIV> | |
22035 | <P> Define new base class called SWIG:</P> | |
22036 | <DIV class="code"> | |
22037 | <PRE> | |
22038 | public abstract class SWIG { | |
22039 | protected abstract long getPointer(); | |
22040 | ||
22041 | public boolean equals(Object obj) { | |
22042 | boolean equal = false; | |
22043 | if (obj instanceof SWIG) | |
22044 | equal = (((SWIG)obj).getPointer() == this.getPointer()); | |
22045 | return equal; | |
22046 | } | |
22047 | ||
22048 | SWIGTYPE_p_void getVoidPointer() { | |
22049 | return new SWIGTYPE_p_void(getPointer(), false); | |
22050 | } | |
22051 | } | |
22052 | </PRE> | |
22053 | </DIV> | |
22054 | <P> This example contains some useful functionality which you may want | |
22055 | in your code.</P> | |
22056 | <UL> | |
22057 | <LI> It has an <TT>equals()</TT> method. Unlike the previous example, | |
22058 | the method code isn't replicated in all classes.</LI> | |
22059 | <LI> It also has a function which effectively implements a cast from the | |
22060 | type of the proxy/type wrapper class to a void pointer. This is | |
22061 | necessary for passing a proxy class or a type wrapper class to a | |
22062 | function that takes a void pointer.</LI> | |
22063 | </UL> | |
22064 | <H3><A name="struct_pointer_pointer"></A>19.9.10 Struct pointer to | |
22065 | pointer</H3> | |
22066 | <P> Pointers to pointers are often used as output parameters in C | |
22067 | factory type functions. These are a bit more tricky to handle. Consider | |
22068 | the following situation where a <TT>Butler</TT> can be hired and fired:</P> | |
22069 | <DIV class="code"> | |
22070 | <PRE> | |
22071 | typedef struct { | |
22072 | int hoursAvailable; | |
22073 | char *greeting; | |
22074 | } Butler; | |
22075 | ||
22076 | // Note: HireButler will allocate the memory | |
22077 | // The caller must free the memory by calling FireButler()!! | |
22078 | extern int HireButler(Butler **ppButler); | |
22079 | extern void FireButler(Butler *pButler); | |
22080 | </PRE> | |
22081 | </DIV> | |
22082 | <P> C code implementation:</P> | |
22083 | <DIV class="code"> | |
22084 | <PRE> | |
22085 | int HireButler(Butler **ppButler) { | |
22086 | Butler *pButler = (Butler *)malloc(sizeof(Butler)); | |
22087 | pButler->hoursAvailable = 24; | |
22088 | pButler->greeting = (char *)malloc(32); | |
22089 | strcpy(pButler->greeting, "At your service Sir"); | |
22090 | *ppButler = pButler; | |
22091 | return 1; | |
22092 | } | |
22093 | void FireButler(Butler *pButler) { | |
22094 | free(pButler->greeting); | |
22095 | free(pButler); | |
22096 | } | |
22097 | </PRE> | |
22098 | </DIV> | |
22099 | <P> Let's take two approaches to wrapping this code. The first is to | |
22100 | provide a functional interface, much like the original C interface. The | |
22101 | following Java code shows how we intend the code to be used:</P> | |
22102 | <DIV class="code"> | |
22103 | <PRE> | |
22104 | Butler jeeves = new Butler(); | |
22105 | example.HireButler(jeeves); | |
22106 | System.out.println("Greeting: " + jeeves.getGreeting()); | |
22107 | System.out.println("Availability: " + jeeves.getHoursAvailable() + " hours per day"); | |
22108 | example.FireButler(jeeves); | |
22109 | </PRE> | |
22110 | </DIV> | |
22111 | <P> Resulting in the following output when run:</P> | |
22112 | <DIV class="shell"> | |
22113 | <PRE> | |
22114 | Greeting: At your service Sir | |
22115 | Availability: 24 hours per day | |
22116 | </PRE> | |
22117 | </DIV> | |
22118 | <P> Note the usage is very much like it would be used if we were writing | |
22119 | C code, that is, explicit memory management is needed. No C memory is | |
22120 | allocated in the construction of the <TT>Butler</TT> proxy class and | |
22121 | the proxy class will not destroy the underlying C memory when it is | |
22122 | collected. A number of typemaps and features are needed to implement | |
22123 | this approach. The following interface file code should be placed | |
22124 | before SWIG parses the above C code.</P> | |
22125 | <DIV class="code"> | |
22126 | <PRE> | |
22127 | %module example | |
22128 | ||
22129 | // Do not generate the default proxy constructor or destructor | |
22130 | %nodefault Butler; | |
22131 | ||
22132 | // Add in pure Java code proxy constructor | |
22133 | %typemap(javacode) Butler %{ | |
22134 | /** This constructor creates the proxy which initially does not create nor own any C memory */ | |
22135 | public Butler() { | |
22136 | this(0, false); | |
22137 | } | |
22138 | %} | |
22139 | ||
22140 | // Type typemaps for marshalling Butler ** | |
22141 | %typemap(jni) Butler ** "jobject" | |
22142 | %typemap(jtype) Butler ** "Butler" | |
22143 | %typemap(jstype) Butler ** "Butler" | |
22144 | ||
22145 | // Typemaps for Butler ** as a parameter output type | |
22146 | %typemap(in) Butler ** (Butler *ppButler = 0) %{ | |
22147 | $1 = &ppButler; | |
22148 | %} | |
22149 | %typemap(argout) Butler ** { | |
22150 | // Give Java proxy the C pointer (of newly created object) | |
22151 | jclass clazz = (*jenv)->FindClass(jenv, "Butler"); | |
22152 | jfieldID fid = (*jenv)->GetFieldID(jenv, clazz, "swigCPtr", "J"); | |
22153 | jlong cPtr = 0; | |
22154 | *(Butler **)(void *)&cPtr = *$1; | |
22155 | (*jenv)->SetLongField(jenv, $input, fid, cPtr); | |
22156 | } | |
22157 | %typemap(javain) Butler ** "$javainput" | |
22158 | </PRE> | |
22159 | </DIV> | |
22160 | <P> Note that the JNI code sets the proxy's <TT>swigCPtr</TT> member | |
22161 | variable to point to the newly created object. The <TT>swigCMemOwn</TT> | |
22162 | remains unchanged (at false), so that the proxy does not own the | |
22163 | memory.</P> | |
22164 | <P> The second approach offers a more object oriented interface to the | |
22165 | Java user. We do this by making the Java proxy class's constructor call | |
22166 | the <TT>HireButler()</TT> method to create the underlying C object. | |
22167 | Additionally we get the proxy to take ownership of the memory so that | |
22168 | the finalizer will call the <TT>FireButler()</TT> function. The proxy | |
22169 | class will thus take ownership of the memory and clean it up when no | |
22170 | longer needed. We will also prevent the user from being able to | |
22171 | explicitly call the <TT>HireButler()</TT> and <TT>FireButler()</TT> | |
22172 | functions. Usage from Java will simply be:</P> | |
22173 | <DIV class="code"> | |
22174 | <PRE> | |
22175 | Butler jeeves = new Butler(); | |
22176 | System.out.println("Greeting: " + jeeves.getGreeting()); | |
22177 | System.out.println("Availability: " + jeeves.getHoursAvailable() + " hours per day"); | |
22178 | </PRE> | |
22179 | </DIV> | |
22180 | <P> Note that the Butler class is used just like any other Java class | |
22181 | and no extra coding by the user needs to be written to clear up the | |
22182 | underlying C memory as the finalizer will be called by the garbage | |
22183 | collector which in turn will call the <TT>FireButler()</TT> function. | |
22184 | To implement this, we use the above interface file code but remove the <TT> | |
22185 | javacode</TT> typemap and add the following:</P> | |
22186 | <DIV class="code"> | |
22187 | <PRE> | |
22188 | // Don't expose the memory allocation/de-allocation functions | |
22189 | %ignore FireButler(Butler *pButler); | |
22190 | %ignore HireButler(Butler **ppButler); | |
22191 | ||
22192 | // Add in a custom proxy constructor and destructor | |
22193 | %extend Butler { | |
22194 | Butler() { | |
22195 | Butler *pButler = 0; | |
22196 | HireButler(&pButler); | |
22197 | return pButler; | |
22198 | } | |
22199 | ~Butler() { | |
22200 | FireButler(self); | |
22201 | } | |
22202 | } | |
22203 | </PRE> | |
22204 | </DIV> | |
22205 | <P> Note that the code in <TT>%extend</TT> is using a C++ type | |
22206 | constructor and destructor, yet the generated code will still compile | |
22207 | as C code, see <A href="#SWIG_adding_member_functions">Adding member | |
22208 | functions to C structures</A>. The C functional interface has been | |
22209 | completely morphed into an object-oriented interface and the Butler | |
22210 | class would behave much like any pure Java class and feel more natural | |
22211 | to Java users.</P> | |
22212 | <H2><A name="java_directors_faq"></A>19.10 Living with Java Directors</H2> | |
22213 | <P> This section is intended to address frequently asked questions and | |
22214 | frequently encountered problems when using Java directors.</P> | |
22215 | <OL> | |
22216 | <LI><I>When my program starts up, it complains that</I> method_foo<I> | |
22217 | cannot be found in a Java method called</I> swig_module_init<I>. How do | |
22218 | I fix this?</I> | |
22219 | <P> Open up the C++ wrapper source code file and look for <CODE> | |
22220 | "method_foo"</CODE> (include the double quotes, they are important!) | |
22221 | Look at the JNI field descriptor and make sure that each class that | |
22222 | occurs in the descriptor has the correct package name in front of it. | |
22223 | If the package name is incorrect, put a "javapackage" typemap in your | |
22224 | SWIG interface file.</P> | |
22225 | </LI> | |
22226 | <LI><I>I'm compiling my code and I'm using templates. I provided a | |
22227 | javapackage typemap, but SWIG doesn't generate the right JNI field | |
22228 | descriptor.</I> | |
22229 | <P> Use the template's renamed name as the argument to the "javapackage" | |
22230 | typemap:</P> | |
22231 | <DIV class="code"> | |
22232 | <PRE> | |
22233 | %typemap(javapackage) std::vector<int> "your.package.here" | |
22234 | %template(VectorOfInt) std::vector<int>; | |
22235 | </PRE> | |
22236 | </DIV></LI> | |
22237 | <LI> | |
22238 | <P><I>When I pass class pointers or references through a C++ upcall and | |
22239 | I try to type cast them, Java complains with a ClassCastException. What | |
22240 | am I doing wrong?</I></P> | |
22241 | <P> Normally, a non-director generated Java proxy class creates | |
22242 | temporary Java objects as follows:</P> | |
22243 | <DIV class="code"> | |
22244 | <PRE> | |
22245 | public static void MyClass_method_upcall(MyClass self, long jarg1) | |
22246 | { | |
22247 | Foo darg1 = new Foo(jarg1, false); | |
22248 | ||
22249 | self.method_upcall(darg1); | |
22250 | } | |
22251 | </PRE> | |
22252 | </DIV> | |
22253 | <P>Unfortunately, this loses the Java type information that is part of | |
22254 | the underlying Foo director proxy class's Java object pointer causing | |
22255 | the type cast to fail. The SWIG Java module's director code attempts to | |
22256 | correct the problem,<B> but only for director-enabled classes</B>, | |
22257 | since the director class retains a global reference to its Java object. | |
22258 | Thus, for director-enabled classes<B> and only for director-enabled | |
22259 | classes</B>, the generated proxy Java code looks something like:</P> | |
22260 | <DIV class="code"> | |
22261 | <PRE> | |
22262 | public static void MyClass_method_upcall(MyClass self, long jarg1, | |
22263 | Foo jarg1_object) | |
22264 | { | |
22265 | Foo darg1 = (jarg1_object != null ? jarg1_object : new Foo(jarg1, false)); | |
22266 | ||
22267 | self.method_upcall(darg1); | |
22268 | } | |
22269 | </PRE> | |
22270 | </DIV> | |
22271 | <P> When you import a SWIG interface file containing class definitions, | |
22272 | the classes you want to be director-enabled must be have the <CODE> | |
22273 | feature("director")</CODE> enabled for type symmetry to work. This | |
22274 | applies even when the class being wrapped isn't a director-enabled | |
22275 | class but takes parameters that are director-enabled classes.</P> | |
22276 | <P> The current "type symmetry" design will work for simple C++ | |
22277 | inheritance, but will most likely fail for anything more compicated | |
22278 | such as tree or diamond C++ inheritance hierarchies. Those who are | |
22279 | interested in challenging problems are more than welcome to hack the <CODE> | |
22280 | Java::Java_director_declaration</CODE> method in <CODE> | |
22281 | Source/Modules/java.cxx</CODE>.</P> | |
22282 | <P> If all else fails, you can use the downcastXXXXX() method to attempt | |
22283 | to recover the director class's Java object pointer. For the Java Foo | |
22284 | proxy class, the Foo director class's java object pointer can be | |
22285 | accessed through the javaObjectFoo() method. The generated method's | |
22286 | signature is:</P> | |
22287 | <DIV class="code"> | |
22288 | <PRE> | |
22289 | public static Foo javaObjectFoo(Foo obj); | |
22290 | </PRE> | |
22291 | </DIV> | |
22292 | <P> From your code, this method is invoked as follows:</P> | |
22293 | <DIV class="code"> | |
22294 | <PRE> | |
22295 | public class MyClassDerived { | |
22296 | public void method_upcall(Foo foo_object) | |
22297 | { | |
22298 | FooDerived derived = (foo_object != null ? | |
22299 | (FooDerived) Foo.downcastFoo(foo_object) : null); | |
22300 | /* rest of your code here */ | |
22301 | } | |
22302 | } | |
22303 | </PRE> | |
22304 | </DIV> | |
22305 | <P> An good approach for managing downcasting is placing a static method | |
22306 | in each derived class that performs the downcast from the superclass, | |
22307 | e.g.,</P> | |
22308 | <DIV class="code"> | |
22309 | <PRE> | |
22310 | public class FooDerived extends Foo { | |
22311 | /* ... */ | |
22312 | public static FooDerived downcastFooDerived(Foo foo_object) | |
22313 | { | |
22314 | try { | |
22315 | return (foo_object != null ? (FooDerived) Foo.downcastFoo(foo_object); | |
22316 | } | |
22317 | ||
22318 | catch (ClassCastException exc) { | |
22319 | // Wasn't a FooDerived object, some other sublcass of Foo | |
22320 | return null; | |
22321 | } | |
22322 | } | |
22323 | } | |
22324 | </PRE> | |
22325 | </DIV> | |
22326 | <P> Then change the code in MyClassDerived as follows:</P> | |
22327 | <DIV class="code"> | |
22328 | <PRE> | |
22329 | public class MyClassDerived extends MyClass { | |
22330 | /* ... */ | |
22331 | public void method_upcall(Foo foo_object) | |
22332 | { | |
22333 | FooDerived derived = FooDerived.downcastFooDerived(foo_object); | |
22334 | /* rest of your code here */ | |
22335 | } | |
22336 | } | |
22337 | </PRE> | |
22338 | </DIV></LI> | |
22339 | <LI> | |
22340 | <P><I>Why isn't the proxy class declared abstract? Why aren't the | |
22341 | director upcall methods in the proxy class declared abstract?</I></P> | |
22342 | <P> Declaring the proxy class and its methods abstract would break the | |
22343 | JNI argument marshalling and SWIG's downcall functionality (going from | |
22344 | Java to C++.) Create an abstract Java subclass that inherits from the | |
22345 | director-enabled class instead. Using the previous Foo class example:</P> | |
22346 | <DIV class="code"> | |
22347 | <PRE> | |
22348 | public abstract class UserVisibleFoo extends Foo { | |
22349 | /** Make sure user overrides this method, it's where the upcall | |
22350 | * happens. | |
22351 | */ | |
22352 | public abstract void method_upcall(Foo foo_object); | |
22353 | ||
22354 | /// Downcast from Foo to UserVisibleFoo | |
22355 | public static UserVisibleFoo downcastUserVisibleFoo(Foo foo_object) | |
22356 | { | |
22357 | try { | |
22358 | return (foo_object != null ? (FooDerived) Foo.downcastFoo(foo_object) : null); | |
22359 | } | |
22360 | ||
22361 | catch (ClassCastException exc) { | |
22362 | // Wasn't a FooDerived object, some other sublcass of Foo | |
22363 | return null; | |
22364 | } | |
22365 | } | |
22366 | } | |
22367 | </PRE> | |
22368 | </DIV> | |
22369 | <P>This doesn't prevent the user from creating subclasses derived from | |
22370 | Foo, however, UserVisibleFoo provides the safety net that reminds the | |
22371 | user to override the <CODE>method_upcall()</CODE> method.</P> | |
22372 | </LI> | |
22373 | </OL> | |
22374 | <H2><A name="odds_ends"></A>19.11 Odds and ends</H2> | |
22375 | <H3><A name="javadoc_comments"></A>19.11.1 JavaDoc comments</H3> | |
22376 | <P> The SWIG documentation system is currently deprecated. When it is | |
22377 | resurrected JavaDoc comments will be fully supported. If you can't wait | |
22378 | for the full documentation system a couple of workarounds are | |
22379 | available. The <TT>%javamethodmodifiers</TT> feature can be used for | |
22380 | adding proxy class method comments and module class method comments. | |
22381 | The "javaimports" typemap can be hijacked for adding in proxy class | |
22382 | JavaDoc comments. The <TT>jniclassimports</TT> or <TT> | |
22383 | jniclassclassmodifiers</TT> pragmas can also be used for adding | |
22384 | intermediary JNI class comments and likewise the <TT>moduleimports</TT> | |
22385 | or <TT>moduleclassmodifiers</TT> pragmas for the module class. Here is | |
22386 | an example adding in a proxy class and method comment:</P> | |
22387 | <DIV class="code"> | |
22388 | <PRE> | |
22389 | %javamethodmodifiers Barmy::lose_marbles() " | |
22390 | /** | |
22391 | * Calling this method will make you mad. | |
22392 | * Use with <b>utmost</b> caution. | |
22393 | */ | |
22394 | public"; | |
22395 | ||
22396 | %typemap(javaimports) Barmy " | |
22397 | /** The crazy class. Use as a last resort. */" | |
22398 | ||
22399 | class Barmy { | |
22400 | public: | |
22401 | void lose_marbles() {} | |
22402 | }; | |
22403 | </PRE> | |
22404 | </DIV> | |
22405 | <P> Note the "public" added at the end of the <TT>%javamethodmodifiers</TT> | |
22406 | as this is the default for this feature. The generated proxy class with | |
22407 | JavaDoc comments is then as follows:</P> | |
22408 | <DIV class="code"> | |
22409 | <PRE> | |
22410 | /** The crazy class. Use as a last resort. */ | |
22411 | public class Barmy { | |
22412 | ... | |
22413 | /** | |
22414 | * Calling this method will make you mad. | |
22415 | * Use with <b>utmost</b> caution. | |
22416 | */ | |
22417 | public void lose_marbles() { | |
22418 | ... | |
22419 | } | |
22420 | ... | |
22421 | } | |
22422 | </PRE> | |
22423 | </DIV> | |
22424 | <H3><A name="functional_interface"></A>19.11.2 Functional interface | |
22425 | without proxy classes</H3> | |
22426 | <P> It is possible to run SWIG in a mode that does not produce proxy | |
22427 | classes by using the -noproxy commandline option. The interface is | |
22428 | rather primitive when wrapping structures or classes and is accessed | |
22429 | through function calls to the module class. All the functions in the | |
22430 | module class are wrapped by functions with identical names as those in | |
22431 | the intermediary JNI class.</P> | |
22432 | <P> Consider the example we looked at when examining proxy classes:</P> | |
22433 | <DIV class="code"> | |
22434 | <PRE> | |
22435 | class Foo { | |
22436 | public: | |
22437 | int x; | |
22438 | int spam(int num, Foo* foo); | |
22439 | }; | |
22440 | </PRE> | |
22441 | </DIV> | |
22442 | <P> When using <TT>-noproxy</TT>, type wrapper classes are generated | |
22443 | instead of proxy classes. Access to all the functions and variables is | |
22444 | through a C like set of functions where the first parameter passed is | |
22445 | the pointer to the class, that is an instance of a type wrapper class. | |
22446 | Here is what the module class looks like:</P> | |
22447 | <DIV class="code"> | |
22448 | <PRE> | |
22449 | public class example { | |
22450 | public static void Foo_x_get(SWIGTYPE_p_Foo self, int x) {...} | |
22451 | public static int Foo_x_get(SWIGTYPE_p_Foo self) {...} | |
22452 | public static int Foo_spam(SWIGTYPE_p_Foo self, int num, SWIGTYPE_p_Foo foo) {...} | |
22453 | public static SWIGTYPE_p_Foo new_Foo() {...} | |
22454 | public static void delete_Foo(SWIGTYPE_p_Foo self) {...} | |
22455 | } | |
22456 | </PRE> | |
22457 | </DIV> | |
22458 | <P> This approach is not nearly as natural as using proxy classes as the | |
22459 | functions need to be used like this:</P> | |
22460 | <DIV class="code"> | |
22461 | <PRE> | |
22462 | SWIGTYPE_p_Foo foo = example.new_Foo(); | |
22463 | example.Foo_x_set(foo, 10); | |
22464 | int var = example.Foo_x_get(foo); | |
22465 | example.Foo_spam(foo, 20, foo); | |
22466 | example.delete_Foo(foo); | |
22467 | </PRE> | |
22468 | </DIV> | |
22469 | <P> Unlike proxy classes, there is no attempt at tracking memory. All | |
22470 | destructors have to be called manually for example the <TT> | |
22471 | delete_Foo(foo)</TT> call above.</P> | |
22472 | <H3><A name="using_own_jni_functions"></A>19.11.3 Using your own JNI | |
22473 | functions</H3> | |
22474 | <P> You may have some hand written JNI functions that you want to use in | |
22475 | addition to the SWIG generated JNI functions. Adding these to your SWIG | |
22476 | generated package is possible using the <TT>%native</TT> directive. If | |
22477 | you don't want SWIG to wrap your JNI function then of course you can | |
22478 | simply use the <TT>%ignore</TT> directive. However, if you want SWIG to | |
22479 | generate just the Java code for a JNI function then use the <TT>%native</TT> | |
22480 | directive. The C types for the parameters and return type must be | |
22481 | specified in place of the JNI types and the function name must be the | |
22482 | native method name. For example:</P> | |
22483 | <DIV class="code"> | |
22484 | <PRE> | |
22485 | %native (HandRolled) void HandRolled(int, char *); | |
22486 | %{ | |
22487 | JNIEXPORT void JNICALL Java_packageName_moduleName_HandRolled(JNIEnv *, jclass, | |
22488 | jlong, jstring); | |
22489 | %} | |
22490 | </PRE> | |
22491 | </DIV> | |
22492 | <P> No C JNI function will be generated and the <TT> | |
22493 | Java_packageName_moduleName_HandRolled</TT> function will be accessible | |
22494 | using the SWIG generated Java native method call in the intermediary | |
22495 | JNI class which will look like this:</P> | |
22496 | <DIV class="code"> | |
22497 | <PRE> | |
22498 | public final static native void HandRolled(int jarg1, String jarg2); | |
22499 | </PRE> | |
22500 | </DIV> | |
22501 | <P> and as usual this function is wrapped by another which for a global | |
22502 | C function would appear in the module class:</P> | |
22503 | <DIV class="code"> | |
22504 | <PRE> | |
22505 | public static void HandRolled(int arg0, String arg1) { | |
22506 | exampleJNI.HandRolled(arg0, arg1); | |
22507 | } | |
22508 | </PRE> | |
22509 | </DIV> | |
22510 | <P> The <TT>packageName</TT> and <TT>moduleName</TT> must of course be | |
22511 | correct else you will get linker errors when the JVM dynamically loads | |
22512 | the JNI function. You may have to add in some "jtype", "jstype", | |
22513 | "javain" and "javaout" typemaps when wrapping some JNI types. Here the | |
22514 | default typemaps work for <TT>int</TT> and <TT>char *</TT>.</P> | |
22515 | <P> In summary the <TT>%native</TT> directive is telling SWIG to | |
22516 | generate the Java code to access the JNI C code, but not the JNI C | |
22517 | function itself. This directive is only really useful if you want to | |
22518 | mix your own hand crafted JNI code and the SWIG generated code into one | |
22519 | Java class or package.</P> | |
22520 | <H3><A name="performance"></A>19.11.4 Performance concerns and hints</H3> | |
22521 | <P> If you're directly manipulating huge arrays of complex objects from | |
22522 | Java, performance may suffer greatly when using the array functions in <TT> | |
22523 | arrays_java.i</TT>. Try and minimise the expensive JNI calls to C/C++ | |
22524 | functions, perhaps by using temporary Java variables instead of | |
22525 | accessing the information directly from the C/C++ object.</P> | |
22526 | <P> Java classes without any finalizers generally speed up code | |
22527 | execution as there is less for the garbage collector to do. Finalizer | |
22528 | generation can be stopped by using an empty <TT>javafinalize</TT> | |
22529 | typemap:</P> | |
22530 | <DIV class="code"> | |
22531 | <PRE> | |
22532 | %typemap(javafinalize) SWIGTYPE "" | |
22533 | </PRE> | |
22534 | </DIV> | |
22535 | <P> However, you will have to be careful about memory management and | |
22536 | make sure that you code in a call to the <TT>delete()</TT> member | |
22537 | function. This method normally calls the C++ destructor or <TT>free()</TT> | |
22538 | for C code.</P> | |
22539 | <H2><A name="java_examples"></A>19.12 Examples</H2> | |
22540 | <P> The directory Examples/java has a number of further examples. Take a | |
22541 | look at these if you want to see some of the techniques described in | |
22542 | action. The Examples/index.html file in the parent directory contains | |
22543 | the SWIG Examples Documentation and is a useful starting point. If your | |
22544 | SWIG installation went well Unix users should be able to type <TT>make</TT> | |
22545 | in each example directory, then <TT>java main</TT> to see them running. | |
22546 | For the benefit of Windows users, there are also Visual C++ project | |
22547 | files in a couple of the <A href="#examples">Windows Examples</A>.</P> | |
22548 | <HR NOSHADE> | |
22549 | <H1><A name="Modula3"></A>20 SWIG and Modula-3</H1> | |
22550 | ||
22551 | <!-- INDEX --> | |
22552 | <DIV class="sectiontoc"> | |
22553 | <UL> | |
22554 | <LI><A href="#modula3_overview">Overview</A> | |
22555 | <UL> | |
22556 | <LI><A href="#whyscripting">Why not scripting ?</A></LI> | |
22557 | <LI><A href="#whymodula3">Why Modula-3 ?</A></LI> | |
22558 | <LI><A href="#whycpp">Why C / C++ ?</A></LI> | |
22559 | <LI><A href="#whyswig">Why SWIG ?</A></LI> | |
22560 | </UL> | |
22561 | </LI> | |
22562 | <LI><A href="#conception">Conception</A> | |
22563 | <UL> | |
22564 | <LI><A href="#cinterface">Interfaces to C libraries</A></LI> | |
22565 | <LI><A href="#cppinterface">Interfaces to C++ libraries</A></LI> | |
22566 | </UL> | |
22567 | </LI> | |
22568 | <LI><A href="#preliminaries">Preliminaries</A> | |
22569 | <UL> | |
22570 | <LI><A href="#compilers">Compilers</A></LI> | |
22571 | <LI><A href="#commandline">Additional Commandline Options</A></LI> | |
22572 | </UL> | |
22573 | </LI> | |
22574 | <LI><A href="#modula3_typemaps">Modula-3 typemaps</A> | |
22575 | <UL> | |
22576 | <LI><A href="#inoutparam">Inputs and outputs</A></LI> | |
22577 | <LI><A href="#ordinals">Subranges, Enumerations, Sets</A></LI> | |
22578 | <LI><A href="#class">Objects</A></LI> | |
22579 | <LI><A href="#imports">Imports</A></LI> | |
22580 | <LI><A href="#exceptions">Exceptions</A></LI> | |
22581 | <LI><A href="#typemap_example">Example</A></LI> | |
22582 | </UL> | |
22583 | </LI> | |
22584 | <LI><A href="#hints">More hints to the generator</A> | |
22585 | <UL> | |
22586 | <LI><A href="#features">Features</A></LI> | |
22587 | <LI><A href="#pragmas">Pragmas</A></LI> | |
22588 | </UL> | |
22589 | </LI> | |
22590 | <LI><A href="#remarks">Remarks</A></LI> | |
22591 | </UL> | |
22592 | </DIV> | |
22593 | <!-- INDEX --> | |
22594 | <P> This chapter describes SWIG's support of <A href="http://www.m3.org/"> | |
22595 | Modula-3</A>. You should be familiar with the <A href="#SWIG">basics</A> | |
22596 | of SWIG, especially <A href="Typemaps.html">typemaps</A>.</P> | |
22597 | <H2><A name="modula3_overview"></A>20.1 Overview</H2> | |
22598 | <P> The Modula-3 support is very basic and highly experimental! Many | |
22599 | features are still not designed satisfyingly and I need more discussion | |
22600 | about the odds and ends. Don't rely on any feature, incompatible | |
22601 | changes are likely in the future! The Modula-3 generator was already | |
22602 | useful for interfacing to the libraries</P> | |
22603 | <OL> | |
22604 | <LI> <A href="http://www.elegosoft.com/cgi-bin/cvsweb.cgi/cm3/m3-libs/plplot/"> | |
22605 | PLPlot</A></LI> | |
22606 | <LI> <A href="http://www.elegosoft.com/cgi-bin/cvsweb.cgi/cm3/m3-libs/fftw/"> | |
22607 | FFTW</A> .</LI> | |
22608 | </OL> | |
22609 | <P> I took some more time to explain why I think it's right what I'm | |
22610 | doing. So the introduction got a bit longer than it should ... ;-)</P> | |
22611 | <H3><A name="whyscripting"></A>20.1.1 Why not scripting ?</H3> | |
22612 | <P> SWIG started as wrapper from the fast compiled languages C and C++ | |
22613 | to high level scripting languages like Python. Although scripting | |
22614 | languages are designed to make programming life easier by hiding | |
22615 | machine internals from the programmer there are several aspects of | |
22616 | todays scripting languages that are unfavourable in my opinion.</P> | |
22617 | <P> Besides C, C++, Cluster (a Modula derivate for Amiga computers) I | |
22618 | evaluated several scripting like languages in the past: Different | |
22619 | dialects of BASIC, Perl, ARexx (a variant of Rexx for Amiga computers), | |
22620 | shell scripts. I found them too inconsistent, too weak in | |
22621 | distinguishing types, too weak in encapsulating pieces of code. | |
22622 | Eventually I have started several projects in Python because of the | |
22623 | fine syntax. But when projects became larger I lost the track. I got | |
22624 | convinced that one can not have maintainable code in a language that is | |
22625 | not statically typed. In fact the main advantages of scripting | |
22626 | languages e.g. matching regular expressions, complex built-in datatypes | |
22627 | like lists, dictionaries, are not advantages of the language itself but | |
22628 | can be provided by function libraries.</P> | |
22629 | <H3><A name="whymodula3"></A>20.1.2 Why Modula-3 ?</H3> | |
22630 | <P> Modula-3 is a compiler language in the tradition of Niklaus Wirth's | |
22631 | Modula 2, which is in turn a successor of the popular Pascal. I have | |
22632 | chosen Modula-3 because of its logical syntax, strong modularization, | |
22633 | the type system which is very detailed for machine types compared to | |
22634 | other languages. Of course it supports all of the modern games like | |
22635 | exceptions, objects, garbage collection, threads. While C++ programmers | |
22636 | must control three languages, namely the preprocessor, C and ++, | |
22637 | Modula-3 is made in one go and the language definition is really | |
22638 | compact.</P> | |
22639 | <P> On the one hand Modula-3 can be safe (but probably less efficient) | |
22640 | in normal modules while providing much static and dynamic safety. On | |
22641 | the other hand you can write efficient but less safe code in the style | |
22642 | of C within <TT>UNSAFE</TT> modules.</P> | |
22643 | <P> Unfortunately Modula's safety and strength requires more writing | |
22644 | than scripting languages do. Today if I want to safe characters I | |
22645 | prefer Haskell (similar to OCAML) - it's statically typed, too.</P> | |
22646 | <H3><A name="whycpp"></A>20.1.3 Why C / C++ ?</H3> | |
22647 | <P> Although it is no problem to write Modula-3 programs that performs | |
22648 | as fast as C most libraries are not written in Modula-3 but in C. | |
22649 | Fortunately the binary interface of most function libraries can be | |
22650 | addressed by Modula-3. Even more fortunately even non-C libraries may | |
22651 | provide C header files. This is where SWIG becomes helpful.</P> | |
22652 | <H3><A name="whyswig"></A>20.1.4 Why SWIG ?</H3> | |
22653 | <P> The C headers and the possibility to interface to C libraries still | |
22654 | leaves the work for you to write Modula-3 interfaces to them. To make | |
22655 | things comfortable you will also need wrappers that convert between | |
22656 | high-level features of Modula-3 (garbage collecting, exceptions) and | |
22657 | the low level of the C libraries.</P> | |
22658 | <P> SWIG converts C headers to Modula-3 interfaces for you. You could | |
22659 | call the C functions without loss of efficiency but it won't be joy | |
22660 | because you could not pass <TT>TEXT</TT>s or open arrays and you would | |
22661 | have to process error return codes rather then exceptions. But using | |
22662 | some typemaps SWIG will also generate wrappers that bring the whole | |
22663 | Modula-3 comfort to you. If the library API is ill designed writing | |
22664 | appropriate typemaps can be still time-consuming. E.g. C programmers | |
22665 | are very creative to work-around missing data types like (real) | |
22666 | enumerations and sets. You should turn such work-arounds back to the | |
22667 | Modula-3 way otherwise you lose static safety and consistency.</P> | |
22668 | <P> But you have still a problem: C library interfaces are often ill. | |
22669 | They lack for certain information because C compilers wouldn't care | |
22670 | about. You should integrate detailed type information by adding <TT> | |
22671 | typedef</TT>s and <TT>const</TT>s and you should persuade the C library | |
22672 | programmer to add this information to his interface. Only this way | |
22673 | other language users can benefit from your work and only this way you | |
22674 | can easily update your interfaces when a new library version is | |
22675 | released. You will realise that writing<B> good</B> SWIG interfaces is | |
22676 | very costly and it will only amortise when considering evolving | |
22677 | libraries.</P> | |
22678 | <P> Without SWIG you would probably never consider to call C++ libraries | |
22679 | from Modula-3. But with SWIG this is worth a consideration. SWIG can | |
22680 | write C wrappers to C++ functions and object methods that may throw | |
22681 | exceptions. In fact it breaks down C++ libraries to C interfaces which | |
22682 | can be in turn called from Modula-3. To make it complete you can hide | |
22683 | the C interface with Modula-3 classes and exceptions.</P> | |
22684 | <P> Although SWIG does the best it can do it can only serve as a one-way | |
22685 | strategy. That means you can use C++ libraries with Modula-3 (even with | |
22686 | call back functions), but it's certainly not possible to smoothly | |
22687 | integrate Modula-3 code into a C / C++ project.</P> | |
22688 | <H2><A name="conception"></A>20.2 Conception</H2> | |
22689 | <H3><A name="cinterface"></A>20.2.1 Interfaces to C libraries</H3> | |
22690 | <P> Modula-3 has an integrated support for calling C functions. This is | |
22691 | also extensively used by the standard Modula-3 libraries to call OS | |
22692 | functions. The Modula-3 part of SWIG and the corresponding SWIG library | |
22693 | <A href="../../Lib/modula3/modula3.swg"><TT>modula3.swg</TT></A> | |
22694 | contain code that uses these features. Because of the built-in support | |
22695 | there is no need for calling the SWIG kernel to generate wrappers | |
22696 | written in C. All conversion and argument checking can be done in | |
22697 | Modula-3 and the interfacing is quite efficient. All you have to do is | |
22698 | to write pieces of Modula-3 code that SWIG puts together.</P> | |
22699 | <TABLE border summary="Modula-3 C library support"> | |
22700 | <TR><TH colspan="2">C library support integrated in Modula-3</TH><TH></TH> | |
22701 | </TR> | |
22702 | <TR><TD>Pragma <TT><* EXTERNAL *></TT></TD><TD>Precedes a declaration of | |
22703 | a PROCEDURE that is implemented in an external library instead of a | |
22704 | Modula-3 module.</TD></TR> | |
22705 | <TR><TD>Pragma <TT><* CALLBACK *></TT></TD><TD>Precedes a declaration of | |
22706 | a PROCEDURE that should be called by external library code.</TD></TR> | |
22707 | <TR><TD>Module <TT>Ctypes</TT></TD><TD>Contains Modula-3 types that | |
22708 | match some basic C types.</TD></TR> | |
22709 | <TR><TD>Module <TT>M3toC</TT></TD><TD>Contains routines that convert | |
22710 | between Modula-3's <TT>TEXT</TT> type and C's <TT>char *</TT> type.</TD> | |
22711 | </TR> | |
22712 | </TABLE> | |
22713 | <P> In each run of SWIG the Modula-3 part generates several files:</P> | |
22714 | <TABLE border summary="Modula-3 generated files"> | |
22715 | <TR><TH>Module name scheme</TH><TH>Identifier for <TT>%insert</TT></TH><TH> | |
22716 | Description</TH></TR> | |
22717 | <TR><TD>Module<TT>Raw.i3</TT></TD><TD><TT>m3rawintf</TT></TD><TD> | |
22718 | Declaration of types that are equivalent to those of the C library, <TT> | |
22719 | EXTERNAL</TT> procedures as interface to the C library functions</TD></TR> | |
22720 | <TR><TD>Module<TT>Raw.m3</TT></TD><TD><TT>m3rawimpl</TT></TD><TD>Almost | |
22721 | empty.</TD></TR> | |
22722 | <TR><TD>Module<TT>.i3</TT></TD><TD><TT>m3wrapintf</TT></TD><TD> | |
22723 | Declaration of comfortable wrappers to the C library functions.</TD></TR> | |
22724 | <TR><TD>Module<TT>.m3</TT></TD><TD><TT>m3wrapimpl</TT></TD><TD> | |
22725 | Implementation of the wrappers that convert between Modula-3 and C | |
22726 | types, check for validity of values, hand-over resource management to | |
22727 | the garbage collector using <TT>WeakRef</TT>s and raises exceptions.</TD> | |
22728 | </TR> | |
22729 | <TR><TD><TT>m3makefile</TT></TD><TD><TT>m3makefile</TT></TD><TD>Add the | |
22730 | modules above to the Modula-3 project and specify the name of the | |
22731 | Modula-3 wrapper library to be generated. Today I'm not sure if it is a | |
22732 | good idea to create a <TT>m3makefile</TT> in each run, because SWIG | |
22733 | must be started for each Modula-3 module it creates. Thus the | |
22734 | m3makefile is overwritten each time. :-(</TD></TR> | |
22735 | </TABLE> | |
22736 | <P> Here's a scheme of how the function calls to Modula-3 wrappers are | |
22737 | redirected to C library functions:</P> | |
22738 | <TABLE summary="Modula-3 C library"> | |
22739 | <TR><TD align="center"> Modula-3 wrapper | |
22740 | <BR> Module<TT>.i3</TT> | |
22741 | <BR> generated by Modula-3 part of SWIG</TD><TD></TD><TD align="center"></TD> | |
22742 | </TR> | |
22743 | <TR><TD align="center"> | |
22744 | <!-- pre tag overrides centering --> | |
22745 | | | |
22746 | <BR> v</TD><TD></TD><TD align="center"></TD></TR> | |
22747 | <TR><TD align="center"> Modula-3 interface to C | |
22748 | <BR> Module<TT>Raw.i3</TT> | |
22749 | <BR> generated by Modula-3 part of SWIG</TD><TD>--></TD><TD align="center"> | |
22750 | C library</TD></TR> | |
22751 | </TABLE> | |
22752 | <P> I have still no good conception how one can split C library | |
22753 | interfaces into type oriented interfaces. A Module in Modula-3 | |
22754 | represents an Abstract DataType (or call it a static classes, i.e. a | |
22755 | class without virtual methods). E.g. if you have a principal type, say <TT> | |
22756 | Database</TT>, it is good Modula-3 style to set up one Module with the | |
22757 | name <TT>Database</TT> where the database type is declared with the | |
22758 | name <TT>T</TT> and where all functions are declared that operates on | |
22759 | it.</P> | |
22760 | <P> The normal operation of SWIG is to generate a fixed set of files per | |
22761 | call. To generate multiple modules one has to write one SWIG interface | |
22762 | (different SWIG interfaces can share common data) per module. | |
22763 | Identifiers belonging to a different module may ignored (<TT>%ignore</TT> | |
22764 | ) and the principal type must be renamed (<TT>%typemap</TT>).</P> | |
22765 | <H3><A name="cppinterface"></A>20.2.2 Interfaces to C++ libraries</H3> | |
22766 | <P> Interfaces to C++ files are much more complicated and there are some | |
22767 | more design decisions that are not made, yet. Modula-3 has no support | |
22768 | for C++ functions but C++ compilers should support generating C++ | |
22769 | functions with a C interface.</P> | |
22770 | <P> Here's a scheme of how the function calls to Modula-3 wrappers a | |
22771 | redirected to C library functions:</P> | |
22772 | <TABLE summary="Modula-3 C++ library"> | |
22773 | <TR><TD align="center"> Modula-3 wrapper | |
22774 | <BR> Module<TT>.i3</TT> | |
22775 | <BR> generated by Modula-3 part of SWIG</TD><TD></TD><TD align="center"> | |
22776 | C++ library</TD></TR> | |
22777 | <TR><TD align="center"> | |
22778 | <!-- pre tag overrides centering --> | |
22779 | | | |
22780 | <BR> v</TD><TD></TD><TD align="center"> ^ | |
22781 | <BR> |</TD></TR> | |
22782 | <TR><TD align="center"> Modula-3 interface to C | |
22783 | <BR> Module<TT>Raw.i3</TT> | |
22784 | <BR> generated by Modula-3 part of SWIG</TD><TD>--></TD><TD align="center"> | |
22785 | C interface to C++ | |
22786 | <BR> module<TT>_wrap.cxx</TT> | |
22787 | <BR> generated by the SWIG core</TD></TR> | |
22788 | </TABLE> | |
22789 | <P> Wrapping C++ libraries arises additional problems:</P> | |
22790 | <UL> | |
22791 | <LI> Is it sensible to wrap C++ classes with Modula-3 classes?</LI> | |
22792 | <LI> How to find the wrapping Modula-3 class for a class pointer that is | |
22793 | returned by a C++ routine?</LI> | |
22794 | <LI> How to deal with multiple inheritance which was neglected for | |
22795 | Modula-3 for good reasons?</LI> | |
22796 | <LI> Is it possible to sub-class C++ classes with Modula-3 code? This | |
22797 | issue is addressed by directors, a feature that was experimentally | |
22798 | added to some Language modules like <A href="#java_directors">Java</A> | |
22799 | and <A href="#directors">Python</A>.</LI> | |
22800 | <LI> How to manage storage with the garbage collector of Modula-3? | |
22801 | Support for <A href="#ownership"> <TT>%newobject</TT> and <TT> | |
22802 | %typemap(newfree)</TT></A> isn't implemented, yet. What's about | |
22803 | resources that are managed by the garbage collector but shall be passed | |
22804 | back to the storage management of the C++ library? This is a general | |
22805 | issue which is not solved in a satisfying fashion as far as I know.</LI> | |
22806 | <LI> How to turn C++ exceptions into Modula-3 exceptions? There's also | |
22807 | no support for <A href="#exception"> <TT>%exception</TT></A>, yet.</LI> | |
22808 | </UL> | |
22809 | <P> Be warned: There is no C++ library I wrote a SWIG interface for, so | |
22810 | I'm not sure if this is possible or sensible, yet.</P> | |
22811 | <H2><A name="preliminaries"></A>20.3 Preliminaries</H2> | |
22812 | <H3><A name="compilers"></A>20.3.1 Compilers</H3> | |
22813 | <P> There are different Modula-3 compilers around: cm3, pm3, ezm3, | |
22814 | Klagenfurth Modula-3, Cambridge Modula-3. SWIG itself does not contain | |
22815 | compiler specific code but the library file <A href="../../Lib/modula3/modula3.swg"> | |
22816 | <TT>modula3.swg</TT></A> may do so. For testing examples I use Critical | |
22817 | Mass cm3.</P> | |
22818 | <H3><A name="commandline"></A>20.3.2 Additional Commandline Options</H3> | |
22819 | <P> There are some experimental command line options that prevent SWIG | |
22820 | from generating interface files. Instead files are emitted that may | |
22821 | assist you when writing SWIG interface files.</P> | |
22822 | <TABLE border summary="Modula-3 specific options"> | |
22823 | <TR><TH>Modula-3 specific options</TH><TH>Description</TH></TR> | |
22824 | <TR><TD valign="top">-generateconst <file></TD><TD> Disable generation | |
22825 | of interfaces and wrappers. Instead write code for computing numeric | |
22826 | values of constants to the specified file. | |
22827 | <BR> C code may contain several constant definitions written as | |
22828 | preprocessor macros. Other language modules of SWIG use | |
22829 | compute-once-use-readonly variables or functions to wrap such | |
22830 | definitions. All of them can invoke C code dynamically for computing | |
22831 | the macro values. But if one wants to turn them into Modula-3 integer | |
22832 | constants, enumerations or set types, the values of these expressions | |
22833 | has to be known statically. Although definitions like <TT>(1 << | |
22834 | FLAG_MAXIMIZEWINDOW)</TT> must be considered as good C style they are | |
22835 | hard to convert to Modula-3 since the value computation can use every | |
22836 | feature of C. | |
22837 | <BR> Thus I implemented these switch to extract all constant definitions | |
22838 | and write a C program that output the values of them. It works for | |
22839 | numeric constants only and treats all of them as <TT>double</TT>. | |
22840 | Future versions may generate a C++ program that can detect the type of | |
22841 | the macros by overloaded output functions. Then strings can also be | |
22842 | processed.</TD></TR> | |
22843 | <TR><TD valign="top">-generaterename <file></TD><TD> Disable generation | |
22844 | of interfaces and wrappers. Instead generate suggestions for <TT> | |
22845 | %rename</TT>. | |
22846 | <BR> C libraries use a naming style that is neither homogenous nor | |
22847 | similar to that of Modula-3. C function names often contain a prefix | |
22848 | denoting the library and some name components separated by underscores | |
22849 | or capitalization changes. To get library interfaces that are really | |
22850 | Modula-3 like you should rename the function names with the <TT>%rename</TT> | |
22851 | directive. This switch outputs a list of such directives with a name | |
22852 | suggestion generated by a simple heuristic.</TD></TR> | |
22853 | <TR><TD valign="top">-generatetypemap <file></TD><TD> Disable generation | |
22854 | of interfaces and wrappers. Instead generate templates for some basic | |
22855 | typemaps.</TD></TR> | |
22856 | </TABLE> | |
22857 | <H2><A name="modula3_typemaps"></A>20.4 Modula-3 typemaps</H2> | |
22858 | <H3><A name="inoutparam"></A>20.4.1 Inputs and outputs</H3> | |
22859 | <P> Each C procedure has a bunch of inputs and outputs. Inputs are | |
22860 | passed as function arguments, outputs are updated referential arguments | |
22861 | and the function value.</P> | |
22862 | <P> Each C type can have several typemaps that apply only in case if a | |
22863 | type is used for an input argument, for an output argument, or for a | |
22864 | return value. A further typemap may specify the direction that is used | |
22865 | for certain parameters. I have chosen this separation in order to be | |
22866 | able to write general typemaps for the typemap library <A href="../../Lib/modula3/modula3.swg"> | |
22867 | <TT>modula3.swg</TT></A> . In the library code the final usage of the | |
22868 | type is not known. Using separate typemaps for each possible use allows | |
22869 | appropriate definitions for each case. If these pre-definitions are | |
22870 | fine then the direction of the function parameter is the only hint the | |
22871 | user must give.</P> | |
22872 | <P> The typemaps specific to Modula-3 have a common name scheme: A | |
22873 | typemap name starts with "m3", followed by "raw" or "wrap" depending on | |
22874 | whether it controls the generation of the Module<TT>Raw.i3</TT> or the | |
22875 | Module<TT>.i3</TT>, respectively. It follows an "in" for typemaps | |
22876 | applied to input argument, "out" for output arguments, "arg" for all | |
22877 | kind of arguments, "ret" for returned values.</P> | |
22878 | <P> The main task of SWIG is to build wrapper function, i.e. functions | |
22879 | that convert values between C and Modula-3 and call the corresponding C | |
22880 | function. Modula-3 wrapper functions generated by SWIG consist of the | |
22881 | following parts:</P> | |
22882 | <UL> | |
22883 | <LI>Generate <TT>PROCEDURE</TT> signature.</LI> | |
22884 | <LI>Declare local variables.</LI> | |
22885 | <LI>Convert input values from Modula-3 to C.</LI> | |
22886 | <LI>Check for input value integrity.</LI> | |
22887 | <LI>Call the C function.</LI> | |
22888 | <LI>Check returned values, e.g. error codes.</LI> | |
22889 | <LI>Convert and write back values into Modula-3 records.</LI> | |
22890 | <LI>Free temporary storage.</LI> | |
22891 | <LI>Return values.</LI> | |
22892 | </UL> | |
22893 | <TABLE border summary="Modula-3 typemaps"> | |
22894 | <TR><TH>Typemap</TH><TH>Example</TH><TH>Description</TH></TR> | |
22895 | <TR><TD>m3wrapargvar</TD><TD><TT>$1: INTEGER := $1_name;</TT></TD><TD> | |
22896 | Declaration of some variables needed for temporary results.</TD></TR> | |
22897 | <TR><TD>m3wrapargconst</TD><TD><TT>$1 = "$1_name";</TT></TD><TD> | |
22898 | Declaration of some constant, maybe for debug purposes.</TD></TR> | |
22899 | <TR><TD>m3wrapargraw</TD><TD><TT>ORD($1_name)</TT></TD><TD> The | |
22900 | expression that should be passed as argument to the raw Modula-3 | |
22901 | interface function.</TD></TR> | |
22902 | <TR><TD>m3wrapargdir</TD><TD><TT>out</TT></TD><TD> Referential arguments | |
22903 | can be used for input, output, update. ???</TD></TR> | |
22904 | <TR><TD>m3wrapinmode</TD><TD><TT>READONLY</TT></TD><TD> One of Modula-3 | |
22905 | parameter modes <TT>VALUE</TT> (or empty), <TT>VAR</TT>, <TT>READONLY</TT> | |
22906 | </TD></TR> | |
22907 | <TR><TD>m3wrapinname</TD><TD></TD><TD> New name of the input argument.</TD> | |
22908 | </TR> | |
22909 | <TR><TD>m3wrapintype</TD><TD></TD><TD> Modula-3 type of the input | |
22910 | argument.</TD></TR> | |
22911 | <TR><TD>m3wrapindefault</TD><TD></TD><TD> Default value of the input | |
22912 | argument</TD></TR> | |
22913 | <TR><TD>m3wrapinconv</TD><TD><TT>$1 := M3toC.SharedTtoS($1_name);</TT></TD><TD> | |
22914 | Statement for converting the Modula-3 input value to C compliant value.</TD> | |
22915 | </TR> | |
22916 | <TR><TD>m3wrapincheck</TD><TD><TT>IF Text.Length($1_name) > 10 THEN | |
22917 | RAISE E("str too long"); END;</TT></TD><TD> Check the integrity of the | |
22918 | input value.</TD></TR> | |
22919 | <TR><TD>m3wrapoutname</TD><TD></TD><TD> Name of the <TT>RECORD</TT> | |
22920 | field to be used for returning multiple values. This applies to | |
22921 | referential output arguments that shall be turned into return values.</TD> | |
22922 | </TR> | |
22923 | <TR><TD>m3wrapouttype</TD><TD></TD><TD> Type of the value that is | |
22924 | returned instead of a referential output argument.</TD></TR> | |
22925 | <TR><TD>m3wrapoutconv</TD><TD></TD><TD></TD></TR> | |
22926 | <TR><TD>m3wrapoutcheck</TD><TD></TD><TD></TD></TR> | |
22927 | <TR><TD>m3wrapretraw</TD><TD></TD><TD></TD></TR> | |
22928 | <TR><TD>m3wrapretname</TD><TD></TD><TD></TD></TR> | |
22929 | <TR><TD>m3wraprettype</TD><TD></TD><TD></TD></TR> | |
22930 | <TR><TD>m3wrapretvar</TD><TD></TD><TD></TD></TR> | |
22931 | <TR><TD>m3wrapretconv</TD><TD></TD><TD></TD></TR> | |
22932 | <TR><TD>m3wrapretcheck</TD><TD></TD><TD></TD></TR> | |
22933 | <TR><TD>m3wrapfreearg</TD><TD><TT>M3toC.FreeSharedS(str,arg1);</TT></TD><TD> | |
22934 | Free resources that were temporarily used in the wrapper. Since this | |
22935 | step should never be skipped, SWIG will put it in the <TT>FINALLY</TT> | |
22936 | branch of a <TT>TRY .. FINALLY</TT> structure.</TD></TR> | |
22937 | </TABLE> | |
22938 | <H3><A name="ordinals"></A>20.4.2 Subranges, Enumerations, Sets</H3> | |
22939 | <P> Subranges, enumerations, and sets are machine oriented types that | |
22940 | make Modula very strong and expressive compared with the type systems | |
22941 | of many other languages.</P> | |
22942 | <UL> | |
22943 | <LI> Subranges are used for statically restricted choices of integers.</LI> | |
22944 | <LI> Enumerations are used for named choices.</LI> | |
22945 | <LI> Sets are commonly used for flag (option) sets.</LI> | |
22946 | </UL> | |
22947 | <P> Using them extensively makes Modula code very safe and readable.</P> | |
22948 | <P> C supports enumerations, too, but they are not as safe as the ones | |
22949 | of Modula. Thus they are abused for many things: For named choices, for | |
22950 | integer constant definitions, for sets. To make it complete every way | |
22951 | of defining a value in C (<TT>#define</TT>, <TT>const int</TT>, <TT> | |
22952 | enum</TT>) is somewhere used for defining something that must be handled | |
22953 | completely different in Modula-3 (<TT>INTEGER</TT>, enumeration, <TT> | |
22954 | SET</TT>).</P> | |
22955 | <P> I played around with several <TT>%feature</TT>s and <TT>%pragma</TT> | |
22956 | s that split the task up into converting the C bit patterns (integer or | |
22957 | bit set) into Modula-3 bit patterns (integer or bit set) and change the | |
22958 | type as requested. See the corresponding <A href="../../Examples/modula3/enum/example.i"> | |
22959 | example</A>. This is quite messy and not satisfying. So the best what | |
22960 | you can currently do is to rewrite constant definitions manually. | |
22961 | Though this is a tedious work that I'd like to automate.</P> | |
22962 | <H3><A name="class"></A>20.4.3 Objects</H3> | |
22963 | <P> Declarations of C++ classes are mapped to <TT>OBJECT</TT> types | |
22964 | while it is tried to retain the access hierarchy "public - protected - | |
22965 | private" using partial revelation. Though the <A href="../../Examples/modula3/class/example.i"> | |
22966 | implementation</A> is not really useful, yet.</P> | |
22967 | <H3><A name="imports"></A>20.4.4 Imports</H3> | |
22968 | <P> Pieces of Modula-3 code provided by typemaps may contain identifiers | |
22969 | from foreign modules. If the typemap <TT>m3wrapinconv</TT> for <TT>blah | |
22970 | *</TT> contains code using the function <TT>M3toC.SharedTtoS</TT> you | |
22971 | may declare <TT>%typemap("m3wrapinconv:import") blah * %{M3toC%}</TT>. | |
22972 | Then the module <TT>M3toC</TT> is imported if the <TT>m3wrapinconv</TT> | |
22973 | typemap for <TT>blah *</TT> is used at least once. Use <TT> | |
22974 | %typemap("m3wrapinconv:import") blah * %{MyConversions AS M3toC%}</TT> | |
22975 | if you need module renaming. Unqualified import is not supported.</P> | |
22976 | <P> It is cumbersome to add this typemap to each piece of Modula-3 code. | |
22977 | It is especially useful when writing general typemaps for the typemap | |
22978 | library <A href="../../Lib/modula3/modula3.swg"><TT>modula3.swg</TT></A> | |
22979 | . For a monolithic module you might be better off if you add the | |
22980 | imports directly:</P> | |
22981 | <DIV class="code"> | |
22982 | <PRE> | |
22983 | %insert(m3rawintf) %{ | |
22984 | IMPORT M3toC; | |
22985 | %} | |
22986 | </PRE> | |
22987 | </DIV> | |
22988 | <H3><A name="exceptions"></A>20.4.5 Exceptions</H3> | |
22989 | <P> Modula-3 provides another possibility of an output of a function: | |
22990 | exceptions.</P> | |
22991 | <P> Any piece of Modula-3 code that SWIG inserts due to a typemap can | |
22992 | raise an exception. This way you can also convert an error code from a | |
22993 | C function into a Modula-3 exception.</P> | |
22994 | <P> The <TT>RAISES</TT> clause is controlled by typemaps with the <TT> | |
22995 | throws</TT> extension. If the typemap <TT>m3wrapinconv</TT> for <TT>blah | |
22996 | *</TT> contains code that may raise the exceptions <TT>OSError.E</TT> | |
22997 | you should declare <TT>%typemap("m3wrapinconv:throws") blah * | |
22998 | %{OSError.E%}</TT>.</P> | |
22999 | <H3><A name="typemap_example"></A>20.4.6 Example</H3> | |
23000 | <P> The generation of wrappers in Modula-3 needs very fine control to | |
23001 | take advantage of the language features. Here is an example of a | |
23002 | generated wrapper where almost everything is generated by a typemap:</P> | |
23003 | <DIV class="code"> | |
23004 | <PRE> | |
23005 | <I> (* %relabel m3wrapinmode m3wrapinname m3wrapintype m3wrapindefault *)</I> | |
23006 | PROCEDURE Name (READONLY str : TEXT := "" ) | |
23007 | <I> (* m3wrapoutcheck:throws *)</I> | |
23008 | : NameResult RAISES {E} = | |
23009 | CONST | |
23010 | arg1name = "str"; <I>(* m3wrapargconst *)</I> | |
23011 | VAR | |
23012 | arg0 : C.char_star; <I>(* m3wrapretvar *)</I> | |
23013 | arg1 : C.char_star; <I>(* m3wrapargvar *)</I> | |
23014 | arg2 : C.int; | |
23015 | result : RECORD | |
23016 | <I> (*m3wrapretname m3wraprettype*)</I> | |
23017 | unixPath : TEXT; | |
23018 | <I> (*m3wrapoutname m3wrapouttype*)</I> | |
23019 | checksum : CARDINAL; | |
23020 | END; | |
23021 | BEGIN | |
23022 | TRY | |
23023 | arg1 := M3toC.SharedTtoS(str); <I>(* m3wrapinconv *)</I> | |
23024 | IF Text.Length(arg1) > 10 THEN <I>(* m3wrapincheck *)</I> | |
23025 | RAISE E("str too long"); | |
23026 | END; | |
23027 | <I> (* m3wrapretraw m3wrapargraw *)</I> | |
23028 | arg0 := MessyToUnix (arg1, arg2); | |
23029 | result.unixPath := M3toC.CopyStoT(arg0); <I>(* m3wrapretconv *)</I> | |
23030 | result.checksum := arg2; <I>(* m3wrapoutconv *)</I> | |
23031 | IF result.checksum = 0 THEN <I>(* m3wrapoutcheck *)</I> | |
23032 | RAISE E("invalid checksum"); | |
23033 | END; | |
23034 | FINALLY | |
23035 | M3toC.FreeSharedS(str,arg1); <I>(* m3wrapfreearg *)</I> | |
23036 | END; | |
23037 | END Name; | |
23038 | </PRE> | |
23039 | </DIV> | |
23040 | <H2><A name="hints"></A>20.5 More hints to the generator</H2> | |
23041 | <H3><A name="features"></A>20.5.1 Features</H3> | |
23042 | <TABLE border summary="Modula-3 features"> | |
23043 | <TR><TH>Feature</TH><TH>Example</TH><TH>Description</TH></TR> | |
23044 | <TR><TD>multiretval</TD><TD><TT>%m3multiretval get_box;</TT> or <TT> | |
23045 | %feature("modula3:multiretval") get_box;</TT></TD><TD>Let the denoted | |
23046 | function return a <TT>RECORD</TT> rather than a plain value. This <TT> | |
23047 | RECORD</TT> contains all arguments with "out" direction including the | |
23048 | return value of the C function (if there is one). If more than one | |
23049 | argument is "out" then the function<B> must</B> have the <TT> | |
23050 | multiretval</TT> feature activated, but it is explicitly requested from | |
23051 | the user to prevent mistakes.</TD></TR> | |
23052 | <TR><TD>constnumeric</TD><TD><TT>%constnumeric(12) twelve;</TT> or <TT> | |
23053 | %feature("constnumeric","12") twelve;</TT></TD><TD>This feature can be | |
23054 | used to tell Modula-3's back-end of SWIG the value of an identifier. | |
23055 | This is necessary in the cases where it was defined by a non-trivial C | |
23056 | expression. This feature is used by the <TT>-generateconst</TT> <A href="#options"> | |
23057 | option</A>. In future it may be generalized to other kind of values such | |
23058 | as strings.</TD></TR> | |
23059 | </TABLE> | |
23060 | <H3><A name="pragmas"></A>20.5.2 Pragmas</H3> | |
23061 | <TABLE border summary="Modula-3 pragmas"> | |
23062 | <TR><TH>Pragma</TH><TH>Example</TH><TH>Description</TH></TR> | |
23063 | <TR><TD>unsafe</TD><TD><TT>%pragma(modula3) unsafe="true";</TT></TD><TD> | |
23064 | Mark the raw interface modules as <TT>UNSAFE</TT>. This will be | |
23065 | necessary in many cases.</TD></TR> | |
23066 | <TR><TD>library</TD><TD><TT>%pragma(modula3) library="m3fftw";</TT></TD><TD> | |
23067 | Specifies the library name for the wrapper library to be created. It | |
23068 | should be distinct from the name of the library to be wrapped.</TD></TR> | |
23069 | </TABLE> | |
23070 | <H2><A name="remarks"></A>20.6 Remarks</H2> | |
23071 | <UL> | |
23072 | <LI> The Modula-3 part of SWIG doesn't try to generate nicely formatted | |
23073 | code. Use <TT>m3pp</TT> to postprocess the Modula files, it does a very | |
23074 | good job here.</LI> | |
23075 | </UL> | |
23076 | <HR NOSHADE> | |
23077 | ||
23078 | <!-- Hand-written HTML --> | |
23079 | <H1><A name="MzScheme"></A>21 SWIG and MzScheme</H1> | |
23080 | ||
23081 | <!-- INDEX --> | |
23082 | <DIV class="sectiontoc"> | |
23083 | <UL> | |
23084 | <LI><A href="#MzScheme_nn2">Creating native MzScheme structures</A></LI> | |
23085 | </UL> | |
23086 | </DIV> | |
23087 | <!-- INDEX --> | |
23088 | <P> This section contains information on SWIG's support of MzScheme.</P> | |
23089 | <H2><A name="MzScheme_nn2"></A>21.1 Creating native MzScheme structures</H2> | |
23090 | <P> Example interface file:</P> | |
23091 | <DIV class="code"> | |
23092 | <PRE> | |
23093 | /* define a macro for the struct creation */ | |
23094 | %define handle_ptr(TYPE,NAME) | |
23095 | %typemap(mzscheme,argout) TYPE *NAME{ | |
23096 | Scheme_Object *o = SWIG_NewStructFromPtr($1, $*1_mangle); | |
23097 | SWIG_APPEND_VALUE(o); | |
23098 | } | |
23099 | ||
23100 | %typemap(mzscheme,in,numinputs=0) TYPE *NAME (TYPE temp) { | |
23101 | $1 = &temp; | |
23102 | } | |
23103 | %enddef | |
23104 | ||
23105 | /* setup the typemaps for the pointer to an output parameter cntrs */ | |
23106 | handle_ptr(struct diag_cntrs, cntrs); | |
23107 | </PRE> | |
23108 | </DIV> | |
23109 | <P> Then in scheme, you can use regular struct access procedures like</P> | |
23110 | <DIV class="code"> | |
23111 | <PRE> | |
23112 | ; suppose a function created a struct foo as | |
23113 | ; (define foo (make-diag-cntrs (#x1 #x2 #x3) (make-inspector)) | |
23114 | ; Then you can do | |
23115 | (format "0x~x" (diag-cntrs-field1 foo)) | |
23116 | (format "0x~x" (diag-cntrs-field2 foo)) | |
23117 | ;etc... | |
23118 | </PRE> | |
23119 | </DIV> | |
23120 | <P> That's pretty much it. It works with nested structs as well.</P> | |
23121 | <HR NOSHADE> | |
23122 | <A name="n1"></A> | |
23123 | <H1><A name="Ocaml"></A>22 SWIG and Ocaml</H1> | |
23124 | ||
23125 | <!-- INDEX --> | |
23126 | <DIV class="sectiontoc"> | |
23127 | <UL> | |
23128 | <LI><A href="#Ocaml_nn2">Preliminaries</A> | |
23129 | <UL> | |
23130 | <LI><A href="#Ocaml_nn3">Running SWIG</A></LI> | |
23131 | <LI><A href="#Ocaml_nn4">Compiling the code</A></LI> | |
23132 | <LI><A href="#Ocaml_nn5">The camlp4 module</A></LI> | |
23133 | <LI><A href="#Ocaml_nn6">Using your module</A></LI> | |
23134 | <LI><A href="#Ocaml_nn7">Compilation problems and compiling with C++</A></LI> | |
23135 | </UL> | |
23136 | </LI> | |
23137 | <LI><A href="#Ocaml_nn8">The low-level Ocaml/C interface</A> | |
23138 | <UL> | |
23139 | <LI><A href="#Ocaml_nn9">The generated module</A></LI> | |
23140 | <LI><A href="#Ocaml_nn10">Enums</A> | |
23141 | <UL> | |
23142 | <LI><A href="#Ocaml_nn11">Enum typing in Ocaml</A></LI> | |
23143 | </UL> | |
23144 | </LI> | |
23145 | <LI><A href="#Ocaml_nn12">Arrays</A> | |
23146 | <UL> | |
23147 | <LI><A href="#Ocaml_nn13">Simple types of bounded arrays</A></LI> | |
23148 | <LI><A href="#Ocaml_nn14">Complex and unbounded arrays</A></LI> | |
23149 | <LI><A href="#Ocaml_nn15">Using an object</A></LI> | |
23150 | <LI><A href="#Ocaml_nn16">Example typemap for a function taking float * | |
23151 | and int</A></LI> | |
23152 | </UL> | |
23153 | </LI> | |
23154 | <LI><A href="#Ocaml_nn17">C++ Classes</A> | |
23155 | <UL> | |
23156 | <LI><A href="#Ocaml_nn18">STL vector and string Example</A></LI> | |
23157 | <LI><A href="#Ocaml_nn19">C++ Class Example</A></LI> | |
23158 | <LI><A href="#Ocaml_nn20">Compiling the example</A></LI> | |
23159 | <LI><A href="#Ocaml_nn21">Sample Session</A></LI> | |
23160 | </UL> | |
23161 | </LI> | |
23162 | <LI><A href="#Ocaml_nn22">Director Classes</A> | |
23163 | <UL> | |
23164 | <LI><A href="#Ocaml_nn23">Director Introduction</A></LI> | |
23165 | <LI><A href="#Ocaml_nn24">Overriding Methods in Ocaml</A></LI> | |
23166 | <LI><A href="#Ocaml_nn25">Director Usage Example</A></LI> | |
23167 | <LI><A href="#Ocaml_nn26">Creating director objects</A></LI> | |
23168 | <LI><A href="#Ocaml_nn27">Typemaps for directors, <TT>directorin, | |
23169 | directorout, directorargout</TT></A></LI> | |
23170 | <LI><A href="#Ocaml_nn28"><TT>directorin</TT> typemap</A></LI> | |
23171 | <LI><A href="#Ocaml_nn29"><TT>directorout</TT> typemap</A></LI> | |
23172 | <LI><A href="#Ocaml_nn30"><TT>directorargout</TT> typemap</A></LI> | |
23173 | </UL> | |
23174 | </LI> | |
23175 | <LI><A href="#Ocaml_nn31">Exceptions</A></LI> | |
23176 | </UL> | |
23177 | </LI> | |
23178 | </UL> | |
23179 | </DIV> | |
23180 | <!-- INDEX --> | |
23181 | <P> This chapter describes SWIG's support of Ocaml. Ocaml is a | |
23182 | relatively recent addition to the ML family, and is a recent addition | |
23183 | to SWIG. It's the second compiled, typed language to be added. Ocaml | |
23184 | has widely acknowledged benefits for engineers, mostly derived from a | |
23185 | sophistocated type system, compile-time checking which eliminates | |
23186 | several classes of common programming errors, and good native | |
23187 | performance. While all of this is wonderful, there are well-written C | |
23188 | and C++ libraries that Ocaml users will want to take advantage of as | |
23189 | part of their arsenal (such as SSL and gdbm), as well as their own | |
23190 | mature C and C++ code. SWIG allows this code to be used in a natural, | |
23191 | type-safe way with Ocaml, by providing the necessary, but repetetive | |
23192 | glue code which creates and uses Ocaml values to communicate with C and | |
23193 | C++ code. In addition, SWIG also produces the needed Ocaml source that | |
23194 | binds variants, functions, classes, etc.</P> | |
23195 | <P> If you're not familiar with the Objective Caml language, you can | |
23196 | visit <A href="http://www.ocaml.org/">The Ocaml Website</A>.</P> | |
23197 | <H2><A name="Ocaml_nn2"></A>22.1 Preliminaries</H2> | |
23198 | <P> SWIG 1.3 works with Ocaml 3.04 and above. Given the choice, you | |
23199 | should use the latest stable release. The SWIG Ocaml module has been | |
23200 | tested on Linux (x86,PPC,Sparc) and Cygwin on Windows. The best way to | |
23201 | determine whether your system will work is to compile the examples and | |
23202 | test-suite which come with SWIG. You can do this by running <TT>make | |
23203 | check</TT> from the SWIG root directory after installing SWIG. The | |
23204 | Ocaml module has been tested using the system's dynamic linking (the | |
23205 | usual -lxxx against libxxx.so, as well as with Gerd Stolpmann's <A href="http://www.ocaml-programming.de/packages/documentation/dl/"> | |
23206 | Dl package</A> . The ocaml_dynamic and ocaml_dynamic_cpp targets in the | |
23207 | file Examples/Makefile illustrate how to compile and link SWIG modules | |
23208 | that will be loaded dynamically. This has only been tested on Linux so | |
23209 | far.</P> | |
23210 | <H3><A name="Ocaml_nn3"></A>22.1.1 Running SWIG</H3> | |
23211 | <P> The basics of getting a SWIG Ocaml module up and running can be seen | |
23212 | from one of SWIG's example Makefiles, but is also described here. To | |
23213 | build an Ocaml module, run SWIG using the <TT>-ocaml</TT> option.</P> | |
23214 | <DIV class="code"> | |
23215 | <PRE> | |
23216 | %swig -ocaml example.i | |
23217 | </PRE> | |
23218 | </DIV> | |
23219 | <P> This will produce 3 files. The file <TT>example_wrap.c</TT> contains | |
23220 | all of the C code needed to build an Ocaml module. To build the module, | |
23221 | you will compile the file <TT>example_wrap.c</TT> with <TT>ocamlc</TT> | |
23222 | or <TT>ocamlopt</TT> to create the needed .o file. You will need to | |
23223 | compile the resulting .ml and .mli files as well, and do the final link | |
23224 | with -custom (not needed for native link).</P> | |
23225 | <H3><A name="Ocaml_nn4"></A>22.1.2 Compiling the code</H3> | |
23226 | <P> The O'Caml SWIG module now requires you to compile a module (<TT> | |
23227 | Swig</TT>) separately. In addition to aggregating common SWIG | |
23228 | functionality, the Swig module contains the data structure that | |
23229 | represents C/C++ values. This allows easier data sharing between | |
23230 | modules if two or more are combined, because the type of each SWIG'ed | |
23231 | module's c_obj is derived from Swig.c_obj_t. This also allows SWIG to | |
23232 | acquire new conversions painlessly, as well as giving the user more | |
23233 | freedom with respect to custom typing. Use <TT>ocamlc</TT> or <TT> | |
23234 | ocamlopt</TT> to compile your SWIG interface like:</P> | |
23235 | <DIV class="code"> | |
23236 | <PRE> | |
23237 | % swig -ocaml -co swig.mli ; swig -ocaml co swig.ml | |
23238 | % ocamlc -c swig.mli ; ocamlc -c swig.ml | |
23239 | % ocamlc -c -ccopt "-I/usr/include/foo" example_wrap.c | |
23240 | % ocamlc -c example.mli | |
23241 | % ocamlc -c example.ml | |
23242 | </PRE> | |
23243 | </DIV> | |
23244 | <P> <TT>ocamlc</TT> is aware of .c files and knows how to handle them. | |
23245 | Unfortunately, it does not know about .cxx, .cc, or .cpp files, so when | |
23246 | SWIG is invoked in C++ mode, you must:</P> | |
23247 | <DIV class="code"> | |
23248 | <PRE> | |
23249 | % cp example_wrap.cxx example_wrap.cxx.c | |
23250 | <BR>% ocamlc -c ... -ccopt -xc++ example_wrap.cxx.c | |
23251 | <BR>% ... | |
23252 | <BR> | |
23253 | </PRE> | |
23254 | </DIV> | |
23255 | <H3><A name="Ocaml_nn5"></A>22.1.3 The camlp4 module</H3> | |
23256 | <P> The camlp4 module (swigp4.ml -> swigp4.cmo) contains a simple | |
23257 | rewriter which makes C++ code blend more seamlessly with objective caml | |
23258 | code. It's use is optional, but encouraged. The source file is included | |
23259 | in the Lib/ocaml directory of the SWIG source distribution. You can | |
23260 | checkout this file with <TT>"swig -ocaml -co swigp4.ml"</TT>. You | |
23261 | should compile the file with <TT>"ocamlc -I `camlp4 -where` -pp | |
23262 | 'camlp4o pa_extend.cmo q_MLast.cmo' -c swigp4.ml"</TT></P> | |
23263 | <P> The basic principle of the module is to recognize certain non-caml | |
23264 | expressions and convert them for use with C++ code as interfaced by | |
23265 | SWIG. The camlp4 module is written to work with generated SWIG | |
23266 | interfaces, and probably isn't great to use with anything else.</P> | |
23267 | <P> Here are the main rewriting rules:</P> | |
23268 | <TABLE border="1" summary="Rewriting rules"> | |
23269 | <TR><TH>Input</TH><TH>Rewritten to</TH></TR> | |
23270 | <TR><TD>f'( ... ) as in | |
23271 | <BR> atoi'("0") or | |
23272 | <BR> _exit'(0)</TD><TD>f(C_list [ ... ]) as in | |
23273 | <BR> atoi (C_list [ C_string "0" ]) or | |
23274 | <BR> _exit (C_list [ C_int 0 ])</TD></TR> | |
23275 | <TR><TD>object -> method ( ... )</TD><TD>(invoke object) "method" | |
23276 | (C_list [ ... ])</TD></TR> | |
23277 | <TR><TD> object<I> 'binop</I> argument as in | |
23278 | <BR> a '+= b</TD><TD> (invoke object) "+=" argument as in | |
23279 | <BR> (invoke a) "+=" b</TD><TD></TD></TR> | |
23280 | <TR><TH colspan="2">Note that because camlp4 always recognizes << and | |
23281 | >>, they are replaced by lsl and lsr in operator names.</TH></TR> | |
23282 | <TR><TD><I> 'unop</I> object as in | |
23283 | <BR> '! a</TD><TD> (invoke a) "!" C_void</TD></TR> | |
23284 | <TR><TD><B> Smart pointer access like this</B> | |
23285 | <BR> object '-> method ( args ) | |
23286 | <BR></TD><TD> (invoke (invoke object "->" C_void))</TD></TR> | |
23287 | <TR><TD><B> Invoke syntax</B> | |
23288 | <BR> object . '( ... )</TD><TD> (invoke object) "()" (C_list [ ... ])</TD> | |
23289 | </TR> | |
23290 | <TR><TD><B> Array syntax</B> | |
23291 | <BR> object '[ 10 ]</TD><TD> (invoke object) "[]" (C_int 10)</TD></TR> | |
23292 | <TR><TD><B> Assignment syntax</B> | |
23293 | <BR> let a = '10 and b = '"foo" and c = '1.0 and d = 'true</TD><TD> let | |
23294 | a = C_int 10 and b = C_string "foo" and c = C_double 1.0 and d = C_bool | |
23295 | true</TD></TR> | |
23296 | <TR><TD><B> Cast syntax</B> | |
23297 | <BR> let a = _atoi '("2") as int | |
23298 | <BR> let b = (getenv "PATH") to string | |
23299 | <BR> This works for int, string, float, bool</TD><TD> let a = get_int | |
23300 | (_atoi (C_string "2")) | |
23301 | <BR> let b = C_string (getenv "PATH")</TD></TR> | |
23302 | </TABLE> | |
23303 | <H3><A name="Ocaml_nn6"></A>22.1.4 Using your module</H3> | |
23304 | <P> You can test-drive your module by building a toplevel ocaml | |
23305 | interpreter. Consult the ocaml manual for details.</P> | |
23306 | <P> When linking any ocaml bytecode with your module, use the -custom | |
23307 | option to build your functions into the primitive list. This option is | |
23308 | not needed when you build native code.</P> | |
23309 | <H3><A name="Ocaml_nn7"></A>22.1.5 Compilation problems and compiling | |
23310 | with C++</H3> | |
23311 | <P> As mentioned above, .cxx files need special handling to be compiled | |
23312 | with <TT>ocamlc</TT>. Other than that, C code that uses <TT>class</TT> | |
23313 | as a non-keyword, and C code that is too liberal with pointer types may | |
23314 | not compile under the C++ compiler. Most code meant to be compiled as | |
23315 | C++ will not have problems.</P> | |
23316 | <H2><A name="Ocaml_nn8"></A>22.2 The low-level Ocaml/C interface</H2> | |
23317 | <P> In order to provide access to overloaded functions, and provide | |
23318 | sensible outputs from them, all C entites are represented as members of | |
23319 | the c_obj type:</P> | |
23320 | <P> In the code as seen by the typemap writer, there is a value, | |
23321 | swig_result, that always contains the current return data. It is a | |
23322 | list, and must be appended with the caml_list_append function, or with | |
23323 | functions and macros provided by objective caml. | |
23324 | <BR></P> | |
23325 | <DIV class="code"> | |
23326 | <PRE> | |
23327 | type c_obj = | |
23328 | C_void | |
23329 | | C_bool of bool | |
23330 | | C_char of char | |
23331 | | C_uchar of char | |
23332 | | C_short of int | |
23333 | | C_ushort of int | |
23334 | | C_int of int | |
23335 | | C_uint of int32 | |
23336 | | C_int32 of int32 | |
23337 | | C_int64 of int64 | |
23338 | | C_float of float | |
23339 | | C_double of float | |
23340 | | C_ptr of int64 * int64 | |
23341 | | C_array of c_obj array | |
23342 | | C_list of c_obj list | |
23343 | | C_obj of (string -> c_obj -> c_obj) | |
23344 | | C_string of string | |
23345 | | C_enum of c_enum_t | |
23346 | </PRE> | |
23347 | </DIV> | |
23348 | <P> A few functions exist which generate and return these:</P> | |
23349 | <UL> | |
23350 | <LI>caml_ptr_val receives a c_obj and returns a void *. This should be | |
23351 | used for all pointer purposes.</LI> | |
23352 | <LI>caml_long_val receives a c_obj and returns a long. This should be | |
23353 | used for most integral purposes. | |
23354 | <BR></LI> | |
23355 | <LI>caml_val_ptr receives a void * and returns a c_obj.</LI> | |
23356 | <LI>caml_val_bool receives a C int and returns a c_obj representing it's | |
23357 | bool value.</LI> | |
23358 | <LI>caml_val_(u)?(char|short|int|long|float|double) receives an | |
23359 | appropriate C value and returns a c_obj representing it.</LI> | |
23360 | <LI>caml_val_string receives a char * and returns a string value.</LI> | |
23361 | <LI>caml_val_string_len receives a char * and a length and returns a | |
23362 | string value.</LI> | |
23363 | <LI>caml_val_obj receives a void * and an object type and returns a | |
23364 | C_obj, which contains a closure giving method access.</LI> | |
23365 | </UL> | |
23366 | <P> Because of this style, a typemap can return any kind of value it | |
23367 | wants from a function. This enables out typemaps and inout typemaps to | |
23368 | work well. The one thing to remember about outputting values is that | |
23369 | you must append them to the return list with swig_result = | |
23370 | caml_list_append(swig_result,v).</P> | |
23371 | <P> This function will return a new list that has your element | |
23372 | appended. Upon return to caml space, the fnhelper function beautifies | |
23373 | the result. A list containing a single item degrades to only that item | |
23374 | (i.e. [ C_int 3 ] -> C_int 3), and a list containing more than one item | |
23375 | is wrapped in C_list (i.e. [ C_char 'a' ; C_char 'b' -> C_list [ C_char | |
23376 | 'a' ; C_char b ]). This is in order to make return values easier to | |
23377 | handle when functions have only one return value, such as constructors, | |
23378 | and operators. In addition, string, pointer, and object values are | |
23379 | interchangable with respect to caml_ptr_val, so you can allocate memory | |
23380 | as caml strings and still use the resulting pointers for C purposes, | |
23381 | even using them to construct simple objects on. Note, though, that | |
23382 | foreign C++ code does not respect the garbage collector, although the | |
23383 | SWIG interface does.</P> | |
23384 | <P> The wild card type that you can use in lots of different ways is | |
23385 | C_obj. It allows you to wrap any type of thing you like as an object | |
23386 | using the same mechanism that the ocaml module does. When evaluated in | |
23387 | caml_ptr_val, the returned value is the result of a call to the | |
23388 | object's "&" operator, taken as a pointer.</P> | |
23389 | <P> You should only construct values using objective caml, or using the | |
23390 | functions caml_val_* functions provided as static functions to a SWIG | |
23391 | ocaml module, as well as the caml_list_* functions. These functions | |
23392 | provide everything a typemap needs to produce values. In addition, | |
23393 | value items pass through directly, but you must make your own type | |
23394 | signature for a function that uses value in this way.</P> | |
23395 | <H3><A name="Ocaml_nn9"></A>22.2.1 The generated module</H3> | |
23396 | <P> The SWIG <TT>%module</TT> directive specifies the name of the Ocaml | |
23397 | module to be generated. If you specified `<TT>%module example</TT>', | |
23398 | then your Ocaml code will be accessible in the module Example. The | |
23399 | module name is always capitalized as is the ocaml convention. Note that | |
23400 | you must not use any Ocaml keyword to name your module. Remember that | |
23401 | the keywords are not the same as the C++ ones.</P> | |
23402 | <P> You can introduce extra code into the output wherever you like with | |
23403 | SWIG. These are the places you can introduce code:</P> | |
23404 | <TABLE border="1" summary="Extra code sections"> | |
23405 | <TR><TD>"header"</TD><TD>This code is inserted near the beginning of the | |
23406 | C wrapper file, before any function definitions.</TD></TR> | |
23407 | <TR><TD>"wrapper"</TD><TD>This code is inserted in the function | |
23408 | definition section.</TD></TR> | |
23409 | <TR><TD>"runtime"</TD><TD>This code is inserted near the end of the C | |
23410 | wrapper file.</TD></TR> | |
23411 | <TR><TD>"mli"</TD><TD>This code is inserted into the caml interface | |
23412 | file. Special signatures should be inserted here.</TD></TR> | |
23413 | <TR><TD>"ml"</TD><TD>This code is inserted in the caml code defining the | |
23414 | interface to your C code. Special caml code, as well as any | |
23415 | initialization which should run when the module is loaded may be | |
23416 | inserted here.</TD></TR> | |
23417 | <TR><TD>"classtemplate"</TD><TD>The "classtemplate" place is special | |
23418 | because it describes the output SWIG will generate for class | |
23419 | definitions.</TD></TR> | |
23420 | </TABLE> | |
23421 | <H3><A name="Ocaml_nn10"></A>22.2.2 Enums</H3> | |
23422 | <P> SWIG will wrap enumerations as polymorphic variants in the output | |
23423 | Ocaml code, as above in C_enum. In order to support all C++-style uses | |
23424 | of enums, the function int_to_enum and enum_to_int are provided for | |
23425 | ocaml code to produce and consume these values as integers. Other than | |
23426 | that, correct uses of enums will not have a problem. Since enum labels | |
23427 | may overlap between enums, the enum_to_int and int_to_enum functions | |
23428 | take an enum type label as an argument. Example:</P> | |
23429 | <DIV class="code"> | |
23430 | <PRE> | |
23431 | %module enum_test | |
23432 | %{ | |
23433 | enum c_enum_type { a = 1, b, c = 4, d = 8 }; | |
23434 | %} | |
23435 | enum c_enum_type { a = 1, b, c = 4, d = 8 }; | |
23436 | </PRE> | |
23437 | </DIV> | |
23438 | <P> The output mli contains:</P> | |
23439 | <DIV class="code"> | |
23440 | <PRE> | |
23441 | type c_enum_type = [ | |
23442 | `unknown | |
23443 | | `c_enum_type | |
23444 | ] | |
23445 | type c_enum_tag = [ | |
23446 | `int of int | |
23447 | | `a | |
23448 | | `b | |
23449 | | `c | |
23450 | | `d | |
23451 | ] | |
23452 | val int_to_enum c_enum_type -> int -> c_obj | |
23453 | val enum_to_int c_enum_type -> c_obj -> c_obj | |
23454 | </PRE> | |
23455 | </DIV> | |
23456 | <P> So it's possible to do this:</P> | |
23457 | <DIV class="code"> | |
23458 | <PRE> | |
23459 | bash-2.05a$ ocamlmktop -custom enum_test_wrap.o enum_test.cmo -o enum_test_top | |
23460 | bash-2.05a$ ./enum_test_top | |
23461 | Objective Caml version 3.04 | |
23462 | ||
23463 | # open Enum_test ;; | |
23464 | # let x = C_enum `a ;; | |
23465 | val x : Enum_test.c_obj = C_enum `a | |
23466 | # enum_to_int `c_enum_type x ;; | |
23467 | - : Enum_test.c_obj = C_int 1 | |
23468 | # int_to_enum `c_enum_type 4 ;; | |
23469 | - : Enum_test.c_obj = C_enum `c | |
23470 | </PRE> | |
23471 | </DIV> | |
23472 | <H4><A name="Ocaml_nn11"></A>22.2.2.1 Enum typing in Ocaml</H4> | |
23473 | <P> The ocaml SWIG module now has support for loading and using multiple | |
23474 | SWIG modules at the same time. This enhances modularity, but presents | |
23475 | problems when used with a language which assumes that each module's | |
23476 | types are complete at compile time. In order to achieve total soundness | |
23477 | enum types are now isolated per-module. The type issue matters when | |
23478 | values are shared between functions imported from different modules. | |
23479 | You must convert values to master values using the swig_val function | |
23480 | before sharing them with another module.</P> | |
23481 | <H3><A name="Ocaml_nn12"></A>22.2.3 Arrays</H3> | |
23482 | <H4><A name="Ocaml_nn13"></A>22.2.3.1 Simple types of bounded arrays</H4> | |
23483 | <P> SWIG has support for array types, but you generally will need to | |
23484 | provide a typemap to handle them. You can currently roll your own, or | |
23485 | expand some of the macros provided (but not included by default) with | |
23486 | the SWIG distribution.</P> | |
23487 | <P> By including "carray.i", you will get access to some macros that | |
23488 | help you create typemaps for array types fairly easily.</P> | |
23489 | <P> <TT>%make_simple_array_typemap</TT> is the easiest way to get access | |
23490 | to arrays of simple types with known bounds in your code, but this only | |
23491 | works for arrays whose bounds are completely specified.</P> | |
23492 | <H4><A name="Ocaml_nn14"></A>22.2.3.2 Complex and unbounded arrays</H4> | |
23493 | <P> Unfortunately, unbounded arrays and pointers can't be handled in a | |
23494 | completely general way by SWIG, because the end-condition of such an | |
23495 | array can't be predicted. In some cases, it will be by consent (e.g. an | |
23496 | array of four or more chars), sometimes by explicit length (char | |
23497 | *buffer, int len), and sometimes by sentinel value (0,-1,etc.). SWIG | |
23498 | can't predict which of these methods will be used in the array, so you | |
23499 | have to specify it for yourself in the form of a typemap.</P> | |
23500 | <H4><A name="Ocaml_nn15"></A>22.2.3.3 Using an object</H4> | |
23501 | <P> It's possible to use C++ to your advantage by creating a simple | |
23502 | object that provides access to your array. This may be more desirable | |
23503 | in some cases, since the object can provide bounds checking, etc., that | |
23504 | prevents crashes.</P> | |
23505 | <P> Consider writing an object when the ending condition of your array | |
23506 | is complex, such as using a required centinel, etc.</P> | |
23507 | <H4><A name="Ocaml_nn16"></A>22.2.3.4 Example typemap for a function | |
23508 | taking float * and int</H4> | |
23509 | <P> This is a simple example <TT>in</TT> typemap for an array of float, | |
23510 | where the length of the array is specified as an extra parameter. Other | |
23511 | such typemaps will work similarly. In the example, the function | |
23512 | printfloats is called with a float array, and specified length. The | |
23513 | actual length reported in the len argument is the length of the array | |
23514 | passed from ocaml, making passing an array into this type of function | |
23515 | convenient.</P> | |
23516 | <TABLE bgcolor="#dddddd" border="1" summary="float * and int typemap example"> | |
23517 | <TR><TH> | |
23518 | <CENTER>tarray.i</CENTER> | |
23519 | </TH></TR> | |
23520 | <TR><TD> | |
23521 | <PRE> | |
23522 | %module tarray | |
23523 | %{ | |
23524 | #include <stdio.h> | |
23525 | ||
23526 | void printfloats( float *tab, int len ) { | |
23527 | int i; | |
23528 | ||
23529 | for( i = 0; i < len; i++ ) { | |
23530 | printf( "%f ", tab[i] ); | |
23531 | } | |
23532 | ||
23533 | printf( "\n" ); | |
23534 | } | |
23535 | %} | |
23536 | ||
23537 | %typemap(in) (float *tab, int len) { | |
23538 | int i; | |
23539 | /* $*1_type */ | |
23540 | $2 = caml_array_len($input); | |
23541 | $1 = ($*1_type *)malloc( $2 * sizeof( float ) ); | |
23542 | for( i = 0; i < $2; i++ ) { | |
23543 | $1[i] = caml_double_val(caml_array_nth($input,i)); | |
23544 | } | |
23545 | } | |
23546 | ||
23547 | void printfloats( float *tab, int len ); | |
23548 | </PRE> | |
23549 | </TD></TR> | |
23550 | <TR><TH>Sample Run</TH></TR> | |
23551 | <TR><TD> | |
23552 | <PRE> | |
23553 | # open Tarray ;; | |
23554 | # _printfloats (C_array [| C_double 1.0 ; C_double 3.0 ; C_double 5.6666 |]) ;; | |
23555 | 1.000000 3.000000 5.666600 | |
23556 | - : Tarray.c_obj = C_void | |
23557 | </PRE> | |
23558 | </TD></TR> | |
23559 | </TABLE> | |
23560 | <H3><A name="Ocaml_nn17"></A>22.2.4 C++ Classes</H3> | |
23561 | <P> C++ classes, along with structs and unions are represented by C_obj | |
23562 | (string -> c_obj -> c_obj) wrapped closures. These objects contain a | |
23563 | method list, and a type, which allow them to be used like C++ objects. | |
23564 | When passed into typemaps that use pointers, they degrade to pointers | |
23565 | through their "&" method. Every method an object has is represented as | |
23566 | a string in the object's method table, and each method table exists in | |
23567 | memory only once. In addition to any other operators an object might | |
23568 | have, certain builtin ones are provided by SWIG: (all of these take no | |
23569 | arguments (C_void))</P> | |
23570 | <TABLE summary="SWIG provided operators"> | |
23571 | <TR><TD>"~"</TD><TD>Delete this object</TD></TR> | |
23572 | <TR><TD>"&"</TD><TD>Return an ordinary C_ptr value representing this | |
23573 | object's address</TD></TR> | |
23574 | <TR><TD>"sizeof"</TD><TD>If enabled with ("sizeof"="1") on the module | |
23575 | node, return the object's size in char.</TD></TR> | |
23576 | <TR><TD>":methods"</TD><TD>Returns a list of strings containing the | |
23577 | names of the methods this object contains</TD></TR> | |
23578 | <TR><TD>":classof"</TD><TD>Returns the name of the class this object | |
23579 | belongs to.</TD></TR> | |
23580 | <TR><TD>":parents"</TD><TD>Returns a list of all direct parent classes | |
23581 | which have been wrapped by SWIG.</TD></TR> | |
23582 | <TR><TD>"::[parent-class]"</TD><TD>Returns a view of the object as the | |
23583 | indicated parent class. This is mainly used internally by the SWIG | |
23584 | module, but may be useful to client programs.</TD></TR> | |
23585 | <TR><TD>"[member-variable]"</TD><TD>Each member variable is wrapped as a | |
23586 | method with an optional parameter. Called with one argument, the member | |
23587 | variable is set to the value of the argument. With zero arguments, the | |
23588 | value is returned.</TD></TR> | |
23589 | </TABLE> | |
23590 | <P> Note that this string belongs to the wrapper object, and not the | |
23591 | underlying pointer, so using create_[x]_from_ptr alters the returned | |
23592 | value for the same object.</P> | |
23593 | <H4><A name="Ocaml_nn18"></A>22.2.4.1 STL vector and string Example</H4> | |
23594 | <P> Standard typemaps are now provided for STL vector and string. More | |
23595 | are in the works. STL strings are passed just like normal strings, and | |
23596 | returned as strings. STL string references don't mutate the original | |
23597 | string, (which might be surprising), because Ocaml strings are mutable | |
23598 | but have fixed length. Instead, use multiple returns, as in the | |
23599 | argout_ref example.</P> | |
23600 | <TABLE bgcolor="#dddddd" border="1" summary="STL vector and string example"> | |
23601 | <TR><TH> | |
23602 | <CENTER>example.i</CENTER> | |
23603 | </TH></TR> | |
23604 | <TR><TD> | |
23605 | <PRE> | |
23606 | %module example | |
23607 | %{ | |
23608 | #include "example.h" | |
23609 | %} | |
23610 | ||
23611 | %include stl.i | |
23612 | ||
23613 | namespace std { | |
23614 | %template(StringVector) std::vector < string >; | |
23615 | }; | |
23616 | ||
23617 | %include example.h | |
23618 | </PRE> | |
23619 | </TD></TR> | |
23620 | <TR><TD><FONT size="-1"><I>This example is in Examples/ocaml/stl</I></FONT> | |
23621 | </TD></TR> | |
23622 | </TABLE> | |
23623 | <P> Since there's a makefile in that directory, the example is easy to | |
23624 | build.</P> | |
23625 | <P> Here's a sample transcript of an interactive session using a string | |
23626 | vector after making a toplevel (make toplevel). This example uses the | |
23627 | camlp4 module.</P> | |
23628 | <DIV class="code"> | |
23629 | <PRE> | |
23630 | bash-2.05a$ ./example_top | |
23631 | Objective Caml version 3.06 | |
23632 | ||
23633 | Camlp4 Parsing version 3.06 | |
23634 | ||
23635 | # open Swig ;; | |
23636 | # open Example ;; | |
23637 | # let x = new_StringVector '() ;; | |
23638 | val x : Example.c_obj = C_obj <fun> | |
23639 | # x -> ":methods" () ;; | |
23640 | - : Example.c_obj = | |
23641 | C_list | |
23642 | [C_string "nop"; C_string "size"; C_string "empty"; C_string "clear"; | |
23643 | C_string "push_back"; C_string "[]"; C_string "="; C_string "set"; | |
23644 | C_string "~"; C_string "&"; C_string ":parents"; C_string ":classof"; | |
23645 | C_string ":methods"] | |
23646 | # x -> push_back ("foo") ;; | |
23647 | - : Example.c_obj = C_void | |
23648 | # x -> push_back ("bar") ;; | |
23649 | - : Example.c_obj = C_void | |
23650 | # x -> push_back ("baz") ;; | |
23651 | - : Example.c_obj = C_void | |
23652 | # x '[1] ;; | |
23653 | - : Example.c_obj = C_string "bar" | |
23654 | # x -> set (1,"spam") ;; | |
23655 | - : Example.c_obj = C_void | |
23656 | # x '[1] ;; | |
23657 | - : Example.c_obj = C_string "spam" | |
23658 | # for i = 0 to (x -> size() as int) - 1 do | |
23659 | print_endline ((x '[i to int]) as string) | |
23660 | done ;; | |
23661 | foo | |
23662 | bar | |
23663 | baz | |
23664 | - : unit = () | |
23665 | # | |
23666 | </PRE> | |
23667 | </DIV> | |
23668 | <H4><A name="Ocaml_nn19"></A>22.2.4.2 C++ Class Example</H4> | |
23669 | <P> Here's a simple example using Trolltech's Qt Library:</P> | |
23670 | <TABLE bgcolor="#dddddd" border="1" summary="Qt Library example"> | |
23671 | <TR><TH> | |
23672 | <CENTER>qt.i</CENTER> | |
23673 | </TH></TR> | |
23674 | <TR><TD> | |
23675 | <PRE> | |
23676 | %module qt | |
23677 | %{ | |
23678 | #include <qapplication.h> | |
23679 | #include <qpushbutton.h> | |
23680 | %} | |
23681 | class QApplication { | |
23682 | public: | |
23683 | QApplication( int argc, char **argv ); | |
23684 | void setMainWidget( QWidget *widget ); | |
23685 | void exec(); | |
23686 | }; | |
23687 | ||
23688 | class QPushButton { | |
23689 | public: | |
23690 | QPushButton( char *str, QWidget *w ); | |
23691 | void resize( int x, int y ); | |
23692 | void show(); | |
23693 | }; | |
23694 | </PRE> | |
23695 | </TD></TR> | |
23696 | </TABLE> | |
23697 | <H4><A name="Ocaml_nn20"></A>22.2.4.3 Compiling the example</H4> | |
23698 | <DIV class="code"> | |
23699 | <PRE> | |
23700 | bash-2.05a$ QTPATH=/your/qt/path | |
23701 | bash-2.05a$ for file in swig.mli swig.ml swigp4.ml ; do swig -ocaml -co $file ; done | |
23702 | bash-2.05a$ ocamlc -c swig.mli ; ocamlc -c swig.ml | |
23703 | bash-2.05a$ ocamlc -I `camlp4 -where` -pp "camlp4o pa_extend.cmo q_MLast.cmo" -c swigp4.ml | |
23704 | bash-2.05a$ swig -ocaml -c++ -I$QTPATH/include qt.i | |
23705 | bash-2.05a$ mv qt_wrap.cxx qt_wrap.c | |
23706 | bash-2.05a$ ocamlc -c -ccopt -xc++ -ccopt -g -g -ccopt -I$QTPATH/include qt_wrap.c | |
23707 | bash-2.05a$ ocamlc -c qt.mli | |
23708 | bash-2.05a$ ocamlc -c qt.ml | |
23709 | bash-2.05a$ ocamlmktop -custom swig.cmo -I `camlp4 -where` \ | |
23710 | camlp4o.cma swigp4.cmo qt_wrap.o qt.cmo -o qt_top -cclib \ | |
23711 | -L$QTPATH/lib -cclib -lqt | |
23712 | </PRE> | |
23713 | </DIV> | |
23714 | <H4><A name="Ocaml_nn21"></A>22.2.4.4 Sample Session</H4> | |
23715 | <DIV class="code"> | |
23716 | <PRE> | |
23717 | bash-2.05a$ ./qt_top | |
23718 | Objective Caml version 3.06 | |
23719 | ||
23720 | Camlp4 Parsing version 3.06 | |
23721 | ||
23722 | # open Swig ;; | |
23723 | # open Qt ;; | |
23724 | # let a = new_QApplication '(0,0) ;; | |
23725 | val a : Qt.c_obj = C_obj <fun> | |
23726 | # let hello = new_QPushButton '("hi",0) ;; | |
23727 | val hello : Qt.c_obj = C_obj <fun> | |
23728 | # hello -> resize (100,30) ;; | |
23729 | - : Qt.c_obj = C_void | |
23730 | # hello -> show () ;; | |
23731 | - : Qt.c_obj = C_void | |
23732 | # a -> exec () ;; | |
23733 | </PRE> | |
23734 | </DIV> | |
23735 | <P> Assuming you have a working installation of QT, you will see a | |
23736 | window containing the string "hi" in a button.</P> | |
23737 | <H3><A name="Ocaml_nn22"></A>22.2.5 Director Classes</H3> | |
23738 | <H4><A name="Ocaml_nn23"></A>22.2.5.1 Director Introduction</H4> | |
23739 | <P> Director classes are classes which allow Ocaml code to override the | |
23740 | public methods of a C++ object. This facility allows the user to use | |
23741 | C++ libraries that require a derived class to provide application | |
23742 | specific functionality in the context of an application or utility | |
23743 | framework.</P> | |
23744 | <P> You can turn on director classes by using an optional module | |
23745 | argument like this:</P> | |
23746 | <DIV class="code"> | |
23747 | <PRE> | |
23748 | %module(directors="1") | |
23749 | ||
23750 | ... | |
23751 | ||
23752 | // Turn on the director class for a specific class like this: | |
23753 | %feature("director") | |
23754 | class foo { | |
23755 | ... | |
23756 | }; | |
23757 | </PRE> | |
23758 | </DIV> | |
23759 | <H4><A name="Ocaml_nn24"></A>22.2.5.2 Overriding Methods in Ocaml</H4> | |
23760 | <P> Because the Ocaml language module treats C++ method calls as calls | |
23761 | to a certain function, all you need to do is to define the function | |
23762 | that will handle the method calls in terms of the public methods of the | |
23763 | object, and any other relevant information. The function <TT> | |
23764 | new_derived_object</TT> uses a stub class to call your methods in place | |
23765 | of the ones provided by the underlying implemenation. The object you | |
23766 | receive is the underlying object, so you are free to call any methods | |
23767 | you want from within your derived method. Note that calls to the | |
23768 | underlying object do not invoke Ocaml code. You need to handle that | |
23769 | yourself.</P> | |
23770 | <P> <TT>new_derived_object</TT> receives your function, the function | |
23771 | that creates the underlying object, and any constructor arguments, and | |
23772 | provides an object that you can use in any usual way. When C++ code | |
23773 | calls one of the object's methods, the object invokes the Ocaml | |
23774 | function as if it had been invoked from Ocaml, allowing any method | |
23775 | definitions to override the C++ ones.</P> | |
23776 | <P> In this example, I'll examine the objective caml code involved in | |
23777 | providing an overloaded class. This example is contained in | |
23778 | Examples/ocaml/shapes.</P> | |
23779 | <H4><A name="Ocaml_nn25"></A>22.2.5.3 Director Usage Example</H4> | |
23780 | <TABLE bgcolor="#dddddd" border="1" summary="Director usage example"> | |
23781 | <TR><TH> | |
23782 | <CENTER>example_prog.ml</CENTER> | |
23783 | </TH></TR> | |
23784 | <TR><TD> | |
23785 | <PRE> | |
23786 | open Swig | |
23787 | open Example | |
23788 | ||
23789 | ... | |
23790 | ||
23791 | let triangle_class pts ob meth args = | |
23792 | match meth with | |
23793 | "cover" -> | |
23794 | (match args with | |
23795 | C_list [ x_arg ; y_arg ] -> | |
23796 | let xa = x_arg as float | |
23797 | and ya = y_arg as float in | |
23798 | (point_in_triangle pts xa ya) to bool | |
23799 | | _ -> raise (Failure "cover needs two double arguments.")) | |
23800 | | _ -> (invoke ob) meth args ;; | |
23801 | ||
23802 | let triangle = | |
23803 | new_derived_object | |
23804 | new_shape | |
23805 | (triangle_class ((0.0,0.0),(0.5,1.0),(1.0,0.0))) | |
23806 | '() ;; | |
23807 | ||
23808 | let _ = _draw_shape_coverage '(triangle, C_int 60, C_int 20) ;; | |
23809 | </PRE> | |
23810 | </TD></TR> | |
23811 | </TABLE> | |
23812 | <P> This is the meat of what you need to do. The actual "class" | |
23813 | definition containing the overloaded method is defined in the function | |
23814 | triangle_class. This is a lot like the class definitions emitted by | |
23815 | SWIG, if you look at example.ml, which is generated when SWIG consumes | |
23816 | example.i. Basically, you are given the arguments as a c_obj and the | |
23817 | method name as a string, and you must intercept the method you are | |
23818 | interested in and provide whatever return value you need. Bear in mind | |
23819 | that the underlying C++ code needs the right return type, or an | |
23820 | exception will be thrown. This exception will generally be Failure, or | |
23821 | NotObject. You must call other ocaml methods that you rely on yourself. | |
23822 | Due to the way directors are implemented, method calls on your object | |
23823 | from with ocaml code will always invoke C++ methods even if they are | |
23824 | overridden in ocaml.</P> | |
23825 | <P> In the example, the draw_shape_coverage function plots the indicated | |
23826 | number of points as either covered (<TT>x</TT>) or uncovered ( ) | |
23827 | between 0 and 1 on the X and Y axes. Your shape implementation can | |
23828 | provide any coverage map it likes, as long as it responds to the | |
23829 | "cover" method call with a boolean return (the underlying method | |
23830 | returns bool). This might allow a tricky shape implementation, such as | |
23831 | a boolean combination, to be expressed in a more effortless style in | |
23832 | ocaml, while leaving the "engine" part of the program in C++.</P> | |
23833 | <H4><A name="Ocaml_nn26"></A>22.2.5.4 Creating director objects</H4> | |
23834 | <P> The definition of the actual object triangle can be described this | |
23835 | way:</P> | |
23836 | <DIV class="code"> | |
23837 | <PRE> | |
23838 | let triangle = | |
23839 | new_derived_object | |
23840 | new_shape | |
23841 | (triangle_class ((0.0,0.0),(0.5,1.0),(1.0,0.0))) | |
23842 | '() | |
23843 | </PRE> | |
23844 | </DIV> | |
23845 | <P> The first argument to <TT>new_derived_object</TT>, new_shape is the | |
23846 | method which returns a shape instance. This function will be invoked | |
23847 | with the third argument will be appended to the argument list [ C_void | |
23848 | ]. In the example, the actual argument list is sent as (C_list [ C_void | |
23849 | ; C_void ]). The augmented constructor for a director class needs the | |
23850 | first argument to determine whether it is being constructed as a | |
23851 | derived object, or as an object of the indicated type only (in this | |
23852 | case <TT>shape</TT>). The Second argument is a closure that will be | |
23853 | added to the final C_obj.</P> | |
23854 | <P> The actual object passed to the self parameter of the director | |
23855 | object will be a C_director_core, containing a c_obj option ref and a | |
23856 | c_obj. The c_obj provided is the same object that will be returned from | |
23857 | new_derived object, that is, the object exposing the overridden | |
23858 | methods. The other part is an option ref that will have its value | |
23859 | extracted before becoming the <TT>ob</TT> parameter of your class | |
23860 | closure. This ref will contain <TT>None</TT> if the C++ object | |
23861 | underlying is ever destroyed, and will consequently trigger an | |
23862 | exception when any method is called on the object after that point (the | |
23863 | actual raise is from an inner function used by new_derived_object, and | |
23864 | throws NotObject). This prevents a deleted C++ object from causing a | |
23865 | core dump, as long as the object is destroyed properly.</P> | |
23866 | <H4><A name="Ocaml_nn27"></A>22.2.5.5 Typemaps for directors, <TT> | |
23867 | directorin, directorout, directorargout</TT></H4> | |
23868 | <P> Special typemaps exist for use with directors, the <TT>directorin, | |
23869 | directorout, directorargout</TT> are used in place of <TT>in, out, | |
23870 | argout</TT> typemaps, except that their direction is reversed. They | |
23871 | provide for you to provide argout values, as well as a function return | |
23872 | value in the same way you provide function arguments, and to receive | |
23873 | arguments the same way you normally receive function returns.</P> | |
23874 | <H4><A name="Ocaml_nn28"></A>22.2.5.6 <TT>directorin</TT> typemap</H4> | |
23875 | <P> The <TT>directorin</TT> typemap is used when you will receive | |
23876 | arguments from a call made by C++ code to you, therefore, values will | |
23877 | be translated from C++ to ocaml. You must provide some valid C_obj | |
23878 | value. This is the value your ocaml code receives when you are called. | |
23879 | In general, a simple <TT>directorin</TT> typemap can use the same body | |
23880 | as a simple <TT>out</TT> typemap.</P> | |
23881 | <H4><A name="Ocaml_nn29"></A>22.2.5.7 <TT>directorout</TT> typemap</H4> | |
23882 | <P> The <TT>directorout</TT> typemap is used when you will send an | |
23883 | argument from your code back to the C++ caller. That is; directorout | |
23884 | specifies a function return conversion. You can usually use the same | |
23885 | body as an <TT>in</TT> typemap for the same type, except when there are | |
23886 | special requirements for object ownership, etc.</P> | |
23887 | <H4><A name="Ocaml_nn30"></A>22.2.5.8 <TT>directorargout</TT> typemap</H4> | |
23888 | <P> C++ allows function arguments which are by pointer (*) and by | |
23889 | reference (&) to receive a value from the called function, as well as | |
23890 | sending one there. Sometimes, this is the main purpose of the argument | |
23891 | given. <TT>directorargout</TT> typemaps allow your caml code to emulate | |
23892 | this by specifying additional return values to be put into the output | |
23893 | parameters. The SWIG ocaml module is a bit loose in order to make code | |
23894 | eaiser to write. In this case, your return to the caller must be a list | |
23895 | containing the normal function return first, followed by any argout | |
23896 | values in order. These argout values will be taken from the list and | |
23897 | assigned to the values to be returned to C++ through directorargout | |
23898 | typemaps. In the event that you don't specify all of the necessary | |
23899 | values, integral values will read zero, and struct or object returns | |
23900 | have undefined results.</P> | |
23901 | <H3><A name="Ocaml_nn31"></A>22.2.6 Exceptions</H3> | |
23902 | <P> Catching exceptions is now supported using SWIG's %exception | |
23903 | feature. A simple but not too useful example is provided by the | |
23904 | throw_exception testcase in Examples/test-suite. You can provide your | |
23905 | own exceptions, too.</P> | |
23906 | <HR NOSHADE> | |
23907 | <H1><A name="Perl5"></A>23 SWIG and Perl5</H1> | |
23908 | ||
23909 | <!-- INDEX --> | |
23910 | <DIV class="sectiontoc"> | |
23911 | <UL> | |
23912 | <LI><A href="#Perl5_nn2">Overview</A></LI> | |
23913 | <LI><A href="#Perl5_nn3">Preliminaries</A> | |
23914 | <UL> | |
23915 | <LI><A href="#Perl5_nn4">Getting the right header files</A></LI> | |
23916 | <LI><A href="#Perl5_nn5">Compiling a dynamic module</A></LI> | |
23917 | <LI><A href="#Perl5_nn6">Building a dynamic module with MakeMaker</A></LI> | |
23918 | <LI><A href="#Perl5_nn7">Building a static version of Perl</A></LI> | |
23919 | <LI><A href="#Perl5_nn8">Using the module</A></LI> | |
23920 | <LI><A href="#Perl5_nn9">Compilation problems and compiling with C++</A></LI> | |
23921 | <LI><A href="#Perl5_nn10">Compiling for 64-bit platforms</A></LI> | |
23922 | </UL> | |
23923 | </LI> | |
23924 | <LI><A href="#Perl5_nn11">Building Perl Extensions under Windows</A> | |
23925 | <UL> | |
23926 | <LI><A href="#Perl5_nn12">Running SWIG from Developer Studio</A></LI> | |
23927 | <LI><A href="#Perl5_nn13">Using other compilers</A></LI> | |
23928 | </UL> | |
23929 | </LI> | |
23930 | <LI><A href="#Perl5_nn14">The low-level interface</A> | |
23931 | <UL> | |
23932 | <LI><A href="#Perl5_nn15">Functions</A></LI> | |
23933 | <LI><A href="#Perl5_nn16">Global variables</A></LI> | |
23934 | <LI><A href="#Perl5_nn17">Constants</A></LI> | |
23935 | <LI><A href="#Perl5_nn18">Pointers</A></LI> | |
23936 | <LI><A href="#Perl5_nn19">Structures</A></LI> | |
23937 | <LI><A href="#Perl5_nn20">C++ classes</A></LI> | |
23938 | <LI><A href="#Perl5_nn21">C++ classes and type-checking</A></LI> | |
23939 | <LI><A href="#Perl5_nn22">C++ overloaded functions</A></LI> | |
23940 | <LI><A href="#Perl5_nn23">Operators</A></LI> | |
23941 | <LI><A href="#Perl5_nn24">Modules and packages</A></LI> | |
23942 | </UL> | |
23943 | </LI> | |
23944 | <LI><A href="#Perl5_nn25">Input and output parameters</A></LI> | |
23945 | <LI><A href="#Perl5_nn26">Exception handling</A></LI> | |
23946 | <LI><A href="#Perl5_nn27">Remapping datatypes with typemaps</A> | |
23947 | <UL> | |
23948 | <LI><A href="#Perl5_nn28">A simple typemap example</A></LI> | |
23949 | <LI><A href="#Perl5_nn29">Perl5 typemaps</A></LI> | |
23950 | <LI><A href="#Perl5_nn30">Typemap variables</A></LI> | |
23951 | <LI><A href="#Perl5_nn31">Useful functions</A></LI> | |
23952 | </UL> | |
23953 | </LI> | |
23954 | <LI><A href="#Perl5_nn32">Typemap Examples</A> | |
23955 | <UL> | |
23956 | <LI><A href="#Perl5_nn33">Converting a Perl5 array to a char **</A></LI> | |
23957 | <LI><A href="#Perl5_nn34">Return values</A></LI> | |
23958 | <LI><A href="#Perl5_nn35">Returning values from arguments</A></LI> | |
23959 | <LI><A href="#Perl5_nn36">Accessing array structure members</A></LI> | |
23960 | <LI><A href="#Perl5_nn37">Turning Perl references into C pointers</A></LI> | |
23961 | <LI><A href="#Perl5_nn38">Pointer handling</A></LI> | |
23962 | </UL> | |
23963 | </LI> | |
23964 | <LI><A href="#Perl5_nn39">Proxy classes</A> | |
23965 | <UL> | |
23966 | <LI><A href="#Perl5_nn40">Preliminaries</A></LI> | |
23967 | <LI><A href="#Perl5_nn41">Structure and class wrappers</A></LI> | |
23968 | <LI><A href="#Perl5_nn42">Object Ownership</A></LI> | |
23969 | <LI><A href="#Perl5_nn43">Nested Objects</A></LI> | |
23970 | <LI><A href="#Perl5_nn44">Proxy Functions</A></LI> | |
23971 | <LI><A href="#Perl5_nn45">Inheritance</A></LI> | |
23972 | <LI><A href="#Perl5_nn46">Modifying the proxy methods</A></LI> | |
23973 | </UL> | |
23974 | </LI> | |
23975 | </UL> | |
23976 | </DIV> | |
23977 | <!-- INDEX --> | |
23978 | <P><B> Caution: This chapter is under repair!</B></P> | |
23979 | <P> This chapter describes SWIG's support of Perl5. Although the Perl5 | |
23980 | module is one of the earliest SWIG modules, it has continued to evolve | |
23981 | and has been improved greatly with the help of SWIG users. For the best | |
23982 | results, it is recommended that SWIG be used with Perl5.003 or later. | |
23983 | Earlier versions are problematic and SWIG generated extensions may not | |
23984 | compile or run correctly.</P> | |
23985 | <H2><A name="Perl5_nn2"></A>23.1 Overview</H2> | |
23986 | <P> To build Perl extension modules, SWIG uses a layered approach. At | |
23987 | the lowest level, simple procedural wrappers are generated for | |
23988 | functions, classes, methods, and other declarations in the input file. | |
23989 | Then, for structures and classes, an optional collection of Perl proxy | |
23990 | classes can be generated in order to provide a more natural object | |
23991 | oriented Perl interface. These proxy classes simply build upon the | |
23992 | low-level interface.</P> | |
23993 | <P> In describing the Perl interface, this chapter begins by covering | |
23994 | the essentials. First, the problem of configuration, compiling, and | |
23995 | installing Perl modules is discussed. Next, the low-level procedural | |
23996 | interface is presented. Finally, proxy classes are described. Advanced | |
23997 | customization features, typemaps, and other options are found near the | |
23998 | end of the chapter.</P> | |
23999 | <H2><A name="Perl5_nn3"></A>23.2 Preliminaries</H2> | |
24000 | <P> To build a Perl5 module, run Swig using the <TT>-perl</TT> option as | |
24001 | follows :</P> | |
24002 | <DIV class="code"> | |
24003 | <PRE> | |
24004 | swig -perl example.i | |
24005 | ||
24006 | </PRE> | |
24007 | </DIV> | |
24008 | <P> This produces two files. The first file, <TT>example_wrap.c</TT> | |
24009 | contains all of the C code needed to build a Perl5 module. The second | |
24010 | file, <TT>example.pm</TT> contains supporting Perl code needed to | |
24011 | properly load the module.</P> | |
24012 | <P> To build the module, you will need to compile the file <TT> | |
24013 | example_wrap.c</TT> and link it with the rest of your program.</P> | |
24014 | <H3><A name="Perl5_nn4"></A>23.2.1 Getting the right header files</H3> | |
24015 | <P> In order to compile, SWIG extensions need the following Perl5 header | |
24016 | files :</P> | |
24017 | <DIV class="code"> | |
24018 | <PRE> | |
24019 | #include "Extern.h" | |
24020 | #include "perl.h" | |
24021 | #include "XSUB.h" | |
24022 | </PRE> | |
24023 | </DIV> | |
24024 | <P> These are typically located in a directory like this</P> | |
24025 | <DIV class="code"> | |
24026 | <PRE> | |
24027 | /usr/lib/perl5/5.00503/i386-linux/CORE | |
24028 | </PRE> | |
24029 | </DIV> | |
24030 | <P> The SWIG configuration script automatically tries to locate this | |
24031 | directory so that it can compile examples. However, if you need to find | |
24032 | out where the directory is loaded, an easy way to find out is to run | |
24033 | Perl itself.</P> | |
24034 | <DIV class="code"> | |
24035 | <PRE> | |
24036 | % perl -e 'use Config; print $Config{archlib};' | |
24037 | /usr/lib/perl5/5.00503/i386-linux | |
24038 | </PRE> | |
24039 | </DIV> | |
24040 | <H3><A name="Perl5_nn5"></A>23.2.2 Compiling a dynamic module</H3> | |
24041 | <P> The preferred approach to building an extension module is to compile | |
24042 | it into a shared object file or DLL. To do this, you will need to | |
24043 | compile your program using comands like this (shown for Linux):</P> | |
24044 | <DIV class="code"> | |
24045 | <PRE> | |
24046 | $ swig -perl example.i | |
24047 | % gcc example.c | |
24048 | % gcc -c example_wrap.c -I/usr/lib/perl5/5.00503/i386-linux/CORE -Dbool=char | |
24049 | % gcc -shared example.o example_wrap.o -o example.so | |
24050 | </PRE> | |
24051 | </DIV> | |
24052 | <P> The exact compiler options vary from platform to platform. SWIG | |
24053 | tries to guess the right options when it is installed. Therefore, you | |
24054 | may want to start with one of the examples in the <TT> | |
24055 | SWIG/Examples/perl5</TT> directory. If that doesn't work, you will need | |
24056 | to read the man-pages for your compiler and linker to get the right set | |
24057 | of options. You might also check the <A href="http://swig.cs.uchicago.edu/cgi-bin/wiki.pl"> | |
24058 | SWIG Wiki</A> for additional information.</P> | |
24059 | <P> When linking the module, the name of the shared object file must | |
24060 | match the module name used in the SWIG interface file. If you used `<TT> | |
24061 | %module example</TT>', then the target should be named `<TT>example.so</TT> | |
24062 | ', `<TT>example.sl</TT>', or the appropriate dynamic module name on your | |
24063 | system.</P> | |
24064 | <H3><A name="Perl5_nn6"></A>23.2.3 Building a dynamic module with | |
24065 | MakeMaker</H3> | |
24066 | <P> It is also possible to use Perl to build dynamically loadable | |
24067 | modules for you using the MakeMaker utility. To do this, write a Perl | |
24068 | script such as the following :</P> | |
24069 | <DIV class="code"> | |
24070 | <PRE> | |
24071 | # File : Makefile.PL | |
24072 | use ExtUtils::MakeMaker; | |
24073 | WriteMakefile( | |
24074 | `NAME' => `example', # Name of package | |
24075 | `LIBS' => [`-lm'], # Name of custom libraries | |
24076 | `OBJECT' => `example.o example_wrap.o' # Object files | |
24077 | ); | |
24078 | ||
24079 | </PRE> | |
24080 | </DIV> | |
24081 | <P> Now, to build a module, simply follow these steps :</P> | |
24082 | <DIV class="code"> | |
24083 | <PRE> | |
24084 | % perl Makefile.PL | |
24085 | % make | |
24086 | % make install | |
24087 | </PRE> | |
24088 | </DIV> | |
24089 | <P> If you are planning to distribute a SWIG-generated module, this is | |
24090 | the preferred approach to compilation. More information about MakeMaker | |
24091 | can be found in "Programming Perl, 2nd ed." by Larry Wall, Tom | |
24092 | Christiansen, and Randal Schwartz.</P> | |
24093 | <H3><A name="Perl5_nn7"></A>23.2.4 Building a static version of Perl</H3> | |
24094 | <P> If you machine does not support dynamic loading or if you've tried | |
24095 | to use it without success, you can build a new version of the Perl | |
24096 | interpreter with your SWIG extensions added to it. To build a static | |
24097 | extension, you first need to invoke SWIG as follows :</P> | |
24098 | <DIV class="code"> | |
24099 | <PRE> | |
24100 | % swig -perl -static example.i | |
24101 | </PRE> | |
24102 | </DIV> | |
24103 | <P> By default SWIG includes code for dynamic loading, but the <TT> | |
24104 | -static</TT> option takes it out.</P> | |
24105 | <P> Next, you will need to supply a <TT>main()</TT> function that | |
24106 | initializes your extension and starts the Perl interpreter. While, this | |
24107 | may sound daunting, SWIG can do this for you automatically as follows :</P> | |
24108 | <DIV class="code"> | |
24109 | <PRE> | |
24110 | %module example | |
24111 | ||
24112 | %inline %{ | |
24113 | extern double My_variable; | |
24114 | extern int fact(int); | |
24115 | %} | |
24116 | ||
24117 | // Include code for rebuilding Perl | |
24118 | %include perlmain.i | |
24119 | </PRE> | |
24120 | </DIV> | |
24121 | <P> The same thing can be accomplished by running SWIG as follows :</P> | |
24122 | <DIV class="code"> | |
24123 | <PRE> | |
24124 | % swig -perl -static -lperlmain.i example.i | |
24125 | </PRE> | |
24126 | </DIV> | |
24127 | <P> The <TT>permain.i</TT> file inserts Perl's <TT>main()</TT> function | |
24128 | into the wrapper code and automatically initializes the SWIG generated | |
24129 | module. If you just want to make a quick a dirty module, this may be | |
24130 | the easiest way. By default, the <TT>perlmain.i</TT> code does not | |
24131 | initialize any other Perl extensions. If you need to use other | |
24132 | packages, you will need to modify it appropriately. You can do this by | |
24133 | just copying <TT>perlmain.i</TT> out of the SWIG library, placing it in | |
24134 | your own directory, and modifying it to suit your purposes.</P> | |
24135 | <P> To build your new Perl executable, follow the exact same procedure | |
24136 | as for a dynamic module, but change the link line to something like | |
24137 | this:</P> | |
24138 | <DIV class="code"> | |
24139 | <PRE> | |
24140 | % gcc example.o example_wrap.o -L/usr/lib/perl5/5.00503/i386-linux/CORE \ | |
24141 | -lperl -lsocket -lnsl -lm -o myperl | |
24142 | </PRE> | |
24143 | </DIV> | |
24144 | <P> This will produce a new version of Perl called <TT>myperl</TT>. It | |
24145 | should be functionality identical to Perl with your C/C++ extension | |
24146 | added to it. Depending on your machine, you may need to link with | |
24147 | additional libraries such as <TT>-lsocket, -lnsl, -ldl</TT>, etc.</P> | |
24148 | <H3><A name="Perl5_nn8"></A>23.2.5 Using the module</H3> | |
24149 | <P> To use the module, simply use the Perl <TT>use</TT> statement. If | |
24150 | all goes well, you will be able to do this:</P> | |
24151 | <DIV class="code"> | |
24152 | <PRE> | |
24153 | $ perl | |
24154 | use example; | |
24155 | print example::fact(4),"\n"; | |
24156 | 24 | |
24157 | </PRE> | |
24158 | </DIV> | |
24159 | <P> A common error received by first-time users is the following:</P> | |
24160 | <DIV class="code"> | |
24161 | <PRE> | |
24162 | use example; | |
24163 | Can't locate example.pm in @INC (@INC contains: /usr/lib/perl5/5.00503/i386-lin | |
24164 | ux /usr/lib/perl5/5.00503 /usr/lib/perl5/site_perl/5.005/i386-linux /usr/lib/pe | |
24165 | rl5/site_perl/5.005 .) at - line 1. | |
24166 | BEGIN failed--compilation aborted at - line 1. | |
24167 | </PRE> | |
24168 | </DIV> | |
24169 | <P> This error is almost caused when the name of the shared object file | |
24170 | you created doesn't match the module name you specified with the <TT> | |
24171 | %module</TT> directive.</P> | |
24172 | <P> A somewhat related, but slightly different error is this:</P> | |
24173 | <DIV class="code"> | |
24174 | <PRE> | |
24175 | use example; | |
24176 | Can't find 'boot_example' symbol in ./example.so | |
24177 | at - line 1 | |
24178 | BEGIN failed--compilation aborted at - line 1. | |
24179 | </PRE> | |
24180 | </DIV> | |
24181 | <P> This error is generated because Perl can't locate the module | |
24182 | bootstrap function in the SWIG extension module. This could be caused | |
24183 | by a mismatch between the module name and the shared library name. | |
24184 | However, another possible cause is forgetting to link the | |
24185 | SWIG-generated wrapper code with the rest of your application when you | |
24186 | linked the extension module.</P> | |
24187 | <P> Another common error is the following:</P> | |
24188 | <DIV class="code"> | |
24189 | <PRE> | |
24190 | use example; | |
24191 | Can't load './example.so' for module example: ./example.so: | |
24192 | undefined symbol: Foo at /usr/lib/perl5/5.00503/i386-linux/DynaLoader.pm line 169. | |
24193 | ||
24194 | at - line 1 | |
24195 | BEGIN failed--compilation aborted at - line 1. | |
24196 | </PRE> | |
24197 | </DIV> | |
24198 | <P> This error usually indicates that you forgot to include some object | |
24199 | files or libraries in the linking of the shared library file. Make sure | |
24200 | you compile both the SWIG wrapper file and your original program into a | |
24201 | shared library file. Make sure you pass all of the required libraries | |
24202 | to the linker.</P> | |
24203 | <P> Sometimes unresolved symbols occur because a wrapper has been | |
24204 | created for a function that doesn't actually exist in a library. This | |
24205 | usually occurs when a header file includes a declaration for a function | |
24206 | that was never actually implemented or it was removed from a library | |
24207 | without updating the header file. To fix this, you can either edit the | |
24208 | SWIG input file to remove the offending declaration or you can use the <TT> | |
24209 | %ignore</TT> directive to ignore the declaration. Better yet, update the | |
24210 | header file so that it doesn't have an undefined declaration.</P> | |
24211 | <P> Finally, suppose that your extension module is linked with another | |
24212 | library like this:</P> | |
24213 | <DIV class="code"> | |
24214 | <PRE> | |
24215 | $ gcc -shared example.o example_wrap.o -L/home/beazley/projects/lib -lfoo \ | |
24216 | -o example.so | |
24217 | </PRE> | |
24218 | </DIV> | |
24219 | <P> If the <TT>foo</TT> library is compiled as a shared library, you | |
24220 | might get the following error when you try to use your module:</P> | |
24221 | <DIV class="code"> | |
24222 | <PRE> | |
24223 | use example; | |
24224 | Can't load './example.so' for module example: libfoo.so: cannot open shared object file: | |
24225 | No such file or directory at /usr/lib/perl5/5.00503/i386-linux/DynaLoader.pm line 169. | |
24226 | ||
24227 | at - line 1 | |
24228 | BEGIN failed--compilation aborted at - line 1. | |
24229 | >>> | |
24230 | </PRE> | |
24231 | </DIV> | |
24232 | <P> This error is generated because the dynamic linker can't locate the <TT> | |
24233 | libfoo.so</TT> library. When shared libraries are loaded, the system | |
24234 | normally only checks a few standard locations such as <TT>/usr/lib</TT> | |
24235 | and <TT>/usr/local/lib</TT>. To get the loader to look in other | |
24236 | locations, there are several things you can do. First, you can | |
24237 | recompile your extension module with extra path information. For | |
24238 | example, on Linux you can do this:</P> | |
24239 | <DIV class="code"> | |
24240 | <PRE> | |
24241 | $ gcc -shared example.o example_wrap.o -L/home/beazley/projects/lib -lfoo \ | |
24242 | <B>-Xlinker -rpath /home/beazley/projects/lib \</B> | |
24243 | -o example.so | |
24244 | </PRE> | |
24245 | </DIV> | |
24246 | <P> Alternatively, you can set the <TT>LD_LIBRARY_PATH</TT> environment | |
24247 | variable to include the directory with your shared libraries. If | |
24248 | setting <TT>LD_LIBRARY_PATH</TT>, be aware that setting this variable | |
24249 | can introduce a noticeable performance impact on all other applications | |
24250 | that you run. To set it only for Perl, you might want to do this | |
24251 | instead:</P> | |
24252 | <DIV class="code"> | |
24253 | <PRE> | |
24254 | $ env LD_LIBRARY_PATH=/home/beazley/projects/lib perl | |
24255 | </PRE> | |
24256 | </DIV> | |
24257 | <P> Finally, you can use a command such as <TT>ldconfig</TT> (Linux) or <TT> | |
24258 | crle</TT> (Solaris) to add additional search paths to the default system | |
24259 | configuration (this requires root access and you will need to read the | |
24260 | man pages).</P> | |
24261 | <H3><A name="Perl5_nn9"></A>23.2.6 Compilation problems and compiling | |
24262 | with C++</H3> | |
24263 | <P> Compilation of C++ extensions has traditionally been a tricky | |
24264 | problem. Since the Perl interpreter is written in C, you need to take | |
24265 | steps to make sure C++ is properly initialized and that modules are | |
24266 | compiled correctly.</P> | |
24267 | <P> On most machines, C++ extension modules should be linked using the | |
24268 | C++ compiler. For example:</P> | |
24269 | <DIV class="code"> | |
24270 | <PRE> | |
24271 | % swig -c++ -perl example.i | |
24272 | % g++ -c example.cxx | |
24273 | % g++ -c example_wrap.cxx -I/usr/lib/perl5/5.00503/i386-linux/CORE | |
24274 | % <B>g++ -shared example.o example_wrap.o -o example.so</B> | |
24275 | </PRE> | |
24276 | </DIV> | |
24277 | <P> In addition to this, you may need to include additional library | |
24278 | files to make it work. For example, if you are using the Sun C++ | |
24279 | compiler on Solaris, you often need to add an extra library <TT>-lCrun</TT> | |
24280 | like this:</P> | |
24281 | <DIV class="code"> | |
24282 | <PRE> | |
24283 | % swig -c++ -perl example.i | |
24284 | % g++ -c example.cxx | |
24285 | % g++ -c example_wrap.cxx -I/usr/lib/perl5/5.00503/i386-linux/CORE | |
24286 | % g++ -shared example.o example_wrap.o -o example.so <B>-lCrun</B> | |
24287 | </PRE> | |
24288 | </DIV> | |
24289 | <P> Of course, the names of the extra libraries are completely | |
24290 | non-portable---you will probably need to do some experimentation.</P> | |
24291 | <P> Another possible compile problem comes from recent versions of Perl | |
24292 | (5.8.0) and the GNU tools. If you see errors having to do with | |
24293 | _crypt_struct, that means _GNU_SOURCE is not defined and it needs to | |
24294 | be. So you should compile the wrapper like:</P> | |
24295 | <DIV class="code"> | |
24296 | <PRE> | |
24297 | % g++ -c example_wrap.cxx -I/usr/lib/perl/5.8.0/CORE -D_GNU_SOURCE | |
24298 | </PRE> | |
24299 | </DIV> | |
24300 | <P> -D_GNU_SOURCE is also included in the Perl ccflags, which can be | |
24301 | found by running</P> | |
24302 | <DIV class="code"> | |
24303 | <PRE> | |
24304 | % perl -e 'use Config; print $Config{ccflags};' | |
24305 | </PRE> | |
24306 | </DIV> | |
24307 | <P> So you could also compile the wrapper like</P> | |
24308 | <DIV class="code"> | |
24309 | <PRE> | |
24310 | % g++ -c example_wrap.cxx -I/usr/lib/perl/5.8.0/CORE \ | |
24311 | `perl -e 'use Config; print $Config{ccflags}'` | |
24312 | </PRE> | |
24313 | </DIV> | |
24314 | <P> Sometimes people have suggested that it is necessary to relink the | |
24315 | Perl interpreter using the C++ compiler to make C++ extension modules | |
24316 | work. In the experience of this author, this has never actually | |
24317 | appeared to be necessary on most platforms. Relinking the interpreter | |
24318 | with C++ really only includes the special run-time libraries described | |
24319 | above---as long as you link your extension modules with these | |
24320 | libraries, it should not be necessary to rebuild Perl.</P> | |
24321 | <P> If you aren't entirely sure about the linking of a C++ extension, | |
24322 | you might look at an existing C++ program. On many Unix machines, the <TT> | |
24323 | ldd</TT> command will list library dependencies. This should give you | |
24324 | some clues about what you might have to include when you link your | |
24325 | extension module. For example, notice the first line of output here:</P> | |
24326 | <DIV class="code"> | |
24327 | <PRE> | |
24328 | $ ldd swig | |
24329 | <B>libstdc++-libc6.1-1.so.2 => /usr/lib/libstdc++-libc6.1-1.so.2 (0x40019000)</B> | |
24330 | libm.so.6 => /lib/libm.so.6 (0x4005b000) | |
24331 | libc.so.6 => /lib/libc.so.6 (0x40077000) | |
24332 | /lib/ld-linux.so.2 => /lib/ld-linux.so.2 (0x40000000) | |
24333 | $ | |
24334 | </PRE> | |
24335 | </DIV> | |
24336 | <P> If linking wasn't enough of a problem, another major complication of | |
24337 | C++ is that it does not define any sort of standard for binary linking | |
24338 | of libraries. This means that C++ code compiled by different compilers | |
24339 | will not link together properly as libraries nor is the memory layout | |
24340 | of classes and data structures implemented in any kind of portable | |
24341 | manner. In a monolithic C++ program, this problem may be unnoticed. | |
24342 | However, in Perl, it is possible for different extension modules to be | |
24343 | compiled with different C++ compilers. As long as these modules are | |
24344 | self-contained, this probably won't matter. However, if these modules | |
24345 | start sharing data, you will need to take steps to avoid segmentation | |
24346 | faults and other erratic program behavior. Also, be aware that certain | |
24347 | C++ features, especially RTTI, can behave strangely when working with | |
24348 | multiple modules.</P> | |
24349 | <P> It should be noted that you may get alot of error messages about the | |
24350 | `<TT>bool</TT>' datatype when compiling a C++ Perl module. If you | |
24351 | experience this problem, you can try the following :</P> | |
24352 | <UL> | |
24353 | <LI>Use <TT>-DHAS_BOOL</TT> when compiling the SWIG wrapper code</LI> | |
24354 | <LI>Or use <TT>-Dbool=char</TT> when compiling.</LI> | |
24355 | </UL> | |
24356 | <P> Finally, recent versions of Perl (5.8.0) have namespace conflict | |
24357 | problems. Perl defines a bunch of short macros to make the Perl API | |
24358 | function names shorter. For example, in | |
24359 | /usr/lib/perl/5.8.0/CORE/embed.h there is a line:</P> | |
24360 | <DIV class="code"> | |
24361 | <PRE> | |
24362 | #define do_open Perl_do_open | |
24363 | </PRE> | |
24364 | </DIV> | |
24365 | <P> The problem is, in the <iostream> header from GNU libstdc++v3 there | |
24366 | is a private function named do_open. If <iostream> is included after | |
24367 | the perl headers, then the Perl macro causes the iostream do_open to be | |
24368 | renamed, which causes compile errors. Hopefully in the future Perl will | |
24369 | support a PERL_NO_SHORT_NAMES flag, but for now the only solution is to | |
24370 | undef the macros that conflict. Lib/perl5/noembed.h in the SWIG source | |
24371 | has a list of macros that are known to conflict with either standard | |
24372 | headers or other headers. But if you get macro type conflicts from | |
24373 | other macros not included in Lib/perl5/noembed.h while compiling the | |
24374 | wrapper, you will have to find the macro that conflicts and add an | |
24375 | #undef into the .i file. Please report any conflicting macros you find | |
24376 | to <A href="http://www.swig.org/mail.html">swig mailing list</A>.</P> | |
24377 | <H3><A name="Perl5_nn10"></A>23.2.7 Compiling for 64-bit platforms</H3> | |
24378 | <P> On platforms that support 64-bit applications (Solaris, Irix, etc.), | |
24379 | special care is required when building extension modules. On these | |
24380 | machines, 64-bit applications are compiled and linked using a different | |
24381 | set of compiler/linker options. In addition, it is not generally | |
24382 | possible to mix 32-bit and 64-bit code together in the same | |
24383 | application.</P> | |
24384 | <P> To utilize 64-bits, the Perl executable will need to be recompiled | |
24385 | as a 64-bit application. In addition, all libraries, wrapper code, and | |
24386 | every other part of your application will need to be compiled for | |
24387 | 64-bits. If you plan to use other third-party extension modules, they | |
24388 | will also have to be recompiled as 64-bit extensions.</P> | |
24389 | <P> If you are wrapping commercial software for which you have no source | |
24390 | code, you will be forced to use the same linking standard as used by | |
24391 | that software. This may prevent the use of 64-bit extensions. It may | |
24392 | also introduce problems on platforms that support more than one linking | |
24393 | standard (e.g., -o32 and -n32 on Irix).</P> | |
24394 | <H2><A name="Perl5_nn11"></A>23.3 Building Perl Extensions under Windows</H2> | |
24395 | <P> Building a SWIG extension to Perl under Windows is roughly similar | |
24396 | to the process used with Unix. Normally, you will want to produce a DLL | |
24397 | that can be loaded into the Perl interpreter. This section assumes you | |
24398 | are using SWIG with Microsoft Visual C++ although the procedure may be | |
24399 | similar with other compilers.</P> | |
24400 | <H3><A name="Perl5_nn12"></A>23.3.1 Running SWIG from Developer Studio</H3> | |
24401 | <P> If you are developing your application within Microsoft developer | |
24402 | studio, SWIG can be invoked as a custom build option. The process | |
24403 | roughly requires these steps :</P> | |
24404 | <UL> | |
24405 | <LI>Open up a new workspace and use the AppWizard to select a DLL | |
24406 | project.</LI> | |
24407 | <LI>Add both the SWIG interface file (the .i file), any supporting C | |
24408 | files, and the name of the wrapper file that will be created by SWIG | |
24409 | (ie. <TT>example_wrap.c</TT>). Note : If using C++, choose a different | |
24410 | suffix for the wrapper file such as <TT>example_wrap.cxx</TT>. Don't | |
24411 | worry if the wrapper file doesn't exist yet--Developer studio will keep | |
24412 | a reference to it around.</LI> | |
24413 | <LI>Select the SWIG interface file and go to the settings menu. Under | |
24414 | settings, select the "Custom Build" option.</LI> | |
24415 | <LI>Enter "SWIG" in the description field.</LI> | |
24416 | <LI>Enter "<TT>swig -perl5 -o $(ProjDir)\$(InputName)_wrap.cxx | |
24417 | $(InputPath)</TT>" in the "Build command(s) field"</LI> | |
24418 | <LI>Enter "<TT>$(ProjDir)\$(InputName)_wrap.c</TT>xx" in the "Output | |
24419 | files(s) field".</LI> | |
24420 | <LI>Next, select the settings for the entire project and go to | |
24421 | "C++:Preprocessor". Add the include directories for your Perl 5 | |
24422 | installation under "Additional include directories".</LI> | |
24423 | <LI>Define the symbols WIN32 and MSWIN32 under preprocessor options. If | |
24424 | using the ActiveWare port, also define the symbol PERL_OBJECT. Note | |
24425 | that all extensions to the ActiveWare port must be compiled with the | |
24426 | C++ compiler since Perl has been encapsulated in a C++ class.</LI> | |
24427 | <LI>Finally, select the settings for the entire project and go to "Link | |
24428 | Options". Add the Perl library file to your link libraries. For example | |
24429 | "perl.lib". Also, set the name of the output file to match the name of | |
24430 | your Perl module (ie. example.dll).</LI> | |
24431 | <LI>Build your project.</LI> | |
24432 | </UL> | |
24433 | <P> Now, assuming you made it this far, SWIG will be automatically | |
24434 | invoked when you build your project. Any changes made to the interface | |
24435 | file will result in SWIG being automatically invoked to produce a new | |
24436 | version of the wrapper file. To run your new Perl extension, simply run | |
24437 | Perl and use the use command as normal. For example :</P> | |
24438 | <DIV class="code"> | |
24439 | <PRE> | |
24440 | DOS > perl | |
24441 | use example; | |
24442 | $a = example::fact(4); | |
24443 | print "$a\n"; | |
24444 | ||
24445 | </PRE> | |
24446 | </DIV> | |
24447 | <H3><A name="Perl5_nn13"></A>23.3.2 Using other compilers</H3> | |
24448 | <P> SWIG is known to work with Cygwin and may work with other compilers | |
24449 | on Windows. For general hints and suggestions refer to the <A href="#Windows"> | |
24450 | Windows</A> chapter.</P> | |
24451 | <H2><A name="Perl5_nn14"></A>23.4 The low-level interface</H2> | |
24452 | <P> At its core, the Perl module uses a simple low-level interface to C | |
24453 | function, variables, constants, and classes. This low-level interface | |
24454 | can be used to control your application. However, it is also used to | |
24455 | construct more user-friendly proxy classes as described in the next | |
24456 | section.</P> | |
24457 | <H3><A name="Perl5_nn15"></A>23.4.1 Functions</H3> | |
24458 | <P> C functions are converted into new Perl built-in commands (or | |
24459 | subroutines). For example:</P> | |
24460 | <DIV class="code"> | |
24461 | <PRE> | |
24462 | %module example | |
24463 | int fact(int a); | |
24464 | ... | |
24465 | </PRE> | |
24466 | </DIV> | |
24467 | <P> Now, in Perl:</P> | |
24468 | <DIV class="code"> | |
24469 | <PRE> | |
24470 | use example; | |
24471 | $a = &example::fact(2); | |
24472 | </PRE> | |
24473 | </DIV> | |
24474 | <H3><A name="Perl5_nn16"></A>23.4.2 Global variables</H3> | |
24475 | <P> Global variables are handled using Perl's magic variable mechanism. | |
24476 | SWIG generates a pair of functions that intercept read/write operations | |
24477 | and attaches them to a Perl variable with the same name as the C global | |
24478 | variable. Thus, an interface like this</P> | |
24479 | <DIV class="code"> | |
24480 | <PRE> | |
24481 | %module example; | |
24482 | ... | |
24483 | double Spam; | |
24484 | ... | |
24485 | </PRE> | |
24486 | </DIV> | |
24487 | <P> is accessed as follows :</P> | |
24488 | <DIV class="code"> | |
24489 | <PRE> | |
24490 | use example; | |
24491 | print $example::Spam,"\n"; | |
24492 | $example::Spam = $example::Spam + 4 | |
24493 | # ... etc ... | |
24494 | ||
24495 | </PRE> | |
24496 | </DIV> | |
24497 | <P> If a variable is declared as <TT>const</TT>, it is wrapped as a | |
24498 | read-only variable. Attempts to modify its value will result in an | |
24499 | error.</P> | |
24500 | <P> To make ordinary variables read-only, you can also use the <TT> | |
24501 | %immutable</TT> directive. For example:</P> | |
24502 | <DIV class="code"> | |
24503 | <PRE> | |
24504 | %{ | |
24505 | extern char *path; | |
24506 | %} | |
24507 | %immutable; | |
24508 | extern char *path; | |
24509 | %mutable; | |
24510 | </PRE> | |
24511 | </DIV> | |
24512 | <P> The <TT>%immutable</TT> directive stays in effect until it is | |
24513 | explicitly disabled or cleared using <TT>%mutable</TT>. See the <A href="#SWIG_readonly_variables"> | |
24514 | Creatng read-only variables</A> section for further details.</P> | |
24515 | <P> It is also possible to tag a specific variable as read-only like | |
24516 | this:</P> | |
24517 | <DIV class="code"> | |
24518 | <PRE> | |
24519 | %{ | |
24520 | extern char *path; | |
24521 | %} | |
24522 | %immutable path; | |
24523 | ... | |
24524 | ... | |
24525 | extern char *path; // Declared later in the input | |
24526 | </PRE> | |
24527 | </DIV> | |
24528 | <H3><A name="Perl5_nn17"></A>23.4.3 Constants</H3> | |
24529 | <P> Constants are wrapped as read-only Perl variables. For example:</P> | |
24530 | <DIV class="code"> | |
24531 | <PRE> | |
24532 | %module example | |
24533 | ||
24534 | #define FOO 42 | |
24535 | </PRE> | |
24536 | </DIV> | |
24537 | <P> In Perl:</P> | |
24538 | <DIV class="code"> | |
24539 | <PRE> | |
24540 | use example; | |
24541 | print $example::FOO,"\n"; # OK | |
24542 | $example::FOO = 2; # Error | |
24543 | </PRE> | |
24544 | </DIV> | |
24545 | <H3><A name="Perl5_nn18"></A>23.4.4 Pointers</H3> | |
24546 | <P> SWIG represents pointers as blessed references. A blessed reference | |
24547 | is the same as a Perl reference except that it has additional | |
24548 | information attached to it indicating what kind of reference it is. | |
24549 | That is, if you have a C declaration like this :</P> | |
24550 | <DIV class="code"> | |
24551 | <PRE> | |
24552 | Matrix *new_Matrix(int n, int m); | |
24553 | </PRE> | |
24554 | </DIV> | |
24555 | <P> The module returns a value generated as follows:</P> | |
24556 | <DIV class="code"> | |
24557 | <PRE> | |
24558 | $ptr = new_Matrix(int n, int m); # Save pointer return result | |
24559 | bless $ptr, "p_Matrix"; # Bless it as a pointer to Matrix | |
24560 | </PRE> | |
24561 | </DIV> | |
24562 | <P> SWIG uses the "blessing" to check the datatype of various pointers. | |
24563 | In the event of a mismatch, an error or warning message is generated.</P> | |
24564 | <P> To check to see if a value is the NULL pointer, use the <TT> | |
24565 | defined()</TT> command :</P> | |
24566 | <DIV class="code"> | |
24567 | <PRE> | |
24568 | if (defined($ptr)) { | |
24569 | print "Not a NULL pointer."; | |
24570 | } else { | |
24571 | print "Is a NULL pointer."; | |
24572 | } | |
24573 | ||
24574 | </PRE> | |
24575 | </DIV> | |
24576 | <P> To create a NULL pointer, you should pass the <TT>undef</TT> value | |
24577 | to a function.</P> | |
24578 | <P> The "value" of a Perl reference is not the same as the underlying C | |
24579 | pointer that SWIG wrapper functions return. Suppose that <TT>$a</TT> | |
24580 | and <TT>$b</TT> are two references that point to the same C object. In | |
24581 | general, <TT>$a</TT> and <TT>$b</TT> will be different--since they are | |
24582 | different references. Thus, it is a mistake to check the equality of <TT> | |
24583 | $a</TT> and <TT>$b</TT> to check the equality of two C pointers. The | |
24584 | correct method to check equality of C pointers is to dereference them | |
24585 | as follows :</P> | |
24586 | <DIV class="code"> | |
24587 | <PRE> | |
24588 | if ($$a == $$b) { | |
24589 | print "a and b point to the same thing in C"; | |
24590 | } else { | |
24591 | print "a and b point to different objects."; | |
24592 | } | |
24593 | ||
24594 | </PRE> | |
24595 | </DIV> | |
24596 | <P> As much as you might be inclined to modify a pointer value directly | |
24597 | from Perl, don't. Manipulating pointer values is architecture dependent | |
24598 | and could cause your program to crash. Similarly, don't try to manually | |
24599 | cast a pointer to a new type by reblessing a pointer. This may not work | |
24600 | like you expect and it is particularly dangerous when casting C++ | |
24601 | objects. If you need to cast a pointer or change its value, consider | |
24602 | writing some helper functions instead. For example:</P> | |
24603 | <DIV class="code"> | |
24604 | <PRE> | |
24605 | %inline %{ | |
24606 | /* C-style cast */ | |
24607 | Bar *FooToBar(Foo *f) { | |
24608 | return (Bar *) f; | |
24609 | } | |
24610 | ||
24611 | /* C++-style cast */ | |
24612 | Foo *BarToFoo(Bar *b) { | |
24613 | return dynamic_cast<Foo*>(b); | |
24614 | } | |
24615 | ||
24616 | Foo *IncrFoo(Foo *f, int i) { | |
24617 | return f+i; | |
24618 | } | |
24619 | %} | |
24620 | </PRE> | |
24621 | </DIV> | |
24622 | <P> Also, if working with C++, you should always try to use the new C++ | |
24623 | style casts. For example, in the above code, the C-style cast may | |
24624 | return a bogus result whereas as the C++-style cast will return <TT> | |
24625 | NULL</TT> if the conversion can't be performed.</P> | |
24626 | <P><B> Compatibility Note:</B> In earlier versions, SWIG tried to | |
24627 | preserve the same pointer naming conventions as XS and <TT>xsubpp</TT>. | |
24628 | Given the advancement of the SWIG typesystem and the growing | |
24629 | differences between SWIG and XS, this is no longer supported.</P> | |
24630 | <H3><A name="Perl5_nn19"></A>23.4.5 Structures</H3> | |
24631 | <P> Access to the contents of a structure are provided through a set of | |
24632 | low-level accessor functions as described in the "SWIG Basics" chapter. | |
24633 | For example,</P> | |
24634 | <DIV class="code"> | |
24635 | <PRE> | |
24636 | struct Vector { | |
24637 | double x,y,z; | |
24638 | }; | |
24639 | </PRE> | |
24640 | </DIV> | |
24641 | <P> gets mapped into the following collection of accessor functions:</P> | |
24642 | <DIV class="code"> | |
24643 | <PRE> | |
24644 | struct Vector *new_Vector(); | |
24645 | void delete_Vector(Vector *v); | |
24646 | double Vector_x_get(Vector *obj) | |
24647 | void Vector_x_set(Vector *obj, double x) | |
24648 | double Vector_y_get(Vector *obj) | |
24649 | void Vector_y_set(Vector *obj, double y) | |
24650 | double Vector_z_get(Vector *obj) | |
24651 | void Vector_z_set(Vector *obj, double z) | |
24652 | ||
24653 | </PRE> | |
24654 | </DIV> | |
24655 | <P> These functions are then used to access structure data from Perl as | |
24656 | follows:</P> | |
24657 | <DIV class="code"> | |
24658 | <PRE> | |
24659 | $v = example::new_Vector(); | |
24660 | print example::Vector_x_get($v),"\n"; # Get x component | |
24661 | example::Vector_x_set($v,7.8); # Change x component | |
24662 | </PRE> | |
24663 | </DIV> | |
24664 | <P> Similar access is provided for unions and the data members of C++ | |
24665 | classes.</P> | |
24666 | <P> <TT>const</TT> members of a structure are read-only. Data members | |
24667 | can also be forced to be read-only using the <TT>%immutable</TT> | |
24668 | directive. For example:</P> | |
24669 | <DIV class="code"> | |
24670 | <PRE> | |
24671 | struct Foo { | |
24672 | ... | |
24673 | %immutable; | |
24674 | int x; /* Read-only members */ | |
24675 | char *name; | |
24676 | %mutable; | |
24677 | ... | |
24678 | }; | |
24679 | </PRE> | |
24680 | </DIV> | |
24681 | <P> When <TT>char *</TT> members of a structure are wrapped, the | |
24682 | contents are assumed to be dynamically allocated using <TT>malloc</TT> | |
24683 | or <TT>new</TT> (depending on whether or not SWIG is run with the -c++ | |
24684 | option). When the structure member is set, the old contents will be | |
24685 | released and a new value created. If this is not the behavior you want, | |
24686 | you will have to use a typemap (described later).</P> | |
24687 | <P> Array members are normally wrapped as read-only. For example,</P> | |
24688 | <DIV class="code"> | |
24689 | <PRE> | |
24690 | struct Foo { | |
24691 | int x[50]; | |
24692 | }; | |
24693 | </PRE> | |
24694 | </DIV> | |
24695 | <P> produces a single accessor function like this:</P> | |
24696 | <DIV class="code"> | |
24697 | <PRE> | |
24698 | int *Foo_x_get(Foo *self) { | |
24699 | return self->x; | |
24700 | }; | |
24701 | </PRE> | |
24702 | </DIV> | |
24703 | <P> If you want to set an array member, you will need to supply a | |
24704 | "memberin" typemap described later in this chapter. As a special case, | |
24705 | SWIG does generate code to set array members of type <TT>char</TT> | |
24706 | (allowing you to store a Python string in the structure).</P> | |
24707 | <P> When structure members are wrapped, they are handled as pointers. | |
24708 | For example,</P> | |
24709 | <DIV class="code"> | |
24710 | <PRE> | |
24711 | struct Foo { | |
24712 | ... | |
24713 | }; | |
24714 | ||
24715 | struct Bar { | |
24716 | Foo f; | |
24717 | }; | |
24718 | </PRE> | |
24719 | </DIV> | |
24720 | <P> generates accessor functions such as this:</P> | |
24721 | <DIV class="code"> | |
24722 | <PRE> | |
24723 | Foo *Bar_f_get(Bar *b) { | |
24724 | return &b->f; | |
24725 | } | |
24726 | ||
24727 | void Bar_f_set(Bar *b, Foo *val) { | |
24728 | b->f = *val; | |
24729 | } | |
24730 | </PRE> | |
24731 | </DIV> | |
24732 | <H3><A name="Perl5_nn20"></A>23.4.6 C++ classes</H3> | |
24733 | <P> C++ classes are wrapped by building a set of low level accessor | |
24734 | functions. Consider the following class :</P> | |
24735 | <DIV class="code"> | |
24736 | <PRE> | |
24737 | class List { | |
24738 | public: | |
24739 | List(); | |
24740 | ~List(); | |
24741 | int search(char *item); | |
24742 | void insert(char *item); | |
24743 | void remove(char *item); | |
24744 | char *get(int n); | |
24745 | int length; | |
24746 | static void print(List *l); | |
24747 | }; | |
24748 | </PRE> | |
24749 | </DIV> | |
24750 | <P> When wrapped by SWIG, the following functions are created :</P> | |
24751 | <DIV class="code"> | |
24752 | <PRE> | |
24753 | List *new_List(); | |
24754 | void delete_List(List *l); | |
24755 | int List_search(List *l, char *item); | |
24756 | void List_insert(List *l, char *item); | |
24757 | void List_remove(List *l, char *item); | |
24758 | char *List_get(List *l, int n); | |
24759 | int List_length_get(List *l); | |
24760 | void List_length_set(List *l, int n); | |
24761 | void List_print(List *l); | |
24762 | ||
24763 | </PRE> | |
24764 | </DIV> | |
24765 | <P> In Perl, these functions are used in a straightforward manner:</P> | |
24766 | <DIV class="code"> | |
24767 | <PRE> | |
24768 | use example; | |
24769 | $l = example::new_List(); | |
24770 | example::List_insert($l,"Ale"); | |
24771 | example::List_insert($l,"Stout"); | |
24772 | example::List_insert($l,"Lager") | |
24773 | example::List_print($l) | |
24774 | Lager | |
24775 | Stout | |
24776 | Ale | |
24777 | print example::List_length_get($l),"\n"; | |
24778 | 3 | |
24779 | </PRE> | |
24780 | </DIV> | |
24781 | <P> At this low level, C++ objects are really just typed pointers. | |
24782 | Member functions are accessed by calling a C-like wrapper with an | |
24783 | instance pointer as the first argument. Although this interface is | |
24784 | fairly primitive, it provides direct access to C++ objects. A higher | |
24785 | level interface using Perl proxy classes can be built using these | |
24786 | low-level accessors. This is described shortly.</P> | |
24787 | <H3><A name="Perl5_nn21"></A>23.4.7 C++ classes and type-checking</H3> | |
24788 | <P> The SWIG type-checker is fully aware of C++ inheritance. Therefore, | |
24789 | if you have classes like this</P> | |
24790 | <DIV class="code"> | |
24791 | <PRE> | |
24792 | class Foo { | |
24793 | ... | |
24794 | }; | |
24795 | ||
24796 | class Bar : public Foo { | |
24797 | ... | |
24798 | }; | |
24799 | </PRE> | |
24800 | </DIV> | |
24801 | <P> and a function</P> | |
24802 | <DIV class="code"> | |
24803 | <PRE> | |
24804 | void spam(Foo *f); | |
24805 | </PRE> | |
24806 | </DIV> | |
24807 | <P> then the function <TT>spam()</TT> accepts <TT>Foo *</TT> or a | |
24808 | pointer to any class derived from <TT>Foo</TT>. If necesssary, the | |
24809 | type-checker also adjusts the value of the pointer (as is necessary | |
24810 | when multiple inheritance is used).</P> | |
24811 | <H3><A name="Perl5_nn22"></A>23.4.8 C++ overloaded functions</H3> | |
24812 | <P> If you have a C++ program with overloaded functions or methods, you | |
24813 | will need to disambiguate those methods using <TT>%rename</TT>. For | |
24814 | example:</P> | |
24815 | <DIV class="code"> | |
24816 | <PRE> | |
24817 | /* Forward renaming declarations */ | |
24818 | %rename(foo_i) foo(int); | |
24819 | %rename(foo_d) foo(double); | |
24820 | ... | |
24821 | void foo(int); // Becomes 'foo_i' | |
24822 | void foo(char *c); // Stays 'foo' (not renamed) | |
24823 | ||
24824 | class Spam { | |
24825 | public: | |
24826 | void foo(int); // Becomes 'foo_i' | |
24827 | void foo(double); // Becomes 'foo_d' | |
24828 | ... | |
24829 | }; | |
24830 | </PRE> | |
24831 | </DIV> | |
24832 | <P> Now, in Perl, the methods are accessed as follows:</P> | |
24833 | <DIV class="code"> | |
24834 | <PRE> | |
24835 | use example; | |
24836 | example::foo_i(3); | |
24837 | $s = example::new_Spam(); | |
24838 | example::Spam_foo_i($s,3); | |
24839 | example::Spam_foo_d($s,3.14); | |
24840 | </PRE> | |
24841 | </DIV> | |
24842 | <P> Please refer to the "SWIG Basics" chapter for more information.</P> | |
24843 | <H3><A name="Perl5_nn23"></A>23.4.9 Operators</H3> | |
24844 | <P> C++ operators can also be wrapped using the <TT>%rename</TT> | |
24845 | directive. All you need to do is give the operator the name of a valid | |
24846 | Perl identifier. For example:</P> | |
24847 | <DIV class="code"> | |
24848 | <PRE> | |
24849 | %rename(add_complex) operator+(Complex &, Complex &); | |
24850 | ... | |
24851 | Complex operator+(Complex &, Complex &); | |
24852 | </PRE> | |
24853 | </DIV> | |
24854 | <P> Now, in Perl, you can do this:</P> | |
24855 | <DIV class="code"> | |
24856 | <PRE> | |
24857 | use example; | |
24858 | $a = example::new_Complex(2,3); | |
24859 | $b = example::new_Complex(4,-1); | |
24860 | $c = example::add_complex($a,$b); | |
24861 | </PRE> | |
24862 | </DIV> | |
24863 | <P> Some preliminary work on mapping C++ operators into Perl operators | |
24864 | has been completed. This is covered later.</P> | |
24865 | <H3><A name="Perl5_nn24"></A>23.4.10 Modules and packages</H3> | |
24866 | <P> When you create a SWIG extension, everything gets placed into a | |
24867 | single Perl module. The name of the module is determined by the <TT> | |
24868 | %module</TT> directive. To use the module, do the following :</P> | |
24869 | <DIV class="code"> | |
24870 | <PRE> | |
24871 | % perl5 | |
24872 | use example; # load the example module | |
24873 | print example::fact(4),"\n" # Call a function in it | |
24874 | 24 | |
24875 | </PRE> | |
24876 | </DIV> | |
24877 | <P> Usually, a module consists of a collection of code that is contained | |
24878 | within a single file. A package, on the other hand, is the Perl | |
24879 | equivalent of a namespace. A package is alot like a module, except that | |
24880 | it is independent of files. Any number of files may be part of the same | |
24881 | package--or a package may be broken up into a collection of modules if | |
24882 | you prefer to think about it in this way.</P> | |
24883 | <P> SWIG installs its functions into a package with the same name as the | |
24884 | module.</P> | |
24885 | <P><B> Incompatible Change:</B> previous versions of SWIG enabled you to | |
24886 | change the name of the package by using the -package option, this | |
24887 | feature has been removed in order to properly support modules that used | |
24888 | nested namespaces, e.g. Foo::Bar::Baz. To give your module a nested | |
24889 | namespace simply provide the fully qualified name in your %module | |
24890 | directive:</P> | |
24891 | <DIV class="code"> | |
24892 | <PRE> | |
24893 | %module "Foo::Bar::Baz" | |
24894 | </PRE> | |
24895 | </DIV> | |
24896 | <P><B> NOTE:</B> the double quotes are necessary.</P> | |
24897 | ||
24898 | <!-- | |
24899 | <p> | |
24900 | This can be changed by giving SWIG the -package | |
24901 | option : | |
24902 | </p> | |
24903 | ||
24904 | <div class="code"><pre> | |
24905 | % swig -perl -package Foo example.i | |
24906 | </pre></div> | |
24907 | ||
24908 | <p> | |
24909 | In this case, you still create a module called `<tt>example</tt>' exactly as before, but | |
24910 | all of the functions in that module will be installed into the package | |
24911 | `<tt>Foo</tt>.' For example : | |
24912 | </p> | |
24913 | ||
24914 | <div class="code"><pre> | |
24915 | use example; # Load the module like before | |
24916 | print Foo::fact(4),"\n"; # Call a function in package FooBar | |
24917 | </pre></div> | |
24918 | --> | |
24919 | <H2><A name="Perl5_nn25"></A>23.5 Input and output parameters</H2> | |
24920 | <P> A common problem in some C programs is handling parameters passed as | |
24921 | simple pointers. For example:</P> | |
24922 | <DIV class="code"> | |
24923 | <PRE> | |
24924 | void add(int x, int y, int *result) { | |
24925 | *result = x + y; | |
24926 | } | |
24927 | </PRE> | |
24928 | </DIV> | |
24929 | <P> or perhaps</P> | |
24930 | <DIV class="code"> | |
24931 | <PRE> | |
24932 | int sub(int *x, int *y) { | |
24933 | return *x+*y; | |
24934 | } | |
24935 | </PRE> | |
24936 | </DIV> | |
24937 | <P> The easiest way to handle these situations is to use the <TT> | |
24938 | typemaps.i</TT> file. For example:</P> | |
24939 | <DIV class="code"> | |
24940 | <PRE> | |
24941 | %module example | |
24942 | %include "typemaps.i" | |
24943 | ||
24944 | void add(int, int, int *OUTPUT); | |
24945 | int sub(int *INPUT, int *INPUT); | |
24946 | </PRE> | |
24947 | </DIV> | |
24948 | <P> In Perl, this allows you to pass simple values. For example:</P> | |
24949 | <DIV class="code"> | |
24950 | <PRE> | |
24951 | $a = example::add(3,4); | |
24952 | print "$a\n"; | |
24953 | 7 | |
24954 | $b = example::sub(7,4); | |
24955 | print "$b\n"; | |
24956 | 3 | |
24957 | </PRE> | |
24958 | </DIV> | |
24959 | <P> Notice how the <TT>INPUT</TT> parameters allow integer values to be | |
24960 | passed instead of pointers and how the <TT>OUTPUT</TT> parameter | |
24961 | creates a return result.</P> | |
24962 | <P> If you don't want to use the names <TT>INPUT</TT> or <TT>OUTPUT</TT> | |
24963 | , use the <TT>%apply</TT> directive. For example:</P> | |
24964 | <DIV class="code"> | |
24965 | <PRE> | |
24966 | %module example | |
24967 | %include "typemaps.i" | |
24968 | ||
24969 | %apply int *OUTPUT { int *result }; | |
24970 | %apply int *INPUT { int *x, int *y}; | |
24971 | ||
24972 | void add(int x, int y, int *result); | |
24973 | int sub(int *x, int *y); | |
24974 | </PRE> | |
24975 | </DIV> | |
24976 | <P> If a function mutates one of its parameters like this,</P> | |
24977 | <DIV class="code"> | |
24978 | <PRE> | |
24979 | void negate(int *x) { | |
24980 | *x = -(*x); | |
24981 | } | |
24982 | </PRE> | |
24983 | </DIV> | |
24984 | <P> you can use <TT>INOUT</TT> like this:</P> | |
24985 | <DIV class="code"> | |
24986 | <PRE> | |
24987 | %include "typemaps.i" | |
24988 | ... | |
24989 | void negate(int *INOUT); | |
24990 | </PRE> | |
24991 | </DIV> | |
24992 | <P> In Perl, a mutated parameter shows up as a return value. For | |
24993 | example:</P> | |
24994 | <DIV class="code"> | |
24995 | <PRE> | |
24996 | $a = example::negate(3); | |
24997 | print "$a\n"; | |
24998 | -3 | |
24999 | </PRE> | |
25000 | </DIV> | |
25001 | <P> The most common use of these special typemap rules is to handle | |
25002 | functions that return more than one value. For example, sometimes a | |
25003 | function returns a result as well as a special error code:</P> | |
25004 | <DIV class="code"> | |
25005 | <PRE> | |
25006 | /* send message, return number of bytes sent, along with success code */ | |
25007 | int send_message(char *text, int len, int *success); | |
25008 | </PRE> | |
25009 | </DIV> | |
25010 | <P> To wrap such a function, simply use the <TT>OUTPUT</TT> rule above. | |
25011 | For example:</P> | |
25012 | <DIV class="code"> | |
25013 | <PRE> | |
25014 | %module example | |
25015 | %include "typemaps.i" | |
25016 | %apply int *OUTPUT { int *success }; | |
25017 | ... | |
25018 | int send_message(char *text, int *success); | |
25019 | </PRE> | |
25020 | </DIV> | |
25021 | <P> When used in Perl, the function will return multiple values.</P> | |
25022 | <DIV class="code"> | |
25023 | <PRE> | |
25024 | ($bytes, $success) = example::send_message("Hello World"); | |
25025 | </PRE> | |
25026 | </DIV> | |
25027 | <P> Another common use of multiple return values are in query functions. | |
25028 | For example:</P> | |
25029 | <DIV class="code"> | |
25030 | <PRE> | |
25031 | void get_dimensions(Matrix *m, int *rows, int *columns); | |
25032 | </PRE> | |
25033 | </DIV> | |
25034 | <P> To wrap this, you might use the following:</P> | |
25035 | <DIV class="code"> | |
25036 | <PRE> | |
25037 | %module example | |
25038 | %include "typemaps.i" | |
25039 | %apply int *OUTPUT { int *rows, int *columns }; | |
25040 | ... | |
25041 | void get_dimensions(Matrix *m, int *rows, *columns); | |
25042 | </PRE> | |
25043 | </DIV> | |
25044 | <P> Now, in Perl:</P> | |
25045 | <DIV class="code"> | |
25046 | <PRE> | |
25047 | ($r,$c) = example::get_dimensions($m); | |
25048 | </PRE> | |
25049 | </DIV> | |
25050 | <P> In certain cases, it is possible to treat Perl references as C | |
25051 | pointers. To do this, use the <TT>REFERENCE</TT> typemap. For example:</P> | |
25052 | <DIV class="code"> | |
25053 | <PRE> | |
25054 | %module example | |
25055 | %include typemaps.i | |
25056 | ||
25057 | void add(int x, int y, int *REFERENCE); | |
25058 | </PRE> | |
25059 | </DIV> | |
25060 | <P> In Perl:</P> | |
25061 | <DIV class="code"> | |
25062 | <PRE> | |
25063 | use example; | |
25064 | $c = 0.0; | |
25065 | example::add(3,4,\$c); | |
25066 | print "$c\n"; | |
25067 | 7 | |
25068 | </PRE> | |
25069 | </DIV> | |
25070 | <P><B> Note:</B> The <TT>REFERENCE</TT> feature is only currently | |
25071 | supported for numeric types (integers and floating point).</P> | |
25072 | <H2><A name="Perl5_nn26"></A>23.6 Exception handling</H2> | |
25073 | <P> The SWIG <TT>%exception</TT> directive can be used to create a | |
25074 | user-definable exception handler for converting exceptions in your | |
25075 | C/C++ program into Perl exceptions. The chapter on customization | |
25076 | features contains more details, but suppose you have a C++ class like | |
25077 | the following :</P> | |
25078 | <DIV class="code"> | |
25079 | <PRE> | |
25080 | class RangeError {}; // Used for an exception | |
25081 | ||
25082 | class DoubleArray { | |
25083 | private: | |
25084 | int n; | |
25085 | double *ptr; | |
25086 | public: | |
25087 | // Create a new array of fixed size | |
25088 | DoubleArray(int size) { | |
25089 | ptr = new double[size]; | |
25090 | n = size; | |
25091 | } | |
25092 | // Destroy an array | |
25093 | ~DoubleArray() { | |
25094 | delete ptr; | |
25095 | } | |
25096 | // Return the length of the array | |
25097 | int length() { | |
25098 | return n; | |
25099 | } | |
25100 | ||
25101 | // Get an item from the array and perform bounds checking. | |
25102 | double getitem(int i) { | |
25103 | if ((i >= 0) && (i < n)) | |
25104 | return ptr[i]; | |
25105 | else | |
25106 | throw RangeError(); | |
25107 | } | |
25108 | ||
25109 | // Set an item in the array and perform bounds checking. | |
25110 | void setitem(int i, double val) { | |
25111 | if ((i >= 0) && (i < n)) | |
25112 | ptr[i] = val; | |
25113 | else { | |
25114 | throw RangeError(); | |
25115 | } | |
25116 | } | |
25117 | }; | |
25118 | </PRE> | |
25119 | </DIV> | |
25120 | <P> Since several methods in this class can throw an exception for an | |
25121 | out-of-bounds access, you might want to catch this in the Perl | |
25122 | extension by writing the following in an interface file:</P> | |
25123 | <DIV class="code"> | |
25124 | <PRE> | |
25125 | %exception { | |
25126 | try { | |
25127 | $action | |
25128 | } | |
25129 | catch (RangeError) { | |
25130 | croak("Array index out-of-bounds"); | |
25131 | } | |
25132 | } | |
25133 | ||
25134 | class DoubleArray { | |
25135 | ... | |
25136 | }; | |
25137 | </PRE> | |
25138 | </DIV> | |
25139 | <P> The exception handling code is inserted directly into generated | |
25140 | wrapper functions. The <TT>$action</TT> variable is replaced with the | |
25141 | C/C++ code being executed by the wrapper. When an exception handler is | |
25142 | defined, errors can be caught and used to gracefully generate a Perl | |
25143 | error instead of forcing the entire program to terminate with an | |
25144 | uncaught error.</P> | |
25145 | <P> As shown, the exception handling code will be added to every wrapper | |
25146 | function. Since this is somewhat inefficient. You might consider | |
25147 | refining the exception handler to only apply to specific methods like | |
25148 | this:</P> | |
25149 | <DIV class="code"> | |
25150 | <PRE> | |
25151 | %exception getitem { | |
25152 | try { | |
25153 | $action | |
25154 | } | |
25155 | catch (RangeError) { | |
25156 | croak("Array index out-of-bounds"); | |
25157 | } | |
25158 | } | |
25159 | ||
25160 | %exception setitem { | |
25161 | try { | |
25162 | $action | |
25163 | } | |
25164 | catch (RangeError) { | |
25165 | croak("Array index out-of-bounds"); | |
25166 | } | |
25167 | } | |
25168 | </PRE> | |
25169 | </DIV> | |
25170 | <P> In this case, the exception handler is only attached to methods and | |
25171 | functions named <TT>getitem</TT> and <TT>setitem</TT>.</P> | |
25172 | <P> If you had a lot of different methods, you can avoid extra typing by | |
25173 | using a macro. For example:</P> | |
25174 | <DIV class="code"> | |
25175 | <PRE> | |
25176 | %define RANGE_ERROR | |
25177 | { | |
25178 | try { | |
25179 | $action | |
25180 | } | |
25181 | catch (RangeError) { | |
25182 | croak("Array index out-of-bounds"); | |
25183 | } | |
25184 | } | |
25185 | %enddef | |
25186 | ||
25187 | %exception getitem RANGE_ERROR; | |
25188 | %exception setitem RANGE_ERROR; | |
25189 | </PRE> | |
25190 | </DIV> | |
25191 | <P> Since SWIG's exception handling is user-definable, you are not | |
25192 | limited to C++ exception handling. See the chapter on "<A href="#Customization"> | |
25193 | Customization features</A>" for more examples.</P> | |
25194 | <P><B> Compatibility note:</B> In SWIG1.1, exceptions were defined using | |
25195 | the older <TT>%except</TT> directive:</P> | |
25196 | <DIV class="code"> | |
25197 | <PRE> | |
25198 | %except(python) { | |
25199 | try { | |
25200 | $function | |
25201 | } | |
25202 | catch (RangeError) { | |
25203 | croak("Array index out-of-bounds"); | |
25204 | } | |
25205 | } | |
25206 | </PRE> | |
25207 | </DIV> | |
25208 | <P> This is still supported, but it is deprecated. The newer <TT> | |
25209 | %exception</TT> directive provides the same functionality, but it has | |
25210 | additional capabilities that make it more powerful.</P> | |
25211 | <H2><A name="Perl5_nn27"></A>23.7 Remapping datatypes with typemaps</H2> | |
25212 | <P> This section describes how you can modify SWIG's default wrapping | |
25213 | behavior for various C/C++ datatypes using the <TT>%typemap</TT> | |
25214 | directive. This is an advanced topic that assumes familiarity with the | |
25215 | Perl C API as well as the material in the "<A href="#Typemaps">Typemaps</A> | |
25216 | " chapter.</P> | |
25217 | <P> Before proceeding, it should be stressed that typemaps are<EM> not</EM> | |
25218 | a required part of using SWIG---the default wrapping behavior is enough | |
25219 | in most cases. Typemaps are only used if you want to change some aspect | |
25220 | of the primitive C-Perl interface.</P> | |
25221 | <H3><A name="Perl5_nn28"></A>23.7.1 A simple typemap example</H3> | |
25222 | <P> A typemap is nothing more than a code generation rule that is | |
25223 | attached to a specific C datatype. For example, to convert integers | |
25224 | from Perl to C, you might define a typemap like this:</P> | |
25225 | <DIV class="code"> | |
25226 | <PRE> | |
25227 | %module example | |
25228 | ||
25229 | %typemap(in) int { | |
25230 | $1 = (int) SvIV($input); | |
25231 | printf("Received an integer : %d\n", $1); | |
25232 | } | |
25233 | ... | |
25234 | %inline %{ | |
25235 | extern int fact(int n); | |
25236 | %} | |
25237 | ||
25238 | </PRE> | |
25239 | </DIV> | |
25240 | <P> Typemaps are always associated with some specific aspect of code | |
25241 | generation. In this case, the "in" method refers to the conversion of | |
25242 | input arguments to C/C++. The datatype <TT>int</TT> is the datatype to | |
25243 | which the typemap will be applied. The supplied C code is used to | |
25244 | convert values. In this code a number of special variable prefaced by a | |
25245 | <TT>$</TT> are used. The <TT>$1</TT> variable is placeholder for a | |
25246 | local variable of type <TT>int</TT>. The <TT>$input</TT> variable is | |
25247 | the input object (usually a <TT>SV *</TT>).</P> | |
25248 | <P> When this example is used in Perl5, it will operate as follows :</P> | |
25249 | <DIV class="code"> | |
25250 | <PRE> | |
25251 | use example; | |
25252 | $n = example::fact(6); | |
25253 | print "$n\n"; | |
25254 | ... | |
25255 | ||
25256 | Output : | |
25257 | Received an integer : 6 | |
25258 | 720 | |
25259 | </PRE> | |
25260 | </DIV> | |
25261 | <P> The application of a typemap to specific datatypes and argument | |
25262 | names involves more than simple text-matching--typemaps are fully | |
25263 | integrated into the SWIG type-system. When you define a typemap for <TT> | |
25264 | int</TT>, that typemap applies to <TT>int</TT> and qualified variations | |
25265 | such as <TT>const int</TT>. In addition, the typemap system follows <TT> | |
25266 | typedef</TT> declarations. For example:</P> | |
25267 | <DIV class="code"> | |
25268 | <PRE> | |
25269 | %typemap(in) int n { | |
25270 | $1 = (int) SvIV($input); | |
25271 | printf("n = %d\n",$1); | |
25272 | } | |
25273 | %inline %{ | |
25274 | typedef int Integer; | |
25275 | extern int fact(Integer n); // Above typemap is applied | |
25276 | %} | |
25277 | </PRE> | |
25278 | </DIV> | |
25279 | <P> It should be noted that the matching of <TT>typedef</TT> only occurs | |
25280 | in one direction. If you defined a typemap for <TT>Integer</TT>, it is | |
25281 | not applied to arguments of type <TT>int</TT>.</P> | |
25282 | <P> Typemaps can also be defined for groups of consecutive arguments. | |
25283 | For example:</P> | |
25284 | <DIV class="code"> | |
25285 | <PRE> | |
25286 | %typemap(in) (char *str, unsigned len) { | |
25287 | $1 = SvPV($input,$2); | |
25288 | }; | |
25289 | ||
25290 | int count(char c, char *str, unsigned len); | |
25291 | </PRE> | |
25292 | </DIV> | |
25293 | <P> When a multi-argument typemap is defined, the arguments are always | |
25294 | handled as a single Perl object. This allows the function to be used | |
25295 | like this (notice how the length parameter is ommitted):</P> | |
25296 | <DIV class="code"> | |
25297 | <PRE> | |
25298 | example::count("e","Hello World"); | |
25299 | 1 | |
25300 | >>> | |
25301 | </PRE> | |
25302 | </DIV> | |
25303 | <H3><A name="Perl5_nn29"></A>23.7.2 Perl5 typemaps</H3> | |
25304 | <P> The previous section illustrated an "in" typemap for converting Perl | |
25305 | objects to C. A variety of different typemap methods are defined by the | |
25306 | Perl module. For example, to convert a C integer back into a Perl | |
25307 | object, you might define an "out" typemap like this:</P> | |
25308 | <DIV class="code"> | |
25309 | <PRE> | |
25310 | %typemap(out) int { | |
25311 | $result = sv_newmortal(); | |
25312 | set_setiv($result, (IV) $1); | |
25313 | argvi++; | |
25314 | } | |
25315 | </PRE> | |
25316 | </DIV> | |
25317 | <P> The following typemap methods are available:</P> | |
25318 | <P> <TT>%typemap(in)</TT></P> | |
25319 | <DIV class="indent"> Converts Perl5 object to input function arguments.</DIV> | |
25320 | <P> <TT>%typemap(out)</TT></P> | |
25321 | <DIV class="indent"> Converts function return value to a Perl5 value.</DIV> | |
25322 | <P> <TT>%typemap(varin)</TT></P> | |
25323 | <DIV class="indent"> Converts a Perl5 object to a global variable.</DIV> | |
25324 | <P> <TT>%typemap(varout)</TT></P> | |
25325 | <DIV class="indent"> Converts a global variable to a Perl5 object.</DIV> | |
25326 | <P> <TT>%typemap(freearg)</TT></P> | |
25327 | <DIV class="indent"> Cleans up a function argument after a function call</DIV> | |
25328 | <P> <TT>%typemap(argout)</TT></P> | |
25329 | <DIV class="indent"> Output argument handling</DIV> | |
25330 | <P> <TT>%typemap(ret)</TT></P> | |
25331 | <DIV class="indent"> Clean up return value from a function.</DIV> | |
25332 | <P> <TT>%typemap(memberin)</TT></P> | |
25333 | <DIV class="indent"> Setting of C++ member data (all languages).</DIV> | |
25334 | <P> <TT>%typemap(memberout)</TT></P> | |
25335 | <DIV class="indent"> Return of C++ member data (all languages).</DIV> | |
25336 | <P> <TT>%typemap(check)</TT></P> | |
25337 | <DIV class="indent"> Check value of input parameter.</DIV> | |
25338 | <H3><A name="Perl5_nn30"></A>23.7.3 Typemap variables</H3> | |
25339 | <P> Within typemap code, a number of special variables prefaced with a <TT> | |
25340 | $</TT> may appear. A full list of variables can be found in the "<A href="#Typemaps"> | |
25341 | Typemaps</A>" chapter. This is a list of the most common variables:</P> | |
25342 | <P> <TT>$1</TT></P> | |
25343 | <DIV class="indent"> A C local variable corresponding to the actual type | |
25344 | specified in the <TT>%typemap</TT> directive. For input values, this is | |
25345 | a C local variable that's supposed to hold an argument value. For | |
25346 | output values, this is the raw result that's supposed to be returned to | |
25347 | Perl.</DIV> | |
25348 | <P> <TT>$input</TT></P> | |
25349 | <DIV class="indent"> A Perl object holding the value of an argument of | |
25350 | variable value.</DIV> | |
25351 | <P> <TT>$result</TT></P> | |
25352 | <DIV class="indent"> A Perl object that holds the result to be returned | |
25353 | to Perl.</DIV> | |
25354 | <P> <TT>$1_name</TT></P> | |
25355 | <DIV class="indent"> The parameter name that was matched.</DIV> | |
25356 | <P> <TT>$1_type</TT></P> | |
25357 | <DIV class="indent"> The actual C datatype matched by the typemap.</DIV> | |
25358 | <P> <TT>$1_ltype</TT></P> | |
25359 | <DIV class="indent"> An assignable version of the datatype matched by | |
25360 | the typemap (a type that can appear on the left-hand-side of a C | |
25361 | assignment operation). This type is stripped of qualifiers and may be | |
25362 | an altered version of <TT>$1_type</TT>. All arguments and local | |
25363 | variables in wrapper functions are declared using this type so that | |
25364 | their values can be properly assigned.</DIV> | |
25365 | <P> <TT>$symname</TT></P> | |
25366 | <DIV class="indent"> The Perl name of the wrapper function being | |
25367 | created.</DIV> | |
25368 | <H3><A name="Perl5_nn31"></A>23.7.4 Useful functions</H3> | |
25369 | <P> When writing typemaps, it is necessary to work directly with Perl5 | |
25370 | objects. This, unfortunately, can be a daunting task. Consult the | |
25371 | "perlguts" man-page for all of the really ugly details. A short summary | |
25372 | of commonly used functions is provided here for reference. It should be | |
25373 | stressed that SWIG can be usef quite effectively without knowing any of | |
25374 | these details--especially now that there are typemap libraries that can | |
25375 | already been written.</P> | |
25376 | <P><B> Perl Integer Functions</B></P> | |
25377 | <DIV class="code"> | |
25378 | <PRE> | |
25379 | int SvIV(SV *); | |
25380 | void sv_setiv(SV *sv, IV value); | |
25381 | SV *newSViv(IV value); | |
25382 | int SvIOK(SV *); | |
25383 | </PRE> | |
25384 | </DIV> | |
25385 | <P><B> Perl Floating Point Functions</B></P> | |
25386 | <DIV class="code"> | |
25387 | <PRE> | |
25388 | double SvNV(SV *); | |
25389 | void sv_setnv(SV *, double value); | |
25390 | SV *newSVnv(double value); | |
25391 | int SvNOK(SV *); | |
25392 | </PRE> | |
25393 | </DIV> | |
25394 | <P><B> Perl String Functions</B></P> | |
25395 | <DIV class="code"> | |
25396 | <PRE> | |
25397 | char *SvPV(SV *, STRLEN len); | |
25398 | void sv_setpv(SV *, char *val); | |
25399 | void sv_setpvn(SV *, char *val, STRLEN len); | |
25400 | SV *newSVpv(char *value, STRLEN len); | |
25401 | int SvPOK(SV *); | |
25402 | void sv_catpv(SV *, char *); | |
25403 | void sv_catpvn(SV *, char *, STRLEN); | |
25404 | </PRE> | |
25405 | </DIV> | |
25406 | <P><B> Perl References</B></P> | |
25407 | <DIV class="code"> | |
25408 | <PRE> | |
25409 | void sv_setref_pv(SV *, char *, void *ptr); | |
25410 | int sv_isobject(SV *); | |
25411 | SV *SvRV(SV *); | |
25412 | int sv_isa(SV *, char *0; | |
25413 | </PRE> | |
25414 | </DIV> | |
25415 | <H2><A name="Perl5_nn32"></A>23.8 Typemap Examples</H2> | |
25416 | <P> This section includes a few examples of typemaps. For more examples, | |
25417 | you might look at the files "<TT>perl5.swg</TT>" and "<TT>typemaps.i</TT> | |
25418 | " in the SWIG library.</P> | |
25419 | <H3><A name="Perl5_nn33"></A>23.8.1 Converting a Perl5 array to a char | |
25420 | **</H3> | |
25421 | <P> A common problem in many C programs is the processing of command | |
25422 | line arguments, which are usually passed in an array of NULL terminated | |
25423 | strings. The following SWIG interface file allows a Perl5 array | |
25424 | reference to be used as a char ** datatype.</P> | |
25425 | <DIV class="code"> | |
25426 | <PRE> | |
25427 | %module argv | |
25428 | ||
25429 | // This tells SWIG to treat char ** as a special case | |
25430 | %typemap(in) char ** { | |
25431 | AV *tempav; | |
25432 | I32 len; | |
25433 | int i; | |
25434 | SV **tv; | |
25435 | if (!SvROK($input)) | |
25436 | croak("Argument $argnum is not a reference."); | |
25437 | if (SvTYPE(SvRV($input)) != SVt_PVAV) | |
25438 | croak("Argument $argnum is not an array."); | |
25439 | tempav = (AV*)SvRV($input); | |
25440 | len = av_len(tempav); | |
25441 | $1 = (char **) malloc((len+2)*sizeof(char *)); | |
25442 | for (i = 0; i <= len; i++) { | |
25443 | tv = av_fetch(tempav, i, 0); | |
25444 | $1[i] = (char *) SvPV(*tv,PL_na); | |
25445 | } | |
25446 | $1[i] = NULL; | |
25447 | }; | |
25448 | ||
25449 | // This cleans up the char ** array after the function call | |
25450 | %typemap(freearg) char ** { | |
25451 | free($1); | |
25452 | } | |
25453 | ||
25454 | // Creates a new Perl array and places a NULL-terminated char ** into it | |
25455 | %typemap(out) char ** { | |
25456 | AV *myav; | |
25457 | SV **svs; | |
25458 | int i = 0,len = 0; | |
25459 | /* Figure out how many elements we have */ | |
25460 | while ($1[len]) | |
25461 | len++; | |
25462 | svs = (SV **) malloc(len*sizeof(SV *)); | |
25463 | for (i = 0; i < len ; i++) { | |
25464 | svs[i] = sv_newmortal(); | |
25465 | sv_setpv((SV*)svs[i],$1[i]); | |
25466 | }; | |
25467 | myav = av_make(len,svs); | |
25468 | free(svs); | |
25469 | $result = newRV((SV*)myav); | |
25470 | sv_2mortal($result); | |
25471 | argvi++; | |
25472 | } | |
25473 | ||
25474 | // Now a few test functions | |
25475 | %inline %{ | |
25476 | int print_args(char **argv) { | |
25477 | int i = 0; | |
25478 | while (argv[i]) { | |
25479 | printf("argv[%d] = %s\n", i,argv[i]); | |
25480 | i++; | |
25481 | } | |
25482 | return i; | |
25483 | } | |
25484 | ||
25485 | // Returns a char ** list | |
25486 | char **get_args() { | |
25487 | static char *values[] = { "Dave", "Mike", "Susan", "John", "Michelle", 0}; | |
25488 | return &values[0]; | |
25489 | } | |
25490 | %} | |
25491 | ||
25492 | </PRE> | |
25493 | </DIV> | |
25494 | <P> When this module is compiled, the wrapped C functions can be used in | |
25495 | a Perl script as follows :</P> | |
25496 | <DIV class="code"> | |
25497 | <PRE> | |
25498 | use argv; | |
25499 | @a = ("Dave", "Mike", "John", "Mary"); # Create an array of strings | |
25500 | argv::print_args(\@a); # Pass it to our C function | |
25501 | $b = argv::get_args(); # Get array of strings from C | |
25502 | print @$b,"\n"; # Print it out | |
25503 | </PRE> | |
25504 | </DIV> | |
25505 | <H3><A name="Perl5_nn34"></A>23.8.2 Return values</H3> | |
25506 | <P> Return values are placed on the argument stack of each wrapper | |
25507 | function. The current value of the argument stack pointer is contained | |
25508 | in a variable <TT>argvi</TT>. Whenever a new output value is added, it | |
25509 | is critical that this value be incremented. For multiple output values, | |
25510 | the final value of <TT>argvi</TT> should be the total number of output | |
25511 | values.</P> | |
25512 | <P> The total number of return values should not exceed the number of | |
25513 | input values unless you explicitly extend the argument stack. This can | |
25514 | be done using the <TT>EXTEND()</TT> macro as in :</P> | |
25515 | <DIV class="code"> | |
25516 | <PRE> | |
25517 | %typemap(argout) int *OUTPUT { | |
25518 | if (argvi >= items) { | |
25519 | EXTEND(sp,1); /* Extend the stack by 1 object */ | |
25520 | } | |
25521 | $result = sv_newmortal(); | |
25522 | sv_setiv($target,(IV) *($1)); | |
25523 | argvi++; | |
25524 | } | |
25525 | </PRE> | |
25526 | </DIV> | |
25527 | <H3><A name="Perl5_nn35"></A>23.8.3 Returning values from arguments</H3> | |
25528 | <P> Sometimes it is desirable for a function to return a value in one of | |
25529 | its arguments. This example describes the implementation of the <TT> | |
25530 | OUTPUT</TT> typemap.</P> | |
25531 | <DIV class="code"> | |
25532 | <PRE> | |
25533 | %module return | |
25534 | ||
25535 | // This tells SWIG to treat an double * argument with name 'OutDouble' as | |
25536 | // an output value. | |
25537 | ||
25538 | %typemap(argout) double *OUTPUT { | |
25539 | $result = sv_newmortal(); | |
25540 | sv_setnv($result, *$input); | |
25541 | argvi++; /* Increment return count -- important! */ | |
25542 | } | |
25543 | ||
25544 | // We don't care what the input value is. Ignore, but set to a temporary variable | |
25545 | ||
25546 | %typemap(in,numinputs=0) double *OUTPUT(double junk) { | |
25547 | $1 = &junk; | |
25548 | } | |
25549 | ||
25550 | // Now a function to test it | |
25551 | %{ | |
25552 | /* Returns the first two input arguments */ | |
25553 | int multout(double a, double b, double *out1, double *out2) { | |
25554 | *out1 = a; | |
25555 | *out2 = b; | |
25556 | return 0; | |
25557 | }; | |
25558 | %} | |
25559 | ||
25560 | // If we name both parameters OutDouble both will be output | |
25561 | ||
25562 | int multout(double a, double b, double *OUTPUT, double *OUTPUT); | |
25563 | ... | |
25564 | </PRE> | |
25565 | </DIV> | |
25566 | <P> When this function is called, the output arguments are appended to | |
25567 | the stack used to return results. This shows up an array in Perl. For | |
25568 | example :</P> | |
25569 | <DIV class="code"> | |
25570 | <PRE> | |
25571 | @r = multout(7,13); | |
25572 | print "multout(7,13) = @r\n"; | |
25573 | ($x,$y) = multout(7,13); | |
25574 | </PRE> | |
25575 | </DIV> | |
25576 | <H3><A name="Perl5_nn36"></A>23.8.4 Accessing array structure members</H3> | |
25577 | <P> Consider the following data structure :</P> | |
25578 | <DIV class="code"> | |
25579 | <PRE> | |
25580 | #define SIZE 8 | |
25581 | typedef struct { | |
25582 | int values[SIZE]; | |
25583 | ... | |
25584 | } Foo; | |
25585 | ||
25586 | </PRE> | |
25587 | </DIV> | |
25588 | <P> By default, SWIG doesn't know how to the handle the values structure | |
25589 | member it's an array, not a pointer. In this case, SWIG makes the array | |
25590 | member read-only. Reading will simply return a pointer to the first | |
25591 | item in the array. To make the member writable, a "memberin" typemap | |
25592 | can be used.</P> | |
25593 | <DIV class="code"> | |
25594 | <PRE> | |
25595 | %typemap(memberin) int [SIZE] { | |
25596 | int i; | |
25597 | for (i = 0; i < SIZE; i++) { | |
25598 | $1[i] = $input[i]; | |
25599 | } | |
25600 | } | |
25601 | ||
25602 | </PRE> | |
25603 | </DIV> | |
25604 | <P> Whenever a <TT>int [SIZE]</TT> member is encountered in a structure | |
25605 | or class, this typemap provides a safe mechanism for setting its value.</P> | |
25606 | <P> As in the previous example, the typemap can be generalized for any | |
25607 | dimension. For example:</P> | |
25608 | <DIV class="code"> | |
25609 | <PRE> | |
25610 | %typemap(memberin) int [ANY] { | |
25611 | int i; | |
25612 | for (i = 0; i < $1_dim0; i++) { | |
25613 | $1[i] = $input[i]; | |
25614 | } | |
25615 | } | |
25616 | </PRE> | |
25617 | </DIV> | |
25618 | <P> When setting structure members, the input object is always assumed | |
25619 | to be a C array of values that have already been converted from the | |
25620 | target language. Because of this, the <TT>memberin</TT> typemap is | |
25621 | almost always combined with the use of an "in" typemap. For example, | |
25622 | the "in" typemap in the previous section would be used to convert an <TT> | |
25623 | int[]</TT> array to C whereas the "memberin" typemap would be used to | |
25624 | copy the converted array into a C data structure.</P> | |
25625 | <H3><A name="Perl5_nn37"></A>23.8.5 Turning Perl references into C | |
25626 | pointers</H3> | |
25627 | <P> A frequent confusion on the SWIG mailing list is errors caused by | |
25628 | the mixing of Perl references and C pointers. For example, suppose you | |
25629 | have a C function that modifies its arguments like this :</P> | |
25630 | <DIV class="code"> | |
25631 | <PRE> | |
25632 | void add(double a, double b, double *c) { | |
25633 | *c = a + b; | |
25634 | } | |
25635 | </PRE> | |
25636 | </DIV> | |
25637 | <P> A common misinterpretation of this function is the following Perl | |
25638 | script :</P> | |
25639 | <DIV class="code"> | |
25640 | <PRE> | |
25641 | # Perl script | |
25642 | $a = 3.5; | |
25643 | $b = 7.5; | |
25644 | $c = 0.0; # Output value | |
25645 | add($a,$b,\$c); # Place result in c (Except that it doesn't work) | |
25646 | </PRE> | |
25647 | </DIV> | |
25648 | <P> To make this work with a reference, you can use a typemap such as | |
25649 | this:</P> | |
25650 | <DIV class="code"> | |
25651 | <PRE> | |
25652 | %typemap(in) double * (double dvalue) { | |
25653 | SV* tempsv; | |
25654 | if (!SvROK($input)) { | |
25655 | croak("expected a reference\n"); | |
25656 | } | |
25657 | tempsv = SvRV($input); | |
25658 | if ((!SvNOK(tempsv)) && (!SvIOK(tempsv))) { | |
25659 | croak("expected a double reference\n"); | |
25660 | } | |
25661 | dvalue = SvNV(tempsv); | |
25662 | $1 = &dvalue; | |
25663 | } | |
25664 | ||
25665 | %typemap(argout) double * { | |
25666 | SV *tempsv; | |
25667 | tempsv = SvRV($input); | |
25668 | sv_setnv(tempsv, *$1); | |
25669 | } | |
25670 | </PRE> | |
25671 | </DIV> | |
25672 | <P> Now, if you place this before the add function, you can do this :</P> | |
25673 | <DIV class="code"> | |
25674 | <PRE> | |
25675 | $a = 3.5; | |
25676 | $b = 7.5; | |
25677 | $c = 0.0; | |
25678 | add($a,$b,\$c); # Now it works! | |
25679 | print "$c\n"; | |
25680 | ||
25681 | </PRE> | |
25682 | </DIV> | |
25683 | <H3><A name="Perl5_nn38"></A>23.8.6 Pointer handling</H3> | |
25684 | <P> Occasionally, it might be necessary to convert pointer values that | |
25685 | have been stored using the SWIG typed-pointer representation. To | |
25686 | convert a pointer from Perl to C, the following function is used:</P> | |
25687 | <P> <TT>int SWIG_ConvertPtr(SV *obj, void **ptr, swig_type_info *ty, int | |
25688 | flags)</TT></P> | |
25689 | <DIV class="indent"> Converts a Perl object <TT>obj</TT> to a C pointer. | |
25690 | The result of the conversion is placed into the pointer located at <TT> | |
25691 | ptr</TT>. <TT>ty</TT> is a SWIG type descriptor structure. <TT>flags</TT> | |
25692 | is used to handle error checking and other aspects of conversion. <TT> | |
25693 | flags</TT> is currently undefined and reserved for future expansion. | |
25694 | Returns 0 on success and -1 on error.</DIV> | |
25695 | <P> <TT>void *SWIG_MakePtr(SV *obj, void *ptr, swig_type_info *ty, int | |
25696 | flags)</TT></P> | |
25697 | <DIV class="indent"> Creates a new Perl pointer object. <TT>obj</TT> is | |
25698 | a Perl SV that has been initialized to hold the result, <TT>ptr</TT> is | |
25699 | the pointer to convert, <TT>ty</TT> is the SWIG type descriptor | |
25700 | structure that describes the type, and <TT>flags</TT> is a flag that | |
25701 | controls properties of the conversion. <TT>flags</TT> is currently | |
25702 | undefined and reserved.</DIV> | |
25703 | <P> Both of these functions require the use of a special SWIG | |
25704 | type-descriptor structure. This structure contains information about | |
25705 | the mangled name of the datatype, type-equivalence information, as well | |
25706 | as information about converting pointer values under C++ inheritance. | |
25707 | For a type of <TT>Foo *</TT>, the type descriptor structure is usually | |
25708 | accessed as follows:</P> | |
25709 | <DIV class="code"> | |
25710 | <PRE> | |
25711 | Foo *f; | |
25712 | if (SWIG_ConvertPtr($input, (void **) &f, SWIGTYPE_p_Foo, 0) == -1) return NULL; | |
25713 | ||
25714 | SV *sv = sv_newmortal(); | |
25715 | SWIG_MakePtr(sv, f, SWIGTYPE_p_Foo, 0); | |
25716 | </PRE> | |
25717 | </DIV> | |
25718 | <P> In a typemap, the type descriptor should always be accessed using | |
25719 | the special typemap variable <TT>$1_descriptor</TT>. For example:</P> | |
25720 | <DIV class="code"> | |
25721 | <PRE> | |
25722 | %typemap(in) Foo * { | |
25723 | if ((SWIG_ConvertPtr($input,(void **) &$1, $1_descriptor,0)) == -1) return NULL; | |
25724 | } | |
25725 | </PRE> | |
25726 | </DIV> | |
25727 | <P> If necessary, the descriptor for any type can be obtained using the <TT> | |
25728 | $descriptor()</TT> macro in a typemap. For example:</P> | |
25729 | <DIV class="code"> | |
25730 | <PRE> | |
25731 | %typemap(in) Foo * { | |
25732 | if ((SWIG_ConvertPtr($input,(void **) &$1, $descriptor(Foo *), 0)) == -1) return NULL; | |
25733 | } | |
25734 | </PRE> | |
25735 | </DIV> | |
25736 | <H2><A name="Perl5_nn39"></A>23.9 Proxy classes</H2> | |
25737 | <P><B> Out of date. Needs update.</B></P> | |
25738 | <P> Using the low-level procedural interface, SWIG can also construct a | |
25739 | high-level object oriented interface to C structures and C++ classes. | |
25740 | This is done by constructing a Perl proxy class (also known as a shadow | |
25741 | class) that provides an OO wrapper to the underlying code. This section | |
25742 | describes the implementation details of the proxy interface.</P> | |
25743 | <H3><A name="Perl5_nn40"></A>23.9.1 Preliminaries</H3> | |
25744 | <P> Proxy classes, are generated by default. If you want to turn them | |
25745 | off, use the <TT>-noproxy</TT> command line option. For example:</P> | |
25746 | <DIV class="code"> | |
25747 | <PRE> | |
25748 | $ swig -c++ -perl -noproxy example.i | |
25749 | </PRE> | |
25750 | </DIV> | |
25751 | <P> When proxy classes are used, SWIG moves all of the low-level | |
25752 | procedural wrappers to another package name. By default, this package | |
25753 | is named 'modulec' where 'module' is the name of the module you | |
25754 | provided with the <TT>%module</TT> directive. Then, in place of the | |
25755 | original module, SWIG creates a collection of high-level Perl wrappers. | |
25756 | In your scripts, you will use these high level wrappers. The wrappers, | |
25757 | in turn, interact with the low-level procedural module.</P> | |
25758 | <H3><A name="Perl5_nn41"></A>23.9.2 Structure and class wrappers</H3> | |
25759 | <P> Suppose you have the following SWIG interface file :</P> | |
25760 | <DIV class="code"> | |
25761 | <PRE> | |
25762 | %module example | |
25763 | struct Vector { | |
25764 | Vector(double x, double y, double z); | |
25765 | ~Vector(); | |
25766 | double x,y,z; | |
25767 | }; | |
25768 | ||
25769 | </PRE> | |
25770 | </DIV> | |
25771 | <P> When wrapped, SWIG creates the following set of low-level accessor | |
25772 | functions as described in previous sections.</P> | |
25773 | <DIV class="code"> | |
25774 | <PRE> | |
25775 | Vector *new_Vector(double x, double y, double z); | |
25776 | void delete_Vector(Vector *v); | |
25777 | double Vector_x_get(Vector *v); | |
25778 | double Vector_x_set(Vector *v, double value); | |
25779 | double Vector_y_get(Vector *v); | |
25780 | double Vector_y_set(Vector *v, double value); | |
25781 | double Vector_z_get(Vector *v); | |
25782 | double Vector_z_set(Vector *v, double value); | |
25783 | ||
25784 | </PRE> | |
25785 | </DIV> | |
25786 | <P> However, when proxy classes are enabled, these accessor functions | |
25787 | are wrapped inside a Perl class like this:</P> | |
25788 | <DIV class="code"> | |
25789 | <PRE> | |
25790 | package example::Vector; | |
25791 | @ISA = qw( example ); | |
25792 | %OWNER = (); | |
25793 | %BLESSEDMEMBERS = (); | |
25794 | ||
25795 | sub new () { | |
25796 | my $self = shift; | |
25797 | my @args = @_; | |
25798 | $self = vectorc::new_Vector(@args); | |
25799 | return undef if (!defined($self)); | |
25800 | bless $self, "example::Vector"; | |
25801 | $OWNER{$self} = 1; | |
25802 | my %retval; | |
25803 | tie %retval, "example::Vector", $self; | |
25804 | return bless \%retval,"Vector"; | |
25805 | } | |
25806 | ||
25807 | sub DESTROY { | |
25808 | return unless $_[0]->isa('HASH'); | |
25809 | my $self = tied(%{$_[0]}); | |
25810 | delete $ITERATORS{$self}; | |
25811 | if (exists $OWNER{$self}) { | |
25812 | examplec::delete_Vector($self)); | |
25813 | delete $OWNER{$self}; | |
25814 | } | |
25815 | ||
25816 | sub FETCH { | |
25817 | my ($self,$field) = @_; | |
25818 | my $member_func = "vectorc::Vector_${field}_get"; | |
25819 | my $val = &$member_func($self); | |
25820 | if (exists $BLESSEDMEMBERS{$field}) { | |
25821 | return undef if (!defined($val)); | |
25822 | my %retval; | |
25823 | tie %retval,$BLESSEDMEMBERS{$field},$val; | |
25824 | return bless \%retval, $BLESSEDMEMBERS{$field}; | |
25825 | } | |
25826 | return $val; | |
25827 | } | |
25828 | ||
25829 | sub STORE { | |
25830 | my ($self,$field,$newval) = @_; | |
25831 | my $member_func = "vectorc::Vector_${field}_set"; | |
25832 | if (exists $BLESSEDMEMBERS{$field}) { | |
25833 | &$member_func($self,tied(%{$newval})); | |
25834 | } else { | |
25835 | &$member_func($self,$newval); | |
25836 | } | |
25837 | } | |
25838 | </PRE> | |
25839 | </DIV> | |
25840 | <P> Each structure or class is mapped into a Perl package of the same | |
25841 | name. The C++ constructors and destructors are mapped into constructors | |
25842 | and destructors for the package and are always named "new" and | |
25843 | "DESTROY". The constructor always returns a tied hash table. This hash | |
25844 | table is used to access the member variables of a structure in addition | |
25845 | to being able to invoke member functions. The <TT>%OWNER</TT> and <TT> | |
25846 | %BLESSEDMEMBERS</TT> hash tables are used internally and described | |
25847 | shortly.</P> | |
25848 | <P> To use our new proxy class we can simply do the following:</P> | |
25849 | <DIV class="code"> | |
25850 | <PRE> | |
25851 | # Perl code using Vector class | |
25852 | $v = new Vector(2,3,4); | |
25853 | $w = Vector->new(-1,-2,-3); | |
25854 | ||
25855 | # Assignment of a single member | |
25856 | $v->{x} = 7.5; | |
25857 | ||
25858 | # Assignment of all members | |
25859 | %$v = ( x=>3, | |
25860 | y=>9, | |
25861 | z=>-2); | |
25862 | ||
25863 | # Reading members | |
25864 | $x = $v->{x}; | |
25865 | ||
25866 | # Destruction | |
25867 | $v->DESTROY(); | |
25868 | ||
25869 | </PRE> | |
25870 | </DIV> | |
25871 | <H3><A name="Perl5_nn42"></A>23.9.3 Object Ownership</H3> | |
25872 | <P> In order for proxy classes to work properly, it is necessary for | |
25873 | Perl to manage some mechanism of object ownership. Here's the crux of | |
25874 | the problem---suppose you had a function like this :</P> | |
25875 | <DIV class="code"> | |
25876 | <PRE> | |
25877 | Vector *Vector_get(Vector *v, int index) { | |
25878 | return &v[i]; | |
25879 | } | |
25880 | </PRE> | |
25881 | </DIV> | |
25882 | <P> This function takes a Vector pointer and returns a pointer to | |
25883 | another Vector. Such a function might be used to manage arrays or lists | |
25884 | of vectors (in C). Now contrast this function with the constructor for | |
25885 | a Vector object :</P> | |
25886 | <DIV class="code"> | |
25887 | <PRE> | |
25888 | Vector *new_Vector(double x, double y, double z) { | |
25889 | Vector *v; | |
25890 | v = new Vector(x,y,z); // Call C++ constructor | |
25891 | return v; | |
25892 | } | |
25893 | </PRE> | |
25894 | </DIV> | |
25895 | <P> Both functions return a Vector, but the constructor is returning a | |
25896 | brand-new Vector while the other function is returning a Vector that | |
25897 | was already created (hopefully). In Perl, both vectors will be | |
25898 | indistinguishable---clearly a problem considering that we would | |
25899 | probably like the newly created Vector to be destroyed when we are done | |
25900 | with it.</P> | |
25901 | <P> To manage these problems, each class contains two methods that | |
25902 | access an internal hash table called <TT>%OWNER</TT>. This hash keeps a | |
25903 | list of all of the objects that Perl knows that it has created. This | |
25904 | happens in two cases: (1) when the constructor has been called, and (2) | |
25905 | when a function implicitly creates a new object (as is done when SWIG | |
25906 | needs to return a complex datatype by value). When the destructor is | |
25907 | invoked, the Perl proxy class module checks the <TT>%OWNER</TT> hash to | |
25908 | see if Perl created the object. If so, the C/C++ destructor is invoked. | |
25909 | If not, we simply destroy the Perl object and leave the underlying C | |
25910 | object alone (under the assumption that someone else must have created | |
25911 | it).</P> | |
25912 | <P> This scheme works remarkably well in practice but it isn't | |
25913 | foolproof. In fact, it will fail if you create a new C object in Perl, | |
25914 | pass it on to a C function that remembers the object, and then destroy | |
25915 | the corresponding Perl object (this situation turns out to come up | |
25916 | frequently when constructing objects like linked lists and trees). When | |
25917 | C takes possession of an object, you can change Perl's owership by | |
25918 | simply deleting the object from the <TT>%OWNER</TT> hash. This is done | |
25919 | using the <TT>DISOWN</TT> method.</P> | |
25920 | <DIV class="code"> | |
25921 | <PRE> | |
25922 | # Perl code to change ownership of an object | |
25923 | $v = new Vector(x,y,z); | |
25924 | $v->DISOWN(); | |
25925 | </PRE> | |
25926 | </DIV> | |
25927 | <P> To acquire ownership of an object, the <TT>ACQUIRE</TT> method can | |
25928 | be used.</P> | |
25929 | <DIV class="code"> | |
25930 | <PRE> | |
25931 | # Given Perl ownership of a file | |
25932 | $u = Vector_get($v); | |
25933 | $u->ACQUIRE(); | |
25934 | ||
25935 | </PRE> | |
25936 | </DIV> | |
25937 | <P> As always, a little care is in order. SWIG does not provide | |
25938 | reference counting, garbage collection, or advanced features one might | |
25939 | find in sophisticated languages.</P> | |
25940 | <H3><A name="Perl5_nn43"></A>23.9.4 Nested Objects</H3> | |
25941 | <P> Suppose that we have a new object that looks like this :</P> | |
25942 | <DIV class="code"> | |
25943 | <PRE> | |
25944 | struct Particle { | |
25945 | Vector r; | |
25946 | Vector v; | |
25947 | Vector f; | |
25948 | int type; | |
25949 | } | |
25950 | ||
25951 | </PRE> | |
25952 | </DIV> | |
25953 | <P> In this case, the members of the structure are complex objects that | |
25954 | have already been encapsulated in a Perl proxy class. To handle these | |
25955 | correctly, we use the <TT>%BLESSEDMEMBERS</TT> hash which would look | |
25956 | like this (along with some supporting code) :</P> | |
25957 | <DIV class="code"> | |
25958 | <PRE> | |
25959 | package Particle; | |
25960 | ... | |
25961 | %BLESSEDMEMBERS = ( | |
25962 | r => `Vector', | |
25963 | v => `Vector', | |
25964 | f => `Vector', | |
25965 | ); | |
25966 | ||
25967 | </PRE> | |
25968 | </DIV> | |
25969 | <P> When fetching members from the structure, <TT>%BLESSEDMEMBERS</TT> | |
25970 | is checked. If the requested field is present, we create a tied-hash | |
25971 | table and return it. If not, we just return the corresponding member | |
25972 | unmodified.</P> | |
25973 | <P> This implementation allows us to operate on nested structures as | |
25974 | follows :</P> | |
25975 | <DIV class="code"> | |
25976 | <PRE> | |
25977 | # Perl access of nested structure | |
25978 | $p = new Particle(); | |
25979 | $p->{f}->{x} = 0.0; | |
25980 | %${$p->{v}} = ( x=>0, y=>0, z=>0); | |
25981 | </PRE> | |
25982 | </DIV> | |
25983 | <H3><A name="Perl5_nn44"></A>23.9.5 Proxy Functions</H3> | |
25984 | <P> When functions take arguments involving a complex object, it is | |
25985 | sometimes necessary to write a proxy function. For example :</P> | |
25986 | <DIV class="code"> | |
25987 | <PRE> | |
25988 | double dot_product(Vector *v1, Vector *v2); | |
25989 | </PRE> | |
25990 | </DIV> | |
25991 | <P> Since Vector is an object already wrapped into a proxy class, we | |
25992 | need to modify this function to accept arguments that are given in the | |
25993 | form of tied hash tables. This is done by creating a Perl function like | |
25994 | this :</P> | |
25995 | <DIV class="code"> | |
25996 | <PRE> | |
25997 | sub dot_product { | |
25998 | my @args = @_; | |
25999 | $args[0] = tied(%{$args[0]}); # Get the real pointer values | |
26000 | $args[1] = tied(%{$args[1]}); | |
26001 | my $result = vectorc::dot_product(@args); | |
26002 | return $result; | |
26003 | } | |
26004 | </PRE> | |
26005 | </DIV> | |
26006 | <P> This function replaces the original function, but operates in an | |
26007 | identical manner.</P> | |
26008 | <H3><A name="Perl5_nn45"></A>23.9.6 Inheritance</H3> | |
26009 | <P> Simple C++ inheritance is handled using the Perl <TT>@ISA</TT> array | |
26010 | in each class package. For example, if you have the following interface | |
26011 | file :</P> | |
26012 | <DIV class="code"> | |
26013 | <PRE> | |
26014 | // shapes.i | |
26015 | // SWIG interface file for shapes class | |
26016 | %module shapes | |
26017 | %{ | |
26018 | #include "shapes.h" | |
26019 | %} | |
26020 | ||
26021 | class Shape { | |
26022 | public: | |
26023 | virtual double area() = 0; | |
26024 | virtual double perimeter() = 0; | |
26025 | void set_location(double x, double y); | |
26026 | }; | |
26027 | class Circle : public Shape { | |
26028 | public: | |
26029 | Circle(double radius); | |
26030 | ~Circle(); | |
26031 | double area(); | |
26032 | double perimeter(); | |
26033 | }; | |
26034 | class Square : public Shape { | |
26035 | public: | |
26036 | Square(double size); | |
26037 | ~Square(); | |
26038 | double area(); | |
26039 | double perimeter(); | |
26040 | } | |
26041 | ||
26042 | </PRE> | |
26043 | </DIV> | |
26044 | <P> The resulting, Perl wrapper class will create the following code :</P> | |
26045 | <DIV class="code"> | |
26046 | <PRE> | |
26047 | Package Shape; | |
26048 | @ISA = (shapes); | |
26049 | ... | |
26050 | Package Circle; | |
26051 | @ISA = (shapes Shape); | |
26052 | ... | |
26053 | Package Square; | |
26054 | @ISA = (shapes Shape); | |
26055 | ||
26056 | </PRE> | |
26057 | </DIV> | |
26058 | <P> The <TT>@ISA</TT> array determines where to look for methods of a | |
26059 | particular class. In this case, both the <TT>Circle</TT> and <TT>Square</TT> | |
26060 | classes inherit functions from <TT>Shape</TT> so we'll want to look in | |
26061 | the <TT>Shape</TT> base class for them. All classes also inherit from | |
26062 | the top-level module <TT>shapes</TT>. This is because certain common | |
26063 | operations needed to implement proxy classes are implemented only once | |
26064 | and reused in the wrapper code for various classes and structures.</P> | |
26065 | <P> Since SWIG proxy classes are implemented in Perl, it is easy to | |
26066 | subclass from any SWIG generated class. To do this, simply put the name | |
26067 | of a SWIG class in the <TT>@ISA</TT> array for your new class. However, | |
26068 | be forewarned that this is not a trivial problem. In particular, | |
26069 | inheritance of data members is extremely tricky (and I'm not even sure | |
26070 | if it really works).</P> | |
26071 | <H3><A name="Perl5_nn46"></A>23.9.7 Modifying the proxy methods</H3> | |
26072 | <P> It is possible to override the SWIG generated proxy/shadow methods, | |
26073 | using <TT>%feature("shadow")</TT>. It works like all the other <A href="#features"> | |
26074 | %feature directives</A>. Here is a simple example showing how to add | |
26075 | some Perl debug code to the constructor:</P> | |
26076 | <DIV class="code"> | |
26077 | <PRE> | |
26078 | /* Let's make the constructor of the class Square more verbose */ | |
26079 | %feature("shadow") Square(double w) | |
26080 | %{ | |
26081 | sub new { | |
26082 | my $pkg = shift; | |
26083 | my $self = examplec::new_Square(@_); | |
26084 | print STDERR "Constructed an @{[ref($self)]}\n"; | |
26085 | bless $self, $pkg if defined($self); | |
26086 | } | |
26087 | %} | |
26088 | ||
26089 | class Square { | |
26090 | public: | |
26091 | Square(double w); | |
26092 | ... | |
26093 | }; | |
26094 | </PRE> | |
26095 | </DIV><HR NOSHADE> | |
26096 | ||
26097 | <!-- Hand crafted HTML --> | |
26098 | <H1><A name="Php"></A>24 SWIG and PHP4</H1> | |
26099 | ||
26100 | <!-- INDEX --> | |
26101 | <DIV class="sectiontoc"> | |
26102 | <UL> | |
26103 | <LI><A href="#Php_nn1">Generating PHP4 Extensions</A> | |
26104 | <UL> | |
26105 | <LI><A href="#Php_nn1_1">Building a loadable extension</A></LI> | |
26106 | <LI><A href="#Php_nn1_2">Building extensions into PHP</A></LI> | |
26107 | <LI><A href="#Php_nn1_3">Using PHP4 Extensions</A></LI> | |
26108 | </UL> | |
26109 | </LI> | |
26110 | <LI><A href="#Php_nn2">Basic PHP4 interface</A> | |
26111 | <UL> | |
26112 | <LI><A href="#Php_nn2_1">Constants</A></LI> | |
26113 | <LI><A href="#Php_nn2_2">Global Variables</A></LI> | |
26114 | <LI><A href="#Php_nn2_3">Functions</A></LI> | |
26115 | <LI><A href="#Php_nn2_4">Overloading</A></LI> | |
26116 | <LI><A href="#Php_nn2_5">Pointers and References</A></LI> | |
26117 | <LI><A href="#Php_nn2_6">Structures and C++ classes</A> | |
26118 | <UL> | |
26119 | <LI><A href="#Php_nn2_6_1">Using <TT>-noproxy</TT></A></LI> | |
26120 | <LI><A href="#Php_nn2_6_2">Constructors and Destructors</A></LI> | |
26121 | <LI><A href="#Php_nn2_6_3">Static Member Variables</A></LI> | |
26122 | <LI><A href="#Php_nn2_6_4">Static Member Functions</A></LI> | |
26123 | </UL> | |
26124 | </LI> | |
26125 | <LI><A href="#Php_nn2_7">PHP4 Pragmas, Startup and Shutdown code</A></LI> | |
26126 | </UL> | |
26127 | </LI> | |
26128 | </UL> | |
26129 | </DIV> | |
26130 | <!-- INDEX --> | |
26131 | <P><B> Caution: This chapter (and module!) is still under construction</B> | |
26132 | </P> | |
26133 | <P> In this chapter, we discuss SWIG's support of PHP4. The PHP4 module | |
26134 | has been extensively rewritten in release 1.3.26. Although it is | |
26135 | significantly more functional, it still does not implement all the | |
26136 | features available in other languages.</P> | |
26137 | <P> The examples and test cases have been developed with PHP4. Support | |
26138 | for PHP5 at this time is limited to wrapping C libraries or C++ | |
26139 | libraries while using the <TT>-noproxy</TT> flag. This deficiency will | |
26140 | be fixed in a subsequent release of SWIG.</P> | |
26141 | <P> In order to use this module, you will need to have a copy of the PHP | |
26142 | 4.0 (or above) include files to compile the SWIG generated files. You | |
26143 | can find these files by running <TT>'php-config --includes'</TT>. To | |
26144 | test the modules you will need either the php binary or the Apache php | |
26145 | module. If you want to build your extension into php directly (without | |
26146 | having the overhead of loading it into each script), you will need the | |
26147 | complete PHP source tree available.</P> | |
26148 | <H2><A name="Php_nn1"></A>24.1 Generating PHP4 Extensions</H2> | |
26149 | <P> To build a PHP4 extension, run swig using the <TT>-php4</TT> option | |
26150 | as follows :</P> | |
26151 | <DIV class="code"> | |
26152 | <PRE> | |
26153 | swig -php4 example.i | |
26154 | </PRE> | |
26155 | </DIV> | |
26156 | <P> This will produce 3 files example_wrap.c, php_example.h and | |
26157 | example.php. The first file, <TT>example_wrap.c</TT> contains all of | |
26158 | the C code needed to build a PHP4 extension. The second file, <TT> | |
26159 | php_example.h</TT> contains the header information needed to statically | |
26160 | link the extension into PHP. The third file, <TT>example.php</TT> can | |
26161 | be included by php scripts. It attempts to dynamically load the | |
26162 | extension and contains extra php code specified in the interface file.</P> | |
26163 | <P> Swig can generate PHP4 extensions from C++ libraries as well when | |
26164 | given the <TT>-c++</TT> option. The support for C++ is discussed in | |
26165 | more detail in <A href="#Php_nn2_6">section 24.2.6</A>.</P> | |
26166 | <P> To finish building the extension, you have two choices. You can | |
26167 | either build the extension as a separate shared object file which will | |
26168 | then have to be explicitly loaded by each script. Or you can rebuild | |
26169 | the entire php source tree and build the extension into the php | |
26170 | executable/library so it will be available in every script. The first | |
26171 | choice is the default, however it can be changed by passing the | |
26172 | '-phpfull' command line switch to select the second build method.</P> | |
26173 | <H3><A name="Php_nn1_1"></A>24.1.1 Building a loadable extension</H3> | |
26174 | <P> There are two methods to build the extension as a dynamically loaded | |
26175 | module: using standard compilation utilities (make, gcc), or using | |
26176 | PHP4's<EM> phpize</EM> utility.</P> | |
26177 | <P> To build manually, use a compile string similar to this (different | |
26178 | for each OS):</P> | |
26179 | <DIV class="code"> | |
26180 | <PRE> | |
26181 | cc -I.. $(PHPINC) -fpic -c example_wrap.c | |
26182 | cc -shared example_wrap.o -o libexample.so | |
26183 | </PRE> | |
26184 | </DIV> | |
26185 | <P> The <TT>-make</TT> command line argument to swig will generate an | |
26186 | additional file Makefile. This Makefile can usually build the extension | |
26187 | itself (on unix platforms).</P> | |
26188 | <P> If you want to build your extension using the <TT>phpize</TT> | |
26189 | utility, or if you want to build your module into PHP directly, you can | |
26190 | specify the <TT>-phpfull</TT> command line argument to swig.</P> | |
26191 | <P> The <TT>-phpfull</TT> will generate three additional files. The | |
26192 | first extra file, <TT>config.m4</TT> contains the shell code needed to | |
26193 | enable the extension as part of the PHP4 build process. The second | |
26194 | extra file, <TT>Makefile.in</TT> contains the information needed to | |
26195 | build the final Makefile after substitutions. The third and final extra | |
26196 | file, <TT>CREDITS</TT> should contain the credits for the extension.</P> | |
26197 | <P> To build with phpize, after you have run swig you will need to run | |
26198 | the 'phpize' command (installed as part of php) in the same directory. | |
26199 | This re-creates the php build environment in that directory. It also | |
26200 | creates a configure file which includes the shell code from the | |
26201 | config.m4 that was generated by SWIG, this configure script will accept | |
26202 | a command line argument to enable the extension to be run ( by default | |
26203 | the command line argument is --enable-modulename, however you can edit | |
26204 | the config.m4 file before running phpize to accept --with-modulename. | |
26205 | You can also add extra tests in config.m4 to check that a correct | |
26206 | library version is installed or correct header files are included, etc, | |
26207 | but you must edit this file before running phpize. ) If you like SWIG | |
26208 | can generate simple extra tests for libraries and header files for you.</P> | |
26209 | <DIV class="code"> | |
26210 | <PRE> | |
26211 | swig -php4 -phpfull | |
26212 | </PRE> | |
26213 | </DIV> | |
26214 | <P> If you depend on source files not generated by SWIG, before | |
26215 | generating the configure file, you may need to edit the <TT>Makefile.in</TT> | |
26216 | file. This contains the names of the source files to compile (just the | |
26217 | wrapper file by default) and any additional libraries needed to be | |
26218 | linked in. If there are extra C files to compile, you will need to add | |
26219 | them to the Makefile.in, or add the names of libraries if they are | |
26220 | needed. In simple cases SWIG is pretty good at generating a complete | |
26221 | Makefile.in and config.m4 which need no further editing.</P> | |
26222 | <P> You then run the configure script with the command line argument | |
26223 | needed to enable the extension. Then run make, which builds the | |
26224 | extension. The extension object file will be left in the modules sub | |
26225 | directory, you can move it to wherever it is convenient to call from | |
26226 | your php script.</P> | |
26227 | <P> Both the <TT>-make</TT> and <TT>-phpfull</TT> arguments accept | |
26228 | additional optional arguments:</P> | |
26229 | <UL> | |
26230 | <LI><TT>-withincs "<files>"</TT> Adds include files to the config.m4 | |
26231 | file.</LI> | |
26232 | <LI><TT>-withlibs "<files>"</TT> Links the libraries into the shared | |
26233 | object.</LI> | |
26234 | <LI><TT>-withc "<files>"</TT> Compiles and links the named C files into | |
26235 | the shared object.</LI> | |
26236 | <LI><TT>-withcxx "<files>"</TT> Compiles and links the named C++ files | |
26237 | into the shared object,</LI> | |
26238 | <LI><TT>-dlname "<name>"</TT> Changes the name of the generated shared | |
26239 | object.</LI> | |
26240 | </UL> | |
26241 | <H3><A name="Php_nn1_2"></A>24.1.2 Building extensions into PHP</H3> | |
26242 | <P> This method, selected with the <TT>-phpfull</TT> command line | |
26243 | switch, involves rebuilding the entire php source tree. Whilst more | |
26244 | complicated to build, it does mean that the extension is then available | |
26245 | without having to load it in each script.</P> | |
26246 | <P> After running swig with the -phpfull switch, you will be left with a | |
26247 | shockingly similar set of files to the previous build process. However | |
26248 | you will then need to move these files to a subdirectory within the php | |
26249 | source tree, this subdirectory you will need to create under the ext | |
26250 | directory, with the name of the extension ( e.g mkdir | |
26251 | php-4.0.6/ext/modulename .)</P> | |
26252 | <P> After moving the files into this directory, you will need to run the | |
26253 | 'buildall' script in the php source directory. This rebuilds the | |
26254 | configure script and includes the extra command line arguments from the | |
26255 | module you have added.</P> | |
26256 | <P> Before running the generated configure file, you may need to edit | |
26257 | the <TT>Makefile.in</TT>. This contains the names of the source files | |
26258 | to compile ( just the wrapper file by default) and any additional | |
26259 | libraries needed to link in. If there are extra C files to compile you | |
26260 | will need to add them to the Makefile, or add the names of libraries if | |
26261 | they are needed. In most cases <TT>Makefile.in</TT> will be complete, | |
26262 | especially if you make use of <TT>-withlibs</TT> and <TT>-withincs</TT></P> | |
26263 | <DIV class="code"> | |
26264 | <PRE> | |
26265 | swig -php4 -phpfull -withlibs "xapian omquery" --withincs "om.h" | |
26266 | </PRE> | |
26267 | </DIV> | |
26268 | <P> Will include in the config.m4 and Makefile.in search for libxapian.a | |
26269 | or libxapian.so and search for libomquery.a or libomquery.so as well as | |
26270 | a search for om.h</P> | |
26271 | <P> You then need to run the configure command and pass the necessary | |
26272 | command line arguments to enable your module ( by default this is | |
26273 | --enable-modulename, but this can be changed by editing the config.m4 | |
26274 | file in the modules directory before running the buildall script. In | |
26275 | addition, extra tests can be added to the config.m4 file to ensure the | |
26276 | correct libraries and header files are installed.)</P> | |
26277 | <P> Once configure has completed, you can run make to build php. If this | |
26278 | all compiles correctly, you should end up with a php executable/library | |
26279 | which contains your new module. You can test it with a php script which | |
26280 | does not have the 'dl' command as used above.</P> | |
26281 | <H3><A name="Php_nn1_3"></A>24.1.3 Using PHP4 Extensions</H3> | |
26282 | <P> To test the extension from a PHP script, you need to load it first. | |
26283 | You do this by putting the line,</P> | |
26284 | <DIV class="code"> | |
26285 | <PRE> | |
26286 | dl("/path/to/modulename.so"); // Load the module | |
26287 | </PRE> | |
26288 | </DIV> | |
26289 | <P> at the start of each PHP file. SWIG also generates a php module, | |
26290 | which attempts to do the <TT>dl()</TT> call for you:</P> | |
26291 | <DIV class="code"> | |
26292 | <PRE> | |
26293 | include("example.php"); | |
26294 | </PRE> | |
26295 | </DIV> | |
26296 | <H2><A name="Php_nn2"></A>24.2 Basic PHP4 interface</H2> | |
26297 | <P> It is important to understand that PHP uses a single global | |
26298 | namespace into which all symbols from extension modules are loaded. It | |
26299 | is quite possible for names of symbols in one extension module to clash | |
26300 | with other symbols unless care is taken to <TT>%rename</TT> them.</P> | |
26301 | <H3><A name="Php_nn2_1"></A>24.2.1 Constants</H3> | |
26302 | <P> These work in much the same way as in C/C++, constants can be | |
26303 | defined by using either the normal C pre-processor declarations, or the | |
26304 | <TT>%constant</TT> SWIG directive. These will then be available from | |
26305 | your PHP script as a PHP constant, (i.e. no dollar sign is needed to | |
26306 | access them. ) For example, with a swig file like this,</P> | |
26307 | <DIV class="code"> | |
26308 | <PRE> | |
26309 | %module example | |
26310 | ||
26311 | #define PI 3.14159 | |
26312 | ||
26313 | %constant int E = 2.71828 | |
26314 | </PRE> | |
26315 | </DIV> | |
26316 | <P> you can access the constants in your php script like this,</P> | |
26317 | <DIV class="code"> | |
26318 | <PRE> | |
26319 | include("example.php"); | |
26320 | ||
26321 | echo "PI = " . PI . "\n"; | |
26322 | ||
26323 | echo "E = " . E . "\n"; | |
26324 | ||
26325 | </PRE> | |
26326 | </DIV> | |
26327 | <P> There are two peculiarities with using constants in PHP4. The first | |
26328 | is that if you try to use an undeclared constant, it will evaluate to a | |
26329 | string set to the constant's name. For example,</P> | |
26330 | <DIV class="code"> | |
26331 | <PRE> | |
26332 | %module example | |
26333 | ||
26334 | #define EASY_TO_MISPELL 0 | |
26335 | </PRE> | |
26336 | </DIV> | |
26337 | <P> accessed incorrectly in PHP,</P> | |
26338 | <DIV class="code"> | |
26339 | <PRE> | |
26340 | include("example.php"); | |
26341 | ||
26342 | if(EASY_TO_MISPEL) { | |
26343 | .... | |
26344 | } else { | |
26345 | .... | |
26346 | } | |
26347 | ||
26348 | </PRE> | |
26349 | </DIV> | |
26350 | <P> will issue a warning about the undeclared constant, but will then | |
26351 | evaluate it and turn it into a string ('EASY_TO_MISPEL'), which | |
26352 | evaluates to true, rather than the value of the constant which would be | |
26353 | false. This is a feature.</P> | |
26354 | <P> The second 'feature' is that although constants are case sensitive | |
26355 | (by default), you cannot declare a constant twice with alternative | |
26356 | cases. E.g.,</P> | |
26357 | <DIV class="code"> | |
26358 | <PRE> | |
26359 | %module example | |
26360 | ||
26361 | #define TEST Hello | |
26362 | #define Test World | |
26363 | </PRE> | |
26364 | </DIV> | |
26365 | <P> accessed from PHP,</P> | |
26366 | <DIV class="code"> | |
26367 | <PRE> | |
26368 | include("example.php"); | |
26369 | ||
26370 | echo TEST, Test; | |
26371 | </PRE> | |
26372 | </DIV> | |
26373 | <P> will output "Hello Test" rather than "Hello World". This is because | |
26374 | internally, all constants are stored in a hash table by their lower | |
26375 | case name, so 'TEST' and 'Test' will map to the same hash element | |
26376 | ('Test'). But, because we declared them case sensitive, the Zend engine | |
26377 | will test if the case matches with the case the constant was declared | |
26378 | with first.</P> | |
26379 | <P> So, in the example above, the TEST constant was declared first, and | |
26380 | will be stored under the hash element 'test'. The 'Test' constant will | |
26381 | also map to the same hash element 'test', but will not overwrite it. | |
26382 | When called from the script, the TEST constant will again be mapped to | |
26383 | the hash element 'test' so the constant will be retrieved. The case | |
26384 | will then be checked, and will match up, so the value ('Hello') will be | |
26385 | returned. When 'Test' is evaluated, it will also map to the same hash | |
26386 | element 'test'. The same constant will be retrieved, this time though | |
26387 | the case check will fail as 'Test' != 'TEST'. So PHP will assume that | |
26388 | Test is a undeclared constant, and as explained above, will return it | |
26389 | as a string set to the constant name ('Test'). Hence the script above | |
26390 | will print 'Hello Test'. If they were declared non-case sensitive, the | |
26391 | output would be 'Hello Hello', as both point to the same value, without | |
26392 | the case test taking place. ( Apologies, this paragraph needs rewriting | |
26393 | to make some sense. )</P> | |
26394 | <H3><A name="Php_nn2_2"></A>24.2.2 Global Variables</H3> | |
26395 | <P> Because PHP4 does not provide a mechanism to intercept access and | |
26396 | assignment of global variables, global variables are supported through | |
26397 | the use of automatically generated accessor functions.</P> | |
26398 | <DIV class="code"> | |
26399 | <PRE> | |
26400 | %module example; | |
26401 | ||
26402 | %inline %{ | |
26403 | double seki = 2; | |
26404 | void print_seki() { | |
26405 | zend_printf("seki is now %f\n",seki); | |
26406 | } | |
26407 | %} | |
26408 | </PRE> | |
26409 | </DIV> | |
26410 | <P> is accessed as follows:</P> | |
26411 | <DIV class="code"> | |
26412 | <PRE> | |
26413 | include("example.php"); | |
26414 | print seki_get(); | |
26415 | seki_set( seki_get() * 2); # The C variable is now 4. | |
26416 | print seki_get(); | |
26417 | </PRE> | |
26418 | </DIV> | |
26419 | <P> SWIG supports global variables of all C datatypes including pointers | |
26420 | and complex objects. Additional types can be supported by using the <TT> | |
26421 | varinit</TT> typemap.</P> | |
26422 | <P> SWIG honors the <TT>%immutable</TT> modifier by not generating code | |
26423 | for the <TT>_set</TT> method. This provides read-only access to the | |
26424 | variable from the php script. Attempting to access the <TT>_set</TT> | |
26425 | method will result in a php fatal error because the function is | |
26426 | undefined.</P> | |
26427 | <P> At this time SWIG does not support custom accessor methods.</P> | |
26428 | <H3><A name="Php_nn2_3"></A>24.2.3 Functions</H3> | |
26429 | <P> C functions are converted into PHP functions. Default/optional | |
26430 | arguments are also allowed. An interface file like this :</P> | |
26431 | <DIV class="code"> | |
26432 | <PRE> | |
26433 | %module example | |
26434 | int foo(int a); | |
26435 | double bar(double, double b = 3.0); | |
26436 | ... | |
26437 | </PRE> | |
26438 | </DIV> | |
26439 | <P> Will be accessed in PHP like this :</P> | |
26440 | <DIV class="code"> | |
26441 | <PRE> | |
26442 | include("example.php"); | |
26443 | $a = foo(2); | |
26444 | $b = bar(3.5, -1.5); | |
26445 | $c = bar(3.5); # Use default argument for 2nd parameter | |
26446 | ||
26447 | </PRE> | |
26448 | </DIV> | |
26449 | <P> Because PHP4 is a dynamically typed language, the default typemaps | |
26450 | used for simple types will attempt to coerce the arguments into the | |
26451 | appropriate type. That is the following invocations are equivalent:</P> | |
26452 | <DIV class="code"> | |
26453 | <PRE> | |
26454 | $a = foo(2); | |
26455 | $a = foo("2"); | |
26456 | $a = foo(2.0); | |
26457 | </PRE> | |
26458 | </DIV> | |
26459 | <P> Functions are invoked using pass by value semantics like all of PHP. | |
26460 | This means the conversion which automatically takes place when invoking | |
26461 | a swig wrapped method does not change the native type of the argument | |
26462 | variable.</P> | |
26463 | <DIV class="code"> | |
26464 | <PRE> | |
26465 | $s = "2 A string representing two"; | |
26466 | $a = foo($s); # invokes 'foo(2)'; | |
26467 | print $s; # The value of $s was not changed. | |
26468 | </PRE> | |
26469 | </DIV> | |
26470 | <H3><A name="Php_nn2_4"></A>24.2.4 Overloading</H3> | |
26471 | <P> Although PHP4 does not support overloading functions natively, swig | |
26472 | will generate dispatch functions which will use <TT>%typecheck</TT> | |
26473 | typemaps to allow overloading. This dispatch function's operation and | |
26474 | precedence is described in <A href="#SWIGPlus_overloaded_methods"> | |
26475 | Wrapping Overloaded Functions and Methods</A>.</P> | |
26476 | <P> Because PHP4 is a dynamically typed language, simple values can be | |
26477 | silently converted from one type to another. For example, integers, | |
26478 | doubles and strings silently convert to each other depending on | |
26479 | context. This situation make overloading slightly problematic because | |
26480 | given the following function:</P> | |
26481 | <DIV class="code"> | |
26482 | <PRE> | |
26483 | void doit( int i ); | |
26484 | void doit( double i ); | |
26485 | </PRE> | |
26486 | </DIV> | |
26487 | <P> it is questionable which to invoke when <TT>doit("2");</TT> is used | |
26488 | in PHP. The string <TT>"2"</TT> simultaneously represents the integer <TT> | |
26489 | 2</TT> and the double <TT>2.0</TT>.</P> | |
26490 | <P> In order to provide the most natural experience to PHP programmers, | |
26491 | the default <TT>%typecheck</TT> implemented in <TT>php4.swg</TT> allows | |
26492 | any simple type (integer, double, string) in PHP to be used for any | |
26493 | simple C type (int, double, char *). The function selected then depends | |
26494 | only on the argument type precedence defined by SWIG.</P> | |
26495 | <P> It should be noted that <TT>SWIGTYPE</TT> references and pointers | |
26496 | will not be silently converted. So these two functions:</P> | |
26497 | <DIV class="code"> | |
26498 | <PRE> | |
26499 | void doit( const Vector & ); | |
26500 | void doit( int i ); | |
26501 | </PRE> | |
26502 | </DIV> | |
26503 | <P> Cause less confusion and <TT>doit("2");</TT> will invoke the | |
26504 | function taking the integer argument.</P> | |
26505 | <H3><A name="Php_nn2_5"></A>24.2.5 Pointers and References</H3> | |
26506 | <P> Pointers to C/C++ objects are<B> no longer</B> represented as | |
26507 | character strings such as: <TT>_523d3f4_Circle_p</TT>, instead they are | |
26508 | represented as PHP resources, rather like MySQL connection handles.</P> | |
26509 | <P> There are multiple ways to wrap pointers to simple types. Given the | |
26510 | following C method:</P> | |
26511 | <DIV class="code"> | |
26512 | <PRE> | |
26513 | void add( int *in1, int *in2, int *result); | |
26514 | </PRE> | |
26515 | </DIV> | |
26516 | <P> One can include<B> cpointer.i</B> to generate PHP wrappers to <TT> | |
26517 | int *</TT>.</P> | |
26518 | <DIV class="code"> | |
26519 | <PRE> | |
26520 | %module example | |
26521 | %include cpointer.i | |
26522 | %pointer_functions(int,intp) | |
26523 | ||
26524 | void add( int *in1, int *in2, int *result); | |
26525 | </PRE> | |
26526 | </DIV> | |
26527 | <P> This will result in the following usage in PHP:</P> | |
26528 | <DIV class="code"> | |
26529 | <PRE> | |
26530 | <?php | |
26531 | ||
26532 | include("example.php"); | |
26533 | ||
26534 | $in1=copy_intp(3); | |
26535 | $in2=copy_intp(5); | |
26536 | $result=new_intp(); | |
26537 | ||
26538 | add( $in1, $in2, $result ); | |
26539 | ||
26540 | echo "The sum " . intp_value($in1) . " + " . intp_value($in2) . " = " . intp_value( $result) . "\n"; | |
26541 | ?> | |
26542 | </PRE> | |
26543 | </DIV> | |
26544 | <P> An alternative would be to use the include<B> typemaps.i</B> which | |
26545 | defines named typemaps for INPUT, OUTPUT and INOUT variables. One needs | |
26546 | to either <TT>%apply</TT> the appropriate typemap or adjust the | |
26547 | parameter names as appropriate.</P> | |
26548 | <DIV class="code"> | |
26549 | <PRE> | |
26550 | %module example | |
26551 | %include typemaps.i | |
26552 | ||
26553 | void add( int *INPUT, int *INPUT, int *OUTPUT); | |
26554 | ||
26555 | </PRE> | |
26556 | </DIV> | |
26557 | <P> This will result in the following usage in PHP:</P> | |
26558 | <DIV class="code"> | |
26559 | <PRE> | |
26560 | <?php | |
26561 | ||
26562 | include("example.php"); | |
26563 | ||
26564 | $in1 = 3; | |
26565 | $in2 = 5; | |
26566 | $result= add($in1,$in2); # Note using variables for the input is unnecessary. | |
26567 | ||
26568 | echo "The sum $in1 + $in2 = $result\n"; | |
26569 | ?> | |
26570 | </PRE> | |
26571 | </DIV> | |
26572 | <P> Because PHP has a native concept of reference, it may seem more | |
26573 | natural to the PHP developer to use references to pass pointers. To | |
26574 | enable this, one needs to include<B> phppointers.i</B> which defines | |
26575 | the named typemap REFERENCE.</P> | |
26576 | <DIV class="code"> | |
26577 | <PRE> | |
26578 | %module example | |
26579 | %include phppointers.i | |
26580 | ||
26581 | void add( int *REF, int *REF, int *REF); | |
26582 | ||
26583 | </PRE> | |
26584 | </DIV> | |
26585 | <P> This will result in the following usage in PHP:</P> | |
26586 | <DIV class="code"> | |
26587 | <PRE> | |
26588 | <?php | |
26589 | ||
26590 | include("example.php"); | |
26591 | ||
26592 | $in1 = 3; | |
26593 | $in2 = 5; | |
26594 | $result = 0; | |
26595 | add(&$in1,&$in2,&$result); | |
26596 | ||
26597 | echo "The sum $in1 + $in2 = $result\n"; | |
26598 | ?> | |
26599 | </PRE> | |
26600 | </DIV> | |
26601 | <P> It is important to note that a php variable which is NULL when | |
26602 | passed by reference would end up passing a NULL pointer into the | |
26603 | function. In PHP, an unassigned variable (ie first reference is not | |
26604 | assigned) is NULL. In the above example, if any of the three variables | |
26605 | had not been assigned, a NULL pointer would have been passed into <TT> | |
26606 | add</TT>. Depending on the implementation of the function, this may or | |
26607 | may not be a good thing.</P> | |
26608 | <P> We chose to allow passing NULL pointers into functions because that | |
26609 | is sometimes required in C libraries. A NULL pointer can be created in | |
26610 | PHP in a number of ways: by using <TT>unset</TT> on an existing | |
26611 | variable, or assigning <TT>NULL</TT> to a variable.</P> | |
26612 | <H3><A name="Php_nn2_6"></A>24.2.6 Structures and C++ classes</H3> | |
26613 | <P> By default, SWIG represents structs and C++ classes using a PHP4 | |
26614 | class. The PHP4 class is implemented entirely using the Zend C API so | |
26615 | no additional php code is generated.</P> | |
26616 | <P> This interface file</P> | |
26617 | <DIV class="code"> | |
26618 | <PRE> | |
26619 | %module vector | |
26620 | ||
26621 | class Vector { | |
26622 | public: | |
26623 | double x,y,z; | |
26624 | Vector(); | |
26625 | ~Vector(); | |
26626 | double magnitude(); | |
26627 | }; | |
26628 | ||
26629 | struct Complex { | |
26630 | double re, im; | |
26631 | }; | |
26632 | </PRE> | |
26633 | </DIV> | |
26634 | <P> Would be used in the following way:</P> | |
26635 | <DIV class="code"> | |
26636 | <PRE> | |
26637 | <?php | |
26638 | require "vector.php"; | |
26639 | ||
26640 | $v = new Vector(); | |
26641 | $v->x = 3; | |
26642 | $v->y = 4; | |
26643 | $v->z = 5; | |
26644 | ||
26645 | echo "Magnitude of ($v->x,$v->y,$v->z) = " . $v->magnitude() . "\n"; | |
26646 | ||
26647 | $v = NULL; # destructor called. | |
26648 | ||
26649 | $c = new Complex(); | |
26650 | ||
26651 | $c->re = 0; | |
26652 | $c->im = 0; | |
26653 | ||
26654 | # $c destructor called when $c goes out of scope. | |
26655 | ?> | |
26656 | </PRE> | |
26657 | </DIV> | |
26658 | <P> Member variables and methods are accessed using the <TT>-></TT> | |
26659 | operator.</P> | |
26660 | <H4><A name="Php_nn2_6_1"></A>24.2.6.1 Using <TT>-noproxy</TT></H4> | |
26661 | <P> The <TT>-noproxy</TT> option flattens the object structure and | |
26662 | generates collections of named functions. The above example results in | |
26663 | the following PHP functions:</P> | |
26664 | <DIV class="code"> | |
26665 | <PRE> | |
26666 | new_Vector(); | |
26667 | Vector_x_set($obj,$d); | |
26668 | Vector_x_get($obj); | |
26669 | Vector_y_set($obj,$d); | |
26670 | Vector_y_get($obj); | |
26671 | Vector_z_set($obj,$d); | |
26672 | Vector_z_get($obj); | |
26673 | Vector_magnitude($obj); | |
26674 | new_Complex(); | |
26675 | Complex_re_set($obj,$d); | |
26676 | Complex_re_get($obj); | |
26677 | Complex_im_set($obj,$d); | |
26678 | Complex_im_get($obj); | |
26679 | </PRE> | |
26680 | </DIV> | |
26681 | <H4><A name="Php_nn2_6_2"></A>24.2.6.2 Constructors and Destructors</H4> | |
26682 | <P> The constructor is called when <TT>new Object()</TT> (or <TT> | |
26683 | new_Object()</TT> if using <TT>-noproxy</TT>) is used to create an | |
26684 | instance of the object. If multiple constructors are defined for an | |
26685 | object, function overloading will be used to determine which | |
26686 | constructor to execute.</P> | |
26687 | <P> Because PHP4 uses reference counting to manage resources, simple | |
26688 | assignment of one variable to another such as:</P> | |
26689 | <DIV class="code"> | |
26690 | <PRE> | |
26691 | $ref = $v; | |
26692 | </PRE> | |
26693 | </DIV> | |
26694 | <P> causes the symbol <TT>$ref</TT> to refer to the same underlying | |
26695 | object as <TT>$v</TT>. This does not result in a call to the C++ copy | |
26696 | constructor or copy assignment operator.</P> | |
26697 | <P> One can force execution of the copy constructor by using:</P> | |
26698 | <DIV class="code"> | |
26699 | <PRE> | |
26700 | $o_copy = new Object($o); | |
26701 | </PRE> | |
26702 | </DIV> | |
26703 | <P> Destructors are automatically called when all variables referencing | |
26704 | the instance are reassigned or go out of scope. The destructor is not | |
26705 | available to be called manually. To force a destructor to be called the | |
26706 | programmer can either reassign the variable or call <TT>unset($v)</TT></P> | |
26707 | <H4><A name="Php_nn2_6_3"></A>24.2.6.3 Static Member Variables</H4> | |
26708 | <P> Class variables are not supported in PHP. Static member variables | |
26709 | are therefore accessed using a class function with the same name, which | |
26710 | returns the current value of the class variable. For example</P> | |
26711 | <DIV class="code"> | |
26712 | <PRE> | |
26713 | %module example | |
26714 | ||
26715 | class Ko { | |
26716 | static int threats; | |
26717 | }; | |
26718 | ||
26719 | </PRE> | |
26720 | </DIV> | |
26721 | <P> would be accessed in PHP as,</P> | |
26722 | <DIV class="code"> | |
26723 | <PRE> | |
26724 | include("example.php"); | |
26725 | ||
26726 | echo "There has now been " . Ko::threats() . " threats\n"; | |
26727 | ||
26728 | </PRE> | |
26729 | </DIV> | |
26730 | <P> To set the static member variable, pass the value as the argument to | |
26731 | the class function, e.g.</P> | |
26732 | <DIV class="code"> | |
26733 | <PRE> | |
26734 | ||
26735 | Ko::threats(10); | |
26736 | ||
26737 | echo "There has now been " . Ko::threats() . " threats\n"; | |
26738 | ||
26739 | </PRE> | |
26740 | </DIV> | |
26741 | <H4><A name="Php_nn2_6_4"></A>24.2.6.4 Static Member Functions</H4> | |
26742 | <P> Class functions are supported in PHP using the <TT>class::function()</TT> | |
26743 | syntax. For example</P> | |
26744 | <DIV class="code"> | |
26745 | <PRE> | |
26746 | %module example | |
26747 | class Ko { | |
26748 | static void threats(); | |
26749 | }; | |
26750 | </PRE> | |
26751 | </DIV> would be executed in PHP as,<DIV class="code"> | |
26752 | <PRE> | |
26753 | include("example.php"); | |
26754 | Ko::threats(); | |
26755 | </PRE> | |
26756 | </DIV> | |
26757 | <H3><A name="Php_nn2_7"></A>24.2.7 PHP4 Pragmas, Startup and Shutdown | |
26758 | code</H3> | |
26759 | <P> To place PHP code in the generated "example.php" file one can use | |
26760 | the<B> code</B> pragma. The code is inserted after loading the shared | |
26761 | object.</P> | |
26762 | <DIV class="code"> | |
26763 | <PRE> | |
26764 | %module example | |
26765 | %pragma(php4) code=" | |
26766 | # This code is inserted into example.php | |
26767 | echo \"example.php execution\\n\"; | |
26768 | " | |
26769 | </PRE> | |
26770 | </DIV> | |
26771 | <P> Results in the following in "example.php"</P> | |
26772 | <DIV class="code"> | |
26773 | <PRE> | |
26774 | # This code is inserted into example.php | |
26775 | echo "example.php execution\n"; | |
26776 | </PRE> | |
26777 | </DIV> | |
26778 | <P> The<B> include</B> pragma is a short cut to add include statements | |
26779 | to the example.php file.</P> | |
26780 | <DIV class="code"> | |
26781 | <PRE> | |
26782 | %module example | |
26783 | %pragma(php4) code=" | |
26784 | include \"include.php\"; | |
26785 | " | |
26786 | %pragma(php) include="include.php" // equivalent. | |
26787 | </PRE> | |
26788 | </DIV> | |
26789 | <P> The<B> phpinfo</B> pragma inserts code in the <TT>PHP_MINFO_FUNCTION</TT> | |
26790 | which is called from PHP's phpinfo() function.</P> | |
26791 | <DIV class="code"> | |
26792 | <PRE> | |
26793 | %module example; | |
26794 | %pragma(php4) phpinfo=" | |
26795 | zend_printf("An example of PHP support through SWIG\n"); | |
26796 | php_info_print_table_start(); | |
26797 | php_info_print_table_header(2, \"Directive\", \"Value\"); | |
26798 | php_info_print_table_row(2, \"Example support\", \"enabled\"); | |
26799 | php_info_print_table_end(); | |
26800 | " | |
26801 | </PRE> | |
26802 | </DIV> | |
26803 | <P> To insert code into the <TT>PHP_MINIT_FUNCTION</TT>, one can use | |
26804 | either <TT>%init</TT> or <TT>%minit</TT>.</P> | |
26805 | <DIV class="code"> | |
26806 | <PRE> | |
26807 | %module example; | |
26808 | %init { | |
26809 | zend_printf("Inserted into PHP_MINIT_FUNCTION\n"); | |
26810 | } | |
26811 | %minit { | |
26812 | zend_printf("Inserted into PHP_MINIT_FUNCTION\n"); | |
26813 | } | |
26814 | </PRE> | |
26815 | </DIV> | |
26816 | <P> To insert code into the <TT>PHP_MSHUTDOWN_FUNCTION</TT>, one can use | |
26817 | either <TT>%init</TT> or <TT>%minit</TT>.</P> | |
26818 | <DIV class="code"> | |
26819 | <PRE> | |
26820 | %module example; | |
26821 | %mshutdown { | |
26822 | zend_printf("Inserted into PHP_MSHUTDOWN_FUNCTION\n"); | |
26823 | } | |
26824 | </PRE> | |
26825 | </DIV> | |
26826 | <P> The <TT>%rinit</TT> and <TT>%rshutdown</TT> statements insert code | |
26827 | into the request init and shutdown code respectively.</P> | |
26828 | <HR NOSHADE> | |
26829 | <H1><A name="Pike"></A>25 SWIG and Pike</H1> | |
26830 | ||
26831 | <!-- INDEX --> | |
26832 | <DIV class="sectiontoc"> | |
26833 | <UL> | |
26834 | <LI><A href="#Pike_nn2">Preliminaries</A> | |
26835 | <UL> | |
26836 | <LI><A href="#Pike_nn3">Running SWIG</A></LI> | |
26837 | <LI><A href="#Pike_nn4">Getting the right header files</A></LI> | |
26838 | <LI><A href="#Pike_nn5">Using your module</A></LI> | |
26839 | </UL> | |
26840 | </LI> | |
26841 | <LI><A href="#Pike_nn6">Basic C/C++ Mapping</A> | |
26842 | <UL> | |
26843 | <LI><A href="#Pike_nn7">Modules</A></LI> | |
26844 | <LI><A href="#Pike_nn8">Functions</A></LI> | |
26845 | <LI><A href="#Pike_nn9">Global variables</A></LI> | |
26846 | <LI><A href="#Pike_nn10">Constants and enumerated types</A></LI> | |
26847 | <LI><A href="#Pike_nn11">Constructors and Destructors</A></LI> | |
26848 | <LI><A href="#Pike_nn12">Static Members</A></LI> | |
26849 | </UL> | |
26850 | </LI> | |
26851 | </UL> | |
26852 | </DIV> | |
26853 | <!-- INDEX --> | |
26854 | <P> This chapter describes SWIG support for Pike. As of this writing, | |
26855 | the SWIG Pike module is still under development and is not considered | |
26856 | ready for prime time. The Pike module is being developed against the | |
26857 | Pike 7.4.10 release and may not be compatible with previous versions of | |
26858 | Pike.</P> | |
26859 | <P> This chapter covers most SWIG features, but certain low-level | |
26860 | details are covered in less depth than in earlier chapters. At the very | |
26861 | least, make sure you read the "<A href="#SWIG">SWIG Basics</A>" | |
26862 | chapter. | |
26863 | <BR></P> | |
26864 | <H2><A name="Pike_nn2"></A>25.1 Preliminaries</H2> | |
26865 | <H3><A name="Pike_nn3"></A>25.1.1 Running SWIG</H3> | |
26866 | <P> Suppose that you defined a SWIG module such as the following:</P> | |
26867 | <DIV class="code"> | |
26868 | <PRE>%module example | |
26869 | <BR> | |
26870 | <BR>%{ | |
26871 | <BR>#include "example.h" | |
26872 | <BR>%} | |
26873 | <BR> | |
26874 | <BR>int fact(int n); | |
26875 | <BR></PRE> | |
26876 | </DIV> | |
26877 | <P> To build a C extension module for Pike, run SWIG using the <TT>-pike</TT> | |
26878 | option :</P> | |
26879 | <DIV class="code"> | |
26880 | <PRE>$ <B>swig -pike example.i</B> | |
26881 | <BR></PRE> | |
26882 | </DIV> | |
26883 | <P> If you're building a C++ extension, be sure to add the <TT>-c++</TT> | |
26884 | option:</P> | |
26885 | <DIV class="code"> | |
26886 | <PRE>$ <B>swig -c++ -pike example.i</B> | |
26887 | <BR></PRE> | |
26888 | </DIV> | |
26889 | <P> This creates a single source file named <TT>example_wrap.c</TT> (or <TT> | |
26890 | example_wrap.cxx</TT>, if you ran SWIG with the <TT>-c++</TT> option). | |
26891 | The SWIG-generated source file contains the low-level wrappers that | |
26892 | need to be compiled and linked with the rest of your C/C++ application | |
26893 | to create an extension module.</P> | |
26894 | <P> The name of the wrapper file is derived from the name of the input | |
26895 | file. For example, if the input file is <TT>example.i</TT>, the name of | |
26896 | the wrapper file is <TT>example_wrap.c</TT>. To change this, you can | |
26897 | use the <TT>-o</TT> option:</P> | |
26898 | <DIV class="code"> | |
26899 | <PRE>$ <B>swig -pike -o pseudonym.c example.i</B> | |
26900 | <BR></PRE> | |
26901 | </DIV> | |
26902 | <H3><A name="Pike_nn4"></A>25.1.2 Getting the right header files</H3> | |
26903 | <P> In order to compile the C/C++ wrappers, the compiler needs to know | |
26904 | the path to the Pike header files. These files are usually contained in | |
26905 | a directory such as</P> | |
26906 | <DIV class="code"> | |
26907 | <PRE>/usr/local/pike/7.4.10/include/pike | |
26908 | <BR></PRE> | |
26909 | </DIV> | |
26910 | <P> There doesn't seem to be any way to get Pike itself to reveal the | |
26911 | location of these files, so you may need to hunt around for them. | |
26912 | You're looking for files with the names <TT>global.h</TT>, <TT> | |
26913 | program.h</TT> and so on.</P> | |
26914 | <H3><A name="Pike_nn5"></A>25.1.3 Using your module</H3> | |
26915 | <P> To use your module, simply use Pike's <TT>import</TT> statement:</P> | |
26916 | <DIV class="code"> | |
26917 | <PRE> | |
26918 | $ <B>pike</B> | |
26919 | Pike v7.4 release 10 running Hilfe v3.5 (Incremental Pike Frontend) | |
26920 | > <B>import example;</B> | |
26921 | > <B>fact(4);</B> | |
26922 | (1) Result: 24 | |
26923 | </PRE> | |
26924 | </DIV> | |
26925 | <H2><A name="Pike_nn6"></A>25.2 Basic C/C++ Mapping</H2> | |
26926 | <H3><A name="Pike_nn7"></A>25.2.1 Modules</H3> | |
26927 | <P> All of the code for a given SWIG module is wrapped into a single | |
26928 | Pike module. Since the name of the shared library that implements your | |
26929 | module ultimately determines the module's name (as far as Pike is | |
26930 | concerned), SWIG's <TT>%module</TT> directive doesn't really have any | |
26931 | significance.</P> | |
26932 | <H3><A name="Pike_nn8"></A>25.2.2 Functions</H3> | |
26933 | <P> Global functions are wrapped as new Pike built-in functions. For | |
26934 | example,</P> | |
26935 | <DIV class="code"> | |
26936 | <PRE> | |
26937 | %module example | |
26938 | ||
26939 | int fact(int n); | |
26940 | </PRE> | |
26941 | </DIV> | |
26942 | <P> creates a new built-in function <TT>example.fact(n)</TT> that works | |
26943 | exactly as you'd expect it to:</P> | |
26944 | <DIV class="code"> | |
26945 | <PRE> | |
26946 | > <B>import example;</B> | |
26947 | > <B>fact(4);</B> | |
26948 | (1) Result: 24 | |
26949 | </PRE> | |
26950 | </DIV> | |
26951 | <H3><A name="Pike_nn9"></A>25.2.3 Global variables</H3> | |
26952 | <P> Global variables are currently wrapped as a pair of of functions, | |
26953 | one to get the current value of the variable and another to set it. For | |
26954 | example, the declaration</P> | |
26955 | <DIV class="code"> | |
26956 | <PRE> | |
26957 | %module example | |
26958 | ||
26959 | double Foo; | |
26960 | </PRE> | |
26961 | </DIV> | |
26962 | <P> will result in two functions, <TT>Foo_get()</TT> and <TT>Foo_set()</TT> | |
26963 | :</P> | |
26964 | <DIV class="code"> | |
26965 | <PRE> | |
26966 | > <B>import example;</B> | |
26967 | > <B>Foo_get();</B> | |
26968 | (1) Result: 3.000000 | |
26969 | > <B>Foo_set(3.14159);</B> | |
26970 | (2) Result: 0 | |
26971 | > <B>Foo_get();</B> | |
26972 | (3) Result: 3.141590 | |
26973 | </PRE> | |
26974 | </DIV> | |
26975 | <H3><A name="Pike_nn10"></A>25.2.4 Constants and enumerated types</H3> | |
26976 | <P> Enumerated types in C/C++ declarations are wrapped as Pike | |
26977 | constants, not as Pike enums.</P> | |
26978 | <H3><A name="Pike_nn11"></A>25.2.5 Constructors and Destructors</H3> | |
26979 | <P> Constructors are wrapped as <TT>create()</TT> methods, and | |
26980 | destructors are wrapped as <TT>destroy()</TT> methods, for Pike | |
26981 | classes.</P> | |
26982 | <H3><A name="Pike_nn12"></A>25.2.6 Static Members</H3> | |
26983 | <P> Since Pike doesn't support static methods or data for Pike classes, | |
26984 | static member functions in your C++ classes are wrapped as regular | |
26985 | functions and static member variables are wrapped as pairs of functions | |
26986 | (one to get the value of the static member variable, and another to set | |
26987 | it). The names of these functions are prepended with the name of the | |
26988 | class. For example, given this C++ class declaration:</P> | |
26989 | <DIV class="code"> | |
26990 | <PRE> | |
26991 | class Shape | |
26992 | { | |
26993 | public: | |
26994 | static void print(); | |
26995 | static int nshapes; | |
26996 | }; | |
26997 | </PRE> | |
26998 | </DIV> | |
26999 | <P> SWIG will generate a <TT>Shape_print()</TT> method that invokes the | |
27000 | static <TT>Shape::print()</TT> member function, as well as a pair of | |
27001 | methods, <TT>Shape_nshapes_get()</TT> and <TT>Shape_nshapes_set()</TT>, | |
27002 | to get and set the value of <TT>Shape::nshapes</TT>.</P> | |
27003 | <HR NOSHADE> | |
27004 | <H1><A name="Python"></A>26 SWIG and Python</H1> | |
27005 | ||
27006 | <!-- INDEX --> | |
27007 | <DIV class="sectiontoc"> | |
27008 | <UL> | |
27009 | <LI><A href="#Python_nn2">Overview</A></LI> | |
27010 | <LI><A href="#Python_nn3">Preliminaries</A> | |
27011 | <UL> | |
27012 | <LI><A href="#Python_nn4">Running SWIG</A></LI> | |
27013 | <LI><A href="#Python_nn5">Getting the right header files</A></LI> | |
27014 | <LI><A href="#Python_nn6">Compiling a dynamic module</A></LI> | |
27015 | <LI><A href="#Python_nn7">Using distutils</A></LI> | |
27016 | <LI><A href="#Python_nn8">Static linking</A></LI> | |
27017 | <LI><A href="#Python_nn9">Using your module</A></LI> | |
27018 | <LI><A href="#Python_nn10">Compilation of C++ extensions</A></LI> | |
27019 | <LI><A href="#Python_nn11">Compiling for 64-bit platforms</A></LI> | |
27020 | <LI><A href="#Python_nn12">Building Python Extensions under Windows</A></LI> | |
27021 | </UL> | |
27022 | </LI> | |
27023 | <LI><A href="#Python_nn13">A tour of basic C/C++ wrapping</A> | |
27024 | <UL> | |
27025 | <LI><A href="#Python_nn14">Modules</A></LI> | |
27026 | <LI><A href="#Python_nn15">Functions</A></LI> | |
27027 | <LI><A href="#Python_nn16">Global variables</A></LI> | |
27028 | <LI><A href="#Python_nn17">Constants and enums</A></LI> | |
27029 | <LI><A href="#Python_nn18">Pointers</A></LI> | |
27030 | <LI><A href="#Python_nn19">Structures</A></LI> | |
27031 | <LI><A href="#Python_nn20">C++ classes</A></LI> | |
27032 | <LI><A href="#Python_nn21">C++ inheritance</A></LI> | |
27033 | <LI><A href="#Python_nn22">Pointers, references, values, and arrays</A></LI> | |
27034 | <LI><A href="#Python_nn23">C++ overloaded functions</A></LI> | |
27035 | <LI><A href="#Python_nn24">C++ operators</A></LI> | |
27036 | <LI><A href="#Python_nn25">C++ namespaces</A></LI> | |
27037 | <LI><A href="#Python_nn26">C++ templates</A></LI> | |
27038 | <LI><A href="#Python_nn27">C++ Smart Pointers</A></LI> | |
27039 | <LI><A href="#Python_nn27a">C++ Reference Counted Objects (ref/unref)</A> | |
27040 | </LI> | |
27041 | </UL> | |
27042 | </LI> | |
27043 | <LI><A href="#Python_nn28">Further details on the Python class interface</A> | |
27044 | <UL> | |
27045 | <LI><A href="#Python_nn29">Proxy classes</A></LI> | |
27046 | <LI><A href="#Python_nn30">Memory management</A></LI> | |
27047 | <LI><A href="#Python_nn31">Python 2.2 and classic classes</A></LI> | |
27048 | </UL> | |
27049 | </LI> | |
27050 | <LI><A href="#directors">Cross language polymorphism</A> | |
27051 | <UL> | |
27052 | <LI><A href="#Python_nn33">Enabling directors</A></LI> | |
27053 | <LI><A href="#Python_nn34">Director classes</A></LI> | |
27054 | <LI><A href="#Python_nn35">Ownership and object destruction</A></LI> | |
27055 | <LI><A href="#Python_nn36">Exception unrolling</A></LI> | |
27056 | <LI><A href="#Python_nn37">Overhead and code bloat</A></LI> | |
27057 | <LI><A href="#Python_nn38">Typemaps</A></LI> | |
27058 | <LI><A href="#Python_nn39">Miscellaneous</A></LI> | |
27059 | </UL> | |
27060 | </LI> | |
27061 | <LI><A href="#Python_nn40">Common customization features</A> | |
27062 | <UL> | |
27063 | <LI><A href="#Python_nn41">C/C++ helper functions</A></LI> | |
27064 | <LI><A href="#Python_nn42">Adding additional Python code</A></LI> | |
27065 | <LI><A href="#Python_nn43">Class extension with %extend</A></LI> | |
27066 | <LI><A href="#Python_nn44">Exception handling with %exception</A></LI> | |
27067 | </UL> | |
27068 | </LI> | |
27069 | <LI><A href="#Python_nn45">Tips and techniques</A> | |
27070 | <UL> | |
27071 | <LI><A href="#Python_nn46">Input and output parameters</A></LI> | |
27072 | <LI><A href="#Python_nn47">Simple pointers</A></LI> | |
27073 | <LI><A href="#Python_nn48">Unbounded C Arrays</A></LI> | |
27074 | <LI><A href="#Python_nn49">String handling</A></LI> | |
27075 | <LI><A href="#Python_nn50">Arrays</A></LI> | |
27076 | <LI><A href="#Python_nn51">String arrays</A></LI> | |
27077 | <LI><A href="#Python_nn52">STL wrappers</A></LI> | |
27078 | </UL> | |
27079 | </LI> | |
27080 | <LI><A href="#Python_nn53">Typemaps</A> | |
27081 | <UL> | |
27082 | <LI><A href="#Python_nn54">What is a typemap?</A></LI> | |
27083 | <LI><A href="#Python_nn55">Python typemaps</A></LI> | |
27084 | <LI><A href="#Python_nn56">Typemap variables</A></LI> | |
27085 | <LI><A href="#Python_nn57">Useful Python Functions</A></LI> | |
27086 | </UL> | |
27087 | </LI> | |
27088 | <LI><A href="#Python_nn58">Typemap Examples</A> | |
27089 | <UL> | |
27090 | <LI><A href="#Python_nn59">Converting Python list to a char **</A></LI> | |
27091 | <LI><A href="#Python_nn60">Expanding a Python object into multiple | |
27092 | arguments</A></LI> | |
27093 | <LI><A href="#Python_nn61">Using typemaps to return arguments</A></LI> | |
27094 | <LI><A href="#Python_nn62">Mapping Python tuples into small arrays</A></LI> | |
27095 | <LI><A href="#Python_nn63">Mapping sequences to C arrays</A></LI> | |
27096 | <LI><A href="#Python_nn64">Pointer handling</A></LI> | |
27097 | </UL> | |
27098 | </LI> | |
27099 | <LI><A href="#Python_nn65">Docstring Features</A> | |
27100 | <UL> | |
27101 | <LI><A href="#Python_nn66">Module docstring</A></LI> | |
27102 | <LI><A href="#Python_nn67">%feature("autodoc")</A> | |
27103 | <UL> | |
27104 | <LI><A href="#Python_nn68">%feature("autodoc", "0")</A></LI> | |
27105 | <LI><A href="#Python_nn69">%feature("autodoc", "1")</A></LI> | |
27106 | <LI><A href="#Python_nn70">%feature("autodoc", "docstring")</A></LI> | |
27107 | </UL> | |
27108 | </LI> | |
27109 | <LI><A href="#Python_nn71">%feature("docstring")</A></LI> | |
27110 | </UL> | |
27111 | </LI> | |
27112 | <LI><A href="#Python_nn72">Python Packages</A></LI> | |
27113 | </UL> | |
27114 | </DIV> | |
27115 | <!-- INDEX --> | |
27116 | <P><B> Caution: This chapter is under repair!</B></P> | |
27117 | <P> This chapter describes SWIG's support of Python. SWIG is compatible | |
27118 | with most recent Python versions including Python 2.2 as well as older | |
27119 | versions dating back to Python 1.5.2. For the best results, consider | |
27120 | using Python 2.0 or newer.</P> | |
27121 | <P> This chapter covers most SWIG features, but certain low-level | |
27122 | details are covered in less depth than in earlier chapters. At the very | |
27123 | least, make sure you read the "<A href="#SWIG">SWIG Basics</A>" | |
27124 | chapter.</P> | |
27125 | <H2><A name="Python_nn2"></A>26.1 Overview</H2> | |
27126 | <P> To build Python extension modules, SWIG uses a layered approach in | |
27127 | which parts of the extension module are defined in C and other parts | |
27128 | are defined in Python. The C layer contains low-level wrappers whereas | |
27129 | Python code is used to define high-level features.</P> | |
27130 | <P> This layered approach recognizes the fact that certain aspects of | |
27131 | extension building are better accomplished in each language (instead of | |
27132 | trying to do everything in C or C++). Furthermore, by generating code | |
27133 | in both languages, you get a lot more flexibility since you can enhance | |
27134 | the extension module with support code in either language.</P> | |
27135 | <P> In describing the Python interface, this chapter starts by covering | |
27136 | the basics of configuration, compiling, and installing Python modules. | |
27137 | Next, the Python interface to common C and C++ programming features is | |
27138 | described. Advanced customization features such as typemaps are then | |
27139 | described followed by a discussion of low-level implementation details.</P> | |
27140 | <H2><A name="Python_nn3"></A>26.2 Preliminaries</H2> | |
27141 | <H3><A name="Python_nn4"></A>26.2.1 Running SWIG</H3> | |
27142 | <P> Suppose that you defined a SWIG module such as the following:</P> | |
27143 | <DIV class="code"> | |
27144 | <PRE> | |
27145 | %module example | |
27146 | %{ | |
27147 | #include "header.h" | |
27148 | %} | |
27149 | int fact(int n); | |
27150 | </PRE> | |
27151 | </DIV> | |
27152 | <P> To build a Python module, run SWIG using the <TT>-python</TT> option | |
27153 | :</P> | |
27154 | <DIV class="shell"> | |
27155 | <PRE> | |
27156 | $ swig -python example.i | |
27157 | </PRE> | |
27158 | </DIV> | |
27159 | <P> If building a C++ extension, add the <TT>-c++</TT> option:</P> | |
27160 | <DIV class="shell"> | |
27161 | <PRE> | |
27162 | $ swig -c++ -python example.i | |
27163 | </PRE> | |
27164 | </DIV> | |
27165 | <P> This creates two different files; a C/C++ source file <TT> | |
27166 | example_wrap.c</TT> or <TT>example_wrap.cxx</TT> and a Python source | |
27167 | file <TT>example.py</TT>. The generated C source file contains the | |
27168 | low-level wrappers that need to be compiled and linked with the rest of | |
27169 | your C/C++ application to create an extension module. The Python source | |
27170 | file contains high-level support code. This is the file that you will | |
27171 | import to use the module.</P> | |
27172 | <P> The name of the wrapper file is derived from the name of the input | |
27173 | file. For example, if the input file is <TT>example.i</TT>, the name of | |
27174 | the wrapper file is <TT>example_wrap.c</TT>. To change this, you can | |
27175 | use the <TT>-o</TT> option. The name of the Python file is derived from | |
27176 | the module name specified with <TT>%module</TT>. If the module name is <TT> | |
27177 | example</TT>, then a file <TT>example.py</TT> is created.</P> | |
27178 | <H3><A name="Python_nn5"></A>26.2.2 Getting the right header files</H3> | |
27179 | <P> In order to compile the C/C++ wrappers, the compiler needs the <TT> | |
27180 | Python.h</TT> header file. This file is usually contained in a directory | |
27181 | such as</P> | |
27182 | <DIV class="diagram"> | |
27183 | <PRE> | |
27184 | /usr/local/include/python2.0 | |
27185 | </PRE> | |
27186 | </DIV> | |
27187 | <P> The exact location may vary on your machine, but the above location | |
27188 | is typical. If you are not entirely sure where Python is installed, you | |
27189 | can run Python to find out. For example:</P> | |
27190 | <DIV class="targetlang"> | |
27191 | <PRE> | |
27192 | $ python | |
27193 | Python 2.1.1 (#1, Jul 23 2001, 14:36:06) | |
27194 | [GCC egcs-2.91.66 19990314/Linux (egcs-1.1.2 release)] on linux2 | |
27195 | Type "copyright", "credits" or "license" for more information. | |
27196 | >>> import sys | |
27197 | >>> print sys.prefix | |
27198 | /usr/local | |
27199 | >>> | |
27200 | </PRE> | |
27201 | </DIV> | |
27202 | <H3><A name="Python_nn6"></A>26.2.3 Compiling a dynamic module</H3> | |
27203 | <P> The preferred approach to building an extension module is to compile | |
27204 | it into a shared object file or DLL. To do this, you need to compile | |
27205 | your program using commands like this (shown for Linux):</P> | |
27206 | <DIV class="shell"> | |
27207 | <PRE> | |
27208 | $ swig -python example.i | |
27209 | $ gcc -c -fPIC example.c | |
27210 | $ gcc -c -fPIC example_wrap.c -I/usr/local/include/python2.0 | |
27211 | $ gcc -shared example.o example_wrap.o -o _example.so | |
27212 | </PRE> | |
27213 | </DIV> | |
27214 | <P> The exact commands for doing this vary from platform to platform. | |
27215 | However, SWIG tries to guess the right options when it is installed. | |
27216 | Therefore, you may want to start with one of the examples in the <TT> | |
27217 | SWIG/Examples/python</TT> directory. If that doesn't work, you will need | |
27218 | to read the man-pages for your compiler and linker to get the right set | |
27219 | of options. You might also check the <A href="http://swig.cs.uchicago.edu/cgi-bin/wiki.pl"> | |
27220 | SWIG Wiki</A> for additional information.</P> | |
27221 | <P> When linking the module,<B> the name of the output file has to match | |
27222 | the name of the module prefixed by an underscore</B>. If the name of | |
27223 | your module is "<TT>example</TT>", then the name of the corresponding | |
27224 | object file should be "<TT>_example.so</TT>" or "<TT>_examplemodule.so</TT> | |
27225 | ". The name of the module is specified using the <TT>%module</TT> | |
27226 | directive or the <TT>-module</TT> command line option.</P> | |
27227 | <P><B> Compatibility Note:</B> In SWIG-1.3.13 and earlier releases, | |
27228 | module names did not include the leading underscore. This is because | |
27229 | modules were normally created as C-only extensions without the extra | |
27230 | Python support file (instead, creating Python code was supported as an | |
27231 | optional feature). This has been changed in SWIG-1.3.14 and is | |
27232 | consistent with other Python extension modules. For example, the <TT> | |
27233 | socket</TT> module actually consists of two files; <TT>socket.py</TT> | |
27234 | and <TT>_socket.so</TT>. Many other built-in Python modules follow a | |
27235 | similar convention.</P> | |
27236 | <H3><A name="Python_nn7"></A>26.2.4 Using distutils</H3> | |
27237 | <H3><A name="Python_nn8"></A>26.2.5 Static linking</H3> | |
27238 | <P> An alternative approach to dynamic linking is to rebuild the Python | |
27239 | interpreter with your extension module added to it. In the past, this | |
27240 | approach was sometimes necessary due to limitations in dynamic loading | |
27241 | support on certain machines. However, the situation has improved | |
27242 | greatly over the last few years and you should not consider this | |
27243 | approach unless there is really no other option.</P> | |
27244 | <P> The usual procedure for adding a new module to Python involves | |
27245 | finding the Python source, adding an entry to the <TT>Modules/Setup</TT> | |
27246 | file, and rebuilding the interpreter using the Python Makefile. | |
27247 | However, newer Python versions have changed the build process. You may | |
27248 | need to edit the 'setup.py' file in the Python distribution instead.</P> | |
27249 | <P> In earlier versions of SWIG, the <TT>embed.i</TT> library file could | |
27250 | be used to rebuild the interpreter. For example:</P> | |
27251 | <DIV class="code"> | |
27252 | <PRE> | |
27253 | %module example | |
27254 | ||
27255 | %inline %{ | |
27256 | extern int fact(int); | |
27257 | extern int mod(int, int); | |
27258 | extern double My_variable; | |
27259 | %} | |
27260 | ||
27261 | %include embed.i // Include code for a static version of Python | |
27262 | ||
27263 | </PRE> | |
27264 | </DIV> | |
27265 | <P> The <TT>embed.i</TT> library file includes supporting code that | |
27266 | contains everything needed to rebuild Python. To rebuild the | |
27267 | interpreter, you simply do something like this:</P> | |
27268 | <DIV class="shell"> | |
27269 | <PRE> | |
27270 | $ swig -python example.i | |
27271 | $ gcc example.c example_wrap.c \ | |
27272 | -Xlinker -export-dynamic \ | |
27273 | -DHAVE_CONFIG_H -I/usr/local/include/python2.1 \ | |
27274 | -I/usr/local/lib/python2.1/config \ | |
27275 | -L/usr/local/lib/python2.1/config -lpython2.1 -lm -ldl \ | |
27276 | -o mypython | |
27277 | ||
27278 | </PRE> | |
27279 | </DIV> | |
27280 | <P> You will need to supply the same libraries that were used to build | |
27281 | Python the first time. This may include system libraries such as <TT> | |
27282 | -lsocket</TT>, <TT>-lnsl</TT>, and <TT>-lpthread</TT>. Assuming this | |
27283 | actually works, the new version of Python should be identical to the | |
27284 | default version except that your extension module will be a built-in | |
27285 | part of the interpreter.</P> | |
27286 | <P><B> Comment:</B> In practice, you should probably try to avoid static | |
27287 | linking if possible. Some programmers may be inclined to use static | |
27288 | linking in the interest of getting better performance. However, the | |
27289 | performance gained by static linking tends to be rather minimal in most | |
27290 | situations (and quite frankly not worth the extra hassle in the opinion | |
27291 | of this author).</P> | |
27292 | <P><B> Compatibility note:</B> The <TT>embed.i</TT> library file is | |
27293 | deprecated and has not been maintained for several years. Even though | |
27294 | it appears to "work" with Python 2.1, no future support is guaranteed. | |
27295 | If using static linking, you might want to rely on a different approach | |
27296 | (perhaps using distutils).</P> | |
27297 | <H3><A name="Python_nn9"></A>26.2.6 Using your module</H3> | |
27298 | <P> To use your module, simply use the Python <TT>import</TT> statement. | |
27299 | If all goes well, you will be able to this:</P> | |
27300 | <DIV class="targetlang"> | |
27301 | <PRE> | |
27302 | $ python | |
27303 | >>> import example | |
27304 | >>> example.fact(4) | |
27305 | 24 | |
27306 | >>> | |
27307 | </PRE> | |
27308 | </DIV> | |
27309 | <P> A common error received by first-time users is the following:</P> | |
27310 | <DIV class="targetlang"> | |
27311 | <PRE> | |
27312 | >>> import example | |
27313 | Traceback (most recent call last): | |
27314 | File "<stdin>", line 1, in ? | |
27315 | File "example.py", line 2, in ? | |
27316 | import _example | |
27317 | ImportError: No module named _example | |
27318 | </PRE> | |
27319 | </DIV> | |
27320 | <P> If you get this message, it means that you either forgot to compile | |
27321 | the wrapper code into an extension module or you didn't give the | |
27322 | extension module the right name. Make sure that you compiled the | |
27323 | wrappers into a module called <TT>_example.so</TT>. And don't forget | |
27324 | the leading underscore (_).</P> | |
27325 | <P> Another possible error is the following:</P> | |
27326 | <DIV class="targetlang"> | |
27327 | <PRE> | |
27328 | >>> import example | |
27329 | Traceback (most recent call last): | |
27330 | File "<stdin>", line 1, in ? | |
27331 | ImportError: dynamic module does not define init function (init_example) | |
27332 | >>> | |
27333 | </PRE> | |
27334 | </DIV> | |
27335 | <P> This error is almost always caused when a bad name is given to the | |
27336 | shared object file. For example, if you created a file <TT>example.so</TT> | |
27337 | instead of <TT>_example.so</TT> you would get this error. | |
27338 | Alternatively, this error could arise if the name of the module is | |
27339 | inconsistent with the module name supplied with the <TT>%module</TT> | |
27340 | directive. Double-check the interface to make sure the module name and | |
27341 | the shared object filename match. Another possible cause of this error | |
27342 | is forgetting to link the SWIG-generated wrapper code with the rest of | |
27343 | your application when creating the extension module.</P> | |
27344 | <P> Another common error is something similar to the following:</P> | |
27345 | <DIV class="targetlang"> | |
27346 | <PRE> | |
27347 | Traceback (most recent call last): | |
27348 | File "example.py", line 3, in ? | |
27349 | import example | |
27350 | ImportError: ./_example.so: undefined symbol: fact | |
27351 | </PRE> | |
27352 | </DIV> | |
27353 | <P> This error usually indicates that you forgot to include some object | |
27354 | files or libraries in the linking of the shared library file. Make sure | |
27355 | you compile both the SWIG wrapper file and your original program into a | |
27356 | shared library file. Make sure you pass all of the required libraries | |
27357 | to the linker.</P> | |
27358 | <P> Sometimes unresolved symbols occur because a wrapper has been | |
27359 | created for a function that doesn't actually exist in a library. This | |
27360 | usually occurs when a header file includes a declaration for a function | |
27361 | that was never actually implemented or it was removed from a library | |
27362 | without updating the header file. To fix this, you can either edit the | |
27363 | SWIG input file to remove the offending declaration or you can use the <TT> | |
27364 | %ignore</TT> directive to ignore the declaration.</P> | |
27365 | <P> Finally, suppose that your extension module is linked with another | |
27366 | library like this:</P> | |
27367 | <DIV class="shell"> | |
27368 | <PRE> | |
27369 | $ gcc -shared example.o example_wrap.o -L/home/beazley/projects/lib <B>-lfoo</B> \ | |
27370 | -o _example.so | |
27371 | </PRE> | |
27372 | </DIV> | |
27373 | <P> If the <TT>foo</TT> library is compiled as a shared library, you | |
27374 | might encounter the following problem when you try to use your module:</P> | |
27375 | <DIV class="targetlang"> | |
27376 | <PRE> | |
27377 | >>> import example | |
27378 | Traceback (most recent call last): | |
27379 | File "<stdin>", line 1, in ? | |
27380 | ImportError: libfoo.so: cannot open shared object file: No such file or directory | |
27381 | >>> | |
27382 | </PRE> | |
27383 | </DIV> | |
27384 | <P> This error is generated because the dynamic linker can't locate the <TT> | |
27385 | libfoo.so</TT> library. When shared libraries are loaded, the system | |
27386 | normally only checks a few standard locations such as <TT>/usr/lib</TT> | |
27387 | and <TT>/usr/local/lib</TT>. To fix this problem, there are several | |
27388 | things you can do. First, you can recompile your extension module with | |
27389 | extra path information. For example, on Linux you can do this:</P> | |
27390 | <DIV class="shell"> | |
27391 | <PRE> | |
27392 | $ gcc -shared example.o example_wrap.o -L/home/beazley/projects/lib -lfoo \ | |
27393 | <B>-Xlinker -rpath /home/beazley/projects/lib </B> \ | |
27394 | -o _example.so | |
27395 | </PRE> | |
27396 | </DIV> | |
27397 | <P> Alternatively, you can set the <TT>LD_LIBRARY_PATH</TT> environment | |
27398 | variable to include the directory with your shared libraries. If | |
27399 | setting <TT>LD_LIBRARY_PATH</TT>, be aware that setting this variable | |
27400 | can introduce a noticeable performance impact on all other applications | |
27401 | that you run. To set it only for Python, you might want to do this | |
27402 | instead:</P> | |
27403 | <DIV class="shell"> | |
27404 | <PRE> | |
27405 | $ env LD_LIBRARY_PATH=/home/beazley/projects/lib python | |
27406 | </PRE> | |
27407 | </DIV> | |
27408 | <P> Finally, you can use a command such as <TT>ldconfig</TT> (Linux) or <TT> | |
27409 | crle</TT> (Solaris) to add additional search paths to the default system | |
27410 | configuration (this requires root access and you will need to read the | |
27411 | man pages).</P> | |
27412 | <H3><A name="Python_nn10"></A>26.2.7 Compilation of C++ extensions</H3> | |
27413 | <P> Compilation of C++ extensions has traditionally been a tricky | |
27414 | problem. Since the Python interpreter is written in C, you need to take | |
27415 | steps to make sure C++ is properly initialized and that modules are | |
27416 | compiled correctly.</P> | |
27417 | <P> On most machines, C++ extension modules should be linked using the | |
27418 | C++ compiler. For example:</P> | |
27419 | <DIV class="shell"> | |
27420 | <PRE> | |
27421 | $ swig -c++ -python example.i | |
27422 | $ g++ -c example.cxx | |
27423 | $ g++ -c example_wrap.cxx -I/usr/local/include/python2.0 | |
27424 | $ g++ -shared example.o example_wrap.o -o _example.so | |
27425 | </PRE> | |
27426 | </DIV> | |
27427 | <P> On some platforms, you could also need to generate | |
27428 | position-independent code (PIC), by using a compiler option such as | |
27429 | -fPIC. Notably, the x86_64 (Opteron and EM64T) platform requires it, | |
27430 | and when using the GNU Compiler Suite, you will need to modify the | |
27431 | previous example as follows:</P> | |
27432 | <DIV class="shell"> | |
27433 | <PRE> | |
27434 | $ swig -c++ -python example.i | |
27435 | $ g++ -fPIC -c example.cxx | |
27436 | $ g++ -fPIC -c example_wrap.cxx -I/usr/local/include/python2.0 | |
27437 | $ g++ -shared example.o example_wrap.o -o _example.so | |
27438 | </PRE> | |
27439 | </DIV> | |
27440 | <P> In addition to this, you may need to include additional library | |
27441 | files to make it work. For example, if you are using the Sun C++ | |
27442 | compiler on Solaris, you often need to add an extra library <TT>-lCrun</TT> | |
27443 | like this:</P> | |
27444 | <DIV class="shell"> | |
27445 | <PRE> | |
27446 | $ swig -c++ -python example.i | |
27447 | $ CC -c example.cxx | |
27448 | $ CC -c example_wrap.cxx -I/usr/local/include/python2.0 | |
27449 | $ CC -G example.o example_wrap.o -L/opt/SUNWspro/lib -o _example.so -lCrun | |
27450 | </PRE> | |
27451 | </DIV> | |
27452 | <P> Of course, the extra libraries to use are completely | |
27453 | non-portable---you will probably need to do some experimentation.</P> | |
27454 | <P> Sometimes people have suggested that it is necessary to relink the | |
27455 | Python interpreter using the C++ compiler to make C++ extension modules | |
27456 | work. In the experience of this author, this has never actually | |
27457 | appeared to be necessary. Relinking the interpreter with C++ really | |
27458 | only includes the special run-time libraries described above---as long | |
27459 | as you link your extension modules with these libraries, it should not | |
27460 | be necessary to rebuild Python.</P> | |
27461 | <P> If you aren't entirely sure about the linking of a C++ extension, | |
27462 | you might look at an existing C++ program. On many Unix machines, the <TT> | |
27463 | ldd</TT> command will list library dependencies. This should give you | |
27464 | some clues about what you might have to include when you link your | |
27465 | extension module. For example:</P> | |
27466 | <DIV class="shell"> | |
27467 | <PRE> | |
27468 | $ ldd swig | |
27469 | libstdc++-libc6.1-1.so.2 => /usr/lib/libstdc++-libc6.1-1.so.2 (0x40019000) | |
27470 | libm.so.6 => /lib/libm.so.6 (0x4005b000) | |
27471 | libc.so.6 => /lib/libc.so.6 (0x40077000) | |
27472 | /lib/ld-linux.so.2 => /lib/ld-linux.so.2 (0x40000000) | |
27473 | </PRE> | |
27474 | </DIV> | |
27475 | <P> As a final complication, a major weakness of C++ is that it does not | |
27476 | define any sort of standard for binary linking of libraries. This means | |
27477 | that C++ code compiled by different compilers will not link together | |
27478 | properly as libraries nor is the memory layout of classes and data | |
27479 | structures implemented in any kind of portable manner. In a monolithic | |
27480 | C++ program, this problem may be unnoticed. However, in Python, it is | |
27481 | possible for different extension modules to be compiled with different | |
27482 | C++ compilers. As long as these modules are self-contained, this | |
27483 | probably won't matter. However, if these modules start sharing data, | |
27484 | you will need to take steps to avoid segmentation faults and other | |
27485 | erratic program behavior. If working with lots of software components, | |
27486 | you might want to investigate using a more formal standard such as COM.</P> | |
27487 | <H3><A name="Python_nn11"></A>26.2.8 Compiling for 64-bit platforms</H3> | |
27488 | <P> On platforms that support 64-bit applications (Solaris, Irix, etc.), | |
27489 | special care is required when building extension modules. On these | |
27490 | machines, 64-bit applications are compiled and linked using a different | |
27491 | set of compiler/linker options. In addition, it is not generally | |
27492 | possible to mix 32-bit and 64-bit code together in the same | |
27493 | application.</P> | |
27494 | <P> To utilize 64-bits, the Python executable will need to be recompiled | |
27495 | as a 64-bit application. In addition, all libraries, wrapper code, and | |
27496 | every other part of your application will need to be compiled for | |
27497 | 64-bits. If you plan to use other third-party extension modules, they | |
27498 | will also have to be recompiled as 64-bit extensions.</P> | |
27499 | <P> If you are wrapping commercial software for which you have no source | |
27500 | code, you will be forced to use the same linking standard as used by | |
27501 | that software. This may prevent the use of 64-bit extensions. It may | |
27502 | also introduce problems on platforms that support more than one linking | |
27503 | standard (e.g., -o32 and -n32 on Irix).</P> | |
27504 | <P> On the Linux x86_64 platform (Opteron or EM64T), besides of the | |
27505 | required compiler option -fPIC discussed above, you will need to be | |
27506 | careful about the libraries you link with or the library path you use. | |
27507 | In general, a Linux distribution will have two set of libraries, one | |
27508 | for native x86_64 programs (under /usr/lib64), and another for 32 bits | |
27509 | compatibility (under /usr/lib). Also, the compiler options -m32 and | |
27510 | -m64 allow you to choose the desired binary format for your python | |
27511 | extension.</P> | |
27512 | <H3><A name="Python_nn12"></A>26.2.9 Building Python Extensions under | |
27513 | Windows</H3> | |
27514 | <P> Building a SWIG extension to Python under Windows is roughly similar | |
27515 | to the process used with Unix. You will need to create a DLL that can | |
27516 | be loaded into the interpreter. This section briefly describes the use | |
27517 | of SWIG with Microsoft Visual C++. As a starting point, many of SWIG's | |
27518 | examples include project files. You might want to take a quick look at | |
27519 | these in addition to reading this section.</P> | |
27520 | <P> In Developer Studio, SWIG should be invoked as a custom build | |
27521 | option. This is usually done as follows:</P> | |
27522 | <UL> | |
27523 | <LI>Open up a new workspace and use the AppWizard to select a DLL | |
27524 | project.</LI> | |
27525 | <LI>Add both the SWIG interface file (the .i file), any supporting C | |
27526 | files, and the name of the wrapper file that will be created by SWIG | |
27527 | (ie. <TT>example_wrap.c</TT>). Note : If using C++, choose a different | |
27528 | suffix for the wrapper file such as <TT>example_wrap.cxx</TT>. Don't | |
27529 | worry if the wrapper file doesn't exist yet--Developer Studio keeps a | |
27530 | reference to it.</LI> | |
27531 | <LI>Select the SWIG interface file and go to the settings menu. Under | |
27532 | settings, select the "Custom Build" option.</LI> | |
27533 | <LI>Enter "SWIG" in the description field.</LI> | |
27534 | <LI>Enter "<TT>swig -python -o $(ProjDir)\$(InputName)_wrap.c | |
27535 | $(InputPath)</TT>" in the "Build command(s) field"</LI> | |
27536 | <LI>Enter "<TT>$(ProjDir)\$(InputName)_wrap.c</TT>" in the "Output | |
27537 | files(s) field".</LI> | |
27538 | <LI>Next, select the settings for the entire project and go to | |
27539 | "C++:Preprocessor". Add the include directories for your Python | |
27540 | installation under "Additional include directories".</LI> | |
27541 | <LI>Define the symbol __WIN32__ under preprocessor options.</LI> | |
27542 | <LI>Finally, select the settings for the entire project and go to "Link | |
27543 | Options". Add the Python library file to your link libraries. For | |
27544 | example "python21.lib". Also, set the name of the output file to match | |
27545 | the name of your Python module (ie. _example.dll).</LI> | |
27546 | <LI>Build your project.</LI> | |
27547 | </UL> | |
27548 | <P> If all went well, SWIG will be automatically invoked whenever you | |
27549 | build your project. Any changes made to the interface file will result | |
27550 | in SWIG being automatically executed to produce a new version of the | |
27551 | wrapper file.</P> | |
27552 | <P> To run your new Python extension, simply run Python and use the <TT> | |
27553 | import</TT> command as normal. For example :</P> | |
27554 | <DIV class="targetlang"> | |
27555 | <PRE> | |
27556 | $ python | |
27557 | >>> import example | |
27558 | >>> print example.fact(4) | |
27559 | 24 | |
27560 | >>> | |
27561 | </PRE> | |
27562 | </DIV> | |
27563 | <P> If you get an <TT>ImportError</TT> exception when importing the | |
27564 | module, you may have forgotten to include aditional library files when | |
27565 | you built your module. If you get an access violation or some kind of | |
27566 | general protection fault immediately upon import, you have a more | |
27567 | serious problem. This is often caused by linking your extension module | |
27568 | against the wrong set of Win32 debug or thread libraries. You will have | |
27569 | to fiddle around with the build options of project to try and track | |
27570 | this down.</P> | |
27571 | <P> Some users have reported success in building extension modules using | |
27572 | Cygwin and other compilers. However, the problem of building usable | |
27573 | DLLs with these compilers tends to be rather problematic. For the | |
27574 | latest information, you may want to consult the <A href="http://swig.cs.uchicago.edu/cgi-bin/wiki.pl"> | |
27575 | SWIG Wiki</A>.</P> | |
27576 | <H2><A name="Python_nn13"></A>26.3 A tour of basic C/C++ wrapping</H2> | |
27577 | <P> By default, SWIG tries to build a very natural Python interface to | |
27578 | your C/C++ code. Functions are wrapped as functions, classes are | |
27579 | wrapped as classes, and so forth. This section briefly covers the | |
27580 | essential aspects of this wrapping.</P> | |
27581 | <H3><A name="Python_nn14"></A>26.3.1 Modules</H3> | |
27582 | <P> The SWIG <TT>%module</TT> directive specifies the name of the Python | |
27583 | module. If you specify `<TT>%module example</TT>', then everything is | |
27584 | wrapped into a Python '<TT>example</TT>' module. Underneath the covers, | |
27585 | this module consists of a Python source file <TT>example.py</TT> and a | |
27586 | low-level extension module <TT>_example.so</TT>. When choosing a module | |
27587 | name, make sure you don't use the same name as a built-in Python | |
27588 | command or standard module name.</P> | |
27589 | <H3><A name="Python_nn15"></A>26.3.2 Functions</H3> | |
27590 | <P> Global functions are wrapped as new Python built-in functions. For | |
27591 | example,</P> | |
27592 | <DIV class="code"> | |
27593 | <PRE> | |
27594 | %module example | |
27595 | int fact(int n); | |
27596 | </PRE> | |
27597 | </DIV> | |
27598 | <P> creates a built-in function <TT>example.fact(n)</TT> that works | |
27599 | exactly like you think it does:</P> | |
27600 | <DIV class="targetlang"> | |
27601 | <PRE> | |
27602 | >>> import example | |
27603 | >>> print example.fact(4) | |
27604 | 24 | |
27605 | >>> | |
27606 | </PRE> | |
27607 | </DIV> | |
27608 | <H3><A name="Python_nn16"></A>26.3.3 Global variables</H3> | |
27609 | <P> C/C++ global variables are fully supported by SWIG. However, the | |
27610 | underlying mechanism is somewhat different than you might expect due to | |
27611 | the way that Python assignment works. When you type the following in | |
27612 | Python</P> | |
27613 | <DIV class="targetlang"> | |
27614 | <PRE> | |
27615 | a = 3.4 | |
27616 | </PRE> | |
27617 | </DIV> | |
27618 | <P> "a" becomes a name for an object containing the value 3.4. If you | |
27619 | later type</P> | |
27620 | <DIV class="targetlang"> | |
27621 | <PRE> | |
27622 | b = a | |
27623 | </PRE> | |
27624 | </DIV> | |
27625 | <P> then "a" and "b" are both names for the object containing the value | |
27626 | 3.4. Thus, there is only one object containing 3.4 and "a" and "b" are | |
27627 | both names that refer to it. This is quite different than C where a | |
27628 | variable name refers to a memory location in which a value is stored | |
27629 | (and assignment copies data into that location). Because of this, there | |
27630 | is no direct way to map variable assignment in C to variable assignment | |
27631 | in Python.</P> | |
27632 | <P> To provide access to C global variables, SWIG creates a special | |
27633 | object called `<TT>cvar</TT>' that is added to each SWIG generated | |
27634 | module. Global variables are then accessed as attributes of this | |
27635 | object. For example, consider this interface</P> | |
27636 | <DIV class="code"> | |
27637 | <PRE> | |
27638 | // SWIG interface file with global variables | |
27639 | %module example | |
27640 | ... | |
27641 | %inline %{ | |
27642 | extern int My_variable; | |
27643 | extern double density; | |
27644 | %} | |
27645 | ... | |
27646 | </PRE> | |
27647 | </DIV> | |
27648 | <P> Now look at the Python interface:</P> | |
27649 | <DIV class="targetlang"> | |
27650 | <PRE> | |
27651 | >>> import example | |
27652 | >>> # Print out value of a C global variable | |
27653 | >>> print example.cvar.My_variable | |
27654 | 4 | |
27655 | >>> # Set the value of a C global variable | |
27656 | >>> example.cvar.density = 0.8442 | |
27657 | >>> # Use in a math operation | |
27658 | >>> example.cvar.density = example.cvar.density*1.10 | |
27659 | </PRE> | |
27660 | </DIV> | |
27661 | <P> If you make an error in variable assignment, you will receive an | |
27662 | error message. For example:</P> | |
27663 | <DIV class="targetlang"> | |
27664 | <PRE> | |
27665 | >>> example.cvar.density = "Hello" | |
27666 | Traceback (most recent call last): | |
27667 | File "<stdin>", line 1, in ? | |
27668 | TypeError: C variable 'density (double )' | |
27669 | >>> | |
27670 | </PRE> | |
27671 | </DIV> | |
27672 | <P> If a variable is declared as <TT>const</TT>, it is wrapped as a | |
27673 | read-only variable. Attempts to modify its value will result in an | |
27674 | error.</P> | |
27675 | <P> To make ordinary variables read-only, you can use the <TT>%immutable</TT> | |
27676 | directive. For example:</P> | |
27677 | <DIV class="code"> | |
27678 | <PRE> | |
27679 | %{ | |
27680 | extern char *path; | |
27681 | %} | |
27682 | %immutable; | |
27683 | extern char *path; | |
27684 | %mutable; | |
27685 | </PRE> | |
27686 | </DIV> | |
27687 | <P> The <TT>%immutable</TT> directive stays in effect until it is | |
27688 | explicitly disabled or cleared using <TT>%mutable</TT>. See the <A href="#SWIG_readonly_variables"> | |
27689 | Creatng read-only variables</A> section for further details.</P> | |
27690 | <P> If you just want to make a specific variable immutable, supply a | |
27691 | declaration name. For example:</P> | |
27692 | <DIV class="code"> | |
27693 | <PRE> | |
27694 | %{ | |
27695 | extern char *path; | |
27696 | %} | |
27697 | %immutable path; | |
27698 | ... | |
27699 | extern char *path; // Read-only (due to %immutable) | |
27700 | </PRE> | |
27701 | </DIV> | |
27702 | <P> If you would like to access variables using a name other than "<TT> | |
27703 | cvar</TT>", it can be changed using the <TT>-globals</TT> option :</P> | |
27704 | <DIV class="shell"> | |
27705 | <PRE> | |
27706 | $ swig -python -globals myvar example.i | |
27707 | </PRE> | |
27708 | </DIV> | |
27709 | <P> Some care is in order when importing multiple SWIG modules. If you | |
27710 | use the "<TT>from <file> import *</TT>" style of importing, you will | |
27711 | get a name clash on the variable `<TT>cvar</TT>' and you will only be | |
27712 | able to access global variables from the last module loaded. To prevent | |
27713 | this, you might consider renaming <TT>cvar</TT> or making it private to | |
27714 | the module by giving it a name that starts with a leading underscore. | |
27715 | SWIG does not create <TT>cvar</TT> if there are no global variables in | |
27716 | a module.</P> | |
27717 | <H3><A name="Python_nn17"></A>26.3.4 Constants and enums</H3> | |
27718 | <P> C/C++ constants are installed as Python objects containing the | |
27719 | appropriate value. To create a constant, use <TT>#define</TT>, <TT>enum</TT> | |
27720 | , or the <TT>%constant</TT> directive. For example:</P> | |
27721 | <DIV class="code"> | |
27722 | <PRE> | |
27723 | #define PI 3.14159 | |
27724 | #define VERSION "1.0" | |
27725 | ||
27726 | enum Beverage { ALE, LAGER, STOUT, PILSNER }; | |
27727 | ||
27728 | %constant int FOO = 42; | |
27729 | %constant const char *path = "/usr/local"; | |
27730 | </PRE> | |
27731 | </DIV> | |
27732 | <P> For enums, make sure that the definition of the enumeration actually | |
27733 | appears in a header file or in the wrapper file somehow---if you just | |
27734 | stick an enum in a SWIG interface without also telling the C compiler | |
27735 | about it, the wrapper code won't compile.</P> | |
27736 | <P> Note: declarations declared as <TT>const</TT> are wrapped as | |
27737 | read-only variables and will be accessed using the <TT>cvar</TT> object | |
27738 | described in the previous section. They are not wrapped as constants. | |
27739 | For further discussion about this, see the <A href="#SWIG">SWIG Basics</A> | |
27740 | chapter.</P> | |
27741 | <P> Constants are not guaranteed to remain constant in Python---the name | |
27742 | of the constant could be accidentally reassigned to refer to some other | |
27743 | object. Unfortunately, there is no easy way for SWIG to generate code | |
27744 | that prevents this. You will just have to be careful.</P> | |
27745 | <H3><A name="Python_nn18"></A>26.3.5 Pointers</H3> | |
27746 | <P> C/C++ pointers are fully supported by SWIG. Furthermore, SWIG has no | |
27747 | problem working with incomplete type information. Here is a rather | |
27748 | simple interface:</P> | |
27749 | <DIV class="code"> | |
27750 | <PRE> | |
27751 | %module example | |
27752 | ||
27753 | FILE *fopen(const char *filename, const char *mode); | |
27754 | int fputs(const char *, FILE *); | |
27755 | int fclose(FILE *); | |
27756 | </PRE> | |
27757 | </DIV> | |
27758 | <P> When wrapped, you will be able to use the functions in a natural way | |
27759 | from Python. For example:</P> | |
27760 | <DIV class="targetlang"> | |
27761 | <PRE> | |
27762 | >>> import example | |
27763 | >>> f = example.fopen("junk","w") | |
27764 | >>> example.fputs("Hello World\n", f) | |
27765 | >>> example.fclose(f) | |
27766 | </PRE> | |
27767 | </DIV> | |
27768 | <P> If this makes you uneasy, rest assured that there is no deep magic | |
27769 | involved. Underneath the covers, pointers to C/C++ objects are simply | |
27770 | represented as opaque values using an especial python container object:</P> | |
27771 | <DIV class="targetlang"> | |
27772 | <PRE> | |
27773 | >>> print f | |
27774 | <Swig Object at _08a71808_p_FILE> | |
27775 | </PRE> | |
27776 | </DIV> | |
27777 | <P> This pointer value can be freely passed around to different C | |
27778 | functions that expect to receive an object of type <TT>FILE *</TT>. The | |
27779 | only thing you can't do is dereference the pointer from Python. Of | |
27780 | course, that isn't much of a concern in this example.</P> | |
27781 | <P> In older versions of Swig (1.3.22 or older), pointers were | |
27782 | represented using a plain string object. If you have an old package | |
27783 | that still requires that representation, or you just feel nostalgic, | |
27784 | you can always retreive it by casting the pointer object to a string:</P> | |
27785 | <DIV class="targetlang"> | |
27786 | <PRE> | |
27787 | >>> print str(f) | |
27788 | _c0671108_p_FILE | |
27789 | </PRE> | |
27790 | </DIV> | |
27791 | <P> Also, if you need to pass the raw pointer value to some external | |
27792 | python library, you can do it by casting the pointer object to an | |
27793 | integer:</P> | |
27794 | <DIV class="targetlang"> | |
27795 | <PRE> | |
27796 | >>> print int(f) | |
27797 | 135833352 | |
27798 | </PRE> | |
27799 | </DIV> | |
27800 | <P> However, the inverse operation is not possible, i.e., you can't | |
27801 | build a Swig pointer object from a raw integer value.</P> | |
27802 | <P> Note also that the '0' or NULL pointer is always represented by <TT> | |
27803 | None</TT>, no matter what type swig is addressing. In the previous | |
27804 | example, you can call:</P> | |
27805 | <DIV class="targetlang"> | |
27806 | <PRE> | |
27807 | >>> example.fclose(None) | |
27808 | </PRE> | |
27809 | </DIV> | |
27810 | <P> and that will be equivalent to the following, but not really useful, | |
27811 | C code:</P> | |
27812 | <DIV class="code"> | |
27813 | <PRE> | |
27814 | FILE *f = NULL; | |
27815 | fclose(f); | |
27816 | </PRE> | |
27817 | </DIV> | |
27818 | <P> As much as you might be inclined to modify a pointer value directly | |
27819 | from Python, don't. The hexadecimal encoding is not necessarily the | |
27820 | same as the logical memory address of the underlying object. Instead it | |
27821 | is the raw byte encoding of the pointer value. The encoding will vary | |
27822 | depending on the native byte-ordering of the platform (i.e., big-endian | |
27823 | vs. little-endian). Similarly, don't try to manually cast a pointer to | |
27824 | a new type by simply replacing the type-string. This may not work like | |
27825 | you expect, it is particularly dangerous when casting C++ objects. If | |
27826 | you need to cast a pointer or change its value, consider writing some | |
27827 | helper functions instead. For example:</P> | |
27828 | <DIV class="code"> | |
27829 | <PRE> | |
27830 | %inline %{ | |
27831 | /* C-style cast */ | |
27832 | Bar *FooToBar(Foo *f) { | |
27833 | return (Bar *) f; | |
27834 | } | |
27835 | ||
27836 | /* C++-style cast */ | |
27837 | Foo *BarToFoo(Bar *b) { | |
27838 | return dynamic_cast<Foo*>(b); | |
27839 | } | |
27840 | ||
27841 | Foo *IncrFoo(Foo *f, int i) { | |
27842 | return f+i; | |
27843 | } | |
27844 | %} | |
27845 | </PRE> | |
27846 | </DIV> | |
27847 | <P> Also, if working with C++, you should always try to use the new C++ | |
27848 | style casts. For example, in the above code, the C-style cast may | |
27849 | return a bogus result whereas as the C++-style cast will return <TT> | |
27850 | None</TT> if the conversion can't be performed.</P> | |
27851 | <H3><A name="Python_nn19"></A>26.3.6 Structures</H3> | |
27852 | <P> If you wrap a C structure, it is wrapped by a Python class. This | |
27853 | provides a very natural interface. For example,</P> | |
27854 | <DIV class="code"> | |
27855 | <PRE> | |
27856 | struct Vector { | |
27857 | double x,y,z; | |
27858 | }; | |
27859 | ||
27860 | </PRE> | |
27861 | </DIV> | |
27862 | <P> is used as follows:</P> | |
27863 | <DIV class="targetlang"> | |
27864 | <PRE> | |
27865 | >>> v = example.Vector() | |
27866 | >>> v.x = 3.5 | |
27867 | >>> v.y = 7.2 | |
27868 | >>> print v.x, v.y, v.z | |
27869 | 7.8 -4.5 0.0 | |
27870 | >>> | |
27871 | </PRE> | |
27872 | </DIV> | |
27873 | <P> Similar access is provided for unions and the data members of C++ | |
27874 | classes.</P> | |
27875 | <P> If you print out the value of <TT>v</TT> in the above example, you | |
27876 | will see something like this:</P> | |
27877 | <DIV class="targetlang"> | |
27878 | <PRE> | |
27879 | >>> print v | |
27880 | <C Vector instance at _18e31408_p_Vector> | |
27881 | </PRE> | |
27882 | </DIV> | |
27883 | <P> This object is actually a Python instance that has been wrapped | |
27884 | around a pointer to the low-level C structure. This instance doesn't | |
27885 | actually do anything--it just serves as a proxy. The pointer to the C | |
27886 | object can be found in the the <TT>.this</TT> attribute. For example:</P> | |
27887 | <DIV class="targetlang"> | |
27888 | <PRE> | |
27889 | >>> print v.this | |
27890 | _18e31408_p_Vector | |
27891 | >>> | |
27892 | </PRE> | |
27893 | </DIV> | |
27894 | <P> Further details about the Python proxy class are covered a little | |
27895 | later.</P> | |
27896 | <P> <TT>const</TT> members of a structure are read-only. Data members | |
27897 | can also be forced to be read-only using the <TT>%immutable</TT> | |
27898 | directive. For example:</P> | |
27899 | <DIV class="code"> | |
27900 | <PRE> | |
27901 | struct Foo { | |
27902 | ... | |
27903 | %immutable; | |
27904 | int x; /* Read-only members */ | |
27905 | char *name; | |
27906 | %mutable; | |
27907 | ... | |
27908 | }; | |
27909 | </PRE> | |
27910 | </DIV> | |
27911 | <P> When <TT>char *</TT> members of a structure are wrapped, the | |
27912 | contents are assumed to be dynamically allocated using <TT>malloc</TT> | |
27913 | or <TT>new</TT> (depending on whether or not SWIG is run with the -c++ | |
27914 | option). When the structure member is set, the old contents will be | |
27915 | released and a new value created. If this is not the behavior you want, | |
27916 | you will have to use a typemap (described later).</P> | |
27917 | <P> If a structure contains arrays, access to those arrays is managed | |
27918 | through pointers. For example, consider this:</P> | |
27919 | <DIV class="code"> | |
27920 | <PRE> | |
27921 | struct Bar { | |
27922 | int x[16]; | |
27923 | }; | |
27924 | </PRE> | |
27925 | </DIV> | |
27926 | <P> If accessed in Python, you will see behavior like this:</P> | |
27927 | <DIV class="targetlang"> | |
27928 | <PRE> | |
27929 | >>> b = example.Bar() | |
27930 | >>> print b.x | |
27931 | _801861a4_p_int | |
27932 | >>> | |
27933 | </PRE> | |
27934 | </DIV> | |
27935 | <P> This pointer can be passed around to functions that expect to | |
27936 | receive an <TT>int *</TT> (just like C). You can also set the value of | |
27937 | an array member using another pointer. For example:</P> | |
27938 | <DIV class="targetlang"> | |
27939 | <PRE> | |
27940 | >>> c = example.Bar() | |
27941 | >>> c.x = b.x # Copy contents of b.x to c.x | |
27942 | </PRE> | |
27943 | </DIV> | |
27944 | <P> For array assignment, SWIG copies the entire contents of the array | |
27945 | starting with the data pointed to by <TT>b.x</TT>. In this example, 16 | |
27946 | integers would be copied. Like C, SWIG makes no assumptions about | |
27947 | bounds checking---if you pass a bad pointer, you may get a segmentation | |
27948 | fault or access violation.</P> | |
27949 | <P> When a member of a structure is itself a structure, it is handled as | |
27950 | a pointer. For example, suppose you have two structures like this:</P> | |
27951 | <DIV class="code"> | |
27952 | <PRE> | |
27953 | struct Foo { | |
27954 | int a; | |
27955 | }; | |
27956 | ||
27957 | struct Bar { | |
27958 | Foo f; | |
27959 | }; | |
27960 | </PRE> | |
27961 | </DIV> | |
27962 | <P> Now, suppose that you access the <TT>f</TT> attribute of <TT>Bar</TT> | |
27963 | like this:</P> | |
27964 | <DIV class="targetlang"> | |
27965 | <PRE> | |
27966 | >>> b = Bar() | |
27967 | >>> x = b.f | |
27968 | </PRE> | |
27969 | </DIV> | |
27970 | <P> In this case, <TT>x</TT> is a pointer that points to the <TT>Foo</TT> | |
27971 | that is inside <TT>b</TT>. This is the same value as generated by this | |
27972 | C code:</P> | |
27973 | <DIV class="code"> | |
27974 | <PRE> | |
27975 | Bar b; | |
27976 | Foo *x = &b->f; /* Points inside b */ | |
27977 | </PRE> | |
27978 | </DIV> | |
27979 | <P> Because the pointer points inside the structure, you can modify the | |
27980 | contents and everything works just like you would expect. For example:</P> | |
27981 | <DIV class="targetlang"> | |
27982 | <PRE> | |
27983 | >>> b = Bar() | |
27984 | >>> b.f.a = 3 # Modify attribute of structure member | |
27985 | >>> x = b.f | |
27986 | >>> x.a = 3 # Modifies the same structure | |
27987 | </PRE> | |
27988 | </DIV> | |
27989 | <H3><A name="Python_nn20"></A>26.3.7 C++ classes</H3> | |
27990 | <P> C++ classes are wrapped by Python classes as well. For example, if | |
27991 | you have this class,</P> | |
27992 | <DIV class="code"> | |
27993 | <PRE> | |
27994 | class List { | |
27995 | public: | |
27996 | List(); | |
27997 | ~List(); | |
27998 | int search(char *item); | |
27999 | void insert(char *item); | |
28000 | void remove(char *item); | |
28001 | char *get(int n); | |
28002 | int length; | |
28003 | }; | |
28004 | </PRE> | |
28005 | </DIV> | |
28006 | <P> you can use it in Python like this:</P> | |
28007 | <DIV class="targetlang"> | |
28008 | <PRE> | |
28009 | >>> l = example.List() | |
28010 | >>> l.insert("Ale") | |
28011 | >>> l.insert("Stout") | |
28012 | >>> l.insert("Lager") | |
28013 | >>> l.get(1) | |
28014 | 'Stout' | |
28015 | >>> print l.length | |
28016 | 3 | |
28017 | >>> | |
28018 | </PRE> | |
28019 | </DIV> | |
28020 | <P> Class data members are accessed in the same manner as C structures.</P> | |
28021 | <P> Static class members present a special problem for Python. Prior to | |
28022 | Python-2.2, Python classes had no support for static methods and no | |
28023 | version of Python supports static member variables in a manner that | |
28024 | SWIG can utilize. Therefore, SWIG generates wrappers that try to work | |
28025 | around some of these issues. To illustrate, suppose you have a class | |
28026 | like this:</P> | |
28027 | <DIV class="code"> | |
28028 | <PRE> | |
28029 | class Spam { | |
28030 | public: | |
28031 | static void foo(); | |
28032 | static int bar; | |
28033 | ||
28034 | }; | |
28035 | </PRE> | |
28036 | </DIV> | |
28037 | <P> In Python, the static member can be access in three different ways:</P> | |
28038 | <DIV class="targetlang"> | |
28039 | <PRE> | |
28040 | >>> example.Spam_foo() # Spam::foo() | |
28041 | >>> s = example.Spam() | |
28042 | >>> s.foo() # Spam::foo() via an instance | |
28043 | >>> example.Spam.foo() # Spam::foo(). Python-2.2 only | |
28044 | </PRE> | |
28045 | </DIV> | |
28046 | <P> The first two methods of access are supported in all versions of | |
28047 | Python. The last technique is only available in Python-2.2 and later | |
28048 | versions.</P> | |
28049 | <P> Static member variables are currently accessed as global variables. | |
28050 | This means, they are accessed through <TT>cvar</TT> like this:</P> | |
28051 | <DIV class="targetlang"> | |
28052 | <PRE> | |
28053 | >>> print example.cvar.Spam_bar | |
28054 | 7 | |
28055 | </PRE> | |
28056 | </DIV> | |
28057 | <H3><A name="Python_nn21"></A>26.3.8 C++ inheritance</H3> | |
28058 | <P> SWIG is fully aware of issues related to C++ inheritance. Therefore, | |
28059 | if you have classes like this</P> | |
28060 | <DIV class="code"> | |
28061 | <PRE> | |
28062 | class Foo { | |
28063 | ... | |
28064 | }; | |
28065 | ||
28066 | class Bar : public Foo { | |
28067 | ... | |
28068 | }; | |
28069 | </PRE> | |
28070 | </DIV> | |
28071 | <P> those classes are wrapped into a hierarchy of Python classes that | |
28072 | reflect the same inheritance structure. All of the usual Python utility | |
28073 | functions work normally:</P> | |
28074 | <DIV class="targetlang"> | |
28075 | <PRE> | |
28076 | >>> b = Bar() | |
28077 | >>> instance(b,Foo) | |
28078 | 1 | |
28079 | >>> issubclass(Bar,Foo) | |
28080 | 1 | |
28081 | >>> issubclass(Foo,Bar) | |
28082 | 0 | |
28083 | </PRE> | |
28084 | </DIV> | |
28085 | <P> Furthermore, if you have functions like this</P> | |
28086 | <DIV class="code"> | |
28087 | <PRE> | |
28088 | void spam(Foo *f); | |
28089 | </PRE> | |
28090 | </DIV> | |
28091 | <P> then the function <TT>spam()</TT> accepts <TT>Foo *</TT> or a | |
28092 | pointer to any class derived from <TT>Foo</TT>.</P> | |
28093 | <P> It is safe to use multiple inheritance with SWIG.</P> | |
28094 | <H3><A name="Python_nn22"></A>26.3.9 Pointers, references, values, and | |
28095 | arrays</H3> | |
28096 | <P> In C++, there are many different ways a function might receive and | |
28097 | manipulate objects. For example:</P> | |
28098 | <DIV class="code"> | |
28099 | <PRE> | |
28100 | void spam1(Foo *x); // Pass by pointer | |
28101 | void spam2(Foo &x); // Pass by reference | |
28102 | void spam3(const Foo &x);// Pass by const reference | |
28103 | void spam4(Foo x); // Pass by value | |
28104 | void spam5(Foo x[]); // Array of objects | |
28105 | </PRE> | |
28106 | </DIV> | |
28107 | <P> In Python, there is no detailed distinction like this--specifically, | |
28108 | there are only "objects". There are no pointers, references, arrays, | |
28109 | and so forth. Because of this, SWIG unifies all of these types together | |
28110 | in the wrapper code. For instance, if you actually had the above | |
28111 | functions, it is perfectly legal to do this:</P> | |
28112 | <DIV class="targetlang"> | |
28113 | <PRE> | |
28114 | >>> f = Foo() # Create a Foo | |
28115 | >>> spam1(f) # Ok. Pointer | |
28116 | >>> spam2(f) # Ok. Reference | |
28117 | >>> spam3(f) # Ok. Const reference | |
28118 | >>> spam4(f) # Ok. Value. | |
28119 | >>> spam5(f) # Ok. Array (1 element) | |
28120 | </PRE> | |
28121 | </DIV> | |
28122 | <P> Similar behavior occurs for return values. For example, if you had | |
28123 | functions like this,</P> | |
28124 | <DIV class="code"> | |
28125 | <PRE> | |
28126 | Foo *spam6(); | |
28127 | Foo &spam7(); | |
28128 | Foo spam8(); | |
28129 | const Foo &spam9(); | |
28130 | </PRE> | |
28131 | </DIV> | |
28132 | <P> then all three functions will return a pointer to some <TT>Foo</TT> | |
28133 | object. Since the third function (spam8) returns a value, newly | |
28134 | allocated memory is used to hold the result and a pointer is returned | |
28135 | (Python will release this memory when the return value is garbage | |
28136 | collected). The fourth case (spam9) which returns a const reference, in | |
28137 | most of the cases will be treated as a returning value, and it will | |
28138 | follow the same allocation/deallocation process.</P> | |
28139 | <H3><A name="Python_nn23"></A>26.3.10 C++ overloaded functions</H3> | |
28140 | <P> C++ overloaded functions, methods, and constructors are mostly | |
28141 | supported by SWIG. For example, if you have two functions like this:</P> | |
28142 | <DIV class="code"> | |
28143 | <PRE> | |
28144 | void foo(int); | |
28145 | void foo(char *c); | |
28146 | </PRE> | |
28147 | </DIV> | |
28148 | <P> You can use them in Python in a straightforward manner:</P> | |
28149 | <DIV class="targetlang"> | |
28150 | <PRE> | |
28151 | >>> foo(3) # foo(int) | |
28152 | >>> foo("Hello") # foo(char *c) | |
28153 | </PRE> | |
28154 | </DIV> | |
28155 | <P> Similarly, if you have a class like this,</P> | |
28156 | <DIV class="code"> | |
28157 | <PRE> | |
28158 | class Foo { | |
28159 | public: | |
28160 | Foo(); | |
28161 | Foo(const Foo &); | |
28162 | ... | |
28163 | }; | |
28164 | </PRE> | |
28165 | </DIV> | |
28166 | <P> you can write Python code like this:</P> | |
28167 | <DIV class="targetlang"> | |
28168 | <PRE> | |
28169 | >>> f = Foo() # Create a Foo | |
28170 | >>> g = Foo(f) # Copy f | |
28171 | </PRE> | |
28172 | </DIV> | |
28173 | <P> Overloading support is not quite as flexible as in C++. Sometimes | |
28174 | there are methods that SWIG can't disambiguate. For example:</P> | |
28175 | <DIV class="code"> | |
28176 | <PRE> | |
28177 | void spam(int); | |
28178 | void spam(short); | |
28179 | </PRE> | |
28180 | </DIV> | |
28181 | <P> or</P> | |
28182 | <DIV class="code"> | |
28183 | <PRE> | |
28184 | void foo(Bar *b); | |
28185 | void foo(Bar &b); | |
28186 | </PRE> | |
28187 | </DIV> | |
28188 | <P> If declarations such as these appear, you will get a warning message | |
28189 | like this:</P> | |
28190 | <DIV class="shell"> | |
28191 | <PRE> | |
28192 | example.i:12: Warning(509): Overloaded spam(short) is shadowed by spam(int) | |
28193 | at example.i:11. | |
28194 | </PRE> | |
28195 | </DIV> | |
28196 | <P> To fix this, you either need to ignore or rename one of the methods. | |
28197 | For example:</P> | |
28198 | <DIV class="code"> | |
28199 | <PRE> | |
28200 | %rename(spam_short) spam(short); | |
28201 | ... | |
28202 | void spam(int); | |
28203 | void spam(short); // Accessed as spam_short | |
28204 | </PRE> | |
28205 | </DIV> | |
28206 | <P> or</P> | |
28207 | <DIV class="code"> | |
28208 | <PRE> | |
28209 | %ignore spam(short); | |
28210 | ... | |
28211 | void spam(int); | |
28212 | void spam(short); // Ignored | |
28213 | </PRE> | |
28214 | </DIV> | |
28215 | <P> SWIG resolves overloaded functions and methods using a | |
28216 | disambiguation scheme that ranks and sorts declarations according to a | |
28217 | set of type-precedence rules. The order in which declarations appear in | |
28218 | the input does not matter except in situations where ambiguity | |
28219 | arises--in this case, the first declaration takes precedence.</P> | |
28220 | <P> Please refer to the "SWIG and C++" chapter for more information | |
28221 | about overloading.</P> | |
28222 | <H3><A name="Python_nn24"></A>26.3.11 C++ operators</H3> | |
28223 | <P> Certain C++ overloaded operators can be handled automatically by | |
28224 | SWIG. For example, consider a class like this:</P> | |
28225 | <DIV class="code"> | |
28226 | <PRE> | |
28227 | class Complex { | |
28228 | private: | |
28229 | double rpart, ipart; | |
28230 | public: | |
28231 | Complex(double r = 0, double i = 0) : rpart(r), ipart(i) { } | |
28232 | Complex(const Complex &c) : rpart(c.rpart), ipart(c.ipart) { } | |
28233 | Complex &operator=(const Complex &c); | |
28234 | ||
28235 | Complex operator+=(const Complex &c) const; | |
28236 | Complex operator+(const Complex &c) const; | |
28237 | Complex operator-(const Complex &c) const; | |
28238 | Complex operator*(const Complex &c) const; | |
28239 | Complex operator-() const; | |
28240 | ||
28241 | double re() const { return rpart; } | |
28242 | double im() const { return ipart; } | |
28243 | }; | |
28244 | </PRE> | |
28245 | </DIV> | |
28246 | <P> When wrapped, it works like you expect:</P> | |
28247 | <DIV class="targetlang"> | |
28248 | <PRE> | |
28249 | >>> c = Complex(3,4) | |
28250 | >>> d = Complex(7,8) | |
28251 | >>> e = c + d | |
28252 | >>> e.re() | |
28253 | 10.0 | |
28254 | >>> e.im() | |
28255 | 12.0 | |
28256 | >>> c += d | |
28257 | >>> c.re() | |
28258 | 10.0 | |
28259 | >>> c.im() | |
28260 | 12.0 | |
28261 | ||
28262 | </PRE> | |
28263 | </DIV> | |
28264 | <P> One restriction with operator overloading support is that SWIG is | |
28265 | not able to fully handle operators that aren't defined as part of the | |
28266 | class. For example, if you had code like this</P> | |
28267 | <DIV class="code"> | |
28268 | <PRE> | |
28269 | class Complex { | |
28270 | ... | |
28271 | friend Complex operator+(double, const Complex &c); | |
28272 | ... | |
28273 | }; | |
28274 | </PRE> | |
28275 | </DIV> | |
28276 | <P> then SWIG ignores it and issues a warning. You can still wrap the | |
28277 | operator, but you may have to encapsulate it in a special function. For | |
28278 | example:</P> | |
28279 | <DIV class="code"> | |
28280 | <PRE> | |
28281 | %rename(Complex_add_dc) operator+(double, const Complex &); | |
28282 | </PRE> | |
28283 | </DIV> | |
28284 | <P> There are ways to make this operator appear as part of the class | |
28285 | using the <TT>%extend</TT> directive. Keep reading.</P> | |
28286 | <P> Also, be aware that certain operators don't map cleanly to Python. | |
28287 | For instance, overloaded assignment operators don't map to Python | |
28288 | semantics and will be ignored.</P> | |
28289 | <H3><A name="Python_nn25"></A>26.3.12 C++ namespaces</H3> | |
28290 | <P> SWIG is aware of C++ namespaces, but namespace names do not appear | |
28291 | in the module nor do namespaces result in a module that is broken up | |
28292 | into submodules or packages. For example, if you have a file like this,</P> | |
28293 | <DIV class="code"> | |
28294 | <PRE> | |
28295 | %module example | |
28296 | ||
28297 | namespace foo { | |
28298 | int fact(int n); | |
28299 | struct Vector { | |
28300 | double x,y,z; | |
28301 | }; | |
28302 | }; | |
28303 | </PRE> | |
28304 | </DIV> | |
28305 | <P> it works in Python as follows:</P> | |
28306 | <DIV class="targetlang"> | |
28307 | <PRE> | |
28308 | >>> import example | |
28309 | >>> example.fact(3) | |
28310 | 6 | |
28311 | >>> v = example.Vector() | |
28312 | >>> v.x = 3.4 | |
28313 | >>> print v.y | |
28314 | 0.0 | |
28315 | >>> | |
28316 | </PRE> | |
28317 | </DIV> | |
28318 | <P> If your program has more than one namespace, name conflicts (if any) | |
28319 | can be resolved using <TT>%rename</TT> For example:</P> | |
28320 | <DIV class="code"> | |
28321 | <PRE> | |
28322 | %rename(Bar_spam) Bar::spam; | |
28323 | ||
28324 | namespace Foo { | |
28325 | int spam(); | |
28326 | } | |
28327 | ||
28328 | namespace Bar { | |
28329 | int spam(); | |
28330 | } | |
28331 | </PRE> | |
28332 | </DIV> | |
28333 | <P> If you have more than one namespace and your want to keep their | |
28334 | symbols separate, consider wrapping them as separate SWIG modules. For | |
28335 | example, make the module name the same as the namespace and create | |
28336 | extension modules for each namespace separately. If your program | |
28337 | utilizes thousands of small deeply nested namespaces each with | |
28338 | identical symbol names, well, then you get what you deserve.</P> | |
28339 | <H3><A name="Python_nn26"></A>26.3.13 C++ templates</H3> | |
28340 | <P> C++ templates don't present a huge problem for SWIG. However, in | |
28341 | order to create wrappers, you have to tell SWIG to create wrappers for | |
28342 | a particular template instantiation. To do this, you use the <TT> | |
28343 | %template</TT> directive. For example:</P> | |
28344 | <DIV class="code"> | |
28345 | <PRE> | |
28346 | %module example | |
28347 | %{ | |
28348 | #include "pair.h" | |
28349 | %} | |
28350 | ||
28351 | template<class T1, class T2> | |
28352 | struct pair { | |
28353 | typedef T1 first_type; | |
28354 | typedef T2 second_type; | |
28355 | T1 first; | |
28356 | T2 second; | |
28357 | pair(); | |
28358 | pair(const T1&, const T2&); | |
28359 | ~pair(); | |
28360 | }; | |
28361 | ||
28362 | %template(pairii) pair<int,int>; | |
28363 | </PRE> | |
28364 | </DIV> | |
28365 | <P> In Python:</P> | |
28366 | <DIV class="targetlang"> | |
28367 | <PRE> | |
28368 | >>> import example | |
28369 | >>> p = example.pairii(3,4) | |
28370 | >>> p.first | |
28371 | 3 | |
28372 | >>> p.second | |
28373 | 4 | |
28374 | </PRE> | |
28375 | </DIV> | |
28376 | <P> Obviously, there is more to template wrapping than shown in this | |
28377 | example. More details can be found in the <A href="#SWIGPlus">SWIG and | |
28378 | C++</A> chapter. Some more complicated examples will appear later.</P> | |
28379 | <H3><A name="Python_nn27"></A>26.3.14 C++ Smart Pointers</H3> | |
28380 | <P> In certain C++ programs, it is common to use classes that have been | |
28381 | wrapped by so-called "smart pointers." Generally, this involves the use | |
28382 | of a template class that implements <TT>operator->()</TT> like this:</P> | |
28383 | <DIV class="code"> | |
28384 | <PRE> | |
28385 | template<class T> class SmartPtr { | |
28386 | ... | |
28387 | T *operator->(); | |
28388 | ... | |
28389 | } | |
28390 | </PRE> | |
28391 | </DIV> | |
28392 | <P> Then, if you have a class like this,</P> | |
28393 | <DIV class="code"> | |
28394 | <PRE> | |
28395 | class Foo { | |
28396 | public: | |
28397 | int x; | |
28398 | int bar(); | |
28399 | }; | |
28400 | </PRE> | |
28401 | </DIV> | |
28402 | <P> A smart pointer would be used in C++ as follows:</P> | |
28403 | <DIV class="code"> | |
28404 | <PRE> | |
28405 | SmartPtr<Foo> p = CreateFoo(); // Created somehow (not shown) | |
28406 | ... | |
28407 | p->x = 3; // Foo::x | |
28408 | int y = p->bar(); // Foo::bar | |
28409 | </PRE> | |
28410 | </DIV> | |
28411 | <P> To wrap this in Python, simply tell SWIG about the <TT>SmartPtr</TT> | |
28412 | class and the low-level <TT>Foo</TT> object. Make sure you instantiate <TT> | |
28413 | SmartPtr</TT> using <TT>%template</TT> if necessary. For example:</P> | |
28414 | <DIV class="code"> | |
28415 | <PRE> | |
28416 | %module example | |
28417 | ... | |
28418 | %template(SmartPtrFoo) SmartPtr<Foo>; | |
28419 | ... | |
28420 | </PRE> | |
28421 | </DIV> | |
28422 | <P> Now, in Python, everything should just "work":</P> | |
28423 | <DIV class="targetlang"> | |
28424 | <PRE> | |
28425 | >>> p = example.CreateFoo() # Create a smart-pointer somehow | |
28426 | >>> p.x = 3 # Foo::x | |
28427 | >>> p.bar() # Foo::bar | |
28428 | </PRE> | |
28429 | </DIV> | |
28430 | <P> If you ever need to access the underlying pointer returned by <TT> | |
28431 | operator->()</TT> itself, simply use the <TT>__deref__()</TT> method. | |
28432 | For example:</P> | |
28433 | <DIV class="targetlang"> | |
28434 | <PRE> | |
28435 | >>> f = p.__deref__() # Returns underlying Foo * | |
28436 | </PRE> | |
28437 | </DIV> | |
28438 | <H3><A name="Python_nn27a"></A>26.3.15 C++ Reference Counted Objects | |
28439 | (ref/unref)</H3> | |
28440 | <P> Another usual idiom in C++ is the use of reference counted objects. | |
28441 | Consider for example:<DIV class="code"> | |
28442 | <PRE> | |
28443 | class RCObj { | |
28444 | // implement the ref counting mechanism | |
28445 | int add_ref(); | |
28446 | int del_ref(); | |
28447 | int ref_count(); | |
28448 | ||
28449 | public: | |
28450 | virtual ~RCObj() = 0; | |
28451 | ||
28452 | int ref() const { | |
28453 | return add_ref(); | |
28454 | } | |
28455 | ||
28456 | int unref() const { | |
28457 | if (ref_count() == 0 || del_ref() == 0 ) { | |
28458 | delete this; | |
28459 | return 0; | |
28460 | } | |
28461 | return ref_count(); | |
28462 | } | |
28463 | }; | |
28464 | ||
28465 | ||
28466 | class A : RCObj { | |
28467 | public: | |
28468 | A(); | |
28469 | int foo(); | |
28470 | }; | |
28471 | ||
28472 | ||
28473 | class B { | |
28474 | A *_a; | |
28475 | ||
28476 | public: | |
28477 | B(A *a) : _a(a) { | |
28478 | a->ref(); | |
28479 | } | |
28480 | ||
28481 | ~B() { | |
28482 | a->unref(); | |
28483 | } | |
28484 | }; | |
28485 | ||
28486 | int main() { | |
28487 | A *a = new A(); | |
28488 | a->ref(); // 'a' is ref here | |
28489 | ||
28490 | B *b1 = new B(a); // 'a' is ref here | |
28491 | if (1 + 1 == 2) { | |
28492 | B *b2 = new B(a); // 'a' is ref here | |
28493 | delete b2; // 'a' is unref, but not deleted | |
28494 | } | |
28495 | ||
28496 | delete b1; // 'a' is unref, but not deleted | |
28497 | a->unref(); // 'a' is unref and deleted | |
28498 | } | |
28499 | </PRE> | |
28500 | </DIV></P> | |
28501 | <P> In the example above, the 'A' class instance 'a' is a reference | |
28502 | counted object, which can't be deleted arbitrarily since it is shared | |
28503 | between the objects 'b1' and 'b2'. 'A' is derived from an Reference | |
28504 | Counted Object 'RCObj', which implements the ref/unref idiom.</P> | |
28505 | <P> To tell SWIG that 'RCObj' and all its derived classes are reference | |
28506 | counted objects, you use the "ref" and "unref" features. For example:</P> | |
28507 | <DIV class="code"> | |
28508 | <PRE> | |
28509 | %module example | |
28510 | ... | |
28511 | ||
28512 | %feature("ref") RCObj "$this->ref();" | |
28513 | %feature("unref") RCObj "$this->unref();" | |
28514 | ||
28515 | %include "rcobj.h" | |
28516 | %include "A.h" | |
28517 | ... | |
28518 | </PRE> | |
28519 | </DIV> | |
28520 | <P> where the code passed to the "ref" and "unref" methods will be | |
28521 | executed as needed whenever a new object is passed to python, or when | |
28522 | python tries to release the shadow object instance, respectively.</P> | |
28523 | <P> In the python side, the use of a reference counted object is not | |
28524 | different than any other regular instance:</P> | |
28525 | <DIV class="targetlang"> | |
28526 | <PRE> | |
28527 | def create_A(): | |
28528 | a = A() # SWIG ref 'a' (new object is passed to python) | |
28529 | b1 = B(a) # C++ ref 'a' | |
28530 | if 1 + 1 == 2: | |
28531 | b2 = B(a) # C++ ref 'a' | |
28532 | return a # 'b1' and 'b2' are released, C++ unref 'a' twice | |
28533 | ||
28534 | a = create_A() | |
28535 | exit # 'a' is released, SWIG unref 'a' | |
28536 | </PRE> | |
28537 | </DIV> | |
28538 | <P> Note that the user doens't explicitly need to call 'a->ref()' nor | |
28539 | 'a->unref()' (as neither 'delete a'). Instead, SWIG take cares of | |
28540 | executing the "ref" and "unref" codes as needed. If the user doesn't | |
28541 | specify the "ref/unref" features, SWIG will produce a code equivalent | |
28542 | to define them as:</P> | |
28543 | <DIV class="code"> | |
28544 | <PRE> | |
28545 | %feature("ref") "" | |
28546 | %feature("unref") "delete $this;" | |
28547 | </PRE> | |
28548 | </DIV> | |
28549 | <P> In other words, SWIG will not do anything special when a new object | |
28550 | is passed to python, and it will always 'delete' the object when python | |
28551 | releases the shadow instance.</P> | |
28552 | <H2><A name="Python_nn28"></A>26.4 Further details on the Python class | |
28553 | interface</H2> | |
28554 | <P> In the previous section, a high-level view of Python wrapping was | |
28555 | presented. A key component of this wrapping is that structures and | |
28556 | classes are wrapped by Python proxy classes. This provides a very | |
28557 | natural Python interface and allows SWIG to support a number of | |
28558 | advanced features such as operator overloading. However, a number of | |
28559 | low-level details were omitted. This section provides a brief overview | |
28560 | of how the proxy classes work.</P> | |
28561 | <H3><A name="Python_nn29"></A>26.4.1 Proxy classes</H3> | |
28562 | <P> In the <A href="#SWIG">"SWIG basics"</A> and <A href="#SWIGPlus"> | |
28563 | "SWIG and C++"</A> chapters, details of low-level structure and class | |
28564 | wrapping are described. To summarize those chapters, if you have a | |
28565 | class like this</P> | |
28566 | <DIV class="code"> | |
28567 | <PRE> | |
28568 | class Foo { | |
28569 | public: | |
28570 | int x; | |
28571 | int spam(int); | |
28572 | ... | |
28573 | </PRE> | |
28574 | </DIV> | |
28575 | <P> then SWIG transforms it into a set of low-level procedural wrappers. | |
28576 | For example:</P> | |
28577 | <DIV class="code"> | |
28578 | <PRE> | |
28579 | Foo *new_Foo() { | |
28580 | return new Foo(); | |
28581 | } | |
28582 | void delete_Foo(Foo *f) { | |
28583 | delete f; | |
28584 | } | |
28585 | int Foo_x_get(Foo *f) { | |
28586 | return f->x; | |
28587 | } | |
28588 | void Foo_x_set(Foo *f, int value) { | |
28589 | f->x = value; | |
28590 | } | |
28591 | int Foo_spam(Foo *f, int arg1) { | |
28592 | return f->spam(arg1); | |
28593 | } | |
28594 | </PRE> | |
28595 | </DIV> | |
28596 | <P> These wrappers can be found in the low-level extension module (e.g., | |
28597 | <TT>_example</TT>).</P> | |
28598 | <P> Using these wrappers, SWIG generates a high-level Python proxy class | |
28599 | (also known as a shadow class) like this (shown for Python 2.2):</P> | |
28600 | <DIV class="targetlang"> | |
28601 | <PRE> | |
28602 | import _example | |
28603 | ||
28604 | class Foo(object): | |
28605 | def __init__(self): | |
28606 | self.this = _example.new_Foo() | |
28607 | self.thisown = 1 | |
28608 | def __del__(self): | |
28609 | if self.thisown: | |
28610 | _example.delete_Foo(self.this) | |
28611 | def spam(self,arg1): | |
28612 | return _example.Foo_spam(self.this,arg1) | |
28613 | x = property(_example.Foo_x_get, _example.Foo_x_set) | |
28614 | </PRE> | |
28615 | </DIV> | |
28616 | <P> This class merely holds a pointer to the underlying C++ object (<TT> | |
28617 | .this</TT>) and dispatches methods and member variable access to that | |
28618 | object using the low-level accessor functions. From a user's point of | |
28619 | view, it makes the class work normally:</P> | |
28620 | <DIV class="targetlang"> | |
28621 | <PRE> | |
28622 | >>> f = example.Foo() | |
28623 | >>> f.x = 3 | |
28624 | >>> y = f.spam(5) | |
28625 | </PRE> | |
28626 | </DIV> | |
28627 | <P> The fact that the class has been wrapped by a real Python class | |
28628 | offers certain advantages. For instance, you can attach new Python | |
28629 | methods to the class and you can even inherit from it (something not | |
28630 | supported by Python built-in types until Python 2.2).</P> | |
28631 | <H3><A name="Python_nn30"></A>26.4.2 Memory management</H3> | |
28632 | <P> Associated with proxy object, is an ownership flag <TT>.thisown</TT> | |
28633 | The value of this flag determines who is responsible for deleting the | |
28634 | underlying C++ object. If set to 1, the Python interpreter will destroy | |
28635 | the C++ object when the proxy class is garbage collected. If set to 0 | |
28636 | (or if the attribute is missing), then the destruction of the proxy | |
28637 | class has no effect on the C++ object.</P> | |
28638 | <P> When an object is created by a constructor or returned by value, | |
28639 | Python automatically takes ownership of the result. For example:</P> | |
28640 | <DIV class="code"> | |
28641 | <PRE> | |
28642 | class Foo { | |
28643 | public: | |
28644 | Foo(); | |
28645 | Foo bar(); | |
28646 | }; | |
28647 | </PRE> | |
28648 | </DIV> | |
28649 | <P> In Python:</P> | |
28650 | <DIV class="targetlang"> | |
28651 | <PRE> | |
28652 | >>> f = Foo() | |
28653 | >>> f.thisown | |
28654 | 1 | |
28655 | >>> g = f.bar() | |
28656 | >>> g.thisown | |
28657 | 1 | |
28658 | </PRE> | |
28659 | </DIV> | |
28660 | <P> On the other hand, when pointers are returned to Python, there is | |
28661 | often no way to know where they came from. Therefore, the ownership is | |
28662 | set to zero. For example:</P> | |
28663 | <DIV class="code"> | |
28664 | <PRE> | |
28665 | class Foo { | |
28666 | public: | |
28667 | ... | |
28668 | Foo *spam(); | |
28669 | ... | |
28670 | }; | |
28671 | </PRE> | |
28672 | </DIV> | |
28673 | <BR><DIV class="targetlang"> | |
28674 | <PRE> | |
28675 | >>> f = Foo() | |
28676 | >>> s = f.spam() | |
28677 | >>> print s.thisown | |
28678 | 0 | |
28679 | >>> | |
28680 | </PRE> | |
28681 | </DIV> | |
28682 | <P> This behavior is especially important for classes that act as | |
28683 | containers. For example, if a method returns a pointer to an object | |
28684 | that is contained inside another object, you definitely don't want | |
28685 | Python to assume ownership and destroy it!</P> | |
28686 | <P> Related to containers, ownership issues can arise whenever an object | |
28687 | is assigned to a member or global variable. For example, consider this | |
28688 | interface:</P> | |
28689 | <DIV class="code"> | |
28690 | <PRE> | |
28691 | %module example | |
28692 | ||
28693 | struct Foo { | |
28694 | int value; | |
28695 | Foo *next; | |
28696 | }; | |
28697 | ||
28698 | Foo *head = 0; | |
28699 | </PRE> | |
28700 | </DIV> | |
28701 | <P> When wrapped in Python, careful observation will reveal that | |
28702 | ownership changes whenever an object is assigned to a global variable. | |
28703 | For example:</P> | |
28704 | <DIV class="targetlang"> | |
28705 | <PRE> | |
28706 | >>> f = example.Foo() | |
28707 | >>> f.thisown | |
28708 | 1 | |
28709 | >>> example.cvar.head = f | |
28710 | >>> f.thisown | |
28711 | 0 | |
28712 | >>> | |
28713 | </PRE> | |
28714 | </DIV> | |
28715 | <P> In this case, C is now holding a reference to the object---you | |
28716 | probably don't want Python to destroy it. Similarly, this occurs for | |
28717 | members. For example:</P> | |
28718 | <DIV class="targetlang"> | |
28719 | <PRE> | |
28720 | >>> f = example.Foo() | |
28721 | >>> g = example.Foo() | |
28722 | >>> f.thisown | |
28723 | 1 | |
28724 | >>> g.thisown | |
28725 | 1 | |
28726 | >>> f.next = g | |
28727 | >>> g.thisown | |
28728 | 0 | |
28729 | >>> | |
28730 | </PRE> | |
28731 | </DIV> | |
28732 | <P> For the most part, memory management issues remain hidden. However, | |
28733 | there are occasionally situations where you might have to manually | |
28734 | change the ownership of an object. For instance, consider code like | |
28735 | this:</P> | |
28736 | <DIV class="code"> | |
28737 | <PRE> | |
28738 | class Node { | |
28739 | Object *value; | |
28740 | public: | |
28741 | void set_value(Object *v) { value = v; } | |
28742 | ... | |
28743 | }; | |
28744 | </PRE> | |
28745 | </DIV> | |
28746 | <P> Now, consider the following Python code:</P> | |
28747 | <DIV class="targetlang"> | |
28748 | <PRE> | |
28749 | >>> v = Object() # Create an object | |
28750 | >>> n = Node() # Create a node | |
28751 | >>> n.set_value(v) # Set value | |
28752 | >>> v.thisown | |
28753 | 1 | |
28754 | >>> del v | |
28755 | </PRE> | |
28756 | </DIV> | |
28757 | <P> In this case, the object <TT>n</TT> is holding a reference to <TT>v</TT> | |
28758 | internally. However, SWIG has no way to know that this has occurred. | |
28759 | Therefore, Python still thinks that it has ownership of the object. | |
28760 | Should the proxy object be destroyed, then the C++ destructor will be | |
28761 | invoked and <TT>n</TT> will be holding a stale-pointer. If you're | |
28762 | lucky, you will only get a segmentation fault.</P> | |
28763 | <P> To work around this, it is always possible to flip the ownership | |
28764 | flag. For example,</P> | |
28765 | <DIV class="targetlang"> | |
28766 | <PRE> | |
28767 | >>> v.thisown = 0 | |
28768 | </PRE> | |
28769 | </DIV> | |
28770 | <P> It is also possible to deal with situations like this using | |
28771 | typemaps--an advanced topic discussed later.</P> | |
28772 | <H3><A name="Python_nn31"></A>26.4.3 Python 2.2 and classic classes</H3> | |
28773 | <P> SWIG makes every attempt to preserve backwards compatibility with | |
28774 | older versions of Python to the extent that it is possible. However, in | |
28775 | Python-2.2, an entirely new type of class system was introduced. This | |
28776 | new-style class system offers many enhancements including static member | |
28777 | functions, properties (managed attributes), and class methods. Details | |
28778 | about all of these changes can be found on <A href="//www.python.org"> | |
28779 | www.python.org</A> and is not repeated here.</P> | |
28780 | <P> To address differences between Python versions, SWIG currently emits | |
28781 | dual-mode proxy class wrappers. In Python-2.2 and newer releases, these | |
28782 | wrappers encapsulate C++ objects in new-style classes that take | |
28783 | advantage of new features (static methods and properties). However, if | |
28784 | these very same wrappers are imported into an older version of Python, | |
28785 | old-style classes are used instead.</P> | |
28786 | <P> This dual-nature of the wrapper code means that you can create | |
28787 | extension modules with SWIG and those modules will work with all | |
28788 | versions of Python ranging from Python-1.4 to the very latest release. | |
28789 | Moreover, the wrappers take advantage of Python-2.2 features when | |
28790 | available.</P> | |
28791 | <P> For the most part, the interface presented to users is the same | |
28792 | regardless of what version of Python is used. The only incompatibility | |
28793 | lies in the handling of static member functions. In Python-2.2, they | |
28794 | can be accessed via the class itself. In Python-2.1 and earlier, they | |
28795 | have to be accessed as a global function or through an instance (see | |
28796 | the earlier section).</P> | |
28797 | <H2><A name="directors"></A>26.5 Cross language polymorphism</H2> | |
28798 | <P> Proxy classes provide a more natural, object-oriented way to access | |
28799 | extension classes. As described above, each proxy instance has an | |
28800 | associated C++ instance, and method calls to the proxy are passed to | |
28801 | the C++ instance transparently via C wrapper functions.</P> | |
28802 | <P> This arrangement is asymmetric in the sense that no corresponding | |
28803 | mechanism exists to pass method calls down the inheritance chain from | |
28804 | C++ to Python. In particular, if a C++ class has been extended in | |
28805 | Python (by extending the proxy class), these extensions will not be | |
28806 | visible from C++ code. Virtual method calls from C++ are thus not able | |
28807 | access the lowest implementation in the inheritance chain.</P> | |
28808 | <P> Changes have been made to SWIG 1.3.18 to address this problem and | |
28809 | make the relationship between C++ classes and proxy classes more | |
28810 | symmetric. To achieve this goal, new classes called directors are | |
28811 | introduced at the bottom of the C++ inheritance chain. The job of the | |
28812 | directors is to route method calls correctly, either to C++ | |
28813 | implementations higher in the inheritance chain or to Python | |
28814 | implementations lower in the inheritance chain. The upshot is that C++ | |
28815 | classes can be extended in Python and from C++ these extensions look | |
28816 | exactly like native C++ classes. Neither C++ code nor Python code needs | |
28817 | to know where a particular method is implemented: the combination of | |
28818 | proxy classes, director classes, and C wrapper functions takes care of | |
28819 | all the cross-language method routing transparently.</P> | |
28820 | <H3><A name="Python_nn33"></A>26.5.1 Enabling directors</H3> | |
28821 | <P> The director feature is disabled by default. To use directors you | |
28822 | must make two changes to the interface file. First, add the "directors" | |
28823 | option to the %module directive, like this:</P> | |
28824 | <DIV class="code"> | |
28825 | <PRE> | |
28826 | %module(directors="1") modulename | |
28827 | </PRE> | |
28828 | </DIV> | |
28829 | <P> Without this option no director code will be generated. Second, you | |
28830 | must use the %feature("director") directive to tell SWIG which classes | |
28831 | and methods should get directors. The %feature directive can be applied | |
28832 | globally, to specific classes, and to specific methods, like this:</P> | |
28833 | <DIV class="code"> | |
28834 | <PRE> | |
28835 | // generate directors for all classes that have virtual methods | |
28836 | %feature("director"); | |
28837 | ||
28838 | // genarate directors for all virtual methods in class Foo | |
28839 | %feature("director") Foo; | |
28840 | ||
28841 | // generate a director for just Foo::bar() | |
28842 | %feature("director") Foo::bar; | |
28843 | </PRE> | |
28844 | </DIV> | |
28845 | <P> You can use the %feature("nodirector") directive to turn off | |
28846 | directors for specific classes or methods. So for example,</P> | |
28847 | <DIV class="code"> | |
28848 | <PRE> | |
28849 | %feature("director") Foo; | |
28850 | %feature("nodirector") Foo::bar; | |
28851 | </PRE> | |
28852 | </DIV> | |
28853 | <P> will generate directors for all virtual methods of class Foo except | |
28854 | bar().</P> | |
28855 | <P> Directors can also be generated implicitly through inheritance. In | |
28856 | the following, class Bar will get a director class that handles the | |
28857 | methods one() and two() (but not three()):</P> | |
28858 | <DIV class="code"> | |
28859 | <PRE> | |
28860 | %feature("director") Foo; | |
28861 | class Foo { | |
28862 | public: | |
28863 | Foo(int foo); | |
28864 | virtual void one(); | |
28865 | virtual void two(); | |
28866 | }; | |
28867 | ||
28868 | class Bar: public Foo { | |
28869 | public: | |
28870 | virtual void three(); | |
28871 | }; | |
28872 | </PRE> | |
28873 | </DIV> | |
28874 | <P> then at the python side you can define</P> | |
28875 | <DIV class="targetlang"> | |
28876 | <PRE> | |
28877 | import mymodule | |
28878 | ||
28879 | class MyFoo(mymodule.Foo): | |
28880 | def __init__(self, foo): | |
28881 | mymodule.Foo(self, foo) | |
28882 | ||
28883 | def one(self): | |
28884 | print "one from python" | |
28885 | </PRE> | |
28886 | </DIV> | |
28887 | <H3><A name="Python_nn34"></A>26.5.2 Director classes</H3> | |
28888 | <P> For each class that has directors enabled, SWIG generates a new | |
28889 | class that derives from both the class in question and a special <TT> | |
28890 | Swig::Director</TT> class. These new classes, referred to as director | |
28891 | classes, can be loosely thought of as the C++ equivalent of the Python | |
28892 | proxy classes. The director classes store a pointer to their underlying | |
28893 | Python object and handle various issues related to object ownership. | |
28894 | Indeed, this is quite similar to the "this" and "thisown" members of | |
28895 | the Python proxy classes.</P> | |
28896 | <P> For simplicity let's ignore the <TT>Swig::Director</TT> class and | |
28897 | refer to the original C++ class as the director's base class. By | |
28898 | default, a director class extends all virtual methods in the | |
28899 | inheritance chain of its base class (see the preceding section for how | |
28900 | to modify this behavior). Thus all virtual method calls, whether they | |
28901 | originate in C++ or in Python via proxy classes, eventually end up in | |
28902 | at the implementation in the director class. The job of the director | |
28903 | methods is to route these method calls to the appropriate place in the | |
28904 | inheritance chain. By "appropriate place" we mean the method that would | |
28905 | have been called if the C++ base class and its extensions in Python | |
28906 | were seamlessly integrated. That seamless integration is exactly what | |
28907 | the director classes provide, transparently skipping over all the messy | |
28908 | extension API glue that binds the two languages together.</P> | |
28909 | <P> In reality, the "appropriate place" is one of only two | |
28910 | possibilities: C++ or Python. Once this decision is made, the rest is | |
28911 | fairly easy. If the correct implementation is in C++, then the lowest | |
28912 | implementation of the method in the C++ inheritance chain is called | |
28913 | explicitly. If the correct implementation is in Python, the Python API | |
28914 | is used to call the method of the underlying Python object (after which | |
28915 | the usual virtual method resolution in Python automatically finds the | |
28916 | right implementation).</P> | |
28917 | <P> Now how does the director decide which language should handle the | |
28918 | method call? The basic rule is to handle the method in Python, unless | |
28919 | there's a good reason not to. The reason for this is simple: Python has | |
28920 | the most "extended" implementation of the method. This assertion is | |
28921 | guaranteed, since at a minimum the Python proxy class implements the | |
28922 | method. If the method in question has been extended by a class derived | |
28923 | from the proxy class, that extended implementation will execute exactly | |
28924 | as it should. If not, the proxy class will route the method call into a | |
28925 | C wrapper function, expecting that the method will be resolved in C++. | |
28926 | The wrapper will call the virtual method of the C++ instance, and since | |
28927 | the director extends this the call will end up right back in the | |
28928 | director method. Now comes the "good reason not to" part. If the | |
28929 | director method were to blindly call the Python method again, it would | |
28930 | get stuck in an infinite loop. We avoid this situation by adding | |
28931 | special code to the C wrapper function that tells the director method | |
28932 | to not do this. The C wrapper function compares the pointer to the | |
28933 | Python object that called the wrapper function to the pointer stored by | |
28934 | the director. If these are the same, then the C wrapper function tells | |
28935 | the director to resolve the method by calling up the C++ inheritance | |
28936 | chain, preventing an infinite loop.</P> | |
28937 | <P> One more point needs to be made about the relationship between | |
28938 | director classes and proxy classes. When a proxy class instance is | |
28939 | created in Python, SWIG creates an instance of the original C++ class | |
28940 | and assigns it to <TT>.this</TT>. This is exactly what happens without | |
28941 | directors and is true even if directors are enabled for the particular | |
28942 | class in question. When a class<I> derived</I> from a proxy class is | |
28943 | created, however, SWIG then creates an instance of the corresponding | |
28944 | C++ director class. The reason for this difference is that user-defined | |
28945 | subclasses may override or extend methods of the original class, so the | |
28946 | director class is needed to route calls to these methods correctly. For | |
28947 | unmodified proxy classes, all methods are ultimately implemented in C++ | |
28948 | so there is no need for the extra overhead involved with routing the | |
28949 | calls through Python.</P> | |
28950 | <H3><A name="Python_nn35"></A>26.5.3 Ownership and object destruction</H3> | |
28951 | <P> Memory management issues are slightly more complicated with | |
28952 | directors than for proxy classes alone. Python instances hold a pointer | |
28953 | to the associated C++ director object, and the director in turn holds a | |
28954 | pointer back to the Python object. By default, proxy classes own their | |
28955 | C++ director object and take care of deleting it when they are garbage | |
28956 | collected.</P> | |
28957 | <P> This relationship can be reversed by calling the special <TT> | |
28958 | __disown__()</TT> method of the proxy class. After calling this method, | |
28959 | the <TT>.thisown</TT> flag is set to zero, and the director class | |
28960 | increments the reference count of the Python object. When the director | |
28961 | class is deleted it decrements the reference count. Assuming no | |
28962 | outstanding references to the Python object remain, the Python object | |
28963 | will be destroyed at the same time. This is a good thing, since | |
28964 | directors and proxies refer to each other and so must be created and | |
28965 | destroyed together. Destroying one without destroying the other will | |
28966 | likely cause your program to segfault.</P> | |
28967 | <P> To help ensure that no references to the Python object remain after | |
28968 | calling <TT>__disown__()</TT>, this method returns a weak reference to | |
28969 | the Python object. Weak references are only available in Python | |
28970 | versions 2.1 and higher, so for older versions you must exclicitly | |
28971 | delete all references. Here is an example:</P> | |
28972 | <DIV class="code"> | |
28973 | <PRE> | |
28974 | class Foo { | |
28975 | public: | |
28976 | ... | |
28977 | }; | |
28978 | class FooContainer { | |
28979 | public: | |
28980 | void addFoo(Foo *); | |
28981 | ... | |
28982 | }; | |
28983 | </PRE> | |
28984 | </DIV> | |
28985 | <BR><DIV class="targetlang"> | |
28986 | <PRE> | |
28987 | >>> c = FooContainer() | |
28988 | >>> a = Foo().__disown()__ | |
28989 | >>> c.addFoo(a) | |
28990 | >>> b = Foo() | |
28991 | >>> b = b.__disown()__ | |
28992 | >>> c.addFoo(b) | |
28993 | >>> c.addFoo(Foo().__disown()__) | |
28994 | </PRE> | |
28995 | </DIV> | |
28996 | <P> In this example, we are assuming that FooContainer will take care of | |
28997 | deleting all the Foo pointers it contains at some point. Note that no | |
28998 | hard references to the Foo objects remain in Python.</P> | |
28999 | <H3><A name="Python_nn36"></A>26.5.4 Exception unrolling</H3> | |
29000 | <P> With directors routing method calls to Python, and proxies routing | |
29001 | them to C++, the handling of exceptions is an important concern. By | |
29002 | default, the directors ignore exceptions that occur during method calls | |
29003 | that are resolved in Python. To handle such exceptions correctly, it is | |
29004 | necessary to temporarily translate them into C++ exceptions. This can | |
29005 | be done with the %feature("director:except") directive. The following | |
29006 | code should suffice in most cases:</P> | |
29007 | <DIV class="code"> | |
29008 | <PRE> | |
29009 | %feature("director:except") { | |
29010 | if ($error != NULL) { | |
29011 | throw Swig::DirectorMethodException(); | |
29012 | } | |
29013 | } | |
29014 | </PRE> | |
29015 | </DIV> | |
29016 | <P> This code will check the Python error state after each method call | |
29017 | from a director into Python, and throw a C++ exception if an error | |
29018 | occured. This exception can be caught in C++ to implement an error | |
29019 | handler. Currently no information about the Python error is stored in | |
29020 | the Swig::DirectorMethodException object, but this will likely change | |
29021 | in the future.</P> | |
29022 | <P> It may be the case that a method call originates in Python, travels | |
29023 | up to C++ through a proxy class, and then back into Python via a | |
29024 | director method. If an exception occurs in Python at this point, it | |
29025 | would be nice for that exception to find its way back to the original | |
29026 | caller. This can be done by combining a normal %exception directive | |
29027 | with the <TT>director:except</TT> handler shown above. Here is an | |
29028 | example of a suitable exception handler:</P> | |
29029 | <DIV class="code"> | |
29030 | <PRE> | |
29031 | %exception { | |
29032 | try { $action } | |
29033 | catch (Swig::DirectorException &e) { SWIG_fail; } | |
29034 | } | |
29035 | </PRE> | |
29036 | </DIV> | |
29037 | <P> The class Swig::DirectorException used in this example is actually a | |
29038 | base class of Swig::DirectorMethodException, so it will trap this | |
29039 | exception. Because the Python error state is still set when | |
29040 | Swig::DirectorMethodException is thrown, Python will register the | |
29041 | exception as soon as the C wrapper function returns.</P> | |
29042 | <H3><A name="Python_nn37"></A>26.5.5 Overhead and code bloat</H3> | |
29043 | <P> Enabling directors for a class will generate a new director method | |
29044 | for every virtual method in the class' inheritance chain. This alone | |
29045 | can generate a lot of code bloat for large hierarchies. Method | |
29046 | arguments that require complex conversions to and from target language | |
29047 | types can result in large director methods. For this reason it is | |
29048 | recommended that you selectively enable directors only for specific | |
29049 | classes that are likely to be extended in Python and used in C++.</P> | |
29050 | <P> Compared to classes that do not use directors, the call routing in | |
29051 | the director methods does add some overhead. In particular, at least | |
29052 | one dynamic cast and one extra function call occurs per method call | |
29053 | from Python. Relative to the speed of Python execution this is probably | |
29054 | completely negligible. For worst case routing, a method call that | |
29055 | ultimately resolves in C++ may take one extra detour through Python in | |
29056 | order to ensure that the method does not have an extended Python | |
29057 | implementation. This could result in a noticible overhead in some | |
29058 | cases.</P> | |
29059 | <P> Although directors make it natural to mix native C++ objects with | |
29060 | Python objects (as director objects) via a common base class pointer, | |
29061 | one should be aware of the obvious fact that method calls to Python | |
29062 | objects will be much slower than calls to C++ objects. This situation | |
29063 | can be optimized by selectively enabling director methods (using the | |
29064 | %feature directive) for only those methods that are likely to be | |
29065 | extended in Python.</P> | |
29066 | <H3><A name="Python_nn38"></A>26.5.6 Typemaps</H3> | |
29067 | <P> Typemaps for input and output of most of the basic types from | |
29068 | director classes have been written. These are roughly the reverse of | |
29069 | the usual input and output typemaps used by the wrapper code. The | |
29070 | typemap operation names are 'directorin', 'directorout', and | |
29071 | 'directorargout'. The director code does not currently use any of the | |
29072 | other kinds of typemaps. It is not clear at this point which kinds are | |
29073 | appropriate and need to be supported.</P> | |
29074 | <H3><A name="Python_nn39"></A>26.5.7 Miscellaneous</H3> | |
29075 | <P> Director typemaps for STL classes are in place, and hence you should | |
29076 | be able to use std::vector, std::string, etc., as you would any other | |
29077 | type.</P> | |
29078 | <P><B> Note:</B> The director typemaps for return types based in const | |
29079 | references, such as<DIV class="code"> | |
29080 | <PRE> | |
29081 | class Foo { | |
29082 | &hellip; | |
29083 | virtual const int& bar(); | |
29084 | &hellip; | |
29085 | }; | |
29086 | </PRE> | |
29087 | </DIV></P> | |
29088 | <P> will work only for simple call scenarios. Usually the resulting code | |
29089 | is neither thread or reentrant safe. Hence, the user is advised to | |
29090 | avoid returning const references in director methods. For example, the | |
29091 | user could modify the method interface to use lvalue return types, | |
29092 | wherever possible, for example</P> | |
29093 | <DIV class="code"> | |
29094 | <PRE> | |
29095 | class Foo { | |
29096 | &hellip; | |
29097 | virtual int bar(); | |
29098 | &hellip; | |
29099 | }; | |
29100 | </PRE> | |
29101 | </DIV> | |
29102 | <P> If that is not possible, the user should avoid enabling the director | |
29103 | feature for reentrant, recursive or threaded member methods that return | |
29104 | const references.</P> | |
29105 | <H2><A name="Python_nn40"></A>26.6 Common customization features</H2> | |
29106 | <P> The last section presented the absolute basics of C/C++ wrapping. If | |
29107 | you do nothing but feed SWIG a header file, you will get an interface | |
29108 | that mimics the behavior described. However, sometimes this isn't | |
29109 | enough to produce a nice module. Certain types of functionality might | |
29110 | be missing or the interface to certain functions might be awkward. This | |
29111 | section describes some common SWIG features that are used to improve | |
29112 | your the interface to an extension module.</P> | |
29113 | <H3><A name="Python_nn41"></A>26.6.1 C/C++ helper functions</H3> | |
29114 | <P> Sometimes when you create a module, it is missing certain bits of | |
29115 | functionality. For example, if you had a function like this</P> | |
29116 | <DIV class="code"> | |
29117 | <PRE> | |
29118 | void set_transform(Image *im, double m[4][4]); | |
29119 | </PRE> | |
29120 | </DIV> | |
29121 | <P> it would be accessible from Python, but there may be no easy way to | |
29122 | call it. For example, you might get errors like this:</P> | |
29123 | <DIV class="targetlang"> | |
29124 | <PRE> | |
29125 | >>> a = [ | |
29126 | ... [1,0,0,0], | |
29127 | ... [0,1,0,0], | |
29128 | ... [0,0,1,0], | |
29129 | ... [0,0,0,1]] | |
29130 | >>> set_transform(im,a) | |
29131 | Traceback (most recent call last): | |
29132 | File "<stdin>", line 1, in ? | |
29133 | TypeError: Type error. Expected _p_a_4__double | |
29134 | </PRE> | |
29135 | </DIV> | |
29136 | <P> The problem here is that there is no easy way to construct and | |
29137 | manipulate a suitable <TT>double [4][4]</TT> value to use. To fix this, | |
29138 | you can write some extra C helper functions. Just use the <TT>%inline</TT> | |
29139 | directive. For example:</P> | |
29140 | <DIV class="code"> | |
29141 | <PRE> | |
29142 | %inline %{ | |
29143 | /* Note: double[4][4] is equivalent to a pointer to an array double (*)[4] */ | |
29144 | double (*new_mat44())[4] { | |
29145 | return (double (*)[4]) malloc(16*sizeof(double)); | |
29146 | } | |
29147 | void free_mat44(double (*x)[4]) { | |
29148 | free(x); | |
29149 | } | |
29150 | void mat44_set(double x[4][4], int i, int j, double v) { | |
29151 | x[i][j] = v; | |
29152 | } | |
29153 | double mat44_get(double x[4][4], int i, int j) { | |
29154 | return x[i][j]; | |
29155 | } | |
29156 | %} | |
29157 | </PRE> | |
29158 | </DIV> | |
29159 | <P> From Python, you could then write code like this:</P> | |
29160 | <DIV class="targetlang"> | |
29161 | <PRE> | |
29162 | >>> a = new_mat44() | |
29163 | >>> mat44_set(a,0,0,1.0) | |
29164 | >>> mat44_set(a,1,1,1.0) | |
29165 | >>> mat44_set(a,2,2,1.0) | |
29166 | ... | |
29167 | >>> set_transform(im,a) | |
29168 | >>> | |
29169 | </PRE> | |
29170 | </DIV> | |
29171 | <P> Admittedly, this is not the most elegant looking approach. However, | |
29172 | it works and it wasn't too hard to implement. It is possible to clean | |
29173 | this up using Python code, typemaps, and other customization features | |
29174 | as covered in later sections.</P> | |
29175 | <H3><A name="Python_nn42"></A>26.6.2 Adding additional Python code</H3> | |
29176 | <P> If writing support code in C isn't enough, it is also possible to | |
29177 | write code in Python. This code gets inserted in to the <TT>.py</TT> | |
29178 | file created by SWIG. One use of Python code might be to supply a | |
29179 | high-level interface to certain functions. For example:</P> | |
29180 | <DIV class="code"> | |
29181 | <PRE> | |
29182 | void set_transform(Image *im, double x[4][4]); | |
29183 | ||
29184 | ... | |
29185 | /* Rewrite the high level interface to set_transform */ | |
29186 | %pythoncode %{ | |
29187 | def set_transform(im,x): | |
29188 | a = new_mat44() | |
29189 | for i in range(4): | |
29190 | for j in range(4): | |
29191 | mat44_set(a,i,j,x[i][j]) | |
29192 | _example.set_transform(im,a) | |
29193 | free_mat44(a) | |
29194 | %} | |
29195 | </PRE> | |
29196 | </DIV> | |
29197 | <P> In this example, <TT>set_transform()</TT> provides a high-level | |
29198 | Python interface built on top of low-level helper functions. For | |
29199 | example, this code now seems to work:</P> | |
29200 | <DIV class="targetlang"> | |
29201 | <PRE> | |
29202 | >>> a = [ | |
29203 | ... [1,0,0,0], | |
29204 | ... [0,1,0,0], | |
29205 | ... [0,0,1,0], | |
29206 | ... [0,0,0,1]] | |
29207 | >>> set_transform(im,a) | |
29208 | >>> | |
29209 | </PRE> | |
29210 | </DIV> | |
29211 | <P> Admittedly, this whole scheme for wrapping the two-dimension array | |
29212 | argument is rather ad-hoc. Besides, shouldn't a Python list or a | |
29213 | Numeric Python array just work normally? We'll get to those examples | |
29214 | soon enough. For now, think of this example as an illustration of what | |
29215 | can be done without having to rely on any of the more advanced | |
29216 | customization features.</P> | |
29217 | <H3><A name="Python_nn43"></A>26.6.3 Class extension with %extend</H3> | |
29218 | <P> One of the more interesting features of SWIG is that it can extend | |
29219 | structures and classes with new methods--at least in the Python | |
29220 | interface. Here is a simple example:</P> | |
29221 | <DIV class="code"> | |
29222 | <PRE> | |
29223 | %module example | |
29224 | %{ | |
29225 | #include "someheader.h" | |
29226 | %} | |
29227 | ||
29228 | struct Vector { | |
29229 | double x,y,z; | |
29230 | }; | |
29231 | ||
29232 | %extend Vector { | |
29233 | char *__str__() { | |
29234 | static char tmp[1024]; | |
29235 | sprintf(tmp,"Vector(%g,%g,%g)", self->x,self->y,self->z); | |
29236 | return tmp; | |
29237 | } | |
29238 | Vector(double x, double y, double z) { | |
29239 | Vector *v = (Vector *) malloc(sizeof(Vector)); | |
29240 | v->x = x; | |
29241 | v->y = y; | |
29242 | v->z = z; | |
29243 | return v; | |
29244 | } | |
29245 | }; | |
29246 | </PRE> | |
29247 | </DIV> | |
29248 | <P> Now, in Python</P> | |
29249 | <DIV class="targetlang"> | |
29250 | <PRE> | |
29251 | >>> v = example.Vector(2,3,4) | |
29252 | >>> print v | |
29253 | Vector(2,3,4) | |
29254 | >>> | |
29255 | </PRE> | |
29256 | </DIV> | |
29257 | <P> <TT>%extend</TT> can be used for many more tasks than this. For | |
29258 | example, if you wanted to overload a Python operator, you might do | |
29259 | this:</P> | |
29260 | <DIV class="code"> | |
29261 | <PRE> | |
29262 | %extend Vector { | |
29263 | Vector __add__(Vector *other) { | |
29264 | Vector v; | |
29265 | v.x = self->x + other->x; | |
29266 | v.y = self->y + other->y; | |
29267 | v.z = self->z + other->z; | |
29268 | return v; | |
29269 | } | |
29270 | }; | |
29271 | </PRE> | |
29272 | </DIV> | |
29273 | <P> Use it like this:</P> | |
29274 | <DIV class="targetlang"> | |
29275 | <PRE> | |
29276 | >>> import example | |
29277 | >>> v = example.Vector(2,3,4) | |
29278 | >>> w = example.Vector(10,11,12) | |
29279 | >>> print v+w | |
29280 | Vector(12,14,16) | |
29281 | >>> | |
29282 | </PRE> | |
29283 | </DIV> | |
29284 | <P> <TT>%extend</TT> works with both C and C++ code. It does not modify | |
29285 | the underlying object in any way---the extensions only show up in the | |
29286 | Python interface.</P> | |
29287 | <H3><A name="Python_nn44"></A>26.6.4 Exception handling with %exception</H3> | |
29288 | <P> If a C or C++ function throws an error, you may want to convert that | |
29289 | error into a Python exception. To do this, you can use the <TT> | |
29290 | %exception</TT> directive. <TT>%exception</TT> simply lets you rewrite | |
29291 | part of the generated wrapper code to include an error check.</P> | |
29292 | <P> In C, a function often indicates an error by returning a status code | |
29293 | (a negative number or a NULL pointer perhaps). Here is a simple example | |
29294 | of how you might handle that:</P> | |
29295 | <DIV class="code"> | |
29296 | <PRE> | |
29297 | %exception malloc { | |
29298 | $action | |
29299 | if (!result) { | |
29300 | PyErr_SetString(PyExc_MemoryError,"Not enough memory"); | |
29301 | return NULL; | |
29302 | } | |
29303 | } | |
29304 | void *malloc(size_t nbytes); | |
29305 | </PRE> | |
29306 | </DIV> | |
29307 | <P> In Python,</P> | |
29308 | <DIV class="targetlang"> | |
29309 | <PRE> | |
29310 | >>> a = example.malloc(2000000000) | |
29311 | Traceback (most recent call last): | |
29312 | File "<stdin>", line 1, in ? | |
29313 | MemoryError: Not enough memory | |
29314 | >>> | |
29315 | </PRE> | |
29316 | </DIV> | |
29317 | <P> If a library provides some kind of general error handling framework, | |
29318 | you can also use that. For example:</P> | |
29319 | <DIV class="code"> | |
29320 | <PRE> | |
29321 | %exception { | |
29322 | $action | |
29323 | if (err_occurred()) { | |
29324 | PyErr_SetString(PyExc_RuntimeError, err_message()); | |
29325 | return NULL; | |
29326 | } | |
29327 | } | |
29328 | </PRE> | |
29329 | </DIV> | |
29330 | <P> No declaration name is given to <TT>%exception</TT>, it is applied | |
29331 | to all wrapper functions.</P> | |
29332 | <P> C++ exceptions are also easy to handle. For example, you can write | |
29333 | code like this:</P> | |
29334 | <DIV class="code"> | |
29335 | <PRE> | |
29336 | %exception getitem { | |
29337 | try { | |
29338 | $action | |
29339 | } catch (std::out_of_range &e) { | |
29340 | PyErr_SetString(PyExc_IndexError, const_cast<char*>(e.what())); | |
29341 | return NULL; | |
29342 | } | |
29343 | } | |
29344 | ||
29345 | class Base { | |
29346 | public: | |
29347 | Foo *getitem(int index); // Exception handled added | |
29348 | ... | |
29349 | }; | |
29350 | </PRE> | |
29351 | </DIV> | |
29352 | <P> When raising a Python exception from C, use the <TT> | |
29353 | PyErr_SetString()</TT> function as shown above. The following exception | |
29354 | types can be used as the first argument.</P> | |
29355 | <DIV class="code"> | |
29356 | <PRE> | |
29357 | PyExc_ArithmeticError | |
29358 | PyExc_AssertionError | |
29359 | PyExc_AttributeError | |
29360 | PyExc_EnvironmentError | |
29361 | PyExc_EOFError | |
29362 | PyExc_Exception | |
29363 | PyExc_FloatingPointError | |
29364 | PyExc_ImportError | |
29365 | PyExc_IndexError | |
29366 | PyExc_IOError | |
29367 | PyExc_KeyError | |
29368 | PyExc_KeyboardInterrupt | |
29369 | PyExc_LookupError | |
29370 | PyExc_MemoryError | |
29371 | PyExc_NameError | |
29372 | PyExc_NotImplementedError | |
29373 | PyExc_OSError | |
29374 | PyExc_OverflowError | |
29375 | PyExc_RuntimeError | |
29376 | PyExc_StandardError | |
29377 | PyExc_SyntaxError | |
29378 | PyExc_SystemError | |
29379 | PyExc_TypeError | |
29380 | PyExc_UnicodeError | |
29381 | PyExc_ValueError | |
29382 | PyExc_ZeroDivisionError | |
29383 | </PRE> | |
29384 | </DIV> | |
29385 | <P> The language-independent <TT>exception.i</TT> library file can also | |
29386 | be used to raise exceptions. See the <A href="#Library">SWIG Library</A> | |
29387 | chapter.</P> | |
29388 | <H2><A name="Python_nn45"></A>26.7 Tips and techniques</H2> | |
29389 | <P> Although SWIG is largely automatic, there are certain types of | |
29390 | wrapping problems that require additional user input. Examples include | |
29391 | dealing with output parameters, strings, binary data, and arrays. This | |
29392 | chapter discusses the common techniques for solving these problems.</P> | |
29393 | <H3><A name="Python_nn46"></A>26.7.1 Input and output parameters</H3> | |
29394 | <P> A common problem in some C programs is handling parameters passed as | |
29395 | simple pointers. For example:</P> | |
29396 | <DIV class="code"> | |
29397 | <PRE> | |
29398 | void add(int x, int y, int *result) { | |
29399 | *result = x + y; | |
29400 | } | |
29401 | </PRE> | |
29402 | </DIV> | |
29403 | <P> or perhaps</P> | |
29404 | <DIV class="code"> | |
29405 | <PRE> | |
29406 | int sub(int *x, int *y) { | |
29407 | return *x-*y; | |
29408 | } | |
29409 | </PRE> | |
29410 | </DIV> | |
29411 | <P> The easiest way to handle these situations is to use the <TT> | |
29412 | typemaps.i</TT> file. For example:</P> | |
29413 | <DIV class="code"> | |
29414 | <PRE> | |
29415 | %module example | |
29416 | %include "typemaps.i" | |
29417 | ||
29418 | void add(int, int, int *OUTPUT); | |
29419 | int sub(int *INPUT, int *INPUT); | |
29420 | </PRE> | |
29421 | </DIV> | |
29422 | <P> In Python, this allows you to pass simple values. For example:</P> | |
29423 | <DIV class="targetlang"> | |
29424 | <PRE> | |
29425 | >>> a = add(3,4) | |
29426 | >>> print a | |
29427 | 7 | |
29428 | >>> b = sub(7,4) | |
29429 | >>> print b | |
29430 | 3 | |
29431 | >>> | |
29432 | </PRE> | |
29433 | </DIV> | |
29434 | <P> Notice how the <TT>INPUT</TT> parameters allow integer values to be | |
29435 | passed instead of pointers and how the <TT>OUTPUT</TT> parameter | |
29436 | creates a return result.</P> | |
29437 | <P> If you don't want to use the names <TT>INPUT</TT> or <TT>OUTPUT</TT> | |
29438 | , use the <TT>%apply</TT> directive. For example:</P> | |
29439 | <DIV class="code"> | |
29440 | <PRE> | |
29441 | %module example | |
29442 | %include "typemaps.i" | |
29443 | ||
29444 | %apply int *OUTPUT { int *result }; | |
29445 | %apply int *INPUT { int *x, int *y}; | |
29446 | ||
29447 | void add(int x, int y, int *result); | |
29448 | int sub(int *x, int *y); | |
29449 | </PRE> | |
29450 | </DIV> | |
29451 | <P> If a function mutates one of its parameters like this,</P> | |
29452 | <DIV class="code"> | |
29453 | <PRE> | |
29454 | void negate(int *x) { | |
29455 | *x = -(*x); | |
29456 | } | |
29457 | </PRE> | |
29458 | </DIV> | |
29459 | <P> you can use <TT>INOUT</TT> like this:</P> | |
29460 | <DIV class="code"> | |
29461 | <PRE> | |
29462 | %include "typemaps.i" | |
29463 | ... | |
29464 | void negate(int *INOUT); | |
29465 | </PRE> | |
29466 | </DIV> | |
29467 | <P> In Python, a mutated parameter shows up as a return value. For | |
29468 | example:</P> | |
29469 | <DIV class="targetlang"> | |
29470 | <PRE> | |
29471 | >>> a = negate(3) | |
29472 | >>> print a | |
29473 | -3 | |
29474 | >>> | |
29475 | </PRE> | |
29476 | </DIV> | |
29477 | <P> Note: Since most primitive Python objects are immutable, it is not | |
29478 | possible to perform in-place modification of a Python object passed as | |
29479 | a parameter.</P> | |
29480 | <P> The most common use of these special typemap rules is to handle | |
29481 | functions that return more than one value. For example, sometimes a | |
29482 | function returns a result as well as a special error code:</P> | |
29483 | <DIV class="code"> | |
29484 | <PRE> | |
29485 | /* send message, return number of bytes sent, along with success code */ | |
29486 | int send_message(char *text, int len, int *success); | |
29487 | </PRE> | |
29488 | </DIV> | |
29489 | <P> To wrap such a function, simply use the <TT>OUTPUT</TT> rule above. | |
29490 | For example:</P> | |
29491 | <DIV class="code"> | |
29492 | <PRE> | |
29493 | %module example | |
29494 | %include "typemaps.i" | |
29495 | %apply int *OUTPUT { int *success }; | |
29496 | ... | |
29497 | int send_message(char *text, int *success); | |
29498 | </PRE> | |
29499 | </DIV> | |
29500 | <P> When used in Python, the function will return multiple values.</P> | |
29501 | <DIV class="targetlang"> | |
29502 | <PRE> | |
29503 | bytes, success = send_message("Hello World") | |
29504 | if not success: | |
29505 | print "Whoa!" | |
29506 | else: | |
29507 | print "Sent", bytes | |
29508 | </PRE> | |
29509 | </DIV> | |
29510 | <P> Another common use of multiple return values are in query functions. | |
29511 | For example:</P> | |
29512 | <DIV class="code"> | |
29513 | <PRE> | |
29514 | void get_dimensions(Matrix *m, int *rows, int *columns); | |
29515 | </PRE> | |
29516 | </DIV> | |
29517 | <P> To wrap this, you might use the following:</P> | |
29518 | <DIV class="code"> | |
29519 | <PRE> | |
29520 | %module example | |
29521 | %include "typemaps.i" | |
29522 | %apply int *OUTPUT { int *rows, int *columns }; | |
29523 | ... | |
29524 | void get_dimensions(Matrix *m, int *rows, *columns); | |
29525 | </PRE> | |
29526 | </DIV> | |
29527 | <P> Now, in Python:</P> | |
29528 | <DIV class="targetlang"> | |
29529 | <PRE> | |
29530 | >>> r,c = get_dimensions(m) | |
29531 | </PRE> | |
29532 | </DIV> | |
29533 | <P> Be aware that the primary purpose of the <TT>typemaps.i</TT> file is | |
29534 | to support primitive datatypes. Writing a function like this</P> | |
29535 | <DIV class="code"> | |
29536 | <PRE> | |
29537 | void foo(Bar *OUTPUT); | |
29538 | </PRE> | |
29539 | </DIV> | |
29540 | <P> may not have the intended effect since <TT>typemaps.i</TT> does not | |
29541 | define an OUTPUT rule for <TT>Bar</TT>.</P> | |
29542 | <H3><A name="Python_nn47"></A>26.7.2 Simple pointers</H3> | |
29543 | <P> If you must work with simple pointers such as <TT>int *</TT> or <TT> | |
29544 | double *</TT> and you don't want to use <TT>typemaps.i</TT>, consider | |
29545 | using the <TT>cpointer.i</TT> library file. For example:</P> | |
29546 | <DIV class="code"> | |
29547 | <PRE> | |
29548 | %module example | |
29549 | %include "cpointer.i" | |
29550 | ||
29551 | %inline %{ | |
29552 | extern void add(int x, int y, int *result); | |
29553 | %} | |
29554 | ||
29555 | %pointer_functions(int, intp); | |
29556 | </PRE> | |
29557 | </DIV> | |
29558 | <P> The <TT>%pointer_functions(type,name)</TT> macro generates five | |
29559 | helper functions that can be used to create, destroy, copy, assign, and | |
29560 | dereference a pointer. In this case, the functions are as follows:</P> | |
29561 | <DIV class="code"> | |
29562 | <PRE> | |
29563 | int *new_intp(); | |
29564 | int *copy_intp(int *x); | |
29565 | void delete_intp(int *x); | |
29566 | void intp_assign(int *x, int value); | |
29567 | int intp_value(int *x); | |
29568 | </PRE> | |
29569 | </DIV> | |
29570 | <P> In Python, you would use the functions like this:</P> | |
29571 | <DIV class="targetlang"> | |
29572 | <PRE> | |
29573 | >>> result = new_intp() | |
29574 | >>> print result | |
29575 | _108fea8_p_int | |
29576 | >>> add(3,4,result) | |
29577 | >>> print intp_value(result) | |
29578 | 7 | |
29579 | >>> | |
29580 | </PRE> | |
29581 | </DIV> | |
29582 | <P> If you replace <TT>%pointer_functions()</TT> by <TT> | |
29583 | %pointer_class(type,name)</TT>, the interface is more class-like.</P> | |
29584 | <DIV class="targetlang"> | |
29585 | <PRE> | |
29586 | >>> result = intp() | |
29587 | >>> add(3,4,result) | |
29588 | >>> print result.value() | |
29589 | 7 | |
29590 | </PRE> | |
29591 | </DIV> | |
29592 | <P> See the <A href="#Library">SWIG Library</A> chapter for further | |
29593 | details.</P> | |
29594 | <H3><A name="Python_nn48"></A>26.7.3 Unbounded C Arrays</H3> | |
29595 | <P> Sometimes a C function expects an array to be passed as a pointer. | |
29596 | For example,</P> | |
29597 | <DIV class="code"> | |
29598 | <PRE> | |
29599 | int sumitems(int *first, int nitems) { | |
29600 | int i, sum = 0; | |
29601 | for (i = 0; i < nitems; i++) { | |
29602 | sum += first[i]; | |
29603 | } | |
29604 | return sum; | |
29605 | } | |
29606 | </PRE> | |
29607 | </DIV> | |
29608 | <P> To wrap this into Python, you need to pass an array pointer as the | |
29609 | first argument. A simple way to do this is to use the <TT>carrays.i</TT> | |
29610 | library file. For example:</P> | |
29611 | <DIV class="code"> | |
29612 | <PRE> | |
29613 | %include "carrays.i" | |
29614 | %array_class(int, intArray); | |
29615 | </PRE> | |
29616 | </DIV> | |
29617 | <P> The <TT>%array_class(type, name)</TT> macro creates wrappers for an | |
29618 | unbounded array object that can be passed around as a simple pointer | |
29619 | like <TT>int *</TT> or <TT>double *</TT>. For instance, you will be | |
29620 | able to do this in Python:</P> | |
29621 | <DIV class="targetlang"> | |
29622 | <PRE> | |
29623 | >>> a = intArray(10000000) # Array of 10-million integers | |
29624 | >>> for i in xrange(10000): # Set some values | |
29625 | ... a[i] = i | |
29626 | >>> sumitems(a,10000) | |
29627 | 49995000 | |
29628 | >>> | |
29629 | </PRE> | |
29630 | </DIV> | |
29631 | <P> The array "object" created by <TT>%array_class()</TT> does not | |
29632 | encapsulate pointers inside a special array object. In fact, there is | |
29633 | no bounds checking or safety of any kind (just like in C). Because of | |
29634 | this, the arrays created by this library are extremely low-level | |
29635 | indeed. You can't iterate over them nor can you even query their | |
29636 | length. In fact, any valid memory address can be accessed if you want | |
29637 | (negative indices, indices beyond the end of the array, etc.). Needless | |
29638 | to say, this approach is not going to suit all applications. On the | |
29639 | other hand, this low-level approach is extremely efficient and well | |
29640 | suited for applications in which you need to create buffers, package | |
29641 | binary data, etc.</P> | |
29642 | <H3><A name="Python_nn49"></A>26.7.4 String handling</H3> | |
29643 | <P> If a C function has an argument of <TT>char *</TT>, then a Python | |
29644 | string can be passed as input. For example:</P> | |
29645 | <DIV class="code"> | |
29646 | <PRE> | |
29647 | // C | |
29648 | void foo(char *s); | |
29649 | </PRE> | |
29650 | </DIV><DIV class="targetlang"> | |
29651 | <PRE> | |
29652 | # Python | |
29653 | >>> foo("Hello") | |
29654 | </PRE> | |
29655 | </DIV> | |
29656 | <P> When a Python string is passed as a parameter, the C function | |
29657 | receives a pointer to the raw data contained in the string. Since | |
29658 | Python strings are immutable, it is illegal for your program to change | |
29659 | the value. In fact, doing so will probably crash the Python | |
29660 | interpreter.</P> | |
29661 | <P> If your program modifies the input parameter or uses it to return | |
29662 | data, consider using the <TT>cstring.i</TT> library file described in | |
29663 | the <A href="#Library">SWIG Library</A> chapter.</P> | |
29664 | <P> When functions return a <TT>char *</TT>, it is assumed to be a | |
29665 | NULL-terminated string. Data is copied into a new Python string and | |
29666 | returned.</P> | |
29667 | <P> If your program needs to work with binary data, you can use a | |
29668 | typemap to expand a Python string into a pointer/length argument pair. | |
29669 | As luck would have it, just such a typemap is already defined. Just do | |
29670 | this:</P> | |
29671 | <DIV class="code"> | |
29672 | <PRE> | |
29673 | %apply (char *STRING, int LENGTH) { (char *data, int size) }; | |
29674 | ... | |
29675 | int parity(char *data, int size, int initial); | |
29676 | </PRE> | |
29677 | </DIV> | |
29678 | <P> Now in Python:</P> | |
29679 | <DIV class="targetlang"> | |
29680 | <PRE> | |
29681 | >>> parity("e\x09ffss\x00\x00\x01\nx", 0) | |
29682 | </PRE> | |
29683 | </DIV> | |
29684 | <P> If you need to return binary data, you might use the <TT>cstring.i</TT> | |
29685 | library file. The <TT>cdata.i</TT> library can also be used to extra | |
29686 | binary data from arbitrary pointers.</P> | |
29687 | <H3><A name="Python_nn50"></A>26.7.5 Arrays</H3> | |
29688 | <H3><A name="Python_nn51"></A>26.7.6 String arrays</H3> | |
29689 | <H3><A name="Python_nn52"></A>26.7.7 STL wrappers</H3> | |
29690 | <H2><A name="Python_nn53"></A>26.8 Typemaps</H2> | |
29691 | <P> This section describes how you can modify SWIG's default wrapping | |
29692 | behavior for various C/C++ datatypes using the <TT>%typemap</TT> | |
29693 | directive. This is an advanced topic that assumes familiarity with the | |
29694 | Python C API as well as the material in the "<A href="#Typemaps"> | |
29695 | Typemaps</A>" chapter.</P> | |
29696 | <P> Before proceeding, it should be stressed that typemaps are not a | |
29697 | required part of using SWIG---the default wrapping behavior is enough | |
29698 | in most cases. Typemaps are only used if you want to change some aspect | |
29699 | of the primitive C-Python interface or if you want to elevate your guru | |
29700 | status.</P> | |
29701 | <H3><A name="Python_nn54"></A>26.8.1 What is a typemap?</H3> | |
29702 | <P> A typemap is nothing more than a code generation rule that is | |
29703 | attached to a specific C datatype. For example, to convert integers | |
29704 | from Python to C, you might define a typemap like this:</P> | |
29705 | <DIV class="code"> | |
29706 | <PRE> | |
29707 | %module example | |
29708 | ||
29709 | %typemap(in) int { | |
29710 | $1 = (int) PyLong_AsLong($input); | |
29711 | printf("Received an integer : %d\n",$1); | |
29712 | } | |
29713 | %inline %{ | |
29714 | extern int fact(int n); | |
29715 | %} | |
29716 | </PRE> | |
29717 | </DIV> | |
29718 | <P> Typemaps are always associated with some specific aspect of code | |
29719 | generation. In this case, the "in" method refers to the conversion of | |
29720 | input arguments to C/C++. The datatype <TT>int</TT> is the datatype to | |
29721 | which the typemap will be applied. The supplied C code is used to | |
29722 | convert values. In this code a number of special variable prefaced by a | |
29723 | <TT>$</TT> are used. The <TT>$1</TT> variable is placeholder for a | |
29724 | local variable of type <TT>int</TT>. The <TT>$input</TT> variable is | |
29725 | the input object of type <TT>PyObject *</TT>.</P> | |
29726 | <P> When this example is compiled into a Python module, it operates as | |
29727 | follows:</P> | |
29728 | <DIV class="targetlang"> | |
29729 | <PRE> | |
29730 | >>> from example import * | |
29731 | >>> fact(6) | |
29732 | Received an integer : 6 | |
29733 | 720 | |
29734 | </PRE> | |
29735 | </DIV> | |
29736 | <P> In this example, the typemap is applied to all occurrences of the <TT> | |
29737 | int</TT> datatype. You can refine this by supplying an optional | |
29738 | parameter name. For example:</P> | |
29739 | <DIV class="code"> | |
29740 | <PRE> | |
29741 | %module example | |
29742 | ||
29743 | %typemap(in) int nonnegative { | |
29744 | $1 = (int) PyLong_AsLong($input); | |
29745 | if ($1 < 0) { | |
29746 | PyErr_SetString(PyExc_ValueError,"Expected a nonnegative value."); | |
29747 | return NULL; | |
29748 | } | |
29749 | } | |
29750 | %inline %{ | |
29751 | extern int fact(int nonnegative); | |
29752 | %} | |
29753 | </PRE> | |
29754 | </DIV> | |
29755 | <P> In this case, the typemap code is only attached to arguments that | |
29756 | exactly match <TT>int nonnegative</TT>.</P> | |
29757 | <P> The application of a typemap to specific datatypes and argument | |
29758 | names involves more than simple text-matching--typemaps are fully | |
29759 | integrated into the SWIG C++ type-system. When you define a typemap for | |
29760 | <TT>int</TT>, that typemap applies to <TT>int</TT> and qualified | |
29761 | variations such as <TT>const int</TT>. In addition, the typemap system | |
29762 | follows <TT>typedef</TT> declarations. For example:</P> | |
29763 | <DIV class="code"> | |
29764 | <PRE> | |
29765 | %typemap(in) int n { | |
29766 | $1 = (int) PyLong_AsLong($input); | |
29767 | printf("n = %d\n",$1); | |
29768 | } | |
29769 | %inline %{ | |
29770 | typedef int Integer; | |
29771 | extern int fact(Integer n); // Above typemap is applied | |
29772 | %} | |
29773 | </PRE> | |
29774 | </DIV> | |
29775 | <P> Typemaps can also be defined for groups of consecutive arguments. | |
29776 | For example:</P> | |
29777 | <DIV class="code"> | |
29778 | <PRE> | |
29779 | %typemap(in) (char *str, int len) { | |
29780 | $1 = PyString_AsString($input); | |
29781 | $2 = PyString_Size($input); | |
29782 | }; | |
29783 | ||
29784 | int count(char c, char *str, int len); | |
29785 | </PRE> | |
29786 | </DIV> | |
29787 | <P> When a multi-argument typemap is defined, the arguments are always | |
29788 | handled as a single Python object. This allows the function to be used | |
29789 | like this (notice how the length parameter is omitted):</P> | |
29790 | <DIV class="targetlang"> | |
29791 | <PRE> | |
29792 | >>> example.count('e','Hello World') | |
29793 | 1 | |
29794 | >>> | |
29795 | </PRE> | |
29796 | </DIV> | |
29797 | <H3><A name="Python_nn55"></A>26.8.2 Python typemaps</H3> | |
29798 | <P> The previous section illustrated an "in" typemap for converting | |
29799 | Python objects to C. A variety of different typemap methods are defined | |
29800 | by the Python module. For example, to convert a C integer back into a | |
29801 | Python object, you might define an "out" typemap like this:</P> | |
29802 | <DIV class="code"> | |
29803 | <PRE> | |
29804 | %typemap(out) int { | |
29805 | $result = PyInt_FromLong((long) $1); | |
29806 | } | |
29807 | </PRE> | |
29808 | </DIV> | |
29809 | <P> A detailed list of available methods can be found in the "<A href="#Typemaps"> | |
29810 | Typemaps</A>" chapter.</P> | |
29811 | <P> However, the best source of typemap information (and examples) is | |
29812 | probably the Python module itself. In fact, all of SWIG's default type | |
29813 | handling is defined by typemaps. You can view these typemaps by looking | |
29814 | at the files in the SWIG library. Just take into account that in the | |
29815 | latest versions of swig (1.3.22+), the library files are not very | |
29816 | pristine clear for the casual reader, as they used to be. The extensive | |
29817 | use of macros and other ugly techniques in the latest version produce a | |
29818 | very powerful and consistent python typemap library, but at the cost of | |
29819 | simplicity and pedagogic value.</P> | |
29820 | <P> To learn how to write a simple or your first typemap, you better | |
29821 | take a look at the SWIG library version 1.3.20 or so.</P> | |
29822 | <H3><A name="Python_nn56"></A>26.8.3 Typemap variables</H3> | |
29823 | <P> Within typemap code, a number of special variables prefaced with a <TT> | |
29824 | $</TT> may appear. A full list of variables can be found in the "<A href="#Typemaps"> | |
29825 | Typemaps</A>" chapter. This is a list of the most common variables:</P> | |
29826 | <P> <TT>$1</TT></P> | |
29827 | <DIV class="indent"> A C local variable corresponding to the actual type | |
29828 | specified in the <TT>%typemap</TT> directive. For input values, this is | |
29829 | a C local variable that's supposed to hold an argument value. For | |
29830 | output values, this is the raw result that's supposed to be returned to | |
29831 | Python.</DIV> | |
29832 | <P> <TT>$input</TT></P> | |
29833 | <DIV class="indent"> A <TT>PyObject *</TT> holding a raw Python object | |
29834 | with an argument or variable value.</DIV> | |
29835 | <P> <TT>$result</TT></P> | |
29836 | <DIV class="indent"> A <TT>PyObject *</TT> that holds the result to be | |
29837 | returned to Python.</DIV> | |
29838 | <P> <TT>$1_name</TT></P> | |
29839 | <DIV class="indent"> The parameter name that was matched.</DIV> | |
29840 | <P> <TT>$1_type</TT></P> | |
29841 | <DIV class="indent"> The actual C datatype matched by the typemap.</DIV> | |
29842 | <P> <TT>$1_ltype</TT></P> | |
29843 | <DIV class="indent"> An assignable version of the datatype matched by | |
29844 | the typemap (a type that can appear on the left-hand-side of a C | |
29845 | assignment operation). This type is stripped of qualifiers and may be | |
29846 | an altered version of <TT>$1_type</TT>. All arguments and local | |
29847 | variables in wrapper functions are declared using this type so that | |
29848 | their values can be properly assigned.</DIV> | |
29849 | <P> <TT>$symname</TT></P> | |
29850 | <DIV class="indent"> The Python name of the wrapper function being | |
29851 | created.</DIV> | |
29852 | <H3><A name="Python_nn57"></A>26.8.4 Useful Python Functions</H3> | |
29853 | <P> When you write a typemap, you usually have to work directly with | |
29854 | Python objects. The following functions may prove to be useful.</P> | |
29855 | <P><B> Python Integer Functions</B></P> | |
29856 | <DIV class="code"> | |
29857 | <PRE> | |
29858 | PyObject *PyInt_FromLong(long l); | |
29859 | long PyInt_AsLong(PyObject *); | |
29860 | int PyInt_Check(PyObject *); | |
29861 | </PRE> | |
29862 | </DIV> | |
29863 | <P><B> Python Floating Point Functions</B></P> | |
29864 | <DIV class="code"> | |
29865 | <PRE> | |
29866 | PyObject *PyFloat_FromDouble(double); | |
29867 | double PyFloat_AsDouble(PyObject *); | |
29868 | int PyFloat_Check(PyObject *); | |
29869 | </PRE> | |
29870 | </DIV> | |
29871 | <P><B> Python String Functions</B></P> | |
29872 | <DIV class="code"> | |
29873 | <PRE> | |
29874 | PyObject *PyString_FromString(char *); | |
29875 | PyObject *PyString_FromStringAndSize(char *, lint len); | |
29876 | int PyString_Size(PyObject *); | |
29877 | char *PyString_AsString(PyObject *); | |
29878 | int PyString_Check(PyObject *); | |
29879 | </PRE> | |
29880 | </DIV> | |
29881 | <P><B> Python List Functions</B></P> | |
29882 | <DIV class="code"> | |
29883 | <PRE> | |
29884 | PyObject *PyList_New(int size); | |
29885 | int PyList_Size(PyObject *list); | |
29886 | PyObject *PyList_GetItem(PyObject *list, int i); | |
29887 | int PyList_SetItem(PyObject *list, int i, PyObject *item); | |
29888 | int PyList_Insert(PyObject *list, int i, PyObject *item); | |
29889 | int PyList_Append(PyObject *list, PyObject *item); | |
29890 | PyObject *PyList_GetSlice(PyObject *list, int i, int j); | |
29891 | int PyList_SetSlice(PyObject *list, int i, int , PyObject *list2); | |
29892 | int PyList_Sort(PyObject *list); | |
29893 | int PyList_Reverse(PyObject *list); | |
29894 | PyObject *PyList_AsTuple(PyObject *list); | |
29895 | int PyList_Check(PyObject *); | |
29896 | </PRE> | |
29897 | </DIV> | |
29898 | <P><B> Python Tuple Functions</B></P> | |
29899 | <DIV class="code"> | |
29900 | <PRE> | |
29901 | PyObject *PyTuple_New(int size); | |
29902 | int PyTuple_Size(PyObject *); | |
29903 | PyObject *PyTuple_GetItem(PyObject *, int i); | |
29904 | int PyTuple_SetItem(PyObject *, int i, pyObject *item); | |
29905 | PyObject *PyTuple_GetSlice(PyObject *t, int i, int j); | |
29906 | int PyTuple_Check(PyObject *); | |
29907 | </PRE> | |
29908 | </DIV> | |
29909 | <P><B> Python Dictionary Functions</B></P> | |
29910 | <DIV class="code"> | |
29911 | <PRE> | |
29912 | write me | |
29913 | </PRE> | |
29914 | </DIV> | |
29915 | <P><B> Python File Conversion Functions</B></P> | |
29916 | <DIV class="code"> | |
29917 | <PRE> | |
29918 | PyObject *PyFile_FromFile(FILE *f); | |
29919 | FILE *PyFile_AsFile(PyObject *); | |
29920 | int PyFile_Check(PyObject *); | |
29921 | </PRE> | |
29922 | </DIV> | |
29923 | <P><B> Abstract Object Interface</B></P> | |
29924 | <DIV class="code"> | |
29925 | <PRE> | |
29926 | write me | |
29927 | </PRE> | |
29928 | </DIV> | |
29929 | <H2><A name="Python_nn58"></A>26.9 Typemap Examples</H2> | |
29930 | <P> This section includes a few examples of typemaps. For more examples, | |
29931 | you might look at the files "<TT>python.swg</TT>" and "<TT>typemaps.i</TT> | |
29932 | " in the SWIG library.</P> | |
29933 | <H3><A name="Python_nn59"></A>26.9.1 Converting Python list to a char **</H3> | |
29934 | <P> A common problem in many C programs is the processing of command | |
29935 | line arguments, which are usually passed in an array of NULL terminated | |
29936 | strings. The following SWIG interface file allows a Python list object | |
29937 | to be used as a <TT>char **</TT> object.</P> | |
29938 | <DIV class="code"> | |
29939 | <PRE> | |
29940 | %module argv | |
29941 | ||
29942 | // This tells SWIG to treat char ** as a special case | |
29943 | %typemap(in) char ** { | |
29944 | /* Check if is a list */ | |
29945 | if (PyList_Check($input)) { | |
29946 | int size = PyList_Size($input); | |
29947 | int i = 0; | |
29948 | $1 = (char **) malloc((size+1)*sizeof(char *)); | |
29949 | for (i = 0; i < size; i++) { | |
29950 | PyObject *o = PyList_GetItem($input,i); | |
29951 | if (PyString_Check(o)) | |
29952 | $1[i] = PyString_AsString(PyList_GetItem($input,i)); | |
29953 | else { | |
29954 | PyErr_SetString(PyExc_TypeError,"list must contain strings"); | |
29955 | free($1); | |
29956 | return NULL; | |
29957 | } | |
29958 | } | |
29959 | $1[i] = 0; | |
29960 | } else { | |
29961 | PyErr_SetString(PyExc_TypeError,"not a list"); | |
29962 | return NULL; | |
29963 | } | |
29964 | } | |
29965 | ||
29966 | // This cleans up the char ** array we malloc'd before the function call | |
29967 | %typemap(freearg) char ** { | |
29968 | free((char *) $1); | |
29969 | } | |
29970 | ||
29971 | // Now a test function | |
29972 | %inline %{ | |
29973 | int print_args(char **argv) { | |
29974 | int i = 0; | |
29975 | while (argv[i]) { | |
29976 | printf("argv[%d] = %s\n", i,argv[i]); | |
29977 | i++; | |
29978 | } | |
29979 | return i; | |
29980 | } | |
29981 | %} | |
29982 | ||
29983 | </PRE> | |
29984 | </DIV> | |
29985 | <P> When this module is compiled, the wrapped C function now operates as | |
29986 | follows :</P> | |
29987 | <DIV class="targetlang"> | |
29988 | <PRE> | |
29989 | >>> from argv import * | |
29990 | >>> print_args(["Dave","Mike","Mary","Jane","John"]) | |
29991 | argv[0] = Dave | |
29992 | argv[1] = Mike | |
29993 | argv[2] = Mary | |
29994 | argv[3] = Jane | |
29995 | argv[4] = John | |
29996 | 5 | |
29997 | </PRE> | |
29998 | </DIV> | |
29999 | <P> In the example, two different typemaps are used. The "in" typemap is | |
30000 | used to receive an input argument and convert it to a C array. Since | |
30001 | dynamic memory allocation is used to allocate memory for the array, the | |
30002 | "freearg" typemap is used to later release this memory after the | |
30003 | execution of the C function.</P> | |
30004 | <H3><A name="Python_nn60"></A>26.9.2 Expanding a Python object into | |
30005 | multiple arguments</H3> | |
30006 | <P> Suppose that you had a collection of C functions with arguments such | |
30007 | as the following:</P> | |
30008 | <DIV class="code"> | |
30009 | <PRE> | |
30010 | int foo(int argc, char **argv); | |
30011 | </PRE> | |
30012 | </DIV> | |
30013 | <P> In the previous example, a typemap was written to pass a Python list | |
30014 | as the <TT>char **argv</TT>. This allows the function to be used from | |
30015 | Python as follows:</P> | |
30016 | <DIV class="targetlang"> | |
30017 | <PRE> | |
30018 | >>> foo(4, ["foo","bar","spam","1"]) | |
30019 | </PRE> | |
30020 | </DIV> | |
30021 | <P> Although this works, it's a little awkward to specify the argument | |
30022 | count. To fix this, a multi-argument typemap can be defined. This is | |
30023 | not very difficult--you only have to make slight modifications to the | |
30024 | previous example:</P> | |
30025 | <DIV class="code"> | |
30026 | <PRE> | |
30027 | %typemap(in) (int argc, char **argv) { | |
30028 | /* Check if is a list */ | |
30029 | if (PyList_Check($input)) { | |
30030 | int i; | |
30031 | $1 = PyList_Size($input); | |
30032 | $2 = (char **) malloc(($1+1)*sizeof(char *)); | |
30033 | for (i = 0; i < $1; i++) { | |
30034 | PyObject *o = PyList_GetItem($input,i); | |
30035 | if (PyString_Check(o)) | |
30036 | $2[i] = PyString_AsString(PyList_GetItem($input,i)); | |
30037 | else { | |
30038 | PyErr_SetString(PyExc_TypeError,"list must contain strings"); | |
30039 | free($2); | |
30040 | return NULL; | |
30041 | } | |
30042 | } | |
30043 | $2[i] = 0; | |
30044 | } else { | |
30045 | PyErr_SetString(PyExc_TypeError,"not a list"); | |
30046 | return NULL; | |
30047 | } | |
30048 | } | |
30049 | ||
30050 | %typemap(freearg) (int argc, char **argv) { | |
30051 | free((char *) $2); | |
30052 | } | |
30053 | </PRE> | |
30054 | </DIV> | |
30055 | <P> When writing a multiple-argument typemap, each of the types is | |
30056 | referenced by a variable such as <TT>$1</TT> or <TT>$2</TT>. The | |
30057 | typemap code simply fills in the appropriate values from the supplied | |
30058 | Python object.</P> | |
30059 | <P> With the above typemap in place, you will find it no longer | |
30060 | necessary to supply the argument count. This is automatically set by | |
30061 | the typemap code. For example:</P> | |
30062 | <DIV class="targetlang"> | |
30063 | <PRE> | |
30064 | >>> foo(["foo","bar","spam","1"]) | |
30065 | </PRE> | |
30066 | </DIV> | |
30067 | <H3><A name="Python_nn61"></A>26.9.3 Using typemaps to return arguments</H3> | |
30068 | <P> A common problem in some C programs is that values may be returned | |
30069 | in arguments rather than in the return value of a function. For | |
30070 | example:</P> | |
30071 | <DIV class="code"> | |
30072 | <PRE> | |
30073 | /* Returns a status value and two values in out1 and out2 */ | |
30074 | int spam(double a, double b, double *out1, double *out2) { | |
30075 | ... Do a bunch of stuff ... | |
30076 | *out1 = result1; | |
30077 | *out2 = result2; | |
30078 | return status; | |
30079 | }; | |
30080 | ||
30081 | </PRE> | |
30082 | </DIV> | |
30083 | <P> A typemap can be used to handle this case as follows :</P> | |
30084 | <DIV class="code"> | |
30085 | <PRE> | |
30086 | %module outarg | |
30087 | ||
30088 | // This tells SWIG to treat an double * argument with name 'OutValue' as | |
30089 | // an output value. We'll append the value to the current result which | |
30090 | // is guaranteed to be a List object by SWIG. | |
30091 | ||
30092 | %typemap(argout) double *OutValue { | |
30093 | PyObject *o, *o2, *o3; | |
30094 | o = PyFloat_FromDouble(*$1); | |
30095 | if ((!$result) || ($result == Py_None)) { | |
30096 | $result = o; | |
30097 | } else { | |
30098 | if (!PyTuple_Check($result)) { | |
30099 | PyObject *o2 = $result; | |
30100 | $result = PyTuple_New(1); | |
30101 | PyTuple_SetItem(target,0,o2); | |
30102 | } | |
30103 | o3 = PyTuple_New(1); | |
30104 | PyTuple_SetItem(o3,0,o); | |
30105 | o2 = $result; | |
30106 | $result = PySequence_Concat(o2,o3); | |
30107 | Py_DECREF(o2); | |
30108 | Py_DECREF(o3); | |
30109 | } | |
30110 | } | |
30111 | ||
30112 | int spam(double a, double b, double *OutValue, double *OutValue); | |
30113 | ||
30114 | </PRE> | |
30115 | </DIV> | |
30116 | <P> The typemap works as follows. First, a check is made to see if any | |
30117 | previous result exists. If so, it is turned into a tuple and the new | |
30118 | output value is concatenated to it. Otherwise, the result is returned | |
30119 | normally. For the sample function <TT>spam()</TT>, there are three | |
30120 | output values--meaning that the function will return a 3-tuple of the | |
30121 | results.</P> | |
30122 | <P> As written, the function must accept 4 arguments as input values, | |
30123 | last two being pointers to doubles. If these arguments are only used to | |
30124 | hold output values (and have no meaningful input value), an additional | |
30125 | typemap can be written. For example:</P> | |
30126 | <DIV class="code"> | |
30127 | <PRE> | |
30128 | %typemap(in,numinputs=0) double *OutValue(double temp) { | |
30129 | $1 = &temp; | |
30130 | } | |
30131 | ||
30132 | </PRE> | |
30133 | </DIV> | |
30134 | <P> By specifying numinputs=0, the input value is ignored. However, | |
30135 | since the argument still has to be set to some meaningful value before | |
30136 | calling C, it is set to point to a local variable <TT>temp</TT>. When | |
30137 | the function stores its output value, it will simply be placed in this | |
30138 | local variable. As a result, the function can now be used as follows:</P> | |
30139 | <DIV class="targetlang"> | |
30140 | <PRE> | |
30141 | >>> a = spam(4,5) | |
30142 | >>> print a | |
30143 | (0, 2.45, 5.0) | |
30144 | >>> x,y,z = spam(4,5) | |
30145 | >>> | |
30146 | </PRE> | |
30147 | </DIV> | |
30148 | <H3><A name="Python_nn62"></A>26.9.4 Mapping Python tuples into small | |
30149 | arrays</H3> | |
30150 | <P> In some applications, it is sometimes desirable to pass small arrays | |
30151 | of numbers as arguments. For example :</P> | |
30152 | <DIV class="code"> | |
30153 | <PRE> | |
30154 | extern void set_direction(double a[4]); // Set direction vector | |
30155 | </PRE> | |
30156 | </DIV> | |
30157 | <P> This too, can be handled used typemaps as follows :</P> | |
30158 | <DIV class="code"> | |
30159 | <PRE> | |
30160 | // Grab a 4 element array as a Python 4-tuple | |
30161 | %typemap(in) double[4](double temp[4]) { // temp[4] becomes a local variable | |
30162 | int i; | |
30163 | if (PyTuple_Check($input)) { | |
30164 | if (!PyArg_ParseTuple($input,"dddd",temp,temp+1,temp+2,temp+3)) { | |
30165 | PyErr_SetString(PyExc_TypeError,"tuple must have 4 elements"); | |
30166 | return NULL; | |
30167 | } | |
30168 | $1 = &temp[0]; | |
30169 | } else { | |
30170 | PyErr_SetString(PyExc_TypeError,"expected a tuple."); | |
30171 | return NULL; | |
30172 | } | |
30173 | } | |
30174 | ||
30175 | </PRE> | |
30176 | </DIV> | |
30177 | <P> This allows our <TT>set_direction</TT> function to be called from | |
30178 | Python as follows :</P> | |
30179 | <DIV class="targetlang"> | |
30180 | <PRE> | |
30181 | >>> set_direction((0.5,0.0,1.0,-0.25)) | |
30182 | </PRE> | |
30183 | </DIV> | |
30184 | <P> Since our mapping copies the contents of a Python tuple into a C | |
30185 | array, such an approach would not be recommended for huge arrays, but | |
30186 | for small structures, this approach works fine.</P> | |
30187 | <H3><A name="Python_nn63"></A>26.9.5 Mapping sequences to C arrays</H3> | |
30188 | <P> Suppose that you wanted to generalize the previous example to handle | |
30189 | C arrays of different sizes. To do this, you might write a typemap as | |
30190 | follows:</P> | |
30191 | <DIV class="code"> | |
30192 | <PRE> | |
30193 | // Map a Python sequence into any sized C double array | |
30194 | %typemap(in) double[ANY](double temp[$1_dim0]) { | |
30195 | int i; | |
30196 | if (!PySequence_Check($input)) { | |
30197 | PyErr_SetString(PyExc_TypeError,"Expecting a sequence"); | |
30198 | return NULL; | |
30199 | } | |
30200 | if (PyObject_Length($input) != $1_dim0) { | |
30201 | PyErr_SetString(PyExc_ValueError,"Expecting a sequence with $1_dim0 elements"); | |
30202 | return NULL; | |
30203 | } | |
30204 | for (i =0; i < $1_dim0; i++) { | |
30205 | PyObject *o = PySequence_GetItem($input,i); | |
30206 | if (!PyFloat_Check(o)) { | |
30207 | PyErr_SetString(PyExc_ValueError,"Expecting a sequence of floats"); | |
30208 | return NULL; | |
30209 | } | |
30210 | temp[i] = PyFloat_AsDouble(o); | |
30211 | } | |
30212 | $1 = &temp[0]; | |
30213 | } | |
30214 | </PRE> | |
30215 | </DIV> | |
30216 | <P> In this case, the variable <TT>$1_dim0</TT> is expanded to match the | |
30217 | array dimensions actually used in the C code. This allows the typemap | |
30218 | to be applied to types such as:</P> | |
30219 | <DIV class="code"> | |
30220 | <PRE> | |
30221 | void foo(double x[10]); | |
30222 | void bar(double a[4], double b[8]); | |
30223 | </PRE> | |
30224 | </DIV> | |
30225 | <P> Since the above typemap code gets inserted into every wrapper | |
30226 | function where used, it might make sense to use a helper function | |
30227 | instead. This will greatly reduce the amount of wrapper code. For | |
30228 | example:</P> | |
30229 | <DIV class="code"> | |
30230 | <PRE> | |
30231 | %{ | |
30232 | static int convert_darray(PyObject *input, double *ptr, int size) { | |
30233 | int i; | |
30234 | if (!PySequence_Check(input)) { | |
30235 | PyErr_SetString(PyExc_TypeError,"Expecting a sequence"); | |
30236 | return 0; | |
30237 | } | |
30238 | if (PyObject_Length(input) != size) { | |
30239 | PyErr_SetString(PyExc_ValueError,"Sequence size mismatch"); | |
30240 | return 0; | |
30241 | } | |
30242 | for (i =0; i < size; i++) { | |
30243 | PyObject *o = PySequence_GetItem(input,i); | |
30244 | if (!PyFloat_Check(o)) { | |
30245 | PyErr_SetString(PyExc_ValueError,"Expecting a sequence of floats"); | |
30246 | return 0; | |
30247 | } | |
30248 | ptr[i] = PyFloat_AsDouble(o); | |
30249 | } | |
30250 | return 1; | |
30251 | } | |
30252 | %} | |
30253 | ||
30254 | %typemap(in) double [ANY](double temp[$1_dim0]) { | |
30255 | if (!convert_darray($input,temp,$1_dim0))) { | |
30256 | return NULL; | |
30257 | } | |
30258 | $1 = &temp[0]; | |
30259 | } | |
30260 | </PRE> | |
30261 | </DIV> | |
30262 | <H3><A name="Python_nn64"></A>26.9.6 Pointer handling</H3> | |
30263 | <P> Occasionally, it might be necessary to convert pointer values that | |
30264 | have been stored using the SWIG typed-pointer representation. Since | |
30265 | there are several ways in which pointers can be represented, the | |
30266 | following two functions are used to safely perform this conversion:</P> | |
30267 | <P> <TT>int SWIG_ConvertPtr(PyObject *obj, void **ptr, swig_type_info | |
30268 | *ty, int flags)</TT></P> | |
30269 | <DIV class="indent"> Converts a Python object <TT>obj</TT> to a C | |
30270 | pointer. The result of the conversion is placed into the pointer | |
30271 | located at <TT>ptr</TT>. <TT>ty</TT> is a SWIG type descriptor | |
30272 | structure. <TT>flags</TT> is used to handle error checking and other | |
30273 | aspects of conversion. It is the bitwise-or of several flag values | |
30274 | including <TT>SWIG_POINTER_EXCEPTION</TT> and <TT>SWIG_POINTER_DISOWN</TT> | |
30275 | . The first flag makes the function raise an exception on type error. | |
30276 | The second flag additionally steals ownership of an object. Returns 0 | |
30277 | on success and -1 on error.</DIV> | |
30278 | <P> <TT>PyObject *Swig_NewPointerObj(void *ptr, swig_type_info *ty, int | |
30279 | own)</TT></P> | |
30280 | <DIV class="indent"> Creates a new Python pointer object. <TT>ptr</TT> | |
30281 | is the pointer to convert, <TT>ty</TT> is the SWIG type descriptor | |
30282 | structure that describes the type, and <TT>own</TT> is a flag that | |
30283 | indicates whether or not Python should take ownership of the pointer.</DIV> | |
30284 | <P> Both of these functions require the use of a special SWIG | |
30285 | type-descriptor structure. This structure contains information about | |
30286 | the mangled name of the datatype, type-equivalence information, as well | |
30287 | as information about converting pointer values under C++ inheritance. | |
30288 | For a type of <TT>Foo *</TT>, the type descriptor structure is usually | |
30289 | accessed as follows:</P> | |
30290 | <DIV class="code"> | |
30291 | <PRE> | |
30292 | Foo *f; | |
30293 | if (SWIG_ConvertPtr($input, (void **) &f, SWIGTYPE_p_Foo, SWIG_POINTER_EXCEPTION) == -1) | |
30294 | return NULL; | |
30295 | ||
30296 | PyObject *obj; | |
30297 | obj = SWIG_NewPointerObj(f, SWIGTYPE_p_Foo, 0); | |
30298 | </PRE> | |
30299 | </DIV> | |
30300 | <P> In a typemap, the type descriptor should always be accessed using | |
30301 | the special typemap variable <TT>$1_descriptor</TT>. For example:</P> | |
30302 | <DIV class="code"> | |
30303 | <PRE> | |
30304 | %typemap(in) Foo * { | |
30305 | if ((SWIG_ConvertPtr($input,(void **) &$1, $1_descriptor,SWIG_POINTER_EXCEPTION)) == -1) | |
30306 | return NULL; | |
30307 | } | |
30308 | </PRE> | |
30309 | </DIV> | |
30310 | <P> If necessary, the descriptor for any type can be obtained using the <TT> | |
30311 | $descriptor()</TT> macro in a typemap. For example:</P> | |
30312 | <DIV class="code"> | |
30313 | <PRE> | |
30314 | %typemap(in) Foo * { | |
30315 | if ((SWIG_ConvertPtr($input,(void **) &$1, $descriptor(Foo *), | |
30316 | SWIG_POINTER_EXCEPTION)) == -1) | |
30317 | return NULL; | |
30318 | } | |
30319 | </PRE> | |
30320 | </DIV> | |
30321 | <P> Although the pointer handling functions are primarily intended for | |
30322 | manipulating low-level pointers, both functions are fully aware of | |
30323 | Python proxy classes. Specifically, <TT>SWIG_ConvertPtr()</TT> will | |
30324 | retrieve a pointer from any object that has a <TT>this</TT> attribute. | |
30325 | In addition, <TT>SWIG_NewPointerObj()</TT> can automatically generate a | |
30326 | proxy class object (if applicable).</P> | |
30327 | <H2><A name="Python_nn65"></A>26.10 Docstring Features</H2> | |
30328 | <P> Usign docstrings in Python code is becoming more and more important | |
30329 | ans more tools are coming on the scene that take advantage of them, | |
30330 | everything from full-blown documentaiton generators to class browsers | |
30331 | and popup call-tips in Python-aware IDEs. Given the way that SWIG | |
30332 | generates the proxy code by default, your users will normally get | |
30333 | something like <TT>"function_name(*args)"</TT> in the popup calltip of | |
30334 | their IDE which is next to useless when the real function prototype | |
30335 | might be something like this:</P> | |
30336 | <DIV class="code"> | |
30337 | <PRE> | |
30338 | bool function_name(int x, int y, Foo* foo=NULL, Bar* bar=NULL); | |
30339 | </PRE> | |
30340 | </DIV> | |
30341 | <P> The features described in this section make it easy for you to add | |
30342 | docstrings to your modules, functions and methods that can then be used | |
30343 | by the various tools out there to make the programming experience of | |
30344 | your users much simpler.</P> | |
30345 | <H3><A name="Python_nn66"></A>26.10.1 Module docstring</H3> | |
30346 | <P> Python allows a docstring at the begining of the <TT>.py</TT> file | |
30347 | before any other statements, and it is typically used to give a general | |
30348 | description of the entire module. SWIG supports this by setting an | |
30349 | option of the <TT>%module</TT> directive. For example:</P> | |
30350 | <DIV class="code"> | |
30351 | <PRE> | |
30352 | %module(docstring="This is the example module's docstring") example | |
30353 | </PRE> | |
30354 | </DIV> | |
30355 | <P> When you have more than just a line or so then you can retain the | |
30356 | easy readability of the <TT>%module</TT> directive by using a macro. | |
30357 | For example:</P> | |
30358 | <DIV class="code"> | |
30359 | <PRE> | |
30360 | %define DOCSTRING | |
30361 | "The `XmlResource` class allows program resources defining menus, | |
30362 | layout of controls on a panel, etc. to be loaded from an XML file." | |
30363 | %enddef | |
30364 | ||
30365 | %module(docstring=DOCSTRING) xrc | |
30366 | </PRE> | |
30367 | </DIV> | |
30368 | <H3><A name="Python_nn67"></A>26.10.2 %feature("autodoc")</H3> | |
30369 | <P> As alluded to above SWIG will generate all the function and method | |
30370 | proxy wrappers with just "*args" (or "*args, **kwargs" if the -keyword | |
30371 | option is used) for a parameter list and will then sort out the | |
30372 | individual parameters in the C wrapper code. This is nice and simple | |
30373 | for the wrapper code, but makes it difficult to be programmer and tool | |
30374 | friendly as anyone looking at the <TT>.py</TT> file will not be able to | |
30375 | find out anything about the parameters that the fuctions accept.</P> | |
30376 | <P>But since SWIG does know everything about the fucntion it is possible | |
30377 | to generate a docstring containing the parameter types, names and | |
30378 | default values. Since many of the doctring tools are adopting a | |
30379 | standard of recognizing if the first thing in the docstring is a | |
30380 | function prototype then using that instead of what they found from | |
30381 | introspeciton, then life is good once more.</P> | |
30382 | <P>SWIG's Python module provides support for the "autodoc" feature, | |
30383 | which when attached to a node in the parse tree will cause a docstring | |
30384 | to be generated that includes the name of the funciton, parameter | |
30385 | names, default values if any, and return type if any. There are also | |
30386 | three options for autodoc controlled by the value given to the feature, | |
30387 | described below.</P> | |
30388 | <H4><A name="Python_nn68"></A>26.10.2.1 %feature("autodoc", "0")</H4> | |
30389 | <P> When the "0" option is given then the types of the parameters will<EM> | |
30390 | not</EM> be included in the autodoc string. For example, given this | |
30391 | function prototype:</P> | |
30392 | <DIV class="code"> | |
30393 | <PRE> | |
30394 | %feature("autodoc", "0"); | |
30395 | bool function_name(int x, int y, Foo* foo=NULL, Bar* bar=NULL); | |
30396 | </PRE> | |
30397 | </DIV> | |
30398 | <P> Then Python code like this will be generated:</P> | |
30399 | <DIV class="targetlang"> | |
30400 | <PRE> | |
30401 | def function_name(*args, **kwargs): | |
30402 | """function_name(x, y, foo=None, bar=None) -> bool""" | |
30403 | ... | |
30404 | </PRE> | |
30405 | </DIV> | |
30406 | <H4><A name="Python_nn69"></A>26.10.2.2 %feature("autodoc", "1")</H4> | |
30407 | <P> When the "1" option is used then the parameter types<EM> will</EM> | |
30408 | be used in the autodoc string. In addition, an atempt is made to | |
30409 | simplify the type name such that it makes more sense to the Python | |
30410 | user. Pointer, reference and const info is removed, <TT>%rename</TT>'s | |
30411 | are evaluated, etc. (This is not always successful, but works most of | |
30412 | the time. See the next section for what to do when it doesn't.) Given | |
30413 | the example above, then turning on the parameter types with the "1" | |
30414 | option will result in Python code like this:</P> | |
30415 | <DIV class="targetlang"> | |
30416 | <PRE> | |
30417 | def function_name(*args, **kwargs): | |
30418 | """function_name(int x, int y, Foo foo=None, Bar bar=None) -> bool""" | |
30419 | ... | |
30420 | </PRE> | |
30421 | </DIV> | |
30422 | <H4><A name="Python_nn70"></A>26.10.2.3 %feature("autodoc", "docstring")</H4> | |
30423 | <P> Finally, there are times when the automatically generated autodoc | |
30424 | string will make no sense for a Python programmer, particularly when a | |
30425 | typemap is involved. So if you give an explicit value for the autodoc | |
30426 | feature then that string will be used in place of the automatically | |
30427 | generated string. For example:</P> | |
30428 | <DIV class="code"> | |
30429 | <PRE> | |
30430 | %feature("autodoc", "GetPosition() -> (x, y)") GetPosition; | |
30431 | void GetPosition(int* OUTPUT, int* OUTPUT); | |
30432 | </PRE> | |
30433 | </DIV> | |
30434 | <H3><A name="Python_nn71"></A>26.10.3 %feature("docstring")</H3> | |
30435 | <P> In addition to the autodoc strings described above, you can also | |
30436 | attach any arbitrary descriptive text to a node in the parse tree with | |
30437 | the "docstring" feature. When the proxy module is generated then any | |
30438 | docstring associated with classes, function or methods are output. If | |
30439 | an item already has an autodoc string then it is combined with the | |
30440 | docstring and they are output together. If the docstring is all on a | |
30441 | single line then it is output like this::</P> | |
30442 | <DIV class="targetlang"> | |
30443 | <PRE> | |
30444 | """This is the docstring""" | |
30445 | </PRE> | |
30446 | </DIV> | |
30447 | <P> Otherwise, to aid readability it is output like this:</P> | |
30448 | <DIV class="targetlang"> | |
30449 | <PRE> | |
30450 | """ | |
30451 | This is a multi-line docstring | |
30452 | with more than one line. | |
30453 | """ | |
30454 | </PRE> | |
30455 | </DIV> | |
30456 | <H2><A name="Python_nn72"></A>26.11 Python Packages</H2> | |
30457 | <P> Using the <TT>package</TT> option of the <TT>%module</TT> directive | |
30458 | allows you to specify what Python package that the module will be | |
30459 | living in when installed.</P> | |
30460 | <DIV class="code"> | |
30461 | <PRE> | |
30462 | %module(package="wx") xrc | |
30463 | </PRE> | |
30464 | </DIV> | |
30465 | <P> This is useful when the <TT>.i</TT> file is <TT>%import</TT>ed by | |
30466 | another <TT>.i</TT> file. By default SWIG will assume that the importer | |
30467 | is able to find the importee with just the module name, but if they | |
30468 | live in separate Python packages then that won't work. However if the | |
30469 | importee specifies what its package is with the <TT>%module</TT> option | |
30470 | then the Python code generated for the importer will use that package | |
30471 | name when importing the other module and also in base class | |
30472 | declarations, etc. if the pacakge name is different than its own.</P> | |
30473 | ||
30474 | <!-- LocalWords: polymorphism Typemaps STL typemap typemaps Docstring autodoc | |
30475 | --> | |
30476 | ||
30477 | <!-- LocalWords: docstring SWIG's cxx py GCC linux DLL gcc fPIC Wiki Xlinker | |
30478 | --> | |
30479 | ||
30480 | <!-- LocalWords: examplemodule DHAVE CONFIG lpython lm ldl mypython lsocket | |
30481 | --> | |
30482 | ||
30483 | <!-- LocalWords: lnsl lpthread distutils enums namespaces | |
30484 | --> | |
30485 | <HR NOSHADE> | |
30486 | <H1><A name="Ruby"></A>27 SWIG and Ruby</H1> | |
30487 | ||
30488 | <!-- INDEX --> | |
30489 | <DIV class="sectiontoc"> | |
30490 | <UL> | |
30491 | <LI><A href="#Ruby_nn2">Preliminaries</A> | |
30492 | <UL> | |
30493 | <LI><A href="#Ruby_nn3">Running SWIG</A></LI> | |
30494 | <LI><A href="#Ruby_nn4">Getting the right header files</A></LI> | |
30495 | <LI><A href="#Ruby_nn5">Compiling a dynamic module</A></LI> | |
30496 | <LI><A href="#Ruby_nn6">Using your module</A></LI> | |
30497 | <LI><A href="#Ruby_nn7">Static linking</A></LI> | |
30498 | <LI><A href="#Ruby_nn8">Compilation of C++ extensions</A></LI> | |
30499 | </UL> | |
30500 | </LI> | |
30501 | <LI><A href="#Ruby_nn9">Building Ruby Extensions under Windows 95/NT</A> | |
30502 | <UL> | |
30503 | <LI><A href="#Ruby_nn10">Running SWIG from Developer Studio</A></LI> | |
30504 | </UL> | |
30505 | </LI> | |
30506 | <LI><A href="#Ruby_nn11">The Ruby-to-C/C++ Mapping</A> | |
30507 | <UL> | |
30508 | <LI><A href="#Ruby_nn12">Modules</A></LI> | |
30509 | <LI><A href="#Ruby_nn13">Functions</A></LI> | |
30510 | <LI><A href="#Ruby_nn14">Variable Linking</A></LI> | |
30511 | <LI><A href="#Ruby_nn15">Constants</A></LI> | |
30512 | <LI><A href="#Ruby_nn16">Pointers</A></LI> | |
30513 | <LI><A href="#Ruby_nn17">Structures</A></LI> | |
30514 | <LI><A href="#Ruby_nn18">C++ classes</A></LI> | |
30515 | <LI><A href="#Ruby_nn19">C++ Inheritance</A></LI> | |
30516 | <LI><A href="#Ruby_nn20">C++ Overloaded Functions</A></LI> | |
30517 | <LI><A href="#Ruby_nn21">C++ Operators</A></LI> | |
30518 | <LI><A href="#Ruby_nn22">C++ namespaces</A></LI> | |
30519 | <LI><A href="#Ruby_nn23">C++ templates</A></LI> | |
30520 | <LI><A href="#ruby_cpp_smart_pointers">C++ Smart Pointers</A></LI> | |
30521 | <LI><A href="#Ruby_nn25">Cross-Language Polymorphism</A> | |
30522 | <UL> | |
30523 | <LI><A href="#Ruby_nn26">Exception Unrolling</A></LI> | |
30524 | </UL> | |
30525 | </LI> | |
30526 | </UL> | |
30527 | </LI> | |
30528 | <LI><A href="#Ruby_nn27">Input and output parameters</A></LI> | |
30529 | <LI><A href="#Ruby_nn29">Typemaps</A> | |
30530 | <UL> | |
30531 | <LI><A href="#Ruby_nn30">What is a typemap?</A></LI> | |
30532 | <LI><A href="#Ruby_nn31">Ruby typemaps</A></LI> | |
30533 | <LI><A href="#Ruby_nn32">Typemap variables</A></LI> | |
30534 | <LI><A href="#Ruby_nn33">Useful Functions</A> | |
30535 | <UL> | |
30536 | <LI><A href="#Ruby_nn34">C Datatypes to Ruby Objects</A></LI> | |
30537 | <LI><A href="#Ruby_nn35">Ruby Objects to C Datatypes</A></LI> | |
30538 | <LI><A href="#Ruby_nn36">Macros for VALUE</A></LI> | |
30539 | <LI><A href="#Ruby_nn37">Exceptions</A></LI> | |
30540 | <LI><A href="#Ruby_nn38">Iterators</A></LI> | |
30541 | </UL> | |
30542 | </LI> | |
30543 | <LI><A href="#ruby_typemap_examples">Typemap Examples</A></LI> | |
30544 | <LI><A href="#Ruby_nn40">Converting a Ruby array to a char **</A></LI> | |
30545 | <LI><A href="#Ruby_nn41">Collecting arguments in a hash</A></LI> | |
30546 | <LI><A href="#Ruby_nn42">Pointer handling</A> | |
30547 | <UL> | |
30548 | <LI><A href="#Ruby_nn43">Ruby Datatype Wrapping</A></LI> | |
30549 | </UL> | |
30550 | </LI> | |
30551 | </UL> | |
30552 | </LI> | |
30553 | <LI><A href="#ruby_operator_overloading">Operator overloading</A> | |
30554 | <UL> | |
30555 | <LI><A href="#Ruby_nn45">Example: STL Vector to Ruby Array</A></LI> | |
30556 | </UL> | |
30557 | </LI> | |
30558 | <LI><A href="#Ruby_nn46">Advanced Topics</A> | |
30559 | <UL> | |
30560 | <LI><A href="#Ruby_nn47">Creating Multi-Module Packages</A></LI> | |
30561 | <LI><A href="#Ruby_nn48">Defining Aliases</A></LI> | |
30562 | <LI><A href="#Ruby_nn49">Predicate Methods</A></LI> | |
30563 | <LI><A href="#Ruby_nn50">Specifying Mixin Modules</A></LI> | |
30564 | </UL> | |
30565 | </LI> | |
30566 | <LI><A href="#Ruby_nn51">Memory Management</A> | |
30567 | <UL> | |
30568 | <LI><A href="#Ruby_nn53">Object Ownership</A></LI> | |
30569 | <LI><A href="#Ruby_nn54">Object Tracking</A></LI> | |
30570 | <LI><A href="#Ruby_nn55">Mark Functions</A></LI> | |
30571 | <LI><A href="#Ruby_nn56">Free Functions</A></LI> | |
30572 | </UL> | |
30573 | </LI> | |
30574 | </UL> | |
30575 | </DIV> | |
30576 | <!-- INDEX --> | |
30577 | <DIV class="sectiontoc"> | |
30578 | <UL> | |
30579 | <LI> <A href="#Ruby_nn2">Preliminaries</A> | |
30580 | <UL> | |
30581 | <LI> <A href="#Ruby_nn3">Running SWIG</A></LI> | |
30582 | <LI> <A href="#Ruby_nn4">Getting the right header files</A></LI> | |
30583 | <LI> <A href="#Ruby_nn5">Compiling a dynamic module</A></LI> | |
30584 | <LI> <A href="#Ruby_nn6">Using your module</A></LI> | |
30585 | <LI> <A href="#Ruby_nn7">Static linking</A></LI> | |
30586 | <LI> <A href="#Ruby_nn8">Compilation of C++ extensions</A></LI> | |
30587 | </UL> | |
30588 | </LI> | |
30589 | <LI> <A href="#Ruby_nn9">Building Ruby Extensions under Windows 95/NT</A> | |
30590 | <UL> | |
30591 | <LI> <A href="#Ruby_nn10">Running SWIG from Developer Studio</A></LI> | |
30592 | </UL> | |
30593 | </LI> | |
30594 | <LI> <A href="#Ruby_nn11">The Ruby-to-C/C++ Mapping</A> | |
30595 | <UL> | |
30596 | <LI> <A href="#Ruby_nn12">Modules</A></LI> | |
30597 | <LI> <A href="#Ruby_nn13">Functions</A></LI> | |
30598 | <LI> <A href="#Ruby_nn14">Variable Linking</A></LI> | |
30599 | <LI> <A href="#Ruby_nn15">Constants</A></LI> | |
30600 | <LI> <A href="#Ruby_nn16">Pointers</A></LI> | |
30601 | <LI> <A href="#Ruby_nn17">Structures</A></LI> | |
30602 | <LI> <A href="#Ruby_nn18">C++ classes</A></LI> | |
30603 | <LI> <A href="#Ruby_nn19">C++ Inheritance</A></LI> | |
30604 | <LI> <A href="#Ruby_nn20">C++ Overloaded Functions</A></LI> | |
30605 | <LI> <A href="#Ruby_nn21">C++ Operators</A></LI> | |
30606 | <LI> <A href="#Ruby_nn22">C++ namespaces</A></LI> | |
30607 | <LI> <A href="#Ruby_nn23">C++ templates</A></LI> | |
30608 | <LI> <A href="#ruby_cpp_smart_pointers">C++ Smart Pointers</A></LI> | |
30609 | <LI> <A href="#Ruby_nn25">Cross-Language Polymorphism</A> | |
30610 | <UL> | |
30611 | <LI> <A href="#Ruby_nn26">Exception Unrolling</A></LI> | |
30612 | </UL> | |
30613 | </LI> | |
30614 | </UL> | |
30615 | </LI> | |
30616 | <LI> <A href="#Ruby_nn27">Input and output parameters</A></LI> | |
30617 | <LI> <A href="#Ruby_nn28">Simple exception handling</A></LI> | |
30618 | <LI> <A href="#Ruby_nn29">Typemaps</A> | |
30619 | <UL> | |
30620 | <LI> <A href="#Ruby_nn30">What is a typemap?</A></LI> | |
30621 | <LI> <A href="#Ruby_nn31">Ruby typemaps</A></LI> | |
30622 | <LI> <A href="#Ruby_nn32">Typemap variables</A></LI> | |
30623 | <LI> <A href="#Ruby_nn33">Useful Functions</A> | |
30624 | <UL> | |
30625 | <LI> <A href="#Ruby_nn34">C Datatypes to Ruby Objects</A></LI> | |
30626 | <LI> <A href="#Ruby_nn35">Ruby Objects to C Datatypes</A></LI> | |
30627 | <LI> <A href="#Ruby_nn36">Macros for VALUE</A></LI> | |
30628 | <LI> <A href="#Ruby_nn37">Exceptions</A></LI> | |
30629 | <LI> <A href="#Ruby_nn38">Iterators</A></LI> | |
30630 | </UL> | |
30631 | </LI> | |
30632 | <LI> <A href="#ruby_typemap_examples">Typemap Examples</A></LI> | |
30633 | <LI> <A href="#Ruby_nn40">Converting a Ruby array to a char **</A></LI> | |
30634 | <LI> <A href="#Ruby_nn41">Collecting arguments in a hash</A></LI> | |
30635 | <LI> <A href="#Ruby_nn42">Pointer handling</A> | |
30636 | <UL> | |
30637 | <LI> <A href="#Ruby_nn43">Ruby Datatype Wrapping</A></LI> | |
30638 | </UL> | |
30639 | </LI> | |
30640 | </UL> | |
30641 | </LI> | |
30642 | <LI> <A href="#ruby_operator_overloading">Operator overloading</A> | |
30643 | <UL> | |
30644 | <LI> <A href="#Ruby_nn45">Example: STL Vector to Ruby Array</A></LI> | |
30645 | </UL> | |
30646 | </LI> | |
30647 | <LI> <A href="#Ruby_nn46">Advanced Topics</A> | |
30648 | <UL> | |
30649 | <LI> <A href="#Ruby_nn47">Creating Multi-Module Packages</A></LI> | |
30650 | <LI> <A href="#Ruby_nn48">Defining Aliases</A></LI> | |
30651 | <LI> <A href="#Ruby_nn49">Predicate Methods</A></LI> | |
30652 | <LI> <A href="#Ruby_nn50">Specifying Mixin Modules</A></LI> | |
30653 | </UL> | |
30654 | </LI> | |
30655 | <LI> <A href="#Ruby_nn51">Memory Management</A> | |
30656 | <UL> | |
30657 | <LI> <A href="#Ruby_nn52">Mark and Sweep Garbage Collector</A></LI> | |
30658 | <LI> <A href="#Ruby_nn53">Object Ownership</A></LI> | |
30659 | <LI> <A href="#Ruby_nn54">Object Tracking</A></LI> | |
30660 | <LI> <A href="#Ruby_nn55">Mark Functions</A></LI> | |
30661 | <LI> <A href="#Ruby_nn56">Free Functions</A></LI> | |
30662 | </UL> | |
30663 | </LI> | |
30664 | </UL> | |
30665 | </DIV> | |
30666 | <!-- INDEX --> | |
30667 | <P>This chapter describes SWIG's support of Ruby.</P> | |
30668 | <H2><A name="Ruby_nn2"></A>27.1 Preliminaries</H2> | |
30669 | <P> SWIG 1.3 is known to work with Ruby versions 1.6 and later. Given | |
30670 | the choice, you should use the latest stable version of Ruby. You | |
30671 | should also determine if your system supports shared libraries and | |
30672 | dynamic loading. SWIG will work with or without dynamic loading, but | |
30673 | the compilation process will vary.</P> | |
30674 | <P>This chapter covers most SWIG features, but in less depth than is | |
30675 | found in earlier chapters. At the very least, make sure you also read | |
30676 | the "<A href="#SWIG">SWIG Basics</A>" chapter. It is also assumed that | |
30677 | the reader has a basic understanding of Ruby.</P> | |
30678 | <H3><A name="Ruby_nn3"></A>27.1.1 Running SWIG</H3> | |
30679 | <P> To build a Ruby module, run SWIG using the <TT>-ruby</TT> option:</P> | |
30680 | <DIV class="code"> | |
30681 | <PRE>$ <B>swig -ruby example.i</B> | |
30682 | </PRE> | |
30683 | </DIV> | |
30684 | <P> If building a C++ extension, add the <TT>-c++</TT> option:</P> | |
30685 | <DIV class="code"> | |
30686 | <PRE>$ <B>swig -c++ -ruby example.i</B> | |
30687 | </PRE> | |
30688 | </DIV> | |
30689 | <P> This creates a file <TT>example_wrap.c</TT> (<TT>example_wrap.cxx</TT> | |
30690 | if compiling a C++ extension) that contains all of the code needed to | |
30691 | build a Ruby extension module. To finish building the module, you need | |
30692 | to compile this file and link it with the rest of your program.</P> | |
30693 | <H3><A name="Ruby_nn4"></A>27.1.2 Getting the right header files</H3> | |
30694 | <P> In order to compile the wrapper code, the compiler needs the <TT> | |
30695 | ruby.h</TT> header file. This file is usually contained in a directory | |
30696 | such as</P> | |
30697 | <DIV class="code"> | |
30698 | <PRE>/usr/local/lib/ruby/1.6/i686-linux/ruby.h | |
30699 | <BR></PRE> | |
30700 | </DIV> | |
30701 | <P> The exact location may vary on your machine, but the above location | |
30702 | is typical. If you are not entirely sure where Ruby is installed, you | |
30703 | can run Ruby to find out. For example:</P> | |
30704 | <DIV class="code"> | |
30705 | <PRE> | |
30706 | $ <B>ruby -e 'puts $:.join("\n")'</B> | |
30707 | <BR>/usr/local/lib/ruby/site_ruby/1.6 /usr/local/lib/ruby/site_ruby/1.6/i686-linux | |
30708 | /usr/local/lib/ruby/site_ruby /usr/local/lib/ruby/1.6 /usr/local/lib/ruby/1.6/i686-linux . | |
30709 | </PRE> | |
30710 | </DIV> | |
30711 | <H3><A name="Ruby_nn5"></A>27.1.3 Compiling a dynamic module</H3> | |
30712 | <P> Ruby extension modules are typically compiled into shared libraries | |
30713 | that the interpreter loads dynamically at runtime. Since the exact | |
30714 | commands for doing this vary from platform to platform, your best bet | |
30715 | is to follow the steps described in the <TT>README.EXT</TT> file from | |
30716 | the Ruby distribution:</P> | |
30717 | <OL> | |
30718 | <LI> | |
30719 | <P>Create a file called <TT>extconf.rb</TT> that looks like the | |
30720 | following:</P> | |
30721 | <DIV class="code"> | |
30722 | <PRE>require 'mkmf' | |
30723 | <BR>create_makefile('example') | |
30724 | <BR></PRE> | |
30725 | </DIV></LI> | |
30726 | <LI> | |
30727 | <P>Type the following to build the extension:</P> | |
30728 | <DIV class="code"> | |
30729 | <PRE>$ <B>ruby extconf.rb</B> | |
30730 | <BR>$ <B>make</B> | |
30731 | <BR>$ <B>make install</B> | |
30732 | </PRE> | |
30733 | </DIV></LI> | |
30734 | </OL> | |
30735 | <P> Of course, there is the problem that mkmf does not work correctly on | |
30736 | all platforms, e.g, HPUX. If you need to add your own make rules to the | |
30737 | file that <TT>extconf.rb</TT> produces, you can add this:</P> | |
30738 | <DIV class="code"> | |
30739 | <PRE>open("Makefile", "a") { |mf| | |
30740 | <BR> puts <<EOM | |
30741 | <BR> # Your make rules go here | |
30742 | <BR> EOM | |
30743 | <BR>} | |
30744 | <BR></PRE> | |
30745 | </DIV> | |
30746 | <P> to the end of the <TT>extconf.rb</TT> file. If for some reason you | |
30747 | don't want to use the standard approach, you'll need to determine the | |
30748 | correct compiler and linker flags for your build platform. For example, | |
30749 | a typical sequence of commands for the Linux operating system would | |
30750 | look something like this:</P> | |
30751 | <DIV class="code"> | |
30752 | <PRE>$ <B>swig -ruby example.i</B> | |
30753 | <BR>$ <B>gcc -c example.c</B> | |
30754 | <BR>$ <B>gcc -c example_wrap.c -I/usr/local/lib/ruby/1.6/i686-linux</B> | |
30755 | <BR>$ <B>gcc -shared example.o example_wrap.o -o example.so</B> | |
30756 | </PRE> | |
30757 | </DIV> | |
30758 | <P> For other platforms it may be necessary to compile with the <TT> | |
30759 | -fPIC</TT> option to generate position-independent code. If in doubt, | |
30760 | consult the manual pages for your compiler and linker to determine the | |
30761 | correct set of options. You might also check the <A href="http://swig.cs.uchicago.edu/cgi-bin/wiki.pl"> | |
30762 | SWIG Wiki</A> for additional information.</P> | |
30763 | <P> <A name="n6"></A></P> | |
30764 | <H3><A name="Ruby_nn6"></A>27.1.4 Using your module</H3> | |
30765 | <P> Ruby<I> module</I> names must be capitalized, but the convention for | |
30766 | Ruby<I> feature</I> names is to use lowercase names. So, for example, | |
30767 | the<B> Etc</B> extension module is imported by requiring the<B> etc</B> | |
30768 | feature:</P> | |
30769 | <DIV class="code"> | |
30770 | <PRE># The feature name begins with a lowercase letter... | |
30771 | <BR>require 'etc' | |
30772 | <BR> | |
30773 | <BR># ... but the module name begins with an uppercase letter | |
30774 | <BR>puts "Your login name: #{Etc.getlogin}" | |
30775 | <BR></PRE> | |
30776 | </DIV> | |
30777 | <P> To stay consistent with this practice, you should always specify a<B> | |
30778 | lowercase</B> module name with SWIG's <TT>%module</TT> directive. SWIG | |
30779 | will automatically correct the resulting Ruby module name for your | |
30780 | extension. So for example, a SWIG interface file that begins with:</P> | |
30781 | <DIV class="code"> | |
30782 | <PRE>%module example | |
30783 | <BR></PRE> | |
30784 | </DIV> | |
30785 | <P> will result in an extension module using the feature name "example" | |
30786 | and Ruby module name "Example".</P> | |
30787 | <H3><A name="Ruby_nn7"></A>27.1.5 Static linking</H3> | |
30788 | <P> An alternative approach to dynamic linking is to rebuild the Ruby | |
30789 | interpreter with your extension module added to it. In the past, this | |
30790 | approach was sometimes necessary due to limitations in dynamic loading | |
30791 | support on certain machines. However, the situation has improved | |
30792 | greatly over the last few years and you should not consider this | |
30793 | approach unless there is really no other option.</P> | |
30794 | <P>The usual procedure for adding a new module to Ruby involves finding | |
30795 | the Ruby source, adding an entry to the <TT>ext/Setup</TT> file, adding | |
30796 | your directory to the list of extensions in the file, and finally | |
30797 | rebuilding Ruby.</P> | |
30798 | <P><A name="n8"></A></P> | |
30799 | <H3><A name="Ruby_nn8"></A>27.1.6 Compilation of C++ extensions</H3> | |
30800 | <P> On most machines, C++ extension modules should be linked using the | |
30801 | C++ compiler. For example:</P> | |
30802 | <DIV class="code"> | |
30803 | <PRE>$ <B>swig -c++ -ruby example.i</B> | |
30804 | <BR>$ <B>g++ -c example.cxx</B> | |
30805 | <BR>$ <B>g++ -c example_wrap.cxx -I/usr/local/lib/ruby/1.6/i686-linux</B> | |
30806 | <BR>$ <B>g++ -shared example.o example_wrap.o -o example.so</B> | |
30807 | </PRE> | |
30808 | </DIV> | |
30809 | <P> If you've written an <TT>extconf.rb</TT> script to automatically | |
30810 | generate a <TT>Makefile</TT> for your C++ extension module, keep in | |
30811 | mind that (as of this writing) Ruby still uses <TT>gcc</TT> and not <TT> | |
30812 | g++</TT> as its linker. As a result, the required C++ runtime library | |
30813 | support will not be automatically linked into your extension module and | |
30814 | it may fail to load on some platforms. A workaround for this problem is | |
30815 | use the <TT>mkmf</TT> module's <TT>append_library()</TT> method to add | |
30816 | one of the C++ runtime libraries to the list of libraries linked into | |
30817 | your extension, e.g.</P> | |
30818 | <DIV class="code"> | |
30819 | <PRE>require 'mkmf' | |
30820 | <BR>$libs = append_library($libs, "supc++") | |
30821 | <BR>create_makefile('example') | |
30822 | <BR></PRE> | |
30823 | </DIV> | |
30824 | <H2><A name="Ruby_nn9"></A>27.2 Building Ruby Extensions under Windows | |
30825 | 95/NT</H2> | |
30826 | <P> Building a SWIG extension to Ruby under Windows 95/NT is roughly | |
30827 | similar to the process used with Unix. Normally, you will want to | |
30828 | produce a DLL that can be loaded into the Ruby interpreter. For all | |
30829 | recent versions of Ruby, the procedure described above (i.e. using an <TT> | |
30830 | extconf.rb</TT> script) will work with Windows as well; you should be | |
30831 | able to build your code into a DLL by typing:</P> | |
30832 | <DIV class="code"> | |
30833 | <PRE>C:\swigtest> <B>ruby extconf.rb</B> | |
30834 | <BR>C:\swigtest> <B>nmake</B> | |
30835 | <BR>C:\swigtest> <B>nmake install</B> | |
30836 | </PRE> | |
30837 | </DIV> | |
30838 | <P> The remainder of this section covers the process of compiling | |
30839 | SWIG-generated Ruby extensions with Microsoft Visual C++ 6 (i.e. within | |
30840 | the Developer Studio IDE, instead of using the command line tools). In | |
30841 | order to build extensions, you may need to download the source | |
30842 | distribution to the Ruby package, as you will need the Ruby header | |
30843 | files.</P> | |
30844 | <P><A name="n10"></A></P> | |
30845 | <H3><A name="Ruby_nn10"></A>27.2.1 Running SWIG from Developer Studio</H3> | |
30846 | <P> If you are developing your application within Microsoft developer | |
30847 | studio, SWIG can be invoked as a custom build option. The process | |
30848 | roughly follows these steps :</P> | |
30849 | <UL> | |
30850 | <LI> Open up a new workspace and use the AppWizard to select a DLL | |
30851 | project.</LI> | |
30852 | <LI> Add both the SWIG interface file (the .i file), any supporting C | |
30853 | files, and the name of the wrapper file that will be created by SWIG | |
30854 | (i.e.. <TT>example_wrap.c</TT>). Note : If using C++, choose a | |
30855 | different suffix for the wrapper file such as <TT>example_wrap.cxx</TT> | |
30856 | . Don't worry if the wrapper file doesn't exist yet--Developer Studio | |
30857 | will keep a reference to it around.</LI> | |
30858 | <LI> Select the SWIG interface file and go to the settings menu. Under | |
30859 | settings, select the "Custom Build" option.</LI> | |
30860 | <LI> Enter "SWIG" in the description field.</LI> | |
30861 | <LI> Enter "<TT>swig -ruby -o $(ProjDir)\$(InputName)_wrap.c | |
30862 | $(InputPath)</TT>" in the "Build command(s) field". You may have to | |
30863 | include the path to swig.exe.</LI> | |
30864 | <LI> Enter "<TT>$(ProjDir)\$(InputName)_wrap.c</TT>" in the "Output | |
30865 | files(s) field".</LI> | |
30866 | <LI> Next, select the settings for the entire project and go to the | |
30867 | C/C++ tab and select the Preprocessor category. Add NT=1 to the | |
30868 | Preprocessor definitions. This must be set else you will get | |
30869 | compilation errors. Also add IMPORT to the preprocessor definitions, | |
30870 | else you may get runtime errors. Also add the include directories for | |
30871 | your Ruby installation under "Additional include directories".</LI> | |
30872 | <LI> Next, select the settings for the entire project and go to the Link | |
30873 | tab and select the General category. Set the name of the output file to | |
30874 | match the name of your Ruby module (i.e.. example.dll). Next add the | |
30875 | Ruby library file to your link libraries under Object/Library modules. | |
30876 | For example "mswin32-ruby16.lib. You also need to add the path to the | |
30877 | library under the Input tab - Additional library path.</LI> | |
30878 | <LI> Build your project.</LI> | |
30879 | </UL> | |
30880 | <P> Now, assuming all went well, SWIG will be automatically invoked when | |
30881 | you build your project. Any changes made to the interface file will | |
30882 | result in SWIG being automatically invoked to produce a new version of | |
30883 | the wrapper file. To run your new Ruby extension, simply run Ruby and | |
30884 | use the <TT>require</TT> command as normal. For example if you have | |
30885 | this ruby file run.rb:</P> | |
30886 | <DIV class="code"> | |
30887 | <PRE># file: run.rb | |
30888 | <BR>require 'Example' | |
30889 | <BR> | |
30890 | <BR># Call a c function | |
30891 | <BR>print "Foo = ", Example.Foo, "\n" | |
30892 | <BR></PRE> | |
30893 | </DIV> | |
30894 | <P> Ensure the dll just built is in your path or current directory, then | |
30895 | run the Ruby script from the DOS/Command prompt:</P> | |
30896 | <DIV class="code"> | |
30897 | <PRE>C:\swigtest> <B>ruby run.rb</B> | |
30898 | <BR>Foo = 3.0 | |
30899 | <BR></PRE> | |
30900 | </DIV> | |
30901 | <H2><A name="Ruby_nn11"></A>27.3 The Ruby-to-C/C++ Mapping</H2> | |
30902 | <P> This section describes the basics of how SWIG maps C or C++ | |
30903 | declarations in your SWIG interface files to Ruby constructs.</P> | |
30904 | <H3><A name="Ruby_nn12"></A>27.3.1 Modules</H3> | |
30905 | <P> The SWIG <TT>%module</TT> directive specifies the name of the Ruby | |
30906 | module. If you specify:</P> | |
30907 | <DIV class="code"> | |
30908 | <PRE>%module example</PRE> | |
30909 | </DIV> | |
30910 | <P> then everything is wrapped into a Ruby module named <TT>Example</TT> | |
30911 | that is nested directly under the global module. You can specify a more | |
30912 | deeply nested module by specifying the fully-qualified module name in | |
30913 | quotes, e.g.</P> | |
30914 | <DIV class="code"> | |
30915 | <PRE>%module "foo::bar::spam"</PRE> | |
30916 | </DIV> | |
30917 | <P> An alternate method of specifying a nested module name is to use the | |
30918 | <!--span style="font-family: monospace;"--> | |
30919 | -prefix option on the SWIG command line. The prefix that you specify | |
30920 | with this option will be prepended to the module name specified with | |
30921 | the | |
30922 | <!--span style="font-family: monospace;"--> | |
30923 | %module directive in your SWIG interface file. So for example, this | |
30924 | declaration at the top of your SWIG interface file: | |
30925 | <BR></P> | |
30926 | <DIV class="code"> | |
30927 | <PRE>%module "foo::bar::spam"</PRE> | |
30928 | </DIV> | |
30929 | <P> will result in a nested module name of | |
30930 | <!--span style="font-family: monospace;"--> | |
30931 | Foo::Bar::Spam, but you can achieve the | |
30932 | <!--span style="font-style: italic;"--> | |
30933 | same effect by specifying: | |
30934 | <BR></P> | |
30935 | <DIV class="code"> | |
30936 | <PRE>%module spam</PRE> | |
30937 | </DIV> | |
30938 | <P> and then running SWIG with the | |
30939 | <!--span style="font-family: monospace;"--> | |
30940 | -prefix command line option: | |
30941 | <BR></P> | |
30942 | <DIV class="code"> | |
30943 | <PRE>$ <B>swig -ruby -prefix "foo::bar::" example.i</B></PRE> | |
30944 | </DIV> | |
30945 | <P> Starting with SWIG 1.3.20, you can also choose to wrap everything | |
30946 | into the global module by specifying the <TT>-globalmodule</TT> option | |
30947 | on the SWIG command line, i.e.</P> | |
30948 | <DIV class="code"> | |
30949 | <PRE>$ <B>swig -ruby -globalmodule example.i</B></PRE> | |
30950 | </DIV> | |
30951 | <P> Note that this does not relieve you of the requirement of specifying | |
30952 | the SWIG module name with the <TT>%module</TT> directive (or the <TT> | |
30953 | -module</TT> command-line option) as described earlier.</P> | |
30954 | <P>When choosing a module name, do not use the same name as a built-in | |
30955 | Ruby command or standard module name, as the results may be | |
30956 | unpredictable. Similarly, if you're using the <TT>-globalmodule</TT> | |
30957 | option to wrap everything into the global module, take care that the | |
30958 | names of your constants, classes and methods don't conflict with any of | |
30959 | Ruby's built-in names.</P> | |
30960 | <H3><A name="Ruby_nn13"></A>27.3.2 Functions</H3> | |
30961 | <P> Global functions are wrapped as Ruby module methods. For example, | |
30962 | given the SWIG interface file <TT>example.i</TT>:</P> | |
30963 | <DIV class="code"> | |
30964 | <PRE>%module example | |
30965 | <BR> | |
30966 | <BR>int fact(int n); | |
30967 | <BR></PRE> | |
30968 | </DIV> | |
30969 | <P> and C source file <TT>example.c</TT>:</P> | |
30970 | <DIV class="code"> | |
30971 | <PRE>int fact(int n) { | |
30972 | <BR> if (n == 0) | |
30973 | <BR> return 1; | |
30974 | <BR> return (n * fact(n-1)); | |
30975 | <BR>} | |
30976 | <BR></PRE> | |
30977 | </DIV> | |
30978 | <P> SWIG will generate a method<I> fact</I> in the<I> Example</I> module | |
30979 | that can be used like so:</P> | |
30980 | <DIV class="code"> | |
30981 | <PRE>$ <B>irb</B> | |
30982 | <BR>irb(main):001:0> <B>require 'example'</B> | |
30983 | <BR>true | |
30984 | <BR>irb(main):002:0> <B>Example.fact(4)</B> | |
30985 | <BR>24 | |
30986 | <BR></PRE> | |
30987 | </DIV> | |
30988 | <H3><A name="Ruby_nn14"></A>27.3.3 Variable Linking</H3> | |
30989 | <P> C/C++ global variables are wrapped as a pair of singleton methods | |
30990 | for the module: one to get the value of the global variable and one to | |
30991 | set it. For example, the following SWIG interface file declares two | |
30992 | global variables:</P> | |
30993 | <DIV class="code"> | |
30994 | <PRE>// SWIG interface file with global variables | |
30995 | <BR>%module example | |
30996 | <BR>... | |
30997 | <BR>%inline %{ | |
30998 | <BR>extern int variable1; | |
30999 | <BR>extern double Variable2; | |
31000 | <BR>%} | |
31001 | <BR>... | |
31002 | <BR></PRE> | |
31003 | </DIV> | |
31004 | <P> Now look at the Ruby interface:</P> | |
31005 | <DIV class="code"> | |
31006 | <PRE>$ <B>irb</B> | |
31007 | <BR>irb(main):001:0> <B>require 'Example'</B> | |
31008 | <BR>true | |
31009 | <BR>irb(main):002:0> <B>Example.variable1 = 2</B> | |
31010 | <BR>2 | |
31011 | <BR>irb(main):003:0> <B>Example.Variable2 = 4 * 10.3</B> | |
31012 | <BR>41.2 | |
31013 | <BR>irb(main):004:0> <B>Example.Variable2</B> | |
31014 | <BR>41.2 | |
31015 | <BR></PRE> | |
31016 | </DIV> | |
31017 | <P> If you make an error in variable assignment, you will receive an | |
31018 | error message. For example:</P> | |
31019 | <DIV class="code"> | |
31020 | <PRE>irb(main):005:0> <B>Example.Variable2 = "hello"</B> | |
31021 | <BR>TypeError: no implicit conversion to float from string | |
31022 | <BR>from (irb):5:in `Variable2=' | |
31023 | <BR>from (irb):5 | |
31024 | <BR></PRE> | |
31025 | </DIV> | |
31026 | <P> If a variable is declared as <TT>const</TT>, it is wrapped as a | |
31027 | read-only variable. Attempts to modify its value will result in an | |
31028 | error.</P> | |
31029 | <P>To make ordinary variables read-only, you can also use the <TT> | |
31030 | %immutable</TT> directive. For example:</P> | |
31031 | <DIV class="code"> | |
31032 | <PRE>%immutable; | |
31033 | <BR>%inline %{ | |
31034 | <BR>extern char *path; | |
31035 | <BR>%} | |
31036 | <BR>%mutable; | |
31037 | <BR></PRE> | |
31038 | </DIV> | |
31039 | <P> The <TT>%immutable</TT> directive stays in effect until it is | |
31040 | explicitly disabled using <TT>%mutable</TT>.</P> | |
31041 | <H3><A name="Ruby_nn15"></A>27.3.4 Constants</H3> | |
31042 | <P> C/C++ constants are wrapped as module constants initialized to the | |
31043 | appropriate value. To create a constant, use <TT>#define</TT> or the <TT> | |
31044 | %constant</TT> directive. For example:</P> | |
31045 | <DIV class="code"> | |
31046 | <PRE>#define PI 3.14159 | |
31047 | <BR>#define VERSION "1.0" | |
31048 | <BR> | |
31049 | <BR>%constant int FOO = 42; | |
31050 | <BR>%constant const char *path = "/usr/local"; | |
31051 | <BR> | |
31052 | <BR>const int BAR = 32; | |
31053 | <BR></PRE> | |
31054 | </DIV> | |
31055 | <P> Remember to use the :: operator in Ruby to get at these constant | |
31056 | values, e.g.</P> | |
31057 | <DIV class="code"> | |
31058 | <PRE>$ <B>irb</B> | |
31059 | <BR>irb(main):001:0> <B>require 'Example'</B> | |
31060 | <BR>true | |
31061 | <BR>irb(main):002:0> <B>Example::PI</B> | |
31062 | <BR>3.14159 | |
31063 | <BR></PRE> | |
31064 | </DIV> | |
31065 | <H3><A name="Ruby_nn16"></A>27.3.5 Pointers</H3> | |
31066 | <P> "Opaque" pointers to arbitrary C/C++ types (i.e. types that aren't | |
31067 | explicitly declared in your SWIG interface file) are wrapped as data | |
31068 | objects. So, for example, consider a SWIG interface file containing | |
31069 | only the declarations:</P> | |
31070 | <DIV class="code"> | |
31071 | <PRE>Foo *get_foo(); | |
31072 | <BR>void set_foo(Foo *foo); | |
31073 | <BR></PRE> | |
31074 | </DIV> | |
31075 | <P> For this case, the<I> get_foo()</I> method returns an instance of an | |
31076 | internally generated Ruby class:</P> | |
31077 | <DIV class="code"> | |
31078 | <PRE>irb(main):001:0> <B>foo = Example::get_foo()</B> | |
31079 | <BR>#<SWIG::TYPE_p_Foo:0x402b1654> | |
31080 | <BR></PRE> | |
31081 | </DIV> | |
31082 | <P> A <TT>NULL</TT> pointer is always represented by the Ruby <TT>nil</TT> | |
31083 | object.</P> | |
31084 | <H3><A name="Ruby_nn17"></A>27.3.6 Structures</H3> | |
31085 | <P> C/C++ structs are wrapped as Ruby classes, with accessor methods | |
31086 | (i.e. "getters" and "setters") for all of the struct members. For | |
31087 | example, this struct declaration:</P> | |
31088 | <DIV class="code"> | |
31089 | <PRE>struct Vector { | |
31090 | <BR> double x, y; | |
31091 | <BR>}; | |
31092 | <BR></PRE> | |
31093 | </DIV> | |
31094 | <P> gets wrapped as a <TT>Vector</TT> class, with Ruby instance methods <TT> | |
31095 | x</TT>, <TT> x=</TT>, <TT>y</TT> and <TT>y=</TT>. These methods can be | |
31096 | used to access structure data from Ruby as follows:</P> | |
31097 | <DIV class="code"> | |
31098 | <PRE>$ <B>irb</B> | |
31099 | <BR>irb(main):001:0> <B>require 'Example'</B> | |
31100 | <BR>true | |
31101 | <BR>irb(main):002:0> <B>f = Example::Vector.new</B> | |
31102 | <BR>#<Example::Vector:0x4020b268> | |
31103 | <BR>irb(main):003:0> <B>f.x = 10</B> | |
31104 | <BR>nil | |
31105 | <BR>irb(main):004:0> <B>f.x</B> | |
31106 | <BR>10.0 | |
31107 | <BR></PRE> | |
31108 | </DIV> | |
31109 | <P> Similar access is provided for unions and the public data members of | |
31110 | C++ classes.</P> | |
31111 | <P><TT>const</TT> members of a structure are read-only. Data members can | |
31112 | also be forced to be read-only using the <TT>%immutable</TT> directive | |
31113 | (in C++, <TT>private</TT> may also be used). For example:</P> | |
31114 | <DIV class="code"> | |
31115 | <PRE>struct Foo { | |
31116 | <BR> ... | |
31117 | <BR> %immutable; | |
31118 | <BR> int x; /* Read-only members */ | |
31119 | <BR> char *name; | |
31120 | <BR> %mutable; | |
31121 | <BR> ... | |
31122 | <BR>}; | |
31123 | <BR></PRE> | |
31124 | </DIV> | |
31125 | <P> When <TT>char *</TT> members of a structure are wrapped, the | |
31126 | contents are assumed to be dynamically allocated using <TT>malloc</TT> | |
31127 | or <TT>new</TT> (depending on whether or not SWIG is run with the <TT> | |
31128 | -c++</TT> option). When the structure member is set, the old contents | |
31129 | will be released and a new value created. If this is not the behavior | |
31130 | you want, you will have to use a typemap (described shortly).</P> | |
31131 | <P>Array members are normally wrapped as read-only. For example, this | |
31132 | code:</P> | |
31133 | <DIV class="code"> | |
31134 | <PRE>struct Foo { | |
31135 | <BR> int x[50]; | |
31136 | <BR>}; | |
31137 | <BR></PRE> | |
31138 | </DIV> | |
31139 | <P> produces a single accessor function like this:</P> | |
31140 | <DIV class="code"> | |
31141 | <PRE>int *Foo_x_get(Foo *self) { | |
31142 | <BR> return self->x; | |
31143 | <BR>}; | |
31144 | <BR></PRE> | |
31145 | </DIV> | |
31146 | <P> If you want to set an array member, you will need to supply a | |
31147 | "memberin" typemap described in the <A href="#ruby_cpp_smart_pointers"> | |
31148 | section on typemaps</A>. As a special case, SWIG does generate code to | |
31149 | set array members of type <TT>char</TT> (allowing you to store a Ruby | |
31150 | string in the structure).</P> | |
31151 | <P>When structure members are wrapped, they are handled as pointers. For | |
31152 | example,</P> | |
31153 | <DIV class="code"> | |
31154 | <PRE>struct Foo { | |
31155 | <BR> ... | |
31156 | <BR>}; | |
31157 | <BR> | |
31158 | <BR>struct Bar { | |
31159 | <BR> Foo f; | |
31160 | <BR>}; | |
31161 | <BR></PRE> | |
31162 | </DIV> | |
31163 | <P> generates accessor functions such as this:</P> | |
31164 | <DIV class="code"> | |
31165 | <PRE>Foo *Bar_f_get(Bar *b) { | |
31166 | <BR> return &b->f; | |
31167 | <BR>} | |
31168 | <BR> | |
31169 | <BR>void Bar_f_set(Bar *b, Foo *val) { | |
31170 | <BR> b->f = *val; | |
31171 | <BR>} | |
31172 | <BR></PRE> | |
31173 | </DIV> | |
31174 | <H3><A name="Ruby_nn18"></A>27.3.7 C++ classes</H3> | |
31175 | <P> Like structs, C++ classes are wrapped by creating a new Ruby class | |
31176 | of the same name with accessor methods for the public class member | |
31177 | data. Additionally, public member functions for the class are wrapped | |
31178 | as Ruby instance methods, and public static member functions are | |
31179 | wrapped as Ruby singleton methods. So, given the C++ class declaration:</P> | |
31180 | <DIV class="code"> | |
31181 | <PRE>class List { | |
31182 | <BR>public: | |
31183 | <BR> List(); | |
31184 | <BR> ~List(); | |
31185 | <BR> int search(char *item); | |
31186 | <BR> void insert(char *item); | |
31187 | <BR> void remove(char *item); | |
31188 | <BR> char *get(int n); | |
31189 | <BR> int length; | |
31190 | <BR> static void print(List *l); | |
31191 | <BR>}; | |
31192 | <BR></PRE> | |
31193 | </DIV> | |
31194 | <P> SWIG would create a <TT>List</TT> class with:</P> | |
31195 | <UL> | |
31196 | <LI> instance methods<I> search</I>,<I> insert</I>,<I> remove</I>, and<I> | |
31197 | get</I>;</LI> | |
31198 | <LI> instance methods<I> length</I> and<I> length=</I> (to get and set | |
31199 | the value of the<I> length</I> data member); and,</LI> | |
31200 | <LI> a<I> print</I> singleton method for the class.</LI> | |
31201 | </UL> | |
31202 | <P> In Ruby, these functions are used as follows:</P> | |
31203 | <DIV class="code"> | |
31204 | <PRE>require 'Example' | |
31205 | <BR> | |
31206 | <BR>l = Example::List.new | |
31207 | <BR> | |
31208 | <BR>l.insert("Ale") | |
31209 | <BR>l.insert("Stout") | |
31210 | <BR>l.insert("Lager") | |
31211 | <BR>Example.print(l) | |
31212 | <BR>l.length() | |
31213 | <BR>----- produces the following output | |
31214 | <BR>Lager | |
31215 | <BR>Stout | |
31216 | <BR>Ale | |
31217 | <BR>3 | |
31218 | <BR></PRE> | |
31219 | </DIV> | |
31220 | <H3><A name="Ruby_nn19"></A>27.3.8 C++ Inheritance</H3> | |
31221 | <P> The SWIG type-checker is fully aware of C++ inheritance. Therefore, | |
31222 | if you have classes like this:</P> | |
31223 | <DIV class="code"> | |
31224 | <PRE>class Parent { | |
31225 | <BR> ... | |
31226 | <BR>}; | |
31227 | <BR> | |
31228 | <BR>class Child : public Parent { | |
31229 | <BR> ... | |
31230 | <BR>}; | |
31231 | <BR></PRE> | |
31232 | </DIV> | |
31233 | <P> those classes are wrapped into a hierarchy of Ruby classes that | |
31234 | reflect the same inheritance structure. All of the usual Ruby utility | |
31235 | methods work normally:</P> | |
31236 | <DIV class="code"> | |
31237 | <PRE>irb(main):001:0> <B>c = Child.new</B> | |
31238 | <BR>#<Bar:0x4016efd4> | |
31239 | <BR>irb(main):002:0> <B>c.instance_of? Child</B> | |
31240 | <BR>true | |
31241 | <BR>irb(main):003:0> <B>b.instance_of? Parent</B> | |
31242 | <BR>false | |
31243 | <BR>irb(main):004:0> <B>b.is_a? Child</B> | |
31244 | <BR>true | |
31245 | <BR>irb(main):005:0> <B>b.is_a? Parent</B> | |
31246 | <BR>true | |
31247 | <BR>irb(main):006:0> <B>Child < Parent</B> | |
31248 | <BR>true | |
31249 | <BR>irb(main):007:0> <B>Child > Parent</B> | |
31250 | <BR>false | |
31251 | <BR></PRE> | |
31252 | </DIV> | |
31253 | <P> Furthermore, if you have a function like this:</P> | |
31254 | <DIV class="code"> | |
31255 | <PRE>void spam(Parent *f); | |
31256 | <BR></PRE> | |
31257 | </DIV> | |
31258 | <P> then the function <TT>spam()</TT> accepts <TT>Parent</TT>* or a | |
31259 | pointer to any class derived from <TT>Parent</TT>.</P> | |
31260 | <P>Until recently, the Ruby module for SWIG didn't support multiple | |
31261 | inheritance, and this is still the default behavior. This doesn't mean | |
31262 | that you can't wrap C++ classes which inherit from multiple base | |
31263 | classes; it simply means that only the<B> first</B> base class listed | |
31264 | in the class declaration is considered, and any additional base classes | |
31265 | are ignored. As an example, consider a SWIG interface file with a | |
31266 | declaration like this:</P> | |
31267 | <DIV class="code"> | |
31268 | <PRE>class Derived : public Base1, public Base2 | |
31269 | <BR>{ | |
31270 | <BR> ... | |
31271 | <BR>}; | |
31272 | <BR></PRE> | |
31273 | </DIV> | |
31274 | <P> For this case, the resulting Ruby class (<TT>Derived</TT>) will only | |
31275 | consider <TT>Base1</TT> as its superclass. It won't inherit any of <TT> | |
31276 | Base2</TT>'s member functions or data and it won't recognize <TT>Base2</TT> | |
31277 | as an "ancestor" of <TT>Derived</TT> (i.e. the<EM> is_a?</EM> | |
31278 | relationship would fail). When SWIG processes this interface file, | |
31279 | you'll see a warning message like:</P> | |
31280 | <DIV class="code"> | |
31281 | <PRE>example.i:5: Warning(802): Warning for Derived: Base Base2 ignored. | |
31282 | <BR>Multiple inheritance is not supported in Ruby. | |
31283 | <BR></PRE> | |
31284 | </DIV> | |
31285 | <P> Starting with SWIG 1.3.20, the Ruby module for SWIG provides limited | |
31286 | support for multiple inheritance. Because the approach for dealing with | |
31287 | multiple inheritance introduces some limitations, this is an optional | |
31288 | feature that you can activate with the <TT>-minherit</TT> command-line | |
31289 | option:</P> | |
31290 | <DIV class="code"> | |
31291 | <PRE>$ <B>swig -c++ -ruby -minherit example.i</B></PRE> | |
31292 | </DIV> | |
31293 | <P> Using our previous example, if your SWIG interface file contains a | |
31294 | declaration like this:</P> | |
31295 | <DIV class="code"> | |
31296 | <PRE>class Derived : public Base1, public Base2 | |
31297 | <BR>{ | |
31298 | <BR> ... | |
31299 | <BR>}; | |
31300 | <BR></PRE> | |
31301 | </DIV> | |
31302 | <P> and you run SWIG with the <TT>-minherit</TT> command-line option, | |
31303 | then you will end up with a Ruby class <TT>Derived</TT> that appears to | |
31304 | "inherit" the member data and functions from both <TT>Base1</TT> and <TT> | |
31305 | Base2</TT>. What actually happens is that three different top-level | |
31306 | classes are created, with Ruby's <TT>Object</TT> class as their | |
31307 | superclass. Each of these classes defines a nested module named <TT> | |
31308 | Impl</TT>, and it's in these nested <TT>Impl</TT> modules that the | |
31309 | actual instance methods for the classes are defined, i.e.</P> | |
31310 | <DIV class="code"> | |
31311 | <PRE>class Base1 | |
31312 | <BR> module Impl | |
31313 | <BR> # Define Base1 methods here | |
31314 | <BR> end | |
31315 | <BR> include Impl | |
31316 | <BR>end | |
31317 | <BR> | |
31318 | <BR>class Base2 | |
31319 | <BR> module Impl | |
31320 | <BR> # Define Base2 methods here | |
31321 | <BR> end | |
31322 | <BR> include Impl | |
31323 | <BR>end | |
31324 | <BR> | |
31325 | <BR>class Derived | |
31326 | <BR> module Impl | |
31327 | <BR> include Base1::Impl | |
31328 | <BR> include Base2::Impl | |
31329 | <BR> # Define Derived methods here | |
31330 | <BR> end | |
31331 | <BR> include Impl | |
31332 | <BR>end | |
31333 | <BR></PRE> | |
31334 | </DIV> | |
31335 | <P> Observe that after the nested <TT>Impl</TT> module for a class is | |
31336 | defined, it is mixed-in to the class itself. Also observe that the <TT> | |
31337 | Derived::Impl</TT> module first mixes-in its base classes' <TT>Impl</TT> | |
31338 | modules, thus "inheriting" all of their behavior.</P> | |
31339 | <P>The primary drawback is that, unlike the default mode of operation, | |
31340 | neither <TT>Base1</TT> nor <TT>Base2</TT> is a true superclass of <TT> | |
31341 | Derived</TT> anymore:</P> | |
31342 | <DIV class="code"> | |
31343 | <PRE>obj = Derived.new | |
31344 | <BR>obj.is_a? Base1 # this will return false... | |
31345 | <BR>obj.is_a? Base2 # ... and so will this | |
31346 | <BR></PRE> | |
31347 | </DIV> | |
31348 | <P> In most cases, this is not a serious problem since objects of type <TT> | |
31349 | Derived</TT> will otherwise behave as though they inherit from both <TT> | |
31350 | Base1</TT> and <TT>Base2</TT> (i.e. they exhibit <A href="http://c2.com/cgi/wiki?DuckTyping"> | |
31351 | "Duck Typing"</A>).</P> | |
31352 | <H3><A name="Ruby_nn20"></A>27.3.9 C++ Overloaded Functions</H3> | |
31353 | <P> C++ overloaded functions, methods, and constructors are mostly | |
31354 | supported by SWIG. For example, if you have two functions like this:</P> | |
31355 | <DIV class="code"> | |
31356 | <PRE>void foo(int); | |
31357 | <BR>void foo(char *c); | |
31358 | <BR></PRE> | |
31359 | </DIV> | |
31360 | <P> You can use them in Ruby in a straightforward manner:</P> | |
31361 | <DIV class="code"> | |
31362 | <PRE>irb(main):001:0> <B>foo(3)</B> # foo(int) | |
31363 | <BR>irb(main):002:0> <B>foo("Hello")</B> # foo(char *c) | |
31364 | <BR></PRE> | |
31365 | </DIV> | |
31366 | <P>Similarly, if you have a class like this,</P> | |
31367 | <DIV class="code"> | |
31368 | <PRE>class Foo { | |
31369 | <BR>public: | |
31370 | <BR> Foo(); | |
31371 | <BR> Foo(const Foo &); | |
31372 | <BR> ... | |
31373 | <BR>}; | |
31374 | <BR></PRE> | |
31375 | </DIV> | |
31376 | <P>you can write Ruby code like this:</P> | |
31377 | <DIV class="code"> | |
31378 | <PRE>irb(main):001:0> <B>f = Foo.new</B> # Create a Foo | |
31379 | <BR>irb(main):002:0> <B>g = Foo.new(f)</B> # Copy f | |
31380 | <BR></PRE> | |
31381 | </DIV> | |
31382 | <P> Overloading support is not quite as flexible as in C++. Sometimes | |
31383 | there are methods that SWIG can't disambiguate. For example:</P> | |
31384 | <DIV class="code"> | |
31385 | <PRE>void spam(int); | |
31386 | <BR>void spam(short); | |
31387 | <BR></PRE> | |
31388 | </DIV> | |
31389 | <P>or</P> | |
31390 | <DIV class="code"> | |
31391 | <PRE>void foo(Bar *b); | |
31392 | <BR>void foo(Bar &b); | |
31393 | <BR></PRE> | |
31394 | </DIV> | |
31395 | <P> If declarations such as these appear, you will get a warning message | |
31396 | like this:</P> | |
31397 | <DIV class="code"> | |
31398 | <PRE>example.i:12: Warning(509): Overloaded spam(short) is shadowed by spam(int) | |
31399 | <BR>at example.i:11. | |
31400 | <BR> </PRE> | |
31401 | </DIV> | |
31402 | <P> To fix this, you either need to ignore or rename one of the methods. | |
31403 | For example:</P> | |
31404 | <DIV class="code"> | |
31405 | <PRE>%rename(spam_short) spam(short); | |
31406 | <BR>... | |
31407 | <BR>void spam(int); | |
31408 | <BR>void spam(short); // Accessed as spam_short | |
31409 | <BR></PRE> | |
31410 | </DIV> | |
31411 | <P>or</P> | |
31412 | <DIV class="code"> | |
31413 | <PRE>%ignore spam(short); | |
31414 | <BR>... | |
31415 | <BR>void spam(int); | |
31416 | <BR>void spam(short); // Ignored | |
31417 | <BR></PRE> | |
31418 | </DIV> | |
31419 | <P> SWIG resolves overloaded functions and methods using a | |
31420 | disambiguation scheme that ranks and sorts declarations according to a | |
31421 | set of type-precedence rules. The order in which declarations appear in | |
31422 | the input does not matter except in situations where ambiguity | |
31423 | arises--in this case, the first declaration takes precedence.</P> | |
31424 | <P>Please refer to the <A href="#SWIGPlus">"SWIG and C++"</A> chapter | |
31425 | for more information about overloading. <A name="n21"></A></P> | |
31426 | <H3><A name="Ruby_nn21"></A>27.3.10 C++ Operators</H3> | |
31427 | <P> For the most part, overloaded operators are handled automatically by | |
31428 | SWIG and do not require any special treatment on your part. So if your | |
31429 | class declares an overloaded addition operator, e.g.</P> | |
31430 | <DIV class="code"> | |
31431 | <PRE>class Complex { | |
31432 | <BR> ... | |
31433 | <BR> Complex operator+(Complex &); | |
31434 | <BR> ... | |
31435 | <BR>}; | |
31436 | <BR></PRE> | |
31437 | </DIV> | |
31438 | <P> the resulting Ruby class will also support the addition (+) method | |
31439 | correctly.</P> | |
31440 | <P>For cases where SWIG's built-in support is not sufficient, C++ | |
31441 | operators can be wrapped using the <TT>%rename</TT> directive | |
31442 | (available on SWIG 1.3.10 and later releases). All you need to do is | |
31443 | give the operator the name of a valid Ruby identifier. For example:</P> | |
31444 | <DIV class="code"> | |
31445 | <PRE>%rename(add_complex) operator+(Complex &, Complex &); | |
31446 | <BR>... | |
31447 | <BR>Complex operator+(Complex &, Complex &); | |
31448 | <BR></PRE> | |
31449 | </DIV> | |
31450 | <P>Now, in Ruby, you can do this:</P> | |
31451 | <DIV class="code"> | |
31452 | <PRE>a = Example::Complex.new(2, 3) | |
31453 | <BR>b = Example::Complex.new(4, -1) | |
31454 | <BR>c = Example.add_complex(a, b) | |
31455 | <BR></PRE> | |
31456 | </DIV> | |
31457 | <P> More details about wrapping C++ operators into Ruby operators is | |
31458 | discussed in the <A href="#ruby_operator_overloading">section on | |
31459 | operator overloading</A>.</P> | |
31460 | <H3><A name="Ruby_nn22"></A>27.3.11 C++ namespaces</H3> | |
31461 | <P> SWIG is aware of C++ namespaces, but namespace names do not appear | |
31462 | in the module nor do namespaces result in a module that is broken up | |
31463 | into submodules or packages. For example, if you have a file like this,</P> | |
31464 | <DIV class="code"> | |
31465 | <PRE>%module example | |
31466 | <BR> | |
31467 | <BR>namespace foo { | |
31468 | <BR> int fact(int n); | |
31469 | <BR> struct Vector { | |
31470 | <BR> double x,y,z; | |
31471 | <BR> }; | |
31472 | <BR>}; | |
31473 | <BR></PRE> | |
31474 | </DIV> | |
31475 | <P>it works in Ruby as follows:</P> | |
31476 | <DIV class="code"> | |
31477 | <PRE>irb(main):001:0> <B>require 'example'</B> | |
31478 | <BR>true | |
31479 | <BR>irb(main):002:0> <B>Example.fact(3)</B> | |
31480 | <BR>6 | |
31481 | <BR>irb(main):003:0> <B>v = Example::Vector.new</B> | |
31482 | <BR>#<Example::Vector:0x4016f4d4> | |
31483 | <BR>irb(main):004:0> <B>v.x = 3.4</B> | |
31484 | <BR>3.4 | |
31485 | <BR>irb(main):004:0> <B>v.y</B> | |
31486 | <BR>0.0 | |
31487 | <BR></PRE> | |
31488 | </DIV> | |
31489 | <P> If your program has more than one namespace, name conflicts (if any) | |
31490 | can be resolved using <TT>%rename</TT> For example:</P> | |
31491 | <DIV class="code"> | |
31492 | <PRE>%rename(Bar_spam) Bar::spam; | |
31493 | <BR> | |
31494 | <BR>namespace Foo { | |
31495 | <BR> int spam(); | |
31496 | <BR>} | |
31497 | <BR> | |
31498 | <BR>namespace Bar { | |
31499 | <BR> int spam(); | |
31500 | <BR>} | |
31501 | <BR></PRE> | |
31502 | </DIV> | |
31503 | <P> If you have more than one namespace and your want to keep their | |
31504 | symbols separate, consider wrapping them as separate SWIG modules. For | |
31505 | example, make the module name the same as the namespace and create | |
31506 | extension modules for each namespace separately. If your program | |
31507 | utilizes thousands of small deeply nested namespaces each with | |
31508 | identical symbol names, well, then you get what you deserve.</P> | |
31509 | <H3><A name="Ruby_nn23"></A>27.3.12 C++ templates</H3> | |
31510 | <P> C++ templates don't present a huge problem for SWIG. However, in | |
31511 | order to create wrappers, you have to tell SWIG to create wrappers for | |
31512 | a particular template instantiation. To do this, you use the <TT> | |
31513 | %template</TT> directive. For example:</P> | |
31514 | <DIV class="code"> | |
31515 | <PRE>%module example | |
31516 | <BR> | |
31517 | <BR>%{ | |
31518 | <BR>#include "pair.h" | |
31519 | <BR>%} | |
31520 | <BR> | |
31521 | <BR>template<class T1, class T2> | |
31522 | <BR>struct pair { | |
31523 | <BR> typedef T1 first_type; | |
31524 | <BR> typedef T2 second_type; | |
31525 | <BR> T1 first; | |
31526 | <BR> T2 second; | |
31527 | <BR> pair(); | |
31528 | <BR> pair(const T1&, const T2&); | |
31529 | <BR> ~pair(); | |
31530 | <BR>}; | |
31531 | <BR> | |
31532 | <BR>%template(Pairii) pair<int,int>; | |
31533 | <BR></PRE> | |
31534 | </DIV> | |
31535 | <P>In Ruby:</P> | |
31536 | <DIV class="code"> | |
31537 | <PRE>irb(main):001:0> <B>require 'example'</B> | |
31538 | <BR>true | |
31539 | <BR>irb(main):002:0> <B>p = Example::Pairii.new(3, 4)</B> | |
31540 | <BR>#<Example:Pairii:0x4016f4df> | |
31541 | <BR>irb(main):003:0> <B>p.first</B> | |
31542 | <BR>3 | |
31543 | <BR>irb(main):004:0> <B>p.second</B> | |
31544 | <BR>4 | |
31545 | <BR></PRE> | |
31546 | </DIV> | |
31547 | <P> On a related note, the standard SWIG library contains a number of | |
31548 | modules that provide typemaps for standard C++ library classes (such as | |
31549 | <TT>std::pair</TT>, <TT>std::string</TT> and <TT>std::vector</TT>). | |
31550 | These library modules don't provide wrappers around the templates | |
31551 | themselves, but they do make it convenient for users of your extension | |
31552 | module to pass Ruby objects (such as arrays and strings) to wrapped C++ | |
31553 | code that expects instances of standard C++ templates. For example, | |
31554 | suppose the C++ library you're wrapping has a function that expects a | |
31555 | vector of floats:</P> | |
31556 | <DIV class="code"> | |
31557 | <PRE>%module example | |
31558 | <BR> | |
31559 | <BR>float sum(const std::vector<float>& values); | |
31560 | <BR></PRE> | |
31561 | </DIV> | |
31562 | <P> Rather than go through the hassle of writing an "in" typemap to | |
31563 | convert an array of Ruby numbers into a std::vector<float>, you can | |
31564 | just use the <TT>std_vector.i</TT> module from the standard SWIG | |
31565 | library:</P> | |
31566 | <DIV class="code"> | |
31567 | <PRE>%module example | |
31568 | <BR> | |
31569 | <BR><B>%include std_vector.i</B> | |
31570 | <BR>float sum(const std::vector<float>& values); | |
31571 | <BR></PRE> | |
31572 | </DIV> | |
31573 | <P> Obviously, there is a lot more to template wrapping than shown in | |
31574 | these examples. More details can be found in the <A href="#SWIGPlus"> | |
31575 | SWIG and C++</A> chapter.</P> | |
31576 | <H3><A name="ruby_cpp_smart_pointers"></A>27.3.13 C++ Smart Pointers</H3> | |
31577 | <P> In certain C++ programs, it is common to use classes that have been | |
31578 | wrapped by so-called "smart pointers." Generally, this involves the use | |
31579 | of a template class that implements <TT>operator->()</TT> like this:</P> | |
31580 | <DIV class="code"> | |
31581 | <PRE>template<class T> class SmartPtr { | |
31582 | <BR> ... | |
31583 | <BR> T *operator->(); | |
31584 | <BR> ... | |
31585 | <BR>} | |
31586 | <BR></PRE> | |
31587 | </DIV> | |
31588 | <P>Then, if you have a class like this,</P> | |
31589 | <DIV class="code"> | |
31590 | <PRE>class Foo { | |
31591 | <BR>public: | |
31592 | <BR> int x; | |
31593 | <BR> int bar(); | |
31594 | <BR>}; | |
31595 | <BR></PRE> | |
31596 | </DIV> | |
31597 | <P>A smart pointer would be used in C++ as follows:</P> | |
31598 | <DIV class="code"> | |
31599 | <PRE>SmartPtr<Foo> p = CreateFoo(); // Created somehow (not shown) | |
31600 | <BR>... | |
31601 | <BR>p->x = 3; // Foo::x | |
31602 | <BR>int y = p->bar(); // Foo::bar | |
31603 | <BR></PRE> | |
31604 | </DIV> | |
31605 | <P> To wrap this in Ruby, simply tell SWIG about the <TT>SmartPtr</TT> | |
31606 | class and the low-level <TT>Foo</TT> object. Make sure you instantiate <TT> | |
31607 | SmartPtr</TT> using <TT>%template</TT> if necessary. For example:</P> | |
31608 | <DIV class="code"> | |
31609 | <PRE>%module example | |
31610 | <BR>... | |
31611 | <BR>%template(SmartPtrFoo) SmartPtr<Foo>; | |
31612 | <BR>... | |
31613 | <BR></PRE> | |
31614 | </DIV> | |
31615 | <P>Now, in Ruby, everything should just "work":</P> | |
31616 | <DIV class="code"> | |
31617 | <PRE>irb(main):001:0> <B>p = Example::CreateFoo()</B> # Create a smart-pointer somehow | |
31618 | <BR>#<Example::SmartPtrFoo:0x4016f4df> | |
31619 | <BR>irb(main):002:0> <B>p.x = 3</B> # Foo::x | |
31620 | <BR>3 | |
31621 | <BR>irb(main):003:0> <B>p.bar()</B> # Foo::bar | |
31622 | <BR></PRE> | |
31623 | </DIV> | |
31624 | <P> If you ever need to access the underlying pointer returned by <TT> | |
31625 | operator->()</TT> itself, simply use the <TT>__deref__()</TT> method. | |
31626 | For example:</P> | |
31627 | <DIV class="code"> | |
31628 | <PRE>irb(main):004:0> <B>f = p.__deref__()</B> # Returns underlying Foo * | |
31629 | <BR></PRE> | |
31630 | </DIV> | |
31631 | <H3><A name="Ruby_nn25"></A>27.3.14 Cross-Language Polymorphism</H3> | |
31632 | <P> SWIG's Ruby module supports cross-language polymorphism (a.k.a. the | |
31633 | "directors" feature) similar to that for SWIG's Python module. Rather | |
31634 | than duplicate the information presented in the <A href="#Python"> | |
31635 | Python</A> chapter, this section just notes the differences that you | |
31636 | need to be aware of when using this feature with Ruby.</P> | |
31637 | <H4><A name="Ruby_nn26"></A>27.3.14.1 Exception Unrolling</H4> | |
31638 | <P> Whenever a C++ director class routes one of its virtual member | |
31639 | function calls to a Ruby instance method, there's always the | |
31640 | possibility that an exception will be raised in the Ruby code. By | |
31641 | default, those exceptions are ignored, which simply means that the | |
31642 | exception will be exposed to the Ruby interpreter. If you would like to | |
31643 | change this behavior, you can use the <TT>%feature("director:except")</TT> | |
31644 | directive to indicate what action should be taken when a Ruby exception | |
31645 | is raised. The following code should suffice in most cases:</P> | |
31646 | <DIV class="code"> | |
31647 | <PRE>%feature("director:except") { | |
31648 | <BR> throw Swig::DirectorMethodException($error); | |
31649 | <BR>} | |
31650 | <BR></PRE> | |
31651 | </DIV> | |
31652 | <P> When this feature is activated, the call to the Ruby instance method | |
31653 | is "wrapped" using the <TT>rb_rescue2()</TT> function from Ruby's C | |
31654 | API. If any Ruby exception is raised, it will be caught here and a C++ | |
31655 | exception is raised in its place.</P> | |
31656 | <H2><A name="Ruby_nn27"></A>27.4 Input and output parameters</H2> | |
31657 | <P> A common problem in some C programs is handling parameters passed as | |
31658 | simple pointers. For example:</P> | |
31659 | <DIV class="code"> | |
31660 | <PRE>void add(int x, int y, int *result) { | |
31661 | <BR> *result = x + y; | |
31662 | <BR>} | |
31663 | <BR>or | |
31664 | <BR>int sub(int *x, int *y) { | |
31665 | <BR> return *x-*y; | |
31666 | <BR>} | |
31667 | <BR></PRE> | |
31668 | </DIV> | |
31669 | <P> The easiest way to handle these situations is to use the <TT> | |
31670 | typemaps.i</TT> file. For example:</P> | |
31671 | <DIV class="code"> | |
31672 | <PRE>%module Example | |
31673 | <BR>%include "typemaps.i" | |
31674 | <BR> | |
31675 | <BR>void add(int, int, int *OUTPUT); | |
31676 | <BR>int sub(int *INPUT, int *INPUT); | |
31677 | <BR></PRE> | |
31678 | </DIV> | |
31679 | <P>In Ruby, this allows you to pass simple values. For example:</P> | |
31680 | <DIV class="code"> | |
31681 | <PRE>a = Example.add(3,4) | |
31682 | <BR>puts a | |
31683 | <BR>7 | |
31684 | <BR>b = Example.sub(7,4) | |
31685 | <BR>puts b | |
31686 | <BR>3 | |
31687 | <BR></PRE> | |
31688 | </DIV> | |
31689 | <P> Notice how the <TT>INPUT</TT> parameters allow integer values to be | |
31690 | passed instead of pointers and how the <TT>OUTPUT</TT> parameter | |
31691 | creates a return result.</P> | |
31692 | <P>If you don't want to use the names <TT>INPUT</TT> or <TT>OUTPUT</TT>, | |
31693 | use the <TT>%apply</TT> directive. For example:</P> | |
31694 | <DIV class="code"> | |
31695 | <PRE>%module Example | |
31696 | <BR>%include "typemaps.i" | |
31697 | <BR> | |
31698 | <BR>%apply int *OUTPUT { int *result }; | |
31699 | <BR>%apply int *INPUT { int *x, int *y}; | |
31700 | <BR> | |
31701 | <BR>void add(int x, int y, int *result); | |
31702 | <BR>int sub(int *x, int *y); | |
31703 | <BR></PRE> | |
31704 | </DIV> | |
31705 | <P> If a function mutates one of its parameters like this,</P> | |
31706 | <DIV class="code"> | |
31707 | <PRE>void negate(int *x) { | |
31708 | <BR> *x = -(*x); | |
31709 | <BR>} | |
31710 | <BR></PRE> | |
31711 | </DIV> | |
31712 | <P>you can use <TT>INOUT</TT> like this:</P> | |
31713 | <DIV class="code"> | |
31714 | <PRE>%include "typemaps.i" | |
31715 | <BR>... | |
31716 | <BR>void negate(int *INOUT); | |
31717 | <BR></PRE> | |
31718 | </DIV> | |
31719 | <P>In Ruby, a mutated parameter shows up as a return value. For example:</P> | |
31720 | <DIV class="code"> | |
31721 | <PRE>a = Example.negate(3) | |
31722 | <BR>print a | |
31723 | <BR>-3 | |
31724 | <BR> | |
31725 | <BR></PRE> | |
31726 | </DIV> | |
31727 | <P> The most common use of these special typemap rules is to handle | |
31728 | functions that return more than one value. For example, sometimes a | |
31729 | function returns a result as well as a special error code:</P> | |
31730 | <DIV class="code"> | |
31731 | <PRE>/* send message, return number of bytes sent, success code, and error_code */ | |
31732 | <BR>int send_message(char *text, int *success, int *error_code); | |
31733 | <BR></PRE> | |
31734 | </DIV> | |
31735 | <P> To wrap such a function, simply use the <TT>OUTPUT</TT> rule above. | |
31736 | For example:</P> | |
31737 | <DIV class="code"> | |
31738 | <PRE>%module example | |
31739 | <BR>%include "typemaps.i" | |
31740 | <BR>... | |
31741 | <BR>int send_message(char *, int *OUTPUT, int *OUTPUT); | |
31742 | <BR></PRE> | |
31743 | </DIV> | |
31744 | <P> When used in Ruby, the function will return an array of multiple | |
31745 | values.</P> | |
31746 | <DIV class="code"> | |
31747 | <PRE>bytes, success, error_code = send_message("Hello World") | |
31748 | <BR>if not success | |
31749 | <BR> print "error #{error_code} : in send_message" | |
31750 | <BR>else | |
31751 | <BR> print "Sent", bytes | |
31752 | <BR>end | |
31753 | <BR></PRE> | |
31754 | </DIV> | |
31755 | <P> Another way to access multiple return values is to use the <TT> | |
31756 | %apply</TT> rule. In the following example, the parameters rows and | |
31757 | columns are related to SWIG as <TT>OUTPUT</TT> values through the use | |
31758 | of <TT>%apply</TT></P> | |
31759 | <DIV class="code"> | |
31760 | <PRE>%module Example | |
31761 | <BR>%include "typemaps.i" | |
31762 | <BR>%apply int *OUTPUT { int *rows, int *columns }; | |
31763 | <BR>... | |
31764 | <BR>void get_dimensions(Matrix *m, int *rows, int*columns); | |
31765 | <BR></PRE> | |
31766 | </DIV> | |
31767 | <P>In Ruby:</P> | |
31768 | <DIV class="code"> | |
31769 | <PRE>r, c = Example.get_dimensions(m) | |
31770 | <BR></PRE> | |
31771 | </DIV> | |
31772 | <H2><A name="Ruby_nn28"></A>27.5 Simple exception handling</H2> | |
31773 | <P> The SWIG <TT>%exception</TT> directive can be used to define a | |
31774 | user-definable exception handler that can convert C/C++ errors into | |
31775 | Ruby exceptions. The chapter on <A href="#Customization">Customization | |
31776 | Features</A> contains more details, but suppose you have a C++ class | |
31777 | like the following :</P> | |
31778 | <DIV class="code"> | |
31779 | <PRE>class DoubleArray { | |
31780 | <BR> private: | |
31781 | <BR> int n; | |
31782 | <BR> double *ptr; | |
31783 | <BR> public: | |
31784 | <BR> // Create a new array of fixed size | |
31785 | <BR> DoubleArray(int size) { | |
31786 | <BR> ptr = new double[size]; | |
31787 | <BR> n = size; | |
31788 | <BR> } | |
31789 | <BR> // Destroy an array | |
31790 | <BR> ~DoubleArray() { | |
31791 | <BR> delete ptr; | |
31792 | <BR> } | |
31793 | <BR> // Return the length of the array | |
31794 | <BR> int length() { | |
31795 | <BR> return n; | |
31796 | <BR> } | |
31797 | <BR> | |
31798 | <BR> // Get an array item and perform bounds checking. | |
31799 | <BR> double getitem(int i) { | |
31800 | <BR> if ((i >= 0) && (i < n)) | |
31801 | <BR> return ptr[i]; | |
31802 | <BR> else | |
31803 | <BR> throw RangeError(); | |
31804 | <BR> } | |
31805 | <BR> // Set an array item and perform bounds checking. | |
31806 | <BR> void setitem(int i, double val) { | |
31807 | <BR> if ((i >= 0) && (i < n)) | |
31808 | <BR> ptr[i] = val; | |
31809 | <BR> else { | |
31810 | <BR> throw RangeError(); | |
31811 | <BR> } | |
31812 | <BR> } | |
31813 | <BR> }; | |
31814 | <BR></PRE> | |
31815 | </DIV> | |
31816 | <P> Since several methods in this class can throw an exception for an | |
31817 | out-of-bounds access, you might want to catch this in the Ruby | |
31818 | extension by writing the following in an interface file:</P> | |
31819 | <DIV class="code"> | |
31820 | <PRE>%exception { | |
31821 | <BR> try { | |
31822 | <BR> $action | |
31823 | <BR> } | |
31824 | <BR> catch (const RangeError&) { | |
31825 | <BR> static VALUE cpperror = rb_define_class("CPPError", rb_eStandardError); | |
31826 | <BR> rb_raise(cpperror, "Range error."); | |
31827 | <BR> } | |
31828 | <BR>} | |
31829 | <BR> | |
31830 | <BR>class DoubleArray { | |
31831 | <BR> ... | |
31832 | <BR>}; | |
31833 | <BR></PRE> | |
31834 | </DIV> | |
31835 | <P> The exception handling code is inserted directly into generated | |
31836 | wrapper functions. When an exception handler is defined, errors can be | |
31837 | caught and used to gracefully raise a Ruby exception instead of forcing | |
31838 | the entire program to terminate with an uncaught error.</P> | |
31839 | <P>As shown, the exception handling code will be added to every wrapper | |
31840 | function. Because this is somewhat inefficient, you might consider | |
31841 | refining the exception handler to only apply to specific methods like | |
31842 | this:</P> | |
31843 | <DIV class="code"> | |
31844 | <PRE>%exception getitem { | |
31845 | <BR> try { | |
31846 | <BR> $action | |
31847 | <BR> } | |
31848 | <BR> catch (const RangeError&) { | |
31849 | <BR> static VALUE cpperror = rb_define_class("CPPError", rb_eStandardError); | |
31850 | <BR> rb_raise(cpperror, "Range error in getitem."); | |
31851 | <BR> } | |
31852 | <BR>} | |
31853 | <BR> | |
31854 | <BR>%exception setitem { | |
31855 | <BR> try { | |
31856 | <BR> $action | |
31857 | <BR> } | |
31858 | <BR> catch (const RangeError&) { | |
31859 | <BR> static VALUE cpperror = rb_define_class("CPPError", rb_eStandardError); | |
31860 | <BR> rb_raise(cpperror, "Range error in setitem."); | |
31861 | <BR> } | |
31862 | <BR>} | |
31863 | <BR></PRE> | |
31864 | </DIV> | |
31865 | <P> In this case, the exception handler is only attached to methods and | |
31866 | functions named <TT>getitem</TT> and <TT>setitem</TT>.</P> | |
31867 | <P>Since SWIG's exception handling is user-definable, you are not | |
31868 | limited to C++ exception handling. See the chapter on <A href="#Customization"> | |
31869 | Customization Features</A> for more examples.</P> | |
31870 | <P>When raising a Ruby exception from C/C++, use the <TT>rb_raise()</TT> | |
31871 | function as shown above. The first argument passed to <TT>rb_raise()</TT> | |
31872 | is the exception type. You can raise a custom exception type (like the <TT> | |
31873 | cpperror</TT> example shown above) or one of the built-in Ruby exception | |
31874 | types. For a list of the standard Ruby exception classes, consult a | |
31875 | Ruby reference such as <A href="http://www.rubycentral.com/book"><EM> | |
31876 | Programming Ruby</EM></A>.</P> | |
31877 | <H2><A name="Ruby_nn29"></A>27.5 Typemaps</H2> | |
31878 | <P> This section describes how you can modify SWIG's default wrapping | |
31879 | behavior for various C/C++ datatypes using the <TT>%typemap</TT> | |
31880 | directive. This is an advanced topic that assumes familiarity with the | |
31881 | Ruby C API as well as the material in the "<A href="#Typemaps">Typemaps</A> | |
31882 | " chapter.</P> | |
31883 | <P>Before proceeding, it should be stressed that typemaps are not a | |
31884 | required part of using SWIG---the default wrapping behavior is enough | |
31885 | in most cases. Typemaps are only used if you want to change some aspect | |
31886 | of the primitive C-Ruby interface.</P> | |
31887 | <H3><A name="Ruby_nn30"></A>27.5.1 What is a typemap?</H3> | |
31888 | <P> A typemap is nothing more than a code generation rule that is | |
31889 | attached to a specific C datatype. For example, to convert integers | |
31890 | from Ruby to C, you might define a typemap like this:</P> | |
31891 | <DIV class="code"> | |
31892 | <PRE>%module example | |
31893 | <BR> | |
31894 | <BR>%typemap(in) int { | |
31895 | <BR> $1 = (int) NUM2INT($input); | |
31896 | <BR> printf("Received an integer : %d\n",$1); | |
31897 | <BR>} | |
31898 | <BR> | |
31899 | <BR>%inline %{ | |
31900 | <BR>extern int fact(int n); | |
31901 | <BR>%} | |
31902 | <BR></PRE> | |
31903 | </DIV> | |
31904 | <P> Typemaps are always associated with some specific aspect of code | |
31905 | generation. In this case, the "in" method refers to the conversion of | |
31906 | input arguments to C/C++. The datatype <TT>int</TT> is the datatype to | |
31907 | which the typemap will be applied. The supplied C code is used to | |
31908 | convert values. In this code a number of special variables prefaced by | |
31909 | a <TT>$</TT> are used. The <TT>$1</TT> variable is placeholder for a | |
31910 | local variable of type <TT>int</TT>. The <TT>$input</TT> variable is | |
31911 | the input Ruby object.</P> | |
31912 | <P>When this example is compiled into a Ruby module, the following | |
31913 | sample code:</P> | |
31914 | <DIV class="code"> | |
31915 | <PRE>require 'example' | |
31916 | <BR> | |
31917 | <BR>puts Example.fact(6) | |
31918 | <BR></PRE> | |
31919 | </DIV> | |
31920 | <P>prints the result:</P> | |
31921 | <DIV class="code"> | |
31922 | <PRE>Received an integer : 6 | |
31923 | <BR>720 | |
31924 | <BR></PRE> | |
31925 | </DIV> | |
31926 | <P> In this example, the typemap is applied to all occurrences of the <TT> | |
31927 | int</TT> datatype. You can refine this by supplying an optional | |
31928 | parameter name. For example:</P> | |
31929 | <DIV class="code"> | |
31930 | <PRE>%module example | |
31931 | <BR> | |
31932 | <BR>%typemap(in) int n { | |
31933 | <BR> $1 = (int) NUM2INT($input); | |
31934 | <BR> printf("n = %d\n",$1); | |
31935 | <BR>} | |
31936 | <BR> | |
31937 | <BR>%inline %{ | |
31938 | <BR>extern int fact(int n); | |
31939 | <BR>%} | |
31940 | <BR></PRE> | |
31941 | </DIV> | |
31942 | <P> In this case, the typemap code is only attached to arguments that | |
31943 | exactly match "<TT>int n</TT>".</P> | |
31944 | <P>The application of a typemap to specific datatypes and argument names | |
31945 | involves more than simple text-matching--typemaps are fully integrated | |
31946 | into the SWIG type-system. When you define a typemap for <TT>int</TT>, | |
31947 | that typemap applies to <TT>int</TT> and qualified variations such as <TT> | |
31948 | const int</TT>. In addition, the typemap system follows <TT>typedef</TT> | |
31949 | declarations. For example:</P> | |
31950 | <DIV class="code"> | |
31951 | <PRE>%typemap(in) int n { | |
31952 | <BR> $1 = (int) NUM2INT($input); | |
31953 | <BR> printf("n = %d\n",$1); | |
31954 | <BR>} | |
31955 | <BR> | |
31956 | <BR>typedef int Integer; | |
31957 | <BR>extern int fact(Integer n); // Above typemap is applied | |
31958 | <BR></PRE> | |
31959 | </DIV> | |
31960 | <P> However, the matching of <TT>typedef</TT> only occurs in one | |
31961 | direction. If you defined a typemap for <TT>Integer</TT>, it is not | |
31962 | applied to arguments of type <TT>int</TT>.</P> | |
31963 | <P>Typemaps can also be defined for groups of consecutive arguments. For | |
31964 | example:</P> | |
31965 | <DIV class="code"> | |
31966 | <PRE>%typemap(in) (char *str, int len) { | |
31967 | <BR> $1 = STR2CSTR($input); | |
31968 | <BR> $2 = (int) RSTRING($input)->len; | |
31969 | <BR>}; | |
31970 | <BR> | |
31971 | <BR>int count(char c, char *str, int len); | |
31972 | <BR></PRE> | |
31973 | </DIV> | |
31974 | <P> When a multi-argument typemap is defined, the arguments are always | |
31975 | handled as a single Ruby object. This allows the function <TT>count</TT> | |
31976 | to be used as follows (notice how the length parameter is omitted):</P> | |
31977 | <DIV class="code"> | |
31978 | <PRE>puts Example.count('o','Hello World') | |
31979 | <BR>2 | |
31980 | <BR></PRE> | |
31981 | </DIV> | |
31982 | <H3><A name="Ruby_nn31"></A>27.5.2 Ruby typemaps</H3> | |
31983 | <P> The previous section illustrated an "in" typemap for converting Ruby | |
31984 | objects to C. A variety of different typemap methods are defined by the | |
31985 | Ruby module. For example, to convert a C integer back into a Ruby | |
31986 | object, you might define an "out" typemap like this:</P> | |
31987 | <DIV class="code"> | |
31988 | <PRE>%typemap(out) int { | |
31989 | <BR> $result = INT2NUM($1); | |
31990 | <BR>} | |
31991 | <BR></PRE> | |
31992 | </DIV> | |
31993 | <P> The following list details all of the typemap methods that can be | |
31994 | used by the Ruby module:</P> | |
31995 | <P><TT>%typemap(in)</TT></P> | |
31996 | <DIV class="indent">Converts Ruby objects to input function arguments</DIV> | |
31997 | <P><TT>%typemap(out)</TT></P> | |
31998 | <DIV class="indent">Converts return value of a C function to a Ruby | |
31999 | object</DIV> | |
32000 | <P><TT>%typemap(varin)</TT></P> | |
32001 | <DIV class="indent">Assigns a C global variable from a Ruby object</DIV> | |
32002 | <P><TT>%typemap(varout)</TT></P> | |
32003 | <DIV class="indent">Returns a C global variable as a Ruby object</DIV> | |
32004 | <P><TT>%typemap(freearg)</TT></P> | |
32005 | <DIV class="indent">Cleans up a function argument (if necessary)</DIV> | |
32006 | <P><TT>%typemap(argout)</TT></P> | |
32007 | <DIV class="indent">Output argument processing</DIV> | |
32008 | <P><TT>%typemap(ret)</TT></P> | |
32009 | <DIV class="indent">Cleanup of function return values</DIV> | |
32010 | <P><TT>%typemap(memberin)</TT></P> | |
32011 | <DIV class="indent">Setting of structure/class member data</DIV> | |
32012 | <P><TT>%typemap(globalin)</TT></P> | |
32013 | <DIV class="indent">Setting of C global variables</DIV> | |
32014 | <P><TT>%typemap(check)</TT></P> | |
32015 | <DIV class="indent">Checks function input values.</DIV> | |
32016 | <P><TT>%typemap(default)</TT></P> | |
32017 | <DIV class="indent">Set a default value for an argument (making it | |
32018 | optional).</DIV> | |
32019 | <P><TT>%typemap(arginit)</TT></P> | |
32020 | <DIV class="indent">Initialize an argument to a value before any | |
32021 | conversions occur.</DIV> | |
32022 | <P> Examples of these typemaps appears in the <A href="#ruby_typemap_examples"> | |
32023 | section on typemap examples</A></P> | |
32024 | <H3><A name="Ruby_nn32"></A>27.5.3 Typemap variables</H3> | |
32025 | Within a typemap, a number of special variables prefaced with a <TT>$</TT> | |
32026 | may appear. A full list of variables can be found in the "<A href="#Typemaps"> | |
32027 | Typemaps</A>" chapter. This is a list of the most common variables: | |
32028 | <P><TT>$1</TT></P> | |
32029 | <DIV class="indent">A C local variable corresponding to the actual type | |
32030 | specified in the <TT>%typemap</TT> directive. For input values, this is | |
32031 | a C local variable that is supposed to hold an argument value. For | |
32032 | output values, this is the raw result that is supposed to be returned | |
32033 | to Ruby.</DIV> | |
32034 | <P><TT>$input</TT></P> | |
32035 | <DIV class="indent">A <TT>VALUE</TT> holding a raw Ruby object with an | |
32036 | argument or variable value.</DIV> | |
32037 | <P><TT>$result</TT></P> | |
32038 | <DIV class="indent">A <TT>VALUE</TT> that holds the result to be | |
32039 | returned to Ruby.</DIV> | |
32040 | <P><TT>$1_name</TT></P> | |
32041 | <DIV class="indent">The parameter name that was matched.</DIV> | |
32042 | <P><TT>$1_type</TT></P> | |
32043 | <DIV class="indent">The actual C datatype matched by the typemap.</DIV> | |
32044 | <P><TT>$1_ltype</TT></P> | |
32045 | <DIV class="indent">An assignable version of the datatype matched by the | |
32046 | typemap (a type that can appear on the left-hand-side of a C assignment | |
32047 | operation). This type is stripped of qualifiers and may be an altered | |
32048 | version of <TT>$1_type</TT>. All arguments and local variables in | |
32049 | wrapper functions are declared using this type so that their values can | |
32050 | be properly assigned.</DIV> | |
32051 | <P><TT>$symname</TT></P> | |
32052 | <DIV class="indent">The Ruby name of the wrapper function being created.</DIV> | |
32053 | <H3><A name="Ruby_nn33"></A>27.5.4 Useful Functions</H3> | |
32054 | <P> When you write a typemap, you usually have to work directly with | |
32055 | Ruby objects. The following functions may prove to be useful. (These | |
32056 | functions plus many more can be found in <A href="http://www.rubycentral.com/book"> | |
32057 | <EM>Programming Ruby</EM></A>, by David Thomas and Andrew Hunt.)</P> | |
32058 | <P><A name="n34"></A></P> | |
32059 | <H4><A name="Ruby_nn34"></A>27.5.4.1 C Datatypes to Ruby Objects</H4> | |
32060 | <DIV class="code"> | |
32061 | <PRE>INT2NUM(long or int) - int to Fixnum or Bignum | |
32062 | <BR>INT2FIX(long or int) - int to Fixnum (faster than INT2NUM) | |
32063 | <BR>CHR2FIX(char) - char to Fixnum | |
32064 | <BR>rb_str_new2(char*) - char* to String | |
32065 | <BR>rb_float_new(double) - double to Float | |
32066 | <BR></PRE> | |
32067 | </DIV> | |
32068 | <H4><A name="Ruby_nn35"></A>27.5.4.2 Ruby Objects to C Datatypes</H4> | |
32069 | <DIV class="code"> | |
32070 | <PRE> int NUM2INT(Numeric) | |
32071 | <BR> int FIX2INT(Numeric) | |
32072 | <BR> unsigned int NUM2UINT(Numeric) | |
32073 | <BR> unsigned int FIX2UINT(Numeric) | |
32074 | <BR> long NUM2LONG(Numeric) | |
32075 | <BR> long FIX2LONG(Numeric) | |
32076 | <BR>unsigned long FIX2ULONG(Numeric) | |
32077 | <BR> char NUM2CHR(Numeric or String) | |
32078 | <BR> char * STR2CSTR(String) | |
32079 | <BR> char * rb_str2cstr(String, int*length) | |
32080 | <BR> double NUM2DBL(Numeric) | |
32081 | <BR> | |
32082 | <BR></PRE> | |
32083 | </DIV> | |
32084 | <H4><A name="Ruby_nn36"></A>27.5.4.3 Macros for VALUE</H4> | |
32085 | <P> <TT>RSTRING(str)->len</TT></P> | |
32086 | <DIV class="indent">length of the Ruby string</DIV> | |
32087 | <P><TT>RSTRING(str)->ptr</TT></P> | |
32088 | <DIV class="indent">pointer to string storage</DIV> | |
32089 | <P><TT>RARRAY(arr)->len</TT></P> | |
32090 | <DIV class="indent">length of the Ruby array</DIV> | |
32091 | <P><TT>RARRAY(arr)->capa</TT></P> | |
32092 | <DIV class="indent">capacity of the Ruby array</DIV> | |
32093 | <P><TT>RARRAY(arr)->ptr</TT></P> | |
32094 | <DIV class="indent">pointer to array storage</DIV> | |
32095 | <H4><A name="Ruby_nn37"></A>27.5.4.4 Exceptions</H4> | |
32096 | <P> <TT>void rb_raise(VALUE exception, const char *fmt, ...)</TT></P> | |
32097 | <DIV class="indent"> Raises an exception. The given format string<I> fmt</I> | |
32098 | and remaining arguments are interpreted as with <TT>printf()</TT>.</DIV> | |
32099 | <P><TT>void rb_fatal(const char *fmt, ...)</TT></P> | |
32100 | <DIV class="indent"> Raises a fatal exception, terminating the process. | |
32101 | No rescue blocks are called, but ensure blocks will be called. The | |
32102 | given format string<I> fmt</I> and remaining arguments are interpreted | |
32103 | as with <TT>printf()</TT>.</DIV> | |
32104 | <P><TT>void rb_bug(const char *fmt, ...)</TT></P> | |
32105 | <DIV class="indent"> Terminates the process immediately -- no handlers | |
32106 | of any sort will be called. The given format string<I> fmt</I> and | |
32107 | remaining arguments are interpreted as with <TT>printf()</TT>. You | |
32108 | should call this function only if a fatal bug has been exposed.</DIV> | |
32109 | <P><TT>void rb_sys_fail(const char *msg)</TT></P> | |
32110 | <DIV class="indent"> Raises a platform-specific exception corresponding | |
32111 | to the last known system error, with the given string<I> msg</I>.</DIV> | |
32112 | <P><TT>VALUE rb_rescue(VALUE (*body)(VALUE), VALUE args, | |
32113 | VALUE(*rescue)(VALUE, VALUE), VALUE rargs)</TT></P> | |
32114 | <DIV class="indent"> Executes<I> body</I> with the given<I> args</I>. If | |
32115 | a <TT>StandardError</TT> exception is raised, then execute<I> rescue</I> | |
32116 | with the given<I> rargs</I>.</DIV> | |
32117 | <P><TT>VALUE rb_ensure(VALUE(*body)(VALUE), VALUE args, | |
32118 | VALUE(*ensure)(VALUE), VALUE eargs)</TT></P> | |
32119 | <DIV class="indent"> Executes<I> body</I> with the given<I> args</I>. | |
32120 | Whether or not an exception is raised, execute<I> ensure</I> with the | |
32121 | given<I> rargs</I> after<I> body</I> has completed.</DIV> | |
32122 | <P><TT>VALUE rb_protect(VALUE (*body)(VALUE), VALUE args, int *result)</TT> | |
32123 | </P> | |
32124 | <DIV class="indent"> Executes<I> body</I> with the given<I> args</I> and | |
32125 | returns nonzero in result if any exception was raised.</DIV> | |
32126 | <P><TT>void rb_notimplement()</TT></P> | |
32127 | <DIV class="indent"> Raises a <TT>NotImpError</TT> exception to indicate | |
32128 | that the enclosed function is not implemented yet, or not available on | |
32129 | this platform.</DIV> | |
32130 | <P><TT>void rb_exit(int status)</TT></P> | |
32131 | <DIV class="indent"> Exits Ruby with the given<I> status</I>. Raises a <TT> | |
32132 | SystemExit</TT> exception and calls registered exit functions and | |
32133 | finalizers.</DIV> | |
32134 | <P><TT>void rb_warn(const char *fmt, ...)</TT></P> | |
32135 | <DIV class="indent"> Unconditionally issues a warning message to | |
32136 | standard error. The given format string<I> fmt</I> and remaining | |
32137 | arguments are interpreted as with <TT>printf()</TT>.</DIV> | |
32138 | <P><TT>void rb_warning(const char *fmt, ...)</TT></P> | |
32139 | <DIV class="indent"> Conditionally issues a warning message to standard | |
32140 | error if Ruby was invoked with the <TT>-w</TT> flag. The given format | |
32141 | string<I> fmt</I> and remaining arguments are interpreted as with <TT> | |
32142 | printf()</TT>.</DIV> | |
32143 | <H4><A name="Ruby_nn38"></A>27.5.4.5 Iterators</H4> | |
32144 | <P> <TT>void rb_iter_break()</TT></P> | |
32145 | <DIV class="indent"> Breaks out of the enclosing iterator block.</DIV> | |
32146 | <P><TT>VALUE rb_each(VALUE obj)</TT></P> | |
32147 | <DIV class="indent"> Invokes the <TT>each</TT> method of the given<I> | |
32148 | obj</I>.</DIV> | |
32149 | <P><TT>VALUE rb_yield(VALUE arg)</TT></P> | |
32150 | <DIV class="indent"> Transfers execution to the iterator block in the | |
32151 | current context, passing<I> arg</I> as an argument. Multiple values may | |
32152 | be passed in an array.</DIV> | |
32153 | <P><TT>int rb_block_given_p()</TT></P> | |
32154 | <DIV class="indent"> Returns <TT>true</TT> if <TT>yield</TT> would | |
32155 | execute a block in the current context; that is, if a code block was | |
32156 | passed to the current method and is available to be called.</DIV> | |
32157 | <P><TT>VALUE rb_iterate(VALUE (*method)(VALUE), VALUE args, VALUE | |
32158 | (*block)(VALUE, VALUE), VALUE arg2)</TT></P> | |
32159 | <DIV class="indent"> Invokes<I> method</I> with argument<I> args</I> and | |
32160 | block<I> block</I>. A <TT>yield</TT> from that method will invoke<I> | |
32161 | block</I> with the argument given to <TT>yield</TT>, and a second | |
32162 | argument<I> arg2</I>.</DIV> | |
32163 | <P><TT>VALUE rb_catch(const char *tag, VALUE (*proc)(VALUE, VALUE), | |
32164 | VALUE value)</TT></P> | |
32165 | <DIV class="indent"> Equivalent to Ruby's <TT>catch</TT>.</DIV> | |
32166 | <P><TT>void rb_throw(const char *tag, VALUE value)</TT></P> | |
32167 | <DIV class="indent"> Equivalent to Ruby's <TT>throw</TT>.</DIV> | |
32168 | <H3><A name="ruby_typemap_examples"></A>27.5.5 Typemap Examples</H3> | |
32169 | <P> This section includes a few examples of typemaps. For more examples, | |
32170 | you might look at the examples in the <TT>Example/ruby</TT> directory.</P> | |
32171 | <H3><A name="Ruby_nn40"></A>27.5.6 Converting a Ruby array to a char **</H3> | |
32172 | <P> A common problem in many C programs is the processing of command | |
32173 | line arguments, which are usually passed in an array of <TT>NULL</TT> | |
32174 | terminated strings. The following SWIG interface file allows a Ruby | |
32175 | Array instance to be used as a <TT>char **</TT> object.</P> | |
32176 | <DIV class="code"> | |
32177 | <PRE>%module argv | |
32178 | <BR> | |
32179 | <BR>// This tells SWIG to treat char ** as a special case | |
32180 | <BR>%typemap(in) char ** { | |
32181 | <BR> /* Get the length of the array */ | |
32182 | <BR> int size = RARRAY($input)->len; | |
32183 | <BR> int i; | |
32184 | <BR> $1 = (char **) malloc((size+1)*sizeof(char *)); | |
32185 | <BR> /* Get the first element in memory */ | |
32186 | <BR> VALUE *ptr = RARRAY($input)->ptr; | |
32187 | <BR> for (i=0; i < size; i++, ptr++) | |
32188 | <BR> /* Convert Ruby Object String to char* */ | |
32189 | <BR> $1[i]= STR2CSTR(*ptr); | |
32190 | <BR> $1[i]=NULL; /* End of list */ | |
32191 | <BR>} | |
32192 | <BR> | |
32193 | <BR>// This cleans up the char ** array created before | |
32194 | <BR>// the function call | |
32195 | <BR> | |
32196 | <BR>%typemap(freearg) char ** { | |
32197 | <BR> free((char *) $1); | |
32198 | <BR>} | |
32199 | <BR> | |
32200 | <BR>// Now a test function | |
32201 | <BR>%inline %{ | |
32202 | <BR>int print_args(char **argv) { | |
32203 | <BR> int i = 0; | |
32204 | <BR> while (argv[i]) { | |
32205 | <BR> printf("argv[%d] = %s\n", i,argv[i]); | |
32206 | <BR> i++; | |
32207 | <BR> } | |
32208 | <BR> return i; | |
32209 | <BR>} | |
32210 | <BR>%} | |
32211 | <BR> | |
32212 | <BR></PRE> | |
32213 | </DIV> | |
32214 | <P> When this module is compiled, the wrapped C function now operates as | |
32215 | follows :</P> | |
32216 | <DIV class="code"> | |
32217 | <PRE>require 'Argv' | |
32218 | <BR>Argv.print_args(["Dave","Mike","Mary","Jane","John"]) | |
32219 | <BR>argv[0] = Dave | |
32220 | <BR>argv[1] = Mike | |
32221 | <BR>argv[2] = Mary | |
32222 | <BR>argv[3] = Jane | |
32223 | <BR>argv[4] = John | |
32224 | <BR></PRE> | |
32225 | </DIV> | |
32226 | <P> In the example, two different typemaps are used. The "in" typemap is | |
32227 | used to receive an input argument and convert it to a C array. Since | |
32228 | dynamic memory allocation is used to allocate memory for the array, the | |
32229 | "freearg" typemap is used to later release this memory after the | |
32230 | execution of the C function.</P> | |
32231 | <H3><A name="Ruby_nn41"></A>27.5.7 Collecting arguments in a hash</H3> | |
32232 | <P> Ruby's solution to the "keyword arguments" capability of some other | |
32233 | languages is to allow the programmer to pass in one or more key-value | |
32234 | pairs as arguments to a function. All of those key-value pairs are | |
32235 | collected in a single <TT>Hash</TT> argument that's presented to the | |
32236 | function. If it makes sense, you might want to provide similar | |
32237 | functionality for your Ruby interface. For example, suppose you'd like | |
32238 | to wrap this C function that collects information about people's vital | |
32239 | statistics:</P> | |
32240 | <DIV class="code"> | |
32241 | <PRE>void setVitalStats(const char *person, int nattributes, const char **names, int *values); | |
32242 | <BR></PRE> | |
32243 | </DIV> | |
32244 | <P> and you'd like to be able to call it from Ruby by passing in an | |
32245 | arbitrary number of key-value pairs as inputs, e.g.</P> | |
32246 | <DIV class="code"> | |
32247 | <PRE>setVitalStats("Fred", | |
32248 | <BR> 'weight' => 270, | |
32249 | <BR> 'age' => 42 | |
32250 | <BR> ) | |
32251 | <BR></PRE> | |
32252 | </DIV> | |
32253 | <P> To make this work, you need to write a typemap that expects a Ruby <TT> | |
32254 | Hash</TT> as its input and somehow extracts the last three arguments (<I> | |
32255 | nattributes</I>,<I> names</I> and<I> values</I>) needed by your C | |
32256 | function. Let's start with the basics:</P> | |
32257 | <DIV class="code"> | |
32258 | <PRE>%typemap(in) (int nattributes, const char **names, const int *values) | |
32259 | <BR> (VALUE keys_arr, int i, VALUE key, VALUE val) { | |
32260 | <BR>} | |
32261 | <BR> </PRE> | |
32262 | </DIV> | |
32263 | <P> This <TT>%typemap</TT> directive tells SWIG that we want to match | |
32264 | any function declaration that has the specified types and names of | |
32265 | arguments somewhere in the argument list. The fact that we specified | |
32266 | the argument names (<I>nattributes</I>,<I> names</I> and<I> values</I>) | |
32267 | in our typemap is significant; this ensures that SWIG won't try to | |
32268 | apply this typemap to<I> other</I> functions it sees that happen to | |
32269 | have a similar declaration with different argument names. The arguments | |
32270 | that appear in the second set of parentheses (<I>keys_arr</I>,<I> i</I> | |
32271 | ,<I> key</I> and<I> val</I>) define local variables that our typemap | |
32272 | will need.</P> | |
32273 | <P>Since we expect the input argument to be a <TT>Hash</TT>, let's next | |
32274 | add a check for that:</P> | |
32275 | <DIV class="code"> | |
32276 | <PRE>%typemap(in) (int nattributes, const char **names, const int *values) | |
32277 | <BR> (VALUE keys_arr, int i, VALUE key, VALUE val) { | |
32278 | <BR> <B>Check_Type($input, T_HASH);</B> | |
32279 | <BR>} | |
32280 | <BR></PRE> | |
32281 | </DIV> | |
32282 | <P> <TT>Check_Type()</TT> is just a macro (defined in the Ruby header | |
32283 | files) that confirms that the input argument is of the correct type; if | |
32284 | it isn't, an exception will be raised.</P> | |
32285 | <P>The next task is to determine how many key-value pairs are present in | |
32286 | the hash; we'll assign this number to the first typemap argument (<TT> | |
32287 | $1</TT>). This is a little tricky since the Ruby/C API doesn't provide a | |
32288 | public function for querying the size of a hash, but we can get around | |
32289 | that by calling the hash's<I> size</I> method directly and converting | |
32290 | its result to a C <TT>int</TT> value:</P> | |
32291 | <DIV class="code"> | |
32292 | <PRE>%typemap(in) (int nattributes, const char **names, const int *values) | |
32293 | <BR> (VALUE keys_arr, int i, VALUE key, VALUE val) { | |
32294 | <BR> Check_Type($input, T_HASH); | |
32295 | <BR> <B>$1 = NUM2INT(rb_funcall($input, rb_intern("size"), 0, NULL));</B> | |
32296 | <BR>} | |
32297 | <BR></PRE> | |
32298 | </DIV> | |
32299 | <P> So now we know the number of attributes. Next we need to initialize | |
32300 | the second and third typemap arguments (i.e. the two C arrays) to <TT> | |
32301 | NULL</TT> and set the stage for extracting the keys and values from the | |
32302 | hash:</P> | |
32303 | <DIV class="code"> | |
32304 | <PRE>%typemap(in) (int nattributes, const char **names, const int *values) | |
32305 | <BR> (VALUE keys_arr, int i, VALUE key, VALUE val) { | |
32306 | <BR> Check_Type($input, T_HASH); | |
32307 | <BR> $1 = NUM2INT(rb_funcall($input, rb_intern("size"), 0, NULL)); | |
32308 | <BR> <B>$2 = NULL; | |
32309 | <BR> $3 = NULL; | |
32310 | <BR> if ($1 > 0) { | |
32311 | <BR> $2 = (char **) malloc($1*sizeof(char *)); | |
32312 | <BR> $3 = (int *) malloc($1*sizeof(int)); | |
32313 | <BR> }</B> | |
32314 | <BR>} | |
32315 | <BR></PRE> | |
32316 | </DIV> | |
32317 | <P> There are a number of ways we could extract the keys and values from | |
32318 | the input hash, but the simplest approach is to first call the hash's<I> | |
32319 | keys</I> method (which returns a Ruby array of the keys) and then start | |
32320 | looping over the elements in that array:</P> | |
32321 | <DIV class="code"> | |
32322 | <PRE>%typemap(in) (int nattributes, const char **names, const int *values) | |
32323 | <BR> (VALUE keys_arr, int i, VALUE key, VALUE val) { | |
32324 | <BR> Check_Type($input, T_HASH); | |
32325 | <BR> $1 = NUM2INT(rb_funcall($input, rb_intern("size"), 0, NULL)); | |
32326 | <BR> $2 = NULL; | |
32327 | <BR> $3 = NULL; | |
32328 | <BR> if ($1 > 0) { | |
32329 | <BR> $2 = (char **) malloc($1*sizeof(char *)); | |
32330 | <BR> $3 = (int *) malloc($1*sizeof(int)); | |
32331 | <BR> <B>keys_arr = rb_funcall($input, rb_intern("keys"), 0, NULL); | |
32332 | <BR> for (i = 0; i < $1; i++) { | |
32333 | <BR> }</B> | |
32334 | <BR>} | |
32335 | <BR>} | |
32336 | <BR></PRE> | |
32337 | </DIV> | |
32338 | <P> Recall that<I> keys_arr</I> and<I> i</I> are local variables for | |
32339 | this typemap. For each element in the<I> keys_arr</I> array, we want to | |
32340 | get the key itself, as well as the value corresponding to that key in | |
32341 | the hash:</P> | |
32342 | <DIV class="code"> | |
32343 | <PRE>%typemap(in) (int nattributes, const char **names, const int *values) | |
32344 | <BR> (VALUE keys_arr, int i, VALUE key, VALUE val) { | |
32345 | <BR> Check_Type($input, T_HASH); | |
32346 | <BR> $1 = NUM2INT(rb_funcall($input, rb_intern("size"), 0, NULL)); | |
32347 | <BR> $2 = NULL; | |
32348 | <BR> $3 = NULL; | |
32349 | <BR> if ($1 > 0) { | |
32350 | <BR> $2 = (char **) malloc($1*sizeof(char *)); | |
32351 | <BR> $3 = (int *) malloc($1*sizeof(int)); | |
32352 | <BR> keys_arr = rb_funcall($input, rb_intern("keys"), 0, NULL); | |
32353 | <BR> for (i = 0; i < $1; i++) { | |
32354 | <BR> <B>key = rb_ary_entry(keys_arr, i); | |
32355 | <BR> val = rb_hash_aref($input, key);</B> | |
32356 | <BR>} | |
32357 | <BR>} | |
32358 | <BR>} | |
32359 | <BR></PRE> | |
32360 | </DIV> | |
32361 | <P> To be safe, we should again use the <TT>Check_Type()</TT> macro to | |
32362 | confirm that the key is a <TT>String</TT> and the value is a <TT>Fixnum</TT> | |
32363 | :</P> | |
32364 | <DIV class="code"> | |
32365 | <PRE>%typemap(in) (int nattributes, const char **names, const int *values) | |
32366 | <BR> (VALUE keys_arr, int i, VALUE key, VALUE val) { | |
32367 | <BR> Check_Type($input, T_HASH); | |
32368 | <BR> $1 = NUM2INT(rb_funcall($input, rb_intern("size"), 0, NULL)); | |
32369 | <BR> $2 = NULL; | |
32370 | <BR> $3 = NULL; | |
32371 | <BR> if ($1 > 0) { | |
32372 | <BR> $2 = (char **) malloc($1*sizeof(char *)); | |
32373 | <BR> $3 = (int *) malloc($1*sizeof(int)); | |
32374 | <BR> keys_arr = rb_funcall($input, rb_intern("keys"), 0, NULL); | |
32375 | <BR> for (i = 0; i < $1; i++) { | |
32376 | <BR> key = rb_ary_entry(keys_arr, i); | |
32377 | <BR> val = rb_hash_aref($input, key); | |
32378 | <BR> <B>Check_Type(key, T_STRING); | |
32379 | <BR> Check_Type(val, T_FIXNUM);</B> | |
32380 | <BR>} | |
32381 | <BR>} | |
32382 | <BR>} | |
32383 | <BR></PRE> | |
32384 | </DIV> | |
32385 | <P> Finally, we can convert these Ruby objects into their C equivalents | |
32386 | and store them in our local C arrays:</P> | |
32387 | <DIV class="code"> | |
32388 | <PRE>%typemap(in) (int nattributes, const char **names, const int *values) | |
32389 | <BR> (VALUE keys_arr, int i, VALUE key, VALUE val) { | |
32390 | <BR> Check_Type($input, T_HASH); | |
32391 | <BR> $1 = NUM2INT(rb_funcall($input, rb_intern("size"), 0, NULL)); | |
32392 | <BR> $2 = NULL; | |
32393 | <BR> $3 = NULL; | |
32394 | <BR> if ($1 > 0) { | |
32395 | <BR> $2 = (char **) malloc($1*sizeof(char *)); | |
32396 | <BR> $3 = (int *) malloc($1*sizeof(int)); | |
32397 | <BR> keys_arr = rb_funcall($input, rb_intern("keys"), 0, NULL); | |
32398 | <BR> for (i = 0; i < $1; i++) { | |
32399 | <BR> key = rb_ary_entry(keys_arr, i); | |
32400 | <BR> val = rb_hash_aref($input, key); | |
32401 | <BR> Check_Type(key, T_STRING); | |
32402 | <BR> Check_Type(val, T_FIXNUM); | |
32403 | <BR> <B>$2[i] = STR2CSTR(key); | |
32404 | <BR> $3[i] = NUM2INT(val);</B> | |
32405 | <BR>} | |
32406 | <BR>} | |
32407 | <BR>} | |
32408 | <BR></PRE> | |
32409 | </DIV> | |
32410 | <P> We're not done yet. Since we used <TT>malloc()</TT> to dynamically | |
32411 | allocate the memory used for the<I> names</I> and<I> values</I> | |
32412 | arguments, we need to provide a corresponding "freearg" typemap to free | |
32413 | that memory so that there is no memory leak. Fortunately, this typemap | |
32414 | is a lot easier to write:</P> | |
32415 | <DIV class="code"> | |
32416 | <PRE>%typemap(freearg) (int nattributes, const char **names, const int *values) { | |
32417 | <BR> free((void *) $2); | |
32418 | <BR> free((void *) $3); | |
32419 | <BR>} | |
32420 | <BR></PRE> | |
32421 | </DIV> | |
32422 | <P> All of the code for this example, as well as a sample Ruby program | |
32423 | that uses the extension, can be found in the <TT>Examples/ruby/hashargs</TT> | |
32424 | directory of the SWIG distribution.</P> | |
32425 | <H3><A name="Ruby_nn42"></A>27.5.8 Pointer handling</H3> | |
32426 | <P> Occasionally, it might be necessary to convert pointer values that | |
32427 | have been stored using the SWIG typed-pointer representation. Since | |
32428 | there are several ways in which pointers can be represented, the | |
32429 | following two functions are used to safely perform this conversion:</P> | |
32430 | <P><TT>int SWIG_ConvertPtr(VALUE obj, void **ptr, swig_type_info *ty, | |
32431 | int flags)</TT></P> | |
32432 | <DIV class="indent">Converts a Ruby object<I> obj</I> to a C pointer | |
32433 | whose address is<I> ptr</I> (i.e.<I> ptr</I> is a pointer to a | |
32434 | pointer). The third argument,<I> ty</I>, is a pointer to a SWIG type | |
32435 | descriptor structure. If<I> ty</I> is not <TT>NULL</TT>, that type | |
32436 | information is used to validate type compatibility and other aspects of | |
32437 | the type conversion. If<I> flags</I> is non-zero, any type errors | |
32438 | encountered during this validation result in a Ruby <TT>TypeError</TT> | |
32439 | exception being raised; if<I> flags</I> is zero, such type errors will | |
32440 | cause <TT>SWIG_ConvertPtr()</TT> to return -1 but not raise an | |
32441 | exception. If<I> ty</I> is <TT>NULL</TT>, no type-checking is | |
32442 | performed.</DIV> | |
32443 | <P> <TT>VALUE SWIG_NewPointerObj(void *ptr, swig_type_info *ty, int own)</TT> | |
32444 | </P> | |
32445 | <DIV class="indent">Creates a new Ruby pointer object. Here,<I> ptr</I> | |
32446 | is the pointer to convert,<I> ty</I> is the SWIG type descriptor | |
32447 | structure that describes the type, and<I> own</I> is a flag that | |
32448 | indicates whether or not Ruby should take ownership of the pointer | |
32449 | (i.e. whether Ruby should free this data when the corresponding Ruby | |
32450 | instance is garbage-collected).</DIV> | |
32451 | <P> Both of these functions require the use of a special SWIG | |
32452 | type-descriptor structure. This structure contains information about | |
32453 | the mangled name of the datatype, type-equivalence information, as well | |
32454 | as information about converting pointer values under C++ inheritance. | |
32455 | For a type of <TT>Foo *</TT>, the type descriptor structure is usually | |
32456 | accessed as follows:</P> | |
32457 | <DIV class="indent"> | |
32458 | <PRE>Foo *foo; | |
32459 | <BR>SWIG_ConvertPtr($input, (void **) &foo, SWIGTYPE_p_Foo, 1); | |
32460 | <BR> | |
32461 | <BR>VALUE obj; | |
32462 | <BR>obj = SWIG_NewPointerObj(f, SWIGTYPE_p_Foo, 0); | |
32463 | <BR></PRE> | |
32464 | </DIV> | |
32465 | <P> In a typemap, the type descriptor should always be accessed using | |
32466 | the special typemap variable <TT>$1_descriptor</TT>. For example:</P> | |
32467 | <DIV class="indent"> | |
32468 | <PRE>%typemap(in) Foo * { | |
32469 | <BR> SWIG_ConvertPtr($input, (void **) &$1, $1_descriptor, 1); | |
32470 | <BR>} | |
32471 | <BR></PRE> | |
32472 | </DIV> | |
32473 | <H4><A name="Ruby_nn43"></A>27.5.8.1 Ruby Datatype Wrapping</H4> | |
32474 | <P> <TT>VALUE Data_Wrap_Struct(VALUE class, void (*mark)(void *), void | |
32475 | (*free)(void *), void *ptr)</TT></P> | |
32476 | <DIV class="indent">Given a pointer<I> ptr</I> to some C data, and the | |
32477 | two garbage collection routines for this data (<I>mark</I> and<I> free</I> | |
32478 | ), return a <TT>VALUE</TT> for the Ruby object.</DIV> | |
32479 | <P><TT>VALUE Data_Make_Struct(VALUE class,<I> c-type</I>, void | |
32480 | (*mark)(void *), void (*free)(void *),<I> c-type</I> *ptr)</TT></P> | |
32481 | <DIV class="indent">Allocates a new instance of a C data type<I> c-type</I> | |
32482 | , assigns it to the pointer<I> ptr</I>, then wraps that pointer with <TT> | |
32483 | Data_Wrap_Struct()</TT> as above.</DIV> | |
32484 | <P><TT>Data_Get_Struct(VALUE obj,<I> c-type</I>,<I> c-type</I> *ptr)</TT> | |
32485 | </P> | |
32486 | <DIV class="indent">Retrieves the original C pointer of type<I> c-type</I> | |
32487 | from the data object<I> obj</I> and assigns that pointer to<I> ptr</I>.</DIV> | |
32488 | <H2><A name="ruby_operator_overloading"></A>27.6 Operator overloading</H2> | |
32489 | <P> SWIG allows operator overloading with, by using the <TT>%extend</TT> | |
32490 | or <TT>%rename</TT> commands in SWIG and the following operator names | |
32491 | (derived from Python):</P> | |
32492 | <DIV class="code"> | |
32493 | <PRE><B> General</B> | |
32494 | <BR>__repr__ - inspect | |
32495 | <BR>__str__ - to_s | |
32496 | <BR>__cmp__ - <=> | |
32497 | <BR>__hash__ - hash | |
32498 | <BR>__nonzero__ - nonzero? | |
32499 | <BR> | |
32500 | <BR><B> Callable</B> | |
32501 | <BR>__call__ - call | |
32502 | <BR> | |
32503 | <BR><B> Collection</B> | |
32504 | <BR>__len__ - length | |
32505 | <BR>__getitem__ - [] | |
32506 | <BR>__setitem__ - []= | |
32507 | <BR> | |
32508 | <BR><B> Numeric</B> | |
32509 | <BR>__add__ - + | |
32510 | <BR>__sub__ - - | |
32511 | <BR>__mul__ - * | |
32512 | <BR>__div__ - / | |
32513 | <BR>__mod__ - % | |
32514 | <BR>__divmod__ - divmod | |
32515 | <BR>__pow__ - ** | |
32516 | <BR>__lshift__ - << | |
32517 | <BR>__rshift__ - >> | |
32518 | <BR>__and__ - & | |
32519 | <BR>__xor__ - ^ | |
32520 | <BR>__or__ - | | |
32521 | <BR>__neg__ - -@ | |
32522 | <BR>__pos__ - +@ | |
32523 | <BR>__abs__ - abs | |
32524 | <BR>__invert__ - ~ | |
32525 | <BR>__int__ - to_i | |
32526 | <BR>__float__ - to_f | |
32527 | <BR>__coerce__ - coerce | |
32528 | <BR> | |
32529 | <BR><B>Additions in 1.3.13 </B> | |
32530 | <BR>__lt__ - < | |
32531 | <BR>__le__ - <= | |
32532 | <BR>__eq__ - == | |
32533 | <BR>__gt__ - > | |
32534 | <BR>__ge__ - >= | |
32535 | <BR> | |
32536 | <BR></PRE> | |
32537 | </DIV> | |
32538 | <P> Note that although SWIG supports the <TT>__eq__</TT> magic method | |
32539 | name for defining an equivalence operator, there is no separate method | |
32540 | for handling<I> inequality</I> since Ruby parses the expression<I> a != | |
32541 | b</I> as<I> !(a == b)</I>.</P> | |
32542 | <H3><A name="Ruby_nn45"></A>27.6.1 Example: STL Vector to Ruby Array</H3> | |
32543 | <P><EM><B> FIXME: This example is out of place here!</B></EM></P> | |
32544 | <P>Another use for macros and type maps is to create a Ruby array from a | |
32545 | STL vector of pointers. In essence, copy of all the pointers in the | |
32546 | vector into a Ruby array. The use of the macro is to make the typemap | |
32547 | so generic that any vector with pointers can use the type map. The | |
32548 | following is an example of how to construct this type of macro/typemap | |
32549 | and should give insight into constructing similar typemaps for other | |
32550 | STL structures:</P> | |
32551 | <DIV class="code"> | |
32552 | <PRE>%define PTR_VECTOR_TO_RUBY_ARRAY(vectorclassname, classname) | |
32553 | <BR>%typemap(ruby, out) vectorclassname &, const vectorclassname & { | |
32554 | <BR> VALUE arr = rb_ary_new2($1->size()); | |
32555 | <BR> vectorclassname::iterator i = $1->begin(), iend = $1->end(); | |
32556 | <BR> for ( ; i!=iend; i++ ) | |
32557 | <BR> rb_ary_push(arr, Data_Wrap_Struct(c ## classname.klass, 0, 0, *i)); | |
32558 | <BR> $result = arr; | |
32559 | <BR>} | |
32560 | <BR>%typemap(ruby, out) vectorclassname, const vectorclassname { | |
32561 | <BR> VALUE arr = rb_ary_new2($1.size()); | |
32562 | <BR> vectorclassname::iterator i = $1.begin(), iend = $1.end(); | |
32563 | <BR> for ( ; i!=iend; i++ ) | |
32564 | <BR> rb_ary_push(arr, Data_Wrap_Struct(c ## classname.klass, 0, 0, *i)); | |
32565 | <BR> $result = arr; | |
32566 | <BR>} | |
32567 | <BR>%enddef | |
32568 | <BR></PRE> | |
32569 | </DIV> | |
32570 | <P> Note, that the "<TT>c ## classname.klass"</TT> is used in the | |
32571 | preprocessor step to determine the actual object from the class name.</P> | |
32572 | <P>To use the macro with a class Foo, the following is used:</P> | |
32573 | <DIV class="code"> | |
32574 | <PRE>PTR_VECTOR_TO_RUBY_ARRAY(vector<foo *="">, Foo) | |
32575 | <BR></PRE> | |
32576 | </DIV> | |
32577 | <P> It is also possible to create a STL vector of Ruby objects:</P> | |
32578 | <DIV class="code"> | |
32579 | <PRE>%define RUBY_ARRAY_TO_PTR_VECTOR(vectorclassname, classname) | |
32580 | <BR>%typemap(ruby, in) vectorclassname &, const vectorclassname & { | |
32581 | <BR> Check_Type($input, T_ARRAY); | |
32582 | <BR> vectorclassname *vec = new vectorclassname; | |
32583 | <BR> int len = RARRAY($input)->len; | |
32584 | <BR> for (int i=0; i!=len; i++) { | |
32585 | <BR> VALUE inst = rb_ary_entry($input, i); | |
32586 | <BR> //The following _should_ work but doesn't on HPUX | |
32587 | <BR> // Check_Type(inst, T_DATA); | |
32588 | <BR> classname *element = NULL; | |
32589 | <BR> Data_Get_Struct(inst, classname, element); | |
32590 | <BR> vec->push_back(element); | |
32591 | <BR> } | |
32592 | <BR> $1 = vec; | |
32593 | <BR>} | |
32594 | <BR> | |
32595 | <BR>%typemap(ruby, freearg) vectorclassname &, const vectorclassname & { | |
32596 | <BR> delete $1; | |
32597 | <BR>} | |
32598 | <BR>%enddef | |
32599 | <BR></PRE> | |
32600 | </DIV> | |
32601 | <P> It is also possible to create a Ruby array from a vector of static | |
32602 | data types:</P> | |
32603 | <DIV class="code"> | |
32604 | <PRE>%define VECTOR_TO_RUBY_ARRAY(vectorclassname, classname) | |
32605 | <BR>%typemap(ruby, out) vectorclassname &, const vectorclassname & { | |
32606 | <BR> VALUE arr = rb_ary_new2($1->size()); | |
32607 | <BR> vectorclassname::iterator i = $1->begin(), iend = $1->end(); | |
32608 | <BR> for ( ; i!=iend; i++ ) | |
32609 | <BR> rb_ary_push(arr, Data_Wrap_Struct(c ## classname.klass, 0, 0, &(*i))); | |
32610 | <BR> $result = arr; | |
32611 | <BR>} | |
32612 | <BR>%typemap(ruby, out) vectorclassname, const vectorclassname { | |
32613 | <BR> VALUE arr = rb_ary_new2($1.size()); | |
32614 | <BR> vectorclassname::iterator i = $1.begin(), iend = $1.end(); | |
32615 | <BR> for ( ; i!=iend; i++ ) | |
32616 | <BR> rb_ary_push(arr, Data_Wrap_Struct(c ## classname.klass, 0, 0, &(*i))); | |
32617 | <BR> $result = arr; | |
32618 | <BR>} | |
32619 | <BR>%enddef | |
32620 | <BR></PRE> | |
32621 | </DIV> | |
32622 | <H2><A name="Ruby_nn46"></A>27.7 Advanced Topics</H2> | |
32623 | <H3><A name="Ruby_nn47"></A>27.7.1 Creating Multi-Module Packages</H3> | |
32624 | <P> The chapter on <A href="Modules.html">Working with Modules</A> | |
32625 | discusses the basics of creating multi-module extensions with SWIG, and | |
32626 | in particular the considerations for sharing runtime type information | |
32627 | among the different modules.</P> | |
32628 | <P>As an example, consider one module's interface file (<TT>shape.i</TT> | |
32629 | ) that defines our base class:</P> | |
32630 | <DIV class="code"> | |
32631 | <PRE>%module shape | |
32632 | <BR> | |
32633 | <BR>%{ | |
32634 | <BR>#include "Shape.h" | |
32635 | <BR>%} | |
32636 | <BR> | |
32637 | <BR>class Shape { | |
32638 | <BR>protected: | |
32639 | <BR> double xpos; | |
32640 | <BR> double ypos; | |
32641 | <BR>protected: | |
32642 | <BR> Shape(double x, double y); | |
32643 | <BR>public: | |
32644 | <BR> double getX() const; | |
32645 | <BR> double getY() const; | |
32646 | <BR>}; | |
32647 | <BR></PRE> | |
32648 | </DIV> | |
32649 | <P> We also have a separate interface file (<TT>circle.i</TT>) that | |
32650 | defines a derived class:</P> | |
32651 | <DIV class="code"> | |
32652 | <PRE>%module circle | |
32653 | <BR> | |
32654 | <BR>%{ | |
32655 | <BR>#include "Shape.h" | |
32656 | <BR>#include "Circle.h" | |
32657 | <BR>%} | |
32658 | <BR> | |
32659 | <BR>// Import the base class definition from Shape module | |
32660 | <BR>%import shape.i | |
32661 | <BR> | |
32662 | <BR>class Circle : public Shape { | |
32663 | <BR>protected: | |
32664 | <BR> double radius; | |
32665 | <BR>public: | |
32666 | <BR> Circle(double x, double y, double r); | |
32667 | <BR> double getRadius() const; | |
32668 | <BR>}; | |
32669 | <BR></PRE> | |
32670 | </DIV> | |
32671 | <P> We'll start by building the<B> Shape</B> extension module:</P> | |
32672 | <DIV class="code"> | |
32673 | <PRE>$ <B>swig -c++ -ruby shape.i</B> | |
32674 | </PRE> | |
32675 | </DIV> | |
32676 | <P> SWIG generates a wrapper file named <TT>shape_wrap.cxx</TT>. To | |
32677 | compile this into a dynamically loadable extension for Ruby, prepare an | |
32678 | <TT>extconf.rb</TT> script using this template:</P> | |
32679 | <DIV class="code"> | |
32680 | <PRE>require 'mkmf' | |
32681 | <BR> | |
32682 | <BR># Since the SWIG runtime support library for Ruby | |
32683 | <BR># depends on the Ruby library, make sure it's in the list | |
32684 | <BR># of libraries. | |
32685 | <BR>$libs = append_library($libs, Config::CONFIG['RUBY_INSTALL_NAME']) | |
32686 | <BR> | |
32687 | <BR># Create the makefile | |
32688 | <BR>create_makefile('shape') | |
32689 | <BR></PRE> | |
32690 | </DIV> | |
32691 | <P> Run this script to create a <TT>Makefile</TT> and then type <TT>make</TT> | |
32692 | to build the shared library:</P> | |
32693 | <DIV class="code"> | |
32694 | <PRE>$ <B>ruby extconf.rb</B> | |
32695 | <BR>creating Makefile | |
32696 | <BR>$ <B>make</B> | |
32697 | <BR>g++ -fPIC -g -O2 -I. -I/usr/local/lib/ruby/1.7/i686-linux \ | |
32698 | <BR>-I. -c shape_wrap.cxx | |
32699 | <BR>gcc -shared -L/usr/local/lib -o shape.so shape_wrap.o -L. \ | |
32700 | <BR>-lruby -lruby -lc | |
32701 | <BR></PRE> | |
32702 | </DIV> | |
32703 | <P> Note that depending on your installation, the outputs may be | |
32704 | slightly different; these outputs are those for a Linux-based | |
32705 | development environment. The end result should be a shared library | |
32706 | (here, <TT>shape.so</TT>) containing the extension module code. Now | |
32707 | repeat this process in a separate directory for the<B> Circle</B> | |
32708 | module:</P> | |
32709 | <OL> | |
32710 | <LI> Run SWIG to generate the wrapper code (<TT>circle_wrap.cxx</TT>);</LI> | |
32711 | <LI> Write an <TT>extconf.rb</TT> script that your end-users can use to | |
32712 | create a platform-specific <TT>Makefile</TT> for the extension;</LI> | |
32713 | <LI> Build the shared library for this extension by typing <TT>make</TT> | |
32714 | .</LI> | |
32715 | </OL> | |
32716 | <P> Once you've built both of these extension modules, you can test them | |
32717 | interactively in IRB to confirm that the <TT>Shape</TT> and <TT>Circle</TT> | |
32718 | modules are properly loaded and initialized:</P> | |
32719 | <DIV class="code"> | |
32720 | <PRE>$ <B>irb</B> | |
32721 | <BR>irb(main):001:0> <B>require 'shape'</B> | |
32722 | <BR>true | |
32723 | <BR>irb(main):002:0> <B>require 'circle'</B> | |
32724 | <BR>true | |
32725 | <BR>irb(main):003:0> <B>c = Circle::Circle.new(5, 5, 20)</B> | |
32726 | <BR>#<Circle::Circle:0xa097208> | |
32727 | <BR>irb(main):004:0> <B>c.kind_of? Shape::Shape</B> | |
32728 | <BR>true | |
32729 | <BR>irb(main):005:0> <B>c.getX()</B> | |
32730 | <BR>5.0 | |
32731 | <BR></PRE> | |
32732 | </DIV> | |
32733 | <H3><A name="Ruby_nn48"></A>27.7.2 Defining Aliases</H3> | |
32734 | <P> It's a fairly common practice in the Ruby built-ins and standard | |
32735 | library to provide aliases for method names. For example,<EM> | |
32736 | Array#size</EM> is an alias for<EM> Array#length</EM>. If you'd like to | |
32737 | provide an alias for one of your class' instance methods, one approach | |
32738 | is to use SWIG's <TT>%extend</TT> directive to add a new method of the | |
32739 | aliased name that calls the original function. For example:</P> | |
32740 | <DIV class="code"> | |
32741 | <PRE>class MyArray { | |
32742 | <BR>public: | |
32743 | <BR> // Construct an empty array | |
32744 | <BR> MyArray(); | |
32745 | <BR> | |
32746 | <BR> // Return the size of this array | |
32747 | <BR> size_t length() const; | |
32748 | <BR>}; | |
32749 | <BR> | |
32750 | <BR>%extend MyArray { | |
32751 | <BR> // MyArray#size is an alias for MyArray#length | |
32752 | <BR> size_t size() const { | |
32753 | <BR> return self->length(); | |
32754 | <BR> } | |
32755 | <BR>} | |
32756 | <BR></PRE> | |
32757 | </DIV> | |
32758 | <P> A better solution is to instead use the <TT>%alias</TT> directive | |
32759 | (unique to SWIG's Ruby module). The previous example could then be | |
32760 | rewritten as:</P> | |
32761 | <DIV class="code"> | |
32762 | <PRE>// MyArray#size is an alias for MyArray#length | |
32763 | <BR>%alias MyArray::length "size"; | |
32764 | <BR> | |
32765 | <BR>class MyArray { | |
32766 | <BR>public: | |
32767 | <BR> // Construct an empty array | |
32768 | <BR> MyArray(); | |
32769 | <BR> | |
32770 | <BR> // Return the size of this array | |
32771 | <BR> size_t length() const; | |
32772 | <BR>}; | |
32773 | <BR></PRE> | |
32774 | </DIV> | |
32775 | <P> Multiple aliases can be associated with a method by providing a | |
32776 | comma-separated list of aliases to the <TT>%alias</TT> directive, e.g.</P> | |
32777 | <DIV class="code"> | |
32778 | <PRE>%alias MyArray::length "amount,quantity,size";</PRE> | |
32779 | </DIV> | |
32780 | <P> From an end-user's standpoint, there's no functional difference | |
32781 | between these two approaches; i.e. they should get the same result from | |
32782 | calling either<EM> MyArray#size</EM> or<EM> MyArray#length</EM>. | |
32783 | However, when the <TT>%alias</TT> directive is used, SWIG doesn't need | |
32784 | to generate all of the wrapper code that's usually associated with | |
32785 | added methods like our<EM> MyArray::size()</EM> example.</P> | |
32786 | <P>Note that the <TT>%alias</TT> directive is implemented using SWIG's | |
32787 | "features" mechanism and so the same name matching rules used for other | |
32788 | kinds of features apply (see the chapter on <A href="#Customization"> | |
32789 | "Customization Features"</A>) for more details).</P> | |
32790 | <H3><A name="Ruby_nn49"></A>27.7.3 Predicate Methods</H3> | |
32791 | <P> Predicate methods in Ruby are those which return either <TT>true</TT> | |
32792 | or <TT>false</TT>. By convention, these methods' names end in a | |
32793 | question mark; some examples from built-in Ruby classes include<EM> | |
32794 | Array#empty?</EM> (which returns <TT>true</TT> for an array containing | |
32795 | no elements) and<EM> Object#instance_of?</EM> (which returns <TT>true</TT> | |
32796 | if the object is an instance of the specified class). For consistency | |
32797 | with Ruby conventions you would also want your interface's predicate | |
32798 | methods' names to end in a question mark and return <TT>true</TT> or <TT> | |
32799 | false</TT>.</P> | |
32800 | <P>One cumbersome solution to this problem is to rename the method | |
32801 | (using SWIG's <TT>%rename</TT> directive) and provide a custom typemap | |
32802 | that converts the function's actual return type to Ruby's <TT>true</TT> | |
32803 | or <TT>false</TT>. For example:</P> | |
32804 | <DIV class="code"> | |
32805 | <PRE>%rename("is_it_safe?") is_it_safe(); | |
32806 | <BR> | |
32807 | <BR>%typemap(out) int is_it_safe | |
32808 | <BR> "$result = ($1 != 0) ? Qtrue : Qfalse;"; | |
32809 | <BR> | |
32810 | <BR>int is_it_safe(); | |
32811 | <BR></PRE> | |
32812 | </DIV> | |
32813 | <P> A better solution is to instead use the <TT>%predicate</TT> | |
32814 | directive (unique to SWIG's Ruby module) to designate certain methods | |
32815 | as predicate methods. For the previous example, this would look like:</P> | |
32816 | <DIV class="code"> | |
32817 | <PRE>%predicate is_it_safe(); | |
32818 | <BR> | |
32819 | <BR>int is_it_safe(); | |
32820 | <BR></PRE> | |
32821 | </DIV> | |
32822 | <P>and to use this method from your Ruby code:</P> | |
32823 | <DIV class="code"> | |
32824 | <PRE>irb(main):001:0> <B>Example::is_it_safe?</B> | |
32825 | <BR>true | |
32826 | <BR></PRE> | |
32827 | </DIV> | |
32828 | <P> Note that the <TT>%predicate</TT> directive is implemented using | |
32829 | SWIG's "features" mechanism and so the same name matching rules used | |
32830 | for other kinds of features apply (see the chapter on <A href="#Customization"> | |
32831 | "Customization Features"</A>) for more details).</P> | |
32832 | <H3><A name="Ruby_nn50"></A>27.7.4 Specifying Mixin Modules</H3> | |
32833 | <P> The Ruby language doesn't support multiple inheritance, but it does | |
32834 | allow you to mix one or more modules into a class using Ruby's <TT> | |
32835 | include</TT> method. For example, if you have a Ruby class that defines | |
32836 | an<EM> each</EM> instance method, e.g.</P> | |
32837 | <DIV class="code"> | |
32838 | <PRE>class Set | |
32839 | <BR> def initialize | |
32840 | <BR> @members = [] | |
32841 | <BR> end | |
32842 | <BR> | |
32843 | <BR> def each | |
32844 | <BR> @members.each { |m| yield m } | |
32845 | <BR> end | |
32846 | <BR>end | |
32847 | <BR></PRE> | |
32848 | </DIV> | |
32849 | <P> then you can mix-in Ruby's <TT>Enumerable</TT> module to easily add | |
32850 | a lot of functionality to your class:</P> | |
32851 | <DIV class="code"> | |
32852 | <PRE>class Set | |
32853 | <BR> <B>include Enumerable</B> | |
32854 | <BR>def initialize | |
32855 | <BR>@members = [] | |
32856 | <BR>end | |
32857 | <BR>def each | |
32858 | <BR>@members.each { |m| yield m } | |
32859 | <BR>end | |
32860 | <BR>end | |
32861 | <BR></PRE> | |
32862 | </DIV> | |
32863 | <P> To get the same benefit for your SWIG-wrapped classes, you can use | |
32864 | the <TT>%mixin</TT> directive to specify the names of one or more | |
32865 | modules that should be mixed-in to a class. For the above example, the | |
32866 | SWIG interface specification might look like this:</P> | |
32867 | <DIV class="code"> | |
32868 | <PRE>%mixin Set "Enumerable"; | |
32869 | <BR> | |
32870 | <BR>class Set { | |
32871 | <BR>public: | |
32872 | <BR> // Constructor | |
32873 | <BR> Set(); | |
32874 | <BR> | |
32875 | <BR> // Iterates through set members | |
32876 | <BR> void each(); | |
32877 | <BR>}; | |
32878 | <BR></PRE> | |
32879 | </DIV> | |
32880 | <P> Multiple modules can be mixed into a class by providing a | |
32881 | comma-separated list of module names to the <TT>%mixin</TT> directive, | |
32882 | e.g.</P> | |
32883 | <DIV class="code"> | |
32884 | <PRE>%mixin Set "Fee,Fi,Fo,Fum";</PRE> | |
32885 | </DIV> | |
32886 | <P> Note that the <TT>%mixin</TT> directive is implemented using SWIG's | |
32887 | "features" mechanism and so the same name matching rules used for other | |
32888 | kinds of features apply (see the chapter on <A href="#Customization"> | |
32889 | "Customization Features"</A>) for more details).</P> | |
32890 | <H2><A name="Ruby_nn51"></A>27.8 Memory Management</H2> | |
32891 | <P>One of the most common issues in generating SWIG bindings for Ruby is | |
32892 | proper memory management. The key to proper memory management is | |
32893 | clearly defining whether a wrapper Ruby object owns the underlying C | |
32894 | struct or C++ class. There are two possibilities:</P> | |
32895 | <UL> | |
32896 | <LI> The Ruby object is responsible for freeing the C struct or C++ | |
32897 | object</LI> | |
32898 | <LI> The Ruby object should not free the C struct or C++ object because | |
32899 | it will be freed by the underlying C or C++ code</LI> | |
32900 | </UL> | |
32901 | <P>To complicate matters, object ownership may transfer from Ruby to C++ | |
32902 | (or vice versa) depending on what function or methods are invoked. | |
32903 | Clearly, developing a SWIG wrapper requires a thorough understanding of | |
32904 | how the underlying library manages memory.</P> | |
32905 | <H3><A id="Ruby_nn52" name="Ruby_nn52"></A>27.9.1 Mark and Sweep Garbage | |
32906 | Collector</H3> | |
32907 | <P>Ruby uses a mark and sweep garbage collector. When the garbage | |
32908 | collector runs, it finds all the "root" objects, including local | |
32909 | variables, global variables, global constants, hardware registers and | |
32910 | the C stack. For each root object, the garbage collector sets its mark | |
32911 | flag to true and calls <TT>rb_gc_mark</TT> on the object. The job of <TT> | |
32912 | rb_gc_mark</TT> is to recursively mark all the objects that a Ruby | |
32913 | object has a reference to (ignoring those objects that have already | |
32914 | been marked). Those objects, in turn, may reference other objects. This | |
32915 | process will continue until all active objects have been "marked." | |
32916 | After the mark phase comes the sweep phase. In the sweep phase, all | |
32917 | objects that have not been marked will be garbage collected. For more | |
32918 | information about the Ruby garbage collector please refer to <A href="http://rubygarden.org/ruby/ruby?GCAndExtensions"> | |
32919 | ||
32920 | <!--span style="text-decoration: underline;"--> | |
32921 | http://rubygarden.org/ruby/ruby?GCAndExtensions</A>.</P> | |
32922 | <P>The Ruby C/API provides extension developers two hooks into the | |
32923 | garbage collector - a "mark" function and a "sweep" function. By | |
32924 | default these functions are set to NULL.</P> | |
32925 | <P>If a C struct or C++ class references any other Ruby objects, then it | |
32926 | must provide a "mark" function. The "mark" function should identify any | |
32927 | referenced Ruby objects by calling the rb_gc_mark function for each | |
32928 | one. Unsurprisingly, this function will be called by the Ruby garbage | |
32929 | during the "mark" phase.</P> | |
32930 | <P>During the sweep phase, Ruby destroys any unused objects. If any | |
32931 | memory has been allocated in creating the underlying C struct or C++ | |
32932 | struct, then a "free" function must be defined that deallocates this | |
32933 | memory.</P> | |
32934 | <H3><A name="Ruby_nn53"></A>27.8.1 Object Ownership</H3> | |
32935 | <P>As described above, memory management depends on clearly defining who | |
32936 | is responsible for freeing the underlying C struct or C++ class. If the | |
32937 | Ruby object is responsible for freeing the C++ object, then a "free" | |
32938 | function must be registered for the object. If the Ruby object is not | |
32939 | responsible for freeing the underlying memory, then a "free" function | |
32940 | must not be registered for the object.</P> | |
32941 | <P>For the most part, SWIG takes care of memory management issues. The | |
32942 | rules it uses are:</P> | |
32943 | <UL> | |
32944 | <LI> When calling a C++ object's constructor from Ruby, SWIG will assign | |
32945 | a "free" function thereby making the Ruby object responsible for | |
32946 | freeing the C++ object</LI> | |
32947 | <LI> When calling a C++ member function that returns a pointer, SWIG | |
32948 | will not assign a "free" function thereby making the underlying library | |
32949 | responsible for freeing the object.</LI> | |
32950 | </UL> | |
32951 | <P>To make this clearer, let's look at an example. Assume we have a Foo | |
32952 | and a Bar class.</P> | |
32953 | <DIV class="code"> | |
32954 | <PRE>/* File "RubyOwernshipExample.h" */ | |
32955 | <BR> | |
32956 | <BR>class Foo | |
32957 | <BR>{ | |
32958 | <BR>public: | |
32959 | <BR> Foo() {} | |
32960 | <BR> ~Foo() {} | |
32961 | <BR>}; | |
32962 | <BR> | |
32963 | <BR>class Bar | |
32964 | <BR>{ | |
32965 | <BR> Foo *foo_; | |
32966 | <BR>public: | |
32967 | <BR> Bar(): foo_(new Foo) {} | |
32968 | <BR> ~Bar() { delete foo_; } | |
32969 | <BR> Foo* get_foo() { return foo_; } | |
32970 | <BR> Foo* get_new_foo() { return new Foo; } | |
32971 | <BR> void set_foo(Foo *foo) { delete foo_; foo_ = foo; } | |
32972 | <BR>}; | |
32973 | <BR> | |
32974 | </PRE> | |
32975 | </DIV> | |
32976 | <P>First, consider this Ruby code:</P> | |
32977 | <DIV class="code"> | |
32978 | <PRE>foo = Foo.new</PRE> | |
32979 | </DIV> | |
32980 | <P>In this case, the Ruby code calls the underlying <TT>Foo</TT> C++ | |
32981 | constructor, thus creating a new <TT>foo</TT> object. By default, SWIG | |
32982 | will assign the new Ruby object a "free" function. When the Ruby object | |
32983 | is garbage collected, the "free" function will be called. It in turn | |
32984 | will call <TT>Foo's</TT> destructor.</P> | |
32985 | <P>Next, consider this code:</P> | |
32986 | <DIV class="code"> | |
32987 | <PRE>bar = Bar.new | |
32988 | <BR>foo = bar.get_foo()</PRE> | |
32989 | </DIV> | |
32990 | <P>In this case, the Ruby code calls a C++ member function, <TT>get_foo</TT> | |
32991 | . By default, SWIG will not assign the Ruby object a "free" function. | |
32992 | Thus, when the Ruby object is garbage collected the underlying C++ <TT> | |
32993 | foo</TT> object is not affected.</P> | |
32994 | <P>Unfortunately, the real world is not as simple as the examples above. | |
32995 | For example:</P> | |
32996 | <DIV class="code"> | |
32997 | <PRE>bar = Bar.new | |
32998 | <BR>foo = bar.get_new_foo()</PRE> | |
32999 | </DIV> | |
33000 | <P>In this case, the default SWIG behavior for calling member functions | |
33001 | is incorrect. The Ruby object should assume ownership of the returned | |
33002 | object. This can be done by using the %newobject directive. See <A href="#ownership"> | |
33003 | Object ownership and %newobject</A> for more information.</P> | |
33004 | <P>The SWIG default mappings are also incorrect in this case:</P> | |
33005 | <DIV class="code"> | |
33006 | <PRE>foo = Foo.new | |
33007 | <BR>bar = Bar.new | |
33008 | <BR>bar.set_foo(foo)</PRE> | |
33009 | </DIV> | |
33010 | <P>Without modification, this code will cause a segmentation fault. When | |
33011 | the Ruby <TT>foo</TT> object goes out of scope, it will free the | |
33012 | underlying C++ <TT>foo</TT> object. However, when the Ruby bar object | |
33013 | goes out of scope, it will call the C++ bar destructor which will also | |
33014 | free the C++ <TT>foo</TT> object. The problem is that object ownership | |
33015 | is transferred from the Ruby object to the C++ object when the <TT> | |
33016 | set_foo</TT> method is called. This can be done by using the special | |
33017 | DISOWN type map, which was added to the Ruby bindings in SWIG-1.3.26.</P> | |
33018 | <P>Thus, a correct SWIG interface file correct mapping for these classes | |
33019 | is:</P> | |
33020 | <DIV class="code"> | |
33021 | <PRE>/* File RubyOwnershipExample.i */ | |
33022 | <BR> | |
33023 | <BR>%module RubyOwnershipExample | |
33024 | <BR> | |
33025 | <BR>%{ | |
33026 | <BR>#include "RubyOwnershipExample.h" | |
33027 | <BR>%} | |
33028 | <BR> | |
33029 | <BR>class Foo | |
33030 | <BR>{ | |
33031 | <BR>public: | |
33032 | <BR> Foo(); | |
33033 | <BR> ~Foo(); | |
33034 | <BR>}; | |
33035 | <BR> | |
33036 | <BR>class Bar | |
33037 | <BR>{ | |
33038 | <BR> Foo *foo_; | |
33039 | <BR>public: | |
33040 | <BR> Bar(); | |
33041 | <BR> ~Bar(); | |
33042 | <BR> Foo* get_foo(); | |
33043 | <BR> | |
33044 | <BR> | |
33045 | <!--span style="font-weight: bold;"--> | |
33046 | %newobject get_new_foo; | |
33047 | <BR> Foo* get_new_foo(); | |
33048 | <BR> | |
33049 | <BR> | |
33050 | <!--span style="font-weight: bold;"--> | |
33051 | %apply SWIGTYPE *DISOWN {Foo *foo}; | |
33052 | <BR> void set_foo(Foo *foo); | |
33053 | <BR> | |
33054 | <!--span style="font-weight: bold;"--> | |
33055 | %clear Foo *foo; | |
33056 | <BR>}; | |
33057 | <BR> | |
33058 | </PRE> | |
33059 | </DIV> | |
33060 | <BR> | |
33061 | <P> This code can be seen in swig/examples/ruby/tracking.</P> | |
33062 | <BR> | |
33063 | <H3><A name="Ruby_nn54"></A>27.8.2 Object Tracking</H3> | |
33064 | <P>The remaining parts of this section will use the class library shown | |
33065 | below to illustrate different memory management techniques. The class | |
33066 | library models a zoo and the animals it contains.</P> | |
33067 | <DIV class="code"> | |
33068 | <PRE>%module zoo | |
33069 | <BR> | |
33070 | <BR>%{ | |
33071 | <BR>#include <string> | |
33072 | <BR>#include <vector> | |
33073 | <BR> | |
33074 | <BR>#include "zoo.h" | |
33075 | <BR>%} | |
33076 | <BR> | |
33077 | <BR>class Animal | |
33078 | <BR>{ | |
33079 | <BR>private: | |
33080 | <BR> typedef std::vector<Animal*> AnimalsType; | |
33081 | <BR> typedef AnimalsType::iterator IterType; | |
33082 | <BR>protected: | |
33083 | <BR> AnimalsType animals; | |
33084 | <BR>protected: | |
33085 | <BR> std::string name_; | |
33086 | <BR>public: | |
33087 | <BR> // Construct an animal with this name | |
33088 | <BR> Animal(const char* name) : name_(name) {} | |
33089 | <BR> | |
33090 | <BR> // Return the animal's name | |
33091 | <BR> const char* get_name() const { return name.c_str(); } | |
33092 | <BR>}; | |
33093 | <BR> | |
33094 | <BR>class Zoo | |
33095 | <BR>{ | |
33096 | <BR>protected: | |
33097 | <BR> std::vector<animal *=""> animals; | |
33098 | <BR> | |
33099 | <BR>public: | |
33100 | <BR> // Construct an empty zoo | |
33101 | <BR> Zoo() {} | |
33102 | <BR> | |
33103 | <BR> /* Create a new animal. */ | |
33104 | <BR> static Animal* Zoo::create_animal(const char* name) | |
33105 | <BR> { | |
33106 | <BR> return new Animal(name); | |
33107 | <BR> } | |
33108 | <BR> | |
33109 | <BR> // Add a new animal to the zoo | |
33110 | <BR> void add_animal(Animal* animal) { | |
33111 | <BR> animals.push_back(animal); | |
33112 | <BR> } | |
33113 | <BR> | |
33114 | <BR> Animal* remove_animal(size_t i) { | |
33115 | <BR> Animal* result = this->animals[i]; | |
33116 | <BR> IterType iter = this->animals.begin(); | |
33117 | <BR> std::advance(iter, i); | |
33118 | <BR> this->animals.erase(iter); | |
33119 | <BR> | |
33120 | <BR> return result; | |
33121 | <BR> } | |
33122 | <BR> | |
33123 | <BR> // Return the number of animals in the zoo | |
33124 | <BR> size_t get_num_animals() const { | |
33125 | <BR> return animals.size(); | |
33126 | <BR> } | |
33127 | <BR> | |
33128 | <BR> // Return a pointer to the ith animal | |
33129 | <BR> Animal* get_animal(size_t i) const { | |
33130 | <BR> return animals[i]; | |
33131 | <BR> } | |
33132 | <BR>}; | |
33133 | <BR> | |
33134 | </PRE> | |
33135 | </DIV> | |
33136 | <P>Let's say you SWIG this code and then run IRB: | |
33137 | <BR></P> | |
33138 | <DIV class="code"> | |
33139 | <PRE>$ | |
33140 | <!--span style="font-weight: bold;"--> | |
33141 | irb | |
33142 | <BR>irb(main):001:0> | |
33143 | <!--span style="font-weight: bold;"--> | |
33144 | require 'example' | |
33145 | <BR>=> true | |
33146 | <BR> | |
33147 | <BR>irb(main):002:0> | |
33148 | <!--span style="font-weight: bold;"--> | |
33149 | tiger1 = Example::Animal.new("tiger1") | |
33150 | <BR>=> #<Example::Animal:0x2be3820> | |
33151 | <BR> | |
33152 | <BR>irb(main):004:0> | |
33153 | <!--span style="font-weight: bold;"--> | |
33154 | tiger1.get_name() | |
33155 | <BR>=> "tiger1" | |
33156 | <BR> | |
33157 | <BR>irb(main):003:0> | |
33158 | <!--span style="font-weight: bold;"--> | |
33159 | zoo = Example::Zoo.new() | |
33160 | <BR>=> #<Example::Zoo:0x2be0a60> | |
33161 | <BR> | |
33162 | <BR>irb(main):006:0> | |
33163 | <!--span style="font-weight: bold;"--> | |
33164 | zoo.add_animal(tiger) | |
33165 | <BR>=> nil | |
33166 | <BR> | |
33167 | <BR>irb(main):007:0> | |
33168 | <!--span style="font-weight: bold;"--> | |
33169 | zoo.get_num_animals() | |
33170 | <BR>=> 1 | |
33171 | <BR> | |
33172 | <BR>irb(main):007:0> | |
33173 | <!--span style="font-weight: bold;"--> | |
33174 | tiger2 = zoo.remove_animal(0) | |
33175 | <BR>=> #<Example::Animal:0x2bd4a18> | |
33176 | <BR> | |
33177 | <BR>irb(main):008:0> | |
33178 | <!--span style="font-weight: bold;"--> | |
33179 | tiger2.get_name() | |
33180 | <BR>=> "tiger1" | |
33181 | <BR> | |
33182 | <BR>irb(main):009:0> | |
33183 | <!--span style="font-weight: bold;"--> | |
33184 | tiger1.equal?(tiger2) | |
33185 | <BR>=> false | |
33186 | <BR> | |
33187 | </PRE> | |
33188 | </DIV> | |
33189 | <P>Pay particular attention to the code <TT>tiger1.equal?(tiger2)</TT>. | |
33190 | Note that the two Ruby objects are not the same - but they reference | |
33191 | the same underlying C++ object. This can cause problems. For example: | |
33192 | <BR></P> | |
33193 | <DIV class="code"> | |
33194 | <PRE>irb(main):010:0> | |
33195 | <!--span style="font-weight: bold;"--> | |
33196 | tiger1 = nil | |
33197 | <BR>=> nil | |
33198 | <BR> | |
33199 | <BR>irb(main):011:0> | |
33200 | <!--span style="font-weight: bold;"--> | |
33201 | GC.start | |
33202 | <BR>=> nil | |
33203 | <BR> | |
33204 | <BR>irb(main):012:0> | |
33205 | <!--span style="font-weight: bold;"--> | |
33206 | tiger2.get_name() | |
33207 | <BR>(irb):12: [BUG] Segmentation fault | |
33208 | <BR> | |
33209 | </PRE> | |
33210 | </DIV> | |
33211 | <P>After the the garbage collector runs, as a result of our call to <TT> | |
33212 | GC.start</TT>, calling<TT>tiger2.get_name()</TT> causes a segmentation | |
33213 | fault. The problem is that when <TT>tiger1</TT> is garbage collected, | |
33214 | it frees the underlying C++ object. Thus, when <TT>tiger2</TT> calls | |
33215 | the <TT>get_name()</TT> method it invokes it on a destroyed object.</P> | |
33216 | <P>This problem can be avoided if SWIG enforces a one-to-one mapping | |
33217 | between Ruby objects and C++ classes. This can be done via the use of | |
33218 | the <TT>%trackobjects</TT> functionality available in SWIG-1.3.26. and | |
33219 | later.</P> | |
33220 | <P>When the <TT>%trackobjects</TT> is turned on, SWIG automatically | |
33221 | keeps track of mappings between C++ objects and Ruby objects. Note that | |
33222 | enabling object tracking causes a slight performance degradation. Test | |
33223 | results show this degradation to be about 3% to 5% when creating and | |
33224 | destroying 100,000 animals in a row.</P> | |
33225 | <P>Since <TT>%trackobjects</TT> is implemented as a <TT>%feature</TT>, | |
33226 | it uses the same name matching rules as other kinds of features (see | |
33227 | the chapter on <A href="#Customization"> "Customization Features"</A>) | |
33228 | . Thus it can be applied on a class-by-class basis if needed. To fix | |
33229 | the example above:</P> | |
33230 | <BR><DIV class="code"> | |
33231 | <PRE>%module example | |
33232 | <BR> | |
33233 | <BR>%{ | |
33234 | <BR>#include "example.h" | |
33235 | <BR>%} | |
33236 | <BR> | |
33237 | <BR> | |
33238 | <!--span style="font-weight: bold;"--> | |
33239 | /* Tell SWIG that create_animal creates a new object */ | |
33240 | <BR> | |
33241 | <!--span style="font-weight: bold;"--> | |
33242 | %newobject Zoo::create_animal; | |
33243 | <BR> | |
33244 | <BR> | |
33245 | <!--span style="font-weight: bold;"--> | |
33246 | /* Tell SWIG to keep track of mappings between C/C++ structs/classes. */ | |
33247 | <BR style="font-weight: bold;"> | |
33248 | <!--span style="font-weight: bold;"--> | |
33249 | %trackobjects; | |
33250 | <BR> | |
33251 | <BR>%include "example.h"</PRE> | |
33252 | </DIV> | |
33253 | <P>When this code runs we see: | |
33254 | <BR> | |
33255 | <BR></P> | |
33256 | <DIV class="code"> | |
33257 | <PRE>$ | |
33258 | <!--span style="font-weight: bold;"--> | |
33259 | irb | |
33260 | <BR>irb(main):001:0> | |
33261 | <!--span style="font-weight: bold;"--> | |
33262 | require 'example' | |
33263 | <BR>=> true | |
33264 | <BR> | |
33265 | <BR>irb(main):002:0> | |
33266 | <!--span style="font-weight: bold;"--> | |
33267 | tiger1 = Example::Animal.new("tiger1") | |
33268 | <BR>=> #<Example::Animal:0x2be37d8> | |
33269 | <BR> | |
33270 | <BR>irb(main):003:0> | |
33271 | <!--span style="font-weight: bold;"--> | |
33272 | zoo = Example::Zoo.new() | |
33273 | <BR>=> #<Example::Zoo:0x2be0a18> | |
33274 | <BR> | |
33275 | <BR>irb(main):004:0> | |
33276 | <!--span style="font-weight: bold;"--> | |
33277 | zoo.add_animal(tiger1) | |
33278 | <BR>=> nil | |
33279 | <BR> | |
33280 | <BR>irb(main):006:0> | |
33281 | <!--span style="font-weight: bold;"--> | |
33282 | tiger2 = zoo.remove_animal(0) | |
33283 | <BR>=> #<Example::Animal:0x2be37d8> | |
33284 | <BR> | |
33285 | <BR>irb(main):007:0> | |
33286 | <!--span style="font-weight: bold;"--> | |
33287 | tiger1.equal?(tiger2) | |
33288 | <BR>=> true | |
33289 | <BR> | |
33290 | <BR>irb(main):008:0> | |
33291 | <!--span style="font-weight: bold;"--> | |
33292 | tiger1 = nil | |
33293 | <BR>=> nil | |
33294 | <BR> | |
33295 | <BR>irb(main):009:0> | |
33296 | <!--span style="font-weight: bold;"--> | |
33297 | GC.start | |
33298 | <BR>=> nil | |
33299 | <BR> | |
33300 | <BR>irb(main):010:0> | |
33301 | <!--span style="font-weight: bold;"--> | |
33302 | tiger.get_name() | |
33303 | <BR>=> "tiger1" | |
33304 | <BR>irb(main):011:0> | |
33305 | <BR> | |
33306 | </PRE> | |
33307 | </DIV> | |
33308 | <P>For those who are interested, object tracking is implemented by | |
33309 | storing Ruby objects in a hash table and keying them on C++ pointers. | |
33310 | The underlying API is: | |
33311 | <BR></P> | |
33312 | <DIV class="code"> | |
33313 | <PRE>static void SWIG_RubyAddTracking(void* ptr, VALUE object); | |
33314 | <BR>static VALUE SWIG_RubyInstanceFor(void* ptr) ; | |
33315 | <BR>static void SWIG_RubyRemoveTracking(void* ptr); | |
33316 | <BR>static void SWIG_RubyUnlinkObjects(void* ptr);</PRE> | |
33317 | </DIV> | |
33318 | <P>When an object is created, SWIG will automatically call the <TT> | |
33319 | SWIG_RubyAddTracking</TT> method. Similarly, when an object is deleted, | |
33320 | SWIG will call the <TT>SWIG_RubyRemoveTracking</TT>. When an object is | |
33321 | returned to Ruby from C++, SWIG will use the <TT>SWIG_RubyInstanceFor</TT> | |
33322 | method to ensure a one-to-one mapping from Ruby to C++ objects. Last, | |
33323 | the <TT>RubyUnlinkObjects</TT> method unlinks a Ruby object from its | |
33324 | underlying C++ object.</P> | |
33325 | <P>In general, you will only need to use the <TT>SWIG_RubyInstanceFor</TT> | |
33326 | , which is required for implementing mark functions as shown below. | |
33327 | However, if you implement your own free functions (see below) you may | |
33328 | also have to call the<TT>SWIG_RubyRemoveTracking</TT> and <TT> | |
33329 | RubyUnlinkObjects</TT> methods.</P> | |
33330 | <H3><A name="Ruby_nn55"></A>27.8.3 Mark Functions</H3> | |
33331 | <P>With a bit more testing, we see that our class library still has | |
33332 | problems. For example: | |
33333 | <BR></P> | |
33334 | <DIV class="code"> | |
33335 | <PRE>$ <B>irb</B> | |
33336 | <BR>irb(main):001:0> | |
33337 | <!--span style="font-weight: bold;"--> | |
33338 | require 'example' | |
33339 | <BR>=> true | |
33340 | <BR> | |
33341 | <BR>irb(main):002:0> tiger1 = | |
33342 | <!--span style="font-weight: bold;"--> | |
33343 | Example::Animal.new("tiger1") | |
33344 | <BR>=> #<Example::Animal:0x2bea6a8> | |
33345 | <BR> | |
33346 | <BR>irb(main):003:0> zoo = | |
33347 | <!--span style="font-weight: bold;"--> | |
33348 | Example::Zoo.new() | |
33349 | <BR>=> #<Example::Zoo:0x2be7960> | |
33350 | <BR> | |
33351 | <BR>irb(main):004:0> | |
33352 | <!--span style="font-weight: bold;"--> | |
33353 | zoo.add_animal(tiger1) | |
33354 | <BR>=> nil | |
33355 | <BR> | |
33356 | <BR>irb(main):007:0> | |
33357 | <!--span style="font-weight: bold;"--> | |
33358 | tiger1 = nil | |
33359 | <BR>=> nil | |
33360 | <BR> | |
33361 | <BR>irb(main):007:0> | |
33362 | <!--span style="font-weight: bold;"--> | |
33363 | GC.start | |
33364 | <BR>=> nil | |
33365 | <BR> | |
33366 | <BR>irb(main):005:0> | |
33367 | <!--span style="font-weight: bold;"--> | |
33368 | tiger2 = zoo.get_animal(0) | |
33369 | <BR>(irb):12: [BUG] Segmentation fault</PRE> | |
33370 | </DIV> | |
33371 | <P>The problem is that Ruby does not know that the <TT>zoo</TT> object | |
33372 | contains a reference to a Ruby object. Thus, when Ruby garbage collects | |
33373 | <!--span style="font-family: monospace;"--> | |
33374 | tiger1 it frees the underlying C++ object.</P> | |
33375 | <P>This can be fixed by implementing a <TT>mark</TT> function as | |
33376 | described above in the <A href="#Ruby_nn52">Mark and Sweep Garbage | |
33377 | Collector</A> section. You can specify a mark function by using the <TT> | |
33378 | %markfunc</TT> directive. Since the <TT>%markfunc</TT> directive is | |
33379 | implemented using SWIG's' "features" mechanism it uses the same name | |
33380 | matching rules as other kinds of features (see the chapter on <A href="#Customization"> | |
33381 | "Customization Features"</A> for more details).</P> | |
33382 | <P>A <TT>mark</TT> function takes a single argument, which is a pointer | |
33383 | to the C++ object being marked; it should, in turn, call <TT> | |
33384 | rb_gc_mark()</TT> for any instances that are reachable from the current | |
33385 | object. The mark function for our <TT> Zoo</TT> class should therefore | |
33386 | loop over all of the C++ animal objects in the zoo object, look up | |
33387 | their Ruby object equivalent, and then call <TT>rb_gc_mark()</TT>. One | |
33388 | possible implementation is:</P> | |
33389 | <DIV class="code"> | |
33390 | <PRE>%module example | |
33391 | <BR> | |
33392 | <BR>%{ | |
33393 | <BR>#include "example.h" | |
33394 | <BR>%} | |
33395 | <BR> | |
33396 | <BR>/* Keep track of mappings between C/C++ structs/classes | |
33397 | <BR> and Ruby objects so we can implement a mark function. */ | |
33398 | <BR> | |
33399 | <!--span style="font-weight: bold;"--> | |
33400 | %trackobjects; | |
33401 | <BR> | |
33402 | <BR>/* Specify the mark function */ | |
33403 | <BR> | |
33404 | <!--span style="font-weight: bold;"--> | |
33405 | %markfunc Zoo "mark_Zoo"; | |
33406 | <BR> | |
33407 | <BR>%include "example.h" | |
33408 | <BR> | |
33409 | <BR>%header %{ | |
33410 | <BR> | |
33411 | <BR>static void mark_Zoo(void* ptr) { | |
33412 | <BR> Zoo* zoo = (Zoo*) ptr; | |
33413 | <BR> | |
33414 | <BR> /* Loop over each object and tell the garbage collector | |
33415 | <BR> that we are holding a reference to them. */ | |
33416 | <BR> int count = zoo->get_num_animals(); | |
33417 | <BR> | |
33418 | <BR> for(int i = 0; i < count; ++i) { | |
33419 | <BR> Animal* animal = zoo->get_animal(i); | |
33420 | <BR> VALUE object = SWIG_RubyInstanceFor(animal); | |
33421 | <BR> | |
33422 | <BR> if (object != Qnil) { | |
33423 | <BR> rb_gc_mark(object); | |
33424 | <BR> } | |
33425 | <BR> } | |
33426 | <BR>} | |
33427 | <BR>%} | |
33428 | <BR> | |
33429 | </PRE> | |
33430 | </DIV> | |
33431 | <P> Note the <TT>mark</TT> function is dependent on the <TT> | |
33432 | SWIG_RUBY_InstanceFor</TT> method, and thus requires that <TT> | |
33433 | %trackobjects</TT> is enabled. For more information, please refer to the | |
33434 | track_object.i test case in the SWIG test suite.</P> | |
33435 | <P>When this code is compiled we now see:</P> | |
33436 | <DIV class="code"> | |
33437 | <PRE>$ <B>irb | |
33438 | <BR></B>irb(main):002:0> | |
33439 | <!--span style="font-weight: bold;"--> | |
33440 | tiger1=Example::Animal.new("tiger1") | |
33441 | <BR>=> #<Example::Animal:0x2be3bf8> | |
33442 | <BR> | |
33443 | <BR>irb(main):003:0> | |
33444 | <!--span style="font-weight: bold;"--> | |
33445 | Example::Zoo.new() | |
33446 | <BR>=> #<Example::Zoo:0x2be1780> | |
33447 | <BR> | |
33448 | <BR>irb(main):004:0> | |
33449 | <!--span style="font-weight: bold;"--> | |
33450 | zoo = Example::Zoo.new() | |
33451 | <BR>=> #<Example::Zoo:0x2bde9c0> | |
33452 | <BR> | |
33453 | <BR>irb(main):005:0> | |
33454 | <!--span style="font-weight: bold;"--> | |
33455 | zoo.add_animal(tiger1) | |
33456 | <BR>=> nil | |
33457 | <BR> | |
33458 | <BR>irb(main):009:0> | |
33459 | <!--span style="font-weight: bold;"--> | |
33460 | tiger1 = nil | |
33461 | <BR>=> nil | |
33462 | <BR> | |
33463 | <BR>irb(main):010:0> | |
33464 | <!--span style="font-weight: bold;"--> | |
33465 | GC.start | |
33466 | <BR>=> nil | |
33467 | <BR>irb(main):014:0> | |
33468 | <!--span style="font-weight: bold;"--> | |
33469 | tiger2 = zoo.get_animal(0) | |
33470 | <BR>=> #<Example::Animal:0x2be3bf8> | |
33471 | <BR> | |
33472 | <BR>irb(main):015:0> | |
33473 | <!--span style="font-weight: bold;"--> | |
33474 | tiger2.get_name() | |
33475 | <BR>=> "tiger1" | |
33476 | <BR>irb(main):016:0> | |
33477 | <BR> | |
33478 | </PRE> | |
33479 | </DIV> | |
33480 | <BR> | |
33481 | <P>This code can be seen in swig/examples/ruby/mark_function.</P> | |
33482 | <H3><A name="Ruby_nn56"></A>27.8.4 Free Functions</H3> | |
33483 | <P>By default, SWIG creates a "free" function that is called when a Ruby | |
33484 | object is garbage collected. The free function simply calls the C++ | |
33485 | object's destructor.</P> | |
33486 | <P>However, sometimes an appropriate destructor does not exist or | |
33487 | special processing needs to be performed before the destructor is | |
33488 | called. Therefore, SWIG allows you to manually specify a "free" | |
33489 | function via the use of the <TT>%freefunc</TT> directive. The <TT> | |
33490 | %freefunc</TT> directive is implemented using SWIG's' "features" | |
33491 | mechanism and so the same name matching rules used for other kinds of | |
33492 | features apply (see the chapter on <A href="#Customization"> | |
33493 | "Customization Features"</A>) for more details).</P> | |
33494 | <P>IMPORTANT ! - If you define your own free function, then you must | |
33495 | ensure that you call the underlying C++ object's destructor. In | |
33496 | addition, if object tracking is activated for the object's class, you | |
33497 | must also call the <TT>SWIG_RubyRemoveTracking</TT> function (of course | |
33498 | call this before you destroy the C++ object). Note that it is harmless | |
33499 | to call this method if object tracking if off so it is advised to | |
33500 | always call it.</P> | |
33501 | <P>Note there is a subtle interaction between object ownership and free | |
33502 | functions. A custom defined free function will only be called if the | |
33503 | Ruby object owns the underlying C++ object. This also to Ruby objects | |
33504 | which are created, but then transfer ownership to C++ objects via the | |
33505 | use of the <TT>disown</TT> typemap described above.</P> | |
33506 | <P>To show how to use the <TT>%freefunc</TT> directive, let's slightly | |
33507 | change our example. Assume that the zoo object is responsible for | |
33508 | freeing animal that it contains. This means that the | |
33509 | <!--span style="font-family: monospace;"--> | |
33510 | Zoo::add_animal function should be marked with a | |
33511 | <!--span style="font-family: monospace;"--> | |
33512 | DISOWN typemap and the destructor should be updated as below::</P> | |
33513 | <DIV class="code"> | |
33514 | <PRE>Zoo::~Zoo() { | |
33515 | <BR> IterType iter = this->animals.begin(); | |
33516 | <BR> IterType end = this->animals.end(); | |
33517 | <BR> | |
33518 | <BR> for(iter; iter != end; ++iter) { | |
33519 | <BR> Animal* animal = *iter; | |
33520 | <BR> delete animal; | |
33521 | <BR> } | |
33522 | <BR>}</PRE> | |
33523 | </DIV> | |
33524 | <P>When we use these objects in IRB we see:</P> | |
33525 | <DIV class="code"> | |
33526 | <PRE> | |
33527 | <!--span style="font-weight: bold;"--> | |
33528 | $irb | |
33529 | <BR>irb(main):002:0> | |
33530 | <!--span style="font-weight: bold;"--> | |
33531 | require 'example' | |
33532 | <BR>=> true | |
33533 | <BR> | |
33534 | <BR>irb(main):003:0> | |
33535 | <!--span style="font-weight: bold;"--> | |
33536 | zoo = Example::Zoo.new() | |
33537 | <BR>=> #<Example::Zoo:0x2be0fe8> | |
33538 | <BR> | |
33539 | <BR>irb(main):005:0> | |
33540 | <!--span style="font-weight: bold;"--> | |
33541 | tiger1 = Example::Animal.new("tiger1") | |
33542 | <BR>=> #<Example::Animal:0x2bda760> | |
33543 | <BR> | |
33544 | <BR>irb(main):006:0> | |
33545 | <!--span style="font-weight: bold;"--> | |
33546 | zoo.add_animal(tiger1) | |
33547 | <BR>=> nil | |
33548 | <BR> | |
33549 | <BR>irb(main):007:0> | |
33550 | <!--span style="font-weight: bold;"--> | |
33551 | zoo = nil | |
33552 | <BR>=> nil | |
33553 | <BR> | |
33554 | <BR>irb(main):008:0> | |
33555 | <!--span style="font-weight: bold;"--> | |
33556 | GC.start | |
33557 | <BR>=> nil | |
33558 | <BR> | |
33559 | <BR>irb(main):009:0> | |
33560 | <!--span style="font-weight: bold;"--> | |
33561 | tiger1.get_name() | |
33562 | <BR>(irb):12: [BUG] Segmentation fault | |
33563 | <BR> | |
33564 | </PRE> | |
33565 | </DIV> | |
33566 | <P>The error happens because the C++ <TT>animal</TT> object is freed | |
33567 | when the <TT>zoo</TT> object is freed. Although this error is | |
33568 | unavoidable, we can at least prevent the segmentation fault. To do this | |
33569 | requires enabling object tracking and implementing a custom free | |
33570 | function that calls the <TT>SWIG_RubyUnlinkObjects</TT> function for | |
33571 | each animal object that is destroyed. The <TT>SWIG_RubyUnlinkObjects</TT> | |
33572 | function notifies SWIG that a Ruby object's underlying C++ object is no | |
33573 | longer valid. Once notified, SWIG will intercept any calls from the | |
33574 | existing Ruby object to the destroyed C++ object and raise an | |
33575 | exception. | |
33576 | <BR></P> | |
33577 | <DIV class="code"> | |
33578 | <PRE>%module example | |
33579 | <BR> | |
33580 | <BR>%{ | |
33581 | <BR>#include "example.h" | |
33582 | <BR>%} | |
33583 | <BR> | |
33584 | <BR>/* Specify that ownership is transferred to the zoo | |
33585 | <BR> when calling add_animal */ | |
33586 | <BR>%apply SWIGTYPE *DISOWN { Animal* animal }; | |
33587 | <BR> | |
33588 | <BR>/* Track objects */ | |
33589 | <BR>%trackobjects; | |
33590 | <BR> | |
33591 | <BR>/* Specify the mark function */ | |
33592 | <BR>%freefunc Zoo "free_Zoo"; | |
33593 | <BR> | |
33594 | <BR>%include "example.h" | |
33595 | <BR> | |
33596 | <BR>%header %{ | |
33597 | <BR> static void free_Zoo(void* ptr) { | |
33598 | <BR> Zoo* zoo = (Zoo*) ptr; | |
33599 | <BR> | |
33600 | <BR> /* Loop over each animal */ | |
33601 | <BR> int count = zoo->get_num_animals(); | |
33602 | <BR> | |
33603 | <BR> for(int i = 0; i < count; ++i) { | |
33604 | <BR> /* Get an animal */ | |
33605 | <BR> Animal* animal = zoo->get_animal(i); | |
33606 | <BR> | |
33607 | <BR> /* Unlink the Ruby object from the C++ object */ | |
33608 | <BR> SWIG_RubyUnlinkObjects(animal); | |
33609 | <BR> | |
33610 | <BR> /* Now remove the tracking for this animal */ | |
33611 | <BR> SWIG_RubyRemoveTracking(animal); | |
33612 | <BR> } | |
33613 | <BR> | |
33614 | <BR> /* Now call SWIG_RemoveMapping for the zoo */ | |
33615 | <BR> SWIG_RemoveMapping(ptr); | |
33616 | <BR> | |
33617 | <BR> /* Now free the zoo which will free the animals it contains */ | |
33618 | <BR> delete zoo; | |
33619 | <BR> } | |
33620 | <BR>%} </PRE> | |
33621 | </DIV> | |
33622 | <P>Now when we use these objects in IRB we see:</P> | |
33623 | <DIV class="code"> | |
33624 | <PRE> | |
33625 | <!--span style="font-weight: bold;"--> | |
33626 | $irb | |
33627 | <BR>irb(main):002:0> | |
33628 | <!--span style="font-weight: bold;"--> | |
33629 | require 'example' | |
33630 | <BR>=> true | |
33631 | <BR> | |
33632 | <BR>irb(main):003:0> | |
33633 | <!--span style="font-weight: bold;"--> | |
33634 | zoo = Example::Zoo.new() | |
33635 | <BR>=> #<Example::Zoo:0x2be0fe8> | |
33636 | <BR> | |
33637 | <BR>irb(main):005:0> | |
33638 | <!--span style="font-weight: bold;"--> | |
33639 | tiger1 = Example::Animal.new("tiger1") | |
33640 | <BR>=> #<Example::Animal:0x2bda760> | |
33641 | <BR> | |
33642 | <BR>irb(main):006:0> | |
33643 | <!--span style="font-weight: bold;"--> | |
33644 | zoo.add_animal(tiger1) | |
33645 | <BR>=> nil | |
33646 | <BR> | |
33647 | <BR>irb(main):007:0> | |
33648 | <!--span style="font-weight: bold;"--> | |
33649 | zoo = nil | |
33650 | <BR>=> nil | |
33651 | <BR> | |
33652 | <BR>irb(main):008:0> | |
33653 | <!--span style="font-weight: bold;"--> | |
33654 | GC.start | |
33655 | <BR>=> nil | |
33656 | <BR> | |
33657 | <BR>irb(main):009:0> | |
33658 | <!--span style="font-weight: bold;"--> | |
33659 | tiger1.get_name() | |
33660 | <BR>RuntimeError: This Animal * already released | |
33661 | <BR> from (irb):10:in `get_name' | |
33662 | <BR> from (irb):10 | |
33663 | <BR>irb(main):011:0></PRE> | |
33664 | </DIV> | |
33665 | <P>Notice that SWIG can now detect the underlying C++ object has been | |
33666 | freed, and thus raises a runtime exception.</P> | |
33667 | <P>This code can be seen in swig/examples/ruby/free_function.</P> | |
33668 | <HR NOSHADE> | |
33669 | <H1><A name="Tcl"></A>28 SWIG and Tcl</H1> | |
33670 | ||
33671 | <!-- INDEX --> | |
33672 | <DIV class="sectiontoc"> | |
33673 | <UL> | |
33674 | <LI><A href="#Tcl_nn2">Preliminaries</A> | |
33675 | <UL> | |
33676 | <LI><A href="#Tcl_nn3">Getting the right header files</A></LI> | |
33677 | <LI><A href="#Tcl_nn4">Compiling a dynamic module</A></LI> | |
33678 | <LI><A href="#Tcl_nn5">Static linking</A></LI> | |
33679 | <LI><A href="#Tcl_nn6">Using your module</A></LI> | |
33680 | <LI><A href="#Tcl_nn7">Compilation of C++ extensions</A></LI> | |
33681 | <LI><A href="#Tcl_nn8">Compiling for 64-bit platforms</A></LI> | |
33682 | <LI><A href="#Tcl_nn9">Setting a package prefix</A></LI> | |
33683 | <LI><A href="#Tcl_nn10">Using namespaces</A></LI> | |
33684 | </UL> | |
33685 | </LI> | |
33686 | <LI><A href="#Tcl_nn11">Building Tcl/Tk Extensions under Windows 95/NT</A> | |
33687 | <UL> | |
33688 | <LI><A href="#Tcl_nn12">Running SWIG from Developer Studio</A></LI> | |
33689 | <LI><A href="#Tcl_nn13">Using NMAKE</A></LI> | |
33690 | </UL> | |
33691 | </LI> | |
33692 | <LI><A href="#Tcl_nn14">A tour of basic C/C++ wrapping</A> | |
33693 | <UL> | |
33694 | <LI><A href="#Tcl_nn15">Modules</A></LI> | |
33695 | <LI><A href="#Tcl_nn16">Functions</A></LI> | |
33696 | <LI><A href="#Tcl_nn17">Global variables</A></LI> | |
33697 | <LI><A href="#Tcl_nn18">Constants and enums</A></LI> | |
33698 | <LI><A href="#Tcl_nn19">Pointers</A></LI> | |
33699 | <LI><A href="#Tcl_nn20">Structures</A></LI> | |
33700 | <LI><A href="#Tcl_nn21">C++ classes</A></LI> | |
33701 | <LI><A href="#Tcl_nn22">C++ inheritance</A></LI> | |
33702 | <LI><A href="#Tcl_nn23">Pointers, references, values, and arrays</A></LI> | |
33703 | <LI><A href="#Tcl_nn24">C++ overloaded functions</A></LI> | |
33704 | <LI><A href="#Tcl_nn25">C++ operators</A></LI> | |
33705 | <LI><A href="#Tcl_nn26">C++ namespaces</A></LI> | |
33706 | <LI><A href="#Tcl_nn27">C++ templates</A></LI> | |
33707 | <LI><A href="#Tcl_nn28">C++ Smart Pointers</A></LI> | |
33708 | </UL> | |
33709 | </LI> | |
33710 | <LI><A href="#Tcl_nn29">Further details on the Tcl class interface</A> | |
33711 | <UL> | |
33712 | <LI><A href="#Tcl_nn30">Proxy classes</A></LI> | |
33713 | <LI><A href="#Tcl_nn31">Memory management</A></LI> | |
33714 | </UL> | |
33715 | </LI> | |
33716 | <LI><A href="#Tcl_nn32">Input and output parameters</A></LI> | |
33717 | <LI><A href="#Tcl_nn33">Exception handling</A></LI> | |
33718 | <LI><A href="#Tcl_nn34">Typemaps</A> | |
33719 | <UL> | |
33720 | <LI><A href="#Tcl_nn35">What is a typemap?</A></LI> | |
33721 | <LI><A href="#Tcl_nn36">Tcl typemaps</A></LI> | |
33722 | <LI><A href="#Tcl_nn37">Typemap variables</A></LI> | |
33723 | <LI><A href="#Tcl_nn38">Converting a Tcl list to a char **</A></LI> | |
33724 | <LI><A href="#Tcl_nn39">Returning values in arguments</A></LI> | |
33725 | <LI><A href="#Tcl_nn40">Useful functions</A></LI> | |
33726 | <LI><A href="#Tcl_nn41">Standard typemaps</A></LI> | |
33727 | <LI><A href="#Tcl_nn42">Pointer handling</A></LI> | |
33728 | </UL> | |
33729 | </LI> | |
33730 | <LI><A href="#Tcl_nn43">Turning a SWIG module into a Tcl Package.</A></LI> | |
33731 | <LI><A href="#Tcl_nn44">Building new kinds of Tcl interfaces (in Tcl)</A> | |
33732 | <UL> | |
33733 | <LI><A href="#Tcl_nn45">Proxy classes</A></LI> | |
33734 | </UL> | |
33735 | </LI> | |
33736 | </UL> | |
33737 | </DIV> | |
33738 | <!-- INDEX --> | |
33739 | <P><B> Caution: This chapter is under repair!</B></P> | |
33740 | <P> This chapter discusses SWIG's support of Tcl. SWIG currently | |
33741 | requires Tcl 8.0 or a later release. Earlier releases of SWIG supported | |
33742 | Tcl 7.x, but this is no longer supported.</P> | |
33743 | <H2><A name="Tcl_nn2"></A>28.1 Preliminaries</H2> | |
33744 | <P> To build a Tcl module, run SWIG using the <TT>-tcl</TT> option :</P> | |
33745 | <DIV class="code"> | |
33746 | <PRE> | |
33747 | $ swig -tcl example.i | |
33748 | </PRE> | |
33749 | </DIV> | |
33750 | <P> If building a C++ extension, add the <TT>-c++</TT> option:</P> | |
33751 | <DIV class="code"> | |
33752 | <PRE> | |
33753 | $ swig -c++ -tcl example.i | |
33754 | </PRE> | |
33755 | </DIV> | |
33756 | <P> This creates a file <TT>example_wrap.c</TT> or <TT>example_wrap.cxx</TT> | |
33757 | that contains all of the code needed to build a Tcl extension module. | |
33758 | To finish building the module, you need to compile this file and link | |
33759 | it with the rest of your program.</P> | |
33760 | <H3><A name="Tcl_nn3"></A>28.1.1 Getting the right header files</H3> | |
33761 | <P> In order to compile the wrapper code, the compiler needs the <TT> | |
33762 | tcl.h</TT> header file. This file is usually contained in the directory</P> | |
33763 | <DIV class="code"> | |
33764 | <PRE> | |
33765 | /usr/local/include | |
33766 | </PRE> | |
33767 | </DIV> | |
33768 | <P> Be aware that some Tcl versions install this header file with a | |
33769 | version number attached to it. If this is the case, you should probably | |
33770 | make a symbolic link so that <TT>tcl.h</TT> points to the correct | |
33771 | header file.</P> | |
33772 | <H3><A name="Tcl_nn4"></A>28.1.2 Compiling a dynamic module</H3> | |
33773 | <P> The preferred approach to building an extension module is to compile | |
33774 | it into a shared object file or DLL. To do this, you will need to | |
33775 | compile your program using comands like this (shown for Linux):</P> | |
33776 | <DIV class="code"> | |
33777 | <PRE> | |
33778 | $ swig -tcl example.i | |
33779 | $ gcc -c example.c | |
33780 | $ gcc -c example_wrap.c -I/usr/local/include | |
33781 | $ gcc -shared example.o example_wrap.o -o example.so | |
33782 | </PRE> | |
33783 | </DIV> | |
33784 | <P> The exact commands for doing this vary from platform to platform. | |
33785 | SWIG tries to guess the right options when it is installed. Therefore, | |
33786 | you may want to start with one of the examples in the <TT> | |
33787 | SWIG/Examples/tcl</TT> directory. If that doesn't work, you will need to | |
33788 | read the man-pages for your compiler and linker to get the right set of | |
33789 | options. You might also check the <A href="http://swig.cs.uchicago.edu/cgi-bin/wiki.pl"> | |
33790 | SWIG Wiki</A> for additional information.</P> | |
33791 | <P> When linking the module, the name of the output file has to match | |
33792 | the name of the module. If the name of your SWIG module is "<TT>example</TT> | |
33793 | ", the name of the corresponding object file should be "<TT>example.so</TT> | |
33794 | ". The name of the module is specified using the <TT>%module</TT> | |
33795 | directive or the <TT>-module</TT> command line option.</P> | |
33796 | <H3><A name="Tcl_nn5"></A>28.1.3 Static linking</H3> | |
33797 | <P> An alternative approach to dynamic linking is to rebuild the Tcl | |
33798 | interpreter with your extension module added to it. In the past, this | |
33799 | approach was sometimes necesssary due to limitations in dynamic loading | |
33800 | support on certain machines. However, the situation has improved | |
33801 | greatly over the last few years and you should not consider this | |
33802 | approach unless there is really no other option.</P> | |
33803 | <P> The usual procedure for adding a new module to Tcl involves writing | |
33804 | a special function <TT>Tcl_AppInit()</TT> and using it to initialize | |
33805 | the interpreter and your module. With SWIG, the <TT>tclsh.i</TT> and <TT> | |
33806 | wish.i</TT> library files can be used to rebuild the <TT>tclsh</TT> and <TT> | |
33807 | wish</TT> interpreters respectively. For example:</P> | |
33808 | <DIV class="code"> | |
33809 | <PRE> | |
33810 | %module example | |
33811 | ||
33812 | %inline %{ | |
33813 | extern int fact(int); | |
33814 | extern int mod(int, int); | |
33815 | extern double My_variable; | |
33816 | %} | |
33817 | ||
33818 | %include tclsh.i // Include code for rebuilding tclsh | |
33819 | ||
33820 | </PRE> | |
33821 | </DIV> | |
33822 | <P> The <TT>tclsh.i</TT> library file includes supporting code that | |
33823 | contains everything needed to rebuild tclsh. To rebuild the | |
33824 | interpreter, you simply do something like this:</P> | |
33825 | <DIV class="code"> | |
33826 | <PRE> | |
33827 | $ swig -tcl example.i | |
33828 | $ gcc example.c example_wrap.c \ | |
33829 | -Xlinker -export-dynamic \ | |
33830 | -DHAVE_CONFIG_H -I/usr/local/include/ \ | |
33831 | -L/usr/local/lib -ltcl -lm -ldl \ | |
33832 | -o mytclsh | |
33833 | ||
33834 | </PRE> | |
33835 | </DIV> | |
33836 | <P> You will need to supply the same libraries that were used to build | |
33837 | Tcl the first time. This may include system libraries such as <TT> | |
33838 | -lsocket</TT>, <TT>-lnsl</TT>, and <TT>-lpthread</TT>. If this actually | |
33839 | works, the new version of Tcl should be identical to the default | |
33840 | version except that your extension module will be a built-in part of | |
33841 | the interpreter.</P> | |
33842 | <P><B> Comment:</B> In practice, you should probably try to avoid static | |
33843 | linking if possible. Some programmers may be inclined to use static | |
33844 | linking in the interest of getting better performance. However, the | |
33845 | performance gained by static linking tends to be rather minimal in most | |
33846 | situations (and quite frankly not worth the extra hassle in the opinion | |
33847 | of this author).</P> | |
33848 | <H3><A name="Tcl_nn6"></A>28.1.4 Using your module</H3> | |
33849 | <P> To use your module, simply use the Tcl <TT>load</TT> command. If all | |
33850 | goes well, you will be able to this:</P> | |
33851 | <DIV class="code"> | |
33852 | <PRE> | |
33853 | $ tclsh | |
33854 | % load ./example.so | |
33855 | % fact 4 | |
33856 | 24 | |
33857 | % | |
33858 | </PRE> | |
33859 | </DIV> | |
33860 | <P> A common error received by first-time users is the following:</P> | |
33861 | <DIV class="code"> | |
33862 | <PRE> | |
33863 | % load ./example.so | |
33864 | couldn't find procedure Example_Init | |
33865 | % | |
33866 | </PRE> | |
33867 | </DIV> | |
33868 | <P> This error is almost always caused when the name of the shared | |
33869 | object file doesn't match the name of the module supplied using the | |
33870 | SWIG <TT>%module</TT> directive. Double-check the interface to make | |
33871 | sure the module name and the shared object file match. Another possible | |
33872 | cause of this error is forgetting to link the SWIG-generated wrapper | |
33873 | code with the rest of your application when creating the extension | |
33874 | module.</P> | |
33875 | <P> Another common error is something similar to the following:</P> | |
33876 | <DIV class="code"> | |
33877 | <PRE> | |
33878 | % load ./example.so | |
33879 | couldn't load file "./example.so": ./example.so: undefined symbol: fact | |
33880 | % | |
33881 | </PRE> | |
33882 | </DIV> | |
33883 | <P> This error usually indicates that you forgot to include some object | |
33884 | files or libraries in the linking of the shared library file. Make sure | |
33885 | you compile both the SWIG wrapper file and your original program into a | |
33886 | shared library file. Make sure you pass all of the required libraries | |
33887 | to the linker.</P> | |
33888 | <P> Sometimes unresolved symbols occur because a wrapper has been | |
33889 | created for a function that doesn't actually exist in a library. This | |
33890 | usually occurs when a header file includes a declaration for a function | |
33891 | that was never actually implemented or it was removed from a library | |
33892 | without updating the header file. To fix this, you can either edit the | |
33893 | SWIG input file to remove the offending declaration or you can use the <TT> | |
33894 | %ignore</TT> directive to ignore the declaration.</P> | |
33895 | <P> Finally, suppose that your extension module is linked with another | |
33896 | library like this:</P> | |
33897 | <DIV class="code"> | |
33898 | <PRE> | |
33899 | $ gcc -shared example.o example_wrap.o -L/home/beazley/projects/lib -lfoo \ | |
33900 | -o example.so | |
33901 | </PRE> | |
33902 | </DIV> | |
33903 | <P> If the <TT>foo</TT> library is compiled as a shared library, you | |
33904 | might get the following problem when you try to use your module:</P> | |
33905 | <DIV class="code"> | |
33906 | <PRE> | |
33907 | % load ./example.so | |
33908 | couldn't load file "./example.so": libfoo.so: cannot open shared object file: | |
33909 | No such file or directory | |
33910 | % | |
33911 | </PRE> | |
33912 | </DIV> | |
33913 | <P> This error is generated because the dynamic linker can't locate the <TT> | |
33914 | libfoo.so</TT> library. When shared libraries are loaded, the system | |
33915 | normally only checks a few standard locations such as <TT>/usr/lib</TT> | |
33916 | and <TT>/usr/local/lib</TT>. To fix this problem, there are several | |
33917 | things you can do. First, you can recompile your extension module with | |
33918 | extra path information. For example, on Linux you can do this:</P> | |
33919 | <DIV class="code"> | |
33920 | <PRE> | |
33921 | $ gcc -shared example.o example_wrap.o -L/home/beazley/projects/lib -lfoo \ | |
33922 | -Xlinker -rpath /home/beazley/projects/lib \ | |
33923 | -o example.so | |
33924 | </PRE> | |
33925 | </DIV> | |
33926 | <P> Alternatively, you can set the <TT>LD_LIBRARY_PATH</TT> environment | |
33927 | variable to include the directory with your shared libraries. If | |
33928 | setting <TT>LD_LIBRARY_PATH</TT>, be aware that setting this variable | |
33929 | can introduce a noticeable performance impact on all other applications | |
33930 | that you run. To set it only for Tcl, you might want to do this | |
33931 | instead:</P> | |
33932 | <DIV class="code"> | |
33933 | <PRE> | |
33934 | $ env LD_LIBRARY_PATH=/home/beazley/projects/lib tclsh | |
33935 | </PRE> | |
33936 | </DIV> | |
33937 | <P> Finally, you can use a command such as <TT>ldconfig</TT> to add | |
33938 | additional search paths to the default system configuration (this | |
33939 | requires root access and you will need to read the man pages).</P> | |
33940 | <H3><A name="Tcl_nn7"></A>28.1.5 Compilation of C++ extensions</H3> | |
33941 | <P> Compilation of C++ extensions has traditionally been a tricky | |
33942 | problem. Since the Tcl interpreter is written in C, you need to take | |
33943 | steps to make sure C++ is properly initialized and that modules are | |
33944 | compiled correctly.</P> | |
33945 | <P> On most machines, C++ extension modules should be linked using the | |
33946 | C++ compiler. For example:</P> | |
33947 | <DIV class="code"> | |
33948 | <PRE> | |
33949 | % swig -c++ -tcl example.i | |
33950 | % g++ -c example.cxx | |
33951 | % g++ -c example_wrap.cxx -I/usr/local/include | |
33952 | % g++ -shared example.o example_wrap.o -o example.so | |
33953 | </PRE> | |
33954 | </DIV> | |
33955 | <P> In addition to this, you may need to include additional library | |
33956 | files to make it work. For example, if you are using the Sun C++ | |
33957 | compiler on Solaris, you often need to add an extra library <TT>-lCrun</TT> | |
33958 | like this:</P> | |
33959 | <DIV class="code"> | |
33960 | <PRE> | |
33961 | % swig -c++ -tcl example.i | |
33962 | % CC -c example.cxx | |
33963 | % CC -c example_wrap.cxx -I/usr/local/include | |
33964 | % CC -G example.o example_wrap.o -L/opt/SUNWspro/lib -o example.so -lCrun | |
33965 | </PRE> | |
33966 | </DIV> | |
33967 | <P> Of course, the extra libraries to use are completely | |
33968 | non-portable---you will probably need to do some experimentation.</P> | |
33969 | <P> Sometimes people have suggested that it is necessary to relink the | |
33970 | Tcl interpreter using the C++ compiler to make C++ extension modules | |
33971 | work. In the experience of this author, this has never actually | |
33972 | appeared to be necessary. Relinking the interpreter with C++ really | |
33973 | only includes the special run-time libraries described above---as long | |
33974 | as you link your extension modules with these libraries, it should not | |
33975 | be necessary to rebuild Tcl.</P> | |
33976 | <P> If you aren't entirely sure about the linking of a C++ extension, | |
33977 | you might look at an existing C++ program. On many Unix machines, the <TT> | |
33978 | ldd</TT> command will list library dependencies. This should give you | |
33979 | some clues about what you might have to include when you link your | |
33980 | extension module. For example:</P> | |
33981 | <DIV class="code"> | |
33982 | <PRE> | |
33983 | $ ldd swig | |
33984 | libstdc++-libc6.1-1.so.2 => /usr/lib/libstdc++-libc6.1-1.so.2 (0x40019000) | |
33985 | libm.so.6 => /lib/libm.so.6 (0x4005b000) | |
33986 | libc.so.6 => /lib/libc.so.6 (0x40077000) | |
33987 | /lib/ld-linux.so.2 => /lib/ld-linux.so.2 (0x40000000) | |
33988 | $ | |
33989 | </PRE> | |
33990 | </DIV> | |
33991 | <P> As a final complication, a major weakness of C++ is that it does not | |
33992 | define any sort of standard for binary linking of libraries. This means | |
33993 | that C++ code compiled by different compilers will not link together | |
33994 | properly as libraries nor is the memory layout of classes and data | |
33995 | structures implemented in any kind of portable manner. In a monolithic | |
33996 | C++ program, this problem may be unnoticed. However, in Tcl, it is | |
33997 | possible for different extension modules to be compiled with different | |
33998 | C++ compilers. As long as these modules are self-contained, this | |
33999 | probably won't matter. However, if these modules start sharing data, | |
34000 | you will need to take steps to avoid segmentation faults and other | |
34001 | erratic program behavior. If working with lots of software components, | |
34002 | you might want to investigate using a more formal standard such as COM.</P> | |
34003 | <H3><A name="Tcl_nn8"></A>28.1.6 Compiling for 64-bit platforms</H3> | |
34004 | <P> On platforms that support 64-bit applications (Solaris, Irix, etc.), | |
34005 | special care is required when building extension modules. On these | |
34006 | machines, 64-bit applications are compiled and linked using a different | |
34007 | set of compiler/linker options. In addition, it is not generally | |
34008 | possible to mix 32-bit and 64-bit code together in the same | |
34009 | application.</P> | |
34010 | <P> To utilize 64-bits, the Tcl executable will need to be recompiled as | |
34011 | a 64-bit application. In addition, all libraries, wrapper code, and | |
34012 | every other part of your application will need to be compiled for | |
34013 | 64-bits. If you plan to use other third-party extension modules, they | |
34014 | will also have to be recompiled as 64-bit extensions.</P> | |
34015 | <P> If you are wrapping commercial software for which you have no source | |
34016 | code, you will be forced to use the same linking standard as used by | |
34017 | that software. This may prevent the use of 64-bit extensions. It may | |
34018 | also introduce problems on platforms that support more than one linking | |
34019 | standard (e.g., -o32 and -n32 on Irix).</P> | |
34020 | <H3><A name="Tcl_nn9"></A>28.1.7 Setting a package prefix</H3> | |
34021 | <P> To avoid namespace problems, you can instruct SWIG to append a | |
34022 | package prefix to all of your functions and variables. This is done | |
34023 | using the -prefix option as follows :</P> | |
34024 | <DIV class="code"> | |
34025 | <PRE> | |
34026 | swig -tcl -prefix Foo example.i | |
34027 | </PRE> | |
34028 | </DIV> | |
34029 | <P> If you have a function "<TT>bar</TT>" in the SWIG file, the prefix | |
34030 | option will append the prefix to the name when creating a command and | |
34031 | call it "<TT>Foo_bar</TT>".</P> | |
34032 | <H3><A name="Tcl_nn10"></A>28.1.8 Using namespaces</H3> | |
34033 | <P> Alternatively, you can have SWIG install your module into a Tcl | |
34034 | namespace by specifying the <TT>-namespace</TT> option :</P> | |
34035 | <DIV class="code"> | |
34036 | <PRE> | |
34037 | swig -tcl -namespace example.i | |
34038 | </PRE> | |
34039 | </DIV> | |
34040 | <P> By default, the name of the namespace will be the same as the module | |
34041 | name, but you can override it using the <TT>-prefix</TT> option.</P> | |
34042 | <P> When the <TT>-namespace</TT> option is used, objects in the module | |
34043 | are always accessed with the namespace name such as <TT>Foo::bar</TT>.</P> | |
34044 | <H2><A name="Tcl_nn11"></A>28.2 Building Tcl/Tk Extensions under Windows | |
34045 | 95/NT</H2> | |
34046 | <P> Building a SWIG extension to Tcl/Tk under Windows 95/NT is roughly | |
34047 | similar to the process used with Unix. Normally, you will want to | |
34048 | produce a DLL that can be loaded into tclsh or wish. This section | |
34049 | covers the process of using SWIG with Microsoft Visual C++. although | |
34050 | the procedure may be similar with other compilers.</P> | |
34051 | <H3><A name="Tcl_nn12"></A>28.2.1 Running SWIG from Developer Studio</H3> | |
34052 | <P> If you are developing your application within Microsoft developer | |
34053 | studio, SWIG can be invoked as a custom build option. The process | |
34054 | roughly follows these steps :</P> | |
34055 | <UL> | |
34056 | <LI>Open up a new workspace and use the AppWizard to select a DLL | |
34057 | project.</LI> | |
34058 | <LI>Add both the SWIG interface file (the .i file), any supporting C | |
34059 | files, and the name of the wrapper file that will be created by SWIG | |
34060 | (ie. <TT>example_wrap.c</TT>). Note : If using C++, choose a different | |
34061 | suffix for the wrapper file such as <TT>example_wrap.cxx</TT>. Don't | |
34062 | worry if the wrapper file doesn't exist yet--Developer studio will keep | |
34063 | a reference to it around.</LI> | |
34064 | <LI>Select the SWIG interface file and go to the settings menu. Under | |
34065 | settings, select the "Custom Build" option.</LI> | |
34066 | <LI>Enter "SWIG" in the description field.</LI> | |
34067 | <LI>Enter "<TT>swig -tcl -o $(ProjDir)\$(InputName)_wrap.c $(InputPath)</TT> | |
34068 | " in the "Build command(s) field"</LI> | |
34069 | <LI>Enter "<TT>$(ProjDir)\$(InputName)_wrap.c</TT>" in the "Output | |
34070 | files(s) field".</LI> | |
34071 | <LI>Next, select the settings for the entire project and go to | |
34072 | "C++:Preprocessor". Add the include directories for your Tcl | |
34073 | installation under "Additional include directories".</LI> | |
34074 | <LI>Finally, select the settings for the entire project and go to "Link | |
34075 | Options". Add the Tcl library file to your link libraries. For example | |
34076 | "<TT>tcl80.lib</TT>". Also, set the name of the output file to match | |
34077 | the name of your Tcl module (ie. example.dll).</LI> | |
34078 | <LI>Build your project.</LI> | |
34079 | </UL> | |
34080 | <P> Now, assuming all went well, SWIG will be automatically invoked when | |
34081 | you build your project. Any changes made to the interface file will | |
34082 | result in SWIG being automatically invoked to produce a new version of | |
34083 | the wrapper file. To run your new Tcl extension, simply run <TT>tclsh</TT> | |
34084 | or <TT>wish</TT> and use the <TT>load</TT> command. For example :</P> | |
34085 | <DIV class="code"> | |
34086 | <PRE> | |
34087 | MSDOS > tclsh80 | |
34088 | % load example.dll | |
34089 | % fact 4 | |
34090 | 24 | |
34091 | % | |
34092 | </PRE> | |
34093 | </DIV> | |
34094 | <H3><A name="Tcl_nn13"></A>28.2.2 Using NMAKE</H3> | |
34095 | <P> Alternatively, SWIG extensions can be built by writing a Makefile | |
34096 | for NMAKE. To do this, make sure the environment variables for MSVC++ | |
34097 | are available and the MSVC++ tools are in your path. Now, just write a | |
34098 | short Makefile like this :</P> | |
34099 | <DIV class="code"> | |
34100 | <PRE> | |
34101 | # Makefile for building various SWIG generated extensions | |
34102 | ||
34103 | SRCS = example.c | |
34104 | IFILE = example | |
34105 | INTERFACE = $(IFILE).i | |
34106 | WRAPFILE = $(IFILE)_wrap.c | |
34107 | ||
34108 | # Location of the Visual C++ tools (32 bit assumed) | |
34109 | ||
34110 | TOOLS = c:\msdev | |
34111 | TARGET = example.dll | |
34112 | CC = $(TOOLS)\bin\cl.exe | |
34113 | LINK = $(TOOLS)\bin\link.exe | |
34114 | INCLUDE32 = -I$(TOOLS)\include | |
34115 | MACHINE = IX86 | |
34116 | ||
34117 | # C Library needed to build a DLL | |
34118 | ||
34119 | DLLIBC = msvcrt.lib oldnames.lib | |
34120 | ||
34121 | # Windows libraries that are apparently needed | |
34122 | WINLIB = kernel32.lib advapi32.lib user32.lib gdi32.lib comdlg32.lib | |
34123 | winspool.lib | |
34124 | ||
34125 | # Libraries common to all DLLs | |
34126 | LIBS = $(DLLIBC) $(WINLIB) | |
34127 | ||
34128 | # Linker options | |
34129 | LOPT = -debug:full -debugtype:cv /NODEFAULTLIB /RELEASE /NOLOGO / | |
34130 | MACHINE:$(MACHINE) -entry:_DllMainCRTStartup@12 -dll | |
34131 | ||
34132 | # C compiler flags | |
34133 | ||
34134 | CFLAGS = /Z7 /Od /c /nologo | |
34135 | TCL_INCLUDES = -Id:\tcl8.0a2\generic -Id:\tcl8.0a2\win | |
34136 | TCLLIB = d:\tcl8.0a2\win\tcl80.lib | |
34137 | ||
34138 | tcl:: | |
34139 | ..\..\swig -tcl -o $(WRAPFILE) $(INTERFACE) | |
34140 | $(CC) $(CFLAGS) $(TCL_INCLUDES) $(SRCS) $(WRAPFILE) | |
34141 | set LIB=$(TOOLS)\lib | |
34142 | $(LINK) $(LOPT) -out:example.dll $(LIBS) $(TCLLIB) example.obj example_wrap.obj | |
34143 | ||
34144 | </PRE> | |
34145 | </DIV> | |
34146 | <P> To build the extension, run NMAKE (you may need to run vcvars32 | |
34147 | first). This is a pretty minimal Makefile, but hopefully its enough to | |
34148 | get you started. With a little practice, you'll be making lots of Tcl | |
34149 | extensions.</P> | |
34150 | <H2><A name="Tcl_nn14"></A>28.3 A tour of basic C/C++ wrapping</H2> | |
34151 | <P> By default, SWIG tries to build a very natural Tcl interface to your | |
34152 | C/C++ code. Functions are wrapped as functions, classes are wrapped in | |
34153 | an interface that mimics the style of Tk widgets and [incr Tcl] | |
34154 | classes. This section briefly covers the essential aspects of this | |
34155 | wrapping.</P> | |
34156 | <H3><A name="Tcl_nn15"></A>28.3.1 Modules</H3> | |
34157 | <P> The SWIG <TT>%module</TT> directive specifies the name of the Tcl | |
34158 | module. If you specify `<TT>%module example</TT>', then everything is | |
34159 | compiled into an extension module <TT>example.so</TT>. When choosing a | |
34160 | module name, make sure you don't use the same name as a built-in Tcl | |
34161 | command.</P> | |
34162 | <P> One pitfall to watch out for is module names involving numbers. If | |
34163 | you specify a module name like <TT>%module md5</TT>, you'll find that | |
34164 | the load command no longer seems to work:</P> | |
34165 | <DIV class="code"> | |
34166 | <PRE> | |
34167 | % load ./md5.so | |
34168 | couldn't find procedure Md_Init | |
34169 | </PRE> | |
34170 | </DIV> | |
34171 | <P> To fix this, supply an extra argument to <TT>load</TT> like this:</P> | |
34172 | <DIV class="code"> | |
34173 | <PRE> | |
34174 | % load ./md5.so md5 | |
34175 | </PRE> | |
34176 | </DIV> | |
34177 | <H3><A name="Tcl_nn16"></A>28.3.2 Functions</H3> | |
34178 | <P> Global functions are wrapped as new Tcl built-in commands. For | |
34179 | example,</P> | |
34180 | <DIV class="code"> | |
34181 | <PRE> | |
34182 | %module example | |
34183 | int fact(int n); | |
34184 | </PRE> | |
34185 | </DIV> | |
34186 | <P> creates a built-in function <TT>fact</TT> that works exactly like | |
34187 | you think it does:</P> | |
34188 | <DIV class="code"> | |
34189 | <PRE> | |
34190 | % load ./example.so | |
34191 | % fact 4 | |
34192 | 24 | |
34193 | % set x [fact 6] | |
34194 | % | |
34195 | </PRE> | |
34196 | </DIV> | |
34197 | <H3><A name="Tcl_nn17"></A>28.3.3 Global variables</H3> | |
34198 | <P> C/C++ global variables are wrapped by Tcl global variables. For | |
34199 | example:</P> | |
34200 | <DIV class="code"> | |
34201 | <PRE> | |
34202 | // SWIG interface file with global variables | |
34203 | %module example | |
34204 | ... | |
34205 | %inline %{ | |
34206 | extern double density; | |
34207 | %} | |
34208 | ... | |
34209 | </PRE> | |
34210 | </DIV> | |
34211 | <P> Now look at the Tcl interface:</P> | |
34212 | <DIV class="code"> | |
34213 | <PRE> | |
34214 | % puts $density # Output value of C global variable | |
34215 | 1.0 | |
34216 | % set density 0.95 # Change value | |
34217 | </PRE> | |
34218 | </DIV> | |
34219 | <P> If you make an error in variable assignment, you will get an error | |
34220 | message. For example:</P> | |
34221 | <DIV class="code"> | |
34222 | <PRE> | |
34223 | % set density "hello" | |
34224 | can't set "density": Type error. expected a double. | |
34225 | % | |
34226 | </PRE> | |
34227 | </DIV> | |
34228 | <P> If a variable is declared as <TT>const</TT>, it is wrapped as a | |
34229 | read-only variable. Attempts to modify its value will result in an | |
34230 | error.</P> | |
34231 | <P> To make ordinary variables read-only, you can use the <TT>%immutable</TT> | |
34232 | directive. For example:</P> | |
34233 | <DIV class="code"> | |
34234 | <PRE> | |
34235 | %{ | |
34236 | extern char *path; | |
34237 | %} | |
34238 | %immutable; | |
34239 | extern char *path; | |
34240 | %mutable; | |
34241 | </PRE> | |
34242 | </DIV> | |
34243 | <P> The <TT>%immutable</TT> directive stays in effect until it is | |
34244 | explicitly disabled or cleared using <TT>%mutable</TT>. See the <A href="#SWIG_readonly_variables"> | |
34245 | Creatng read-only variables</A> section for further details.</P> | |
34246 | <P> If you just want to make a specific variable immutable, supply a | |
34247 | declaration name. For example:</P> | |
34248 | <DIV class="code"> | |
34249 | <PRE> | |
34250 | %{ | |
34251 | extern char *path; | |
34252 | %} | |
34253 | %immutable path; | |
34254 | ... | |
34255 | extern char *path; // Read-only (due to %immutable) | |
34256 | </PRE> | |
34257 | </DIV> | |
34258 | <H3><A name="Tcl_nn18"></A>28.3.4 Constants and enums</H3> | |
34259 | <P> C/C++ constants are installed as global Tcl variables containing the | |
34260 | appropriate value. To create a constant, use <TT>#define</TT>, <TT>enum</TT> | |
34261 | , or the <TT>%constant</TT> directive. For example:</P> | |
34262 | <DIV class="code"> | |
34263 | <PRE> | |
34264 | #define PI 3.14159 | |
34265 | #define VERSION "1.0" | |
34266 | ||
34267 | enum Beverage { ALE, LAGER, STOUT, PILSNER }; | |
34268 | ||
34269 | %constant int FOO = 42; | |
34270 | %constant const char *path = "/usr/local"; | |
34271 | </PRE> | |
34272 | </DIV> | |
34273 | <P> For enums, make sure that the definition of the enumeration actually | |
34274 | appears in a header file or in the wrapper file somehow---if you just | |
34275 | stick an enum in a SWIG interface without also telling the C compiler | |
34276 | about it, the wrapper code won't compile.</P> | |
34277 | <P> Note: declarations declared as <TT>const</TT> are wrapped as | |
34278 | read-only variables and will be accessed using the <TT>cvar</TT> object | |
34279 | described in the previous section. They are not wrapped as constants. | |
34280 | For further discussion about this, see the <A href="#SWIG">SWIG Basics</A> | |
34281 | chapter.</P> | |
34282 | <P> Constants are not guaranteed to remain constant in Tcl---the value | |
34283 | of the constant could be accidentally reassigned.You will just have to | |
34284 | be careful.</P> | |
34285 | <P> A peculiarity of installing constants as variables is that it is | |
34286 | necessary to use the Tcl <TT>global</TT> statement to access constants | |
34287 | in procedure bodies. For example:</P> | |
34288 | <DIV class="code"> | |
34289 | <PRE> | |
34290 | proc blah {} { | |
34291 | global FOO | |
34292 | bar $FOO | |
34293 | } | |
34294 | </PRE> | |
34295 | </DIV> | |
34296 | <P> If a program relies on a lot of constants, this can be extremely | |
34297 | annoying. To fix the problem, consider using the following typemap | |
34298 | rule:</P> | |
34299 | <DIV class="code"> | |
34300 | <PRE> | |
34301 | %apply int CONSTANT { int x }; | |
34302 | #define FOO 42 | |
34303 | ... | |
34304 | void bar(int x); | |
34305 | </PRE> | |
34306 | </DIV> | |
34307 | <P> When applied to an input argument, the <TT>CONSTANT</TT> rule allows | |
34308 | a constant to be passed to a function using its actual value or a | |
34309 | symbolic identifier name. For example:</P> | |
34310 | <DIV class="code"> | |
34311 | <PRE> | |
34312 | proc blah {} { | |
34313 | bar FOO | |
34314 | } | |
34315 | </PRE> | |
34316 | </DIV> | |
34317 | <P> When an identifier name is given, it is used to perform an implicit | |
34318 | hash-table lookup of the value during argument conversion. This allows | |
34319 | the <TT>global</TT> statement to be ommitted.</P> | |
34320 | <H3><A name="Tcl_nn19"></A>28.3.5 Pointers</H3> | |
34321 | <P> C/C++ pointers are fully supported by SWIG. Furthermore, SWIG has no | |
34322 | problem working with incomplete type information. Here is a rather | |
34323 | simple interface:</P> | |
34324 | <DIV class="code"> | |
34325 | <PRE> | |
34326 | %module example | |
34327 | ||
34328 | FILE *fopen(const char *filename, const char *mode); | |
34329 | int fputs(const char *, FILE *); | |
34330 | int fclose(FILE *); | |
34331 | </PRE> | |
34332 | </DIV> | |
34333 | <P> When wrapped, you will be able to use the functions in a natural way | |
34334 | from Tcl. For example:</P> | |
34335 | <DIV class="code"> | |
34336 | <PRE> | |
34337 | % load ./example.so | |
34338 | % set f [fopen junk w] | |
34339 | % fputs "Hello World\n" $f | |
34340 | % fclose $f | |
34341 | </PRE> | |
34342 | </DIV> | |
34343 | <P> If this makes you uneasy, rest assured that there is no deep magic | |
34344 | involved. Underneath the covers, pointers to C/C++ objects are simply | |
34345 | represented as opaque values--normally an encoded character string like | |
34346 | this:</P> | |
34347 | <DIV class="code"> | |
34348 | <PRE> | |
34349 | % puts $f | |
34350 | _c0671108_p_FILE | |
34351 | % | |
34352 | </PRE> | |
34353 | </DIV> | |
34354 | <P> This pointer value can be freely passed around to different C | |
34355 | functions that expect to receive an object of type <TT>FILE *</TT>. The | |
34356 | only thing you can't do is dereference the pointer from Tcl.</P> | |
34357 | <P> The NULL pointer is represented by the string <TT>NULL</TT>.</P> | |
34358 | <P> As much as you might be inclined to modify a pointer value directly | |
34359 | from Tcl, don't. The hexadecimal encoding is not necessarily the same | |
34360 | as the logical memory address of the underlying object. Instead it is | |
34361 | the raw byte encoding of the pointer value. The encoding will vary | |
34362 | depending on the native byte-ordering of the platform (i.e., big-endian | |
34363 | vs. little-endian). Similarly, don't try to manually cast a pointer to | |
34364 | a new type by simply replacing the type-string. This may not work like | |
34365 | you expect and it is particularly dangerous when casting C++ objects. | |
34366 | If you need to cast a pointer or change its value, consider writing | |
34367 | some helper functions instead. For example:</P> | |
34368 | <DIV class="code"> | |
34369 | <PRE> | |
34370 | %inline %{ | |
34371 | /* C-style cast */ | |
34372 | Bar *FooToBar(Foo *f) { | |
34373 | return (Bar *) f; | |
34374 | } | |
34375 | ||
34376 | /* C++-style cast */ | |
34377 | Foo *BarToFoo(Bar *b) { | |
34378 | return dynamic_cast<Foo*>(b); | |
34379 | } | |
34380 | ||
34381 | Foo *IncrFoo(Foo *f, int i) { | |
34382 | return f+i; | |
34383 | } | |
34384 | %} | |
34385 | </PRE> | |
34386 | </DIV> | |
34387 | <P> Also, if working with C++, you should always try to use the new C++ | |
34388 | style casts. For example, in the above code, the C-style cast may | |
34389 | return a bogus result whereas as the C++-style cast will return <TT> | |
34390 | None</TT> if the conversion can't be performed.</P> | |
34391 | <H3><A name="Tcl_nn20"></A>28.3.6 Structures</H3> | |
34392 | <P> If you wrap a C structure, it is wrapped by a Tcl interface that | |
34393 | somewhat resembles a Tk widget. This provides a very natural interface. | |
34394 | For example,</P> | |
34395 | <DIV class="code"> | |
34396 | <PRE> | |
34397 | struct Vector { | |
34398 | double x,y,z; | |
34399 | }; | |
34400 | ||
34401 | </PRE> | |
34402 | </DIV> | |
34403 | <P> is used as follows:</P> | |
34404 | <DIV class="code"> | |
34405 | <PRE> | |
34406 | % Vector v | |
34407 | % v configure -x 3.5 -y 7.2 | |
34408 | % puts "[v cget -x] [v cget -y] [v cget -z]" | |
34409 | 3.5 7.2 0.0 | |
34410 | % | |
34411 | </PRE> | |
34412 | </DIV> | |
34413 | <P> Similar access is provided for unions and the data members of C++ | |
34414 | classes.</P> | |
34415 | <P> In the above example, <TT>v</TT> is a name that's used for the | |
34416 | object. However, underneath the covers, there's a pointer to a raw C | |
34417 | structure. This can be obtained by looking at the <TT>-this</TT> | |
34418 | attribute. For example:</P> | |
34419 | <DIV class="code"> | |
34420 | <PRE> | |
34421 | % puts [v cget -this] | |
34422 | _88e31408_p_Vector | |
34423 | </PRE> | |
34424 | </DIV> | |
34425 | <P> Further details about the relationship between the Tcl and the | |
34426 | underlying C structure are covered a little later.</P> | |
34427 | <P> <TT>const</TT> members of a structure are read-only. Data members | |
34428 | can also be forced to be read-only using the <TT>%immutable</TT> | |
34429 | directive. For example:</P> | |
34430 | <DIV class="code"> | |
34431 | <PRE> | |
34432 | struct Foo { | |
34433 | ... | |
34434 | %immutable; | |
34435 | int x; /* Read-only members */ | |
34436 | char *name; | |
34437 | %mutable; | |
34438 | ... | |
34439 | }; | |
34440 | </PRE> | |
34441 | </DIV> | |
34442 | <P> When <TT>char *</TT> members of a structure are wrapped, the | |
34443 | contents are assumed to be dynamically allocated using <TT>malloc</TT> | |
34444 | or <TT>new</TT> (depending on whether or not SWIG is run with the -c++ | |
34445 | option). When the structure member is set, the old contents will be | |
34446 | released and a new value created. If this is not the behavior you want, | |
34447 | you will have to use a typemap (described later).</P> | |
34448 | <P> If a structure contains arrays, access to those arrays is managed | |
34449 | through pointers. For example, consider this:</P> | |
34450 | <DIV class="code"> | |
34451 | <PRE> | |
34452 | struct Bar { | |
34453 | int x[16]; | |
34454 | }; | |
34455 | </PRE> | |
34456 | </DIV> | |
34457 | <P> If accessed in Tcl, you will see behavior like this:</P> | |
34458 | <DIV class="code"> | |
34459 | <PRE> | |
34460 | % Bar b | |
34461 | % puts [b cget -x] | |
34462 | _801861a4_p_int | |
34463 | % | |
34464 | </PRE> | |
34465 | </DIV> | |
34466 | <P> This pointer can be passed around to functions that expect to | |
34467 | receive an <TT>int *</TT> (just like C). You can also set the value of | |
34468 | an array member using another pointer. For example:</P> | |
34469 | <DIV class="code"> | |
34470 | <PRE> | |
34471 | % Bar c | |
34472 | % c configure -x [b cget -x] # Copy contents of b.x to c.x | |
34473 | </PRE> | |
34474 | </DIV> | |
34475 | <P> For array assignment, SWIG copies the entire contents of the array | |
34476 | starting with the data pointed to by <TT>b.x</TT>. In this example, 16 | |
34477 | integers would be copied. Like C, SWIG makes no assumptions about | |
34478 | bounds checking---if you pass a bad pointer, you may get a segmentation | |
34479 | fault or access violation.</P> | |
34480 | <P> When a member of a structure is itself a structure, it is handled as | |
34481 | a pointer. For example, suppose you have two structures like this:</P> | |
34482 | <DIV class="code"> | |
34483 | <PRE> | |
34484 | struct Foo { | |
34485 | int a; | |
34486 | }; | |
34487 | ||
34488 | struct Bar { | |
34489 | Foo f; | |
34490 | }; | |
34491 | </PRE> | |
34492 | </DIV> | |
34493 | <P> Now, suppose that you access the <TT>f</TT> attribute of <TT>Bar</TT> | |
34494 | like this:</P> | |
34495 | <DIV class="code"> | |
34496 | <PRE> | |
34497 | % Bar b | |
34498 | % set x [b cget -f] | |
34499 | </PRE> | |
34500 | </DIV> | |
34501 | <P> In this case, <TT>x</TT> is a pointer that points to the <TT>Foo</TT> | |
34502 | that is inside <TT>b</TT>. This is the same value as generated by this | |
34503 | C code:</P> | |
34504 | <DIV class="code"> | |
34505 | <PRE> | |
34506 | Bar b; | |
34507 | Foo *x = &b->f; /* Points inside b */ | |
34508 | </PRE> | |
34509 | </DIV> | |
34510 | <P> However, one peculiarity of accessing a substructure like this is | |
34511 | that the returned value does work quite like you might expect. For | |
34512 | example:</P> | |
34513 | <DIV class="code"> | |
34514 | <PRE> | |
34515 | % Bar b | |
34516 | % set x [b cget -f] | |
34517 | % x cget -a | |
34518 | invalid command name "x" | |
34519 | </PRE> | |
34520 | </DIV> | |
34521 | <P> This is because the returned value was not created in a normal way | |
34522 | from the interpreter (x is not a command object). To make it function | |
34523 | normally, just evaluate the variable like this:</P> | |
34524 | <DIV class="code"> | |
34525 | <PRE> | |
34526 | % Bar b | |
34527 | % set x [b cget -f] | |
34528 | % $x cget -a | |
34529 | 0 | |
34530 | % | |
34531 | </PRE> | |
34532 | </DIV> | |
34533 | <P> In this example, <TT>x</TT> points inside the original structure. | |
34534 | This means that modifications work just like you would expect. For | |
34535 | example:</P> | |
34536 | <DIV class="code"> | |
34537 | <PRE> | |
34538 | ||
34539 | % Bar b | |
34540 | % set x [b cget -f] | |
34541 | % $x configure -a 3 # Modifies contents of f (inside b) | |
34542 | % [b cget -f] -configure -a 3 # Same thing | |
34543 | </PRE> | |
34544 | </DIV> | |
34545 | <P> In many of these structure examples, a simple name like "v" or "b" | |
34546 | has been given to wrapped structures. If necessary, this name can be | |
34547 | passed to functions that expect to receive an object. For example, if | |
34548 | you have a function like this,</P> | |
34549 | <DIV class="code"> | |
34550 | <PRE> | |
34551 | void blah(Foo *f); | |
34552 | </PRE> | |
34553 | </DIV> | |
34554 | <P> you can call the function in Tcl as follows:</P> | |
34555 | <DIV class="code"> | |
34556 | <PRE> | |
34557 | % Foo x # Create a Foo object | |
34558 | % blah x # Pass the object to a function | |
34559 | </PRE> | |
34560 | </DIV> | |
34561 | <P> It is also possible to call the function using the raw pointer | |
34562 | value. For instance:</P> | |
34563 | <DIV class="code"> | |
34564 | <PRE> | |
34565 | % blah [x cget -this] # Pass object to a function | |
34566 | </PRE> | |
34567 | </DIV> | |
34568 | <P> It is also possible to create and use objects using variables. For | |
34569 | example:</P> | |
34570 | <DIV class="code"> | |
34571 | <PRE> | |
34572 | % set b [Bar] # Create a Bar | |
34573 | % $b cget -f # Member access | |
34574 | % puts $b | |
34575 | _108fea88_p_Bar | |
34576 | % | |
34577 | </PRE> | |
34578 | </DIV> | |
34579 | <P> Finally, to destroy objects created from Tcl, you can either let the | |
34580 | object name go out of scope or you can explicitly delete the object. | |
34581 | For example:</P> | |
34582 | <DIV class="code"> | |
34583 | <PRE> | |
34584 | % Foo f # Create object f | |
34585 | % rename f "" | |
34586 | </PRE> | |
34587 | </DIV> | |
34588 | <P> or</P> | |
34589 | <DIV class="code"> | |
34590 | <PRE> | |
34591 | % Foo f # Create object f | |
34592 | % f -delete | |
34593 | </PRE> | |
34594 | </DIV> | |
34595 | <P> Note: Tcl only destroys the underlying object if it has ownership. | |
34596 | See the memory management section that appears shortly.</P> | |
34597 | <H3><A name="Tcl_nn21"></A>28.3.7 C++ classes</H3> | |
34598 | <P> C++ classes are wrapped as an extension of structure wrapping. For | |
34599 | example, if you have this class,</P> | |
34600 | <DIV class="code"> | |
34601 | <PRE> | |
34602 | class List { | |
34603 | public: | |
34604 | List(); | |
34605 | ~List(); | |
34606 | int search(char *item); | |
34607 | void insert(char *item); | |
34608 | void remove(char *item); | |
34609 | char *get(int n); | |
34610 | int length; | |
34611 | }; | |
34612 | </PRE> | |
34613 | </DIV> | |
34614 | <P> you can use it in Tcl like this:</P> | |
34615 | <DIV class="code"> | |
34616 | <PRE> | |
34617 | % List x | |
34618 | % x insert Ale | |
34619 | % x insert Stout | |
34620 | % x insert Lager | |
34621 | % x get 1 | |
34622 | Stout | |
34623 | % puts [l cget -length] | |
34624 | 3 | |
34625 | % | |
34626 | </PRE> | |
34627 | </DIV> | |
34628 | <P> Class data members are accessed in the same manner as C structures.</P> | |
34629 | <P> Static class members are accessed as global functions or variables. | |
34630 | To illustrate, suppose you have a class like this:</P> | |
34631 | <DIV class="code"> | |
34632 | <PRE> | |
34633 | class Spam { | |
34634 | public: | |
34635 | static void foo(); | |
34636 | static int bar; | |
34637 | ||
34638 | }; | |
34639 | </PRE> | |
34640 | </DIV> | |
34641 | <P> In Tcl, the static member is accessed as follows:</P> | |
34642 | <DIV class="code"> | |
34643 | <PRE> | |
34644 | % Spam_foo # Spam::foo() | |
34645 | % puts $Spam_bar # Spam::bar | |
34646 | </PRE> | |
34647 | </DIV> | |
34648 | <H3><A name="Tcl_nn22"></A>28.3.8 C++ inheritance</H3> | |
34649 | <P> SWIG is fully aware of issues related to C++ inheritance. Therefore, | |
34650 | if you have classes like this</P> | |
34651 | <DIV class="code"> | |
34652 | <PRE> | |
34653 | class Foo { | |
34654 | ... | |
34655 | }; | |
34656 | ||
34657 | class Bar : public Foo { | |
34658 | ... | |
34659 | }; | |
34660 | </PRE> | |
34661 | </DIV> | |
34662 | <P> An object of type <TT>Bar</TT> can be used where a <TT>Foo</TT> is | |
34663 | expected. For example, if you have this function:</P> | |
34664 | <DIV class="code"> | |
34665 | <PRE> | |
34666 | void spam(Foo *f); | |
34667 | </PRE> | |
34668 | </DIV> | |
34669 | <P> then the function <TT>spam()</TT> accepts a <TT>Foo *</TT> or a | |
34670 | pointer to any class derived from <TT>Foo</TT>. For instance:</P> | |
34671 | <DIV class="code"> | |
34672 | <PRE> | |
34673 | % Foo f # Create a Foo | |
34674 | % Bar b # Create a Bar | |
34675 | % spam f # OK | |
34676 | % spam b # OK | |
34677 | </PRE> | |
34678 | </DIV> | |
34679 | <P> It is safe to use multiple inheritance with SWIG.</P> | |
34680 | <H3><A name="Tcl_nn23"></A>28.3.9 Pointers, references, values, and | |
34681 | arrays</H3> | |
34682 | <P> In C++, there are many different ways a function might receive and | |
34683 | manipulate objects. For example:</P> | |
34684 | <DIV class="code"> | |
34685 | <PRE> | |
34686 | void spam1(Foo *x); // Pass by pointer | |
34687 | void spam2(Foo &x); // Pass by reference | |
34688 | void spam3(Foo x); // Pass by value | |
34689 | void spam4(Foo x[]); // Array of objects | |
34690 | </PRE> | |
34691 | </DIV> | |
34692 | <P> In Tcl, there is no detailed distinction like this. Because of this, | |
34693 | SWIG unifies all of these types together in the wrapper code. For | |
34694 | instance, if you actually had the above functions, it is perfectly | |
34695 | legal to do this:</P> | |
34696 | <DIV class="code"> | |
34697 | <PRE> | |
34698 | % Foo f # Create a Foo | |
34699 | % spam1 f # Ok. Pointer | |
34700 | % spam2 f # Ok. Reference | |
34701 | % spam3 f # Ok. Value. | |
34702 | % spam4 f # Ok. Array (1 element) | |
34703 | </PRE> | |
34704 | </DIV> | |
34705 | <P> Similar behavior occurs for return values. For example, if you had | |
34706 | functions like this,</P> | |
34707 | <DIV class="code"> | |
34708 | <PRE> | |
34709 | Foo *spam5(); | |
34710 | Foo &spam6(); | |
34711 | Foo spam7(); | |
34712 | </PRE> | |
34713 | </DIV> | |
34714 | <P> then all three functions will return a pointer to some <TT>Foo</TT> | |
34715 | object. Since the third function (spam7) returns a value, newly | |
34716 | allocated memory is used to hold the result and a pointer is returned | |
34717 | (Tcl will release this memory when the return value is garbage | |
34718 | collected).</P> | |
34719 | <H3><A name="Tcl_nn24"></A>28.3.10 C++ overloaded functions</H3> | |
34720 | <P> C++ overloaded functions, methods, and constructors are mostly | |
34721 | supported by SWIG. For example, if you have two functions like this:</P> | |
34722 | <DIV class="code"> | |
34723 | <PRE> | |
34724 | void foo(int); | |
34725 | void foo(char *c); | |
34726 | </PRE> | |
34727 | </DIV> | |
34728 | <P> You can use them in Tcl in a straightforward manner:</P> | |
34729 | <DIV class="code"> | |
34730 | <PRE> | |
34731 | % foo 3 # foo(int) | |
34732 | % foo Hello # foo(char *c) | |
34733 | </PRE> | |
34734 | </DIV> | |
34735 | <P> Similarly, if you have a class like this,</P> | |
34736 | <DIV class="code"> | |
34737 | <PRE> | |
34738 | class Foo { | |
34739 | public: | |
34740 | Foo(); | |
34741 | Foo(const Foo &); | |
34742 | ... | |
34743 | }; | |
34744 | </PRE> | |
34745 | </DIV> | |
34746 | <P> you can write Tcl code like this:</P> | |
34747 | <DIV class="code"> | |
34748 | <PRE> | |
34749 | % Foo f # Create a Foo | |
34750 | % Foo g f # Copy f | |
34751 | </PRE> | |
34752 | </DIV> | |
34753 | <P> Overloading support is not quite as flexible as in C++. Sometimes | |
34754 | there are methods that SWIG can't disambiguate. For example:</P> | |
34755 | <DIV class="code"> | |
34756 | <PRE> | |
34757 | void spam(int); | |
34758 | void spam(short); | |
34759 | </PRE> | |
34760 | </DIV> | |
34761 | <P> or</P> | |
34762 | <DIV class="code"> | |
34763 | <PRE> | |
34764 | void foo(Bar *b); | |
34765 | void foo(Bar &b); | |
34766 | </PRE> | |
34767 | </DIV> | |
34768 | <P> If declarations such as these appear, you will get a warning message | |
34769 | like this:</P> | |
34770 | <DIV class="code"> | |
34771 | <PRE> | |
34772 | example.i:12: Warning(509): Overloaded spam(short) is shadowed by spam(int) | |
34773 | at example.i:11. | |
34774 | </PRE> | |
34775 | </DIV> | |
34776 | <P> To fix this, you either need to ignore or rename one of the methods. | |
34777 | For example:</P> | |
34778 | <DIV class="code"> | |
34779 | <PRE> | |
34780 | %rename(spam_short) spam(short); | |
34781 | ... | |
34782 | void spam(int); | |
34783 | void spam(short); // Accessed as spam_short | |
34784 | </PRE> | |
34785 | </DIV> | |
34786 | <P> or</P> | |
34787 | <DIV class="code"> | |
34788 | <PRE> | |
34789 | %ignore spam(short); | |
34790 | ... | |
34791 | void spam(int); | |
34792 | void spam(short); // Ignored | |
34793 | </PRE> | |
34794 | </DIV> | |
34795 | <P> SWIG resolves overloaded functions and methods using a | |
34796 | disambiguation scheme that ranks and sorts declarations according to a | |
34797 | set of type-precedence rules. The order in which declarations appear in | |
34798 | the input does not matter except in situations where ambiguity | |
34799 | arises--in this case, the first declaration takes precedence.</P> | |
34800 | <P> Please refer to the "SWIG and C++" chapter for more information | |
34801 | about overloading.</P> | |
34802 | <H3><A name="Tcl_nn25"></A>28.3.11 C++ operators</H3> | |
34803 | <P> Certain C++ overloaded operators can be handled automatically by | |
34804 | SWIG. For example, consider a class like this:</P> | |
34805 | <DIV class="code"> | |
34806 | <PRE> | |
34807 | class Complex { | |
34808 | private: | |
34809 | double rpart, ipart; | |
34810 | public: | |
34811 | Complex(double r = 0, double i = 0) : rpart(r), ipart(i) { } | |
34812 | Complex(const Complex &c) : rpart(c.rpart), ipart(c.ipart) { } | |
34813 | Complex &operator=(const Complex &c); | |
34814 | Complex operator+(const Complex &c) const; | |
34815 | Complex operator-(const Complex &c) const; | |
34816 | Complex operator*(const Complex &c) const; | |
34817 | Complex operator-() const; | |
34818 | ||
34819 | double re() const { return rpart; } | |
34820 | double im() const { return ipart; } | |
34821 | }; | |
34822 | </PRE> | |
34823 | </DIV> | |
34824 | <P> When wrapped, it works like this:</P> | |
34825 | <DIV class="code"> | |
34826 | <PRE> | |
34827 | % Complex c 3 4 | |
34828 | % Complex d 7 8 | |
34829 | % set e [c + d] | |
34830 | % $e re | |
34831 | 10.0 | |
34832 | % $e im | |
34833 | 12.0 | |
34834 | </PRE> | |
34835 | </DIV> | |
34836 | <P> It should be stressed that operators in SWIG have no relationship to | |
34837 | operators in Tcl. In fact, the only thing that's happening here is that | |
34838 | an operator like <TT>operator +</TT> has been renamed to a method <TT>+</TT> | |
34839 | . Therefore, the statement <TT>[c + d]</TT> is really just invoking the <TT> | |
34840 | +</TT> method on <TT>c</TT>. When more than operator is defined (with | |
34841 | different arguments), the standard method overloading facilities are | |
34842 | used. Here is a rather odd looking example:</P> | |
34843 | <DIV class="code"> | |
34844 | <PRE> | |
34845 | % Complex c 3 4 | |
34846 | % Complex d 7 8 | |
34847 | % set e [c - d] # operator-(const Complex &) | |
34848 | % puts "[$e re] [$e im]" | |
34849 | 10.0 12.0 | |
34850 | % set f [c -] # operator-() | |
34851 | % puts "[$f re] [$f im]" | |
34852 | -3.0 -4.0 | |
34853 | % | |
34854 | </PRE> | |
34855 | </DIV> | |
34856 | <P> One restriction with operator overloading support is that SWIG is | |
34857 | not able to fully handle operators that aren't defined as part of the | |
34858 | class. For example, if you had code like this</P> | |
34859 | <DIV class="code"> | |
34860 | <PRE> | |
34861 | class Complex { | |
34862 | ... | |
34863 | friend Complex operator+(double, const Complex &c); | |
34864 | ... | |
34865 | }; | |
34866 | </PRE> | |
34867 | </DIV> | |
34868 | <P> then SWIG doesn't know what to do with the friend function--in fact, | |
34869 | it simply ignores it and issues a warning. You can still wrap the | |
34870 | operator, but you may have to encapsulate it in a special function. For | |
34871 | example:</P> | |
34872 | <DIV class="code"> | |
34873 | <PRE> | |
34874 | %rename(Complex_add_dc) operator+(double, const Complex &); | |
34875 | ... | |
34876 | Complex operator+(double, const Complex &c); | |
34877 | </PRE> | |
34878 | </DIV> | |
34879 | <P> There are ways to make this operator appear as part of the class | |
34880 | using the <TT>%extend</TT> directive. Keep reading.</P> | |
34881 | <H3><A name="Tcl_nn26"></A>28.3.12 C++ namespaces</H3> | |
34882 | <P> SWIG is aware of C++ namespaces, but namespace names do not appear | |
34883 | in the module nor do namespaces result in a module that is broken up | |
34884 | into submodules or packages. For example, if you have a file like this,</P> | |
34885 | <DIV class="code"> | |
34886 | <PRE> | |
34887 | %module example | |
34888 | ||
34889 | namespace foo { | |
34890 | int fact(int n); | |
34891 | struct Vector { | |
34892 | double x,y,z; | |
34893 | }; | |
34894 | }; | |
34895 | </PRE> | |
34896 | </DIV> | |
34897 | <P> it works in Tcl as follows:</P> | |
34898 | <DIV class="code"> | |
34899 | <PRE> | |
34900 | % load ./example.so | |
34901 | % fact 3 | |
34902 | 6 | |
34903 | % Vector v | |
34904 | % v configure -x 3.4 | |
34905 | </PRE> | |
34906 | </DIV> | |
34907 | <P> If your program has more than one namespace, name conflicts (if any) | |
34908 | can be resolved using <TT>%rename</TT> For example:</P> | |
34909 | <DIV class="code"> | |
34910 | <PRE> | |
34911 | %rename(Bar_spam) Bar::spam; | |
34912 | ||
34913 | namespace Foo { | |
34914 | int spam(); | |
34915 | } | |
34916 | ||
34917 | namespace Bar { | |
34918 | int spam(); | |
34919 | } | |
34920 | </PRE> | |
34921 | </DIV> | |
34922 | <P> If you have more than one namespace and your want to keep their | |
34923 | symbols separate, consider wrapping them as separate SWIG modules. For | |
34924 | example, make the module name the same as the namespace and create | |
34925 | extension modules for each namespace separately. If your program | |
34926 | utilizes thousands of small deeply nested namespaces each with | |
34927 | identical symbol names, well, then you get what you deserve.</P> | |
34928 | <H3><A name="Tcl_nn27"></A>28.3.13 C++ templates</H3> | |
34929 | <P> C++ templates don't present a huge problem for SWIG. However, in | |
34930 | order to create wrappers, you have to tell SWIG to create wrappers for | |
34931 | a particular template instantiation. To do this, you use the <TT> | |
34932 | %template</TT> directive. For example:</P> | |
34933 | <DIV class="code"> | |
34934 | <PRE> | |
34935 | %module example | |
34936 | %{ | |
34937 | #include "pair.h" | |
34938 | %} | |
34939 | ||
34940 | template<class T1, class T2> | |
34941 | struct pair { | |
34942 | typedef T1 first_type; | |
34943 | typedef T2 second_type; | |
34944 | T1 first; | |
34945 | T2 second; | |
34946 | pair(); | |
34947 | pair(const T1&, const T2&); | |
34948 | ~pair(); | |
34949 | }; | |
34950 | ||
34951 | %template(pairii) pair<int,int>; | |
34952 | </PRE> | |
34953 | </DIV> | |
34954 | <P> In Tcl:</P> | |
34955 | <DIV class="code"> | |
34956 | <PRE> | |
34957 | % pairii p 3 4 | |
34958 | % p cget -first | |
34959 | 3 | |
34960 | % p cget -second | |
34961 | 4 | |
34962 | </PRE> | |
34963 | </DIV> | |
34964 | <P> Obviously, there is more to template wrapping than shown in this | |
34965 | example. More details can be found in the <A href="#SWIGPlus">SWIG and | |
34966 | C++</A> chapter. Some more complicated examples will appear later.</P> | |
34967 | <H3><A name="Tcl_nn28"></A>28.3.14 C++ Smart Pointers</H3> | |
34968 | <P> In certain C++ programs, it is common to use classes that have been | |
34969 | wrapped by so-called "smart pointers." Generally, this involves the use | |
34970 | of a template class that implements <TT>operator->()</TT> like this:</P> | |
34971 | <DIV class="code"> | |
34972 | <PRE> | |
34973 | template<class T> class SmartPtr { | |
34974 | ... | |
34975 | T *operator->(); | |
34976 | ... | |
34977 | } | |
34978 | </PRE> | |
34979 | </DIV> | |
34980 | <P> Then, if you have a class like this,</P> | |
34981 | <DIV class="code"> | |
34982 | <PRE> | |
34983 | class Foo { | |
34984 | public: | |
34985 | int x; | |
34986 | int bar(); | |
34987 | }; | |
34988 | </PRE> | |
34989 | </DIV> | |
34990 | <P> A smart pointer would be used in C++ as follows:</P> | |
34991 | <DIV class="code"> | |
34992 | <PRE> | |
34993 | SmartPtr<Foo> p = CreateFoo(); // Created somehow (not shown) | |
34994 | ... | |
34995 | p->x = 3; // Foo::x | |
34996 | int y = p->bar(); // Foo::bar | |
34997 | </PRE> | |
34998 | </DIV> | |
34999 | <P> To wrap this in Tcl, simply tell SWIG about the <TT>SmartPtr</TT> | |
35000 | class and the low-level <TT>Foo</TT> object. Make sure you instantiate <TT> | |
35001 | SmartPtr</TT> using <TT>%template</TT> if necessary. For example:</P> | |
35002 | <DIV class="code"> | |
35003 | <PRE> | |
35004 | %module example | |
35005 | ... | |
35006 | %template(SmartPtrFoo) SmartPtr<Foo>; | |
35007 | ... | |
35008 | </PRE> | |
35009 | </DIV> | |
35010 | <P> Now, in Tcl, everything should just "work":</P> | |
35011 | <DIV class="code"> | |
35012 | <PRE> | |
35013 | % set p [CreateFoo] # Create a smart-pointer somehow | |
35014 | % $p configure -x 3 # Foo::x | |
35015 | % $p bar # Foo::bar | |
35016 | </PRE> | |
35017 | </DIV> | |
35018 | <P> If you ever need to access the underlying pointer returned by <TT> | |
35019 | operator->()</TT> itself, simply use the <TT>__deref__()</TT> method. | |
35020 | For example:</P> | |
35021 | <DIV class="code"> | |
35022 | <PRE> | |
35023 | % set f [$p __deref__] # Returns underlying Foo * | |
35024 | </PRE> | |
35025 | </DIV> | |
35026 | <H2><A name="Tcl_nn29"></A>28.4 Further details on the Tcl class | |
35027 | interface</H2> | |
35028 | <P> In the previous section, a high-level view of Tcl wrapping was | |
35029 | presented. A key component of this wrapping is that structures and | |
35030 | classes are wrapped by Tcl class-like objects. This provides a very | |
35031 | natural Tcl interface and allows SWIG to support a number of advanced | |
35032 | features such as operator overloading. However, a number of low-level | |
35033 | details were omitted. This section provides a brief overview of how the | |
35034 | proxy classes work.</P> | |
35035 | <H3><A name="Tcl_nn30"></A>28.4.1 Proxy classes</H3> | |
35036 | <P> In the <A href="#SWIG">"SWIG basics"</A> and <A href="#SWIGPlus"> | |
35037 | "SWIG and C++"</A> chapters, details of low-level structure and class | |
35038 | wrapping are described. To summarize those chapters, if you have a | |
35039 | class like this</P> | |
35040 | <DIV class="code"> | |
35041 | <PRE> | |
35042 | class Foo { | |
35043 | public: | |
35044 | int x; | |
35045 | int spam(int); | |
35046 | ... | |
35047 | </PRE> | |
35048 | </DIV> | |
35049 | <P> then SWIG transforms it into a set of low-level procedural wrappers. | |
35050 | For example:</P> | |
35051 | <DIV class="code"> | |
35052 | <PRE> | |
35053 | Foo *new_Foo() { | |
35054 | return new Foo(); | |
35055 | } | |
35056 | void delete_Foo(Foo *f) { | |
35057 | delete f; | |
35058 | } | |
35059 | int Foo_x_get(Foo *f) { | |
35060 | return f->x; | |
35061 | } | |
35062 | void Foo_x_set(Foo *f, int value) { | |
35063 | f->x = value; | |
35064 | } | |
35065 | int Foo_spam(Foo *f, int arg1) { | |
35066 | return f->spam(arg1); | |
35067 | } | |
35068 | </PRE> | |
35069 | </DIV> | |
35070 | <P> These wrappers are actually found in the Tcl extension module. For | |
35071 | example, you can certainly do this:</P> | |
35072 | <DIV class="code"> | |
35073 | <PRE> | |
35074 | % load ./example.so | |
35075 | % set f [new_Foo] | |
35076 | % Foo_x_get $f | |
35077 | 0 | |
35078 | % Foo_spam $f 3 | |
35079 | 1 | |
35080 | % | |
35081 | </PRE> | |
35082 | </DIV> | |
35083 | <P> However, in addition to this, the classname <TT>Foo</TT> is used as | |
35084 | an object constructor function. This allows objects to be encapsulated | |
35085 | objects that look a lot like Tk widgets as shown in the last section.</P> | |
35086 | <H3><A name="Tcl_nn31"></A>28.4.2 Memory management</H3> | |
35087 | <P> Associated with each wrapped object, is an ownership flag <TT> | |
35088 | thisown</TT> The value of this flag determines who is responsible for | |
35089 | deleting the underlying C++ object. If set to 1, the Tcl interpreter | |
35090 | destroys the C++ object when the proxy class is garbage collected. If | |
35091 | set to 0 (or if the attribute is missing), then the destruction of the | |
35092 | proxy class has no effect on the C++ object.</P> | |
35093 | <P> When an object is created by a constructor or returned by value, Tcl | |
35094 | automatically takes ownership of the result. For example:</P> | |
35095 | <DIV class="code"> | |
35096 | <PRE> | |
35097 | class Foo { | |
35098 | public: | |
35099 | Foo(); | |
35100 | Foo bar(); | |
35101 | }; | |
35102 | </PRE> | |
35103 | </DIV> | |
35104 | <P> In Tcl:</P> | |
35105 | <DIV class="code"> | |
35106 | <PRE> | |
35107 | % Foo f | |
35108 | % f cget -thisown | |
35109 | 1 | |
35110 | % set g [f bar] | |
35111 | % $g cget -thisown | |
35112 | 1 | |
35113 | </PRE> | |
35114 | </DIV> | |
35115 | <P> On the other hand, when pointers are returned to Tcl, there is often | |
35116 | no way to know where they came from. Therefore, the ownership is set to | |
35117 | zero. For example:</P> | |
35118 | <DIV class="code"> | |
35119 | <PRE> | |
35120 | class Foo { | |
35121 | public: | |
35122 | ... | |
35123 | Foo *spam(); | |
35124 | ... | |
35125 | }; | |
35126 | </PRE> | |
35127 | </DIV> | |
35128 | <BR><DIV class="code"> | |
35129 | <PRE> | |
35130 | % Foo f | |
35131 | % set s [f spam] | |
35132 | % $s cget -thisown | |
35133 | 0 | |
35134 | % | |
35135 | </PRE> | |
35136 | </DIV> | |
35137 | <P> This behavior is especially important for classes that act as | |
35138 | containers. For example, if a method returns a pointer to an object | |
35139 | that is contained inside another object, you definitely don't want Tcl | |
35140 | to assume ownership and destroy it!</P> | |
35141 | <P> Related to containers, ownership issues can arise whenever an object | |
35142 | is assigned to a member or global variable. For example, consider this | |
35143 | interface:</P> | |
35144 | <DIV class="code"> | |
35145 | <PRE> | |
35146 | %module example | |
35147 | ||
35148 | struct Foo { | |
35149 | int value; | |
35150 | Foo *next; | |
35151 | }; | |
35152 | ||
35153 | Foo *head = 0; | |
35154 | </PRE> | |
35155 | </DIV> | |
35156 | <P> When wrapped in Tcl, careful observation will reveal that ownership | |
35157 | changes whenever an object is assigned to a global variable. For | |
35158 | example:</P> | |
35159 | <DIV class="code"> | |
35160 | <PRE> | |
35161 | % Foo f | |
35162 | % f cget -thisown | |
35163 | 1 | |
35164 | % set head f | |
35165 | % f cget -thisown | |
35166 | 0 | |
35167 | </PRE> | |
35168 | </DIV> | |
35169 | <P> In this case, C is now holding a reference to the object---you | |
35170 | probably don't want Tcl to destroy it. Similarly, this occurs for | |
35171 | members. For example:</P> | |
35172 | <DIV class="code"> | |
35173 | <PRE> | |
35174 | % Foo f | |
35175 | % Foo g | |
35176 | % f cget -thisown | |
35177 | 1 | |
35178 | % g cget -thisown | |
35179 | 1 | |
35180 | % f configure -next g | |
35181 | % g cget -thisown | |
35182 | 0 | |
35183 | % | |
35184 | </PRE> | |
35185 | </DIV> | |
35186 | <P> For the most part, memory management issues remain hidden. However, | |
35187 | there are occasionally situations where you might have to manually | |
35188 | change the ownership of an object. For instance, consider code like | |
35189 | this:</P> | |
35190 | <DIV class="code"> | |
35191 | <PRE> | |
35192 | class Node { | |
35193 | Object *value; | |
35194 | public: | |
35195 | void set_value(Object *v) { value = v; } | |
35196 | ... | |
35197 | }; | |
35198 | </PRE> | |
35199 | </DIV> | |
35200 | <P> Now, consider the following Tcl code:</P> | |
35201 | <DIV class="code"> | |
35202 | <PRE> | |
35203 | % Object v # Create an object | |
35204 | % Node n # Create a node | |
35205 | % n setvalue v # Set value | |
35206 | % v cget -thisown | |
35207 | 1 | |
35208 | % | |
35209 | </PRE> | |
35210 | </DIV> | |
35211 | <P> In this case, the object <TT>n</TT> is holding a reference to <TT>v</TT> | |
35212 | internally. However, SWIG has no way to know that this has occurred. | |
35213 | Therefore, Tcl still thinks that it has ownership of the object. Should | |
35214 | the proxy object be destroyed, then the C++ destructor will be invoked | |
35215 | and <TT>n</TT> will be holding a stale-pointer. If you're lucky, you | |
35216 | will only get a segmentation fault.</P> | |
35217 | <P> To work around this, it is always possible to flip the ownership | |
35218 | flag. For example,</P> | |
35219 | <DIV class="code"> | |
35220 | <PRE> | |
35221 | % v -disown # Give ownership to C/C++ | |
35222 | % v -acquire # Acquire ownership | |
35223 | </PRE> | |
35224 | </DIV> | |
35225 | <P> It is also possible to deal with situations like this using | |
35226 | typemaps--an advanced topic discussed later.</P> | |
35227 | <H2><A name="Tcl_nn32"></A>28.5 Input and output parameters</H2> | |
35228 | <P> A common problem in some C programs is handling parameters passed as | |
35229 | simple pointers. For example:</P> | |
35230 | <DIV class="code"> | |
35231 | <PRE> | |
35232 | void add(int x, int y, int *result) { | |
35233 | *result = x + y; | |
35234 | } | |
35235 | </PRE> | |
35236 | </DIV> | |
35237 | <P> or perhaps</P> | |
35238 | <DIV class="code"> | |
35239 | <PRE> | |
35240 | int sub(int *x, int *y) { | |
35241 | return *x+*y; | |
35242 | } | |
35243 | </PRE> | |
35244 | </DIV> | |
35245 | <P> The easiest way to handle these situations is to use the <TT> | |
35246 | typemaps.i</TT> file. For example:</P> | |
35247 | <DIV class="code"> | |
35248 | <PRE> | |
35249 | %module example | |
35250 | %include "typemaps.i" | |
35251 | ||
35252 | void add(int, int, int *OUTPUT); | |
35253 | int sub(int *INPUT, int *INPUT); | |
35254 | </PRE> | |
35255 | </DIV> | |
35256 | <P> In Tcl, this allows you to pass simple values instead of pointer. | |
35257 | For example:</P> | |
35258 | <DIV class="code"> | |
35259 | <PRE> | |
35260 | set a [add 3 4] | |
35261 | puts $a | |
35262 | 7 | |
35263 | </PRE> | |
35264 | </DIV> | |
35265 | <P> Notice how the <TT>INPUT</TT> parameters allow integer values to be | |
35266 | passed instead of pointers and how the <TT>OUTPUT</TT> parameter | |
35267 | creates a return result.</P> | |
35268 | <P> If you don't want to use the names <TT>INPUT</TT> or <TT>OUTPUT</TT> | |
35269 | , use the <TT>%apply</TT> directive. For example:</P> | |
35270 | <DIV class="code"> | |
35271 | <PRE> | |
35272 | %module example | |
35273 | %include "typemaps.i" | |
35274 | ||
35275 | %apply int *OUTPUT { int *result }; | |
35276 | %apply int *INPUT { int *x, int *y}; | |
35277 | ||
35278 | void add(int x, int y, int *result); | |
35279 | int sub(int *x, int *y); | |
35280 | </PRE> | |
35281 | </DIV> | |
35282 | <P> If a function mutates one of its parameters like this,</P> | |
35283 | <DIV class="code"> | |
35284 | <PRE> | |
35285 | void negate(int *x) { | |
35286 | *x = -(*x); | |
35287 | } | |
35288 | </PRE> | |
35289 | </DIV> | |
35290 | <P> you can use <TT>INOUT</TT> like this:</P> | |
35291 | <DIV class="code"> | |
35292 | <PRE> | |
35293 | %include "typemaps.i" | |
35294 | ... | |
35295 | void negate(int *INOUT); | |
35296 | </PRE> | |
35297 | </DIV> | |
35298 | <P> In Tcl, a mutated parameter shows up as a return value. For example:</P> | |
35299 | <DIV class="code"> | |
35300 | <PRE> | |
35301 | set a [negate 3] | |
35302 | puts $a | |
35303 | -3 | |
35304 | </PRE> | |
35305 | </DIV> | |
35306 | <P> The most common use of these special typemap rules is to handle | |
35307 | functions that return more than one value. For example, sometimes a | |
35308 | function returns a result as well as a special error code:</P> | |
35309 | <DIV class="code"> | |
35310 | <PRE> | |
35311 | /* send message, return number of bytes sent, along with success code */ | |
35312 | int send_message(char *text, int len, int *success); | |
35313 | </PRE> | |
35314 | </DIV> | |
35315 | <P> To wrap such a function, simply use the <TT>OUTPUT</TT> rule above. | |
35316 | For example:</P> | |
35317 | <DIV class="code"> | |
35318 | <PRE> | |
35319 | %module example | |
35320 | %include "typemaps.i" | |
35321 | %apply int *OUTPUT { int *success }; | |
35322 | ... | |
35323 | int send_message(char *text, int *success); | |
35324 | </PRE> | |
35325 | </DIV> | |
35326 | <P> When used in Tcl, the function will return multiple values as a | |
35327 | list.</P> | |
35328 | <DIV class="code"> | |
35329 | <PRE> | |
35330 | set r [send_message "Hello World"] | |
35331 | set bytes [lindex $r 0] | |
35332 | set success [lindex $r 1] | |
35333 | </PRE> | |
35334 | </DIV> | |
35335 | <P> Another common use of multiple return values are in query functions. | |
35336 | For example:</P> | |
35337 | <DIV class="code"> | |
35338 | <PRE> | |
35339 | void get_dimensions(Matrix *m, int *rows, int *columns); | |
35340 | </PRE> | |
35341 | </DIV> | |
35342 | <P> To wrap this, you might use the following:</P> | |
35343 | <DIV class="code"> | |
35344 | <PRE> | |
35345 | %module example | |
35346 | %include "typemaps.i" | |
35347 | %apply int *OUTPUT { int *rows, int *columns }; | |
35348 | ... | |
35349 | void get_dimensions(Matrix *m, int *rows, *columns); | |
35350 | </PRE> | |
35351 | </DIV> | |
35352 | <P> Now, in Perl:</P> | |
35353 | <DIV class="code"> | |
35354 | <PRE> | |
35355 | set dim [get_dimensions $m] | |
35356 | set r [lindex $dim 0] | |
35357 | set c [lindex $dim 1] | |
35358 | </PRE> | |
35359 | </DIV> | |
35360 | <H2><A name="Tcl_nn33"></A>28.6 Exception handling</H2> | |
35361 | <P> The <TT>%exception</TT> directive can be used to create a | |
35362 | user-definable exception handler in charge of converting exceptions in | |
35363 | your C/C++ program into Tcl exceptions. The chapter on customization | |
35364 | features contains more details, but suppose you extended the array | |
35365 | example into a C++ class like the following :</P> | |
35366 | <DIV class="code"> | |
35367 | <PRE> | |
35368 | class RangeError {}; // Used for an exception | |
35369 | ||
35370 | class DoubleArray { | |
35371 | private: | |
35372 | int n; | |
35373 | double *ptr; | |
35374 | public: | |
35375 | // Create a new array of fixed size | |
35376 | DoubleArray(int size) { | |
35377 | ptr = new double[size]; | |
35378 | n = size; | |
35379 | } | |
35380 | // Destroy an array | |
35381 | ~DoubleArray() { | |
35382 | delete ptr; | |
35383 | } | |
35384 | // Return the length of the array | |
35385 | int length() { | |
35386 | return n; | |
35387 | } | |
35388 | ||
35389 | // Get an item from the array and perform bounds checking. | |
35390 | double getitem(int i) { | |
35391 | if ((i >= 0) && (i < n)) | |
35392 | return ptr[i]; | |
35393 | else | |
35394 | throw RangeError(); | |
35395 | } | |
35396 | ||
35397 | // Set an item in the array and perform bounds checking. | |
35398 | void setitem(int i, double val) { | |
35399 | if ((i >= 0) && (i < n)) | |
35400 | ptr[i] = val; | |
35401 | else { | |
35402 | throw RangeError(); | |
35403 | } | |
35404 | } | |
35405 | }; | |
35406 | </PRE> | |
35407 | </DIV> | |
35408 | <P> The functions associated with this class can throw a C++ range | |
35409 | exception for an out-of-bounds array access. We can catch this in our | |
35410 | Tcl extension by specifying the following in an interface file :</P> | |
35411 | <DIV class="code"> | |
35412 | <PRE> | |
35413 | %exception { | |
35414 | try { | |
35415 | $action // Gets substituted by actual function call | |
35416 | } | |
35417 | catch (RangeError) { | |
35418 | Tcl_SetStringObj(tcl_result,"Array index out-of-bounds"); | |
35419 | return TCL_ERROR; | |
35420 | } | |
35421 | } | |
35422 | </PRE> | |
35423 | </DIV> | |
35424 | <P> As shown, the exception handling code will be added to every wrapper | |
35425 | function. Since this is somewhat inefficient. You might consider | |
35426 | refining the exception handler to only apply to specific methods like | |
35427 | this:</P> | |
35428 | <DIV class="code"> | |
35429 | <PRE> | |
35430 | %exception getitem { | |
35431 | try { | |
35432 | $action | |
35433 | } | |
35434 | catch (RangeError) { | |
35435 | Tcl_SetStringObj(tcl_result,"Array index out-of-bounds"); | |
35436 | return TCL_ERROR; | |
35437 | } | |
35438 | } | |
35439 | ||
35440 | %exception setitem { | |
35441 | try { | |
35442 | $action | |
35443 | } | |
35444 | catch (RangeError) { | |
35445 | Tcl_SetStringObj(tcl_result,"Array index out-of-bounds"); | |
35446 | return TCL_ERROR; | |
35447 | } | |
35448 | } | |
35449 | </PRE> | |
35450 | </DIV> | |
35451 | <P> In this case, the exception handler is only attached to methods and | |
35452 | functions named <TT>getitem</TT> and <TT>setitem</TT>.</P> | |
35453 | <P> If you had a lot of different methods, you can avoid extra typing by | |
35454 | using a macro. For example:</P> | |
35455 | <DIV class="code"> | |
35456 | <PRE> | |
35457 | %define RANGE_ERROR | |
35458 | { | |
35459 | try { | |
35460 | $action | |
35461 | } | |
35462 | catch (RangeError) { | |
35463 | Tcl_SetStringObj(tcl_result,"Array index out-of-bounds"); | |
35464 | return TCL_ERROR; | |
35465 | } | |
35466 | } | |
35467 | %enddef | |
35468 | ||
35469 | %exception getitem RANGE_ERROR; | |
35470 | %exception setitem RANGE_ERROR; | |
35471 | </PRE> | |
35472 | </DIV> | |
35473 | <P> Since SWIG's exception handling is user-definable, you are not | |
35474 | limited to C++ exception handling. See the chapter on "<A href="#Customization"> | |
35475 | Customization Features</A>" for more examples.</P> | |
35476 | <H2><A name="Tcl_nn34"></A>28.7 Typemaps</H2> | |
35477 | <P> This section describes how you can modify SWIG's default wrapping | |
35478 | behavior for various C/C++ datatypes using the <TT>%typemap</TT> | |
35479 | directive. This is an advanced topic that assumes familiarity with the | |
35480 | Tcl C API as well as the material in the "<A href="#Typemaps">Typemaps</A> | |
35481 | " chapter.</P> | |
35482 | <P> Before proceeding, it should be stressed that typemaps are not a | |
35483 | required part of using SWIG---the default wrapping behavior is enough | |
35484 | in most cases. Typemaps are only used if you want to change some aspect | |
35485 | of the primitive C-Tcl interface.</P> | |
35486 | <H3><A name="Tcl_nn35"></A>28.7.1 What is a typemap?</H3> | |
35487 | <P> A typemap is nothing more than a code generation rule that is | |
35488 | attached to a specific C datatype. For example, to convert integers | |
35489 | from Tcl to C, you might define a typemap like this:</P> | |
35490 | <DIV class="code"> | |
35491 | <PRE> | |
35492 | %module example | |
35493 | ||
35494 | %typemap(in) int { | |
35495 | if (Tcl_GetIntFromObj(interp,$input,&$1) == TCL_ERROR) return TCL_ERROR; | |
35496 | printf("Received an integer : %d\n",$1); | |
35497 | } | |
35498 | %inline %{ | |
35499 | extern int fact(int n); | |
35500 | %} | |
35501 | </PRE> | |
35502 | </DIV> | |
35503 | <P> Typemaps are always associated with some specific aspect of code | |
35504 | generation. In this case, the "in" method refers to the conversion of | |
35505 | input arguments to C/C++. The datatype <TT>int</TT> is the datatype to | |
35506 | which the typemap will be applied. The supplied C code is used to | |
35507 | convert values. In this code a number of special variable prefaced by a | |
35508 | <TT>$</TT> are used. The <TT>$1</TT> variable is placeholder for a | |
35509 | local variable of type <TT>int</TT>. The <TT>$input</TT> variable is | |
35510 | the input object of type <TT>Tcl_Obj *</TT>.</P> | |
35511 | <P> When this example is compiled into a Tcl module, it operates as | |
35512 | follows:</P> | |
35513 | <DIV class="code"> | |
35514 | <PRE> | |
35515 | % load ./example.so | |
35516 | % fact 6 | |
35517 | Received an integer : 6 | |
35518 | 720 | |
35519 | </PRE> | |
35520 | </DIV> | |
35521 | <P> In this example, the typemap is applied to all occurrences of the <TT> | |
35522 | int</TT> datatype. You can refine this by supplying an optional | |
35523 | parameter name. For example:</P> | |
35524 | <DIV class="code"> | |
35525 | <PRE> | |
35526 | %module example | |
35527 | ||
35528 | %typemap(in) int n { | |
35529 | if (Tcl_GetIntFromObj(interp,$input,&$1) == TCL_ERROR) return TCL_ERROR; | |
35530 | printf("n = %d\n",$1); | |
35531 | } | |
35532 | %inline %{ | |
35533 | extern int fact(int n); | |
35534 | %} | |
35535 | </PRE> | |
35536 | </DIV> | |
35537 | <P> In this case, the typemap code is only attached to arguments that | |
35538 | exactly match <TT>int n</TT>.</P> | |
35539 | <P> The application of a typemap to specific datatypes and argument | |
35540 | names involves more than simple text-matching--typemaps are fully | |
35541 | integrated into the SWIG type-system. When you define a typemap for <TT> | |
35542 | int</TT>, that typemap applies to <TT>int</TT> and qualified variations | |
35543 | such as <TT>const int</TT>. In addition, the typemap system follows <TT> | |
35544 | typedef</TT> declarations. For example:</P> | |
35545 | <DIV class="code"> | |
35546 | <PRE> | |
35547 | %typemap(in) int n { | |
35548 | if (Tcl_GetIntFromObj(interp,$input,&$1) == TCL_ERROR) return TCL_ERROR; | |
35549 | printf("n = %d\n",$1); | |
35550 | } | |
35551 | %inline %{ | |
35552 | typedef int Integer; | |
35553 | extern int fact(Integer n); // Above typemap is applied | |
35554 | %} | |
35555 | </PRE> | |
35556 | </DIV> | |
35557 | <P> However, the matching of <TT>typedef</TT> only occurs in one | |
35558 | direction. If you defined a typemap for <TT>Integer</TT>, it is not | |
35559 | applied to arguments of type <TT>int</TT>.</P> | |
35560 | <P> Typemaps can also be defined for groups of consecutive arguments. | |
35561 | For example:</P> | |
35562 | <DIV class="code"> | |
35563 | <PRE> | |
35564 | %typemap(in) (char *str, int len) { | |
35565 | $1 = Tcl_GetStringFromObj($input,&$2); | |
35566 | }; | |
35567 | ||
35568 | int count(char c, char *str, int len); | |
35569 | </PRE> | |
35570 | </DIV> | |
35571 | <P> When a multi-argument typemap is defined, the arguments are always | |
35572 | handled as a single Tcl object. This allows the function to be used | |
35573 | like this (notice how the length parameter is ommitted):</P> | |
35574 | <DIV class="code"> | |
35575 | <PRE> | |
35576 | % count e "Hello World" | |
35577 | 1 | |
35578 | </PRE> | |
35579 | </DIV> | |
35580 | <H3><A name="Tcl_nn36"></A>28.7.2 Tcl typemaps</H3> | |
35581 | <P> The previous section illustrated an "in" typemap for converting Tcl | |
35582 | objects to C. A variety of different typemap methods are defined by the | |
35583 | Tcl module. For example, to convert a C integer back into a Tcl object, | |
35584 | you might define an "out" typemap like this:</P> | |
35585 | <DIV class="code"> | |
35586 | <PRE> | |
35587 | %typemap(out) int { | |
35588 | Tcl_SetObjResult(interp,Tcl_NewIntObj($1)); | |
35589 | } | |
35590 | </PRE> | |
35591 | </DIV> | |
35592 | <P> The following list details all of the typemap methods that can be | |
35593 | used by the Tcl module:</P> | |
35594 | <P> <TT>%typemap(in)</TT></P> | |
35595 | <DIV class="indent"> Converts Tcl objects to input function arguments</DIV> | |
35596 | <P> <TT>%typemap(out)</TT></P> | |
35597 | <DIV class="indent"> Converts return value of a C function to a Tcl | |
35598 | object</DIV> | |
35599 | <P> <TT>%typemap(varin)</TT></P> | |
35600 | <DIV class="indent"> Assigns a C global variable from a Tcl object</DIV> | |
35601 | <P> <TT>%typemap(varout)</TT></P> | |
35602 | <DIV class="indent"> Returns a C global variable as a Tcl object</DIV> | |
35603 | <P> <TT>%typemap(freearg)</TT></P> | |
35604 | <DIV class="indent"> Cleans up a function argument (if necessary)</DIV> | |
35605 | <P> <TT>%typemap(argout)</TT></P> | |
35606 | <DIV class="indent"> Output argument processing</DIV> | |
35607 | <P> <TT>%typemap(ret)</TT></P> | |
35608 | <DIV class="indent"> Cleanup of function return values</DIV> | |
35609 | <P> <TT>%typemap(consttab)</TT></P> | |
35610 | <DIV class="indent"> Creation of Tcl constants (constant table)</DIV> | |
35611 | <P> <TT>%typemap(constcode)</TT></P> | |
35612 | <DIV class="indent"> Creation of Tcl constants (init function)</DIV> | |
35613 | <P> <TT>%typemap(memberin)</TT></P> | |
35614 | <DIV class="indent"> Setting of structure/class member data</DIV> | |
35615 | <P> <TT>%typemap(globalin)</TT></P> | |
35616 | <DIV class="indent"> Setting of C global variables</DIV> | |
35617 | <P> <TT>%typemap(check)</TT></P> | |
35618 | <DIV class="indent"> Checks function input values.</DIV> | |
35619 | <P> <TT>%typemap(default)</TT></P> | |
35620 | <DIV class="indent"> Set a default value for an argument (making it | |
35621 | optional).</DIV> | |
35622 | <P> <TT>%typemap(arginit)</TT></P> | |
35623 | <DIV class="indent"> Initialize an argument to a value before any | |
35624 | conversions occur.</DIV> | |
35625 | <P> Examples of these methods will appear shortly.</P> | |
35626 | <H3><A name="Tcl_nn37"></A>28.7.3 Typemap variables</H3> | |
35627 | <P> Within typemap code, a number of special variables prefaced with a <TT> | |
35628 | $</TT> may appear. A full list of variables can be found in the "<A href="#Typemaps"> | |
35629 | Typemaps</A>" chapter. This is a list of the most common variables:</P> | |
35630 | <P> <TT>$1</TT></P> | |
35631 | <DIV class="indent"> A C local variable corresponding to the actual type | |
35632 | specified in the <TT>%typemap</TT> directive. For input values, this is | |
35633 | a C local variable that's supposed to hold an argument value. For | |
35634 | output values, this is the raw result that's supposed to be returned to | |
35635 | Tcl.</DIV> | |
35636 | <P> <TT>$input</TT></P> | |
35637 | <DIV class="indent"> A <TT>Tcl_Obj *</TT> holding a raw Tcl object with | |
35638 | an argument or variable value.</DIV> | |
35639 | <P> <TT>$result</TT></P> | |
35640 | <DIV class="indent"> A <TT>Tcl_Obj *</TT> that holds the result to be | |
35641 | returned to Tcl.</DIV> | |
35642 | <P> <TT>$1_name</TT></P> | |
35643 | <DIV class="indent"> The parameter name that was matched.</DIV> | |
35644 | <P> <TT>$1_type</TT></P> | |
35645 | <DIV class="indent"> The actual C datatype matched by the typemap.</DIV> | |
35646 | <P> <TT>$1_ltype</TT></P> | |
35647 | <DIV class="indent"> An assignable version of the datatype matched by | |
35648 | the typemap (a type that can appear on the left-hand-side of a C | |
35649 | assignment operation). This type is stripped of qualifiers and may be | |
35650 | an altered version of <TT>$1_type</TT>. All arguments and local | |
35651 | variables in wrapper functions are declared using this type so that | |
35652 | their values can be properly assigned.</DIV> | |
35653 | <P> <TT>$symname</TT></P> | |
35654 | <DIV class="indent"> The Tcl name of the wrapper function being created.</DIV> | |
35655 | <H3><A name="Tcl_nn38"></A>28.7.4 Converting a Tcl list to a char **</H3> | |
35656 | <P> A common problem in many C programs is the processing of command | |
35657 | line arguments, which are usually passed in an array of NULL terminated | |
35658 | strings. The following SWIG interface file allows a Tcl list to be used | |
35659 | as a <TT>char **</TT> object.</P> | |
35660 | <DIV class="code"> | |
35661 | <PRE> | |
35662 | %module argv | |
35663 | ||
35664 | // This tells SWIG to treat char ** as a special case | |
35665 | %typemap(in) char ** { | |
35666 | Tcl_Obj **listobjv; | |
35667 | int nitems; | |
35668 | int i; | |
35669 | if (Tcl_ListObjGetElements(interp, $input, &nitems, &listobjv) == TCL_ERROR) { | |
35670 | return TCL_ERROR; | |
35671 | } | |
35672 | $1 = (char **) malloc((nitems+1)*sizeof(char *)); | |
35673 | for (i = 0; i < nitems; i++) { | |
35674 | $1[i] = Tcl_GetStringFromObj(listobjv[i],0); | |
35675 | } | |
35676 | $1[i] = 0; | |
35677 | } | |
35678 | ||
35679 | // This gives SWIG some cleanup code that will get called after the function call | |
35680 | %typemap(freearg) char ** { | |
35681 | if ($1) { | |
35682 | free($1); | |
35683 | } | |
35684 | } | |
35685 | ||
35686 | // Now a test functions | |
35687 | %inline %{ | |
35688 | int print_args(char **argv) { | |
35689 | int i = 0; | |
35690 | while (argv[i]) { | |
35691 | printf("argv[%d] = %s\n", i,argv[i]); | |
35692 | i++; | |
35693 | } | |
35694 | return i; | |
35695 | } | |
35696 | %} | |
35697 | %include tclsh.i | |
35698 | ||
35699 | </PRE> | |
35700 | </DIV> | |
35701 | <P> In Tcl:</P> | |
35702 | <DIV class="code"> | |
35703 | <PRE> | |
35704 | % print_args {John Guido Larry} | |
35705 | argv[0] = John | |
35706 | argv[1] = Guido | |
35707 | argv[2] = Larry | |
35708 | 3 | |
35709 | </PRE> | |
35710 | </DIV> | |
35711 | <H3><A name="Tcl_nn39"></A>28.7.5 Returning values in arguments</H3> | |
35712 | <P> The "argout" typemap can be used to return a value originating from | |
35713 | a function argument. For example :</P> | |
35714 | <DIV class="code"> | |
35715 | <PRE> | |
35716 | // A typemap defining how to return an argument by appending it to the result | |
35717 | %typemap(argout) double *outvalue { | |
35718 | Tcl_Obj *o = Tcl_NewDoubleObj($1); | |
35719 | Tcl_ListObjAppendElement(interp,$result,o); | |
35720 | } | |
35721 | ||
35722 | // A typemap telling SWIG to ignore an argument for input | |
35723 | // However, we still need to pass a pointer to the C function | |
35724 | %typemap(in,numinputs=0) double *outvalue (double temp) { | |
35725 | $1 = &temp; | |
35726 | } | |
35727 | ||
35728 | // Now a function returning two values | |
35729 | int mypow(double a, double b, double *outvalue) { | |
35730 | if ((a < 0) || (b < 0)) return -1; | |
35731 | *outvalue = pow(a,b); | |
35732 | return 0; | |
35733 | }; | |
35734 | </PRE> | |
35735 | </DIV> | |
35736 | <P> When wrapped, SWIG matches the <TT>argout</TT> typemap to the "<TT> | |
35737 | double *outvalue</TT>" argument. The numinputs=0 specification tells | |
35738 | SWIG to simply ignore this argument when generating wrapper code. As a | |
35739 | result, a Tcl function using these typemaps will work like this :</P> | |
35740 | <DIV class="code"> | |
35741 | <PRE> | |
35742 | % mypow 2 3 # Returns two values, a status value and the result | |
35743 | 0 8 | |
35744 | % | |
35745 | </PRE> | |
35746 | </DIV> | |
35747 | <H3><A name="Tcl_nn40"></A>28.7.6 Useful functions</H3> | |
35748 | <P> The following tables provide some functions that may be useful in | |
35749 | writing Tcl typemaps.</P> | |
35750 | <P><B> Integers</B></P> | |
35751 | <DIV class="code"> | |
35752 | <PRE> | |
35753 | Tcl_Obj *Tcl_NewIntObj(int Value); | |
35754 | void Tcl_SetIntObj(Tcl_Obj *obj, int Value); | |
35755 | int Tcl_GetIntFromObj(Tcl_Interp *, Tcl_Obj *obj, int *ip); | |
35756 | </PRE> | |
35757 | </DIV> | |
35758 | <P><B> Floating Point</B></P> | |
35759 | <DIV class="code"> | |
35760 | <PRE> | |
35761 | Tcl_Obj *Tcl_NewDoubleObj(double Value); | |
35762 | void Tcl_SetDoubleObj(Tcl_Obj *obj, double value); | |
35763 | int Tcl_GetDoubleFromObj(Tcl_Interp *, Tcl_Obj *o, double *dp); | |
35764 | </PRE> | |
35765 | </DIV> | |
35766 | <P><B> Strings</B></P> | |
35767 | <DIV class="code"> | |
35768 | <PRE> | |
35769 | Tcl_Obj *Tcl_NewStringObj(char *str, int len); | |
35770 | void Tcl_SetStringObj(Tcl_Obj *obj, char *str, int len); | |
35771 | char *Tcl_GetStringFromObj(Tcl_Obj *obj, int *len); | |
35772 | void Tcl_AppendToObj(Tcl_Obj *obj, char *str, int len); | |
35773 | </PRE> | |
35774 | </DIV> | |
35775 | <P><B> Lists</B></P> | |
35776 | <DIV class="code"> | |
35777 | <PRE> | |
35778 | Tcl_Obj *Tcl_NewListObj(int objc, Tcl_Obj *objv); | |
35779 | int Tcl_ListObjAppendList(Tcl_Interp *, Tcl_Obj *listPtr, Tcl_Obj *elemListPtr); | |
35780 | int Tcl_ListObjAppendElement(Tcl_Interp *, Tcl_Obj *listPtr, Tcl_Obj *element); | |
35781 | int Tcl_ListObjGetElements(Tcl_Interp *, Tcl_Obj *listPtr, int *objcPtr, | |
35782 | Tcl_Obj ***objvPtr); | |
35783 | int Tcl_ListObjLength(Tcl_Interp *, Tcl_Obj *listPtr, int *intPtr); | |
35784 | int Tcl_ListObjIndex(Tcl_Interp *, Tcl_Obj *listPtr, int index, | |
35785 | Tcl_Obj_Obj **objptr); | |
35786 | int Tcl_ListObjReplace(Tcl_Interp *, Tcl_Obj *listPtr, int first, int count, | |
35787 | int objc, Tcl_Obj *objv); | |
35788 | </PRE> | |
35789 | </DIV> | |
35790 | <P><B> Objects</B></P> | |
35791 | <DIV class="code"> | |
35792 | <PRE> | |
35793 | Tcl_Obj *Tcl_DuplicateObj(Tcl_Obj *obj); | |
35794 | void Tcl_IncrRefCount(Tcl_Obj *obj); | |
35795 | void Tcl_DecrRefCount(Tcl_Obj *obj); | |
35796 | int Tcl_IsShared(Tcl_Obj *obj); | |
35797 | </PRE> | |
35798 | </DIV> | |
35799 | <H3><A name="Tcl_nn41"></A>28.7.7 Standard typemaps</H3> | |
35800 | <P> The following typemaps show how to convert a few common kinds of | |
35801 | objects between Tcl and C (and to give a better idea of how typemaps | |
35802 | work)</P> | |
35803 | <P><B> Integer conversion</B></P> | |
35804 | <DIV class="code"> | |
35805 | <PRE> | |
35806 | %typemap(in) int, short, long { | |
35807 | int temp; | |
35808 | if (Tcl_GetIntFromObj(interp, $input, &temp) == TCL_ERROR) | |
35809 | return TCL_ERROR; | |
35810 | $1 = ($1_ltype) temp; | |
35811 | } | |
35812 | </PRE> | |
35813 | </DIV> | |
35814 | <BR><DIV class="code"> | |
35815 | <PRE> | |
35816 | %typemap(out) int, short, long { | |
35817 | Tcl_SetIntObj($result,(int) $1); | |
35818 | } | |
35819 | </PRE> | |
35820 | </DIV> | |
35821 | <P><B> Floating point conversion</B></P> | |
35822 | <DIV class="code"> | |
35823 | <PRE> | |
35824 | %typemap(in) float, double { | |
35825 | double temp; | |
35826 | if (Tcl_GetDoubleFromObj(interp, $input, &temp) == TCL_ERROR) | |
35827 | return TCL_ERROR; | |
35828 | $1 = ($1_ltype) temp; | |
35829 | } | |
35830 | </PRE> | |
35831 | </DIV> | |
35832 | <BR><DIV class="code"> | |
35833 | <PRE> | |
35834 | %typemap(out) float, double { | |
35835 | Tcl_SetDoubleObj($result, $1); | |
35836 | } | |
35837 | </PRE> | |
35838 | </DIV> | |
35839 | <P><B> String Conversion</B></P> | |
35840 | <DIV class="code"> | |
35841 | <PRE> | |
35842 | %typemap(in) char * { | |
35843 | int len; | |
35844 | $1 = Tcl_GetStringFromObj(interp, &len); | |
35845 | } | |
35846 | } | |
35847 | </PRE> | |
35848 | </DIV> | |
35849 | <BR><DIV class="code"> | |
35850 | <PRE> | |
35851 | %typemap(out) char * { | |
35852 | Tcl_SetStringObj($result,$1); | |
35853 | } | |
35854 | </PRE> | |
35855 | </DIV> | |
35856 | <H3><A name="Tcl_nn42"></A>28.7.8 Pointer handling</H3> | |
35857 | <P> SWIG pointers are mapped into Tcl strings containing the hexadecimal | |
35858 | value and type. The following functions can be used to create and read | |
35859 | pointer values.</P> | |
35860 | <P> <TT>int SWIG_ConvertPtr(Tcl_Obj *obj, void **ptr, swig_type_info | |
35861 | *ty, int flags)</TT></P> | |
35862 | <DIV class="indent"> Converts a Tcl object <TT>obj</TT> to a C pointer. | |
35863 | The result of the conversion is placed into the pointer located at <TT> | |
35864 | ptr</TT>. <TT>ty</TT> is a SWIG type descriptor structure. <TT>flags</TT> | |
35865 | is used to handle error checking and other aspects of conversion. It is | |
35866 | currently reserved for future expansion. Returns 0 on success and -1 on | |
35867 | error.</DIV> | |
35868 | <P> <TT>Tcl_Obj *SWIG_NewPointerObj(void *ptr, swig_type_info *ty, int | |
35869 | flags)</TT></P> | |
35870 | <DIV class="indent"> Creates a new Tcl pointer object. <TT>ptr</TT> is | |
35871 | the pointer to convert, <TT>ty</TT> is the SWIG type descriptor | |
35872 | structure that describes the type, and <TT>own</TT> is a flag reserved | |
35873 | for future expansion.</DIV> | |
35874 | <P> Both of these functions require the use of a special SWIG | |
35875 | type-descriptor structure. This structure contains information about | |
35876 | the mangled name of the datatype, type-equivalence information, as well | |
35877 | as information about converting pointer values under C++ inheritance. | |
35878 | For a type of <TT>Foo *</TT>, the type descriptor structure is usually | |
35879 | accessed as follows:</P> | |
35880 | <DIV class="indent"> | |
35881 | <PRE> | |
35882 | Foo *f; | |
35883 | if (SWIG_ConvertPtr($input, (void **) &f, SWIGTYPE_p_Foo, 0) == -1) return NULL; | |
35884 | ||
35885 | Tcl_Obj *; | |
35886 | obj = SWIG_NewPointerObj(f, SWIGTYPE_p_Foo, 0); | |
35887 | </PRE> | |
35888 | </DIV> | |
35889 | <P> In a typemap, the type descriptor should always be accessed using | |
35890 | the special typemap variable <TT>$1_descriptor</TT>. For example:</P> | |
35891 | <DIV class="indent"> | |
35892 | <PRE> | |
35893 | %typemap(in) Foo * { | |
35894 | if ((SWIG_ConvertPtr($input,(void **) &$1, $1_descriptor,0)) == -1) return NULL; | |
35895 | } | |
35896 | </PRE> | |
35897 | </DIV> | |
35898 | <P> If necessary, the descriptor for any type can be obtained using the <TT> | |
35899 | $descriptor()</TT> macro in a typemap. For example:</P> | |
35900 | <DIV class="indent"> | |
35901 | <PRE> | |
35902 | %typemap(in) Foo * { | |
35903 | if ((SWIG_ConvertPtr($input,(void **) &$1, $descriptor(Foo *), 0)) == -1) return NULL; | |
35904 | } | |
35905 | </PRE> | |
35906 | </DIV> | |
35907 | <H2><A name="Tcl_nn43"></A>28.8 Turning a SWIG module into a Tcl | |
35908 | Package.</H2> | |
35909 | <P> Tcl 7.4 introduced the idea of an extension package. By default, | |
35910 | SWIG generates all of the code necessary to create a package. To set | |
35911 | the package version, simply use the <TT>-pkgversion</TT> option. For | |
35912 | example:</P> | |
35913 | <DIV class="code"> | |
35914 | <PRE> | |
35915 | % swig -tcl -pkgversion 2.3 example.i | |
35916 | </PRE> | |
35917 | </DIV> | |
35918 | <P> After building the SWIG generated module, you need to execute the "<TT> | |
35919 | pkg_mkIndex</TT>" command inside tclsh. For example :</P> | |
35920 | <DIV class="code"> | |
35921 | <PRE> | |
35922 | unix > tclsh | |
35923 | % pkg_mkIndex . example.so | |
35924 | % exit | |
35925 | </PRE> | |
35926 | </DIV> | |
35927 | <P> This creates a file "<TT>pkgIndex.tcl</TT>" with information about | |
35928 | the package. To use your package, you now need to move it to its own | |
35929 | subdirectory which has the same name as the package. For example :</P> | |
35930 | <DIV class="code"> | |
35931 | <PRE> | |
35932 | ./example/ | |
35933 | pkgIndex.tcl # The file created by pkg_mkIndex | |
35934 | example.so # The SWIG generated module | |
35935 | </PRE> | |
35936 | </DIV> | |
35937 | <P> Finally, assuming that you're not entirely confused at this point, | |
35938 | make sure that the example subdirectory is visible from the directories | |
35939 | contained in either the <TT>tcl_library</TT> or <TT>auto_path</TT> | |
35940 | variables. At this point you're ready to use the package as follows :</P> | |
35941 | <DIV class="code"> | |
35942 | <PRE> | |
35943 | unix > tclsh | |
35944 | % package require example | |
35945 | % fact 4 | |
35946 | 24 | |
35947 | % | |
35948 | </PRE> | |
35949 | </DIV> | |
35950 | <P> If you're working with an example in the current directory and this | |
35951 | doesn't work, do this instead :</P> | |
35952 | <DIV class="code"> | |
35953 | <PRE> | |
35954 | unix > tclsh | |
35955 | % lappend auto_path . | |
35956 | % package require example | |
35957 | % fact 4 | |
35958 | 24 | |
35959 | </PRE> | |
35960 | </DIV> | |
35961 | <P> As a final note, most SWIG examples do not yet use the <TT>package</TT> | |
35962 | commands. For simple extensions it may be easier just to use the <TT> | |
35963 | load</TT> command instead.</P> | |
35964 | <H2><A name="Tcl_nn44"></A>28.9 Building new kinds of Tcl interfaces (in | |
35965 | Tcl)</H2> | |
35966 | <P> One of the most interesting aspects of Tcl and SWIG is that you can | |
35967 | create entirely new kinds of Tcl interfaces in Tcl using the low-level | |
35968 | SWIG accessor functions. For example, suppose you had a library of | |
35969 | helper functions to access arrays :</P> | |
35970 | <DIV class="code"> | |
35971 | <PRE> | |
35972 | /* File : array.i */ | |
35973 | %module array | |
35974 | ||
35975 | %inline %{ | |
35976 | double *new_double(int size) { | |
35977 | return (double *) malloc(size*sizeof(double)); | |
35978 | } | |
35979 | void delete_double(double *a) { | |
35980 | free(a); | |
35981 | } | |
35982 | double get_double(double *a, int index) { | |
35983 | return a[index]; | |
35984 | } | |
35985 | void set_double(double *a, int index, double val) { | |
35986 | a[index] = val; | |
35987 | } | |
35988 | int *new_int(int size) { | |
35989 | return (int *) malloc(size*sizeof(int)); | |
35990 | } | |
35991 | void delete_int(int *a) { | |
35992 | free(a); | |
35993 | } | |
35994 | int get_int(int *a, int index) { | |
35995 | return a[index]; | |
35996 | } | |
35997 | int set_int(int *a, int index, int val) { | |
35998 | a[index] = val; | |
35999 | } | |
36000 | %} | |
36001 | ||
36002 | </PRE> | |
36003 | </DIV> | |
36004 | <P> While these could be called directly, we could also write a Tcl | |
36005 | script like this :</P> | |
36006 | <DIV class="code"> | |
36007 | <PRE> | |
36008 | proc Array {type size} { | |
36009 | set ptr [new_$type $size] | |
36010 | set code { | |
36011 | set method [lindex $args 0] | |
36012 | set parms [concat $ptr [lrange $args 1 end]] | |
36013 | switch $method { | |
36014 | get {return [eval "get_$type $parms"]} | |
36015 | set {return [eval "set_$type $parms"]} | |
36016 | delete {eval "delete_$type $ptr; rename $ptr {}"} | |
36017 | } | |
36018 | } | |
36019 | # Create a procedure | |
36020 | uplevel "proc $ptr args {set ptr $ptr; set type $type;$code}" | |
36021 | return $ptr | |
36022 | } | |
36023 | </PRE> | |
36024 | </DIV> | |
36025 | <P> Our script allows easy array access as follows :</P> | |
36026 | <DIV class="code"> | |
36027 | <PRE> | |
36028 | set a [Array double 100] ;# Create a double [100] | |
36029 | for {set i 0} {$i < 100} {incr i 1} { ;# Clear the array | |
36030 | $a set $i 0.0 | |
36031 | } | |
36032 | $a set 3 3.1455 ;# Set an individual element | |
36033 | set b [$a get 10] ;# Retrieve an element | |
36034 | ||
36035 | set ia [Array int 50] ;# Create an int[50] | |
36036 | for {set i 0} {$i < 50} {incr i 1} { ;# Clear it | |
36037 | $ia set $i 0 | |
36038 | } | |
36039 | $ia set 3 7 ;# Set an individual element | |
36040 | set ib [$ia get 10] ;# Get an individual element | |
36041 | ||
36042 | $a delete ;# Destroy a | |
36043 | $ia delete ;# Destroy ia | |
36044 | </PRE> | |
36045 | </DIV> | |
36046 | <P> The cool thing about this approach is that it makes a common | |
36047 | interface for two different types of arrays. In fact, if we were to add | |
36048 | more C datatypes to our wrapper file, the Tcl code would work with | |
36049 | those as well--without modification. If an unsupported datatype was | |
36050 | requested, the Tcl code would simply return with an error so there is | |
36051 | very little danger of blowing something up (although it is easily | |
36052 | accomplished with an out of bounds array access).</P> | |
36053 | <H3><A name="Tcl_nn45"></A>28.9.1 Proxy classes</H3> | |
36054 | <P> A similar approach can be applied to proxy classes (also known as | |
36055 | shadow classes). The following example is provided by Erik Bierwagen | |
36056 | and Paul Saxe. To use it, run SWIG with the <TT>-noobject</TT> option | |
36057 | (which disables the builtin object oriented interface). When running | |
36058 | Tcl, simply source this file. Now, objects can be used in a more or | |
36059 | less natural fashion.</P> | |
36060 | <DIV class="code"> | |
36061 | <PRE> | |
36062 | # swig_c++.tcl | |
36063 | # Provides a simple object oriented interface using | |
36064 | # SWIG's low level interface. | |
36065 | # | |
36066 | ||
36067 | proc new {objectType handle_r args} { | |
36068 | # Creates a new SWIG object of the given type, | |
36069 | # returning a handle in the variable "handle_r". | |
36070 | # | |
36071 | # Also creates a procedure for the object and a trace on | |
36072 | # the handle variable that deletes the object when the | |
36073 | # handle varibale is overwritten or unset | |
36074 | upvar $handle_r handle | |
36075 | # | |
36076 | # Create the new object | |
36077 | # | |
36078 | eval set handle \[new_$objectType $args\] | |
36079 | # | |
36080 | # Set up the object procedure | |
36081 | # | |
36082 | proc $handle {cmd args} "eval ${objectType}_\$cmd $handle \$args" | |
36083 | # | |
36084 | # And the trace ... | |
36085 | # | |
36086 | uplevel trace variable $handle_r uw "{deleteObject $objectType $handle}" | |
36087 | # | |
36088 | # Return the handle so that 'new' can be used as an argument to a procedure | |
36089 | # | |
36090 | return $handle | |
36091 | } | |
36092 | ||
36093 | proc deleteObject {objectType handle name element op} { | |
36094 | # | |
36095 | # Check that the object handle has a reasonable form | |
36096 | # | |
36097 | if {![regexp {_[0-9a-f]*_(.+)_p} $handle]} { | |
36098 | error "deleteObject: not a valid object handle: $handle" | |
36099 | } | |
36100 | # | |
36101 | # Remove the object procedure | |
36102 | # | |
36103 | catch {rename $handle {}} | |
36104 | # | |
36105 | # Delete the object | |
36106 | # | |
36107 | delete_$objectType $handle | |
36108 | } | |
36109 | ||
36110 | proc delete {handle_r} { | |
36111 | # | |
36112 | # A synonym for unset that is more familiar to C++ programmers | |
36113 | # | |
36114 | uplevel unset $handle_r | |
36115 | } | |
36116 | </PRE> | |
36117 | </DIV> | |
36118 | <P> To use this file, we simply source it and execute commands such as | |
36119 | "new" and "delete" to manipulate objects. For example :</P> | |
36120 | <DIV class="code"> | |
36121 | <PRE> | |
36122 | // list.i | |
36123 | %module List | |
36124 | %{ | |
36125 | #include "list.h" | |
36126 | %} | |
36127 | ||
36128 | // Very simple C++ example | |
36129 | ||
36130 | class List { | |
36131 | public: | |
36132 | List(); // Create a new list | |
36133 | ~List(); // Destroy a list | |
36134 | int search(char *value); | |
36135 | void insert(char *); // Insert a new item into the list | |
36136 | void remove(char *); // Remove item from list | |
36137 | char *get(int n); // Get the nth item in the list | |
36138 | int length; // The current length of the list | |
36139 | static void print(List *l); // Print out the contents of the list | |
36140 | }; | |
36141 | </PRE> | |
36142 | </DIV> | |
36143 | <P> Now a Tcl script using the interface...</P> | |
36144 | <DIV class="code"> | |
36145 | <PRE> | |
36146 | load ./list.so list ; # Load the module | |
36147 | source swig_c++.tcl ; # Source the object file | |
36148 | ||
36149 | new List l | |
36150 | $l insert Dave | |
36151 | $l insert John | |
36152 | $l insert Guido | |
36153 | $l remove Dave | |
36154 | puts $l length_get | |
36155 | ||
36156 | delete l | |
36157 | </PRE> | |
36158 | </DIV> | |
36159 | <P> The cool thing about this example is that it works with any C++ | |
36160 | object wrapped by SWIG and requires no special compilation. Proof that | |
36161 | a short, but clever Tcl script can be combined with SWIG to do many | |
36162 | interesting things.</P> | |
36163 | <HR NOSHADE> | |
36164 | <H1><A name="Lua_nn1"></A>29 SWIG and Lua</H1> | |
36165 | ||
36166 | <!-- INDEX --> | |
36167 | <DIV class="sectiontoc"> | |
36168 | <UL> | |
36169 | <LI><A href="#Lua_nn2">Preliminaries</A></LI> | |
36170 | <LI><A href="#Lua_nn3">Running SWIG</A> | |
36171 | <UL> | |
36172 | <LI><A href="#Lua_nn4">Compiling and Linking and Interpreter</A></LI> | |
36173 | <LI><A href="#Lua_nn5">Compiling a dynamic module</A></LI> | |
36174 | <LI><A href="#Lua_nn6">Using your module</A></LI> | |
36175 | </UL> | |
36176 | </LI> | |
36177 | <LI><A href="#Lua_nn7">A tour of basic C/C++ wrapping</A> | |
36178 | <UL> | |
36179 | <LI><A href="#Lua_nn8">Modules</A></LI> | |
36180 | <LI><A href="#Lua_nn9">Functions</A></LI> | |
36181 | <LI><A href="#Lua_nn10">Global variables</A></LI> | |
36182 | <LI><A href="#Lua_nn11">Constants and enums</A></LI> | |
36183 | <LI><A href="#Lua_nn12">Pointers</A></LI> | |
36184 | <LI><A href="#Lua_nn13">Structures</A></LI> | |
36185 | <LI><A href="#Lua_nn14">C++ classes</A></LI> | |
36186 | <LI><A href="#Lua_nn15">C++ inheritance</A></LI> | |
36187 | <LI><A href="#Lua_nn16">Pointers, references, values, and arrays</A></LI> | |
36188 | <LI><A href="#Lua_nn17">C++ overloaded functions</A></LI> | |
36189 | <LI><A href="#Lua_nn18">C++ operators</A></LI> | |
36190 | <LI><A href="#Lua_nn19">Class extension with %extend</A></LI> | |
36191 | <LI><A href="#Lua_nn20">C++ templates</A></LI> | |
36192 | <LI><A href="#Lua_nn21">C++ Smart Pointers</A></LI> | |
36193 | </UL> | |
36194 | </LI> | |
36195 | <LI><A href="#Lua_nn22">Details on the Lua binding</A> | |
36196 | <UL> | |
36197 | <LI><A href="#Lua_nn23">Binding global data into the module.</A></LI> | |
36198 | <LI><A href="#Lua_nn24">Userdata and Metatables</A></LI> | |
36199 | <LI><A href="#Lua_nn25">Memory management</A></LI> | |
36200 | </UL> | |
36201 | </LI> | |
36202 | </UL> | |
36203 | </DIV> | |
36204 | <!-- INDEX --> | |
36205 | <P> Lua is an extension programming language designed to support general | |
36206 | procedural programming with data description facilities. It also offers | |
36207 | good support for object-oriented programming, functional programming, | |
36208 | and data-driven programming. Lua is intended to be used as a powerful, | |
36209 | light-weight configuration language for any program that needs one. Lua | |
36210 | is implemented as a library, written in clean C (that is, in the common | |
36211 | subset of ANSI C and C++). Its also a<EM> really</EM> tiny language, | |
36212 | less than 6000 lines of code, which compiles to <100 kilobytes of | |
36213 | binary code. It can be found at <A href="http://www.lua.org"> | |
36214 | http://www.lua.org</A></P> | |
36215 | <H2><A name="Lua_nn2"></A>29.1 Preliminaries</H2> | |
36216 | <P> The current SWIG implementation is designed to work with Lua 5.0. It | |
36217 | should work with later versions of Lua, but certainly not with Lua 4.0 | |
36218 | due to substantial API changes. ((Currently SWIG generated code has | |
36219 | only been tested on Windows with MingW, though given the nature of Lua, | |
36220 | is should not have problems on other OS's)). It is possible to either | |
36221 | static link or dynamic link a Lua module into the interpreter (normally | |
36222 | Lua static links its libraries, as dynamic linking is not available on | |
36223 | all platforms).</P> | |
36224 | <P> Note: Lua 5.1 (alpha) has just (as of September 05) been released. | |
36225 | The current version of SWIG will produce wrappers which are compatible | |
36226 | with Lua 5.1, though the dynamic loading mechanism has changed (see | |
36227 | below). The configure script and makefiles should work correctly with | |
36228 | with Lua 5.1, though some small tweaks may be needed.</P> | |
36229 | <H2><A name="Lua_nn3"></A>29.2 Running SWIG</H2> | |
36230 | <P> Suppose that you defined a SWIG module such as the following:</P> | |
36231 | <DIV class="code"> | |
36232 | <PRE> | |
36233 | %module example | |
36234 | %{ | |
36235 | #include "example.h" | |
36236 | %} | |
36237 | int gcd(int x, int y); | |
36238 | extern double Foo; | |
36239 | </PRE> | |
36240 | </DIV> | |
36241 | <P> To build a Lua module, run SWIG using the <TT>-lua</TT> option.</P> | |
36242 | <DIV class="shell"> | |
36243 | <PRE> | |
36244 | $ swig -lua example.i | |
36245 | </PRE> | |
36246 | </DIV> | |
36247 | <P> If building a C++ extension, add the <TT>-c++</TT> option:</P> | |
36248 | <DIV class="shell"> | |
36249 | <PRE> | |
36250 | $ swig -c++ -lua example.i | |
36251 | </PRE> | |
36252 | </DIV> | |
36253 | <P> This creates a C/C++ source file <TT>example_wrap.c</TT> or <TT> | |
36254 | example_wrap.cxx</TT>. The generated C source file contains the | |
36255 | low-level wrappers that need to be compiled and linked with the rest of | |
36256 | your C/C++ application to create an extension module.</P> | |
36257 | <P> The name of the wrapper file is derived from the name of the input | |
36258 | file. For example, if the input file is <TT>example.i</TT>, the name of | |
36259 | the wrapper file is <TT>example_wrap.c</TT>. To change this, you can | |
36260 | use the -o option. The wrappered module will export one function <TT> | |
36261 | "int Example_Init(LuaState* L)"</TT> which must be called to register | |
36262 | the module with the Lua interpreter. The name "Example_Init" depends | |
36263 | upon the name of the module. Note: SWIG will automatically capitalise | |
36264 | the module name, so <TT>"module example;"</TT> becomes <TT> | |
36265 | "Example_Init"</TT>.</P> | |
36266 | <H3><A name="Lua_nn4"></A>29.2.1 Compiling and Linking and Interpreter</H3> | |
36267 | <P> Normally Lua is embedded into another program and will be statically | |
36268 | linked. An extremely simple stand-alone interpreter (<TT>min.c</TT>) is | |
36269 | given below:</P> | |
36270 | <DIV class="code"> | |
36271 | <PRE> | |
36272 | #include <stdio.h> | |
36273 | #include "lua.h" | |
36274 | #include "lualib.h" | |
36275 | #include "lauxlib.h" | |
36276 | ||
36277 | extern int Example_Init(LuaState* L); // declare the wrapped module | |
36278 | ||
36279 | int main(int argc,char* argv[]) | |
36280 | { | |
36281 | lua_State *L; | |
36282 | if (argc | |
36283 | <!--2) | |
36284 | { | |
36285 | printf("%s: <filename.lua>\n",argv[0]); | |
36286 | return 0; | |
36287 | } | |
36288 | L=lua_open(); | |
36289 | luaopen_base(L); // load basic libs (eg. print) | |
36290 | Example_Init(L); // load the wrappered module | |
36291 | if (luaL_loadfile(L,argv[1])==0) // load and run the file | |
36292 | lua_pcall(L,0,0,0); | |
36293 | else | |
36294 | printf("unable to load %s\n",argv[1]); | |
36295 | lua_close(L); | |
36296 | return 0; | |
36297 | } | |
36298 | </pre--> | |
36299 | </PRE> | |
36300 | </DIV> | |
36301 | <P> A much improved set of code can be found in the Lua distribution <TT> | |
36302 | src/lua/lua.c</TT>. Include your module, just add the external | |
36303 | declaration & add a <TT>#define LUA_EXTRALIBS {"example",Example_Init}</TT> | |
36304 | , at the relevant place.</P> | |
36305 | <P> The exact commands for doing this vary from platform to platform. | |
36306 | Here is a possible set of commands of doing this:</P> | |
36307 | <DIV class="shell"> | |
36308 | <PRE> | |
36309 | $ swig -lua example.i | |
36310 | $ gcc -I/usr/include/lua -c min.c -o min.o | |
36311 | $ gcc -I/usr/include/lua -c example_wrap.c -o example_wrap.o | |
36312 | $ gcc -c example.c -o example.o | |
36313 | $ gcc -I/usr/include/lua -L/usr/lib/lua min.o example_wrap.o example.o -o my_lua | |
36314 | </PRE> | |
36315 | </DIV> | |
36316 | <H3><A name="Lua_nn5"></A>29.2.2 Compiling a dynamic module</H3> | |
36317 | <P> Most, but not all platforms support the dynamic loading of modules | |
36318 | (Windows & Linux do). Refer to the Lua manual to determine if your | |
36319 | platform supports it. For compiling a dynamically loaded module the | |
36320 | same wrapper can be used. The commands will be something like this:</P> | |
36321 | <DIV class="shell"> | |
36322 | <PRE> | |
36323 | $ swig -lua example.i | |
36324 | $ gcc -I/usr/include/lua -c example_wrap.c -o example_wrap.o | |
36325 | $ gcc -c example.c -o example.o | |
36326 | $ gcc -shared -I/usr/include/lua -L/usr/lib/lua example_wrap.o example.o -o example.so | |
36327 | </PRE> | |
36328 | </DIV> | |
36329 | <P> You will also need an interpreter with the loadlib function (such as | |
36330 | the default interpreter compiled with Lua). In order to dynamically | |
36331 | load a module you must call the loadlib function with two parameters: | |
36332 | the filename of the shared library, and the function exported by SWIG. | |
36333 | Calling loadlib should return the function, which you then call to | |
36334 | initialise the module</P> | |
36335 | <DIV class="targetlang"> | |
36336 | <PRE> | |
36337 | my_init=loadlib("example.so","Example_Init") -- for Unix/Linux | |
36338 | --my_init=loadlib("example.dll","Example_Init") -- for Windows | |
36339 | assert(my_init) -- name sure its not nil | |
36340 | my_init() -- call the init fn of the lib | |
36341 | </PRE> | |
36342 | </DIV> | |
36343 | <P> Or can be done in a single line of Lua code</P> | |
36344 | <DIV class="targetlang"> | |
36345 | <PRE> | |
36346 | assert(loadlib("example.so","Example_Init"))() | |
36347 | </PRE> | |
36348 | </DIV> | |
36349 | <P> Update for Lua 5.1 (alpha): | |
36350 | <BR> The wrappers produced by SWIG can be compiled and linked with Lua | |
36351 | 5.1. The loading is now much simpler.</P> | |
36352 | <DIV class="targetlang"> | |
36353 | <PRE> | |
36354 | require("example") | |
36355 | </PRE> | |
36356 | </DIV> | |
36357 | <H3><A name="Lua_nn6"></A>29.2.3 Using your module</H3> | |
36358 | <P> Assuming all goes well, you will be able to this:</P> | |
36359 | <DIV class="targetlang"> | |
36360 | <PRE> | |
36361 | $ ./my_lua | |
36362 | > print(example.gcd(4,6)) | |
36363 | 2 | |
36364 | > print(example.Foo) | |
36365 | 3 | |
36366 | > example.Foo=4 | |
36367 | > print(example.Foo) | |
36368 | 4 | |
36369 | > | |
36370 | </PRE> | |
36371 | </DIV> | |
36372 | <H2><A name="Lua_nn7"></A>29.3 A tour of basic C/C++ wrapping</H2> | |
36373 | <P> By default, SWIG tries to build a very natural Lua interface to your | |
36374 | C/C++ code. This section briefly covers the essential aspects of this | |
36375 | wrapping.</P> | |
36376 | <H3><A name="Lua_nn8"></A>29.3.1 Modules</H3> | |
36377 | <P> The SWIG module directive specifies the name of the Lua module. If | |
36378 | you specify `module example', then everything is wrapped into a Lua | |
36379 | table 'example' containing all the functions and variables. When | |
36380 | choosing a module name, make sure you don't use the same name as a | |
36381 | built-in Lua command or standard module name.</P> | |
36382 | <H3><A name="Lua_nn9"></A>29.3.2 Functions</H3> | |
36383 | <P> Global functions are wrapped as new Lua built-in functions. For | |
36384 | example,</P> | |
36385 | <DIV class="code"> | |
36386 | <PRE> | |
36387 | %module example | |
36388 | int fact(int n);</PRE> | |
36389 | </DIV> | |
36390 | <P> creates a built-in function <TT>example.fact(n)</TT> that works | |
36391 | exactly like you think it does:</P> | |
36392 | <DIV class="targetlang"> | |
36393 | <PRE> | |
36394 | > print example.fact(4) | |
36395 | 24 | |
36396 | > | |
36397 | </PRE> | |
36398 | </DIV> | |
36399 | <P> To avoid name collisions, SWIG create a Lua table which it keeps all | |
36400 | the functions and global variables in. It is possible to copy the | |
36401 | functions out of this and into the global environment with the | |
36402 | following code. This can easily overwrite existing functions, so this | |
36403 | must be used with care.</P> | |
36404 | <DIV class="targetlang"> | |
36405 | <PRE> | |
36406 | > for k,v in pairs(example) do _G[k]=v end | |
36407 | > print(fact(4)) | |
36408 | 24 | |
36409 | > | |
36410 | </PRE> | |
36411 | </DIV> | |
36412 | <P> It is also possible to rename the module with an assignment.</P> | |
36413 | <DIV class="targetlang"> | |
36414 | <PRE> | |
36415 | > e=example | |
36416 | > print(e.fact(4)) | |
36417 | 24 | |
36418 | > print(example.fact(4)) | |
36419 | 24 | |
36420 | </PRE> | |
36421 | </DIV> | |
36422 | <H3><A name="Lua_nn10"></A>29.3.3 Global variables</H3> | |
36423 | <P> Global variables (which are linked to C code) are supported, and | |
36424 | appear to be just another variable in Lua. However the actual mechanism | |
36425 | is more complex. Given a global variable:</P> | |
36426 | <DIV class="code"> | |
36427 | <PRE>%module example | |
36428 | extern double Foo; | |
36429 | </PRE> | |
36430 | </DIV> | |
36431 | <P> SWIG will actually generate two functions <TT>example.Foo_set()</TT> | |
36432 | and <TT>example.Foo_get()</TT>. It then adds a metatable to the table | |
36433 | 'example' to call these functions at the correct time (when you attempt | |
36434 | to set or get examples.Foo). Therefore if you were to attempt to assign | |
36435 | the global to another variable, you will get a local copy within the | |
36436 | interpreter, which is no longer linked to the C code.</P> | |
36437 | <DIV class="targetlang"> | |
36438 | <PRE> | |
36439 | > print(example.Foo) | |
36440 | 3 | |
36441 | > c=example.Foo -- c is a COPY of example.Foo, not the same thing | |
36442 | > example.Foo=4 | |
36443 | > print(c) | |
36444 | 3 | |
36445 | > c=5 -- this will not effect the original example.Foo | |
36446 | > print(example.Foo,c) | |
36447 | 4 5 | |
36448 | </PRE> | |
36449 | </DIV> | |
36450 | <P> Its is therefore not possible to 'move' the global variable into the | |
36451 | global namespace as it is with functions. It is however, possible to | |
36452 | rename the module with an assignment, to make it more convenient.</P> | |
36453 | <DIV class="targetlang"> | |
36454 | <PRE> | |
36455 | > e=example | |
36456 | > -- e and example are the same table | |
36457 | > -- so e.Foo and example.Foo are the same thing | |
36458 | > example.Foo=4 | |
36459 | > print(e.Foo) | |
36460 | 4 | |
36461 | </PRE> | |
36462 | </DIV> | |
36463 | <P> If a variable is marked with the immutable directive then any | |
36464 | attempts to set this variable are silently ignored.</P> | |
36465 | <P> Another interesting feature is that it is not possible to add new | |
36466 | values into the module from within the interpreter, this is because of | |
36467 | the metatable to deal with global variables. It is possible (though not | |
36468 | recommended) to use rawset() to add a new value.</P> | |
36469 | <DIV class="targetlang"> | |
36470 | <PRE> | |
36471 | > -- example.PI does not exist | |
36472 | > print(example.PI) | |
36473 | nil | |
36474 | > example.PI=3.142 -- assign failed, example.PI does still not exist | |
36475 | > print(example.PI) | |
36476 | nil | |
36477 | > -- a rawset will work, after this the value is added | |
36478 | > rawset(example,"PI",3.142) | |
36479 | > print(example.PI) | |
36480 | 3.142 | |
36481 | </PRE> | |
36482 | </DIV> | |
36483 | <H3><A name="Lua_nn11"></A>29.3.4 Constants and enums</H3> | |
36484 | <P> Because Lua doesn't really have the concept of constants, C/C++ | |
36485 | constants are not really constant in Lua. They are actually just a copy | |
36486 | of the value into the Lua interpreter. Therefore they can be changed | |
36487 | just as any other value. For example given some constants:</P> | |
36488 | <DIV class="code"> | |
36489 | <PRE>%module example | |
36490 | %constant int ICONST=42; | |
36491 | #define SCONST "Hello World" | |
36492 | enum Days{SUNDAY,MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY}; | |
36493 | </PRE> | |
36494 | </DIV> | |
36495 | <P> This is 'effectively' converted into the following Lua code:</P> | |
36496 | <DIV class="targetlang"> | |
36497 | <PRE> | |
36498 | example.ICONST=42 | |
36499 | example.SCONST="Hello World" | |
36500 | example.SUNDAY=0 | |
36501 | .... | |
36502 | </PRE> | |
36503 | </DIV> | |
36504 | <P> Constants are not guaranteed to remain constant in Lua. The name of | |
36505 | the constant could be accidentally reassigned to refer to some other | |
36506 | object. Unfortunately, there is no easy way for SWIG to generate code | |
36507 | that prevents this. You will just have to be careful.</P> | |
36508 | <H3><A name="Lua_nn12"></A>29.3.5 Pointers</H3> | |
36509 | <P> C/C++ pointers are fully supported by SWIG. Furthermore, SWIG has no | |
36510 | problem working with incomplete type information. Given a wrapping of | |
36511 | the <file.h> interface:</P> | |
36512 | <DIV class="code"> | |
36513 | <PRE>%module example | |
36514 | ||
36515 | FILE *fopen(const char *filename, const char *mode); | |
36516 | int fputs(const char *, FILE *); | |
36517 | int fclose(FILE *); | |
36518 | </PRE> | |
36519 | </DIV> | |
36520 | <P> When wrapped, you will be able to use the functions in a natural way | |
36521 | from Lua. For example:</P> | |
36522 | <DIV class="targetlang"> | |
36523 | <PRE> | |
36524 | > f=example.fopen("junk","w") | |
36525 | > example.fputs("Hello World",f) | |
36526 | > example.fclose(f) | |
36527 | </PRE> | |
36528 | </DIV> | |
36529 | <P> Unlike many scripting languages, Lua has had support for pointers to | |
36530 | C/C++ object built in for a long time. They are called 'userdata'. | |
36531 | Unlike many other SWIG versions which use some kind of encoded | |
36532 | character string, all objects will be represented as a userdata. The | |
36533 | SWIG-Lua bindings provides a special function <TT>swig_type()</TT>, | |
36534 | which if given a userdata object will return the type of object pointed | |
36535 | to as a string (assuming it was a SWIG wrappered object).</P> | |
36536 | <DIV class="targetlang"> | |
36537 | <PRE> | |
36538 | > print(f) | |
36539 | userdata: 003FDA80 | |
36540 | > print(swig_type(f)) | |
36541 | _p_FILE -- its a FILE* | |
36542 | </PRE> | |
36543 | </DIV> | |
36544 | <P> Lua enforces the integrity of its userdata, so it is virtually | |
36545 | impossible to corrupt the data. But as the user of the pointer, you are | |
36546 | responsible for freeing it, or closing any resources associated with it | |
36547 | (just as you would in a C program). This does not apply so strictly to | |
36548 | classes & structs (see below). One final note: if a function returns a | |
36549 | NULL pointer, this is not encoded as a userdata, but as a Lua nil.</P> | |
36550 | <DIV class="targetlang"> | |
36551 | <PRE> | |
36552 | > f=example.fopen("not there","r") -- this will return a NULL in C | |
36553 | > print(f) | |
36554 | nil | |
36555 | </PRE> | |
36556 | </DIV> | |
36557 | <H3><A name="Lua_nn13"></A>29.3.6 Structures</H3> | |
36558 | <P> If you wrap a C structure, it is also mapped to a Lua userdata. By | |
36559 | adding a metatable to the userdata, this provides a very natural | |
36560 | interface. For example,</P> | |
36561 | <DIV class="code"> | |
36562 | <PRE>struct Point{ | |
36563 | int x,y; | |
36564 | }; | |
36565 | </PRE> | |
36566 | </DIV> | |
36567 | <P> is used as follows:</P> | |
36568 | <DIV class="targetlang"> | |
36569 | <PRE> | |
36570 | > p=example.Point() | |
36571 | > p.x=3 | |
36572 | > p.y=5 | |
36573 | > print(p.x,p.y) | |
36574 | 3 5 | |
36575 | > | |
36576 | </PRE> | |
36577 | </DIV> | |
36578 | <P> Similar access is provided for unions and the data members of C++ | |
36579 | classes. | |
36580 | <BR> SWIG will also create a function <TT>new_Point()</TT> which also | |
36581 | creates a new Point structure.</P> | |
36582 | <P> If you print out the value of p in the above example, you will see | |
36583 | something like this:</P> | |
36584 | <DIV class="targetlang"> | |
36585 | <PRE> | |
36586 | > print(p) | |
36587 | userdata: 003FA320 | |
36588 | </PRE> | |
36589 | </DIV> | |
36590 | <P> Like the pointer in the previous section, this is held as a | |
36591 | userdata. However, additional features have been added to make this | |
36592 | more usable. SWIG creates some accessor/mutator functions <TT> | |
36593 | Point_set_x()</TT> and <TT>Point_get_x()</TT>. These will be wrappered, | |
36594 | and then added to the metatable added to the userdata. This provides | |
36595 | the natural access to the member variables that were shown above (see | |
36596 | end of the document for full details).</P> | |
36597 | <P> <TT>const</TT> members of a structure are read-only. Data members | |
36598 | can also be forced to be read-only using the immutable directive. As | |
36599 | with other immutable's, setting attempts will be silently ignored. For | |
36600 | example:</P> | |
36601 | <DIV class="code"> | |
36602 | <PRE>struct Foo { | |
36603 | ... | |
36604 | %immutable; | |
36605 | int x; // Read-only members | |
36606 | char *name; | |
36607 | %mutable; | |
36608 | ... | |
36609 | }; | |
36610 | </PRE> | |
36611 | </DIV> | |
36612 | <P> The mechanism for managing char* members as well as array members is | |
36613 | similar to other languages. It is somewhat cumbersome and should | |
36614 | probably be better handled by defining of typemaps (described later).</P> | |
36615 | <P> When a member of a structure is itself a structure, it is handled as | |
36616 | a pointer. For example, suppose you have two structures like this:</P> | |
36617 | <DIV class="code"> | |
36618 | <PRE>struct Foo { | |
36619 | int a; | |
36620 | }; | |
36621 | ||
36622 | struct Bar { | |
36623 | Foo f; | |
36624 | }; | |
36625 | </PRE> | |
36626 | </DIV> | |
36627 | <P> Now, suppose that you access the f attribute of Bar like this:</P> | |
36628 | <DIV class="targetlang"> | |
36629 | <PRE> | |
36630 | > b = Bar() | |
36631 | > x = b.f | |
36632 | </PRE> | |
36633 | </DIV> | |
36634 | <P> In this case, x is a pointer that points to the Foo that is inside | |
36635 | b. This is the same value as generated by this C code:</P> | |
36636 | <DIV class="code"> | |
36637 | <PRE> | |
36638 | Bar b; | |
36639 | Foo *x = &b->f; // Points inside b | |
36640 | </PRE> | |
36641 | </DIV> | |
36642 | <P> Because the pointer points inside the structure, you can modify the | |
36643 | contents and everything works just like you would expect. For example:</P> | |
36644 | <DIV class="targetlang"> | |
36645 | <PRE> | |
36646 | > b = Bar() | |
36647 | > b.f.a = 3 -- Modify attribute of structure member | |
36648 | > x = b.f | |
36649 | > x.a = 3 -- Modifies the same structure | |
36650 | </PRE> | |
36651 | </DIV> | |
36652 | <H3><A name="Lua_nn14"></A>29.3.7 C++ classes</H3> | |
36653 | <P> C++ classes are wrapped by a Lua userdata as well. For example, if | |
36654 | you have this class,</P> | |
36655 | <DIV class="code"> | |
36656 | <PRE>class List { | |
36657 | public: | |
36658 | List(); | |
36659 | ~List(); | |
36660 | int search(char *item); | |
36661 | void insert(char *item); | |
36662 | void remove(char *item); | |
36663 | char *get(int n); | |
36664 | int length; | |
36665 | }; | |
36666 | </PRE> | |
36667 | </DIV> | |
36668 | <P> you can use it in Lua like this:</P> | |
36669 | <DIV class="targetlang"> | |
36670 | <PRE> | |
36671 | > l = example.List() | |
36672 | > l.insert("Ale") | |
36673 | > l.insert("Stout") | |
36674 | > l.insert("Lager") | |
36675 | > print(l.get(1)) | |
36676 | Stout | |
36677 | > print(l.length) | |
36678 | 3 | |
36679 | > | |
36680 | </PRE> | |
36681 | </DIV> | |
36682 | <P> Class data members are accessed in the same manner as C structures. | |
36683 | Static class members present a special problem for Lua, as Lua doesn't | |
36684 | have support for such features. Therefore, SWIG generates wrappers that | |
36685 | try to work around some of these issues. To illustrate, suppose you | |
36686 | have a class like this:</P> | |
36687 | <DIV class="targetlang"> | |
36688 | <PRE>class Spam { | |
36689 | public: | |
36690 | static void foo(); | |
36691 | static int bar; | |
36692 | ||
36693 | }; | |
36694 | </PRE> | |
36695 | </DIV> | |
36696 | <P> In Lua, the static members can be accessed as follows:</P> | |
36697 | <DIV class="code"> | |
36698 | <PRE> | |
36699 | > example.Spam_foo() -- Spam::foo() the only way currently | |
36700 | > a=example.Spam_bar_get() -- Spam::bar the hard way | |
36701 | > a=example.Spam_bar -- Spam::bar the nicer way | |
36702 | > example.Spam_bar_set(b) -- Spam::bar the hard way | |
36703 | > example.Spam_bar=b -- Spam::bar the nicer way | |
36704 | </PRE> | |
36705 | </DIV> | |
36706 | <P> It is not (currently) possible to access static members of an | |
36707 | instance:</P> | |
36708 | <DIV class="targetlang"> | |
36709 | <PRE> | |
36710 | > s=example.Spam() -- s is a Spam instance | |
36711 | > s.foo() -- Spam::foo() via an instance | |
36712 | -- does NOT work | |
36713 | </PRE> | |
36714 | </DIV> | |
36715 | <H3><A name="Lua_nn15"></A>29.3.8 C++ inheritance</H3> | |
36716 | <P> SWIG is fully aware of issues related to C++ inheritance. Therefore, | |
36717 | if you have classes like this</P> | |
36718 | <DIV class="code"> | |
36719 | <PRE>class Foo { | |
36720 | ... | |
36721 | }; | |
36722 | ||
36723 | class Bar : public Foo { | |
36724 | ... | |
36725 | }; | |
36726 | </PRE> | |
36727 | </DIV> | |
36728 | <P> And if you have functions like this</P> | |
36729 | <DIV class="code"> | |
36730 | <PRE>void spam(Foo *f); | |
36731 | </PRE> | |
36732 | </DIV> | |
36733 | <P> then the function <TT>spam()</TT> accepts a Foo pointer or a pointer | |
36734 | to any class derived from Foo.</P> | |
36735 | <P> It is safe to use multiple inheritance with SWIG.</P> | |
36736 | <H3><A name="Lua_nn16"></A>29.3.9 Pointers, references, values, and | |
36737 | arrays</H3> | |
36738 | <P> In C++, there are many different ways a function might receive and | |
36739 | manipulate objects. For example:</P> | |
36740 | <DIV class="code"> | |
36741 | <PRE>void spam1(Foo *x); // Pass by pointer | |
36742 | void spam2(Foo &x); // Pass by reference | |
36743 | void spam3(Foo x); // Pass by value | |
36744 | void spam4(Foo x[]); // Array of objects | |
36745 | </PRE> | |
36746 | </DIV> | |
36747 | <P> In SWIG, there is no detailed distinction like this--specifically, | |
36748 | there are only "objects". There are no pointers, references, arrays, | |
36749 | and so forth. Because of this, SWIG unifies all of these types together | |
36750 | in the wrapper code. For instance, if you actually had the above | |
36751 | functions, it is perfectly legal to do this:</P> | |
36752 | <DIV class="targetlang"> | |
36753 | <PRE> | |
36754 | > f = Foo() -- Create a Foo | |
36755 | > spam1(f) -- Ok. Pointer | |
36756 | > spam2(f) -- Ok. Reference | |
36757 | > spam3(f) -- Ok. Value. | |
36758 | > spam4(f) -- Ok. Array (1 element) | |
36759 | </PRE> | |
36760 | </DIV> | |
36761 | <P> Similar behaviour occurs for return values. For example, if you had | |
36762 | functions like this,</P> | |
36763 | <DIV class="code"> | |
36764 | <PRE>Foo *spam5(); | |
36765 | Foo &spam6(); | |
36766 | Foo spam7(); | |
36767 | </PRE> | |
36768 | </DIV> | |
36769 | <P> then all three functions will return a pointer to some Foo object. | |
36770 | Since the third function (spam7) returns a value, newly allocated | |
36771 | memory is used to hold the result and a pointer is returned (Lua will | |
36772 | release this memory when the return value is garbage collected). The | |
36773 | other two are pointers which are assumed to be managed by the C code | |
36774 | and so will not be garbage collected.</P> | |
36775 | <H3><A name="Lua_nn17"></A>29.3.10 C++ overloaded functions</H3> | |
36776 | <P> C++ overloaded functions, methods, and constructors are mostly | |
36777 | supported by SWIG. For example, if you have two functions like this:</P> | |
36778 | <DIV class="code"> | |
36779 | <PRE>void foo(int); | |
36780 | void foo(char *c); | |
36781 | </PRE> | |
36782 | </DIV> | |
36783 | <P> You can use them in Lua in a straightforward manner:</P> | |
36784 | <DIV class="targetlang"> | |
36785 | <PRE> | |
36786 | > foo(3) -- foo(int) | |
36787 | > foo("Hello") -- foo(char *c) | |
36788 | </PRE> | |
36789 | </DIV> | |
36790 | <P> However due to Lua's coercion mechanism is can sometimes do strange | |
36791 | things.</P> | |
36792 | <DIV class="targetlang"> | |
36793 | <PRE> | |
36794 | > foo("3") -- "3" can be coerced into an int, so it calls foo(int)! | |
36795 | </PRE> | |
36796 | </DIV> | |
36797 | <P> As this coercion mechanism is an integral part of Lua, there is no | |
36798 | easy way to get around this other than renaming of functions (see | |
36799 | below).</P> | |
36800 | <P> Similarly, if you have a class like this,</P> | |
36801 | <DIV class="code"> | |
36802 | <PRE>class Foo { | |
36803 | public: | |
36804 | Foo(); | |
36805 | Foo(const Foo &); | |
36806 | ... | |
36807 | }; | |
36808 | </PRE> | |
36809 | </DIV> | |
36810 | <P> you can write Lua code like this:</P> | |
36811 | <DIV class="targetlang"> | |
36812 | <PRE> | |
36813 | > f = Foo() -- Create a Foo | |
36814 | > g = Foo(f) -- Copy f | |
36815 | </PRE> | |
36816 | </DIV> | |
36817 | <P> Overloading support is not quite as flexible as in C++. Sometimes | |
36818 | there are methods that SWIG can't disambiguate. For example:</P> | |
36819 | <DIV class="code"> | |
36820 | <PRE>void spam(int); | |
36821 | void spam(short); | |
36822 | </PRE> | |
36823 | </DIV> | |
36824 | <P> or</P> | |
36825 | <DIV CLASS="CODE"> | |
36826 | <PRE>VOID FOO(bAR *B); | |
36827 | void foo(Bar &b); | |
36828 | </PRE> | |
36829 | </DIV> | |
36830 | <P> If declarations such as these appear, you will get a warning message | |
36831 | like this:</P> | |
36832 | <DIV class="shell"> | |
36833 | <PRE> | |
36834 | example.i:12: Warning(509): Overloaded spam(short) is shadowed by spam(int) | |
36835 | at example.i:11. | |
36836 | </PRE> | |
36837 | </DIV> | |
36838 | <P> To fix this, you either need to ignore or rename one of the methods. | |
36839 | For example:</P> | |
36840 | <DIV class="code"> | |
36841 | <PRE>%rename(spam_short) spam(short); | |
36842 | ... | |
36843 | void spam(int); | |
36844 | void spam(short); // Accessed as spam_short | |
36845 | </PRE> | |
36846 | </DIV> | |
36847 | <P> or</P> | |
36848 | <DIV class="code"> | |
36849 | <PRE>%ignore spam(short); | |
36850 | ... | |
36851 | void spam(int); | |
36852 | void spam(short); // Ignored | |
36853 | </PRE> | |
36854 | </DIV> | |
36855 | <P> SWIG resolves overloaded functions and methods using a | |
36856 | disambiguation scheme that ranks and sorts declarations according to a | |
36857 | set of type-precedence rules. The order in which declarations appear in | |
36858 | the input does not matter except in situations where ambiguity | |
36859 | arises--in this case, the first declaration takes precedence.</P> | |
36860 | <P> Please refer to the "SWIG and C++" chapter for more information | |
36861 | about overloading.</P> | |
36862 | <P> Dealing with the Lua coercion mechanism, the priority is roughly | |
36863 | (integers, floats, strings, userdata). But it is better to rename the | |
36864 | functions rather than rely upon the ordering.</P> | |
36865 | <H3><A name="Lua_nn18"></A>29.3.11 C++ operators</H3> | |
36866 | <P> Certain C++ overloaded operators can be handled automatically by | |
36867 | SWIG. For example, consider a class like this:</P> | |
36868 | <DIV class="code"> | |
36869 | <PRE>class Complex { | |
36870 | private: | |
36871 | double rpart, ipart; | |
36872 | public: | |
36873 | Complex(double r = 0, double i = 0) : rpart(r), ipart(i) { } | |
36874 | Complex(const Complex &c) : rpart(c.rpart), ipart(c.ipart) { } | |
36875 | Complex &operator=(const Complex &c); | |
36876 | Complex operator+(const Complex &c) const; | |
36877 | Complex operator-(const Complex &c) const; | |
36878 | Complex operator*(const Complex &c) const; | |
36879 | Complex operator-() const; | |
36880 | ||
36881 | double re() const { return rpart; } | |
36882 | double im() const { return ipart; } | |
36883 | }; | |
36884 | </PRE> | |
36885 | </DIV> | |
36886 | <P> When wrapped, it works like you expect:</P> | |
36887 | <DIV class="targetlang"> | |
36888 | <PRE> | |
36889 | > c = Complex(3,4) | |
36890 | > d = Complex(7,8) | |
36891 | > e = c + d | |
36892 | > e:re() | |
36893 | 10.0 | |
36894 | > e:im() | |
36895 | 12.0 | |
36896 | </PRE> | |
36897 | </DIV> | |
36898 | <P> (Note: for calling methods of a class, you use <TT> | |
36899 | class:method(args)</TT>, not <TT>class.method(args)</TT>, its an easy | |
36900 | mistake to make.)</P> | |
36901 | <P> One restriction with operator overloading support is that SWIG is | |
36902 | not able to fully handle operators that aren't defined as part of the | |
36903 | class. For example, if you had code like this</P> | |
36904 | <DIV class="targetlang"> | |
36905 | <PRE>class Complex { | |
36906 | ... | |
36907 | friend Complex operator+(double, const Complex &c); | |
36908 | ... | |
36909 | }; | |
36910 | </PRE> | |
36911 | </DIV> | |
36912 | <P> then SWIG doesn't know what to do with the friend function--in fact, | |
36913 | it simply ignores it and issues a warning. You can still wrap the | |
36914 | operator, but you may have to encapsulate it in a special function. For | |
36915 | example:</P> | |
36916 | <DIV class="targetlang"> | |
36917 | <PRE>%rename(Complex_add_dc) operator+(double, const Complex &); | |
36918 | ... | |
36919 | Complex operator+(double, const Complex &c); | |
36920 | </PRE> | |
36921 | </DIV> | |
36922 | <P> There are ways to make this operator appear as part of the class | |
36923 | using the <TT>%extend</TT> directive. Keep reading.</P> | |
36924 | <P> Also, be aware that certain operators don't map cleanly to Lua, and | |
36925 | some Lua operators don't map cleanly to C++ operators. For instance, | |
36926 | overloaded assignment operators don't map to Lua semantics and will be | |
36927 | ignored, and C++ doesn't support Lua's concatenation operator (<TT>..</TT> | |
36928 | ).</P> | |
36929 | <P> In order to keep maximum compatibility within the different | |
36930 | languages in SWIG, the Lua bindings uses the same set of operator names | |
36931 | as python. Although internally it renames the functions to something | |
36932 | else (on order to work with Lua).</P> | |
36933 | <P> The current list of operators which can be overloaded (and the | |
36934 | alternative function names) are:</P> | |
36935 | <UL> | |
36936 | <LI><TT>__add__</TT> operator+</LI> | |
36937 | <LI><TT>__sub__</TT> operator-</LI> | |
36938 | <LI><TT>__mul__</TT> operator *</LI> | |
36939 | <LI><TT>__div__</TT> operator/</LI> | |
36940 | <LI><TT>__neg__</TT> unary minus</LI> | |
36941 | <LI><TT>__call__</TT> operator<TT>()</TT> (often used in functor | |
36942 | classes)</LI> | |
36943 | <LI><TT>__pow__</TT> the exponential fn (no C++ equivalent, Lua uses <TT> | |
36944 | ^</TT>)</LI> | |
36945 | <LI><TT>__concat__</TT> the concatenation operator (SWIG maps C++'s <TT> | |
36946 | ~</TT> to Lua's <TT>..</TT>)</LI> | |
36947 | <LI><TT>__eq__</TT> operator<TT>==</TT></LI> | |
36948 | <LI><TT>__lt__</TT> operator<TT><</TT></LI> | |
36949 | <LI><TT>__le__</TT> operator<TT><=</TT></LI> | |
36950 | </UL> | |
36951 | <P> Note: in Lua, only the equals, less than, and less than equals | |
36952 | operators are defined. The other operators (!=,>,>=) are achieved by | |
36953 | using a logical not applied to the results of other operators.</P> | |
36954 | <P> The following operators cannot be overloaded (mainly because they | |
36955 | are not supported in Lua)</P> | |
36956 | <UL> | |
36957 | <LI>++ and --</LI> | |
36958 | <LI>+=,-=,*= etc</LI> | |
36959 | <LI>% operator (you have to use math.mod)</LI> | |
36960 | <LI>assignment operator</LI> | |
36961 | <LI>all bitwise/logical operations</LI> | |
36962 | </UL> | |
36963 | <P> SWIG also accepts the <TT>__str__()</TT> member function which | |
36964 | converts an object to a string. This function should return a const | |
36965 | char*, preferably to static memory. This will be used for the <TT> | |
36966 | print()</TT> and <TT>tostring()</TT> functions in Lua. Assuming the | |
36967 | complex class has a function</P> | |
36968 | <DIV class="code"> | |
36969 | <PRE>const char* __str__() | |
36970 | { | |
36971 | static char buffer[255]; | |
36972 | sprintf(buffer,"Complex(%g,%g)",this->re(),this->im()); | |
36973 | return buffer; | |
36974 | } | |
36975 | </PRE> | |
36976 | </DIV> | |
36977 | <P> Then this will support the following code in Lua</P> | |
36978 | <DIV class="targetlang"> | |
36979 | <PRE> | |
36980 | > c = Complex(3,4) | |
36981 | > d = Complex(7,8) | |
36982 | > e = c + d | |
36983 | > print(e) | |
36984 | Complex(10,12) | |
36985 | > s=tostring(e) -- s is the number in string form | |
36986 | > print(s) | |
36987 | Complex(10,12) | |
36988 | </PRE> | |
36989 | </DIV> | |
36990 | <P> It is also possible to overload the operator<TT>[]</TT>, but | |
36991 | currently this cannot be automatically performed. To overload the | |
36992 | operator<TT>[]</TT> you need to provide two functions, <TT> | |
36993 | __getitem__()</TT> and <TT>__setitem__()</TT></P> | |
36994 | <DIV class="code"> | |
36995 | <PRE>class Complex | |
36996 | { | |
36997 | //.... | |
36998 | double __getitem__(int i)const; // i is the index, returns the data | |
36999 | void __setitem__(int i,double d); // i is the index, d is the data | |
37000 | }; | |
37001 | </PRE> | |
37002 | </DIV> | |
37003 | <H3><A name="Lua_nn19"></A>29.3.12 Class extension with %extend</H3> | |
37004 | <P> One of the more interesting features of SWIG is that it can extend | |
37005 | structures and classes with new methods. In the previous section, the | |
37006 | Complex class would have benefited greatly from an __str__() method as | |
37007 | well as some repairs to the operator overloading. It can also be used | |
37008 | to add additional functions to the class if they are needed.</P> | |
37009 | <P> Take the original Complex class</P> | |
37010 | <DIV class="code"> | |
37011 | <PRE>class Complex { | |
37012 | private: | |
37013 | double rpart, ipart; | |
37014 | public: | |
37015 | Complex(double r = 0, double i = 0) : rpart(r), ipart(i) { } | |
37016 | Complex(const Complex &c) : rpart(c.rpart), ipart(c.ipart) { } | |
37017 | Complex &operator=(const Complex &c); | |
37018 | Complex operator+(const Complex &c) const; | |
37019 | Complex operator-(const Complex &c) const; | |
37020 | Complex operator*(const Complex &c) const; | |
37021 | Complex operator-() const; | |
37022 | ||
37023 | double re() const { return rpart; } | |
37024 | double im() const { return ipart; } | |
37025 | }; | |
37026 | </PRE> | |
37027 | </DIV> | |
37028 | <P> Now we extend it with some new code</P> | |
37029 | <DIV class="code"> | |
37030 | <PRE>%extend Complex { | |
37031 | const char *__str__() { | |
37032 | static char tmp[1024]; | |
37033 | sprintf(tmp,"Complex(%g,%g)", self->re(),self->im()); | |
37034 | return tmp; | |
37035 | } | |
37036 | bool operator==(const Complex& c) | |
37037 | { return (self->re()==c.re() && self->im()==c.im();} | |
37038 | }; | |
37039 | </PRE> | |
37040 | </DIV> | |
37041 | <P> Now, in Lua</P> | |
37042 | <DIV class="targetlang"> | |
37043 | <PRE> | |
37044 | > c = Complex(3,4) | |
37045 | > d = Complex(7,8) | |
37046 | > e = c + d | |
37047 | > print(e) -- print uses __str__ to get the string form to print | |
37048 | Complex(10,12) | |
37049 | > print(e==Complex(10,12)) -- testing the == operator | |
37050 | true | |
37051 | > print(e!=Complex(12,12)) -- the != uses the == operator | |
37052 | true | |
37053 | </PRE> | |
37054 | </DIV> | |
37055 | <P> Extend works with both C and C++ code, on classes and structs. It | |
37056 | does not modify the underlying object in any way---the extensions only | |
37057 | show up in the Lua interface. The only item to take note of is the code | |
37058 | has to use the 'self' instead of 'this', and that you cannot access | |
37059 | protected/private members of the code (as you are not officially part | |
37060 | of the class).</P> | |
37061 | <H3><A name="Lua_nn20"></A>29.3.13 C++ templates</H3> | |
37062 | <P> C++ templates don't present a huge problem for SWIG. However, in | |
37063 | order to create wrappers, you have to tell SWIG to create wrappers for | |
37064 | a particular template instantiation. To do this, you use the template | |
37065 | directive. For example:</P> | |
37066 | <DIV class="code"> | |
37067 | <PRE>%module example | |
37068 | %{ | |
37069 | #include "pair.h" | |
37070 | %} | |
37071 | ||
37072 | template<class T1, class T2> | |
37073 | struct pair { | |
37074 | typedef T1 first_type; | |
37075 | typedef T2 second_type; | |
37076 | T1 first; | |
37077 | T2 second; | |
37078 | pair(); | |
37079 | pair(const T1&, const T2&); | |
37080 | ~pair(); | |
37081 | }; | |
37082 | ||
37083 | %template(pairii) pair<int,int>; | |
37084 | </PRE> | |
37085 | </DIV> | |
37086 | <P> In Lua:</P> | |
37087 | <DIV class="targetlang"> | |
37088 | <PRE> | |
37089 | > p = example.pairii(3,4) | |
37090 | > print(p.first,p.second) | |
37091 | 3 4 | |
37092 | </PRE> | |
37093 | </DIV> | |
37094 | <P> Obviously, there is more to template wrapping than shown in this | |
37095 | example. More details can be found in the SWIG and C++ chapter. Some | |
37096 | more complicated examples will appear later.</P> | |
37097 | <H3><A name="Lua_nn21"></A>29.3.14 C++ Smart Pointers</H3> | |
37098 | <P> In certain C++ programs, it is common to use classes that have been | |
37099 | wrapped by so-called "smart pointers." Generally, this involves the use | |
37100 | of a template class that implements operator->() like this:</P> | |
37101 | <DIV class="code"> | |
37102 | <PRE>template<class T> class SmartPtr { | |
37103 | ... | |
37104 | T *operator->(); | |
37105 | ... | |
37106 | } | |
37107 | </PRE> | |
37108 | </DIV> | |
37109 | <P> Then, if you have a class like this,</P> | |
37110 | <DIV class="code"> | |
37111 | <PRE>class Foo { | |
37112 | public: | |
37113 | int x; | |
37114 | int bar(); | |
37115 | }; | |
37116 | </PRE> | |
37117 | </DIV> | |
37118 | <P> A smart pointer would be used in C++ as follows:</P> | |
37119 | <DIV class="code"> | |
37120 | <PRE>SmartPtr<Foo> p = CreateFoo(); // Created somehow (not shown) | |
37121 | ... | |
37122 | p->x = 3; // Foo::x | |
37123 | int y = p->bar(); // Foo::bar | |
37124 | </PRE> | |
37125 | </DIV> | |
37126 | <P> To wrap this, simply tell SWIG about the SmartPtr class and the | |
37127 | low-level Foo object. Make sure you instantiate SmartPtr using template | |
37128 | if necessary. For example:</P> | |
37129 | <DIV class="code"> | |
37130 | <PRE>%module example | |
37131 | ... | |
37132 | %template(SmartPtrFoo) SmartPtr<Foo>; | |
37133 | ... | |
37134 | </PRE> | |
37135 | </DIV> | |
37136 | <P> Now, in Lua, everything should just "work":</P> | |
37137 | <DIV class="targetlang"> | |
37138 | <PRE> | |
37139 | > p = example.CreateFoo() -- Create a smart-pointer somehow | |
37140 | > p.x = 3 -- Foo::x | |
37141 | > print(p:bar()) -- Foo::bar | |
37142 | </PRE> | |
37143 | </DIV> | |
37144 | <P> If you ever need to access the underlying pointer returned by <TT> | |
37145 | operator->()</TT> itself, simply use the <TT>__deref__()</TT> method. | |
37146 | For example:</P> | |
37147 | <DIV class="targetlang"> | |
37148 | <PRE> | |
37149 | > f = p:__deref__() -- Returns underlying Foo * | |
37150 | </PRE> | |
37151 | </DIV> | |
37152 | <H2><A name="Lua_nn22"></A>29.4 Details on the Lua binding</H2> | |
37153 | <P> In the previous section, a high-level view of Lua wrapping was | |
37154 | presented. Obviously a lot of stuff happens behind the scenes to make | |
37155 | this happen. This section will explain some of the low-level details on | |
37156 | how this is achieved.</P> | |
37157 | <P><I> If you just want to use SWIG and don't care how it works, then | |
37158 | stop reading here. This is going into the guts of the code and how it | |
37159 | works. Its mainly for people who need to know whats going on within the | |
37160 | code.</I></P> | |
37161 | <H3><A name="Lua_nn23"></A>29.4.1 Binding global data into the module.</H3> | |
37162 | <P> Assuming that you had some global data that you wanted to share | |
37163 | between C and Lua. How does SWIG do it?</P> | |
37164 | <DIV class="code"> | |
37165 | <PRE>%module example; | |
37166 | extern double Foo; | |
37167 | </PRE> | |
37168 | </DIV> | |
37169 | <P> SWIG will effectively generate the pair of functions</P> | |
37170 | <DIV class="code"> | |
37171 | <PRE>void Foo_set(double); | |
37172 | double Foo_get(); | |
37173 | </PRE> | |
37174 | </DIV> | |
37175 | <P> At initialisation time, it will then add to the interpreter a table | |
37176 | called 'example', which represents the module. It will then add all its | |
37177 | functions to the module. But it also adds a metatable to this table, | |
37178 | which has two functions (<TT>__index</TT> and <TT>__newindex</TT>) as | |
37179 | well as two tables (<TT>.get</TT> and <TT>.set</TT>) The following Lua | |
37180 | code will show these hidden features.</P> | |
37181 | <DIV class="targetlang"> | |
37182 | <PRE> | |
37183 | > print(example) | |
37184 | table: 003F8F90 | |
37185 | > m=getmetatable(example) | |
37186 | > table.foreach(m,print) | |
37187 | .set table: 003F9088 | |
37188 | .get table: 003F9038 | |
37189 | __index function: 003F8FE0 | |
37190 | __newindex function: 003F8FF8 | |
37191 | > g=m['.get'] | |
37192 | > table.foreach(g,print) | |
37193 | Foo function: 003FAFD8 | |
37194 | > | |
37195 | </PRE> | |
37196 | </DIV> | |
37197 | <P> The .get and .set tables are lookups connecting the variable name | |
37198 | 'Foo' to the accessor/mutator functions (Foo_set,Foo_get)</P> | |
37199 | <P> The Lua equivalent of the code for the <TT>__index</TT> and <TT> | |
37200 | __newindex</TT> looks a bit like this</P> | |
37201 | <DIV class="targetlang"> | |
37202 | <PRE> | |
37203 | function __index(mod,name) | |
37204 | local g=getmetatable(mod)['.get'] -- gets the table | |
37205 | if not g then return nil end | |
37206 | local f=g[name] -- looks for the function | |
37207 | -- calls it & returns the value | |
37208 | if type(f)=="function" then return f() end | |
37209 | return nil | |
37210 | end | |
37211 | ||
37212 | function __newindex(mod,name,value) | |
37213 | local s=getmetatable(mod)['.set'] -- gets the table | |
37214 | if not s then return end | |
37215 | local f=s[name] -- looks for the function | |
37216 | -- calls it to set the value | |
37217 | if type(f)=="function" then f(value) end | |
37218 | end | |
37219 | </PRE> | |
37220 | </DIV> | |
37221 | <P> That way when you call '<TT>a=example.Foo</TT>', the interpreter | |
37222 | looks at the table 'example' sees that there is no field 'Foo' and | |
37223 | calls __index. This will in turn check in '.get' table and find the | |
37224 | existence of 'Foo' and then return the value of the C function call | |
37225 | 'Foo_get()'. Similarly for the code '<TT>example.Foo=10</TT>', the | |
37226 | interpreter will check the table, then call the __newindex which will | |
37227 | then check the '.set' table and call the C function 'Foo_set(10)'.</P> | |
37228 | <H3><A name="Lua_nn24"></A>29.4.2 Userdata and Metatables</H3> | |
37229 | <P> As mentioned earlier, classes and structures, are all held as | |
37230 | pointer, using the Lua 'userdata' structure. This structure is actually | |
37231 | a pointer to a C structure 'swig_lua_userdata', which contains the | |
37232 | pointer to the data, a pointer to the swig_type_info (an internal SWIG | |
37233 | struct) and a flag which marks if the object is to be disposed of when | |
37234 | the interpreter no longer needs it. The actual accessing of the object | |
37235 | is done via the metatable attached to this userdata.</P> | |
37236 | <P> The metatable is a Lua 5.0 feature (which is also why SWIG cannot | |
37237 | wrap Lua 4.0). Its a table which holds a list of functions, operators | |
37238 | and attributes. This is what gives the userdata the feeling that it is | |
37239 | a real object and not just a hunk of memory.</P> | |
37240 | <P> Given a class</P> | |
37241 | <DIV class="code"> | |
37242 | <PRE>%module excpp; | |
37243 | ||
37244 | class Point | |
37245 | { | |
37246 | public: | |
37247 | int x,y; | |
37248 | Point(){x=y=0;} | |
37249 | ~Point(){} | |
37250 | virtual void Print(){printf("Point @%p (%d,%d)\n",this,x,y);} | |
37251 | }; | |
37252 | </PRE> | |
37253 | </DIV> | |
37254 | <P> SWIG will create a module excpp, with all the various function | |
37255 | inside. However to allow the intuitive use of the userdata is also | |
37256 | creates up a set of metatables. As seen in the above section on global | |
37257 | variables, use of the metatables allows for wrappers to be used | |
37258 | intuitively. To save effort, the code creates one metatable per class | |
37259 | and stores it inside Lua's registry. Then when an new object is | |
37260 | instantiated, the metatable is found in the registry and the userdata | |
37261 | associated to the metatable. Currently derived classes make a complete | |
37262 | copy of the base classes table and then add on their own additional | |
37263 | function.</P> | |
37264 | <P> Some of the internals can be seen by looking at a classes metatable.</P> | |
37265 | <DIV class="targetlang"> | |
37266 | <PRE> | |
37267 | > p=excpp.Point() | |
37268 | > print(p) | |
37269 | userdata: 003FDB28 | |
37270 | > m=getmetatable(p) | |
37271 | > table.foreach(m,print) | |
37272 | .type Point | |
37273 | __gc function: 003FB6C8 | |
37274 | __newindex function: 003FB6B0 | |
37275 | __index function: 003FB698 | |
37276 | .get table: 003FB4D8 | |
37277 | .set table: 003FB500 | |
37278 | .fn table: 003FB528 | |
37279 | </PRE> | |
37280 | </DIV> | |
37281 | <P> The '.type' attribute is the string which is returned from a call to | |
37282 | swig_type(). The '.get' and '.set' tables work in a similar manner to | |
37283 | the modules, the main difference is the '.fn' table which also holds | |
37284 | all the member functions. (The '__gc' function is the classes | |
37285 | destructor function)</P> | |
37286 | <P> The Lua equivalent of the code for enabling functions looks a little | |
37287 | like this</P> | |
37288 | <DIV class="targetlang"> | |
37289 | <PRE> | |
37290 | function __index(obj,name) | |
37291 | local m=getmetatable(obj) -- gets the metatable | |
37292 | if not m then return nil end | |
37293 | local g=m['.get'] -- gets the attribute table | |
37294 | if not g then return nil end | |
37295 | local f=g[name] -- looks for the get_attribute function | |
37296 | -- calls it & returns the value | |
37297 | if type(f)=="function" then return f() end | |
37298 | -- ok, so it not an attribute, maybe its a function | |
37299 | local fn=m['.fn'] -- gets the function table | |
37300 | if not fn then return nil end | |
37301 | local f=fn[name] -- looks for the function | |
37302 | -- if found the fn then return the function | |
37303 | -- so the interpreter can call it | |
37304 | if type(f)=="function" then return f end | |
37305 | return nil | |
37306 | end | |
37307 | </PRE> | |
37308 | </DIV> | |
37309 | <P> So when 'p:Print()' is called, the __index looks on the object | |
37310 | metatable for a 'Print' attribute, then looks for a 'Print' function. | |
37311 | When it finds the function, it returns the function, and then | |
37312 | interpreter can call 'Point_Print(p)'</P> | |
37313 | <P> In theory, you can play with this usertable & add new features, but | |
37314 | remember that it is a shared table between all instances of one class, | |
37315 | and you could very easily corrupt the functions in all the instances.</P> | |
37316 | <P> Note: Both the opaque structures (like the FILE*) and normal | |
37317 | wrappered classes/structs use the same 'swig_lua_userdata' structure. | |
37318 | Though the opaque structures has do not have a metatable attached, or | |
37319 | any information on how to dispose of them when the interpreter has | |
37320 | finished with them.</P> | |
37321 | <P> Note: Operator overloads are basically done in the same way, by | |
37322 | adding functions such as '__add' & '__call' to the classes metatable. | |
37323 | The current implementation is a bit rough as it will add any member | |
37324 | function beginning with '__' into the metatable too, assuming its an | |
37325 | operator overload.</P> | |
37326 | <H3><A name="Lua_nn25"></A>29.4.3 Memory management</H3> | |
37327 | <P> Lua is very helpful with the memory management. The | |
37328 | 'swig_lua_userdata' is fully managed by the interpreter itself. This | |
37329 | means that neither the C code nor the Lua code can damage it. Once a | |
37330 | piece of userdata has no references to it, it is not instantly | |
37331 | collected, but will be collected when Lua deems is necessary. (You can | |
37332 | force collection by calling the Lua function <TT>collectgarbage()</TT> | |
37333 | ). Once the userdata is about to be free'ed, the interpreter will check | |
37334 | the userdata for a metatable and for a function '__gc'. If this exists | |
37335 | this is called. For all complete types (ie normal wrappered classes & | |
37336 | structs) this should exist. The '__gc' function will check the | |
37337 | 'swig_lua_userdata' to check for the 'own' field and if this is true | |
37338 | (which is will be for all owned data's) it will then call the | |
37339 | destructor on the pointer.</P> | |
37340 | <P> It is currently not recommended to edit this field or add some user | |
37341 | code, to change the behaviour. Though for those who wish to try, here | |
37342 | is where to look.</P> | |
37343 | <P> It is also currently not possible to change the ownership flag on | |
37344 | the data (unlike most other scripting languages, Lua does not permit | |
37345 | access to the data from within the interpreter)</P> | |
37346 | <HR NOSHADE> | |
37347 | <H1><A name="Extending"></A>30 Extending SWIG</H1> | |
37348 | ||
37349 | <!-- INDEX --> | |
37350 | <DIV class="sectiontoc"> | |
37351 | <UL> | |
37352 | <LI><A href="#Extending_nn2">Introduction</A></LI> | |
37353 | <LI><A href="#Extending_nn3">Prerequisites</A></LI> | |
37354 | <LI><A href="#Extending_nn4">The Big Picture</A></LI> | |
37355 | <LI><A href="#Extending_nn5">Execution Model</A> | |
37356 | <UL> | |
37357 | <LI><A href="#Extending_nn6">Preprocessing</A></LI> | |
37358 | <LI><A href="#Extending_nn7">Parsing</A></LI> | |
37359 | <LI><A href="#Extending_nn8">Parse Trees</A></LI> | |
37360 | <LI><A href="#Extending_nn9">Attribute namespaces</A></LI> | |
37361 | <LI><A href="#Extending_nn10">Symbol Tables</A></LI> | |
37362 | <LI><A href="#Extending_nn11">The %feature directive</A></LI> | |
37363 | <LI><A href="#Extending_nn12">Code Generation</A></LI> | |
37364 | <LI><A href="#Extending_nn13">SWIG and XML</A></LI> | |
37365 | </UL> | |
37366 | </LI> | |
37367 | <LI><A href="#Extending_nn14">Primitive Data Structures</A> | |
37368 | <UL> | |
37369 | <LI><A href="#Extending_nn15">Strings</A></LI> | |
37370 | <LI><A href="#Extending_nn16">Hashes</A></LI> | |
37371 | <LI><A href="#Extending_nn17">Lists</A></LI> | |
37372 | <LI><A href="#Extending_nn18">Common operations</A></LI> | |
37373 | <LI><A href="#Extending_nn19">Iterating over Lists and Hashes</A></LI> | |
37374 | <LI><A href="#Extending_nn20">I/O</A></LI> | |
37375 | </UL> | |
37376 | </LI> | |
37377 | <LI><A href="#Extending_nn21">Navigating and manipulating parse trees</A> | |
37378 | </LI> | |
37379 | <LI><A href="#Extending_nn22">Working with attributes</A></LI> | |
37380 | <LI><A href="#Extending_nn23">Type system</A> | |
37381 | <UL> | |
37382 | <LI><A href="#Extending_nn24">String encoding of types</A></LI> | |
37383 | <LI><A href="#Extending_nn25">Type construction</A></LI> | |
37384 | <LI><A href="#Extending_nn26">Type tests</A></LI> | |
37385 | <LI><A href="#Extending_nn27">Typedef and inheritance</A></LI> | |
37386 | <LI><A href="#Extending_nn28">Lvalues</A></LI> | |
37387 | <LI><A href="#Extending_nn29">Output functions</A></LI> | |
37388 | </UL> | |
37389 | </LI> | |
37390 | <LI><A href="#Extending_nn30">Parameters</A></LI> | |
37391 | <LI><A href="#Extending_nn31">Writing a Language Module</A> | |
37392 | <UL> | |
37393 | <LI><A href="#Extending_nn32">Execution model</A></LI> | |
37394 | <LI><A href="#Extending_nn33">Starting out</A></LI> | |
37395 | <LI><A href="#Extending_nn34">Command line options</A></LI> | |
37396 | <LI><A href="#Extending_nn35">Configuration and preprocessing</A></LI> | |
37397 | <LI><A href="#Extending_nn36">Entry point to code generation</A></LI> | |
37398 | <LI><A href="#Extending_nn37">Module I/O and wrapper skeleton</A></LI> | |
37399 | <LI><A href="#Extending_nn38">Low-level code generators</A></LI> | |
37400 | <LI><A href="#Extending_nn39">Configuration files</A></LI> | |
37401 | <LI><A href="#Extending_nn40">Runtime support</A></LI> | |
37402 | <LI><A href="#Extending_nn41">Standard library files</A></LI> | |
37403 | <LI><A href="#Extending_nn42">Examples and test cases</A></LI> | |
37404 | <LI><A href="#Extending_nn43">Documentation</A></LI> | |
37405 | </UL> | |
37406 | </LI> | |
37407 | <LI><A href="#Extending_nn44">Typemaps</A> | |
37408 | <UL> | |
37409 | <LI><A href="#Extending_nn45">Proxy classes</A></LI> | |
37410 | </UL> | |
37411 | </LI> | |
37412 | <LI><A href="#Extending_nn46">Guide to parse tree nodes</A></LI> | |
37413 | </UL> | |
37414 | </DIV> | |
37415 | <!-- INDEX --> | |
37416 | <P><B> Caution: This chapter is being rewritten! (11/25/01)</B></P> | |
37417 | <H2><A name="Extending_nn2"></A>30.1 Introduction</H2> | |
37418 | <P> This chapter describes SWIG's internal organization and the process | |
37419 | by which new target languages can be developed. First, a brief word of | |
37420 | warning---SWIG has been undergoing a massive redevelopment effort that | |
37421 | has focused extensively on its internal organization. The information | |
37422 | in this chapter is mostly up to date, but changes are ongoing. Expect a | |
37423 | few inconsistencies.</P> | |
37424 | <P> Also, this chapter is not meant to be a hand-holding tutorial. As a | |
37425 | starting point, you should probably look at one of SWIG's existing | |
37426 | modules.</P> | |
37427 | <H2><A name="Extending_nn3"></A>30.2 Prerequisites</H2> | |
37428 | <P> In order to extend SWIG, it is useful to have the following | |
37429 | background:</P> | |
37430 | <UL> | |
37431 | <LI>An understanding of the C API for the target language.</LI> | |
37432 | <LI>A good grasp of the C++ type system.</LI> | |
37433 | <LI>An understanding of typemaps and some of SWIG's advanced features.</LI> | |
37434 | <LI>Some familiarity with writing C++ (language modules are currently | |
37435 | written in C++).</LI> | |
37436 | </UL> | |
37437 | <P> Since SWIG is essentially a specialized C++ compiler, it may be | |
37438 | useful to have some prior experience with compiler design (perhaps even | |
37439 | a compilers course) to better understand certain parts of the system. A | |
37440 | number of books will also be useful. For example, "The C Programming | |
37441 | Language" by Kernighan and Ritchie (a.k.a, "K&R") and the "C++ | |
37442 | Annotated Reference Manual" by Stroustrup (a.k.a, the "ARM") will be of | |
37443 | great use.</P> | |
37444 | <P> Also, it is useful to keep in mind that SWIG primarily operates as | |
37445 | an extension of the C++<EM> type</EM> system. At first glance, this | |
37446 | might not be obvious, but almost all SWIG directives as well as the | |
37447 | low-level generation of wrapper code are driven by C++ datatypes.</P> | |
37448 | <H2><A name="Extending_nn4"></A>30.3 The Big Picture</H2> | |
37449 | <P> SWIG is a special purpose compiler that parses C++ declarations to | |
37450 | generate wrapper code. To make this conversion possible, SWIG makes | |
37451 | three fundamental extensions to the C++ language:</P> | |
37452 | <UL> | |
37453 | <LI><B>Typemaps</B>. Typemaps are used to define the | |
37454 | conversion/marshalling behavior of specific C++ datatypes. All type | |
37455 | conversion in SWIG is based on typemaps. Furthermore, the association | |
37456 | of typemaps to datatypes utilizes an advanced pattern matching | |
37457 | mechanism that is fully integrated with the C++ type system.</LI> | |
37458 | <LI><B>Declaration Annotation</B>. To customize wrapper code generation, | |
37459 | most declarations can be annotated with special features. For example, | |
37460 | you can make a variable read-only, you can ignore a declaration, you | |
37461 | can rename a member function, you can add exception handling, and so | |
37462 | forth. Virtually all of these customizations are built on top of a | |
37463 | low-level declaration annotator that can attach arbitrary attributes to | |
37464 | any declaration. Code generation modules can look for these attributes | |
37465 | to guide the wrapping process.</LI> | |
37466 | <LI><B>Class extension</B>. SWIG allows classes and structures to be | |
37467 | extended with new methods and attributes (the <TT>%extend</TT> | |
37468 | directive). This has the effect of altering the API in the target | |
37469 | language and can be used to generate OO interfaces to C libraries.</LI> | |
37470 | </UL> | |
37471 | <P> It is important to emphasize that virtually all SWIG features reduce | |
37472 | to one of these three fundamental concepts. The type system and pattern | |
37473 | matching rules also play a critical role in making the system work. For | |
37474 | example, both typemaps and declaration annotation are based on pattern | |
37475 | matching and interact heavily with the underlying type system.</P> | |
37476 | <H2><A name="Extending_nn5"></A>30.4 Execution Model</H2> | |
37477 | <P> When you run SWIG on an interface, processing is handled in stages | |
37478 | by a series of system components:</P> | |
37479 | <UL> | |
37480 | <LI>An integrated C preprocessor reads a collection of configuration | |
37481 | files and the specified interface file into memory. The preprocessor | |
37482 | performs the usual functions including macro expansion and file | |
37483 | inclusion. However, the preprocessor also performs some transformations | |
37484 | of the interface. For instance, <TT>#define</TT> statements are | |
37485 | sometimes transformed into <TT>%constant</TT> declarations. In | |
37486 | addition, information related to file/line number tracking is inserted.</LI> | |
37487 | <LI>A C/C++ parser reads the preprocessed input and generates a full | |
37488 | parse tree of all of the SWIG directives and C declarations found. The | |
37489 | parser is responsible for many aspects of the system including | |
37490 | renaming, declaration annotation, and template expansion. However, the | |
37491 | parser does not produce any output nor does it interact with the target | |
37492 | language module as it runs. SWIG is not a one-pass compiler.</LI> | |
37493 | <LI>A type-checking pass is made. This adjusts all of the C++ typenames | |
37494 | to properly handle namespaces, typedefs, nested classes, and other | |
37495 | issues related to type scoping.</LI> | |
37496 | <LI>A semantic pass is made on the parse tree to collect information | |
37497 | related to properties of the C++ interface. For example, this pass | |
37498 | would determine whether or not a class allows a default constructor.</LI> | |
37499 | <LI>A code generation pass is made using a specific target language | |
37500 | module. This phase is responsible for generating the actual wrapper | |
37501 | code. All of SWIG's user-defined modules are invoked during this stage | |
37502 | of compilation.</LI> | |
37503 | </UL> | |
37504 | <P> The next few sections briefly describe some of these stages.</P> | |
37505 | <H3><A name="Extending_nn6"></A>30.4.1 Preprocessing</H3> | |
37506 | <P> The preprocessor plays a critical role in the SWIG implementation. | |
37507 | This is because a lot of SWIG's processing and internal configuration | |
37508 | is managed not by code written in C, but by configuration files in the | |
37509 | SWIG library. In fact, when you run SWIG, parsing starts with a small | |
37510 | interface file like this (note: this explains the cryptic error | |
37511 | messages that new users sometimes get when SWIG is misconfigured or | |
37512 | installed incorrectly):</P> | |
37513 | <DIV class="code"> | |
37514 | <PRE> | |
37515 | %include "swig.swg" // Global SWIG configuration | |
37516 | %include "<EM>langconfig.swg</EM>" // Language specific configuration | |
37517 | %include "yourinterface.i" // Your interface file | |
37518 | </PRE> | |
37519 | </DIV> | |
37520 | <P> The <TT>swig.swg</TT> file contains global configuration | |
37521 | information. In addition, this file defines many of SWIG's standard | |
37522 | directives as macros. For instance, part of of <TT>swig.swg</TT> looks | |
37523 | like this:</P> | |
37524 | <DIV class="code"> | |
37525 | <PRE> | |
37526 | ... | |
37527 | /* Code insertion directives such as %wrapper %{ ... %} */ | |
37528 | ||
37529 | #define %init %insert("init") | |
37530 | #define %wrapper %insert("wrapper") | |
37531 | #define %header %insert("header") | |
37532 | #define %runtime %insert("runtime") | |
37533 | ||
37534 | /* Access control directives */ | |
37535 | ||
37536 | #define %immutable %feature("immutable","1") | |
37537 | #define %mutable %feature("immutable") | |
37538 | ||
37539 | /* Directives for callback functions */ | |
37540 | ||
37541 | #define %callback(x) %feature("callback") `x`; | |
37542 | #define %nocallback %feature("callback"); | |
37543 | ||
37544 | /* %ignore directive */ | |
37545 | ||
37546 | #define %ignore %rename($ignore) | |
37547 | #define %ignorewarn(x) %rename("$ignore:" x) | |
37548 | ... | |
37549 | </PRE> | |
37550 | </DIV> | |
37551 | <P> The fact that most of the standard SWIG directives are macros is | |
37552 | intended to simplify the implementation of the internals. For instance, | |
37553 | rather than having to support dozens of special directives, it is | |
37554 | easier to have a few basic primitives such as <TT>%feature</TT> or <TT> | |
37555 | %insert</TT>.</P> | |
37556 | <P> The<EM> <TT>langconfig.swg</TT></EM> file is supplied by the target | |
37557 | language. This file contains language-specific configuration | |
37558 | information. More often than not, this file provides run-time wrapper | |
37559 | support code (e.g., the type-checker) as well as a collection of | |
37560 | typemaps that define the default wrapping behavior. Note: the name of | |
37561 | this file depends on the target language and is usually something like <TT> | |
37562 | python.swg</TT> or <TT>perl5.swg</TT>.</P> | |
37563 | <P> As a debugging aide, the text that SWIG feeds to its C++ parser can | |
37564 | be obtained by running <TT>swig -E interface.i</TT>. This output | |
37565 | probably isn't too useful in general, but it will show how macros have | |
37566 | been expanded as well as everything else that goes into the low-level | |
37567 | construction of the wrapper code.</P> | |
37568 | <H3><A name="Extending_nn7"></A>30.4.2 Parsing</H3> | |
37569 | <P> The current C++ parser handles a subset of C++. Most | |
37570 | incompatibilities with C are due to subtle aspects of how SWIG parses | |
37571 | declarations. Specifically, SWIG expects all C/C++ declarations to | |
37572 | follow this general form:</P> | |
37573 | <DIV class="diagram"> | |
37574 | <PRE> | |
37575 | <EM>storage</EM> <EM>type</EM> <EM>declarator</EM> <EM>initializer</EM>; | |
37576 | </PRE> | |
37577 | </DIV> | |
37578 | <P> <TT><EM>storage</EM></TT> is a keyword such as <TT>extern</TT>, <TT> | |
37579 | static</TT>, <TT>typedef</TT>, or <TT>virtual</TT>. <TT><EM>type</EM></TT> | |
37580 | is a primitive datatype such as <TT>int</TT> or <TT>void</TT>. <TT><EM> | |
37581 | type</EM></TT> may be optionally qualified with a qualifier such as <TT> | |
37582 | const</TT> or <TT>volatile</TT>. <TT><EM>declarator</EM></TT> is a name | |
37583 | with additional type-construction modifiers attached to it (pointers, | |
37584 | arrays, references, functions, etc.). Examples of declarators include <TT> | |
37585 | *x</TT>, <TT>**x</TT>, <TT>x[20]</TT>, and <TT>(*x)(int,double)</TT>. | |
37586 | The <TT><EM>initializer</EM></TT> may be a value assigned using <TT>=</TT> | |
37587 | or body of code enclosed in braces <TT>{ ... }</TT>.</P> | |
37588 | <P> This declaration format covers most common C++ declarations. | |
37589 | However, the C++ standard is somewhat more flexible in the placement of | |
37590 | the parts. For example, it is technically legal, although uncommon to | |
37591 | write something like <TT>int typedef const a</TT> in your program. SWIG | |
37592 | simply doesn't bother to deal with this case.</P> | |
37593 | <P> The other significant difference between C++ and SWIG is in the | |
37594 | treatment of typenames. In C++, if you have a declaration like this,</P> | |
37595 | <DIV class="code"> | |
37596 | <PRE> | |
37597 | int blah(Foo *x, Bar *y); | |
37598 | </PRE> | |
37599 | </DIV> | |
37600 | <P> it won't parse correctly unless <TT>Foo</TT> and <TT>Bar</TT> have | |
37601 | been previously defined as types either using a <TT>class</TT> | |
37602 | definition or a <TT>typedef</TT>. The reasons for this are subtle, but | |
37603 | this treatment of typenames is normally integrated at the level of the | |
37604 | C tokenizer---when a typename appears, a different token is returned to | |
37605 | the parser instead of an identifier.</P> | |
37606 | <P> SWIG does not operate in this manner--any legal identifier can be | |
37607 | used as a type name. The reason for this is primarily motivated by the | |
37608 | use of SWIG with partially defined data. Specifically, SWIG is supposed | |
37609 | to be easy to use on interfaces with missing type information.</P> | |
37610 | <P> Because of the different treatment of typenames, the most serious | |
37611 | limitation of the SWIG parser is that it can't process type | |
37612 | declarations where an extra (and unnecessary) grouping operator is | |
37613 | used. For example:</P> | |
37614 | <DIV class="code"> | |
37615 | <PRE> | |
37616 | int (x); /* A variable x */ | |
37617 | int (y)(int); /* A function y */ | |
37618 | </PRE> | |
37619 | </DIV> | |
37620 | <P> The placing of extra parentheses in type declarations like this is | |
37621 | already recognized by the C++ community as a potential source of | |
37622 | strange programming errors. For example, Scott Meyers "Effective STL" | |
37623 | discusses this problem in a section on avoiding C++'s "most vexing | |
37624 | parse."</P> | |
37625 | <P> The parser is also unable to handle declarations with no return type | |
37626 | or bare argument names. For example, in an old C program, you might see | |
37627 | things like this:</P> | |
37628 | <DIV class="code"> | |
37629 | <PRE> | |
37630 | foo(a,b) { | |
37631 | ... | |
37632 | } | |
37633 | </PRE> | |
37634 | </DIV> | |
37635 | <P> In this case, the return type as well as the types of the arguments | |
37636 | are taken by the C compiler to be an <TT>int</TT>. However, SWIG | |
37637 | interprets the above code as an abstract declarator for a function | |
37638 | returning a <TT>foo</TT> and taking types <TT>a</TT> and <TT>b</TT> as | |
37639 | arguments).</P> | |
37640 | <H3><A name="Extending_nn8"></A>30.4.3 Parse Trees</H3> | |
37641 | <P> The SWIG parser produces a complete parse tree of the input file | |
37642 | before any wrapper code is actually generated. Each item in the tree is | |
37643 | known as a "Node". Each node is identified by a symbolic tag. | |
37644 | Furthermore, a node may have an arbitrary number of children. The parse | |
37645 | tree structure and tag names of an interface can be displayed using <TT> | |
37646 | swig -dump_tags</TT>. For example:</P> | |
37647 | <DIV class="shell"> | |
37648 | <PRE> | |
37649 | $ <B>swig -c++ -python -dump_tags example.i</B> | |
37650 | . top (example.i:1) | |
37651 | . top . include (example.i:1) | |
37652 | . top . include . typemap (/r0/beazley/Projects/lib/swig1.3/swig.swg:71) | |
37653 | . top . include . typemap . typemapitem (/r0/beazley/Projects/lib/swig1.3/swig.swg:71) | |
37654 | . top . include . typemap (/r0/beazley/Projects/lib/swig1.3/swig.swg:83) | |
37655 | . top . include . typemap . typemapitem (/r0/beazley/Projects/lib/swig1.3/swig.swg:83) | |
37656 | . top . include (example.i:4) | |
37657 | . top . include . insert (/r0/beazley/Projects/lib/swig1.3/python/python.swg:7) | |
37658 | . top . include . insert (/r0/beazley/Projects/lib/swig1.3/python/python.swg:8) | |
37659 | . top . include . typemap (/r0/beazley/Projects/lib/swig1.3/python/python.swg:19) | |
37660 | ... | |
37661 | . top . include (example.i:6) | |
37662 | . top . include . module (example.i:2) | |
37663 | . top . include . insert (example.i:6) | |
37664 | . top . include . include (example.i:9) | |
37665 | . top . include . include . class (example.h:3) | |
37666 | . top . include . include . class . access (example.h:4) | |
37667 | . top . include . include . class . constructor (example.h:7) | |
37668 | . top . include . include . class . destructor (example.h:10) | |
37669 | . top . include . include . class . cdecl (example.h:11) | |
37670 | . top . include . include . class . cdecl (example.h:11) | |
37671 | . top . include . include . class . cdecl (example.h:12) | |
37672 | . top . include . include . class . cdecl (example.h:13) | |
37673 | . top . include . include . class . cdecl (example.h:14) | |
37674 | . top . include . include . class . cdecl (example.h:15) | |
37675 | . top . include . include . class (example.h:18) | |
37676 | . top . include . include . class . access (example.h:19) | |
37677 | . top . include . include . class . cdecl (example.h:20) | |
37678 | . top . include . include . class . access (example.h:21) | |
37679 | . top . include . include . class . constructor (example.h:22) | |
37680 | . top . include . include . class . cdecl (example.h:23) | |
37681 | . top . include . include . class . cdecl (example.h:24) | |
37682 | . top . include . include . class (example.h:27) | |
37683 | . top . include . include . class . access (example.h:28) | |
37684 | . top . include . include . class . cdecl (example.h:29) | |
37685 | . top . include . include . class . access (example.h:30) | |
37686 | . top . include . include . class . constructor (example.h:31) | |
37687 | . top . include . include . class . cdecl (example.h:32) | |
37688 | . top . include . include . class . cdecl (example.h:33) | |
37689 | </PRE> | |
37690 | </DIV> | |
37691 | <P> Even for the most simple interface, the parse tree structure is | |
37692 | larger than you might expect. For example, in the above output, a | |
37693 | substantial number of nodes are actually generated by the <TT> | |
37694 | python.swg</TT> configuration file which defines typemaps and other | |
37695 | directives. The contents of the user-supplied input file don't appear | |
37696 | until the end of the output.</P> | |
37697 | <P> The contents of each parse tree node consist of a collection of | |
37698 | attribute/value pairs. Internally, the nodes are simply represented by | |
37699 | hash tables. A display of the parse-tree structure can be obtained | |
37700 | using <TT>swig -dump_tree</TT>. For example:</P> | |
37701 | <DIV class="shell"> | |
37702 | <PRE> | |
37703 | $ swig -c++ -python -dump_tree example.i | |
37704 | ... | |
37705 | +++ include ---------------------------------------- | |
37706 | | name - "example.i" | |
37707 | ||
37708 | +++ module ---------------------------------------- | |
37709 | | name - "example" | |
37710 | | | |
37711 | +++ insert ---------------------------------------- | |
37712 | | code - "\n#include \"example.h\"\n" | |
37713 | | | |
37714 | +++ include ---------------------------------------- | |
37715 | | name - "example.h" | |
37716 | ||
37717 | +++ class ---------------------------------------- | |
37718 | | abstract - "1" | |
37719 | | sym:name - "Shape" | |
37720 | | name - "Shape" | |
37721 | | kind - "class" | |
37722 | | symtab - 0x40194140 | |
37723 | | sym:symtab - 0x40191078 | |
37724 | ||
37725 | +++ access ---------------------------------------- | |
37726 | | kind - "public" | |
37727 | | | |
37728 | +++ constructor ---------------------------------------- | |
37729 | | sym:name - "Shape" | |
37730 | | name - "Shape" | |
37731 | | decl - "f()." | |
37732 | | code - "{\n nshapes++;\n }" | |
37733 | | sym:symtab - 0x40194140 | |
37734 | | | |
37735 | +++ destructor ---------------------------------------- | |
37736 | | sym:name - "~Shape" | |
37737 | | name - "~Shape" | |
37738 | | storage - "virtual" | |
37739 | | code - "{\n nshapes--;\n }" | |
37740 | | sym:symtab - 0x40194140 | |
37741 | | | |
37742 | +++ cdecl ---------------------------------------- | |
37743 | | sym:name - "x" | |
37744 | | name - "x" | |
37745 | | decl - "" | |
37746 | | type - "double" | |
37747 | | sym:symtab - 0x40194140 | |
37748 | | | |
37749 | +++ cdecl ---------------------------------------- | |
37750 | | sym:name - "y" | |
37751 | | name - "y" | |
37752 | | decl - "" | |
37753 | | type - "double" | |
37754 | | sym:symtab - 0x40194140 | |
37755 | | | |
37756 | +++ cdecl ---------------------------------------- | |
37757 | | sym:name - "move" | |
37758 | | name - "move" | |
37759 | | decl - "f(double,double)." | |
37760 | | parms - double ,double | |
37761 | | type - "void" | |
37762 | | sym:symtab - 0x40194140 | |
37763 | | | |
37764 | +++ cdecl ---------------------------------------- | |
37765 | | sym:name - "area" | |
37766 | | name - "area" | |
37767 | | decl - "f(void)." | |
37768 | | parms - void | |
37769 | | storage - "virtual" | |
37770 | | value - "0" | |
37771 | | type - "double" | |
37772 | | sym:symtab - 0x40194140 | |
37773 | | | |
37774 | +++ cdecl ---------------------------------------- | |
37775 | | sym:name - "perimeter" | |
37776 | | name - "perimeter" | |
37777 | | decl - "f(void)." | |
37778 | | parms - void | |
37779 | | storage - "virtual" | |
37780 | | value - "0" | |
37781 | | type - "double" | |
37782 | | sym:symtab - 0x40194140 | |
37783 | | | |
37784 | +++ cdecl ---------------------------------------- | |
37785 | | sym:name - "nshapes" | |
37786 | | name - "nshapes" | |
37787 | | decl - "" | |
37788 | | storage - "static" | |
37789 | | type - "int" | |
37790 | | sym:symtab - 0x40194140 | |
37791 | | | |
37792 | +++ class ---------------------------------------- | |
37793 | | sym:name - "Circle" | |
37794 | | name - "Circle" | |
37795 | | kind - "class" | |
37796 | | bases - 0x40194510 | |
37797 | | symtab - 0x40194538 | |
37798 | | sym:symtab - 0x40191078 | |
37799 | ||
37800 | +++ access ---------------------------------------- | |
37801 | | kind - "private" | |
37802 | | | |
37803 | +++ cdecl ---------------------------------------- | |
37804 | | name - "radius" | |
37805 | | decl - "" | |
37806 | | type - "double" | |
37807 | | | |
37808 | +++ access ---------------------------------------- | |
37809 | | kind - "public" | |
37810 | | | |
37811 | +++ constructor ---------------------------------------- | |
37812 | | sym:name - "Circle" | |
37813 | | name - "Circle" | |
37814 | | parms - double | |
37815 | | decl - "f(double)." | |
37816 | | code - "{ }" | |
37817 | | sym:symtab - 0x40194538 | |
37818 | | | |
37819 | +++ cdecl ---------------------------------------- | |
37820 | | sym:name - "area" | |
37821 | | name - "area" | |
37822 | | decl - "f(void)." | |
37823 | | parms - void | |
37824 | | storage - "virtual" | |
37825 | | type - "double" | |
37826 | | sym:symtab - 0x40194538 | |
37827 | | | |
37828 | +++ cdecl ---------------------------------------- | |
37829 | | sym:name - "perimeter" | |
37830 | | name - "perimeter" | |
37831 | | decl - "f(void)." | |
37832 | | parms - void | |
37833 | | storage - "virtual" | |
37834 | | type - "double" | |
37835 | | sym:symtab - 0x40194538 | |
37836 | | | |
37837 | +++ class ---------------------------------------- | |
37838 | | sym:name - "Square" | |
37839 | | name - "Square" | |
37840 | | kind - "class" | |
37841 | | bases - 0x40194760 | |
37842 | | symtab - 0x40194788 | |
37843 | | sym:symtab - 0x40191078 | |
37844 | ||
37845 | +++ access ---------------------------------------- | |
37846 | | kind - "private" | |
37847 | | | |
37848 | +++ cdecl ---------------------------------------- | |
37849 | | name - "width" | |
37850 | | decl - "" | |
37851 | | type - "double" | |
37852 | | | |
37853 | +++ access ---------------------------------------- | |
37854 | | kind - "public" | |
37855 | | | |
37856 | +++ constructor ---------------------------------------- | |
37857 | | sym:name - "Square" | |
37858 | | name - "Square" | |
37859 | | parms - double | |
37860 | | decl - "f(double)." | |
37861 | | code - "{ }" | |
37862 | | sym:symtab - 0x40194788 | |
37863 | | | |
37864 | +++ cdecl ---------------------------------------- | |
37865 | | sym:name - "area" | |
37866 | | name - "area" | |
37867 | | decl - "f(void)." | |
37868 | | parms - void | |
37869 | | storage - "virtual" | |
37870 | | type - "double" | |
37871 | | sym:symtab - 0x40194788 | |
37872 | | | |
37873 | +++ cdecl ---------------------------------------- | |
37874 | | sym:name - "perimeter" | |
37875 | | name - "perimeter" | |
37876 | | decl - "f(void)." | |
37877 | | parms - void | |
37878 | | storage - "virtual" | |
37879 | | type - "double" | |
37880 | | sym:symtab - 0x40194788 | |
37881 | </PRE> | |
37882 | </DIV> | |
37883 | <H3><A name="Extending_nn9"></A>30.4.4 Attribute namespaces</H3> | |
37884 | <P> Attributes of parse tree nodes are often prepended with a namespace | |
37885 | qualifier. For example, the attributes <TT>sym:name</TT> and <TT> | |
37886 | sym:symtab</TT> are attributes related to symbol table management and | |
37887 | are prefixed with <TT>sym:</TT>. As a general rule, only those | |
37888 | attributes which are directly related to the raw declaration appear | |
37889 | without a prefix (type, name, declarator, etc.).</P> | |
37890 | <P> Target language modules may add additional attributes to nodes to | |
37891 | assist the generation of wrapper code. The convention for doing this is | |
37892 | to place these attributes in a namespace that matches the name of the | |
37893 | target language. For example, <TT>python:foo</TT> or <TT>perl:foo</TT>.</P> | |
37894 | <H3><A name="Extending_nn10"></A>30.4.5 Symbol Tables</H3> | |
37895 | <P> During parsing, all symbols are managed in the space of the target | |
37896 | language. The <TT>sym:name</TT> attribute of each node contains the | |
37897 | symbol name selected by the parser. Normally, <TT>sym:name</TT> and <TT> | |
37898 | name</TT> are the same. However, the <TT>%rename</TT> directive can be | |
37899 | used to change the value of <TT>sym:name</TT>. You can see the effect | |
37900 | of <TT>%rename</TT> by trying it on a simple interface and dumping the | |
37901 | parse tree. For example:</P> | |
37902 | <DIV class="code"> | |
37903 | <PRE> | |
37904 | %rename(foo_i) foo(int); | |
37905 | %rename(foo_d) foo(double); | |
37906 | ||
37907 | void foo(int); | |
37908 | void foo(double); | |
37909 | void foo(Bar *b); | |
37910 | </PRE> | |
37911 | </DIV> | |
37912 | <P> Now, running SWIG:</P> | |
37913 | <DIV class="shell"> | |
37914 | <PRE> | |
37915 | $ swig -dump_tree example.i | |
37916 | ... | |
37917 | +++ cdecl ---------------------------------------- | |
37918 | | sym:name - "foo_i" | |
37919 | | name - "foo" | |
37920 | | decl - "f(int)." | |
37921 | | parms - int | |
37922 | | type - "void" | |
37923 | | sym:symtab - 0x40165078 | |
37924 | | | |
37925 | +++ cdecl ---------------------------------------- | |
37926 | | sym:name - "foo_d" | |
37927 | | name - "foo" | |
37928 | | decl - "f(double)." | |
37929 | | parms - double | |
37930 | | type - "void" | |
37931 | | sym:symtab - 0x40165078 | |
37932 | | | |
37933 | +++ cdecl ---------------------------------------- | |
37934 | | sym:name - "foo" | |
37935 | | name - "foo" | |
37936 | | decl - "f(p.Bar)." | |
37937 | | parms - Bar * | |
37938 | | type - "void" | |
37939 | | sym:symtab - 0x40165078 | |
37940 | </PRE> | |
37941 | </DIV> | |
37942 | <P> All symbol-related conflicts and complaints about overloading are | |
37943 | based on <TT>sym:name</TT> values. For instance, the following example | |
37944 | uses <TT>%rename</TT> in reverse to generate a name clash.</P> | |
37945 | <DIV class="code"> | |
37946 | <PRE> | |
37947 | %rename(foo) foo_i(int); | |
37948 | %rename(foo) foo_d(double; | |
37949 | ||
37950 | void foo_i(int); | |
37951 | void foo_d(double); | |
37952 | void foo(Bar *b); | |
37953 | </PRE> | |
37954 | </DIV> | |
37955 | <P> When you run SWIG on this you now get:</P> | |
37956 | <DIV class="shell"> | |
37957 | <PRE> | |
37958 | $ ./swig example.i | |
37959 | example.i:6. Overloaded declaration ignored. foo_d(double ) | |
37960 | example.i:5. Previous declaration is foo_i(int ) | |
37961 | example.i:7. Overloaded declaration ignored. foo(Bar *) | |
37962 | example.i:5. Previous declaration is foo_i(int ) | |
37963 | </PRE> | |
37964 | </DIV> | |
37965 | <H3><A name="Extending_nn11"></A>30.4.6 The %feature directive</H3> | |
37966 | <P> A number of SWIG directives such as <TT>%exception</TT> are | |
37967 | implemented using the low-level <TT>%feature</TT> directive. For | |
37968 | example:</P> | |
37969 | <DIV class="code"> | |
37970 | <PRE> | |
37971 | %feature("except") getitem(int) { | |
37972 | try { | |
37973 | $action | |
37974 | } catch (badindex) { | |
37975 | ... | |
37976 | } | |
37977 | } | |
37978 | ||
37979 | ... | |
37980 | class Foo { | |
37981 | public: | |
37982 | Object *getitem(int index) throws(badindex); | |
37983 | ... | |
37984 | }; | |
37985 | </PRE> | |
37986 | </DIV> | |
37987 | <P> The behavior of <TT>%feature</TT> is very easy to describe--it | |
37988 | simply attaches a new attribute to any parse tree node that matches the | |
37989 | given prototype. When a feature is added, it shows up as an attribute | |
37990 | in the <TT>feature:</TT> namespace. You can see this when running with | |
37991 | the <TT>-dump_tree</TT> option. For example:</P> | |
37992 | <DIV class="shell"> | |
37993 | <PRE> | |
37994 | +++ cdecl ---------------------------------------- | |
37995 | | sym:name - "getitem" | |
37996 | | name - "getitem" | |
37997 | | decl - "f(int).p." | |
37998 | | parms - int | |
37999 | | type - "Object" | |
38000 | | feature:except - "{\n try {\n $action\n } catc..." | |
38001 | | sym:symtab - 0x40168ac8 | |
38002 | | | |
38003 | </PRE> | |
38004 | </DIV> | |
38005 | <P> Feature names are completely arbitrary and a target language module | |
38006 | can be programmed to respond to any feature name that it wants to | |
38007 | recognized. The data stored in a feature attribute is usually just a | |
38008 | raw unparsed string. For example, the exception code above is simply | |
38009 | stored without any modifications.</P> | |
38010 | <H3><A name="Extending_nn12"></A>30.4.7 Code Generation</H3> | |
38011 | <P> Language modules work by defining handler functions that know how to | |
38012 | respond to different types of parse-tree nodes. These handlers simply | |
38013 | look at the attributes of each node in order to produce low-level code.</P> | |
38014 | <P> In reality, the generation of code is somewhat more subtle than | |
38015 | simply invoking handler functions. This is because parse-tree nodes | |
38016 | might be transformed. For example, suppose you are wrapping a class | |
38017 | like this:</P> | |
38018 | <DIV class="code"> | |
38019 | <PRE> | |
38020 | class Foo { | |
38021 | public: | |
38022 | virtual int *bar(int x); | |
38023 | }; | |
38024 | </PRE> | |
38025 | </DIV> | |
38026 | <P> When the parser constructs a node for the member <TT>bar</TT>, it | |
38027 | creates a raw "cdecl" node with the following attributes:</P> | |
38028 | <DIV class="diagram"> | |
38029 | <PRE> | |
38030 | nodeType : cdecl | |
38031 | name : bar | |
38032 | type : int | |
38033 | decl : f(int).p | |
38034 | parms : int x | |
38035 | storage : virtual | |
38036 | sym:name : bar | |
38037 | </PRE> | |
38038 | </DIV> | |
38039 | <P> To produce wrapper code, this "cdecl" node undergoes a number of | |
38040 | transformations. First, the node is recognized as a function | |
38041 | declaration. This adjusts some of the type information--specifically, | |
38042 | the declarator is joined with the base datatype to produce this:</P> | |
38043 | <DIV class="diagram"> | |
38044 | <PRE> | |
38045 | nodeType : cdecl | |
38046 | name : bar | |
38047 | type : p.int <-- Notice change in return type | |
38048 | decl : f(int).p | |
38049 | parms : int x | |
38050 | storage : virtual | |
38051 | sym:name : bar | |
38052 | </PRE> | |
38053 | </DIV> | |
38054 | <P> Next, the context of the node indicates that the node is really a | |
38055 | member function. This produces a transformation to a low-level accessor | |
38056 | function like this:</P> | |
38057 | <DIV class="diagram"> | |
38058 | <PRE> | |
38059 | nodeType : cdecl | |
38060 | name : bar | |
38061 | type : int.p | |
38062 | decl : f(int).p | |
38063 | parms : Foo *self, int x <-- Added parameter | |
38064 | storage : virtual | |
38065 | wrap:action : result = (arg1)->bar(arg2) <-- Action code added | |
38066 | sym:name : Foo_bar <-- Symbol name changed | |
38067 | </PRE> | |
38068 | </DIV> | |
38069 | <P> In this transformation, notice how an additional parameter was added | |
38070 | to the parameter list and how the symbol name of the node has suddenly | |
38071 | changed into an accessor using the naming scheme described in the "SWIG | |
38072 | Basics" chapter. A small fragment of "action" code has also been | |
38073 | generated--notice how the <TT>wrap:action</TT> attribute defines the | |
38074 | access to the underlying method. The data in this transformed node is | |
38075 | then used to generate a wrapper.</P> | |
38076 | <P> Language modules work by registering handler functions for dealing | |
38077 | with various types of nodes at different stages of transformation. This | |
38078 | is done by inheriting from a special <TT>Language</TT> class and | |
38079 | defining a collection of virtual methods. For example, the Python | |
38080 | module defines a class as follows:</P> | |
38081 | <DIV class="code"> | |
38082 | <PRE> | |
38083 | class PYTHON : public Language { | |
38084 | protected: | |
38085 | public : | |
38086 | virtual void main(int, char *argv[]); | |
38087 | virtual int top(Node *); | |
38088 | virtual int functionWrapper(Node *); | |
38089 | virtual int constantWrapper(Node *); | |
38090 | virtual int variableWrapper(Node *); | |
38091 | virtual int nativeWrapper(Node *); | |
38092 | virtual int membervariableHandler(Node *); | |
38093 | virtual int memberconstantHandler(Node *); | |
38094 | virtual int memberfunctionHandler(Node *); | |
38095 | virtual int constructorHandler(Node *); | |
38096 | virtual int destructorHandler(Node *); | |
38097 | virtual int classHandler(Node *); | |
38098 | virtual int classforwardDeclaration(Node *); | |
38099 | virtual int insertDirective(Node *); | |
38100 | virtual int importDirective(Node *); | |
38101 | }; | |
38102 | </PRE> | |
38103 | </DIV> | |
38104 | <P> The role of these functions is described shortly.</P> | |
38105 | <H3><A name="Extending_nn13"></A>30.4.8 SWIG and XML</H3> | |
38106 | <P> Much of SWIG's current parser design was originally motivated by | |
38107 | interest in using XML to represent SWIG parse trees. Although XML is | |
38108 | not currently used in any direct manner, the parse tree structure, use | |
38109 | of node tags, attributes, and attribute namespaces are all influenced | |
38110 | by aspects of XML parsing. Therefore, in trying to understand SWIG's | |
38111 | internal data structures, it may be useful keep XML in the back of your | |
38112 | mind as a model.</P> | |
38113 | <H2><A name="Extending_nn14"></A>30.5 Primitive Data Structures</H2> | |
38114 | <P> Most of SWIG is constructed using three basic data structures: | |
38115 | strings, hashes, and lists. These data structures are dynamic in same | |
38116 | way as similar structures found in many scripting languages. For | |
38117 | instance, you can have containers (lists and hash tables) of mixed | |
38118 | types and certain operations are polymorphic.</P> | |
38119 | <P> This section briefly describes the basic structures so that later | |
38120 | sections of this chapter make more sense.</P> | |
38121 | <P> When describing the low-level API, the following type name | |
38122 | conventions are used:</P> | |
38123 | <UL> | |
38124 | <LI><TT>String</TT>. A string object.</LI> | |
38125 | <LI><TT>Hash</TT>. A hash object.</LI> | |
38126 | <LI><TT>List</TT>. A list object.</LI> | |
38127 | <LI><TT>String_or_char</TT>. A string object or a <TT>char *</TT>.</LI> | |
38128 | <LI><TT>Object_or_char</TT>. An object or a <TT>char *</TT>.</LI> | |
38129 | <LI><TT>Object</TT>. Any object (string, hash, list, etc.)</LI> | |
38130 | </UL> | |
38131 | <P> In most cases, other typenames in the source are aliases for one of | |
38132 | these primitive types. Specifically:</P> | |
38133 | <DIV class="code"> | |
38134 | <PRE> | |
38135 | typedef String SwigType; | |
38136 | typedef Hash Parm; | |
38137 | typedef Hash ParmList; | |
38138 | typedef Hash Node; | |
38139 | typedef Hash Symtab; | |
38140 | typedef Hash Typetab; | |
38141 | </PRE> | |
38142 | </DIV> | |
38143 | <H3><A name="Extending_nn15"></A>30.5.1 Strings</H3> | |
38144 | <P><B> <TT>String *NewString(const String_or_char *val)</TT></B></P> | |
38145 | <DIV class="indent"> Creates a new string with initial value <TT>val</TT> | |
38146 | . <TT>val</TT> may be a <TT>char *</TT> or another <TT>String</TT> | |
38147 | object. If you want to create an empty string, use "" for val.</DIV> | |
38148 | <P><B> <TT>String *NewStringf(const char *fmt, ...)</TT></B></P> | |
38149 | <DIV class="indent"> Creates a new string whose initial value is set | |
38150 | according to a C <TT>printf</TT> style format string in <TT>fmt</TT>. | |
38151 | Additional arguments follow depending on <TT>fmt</TT>.</DIV> | |
38152 | <P><B> <TT>String *Copy(String *s)</TT></B></P> | |
38153 | <DIV class="indent"> Make a copy of the string <TT>s</TT>.</DIV> | |
38154 | <P><B> <TT>void Delete(String *s)</TT></B></P> | |
38155 | <DIV class="indent"> Deletes <TT>s</TT>.</DIV> | |
38156 | <P><B> <TT>int Len(String_or_char *s)</TT></B></P> | |
38157 | <DIV class="indent"> Returns the length of the string.</DIV> | |
38158 | <P><B> <TT>char *Char(String_or_char *s)</TT></B></P> | |
38159 | <DIV class="indent"> Returns a pointer to the first character in a | |
38160 | string.</DIV> | |
38161 | <P><B> <TT>void Append(String *s, String_or_char *t)</TT></B></P> | |
38162 | <DIV class="indent"> Appends <TT>t</TT> to the end of string <TT>s</TT>.</DIV> | |
38163 | <P><B> <TT>void Insert(String *s, int pos, String_or_char *t)</TT></B></P> | |
38164 | <DIV class="indent"> Inserts <TT>t</TT> into <TT>s</TT> at position <TT> | |
38165 | pos</TT>. The contents of <TT>s</TT> are shifted accordingly. The | |
38166 | special value <TT>DOH_END</TT> can be used for <TT>pos</TT> to indicate | |
38167 | insertion at the end of the string (appending).</DIV> | |
38168 | <P><B> <TT>int Strcmp(const String_or_char *s, const String_or_char *t)</TT> | |
38169 | </B></P> | |
38170 | <DIV class="indent"> Compare strings <TT>s</TT> and <TT>t</TT>. Same as | |
38171 | the C <TT>strcmp()</TT> function.</DIV> | |
38172 | <P><B> <TT>int Strncmp(const String_or_char *s, const String_or_char *t, | |
38173 | int len)</TT></B></P> | |
38174 | <DIV class="indent"> Compare the first <TT>len</TT> characters of | |
38175 | strings <TT>s</TT> and <TT>t</TT>. Same as the C <TT>strncmp()</TT> | |
38176 | function.</DIV> | |
38177 | <P><B> <TT>char *Strstr(const String_or_char *s, const String_or_char | |
38178 | *pat)</TT></B></P> | |
38179 | <DIV class="indent"> Returns a pointer to the first occurrence of <TT> | |
38180 | pat</TT> in <TT>s</TT>. Same as the C <TT>strstr()</TT> function.</DIV> | |
38181 | <P><B> <TT>char *Strchr(const String_or_char *s, char ch)</TT></B></P> | |
38182 | <DIV class="indent"> Returns a pointer to the first occurrence of | |
38183 | character <TT>ch</TT> in <TT>s</TT>. Same as the C <TT>strchr()</TT> | |
38184 | function.</DIV> | |
38185 | <P><B> <TT>void Chop(String *s)</TT></B></P> | |
38186 | <DIV class="indent"> Chops trailing whitespace off the end of <TT>s</TT> | |
38187 | .</DIV> | |
38188 | <P><B> <TT>int Replace(String *s, const String_or_char *pat, const | |
38189 | String_or_char *rep, int flags)</TT></B></P> | |
38190 | <DIV class="indent"> | |
38191 | <P> Replaces the pattern <TT>pat</TT> with <TT>rep</TT> in string <TT>s</TT> | |
38192 | . <TT>flags</TT> is a combination of the following flags:</P> | |
38193 | <DIV class="code"> | |
38194 | <PRE> | |
38195 | DOH_REPLACE_ANY - Replace all occurrences | |
38196 | DOH_REPLACE_ID - Valid C identifiers only | |
38197 | DOH_REPLACE_NOQUOTE - Don't replace in quoted strings | |
38198 | DOH_REPLACE_FIRST - Replace first occurrence only. | |
38199 | </PRE> | |
38200 | </DIV> | |
38201 | <P> Returns the number of replacements made (if any).</P> | |
38202 | </DIV> | |
38203 | <H3><A name="Extending_nn16"></A>30.5.2 Hashes</H3> | |
38204 | <P><B> <TT>Hash *NewHash()</TT></B></P> | |
38205 | <DIV class="indent"> Creates a new empty hash table.</DIV> | |
38206 | <P><B> <TT>Hash *Copy(Hash *h)</TT></B></P> | |
38207 | <DIV class="indent"> Make a shallow copy of the hash <TT>h</TT>.</DIV> | |
38208 | <P><B> <TT>void Delete(Hash *h)</TT></B></P> | |
38209 | <DIV class="indent"> Deletes <TT>h</TT>.</DIV> | |
38210 | <P><B> <TT>int Len(Hash *h)</TT></B></P> | |
38211 | <DIV class="indent"> Returns the number of items in <TT>h</TT>.</DIV> | |
38212 | <P><B> <TT>Object *Getattr(Hash *h, String_or_char *key)</TT></B></P> | |
38213 | <DIV class="indent"> Gets an object from <TT>h</TT>. <TT>key</TT> may be | |
38214 | a string or a simple <TT>char *</TT> string. Returns NULL if not found.</DIV> | |
38215 | <P><B> <TT>int Setattr(Hash *h, String_or_char *key, Object_or_char | |
38216 | *val)</TT></B></P> | |
38217 | <DIV class="indent"> Stores <TT>val</TT> in <TT>h</TT>. <TT>key</TT> may | |
38218 | be a string or a simple <TT>char *</TT>. If <TT>val</TT> is not a | |
38219 | standard object (String, Hash, or List) it is assumed to be a <TT>char | |
38220 | *</TT> in which case it is used to construct a <TT>String</TT> that is | |
38221 | stored in the hash. If <TT>val</TT> is NULL, the object is deleted. | |
38222 | Increases the reference count of <TT>val</TT>. Returns 1 if this | |
38223 | operation replaced an existing hash entry, 0 otherwise.</DIV> | |
38224 | <P><B> <TT>int Delattr(Hash *h, String_or_char *key)</TT></B></P> | |
38225 | <DIV class="indent"> Deletes the hash item referenced by <TT>key</TT>. | |
38226 | Decreases the reference count on the corresponding object (if any). | |
38227 | Returns 1 if an object was removed, 0 otherwise.</DIV> | |
38228 | <P><B> <TT>List *Keys(Hash *h)</TT></B></P> | |
38229 | <DIV class="indent"> Returns the list of hash table keys.</DIV> | |
38230 | <H3><A name="Extending_nn17"></A>30.5.3 Lists</H3> | |
38231 | <P><B> <TT>List *NewList()</TT></B></P> | |
38232 | <DIV class="indent"> Creates a new empty list.</DIV> | |
38233 | <P><B> <TT>List *Copy(List *x)</TT></B></P> | |
38234 | <DIV class="indent"> Make a shallow copy of the List <TT>x</TT>.</DIV> | |
38235 | <P><B> <TT>void Delete(List *x)</TT></B></P> | |
38236 | <DIV class="indent"> Deletes <TT>x</TT>.</DIV> | |
38237 | <P><B> <TT>int Len(List *x)</TT></B></P> | |
38238 | <DIV class="indent"> Returns the number of items in <TT>x</TT>.</DIV> | |
38239 | <P><B> <TT>Object *Getitem(List *x, int n)</TT></B></P> | |
38240 | <DIV class="indent"> Returns an object from <TT>x</TT> with index <TT>n</TT> | |
38241 | . If <TT>n</TT> is beyond the end of the list, the last item is | |
38242 | returned. If <TT>n</TT> is negative, the first item is returned.</DIV> | |
38243 | <P><B> <TT>int *Setitem(List *x, int n, Object_or_char *val)</TT></B></P> | |
38244 | <DIV class="indent"> Stores <TT>val</TT> in <TT>x</TT>. If <TT>val</TT> | |
38245 | is not a standard object (String, Hash, or List) it is assumed to be a <TT> | |
38246 | char *</TT> in which case it is used to construct a <TT>String</TT> that | |
38247 | is stored in the list. <TT>n</TT> must be in range. Otherwise, an | |
38248 | assertion will be raised.</DIV> | |
38249 | <P><B> <TT>int *Delitem(List *x, int n)</TT></B></P> | |
38250 | <DIV class="indent"> Deletes item <TT>n</TT> from the list, shifting | |
38251 | items down if necessary. To delete the last item in the list, use the | |
38252 | special value <TT>DOH_END</TT> for <TT>n</TT>.</DIV> | |
38253 | <P><B> <TT>void Append(List *x, Object_or_char *t)</TT></B></P> | |
38254 | <DIV class="indent"> Appends <TT>t</TT> to the end of <TT>x</TT>. If <TT> | |
38255 | t</TT> is not a standard object, it is assumed to be a <TT>char *</TT> | |
38256 | and is used to create a String object.</DIV> | |
38257 | <P><B> <TT>void Insert(String *s, int pos, Object_or_char *t)</TT></B></P> | |
38258 | <DIV class="indent"> Inserts <TT>t</TT> into <TT>s</TT> at position <TT> | |
38259 | pos</TT>. The contents of <TT>s</TT> are shifted accordingly. The | |
38260 | special value <TT>DOH_END</TT> can be used for <TT>pos</TT> to indicate | |
38261 | insertion at the end of the list (appending). If <TT>t</TT> is not a | |
38262 | standard object, it is assumed to be a <TT>char *</TT> and is used to | |
38263 | create a String object.</DIV> | |
38264 | <H3><A name="Extending_nn18"></A>30.5.4 Common operations</H3> | |
38265 | The following operations are applicable to all datatypes. | |
38266 | <P><B> <TT>Object *Copy(Object *x)</TT></B></P> | |
38267 | <DIV class="indent"> Make a copy of the object <TT>x</TT>.</DIV> | |
38268 | <P><B> <TT>void Delete(Object *x)</TT></B></P> | |
38269 | <DIV class="indent"> Deletes <TT>x</TT>.</DIV> | |
38270 | <P><B> <TT>void Setfile(Object *x, String_or_char *f)</TT></B></P> | |
38271 | <DIV class="indent"> Sets the filename associated with <TT>x</TT>. Used | |
38272 | to track objects and report errors.</DIV> | |
38273 | <P><B> <TT>String *Getfile(Object *x)</TT></B></P> | |
38274 | <DIV class="indent"> Gets the filename associated with <TT>x</TT>.</DIV> | |
38275 | <P><B> <TT>void Setline(Object *x, int n)</TT></B></P> | |
38276 | <DIV class="indent"> Sets the line number associated with <TT>x</TT>. | |
38277 | Used to track objects and report errors.</DIV> | |
38278 | <P><B> <TT>int Getline(Object *x)</TT></B></P> | |
38279 | <DIV class="indent"> Gets the line number associated with <TT>x</TT>.</DIV> | |
38280 | <H3><A name="Extending_nn19"></A>30.5.5 Iterating over Lists and Hashes</H3> | |
38281 | To iterate over the elements of a list or a hash table, the following | |
38282 | functions are used: | |
38283 | <P><B> <TT>Iterator First(Object *x)</TT></B></P> | |
38284 | <DIV class="indent"> Returns an iterator object that points to the first | |
38285 | item in a list or hash table. The <TT>item</TT> attribute of the | |
38286 | Iterator object is a pointer to the item. For hash tables, the <TT>key</TT> | |
38287 | attribute of the Iterator object additionally points to the | |
38288 | corresponding Hash table key. The <TT>item</TT> and <TT>key</TT> | |
38289 | attributes are NULL if the object contains no items or if there are no | |
38290 | more items.</DIV> | |
38291 | <P><B> <TT>Iterator Next(Iterator i)</TT></B></P> | |
38292 | <DIV class="indent"> | |
38293 | <P>Returns an iterator that points to the next item in a list or hash | |
38294 | table. Here are two examples of iteration:</P> | |
38295 | <DIV class="code"> | |
38296 | <PRE> | |
38297 | List *l = (some list); | |
38298 | Iterator i; | |
38299 | ||
38300 | for (i = First(l); i.item; i = Next(i)) { | |
38301 | Printf(stdout,"%s\n", i.item); | |
38302 | } | |
38303 | ||
38304 | Hash *h = (some hash); | |
38305 | Iterator j; | |
38306 | ||
38307 | for (j = First(j); j.item; j= Next(j)) { | |
38308 | Printf(stdout,"%s : %s\n", j.key, j.item); | |
38309 | } | |
38310 | </PRE> | |
38311 | </DIV></DIV> | |
38312 | <H3><A name="Extending_nn20"></A>30.5.6 I/O</H3> | |
38313 | Special I/O functions are used for all internal I/O. These operations | |
38314 | work on C <TT>FILE *</TT> objects, String objects, and special <TT>File</TT> | |
38315 | objects (which are merely a wrapper around <TT>FILE *</TT>). | |
38316 | <P><B> <TT>int Printf(String_or_FILE *f, const char *fmt, ...)</TT></B></P> | |
38317 | <DIV class="indent"> Formatted I/O. Same as the C <TT>fprintf()</TT> | |
38318 | function except that output can also be directed to a string object. | |
38319 | Note: the <TT>%s</TT> format specifier works with both strings and <TT> | |
38320 | char *</TT>. All other format operators have the same meaning.</DIV> | |
38321 | <P><B> <TT>int Printv(String_or_FILE *f, String_or_char *arg1,..., NULL)</TT> | |
38322 | </B></P> | |
38323 | <DIV class="indent"> Prints a variable number of strings arguments to | |
38324 | the output. The last argument to this function must be NULL. The other | |
38325 | arguments can either be <TT>char *</TT> or string objects.</DIV> | |
38326 | <P><B> <TT>int Putc(int ch, String_or_FILE *f)</TT></B></P> | |
38327 | <DIV class="indent"> Same as the C <TT>fputc()</TT> function.</DIV> | |
38328 | <P><B> <TT>int Write(String_or_FILE *f, void *buf, int len)</TT></B></P> | |
38329 | <DIV class="indent"> Same as the C <TT>write()</TT> function.</DIV> | |
38330 | <P><B> <TT>int Read(String_or_FILE *f, void *buf, int maxlen)</TT></B></P> | |
38331 | <DIV class="indent"> Same as the C <TT>read()</TT> function.</DIV> | |
38332 | <P><B> <TT>int Getc(String_or_FILE *f)</TT></B></P> | |
38333 | <DIV class="indent"> Same as the C <TT>fgetc()</TT> function.</DIV> | |
38334 | <P><B> <TT>int Ungetc(int ch, String_or_FILE *f)</TT></B></P> | |
38335 | <DIV class="indent"> Same as the C <TT>ungetc()</TT> function.</DIV> | |
38336 | <P><B> <TT>int Seek(String_or_FILE *f, int offset, int whence)</TT></B></P> | |
38337 | <DIV class="indent"> Same as the C <TT>seek()</TT> function. <TT>offset</TT> | |
38338 | is the number of bytes. <TT>whence</TT> is one of <TT>SEEK_SET</TT>,<TT> | |
38339 | SEEK_CUR</TT>, or <TT>SEEK_END</TT>..</DIV> | |
38340 | <P><B> <TT>long Tell(String_or_FILE *f)</TT></B></P> | |
38341 | <DIV class="indent"> Same as the C <TT>tell()</TT> function.</DIV> | |
38342 | <P><B> <TT>File *NewFile(const char *filename, const char *mode)</TT></B> | |
38343 | </P> | |
38344 | <DIV class="indent"> Create a File object using the <TT>fopen()</TT> | |
38345 | library call. This file differs from <TT>FILE *</TT> in that it can be | |
38346 | placed in the standard SWIG containers (lists, hashes, etc.).</DIV> | |
38347 | <P><B> <TT>File *NewFileFromFile(FILE *f)</TT></B></P> | |
38348 | <DIV class="indent"> Create a File object wrapper around an existing <TT> | |
38349 | FILE *</TT> object.</DIV> | |
38350 | <P><B> <TT>int Close(String_or_FILE *f)</TT></B></P> | |
38351 | <DIV class="indent"> | |
38352 | <P>Closes a file. Has no effect on strings.</P> | |
38353 | <P> The use of the above I/O functions and strings play a critical role | |
38354 | in SWIG. It is common to see small code fragments of code generated | |
38355 | using code like this:</P> | |
38356 | <DIV class="code"> | |
38357 | <PRE> | |
38358 | /* Print into a string */ | |
38359 | String *s = NewString(""); | |
38360 | Printf(s,"Hello\n"); | |
38361 | for (i = 0; i < 10; i++) { | |
38362 | Printf(s,"%d\n", i); | |
38363 | } | |
38364 | ... | |
38365 | /* Print string into a file */ | |
38366 | Printf(f, "%s\n", s); | |
38367 | </PRE> | |
38368 | </DIV> | |
38369 | <P> Similarly, the preprocessor and parser all operate on string-files.</P> | |
38370 | </DIV> | |
38371 | <H2><A name="Extending_nn21"></A>30.6 Navigating and manipulating parse | |
38372 | trees</H2> | |
38373 | Parse trees are built as collections of hash tables. Each node is a | |
38374 | hash table in which arbitrary attributes can be stored. Certain | |
38375 | attributes in the hash table provide links to other parse tree nodes. | |
38376 | The following macros can be used to move around the parse tree. | |
38377 | <P><B> <TT>String *nodeType(Node *n)</TT></B></P> | |
38378 | <DIV class="indent"> Returns the node type tag as a string. The returned | |
38379 | string indicates the type of parse tree node.</DIV> | |
38380 | <P><B> <TT>Node *nextSibling(Node *n)</TT></B></P> | |
38381 | <DIV class="indent"> Returns the next node in the parse tree. For | |
38382 | example, the next C declaration.</DIV> | |
38383 | <P><B> <TT>Node *previousSibling(Node *n)</TT></B></P> | |
38384 | <DIV class="indent"> Returns the previous node in the parse tree. For | |
38385 | example, the previous C declaration.</DIV> | |
38386 | <P><B> <TT>Node *firstChild(Node *n)</TT></B></P> | |
38387 | <DIV class="indent"> Returns the first child node. For example, if <TT>n</TT> | |
38388 | was a C++ class node, this would return the node for the first class | |
38389 | member.</DIV> | |
38390 | <P><B> <TT>Node *lastChild(Node *n)</TT></B></P> | |
38391 | <DIV class="indent"> Returns the last child node. You might use this if | |
38392 | you wanted to append a new node to the of a class.</DIV> | |
38393 | <P><B> <TT>Node *parentNode(Node *n)</TT></B></P> | |
38394 | <DIV class="indent"> Returns the parent of node <TT>n</TT>. Use this to | |
38395 | move up the pass tree.</DIV> | |
38396 | <P> The following macros can be used to change all of the above | |
38397 | attributes. Normally, these functions are only used by the parser. | |
38398 | Changing them without knowing what you are doing is likely to be | |
38399 | dangerous.</P> | |
38400 | <P><B> <TT>void set_nodeType(Node *n, const String_or_char)</TT></B></P> | |
38401 | <DIV class="indent"> Change the node type. tree node.</DIV> | |
38402 | <P><B> <TT>void set_nextSibling(Node *n, Node *s)</TT></B></P> | |
38403 | <DIV class="indent"> Set the next sibling.</DIV> | |
38404 | <P><B> <TT>void set_previousSibling(Node *n, Node *s)</TT></B></P> | |
38405 | <DIV class="indent"> Set the previous sibling.</DIV> | |
38406 | <P><B> <TT>void set_firstChild(Node *n, Node *c)</TT></B></P> | |
38407 | <DIV class="indent"> Set the first child node.</DIV> | |
38408 | <P><B> <TT>void set_lastChild(Node *n, Node *c)</TT></B></P> | |
38409 | <DIV class="indent"> Set the last child node.</DIV> | |
38410 | <P><B> <TT>void set_parentNode(Node *n, Node *p)</TT></B></P> | |
38411 | <DIV class="indent"> Set the parent node.</DIV> | |
38412 | <P> The following utility functions are used to alter the parse tree (at | |
38413 | your own risk)</P> | |
38414 | <P><B> <TT>void appendChild(Node *parent, Node *child)</TT></B></P> | |
38415 | <DIV class="indent"> Append a child to <TT>parent</TT>. The appended | |
38416 | node becomes the last child.</DIV> | |
38417 | <P><B> <TT>void deleteNode(Node *node)</TT></B></P> | |
38418 | <DIV class="indent"> Deletes a node from the parse tree. Deletion | |
38419 | reconnects siblings and properly updates the parent so that sibling | |
38420 | nodes are unaffected.</DIV> | |
38421 | <H2><A name="Extending_nn22"></A>30.7 Working with attributes</H2> | |
38422 | <P> Since parse tree nodes are just hash tables, attributes are accessed | |
38423 | using the <TT>Getattr()</TT>, <TT>Setattr()</TT>, and <TT>Delattr()</TT> | |
38424 | operations. For example:</P> | |
38425 | <DIV class="code"> | |
38426 | <PRE> | |
38427 | int functionHandler(Node *n) { | |
38428 | String *name = Getattr(n,"name"); | |
38429 | String *symname = Getattr(n,"sym:name"); | |
38430 | SwigType *type = Getattr(n,"type"); | |
38431 | ... | |
38432 | } | |
38433 | </PRE> | |
38434 | </DIV> | |
38435 | <P> New attributes can be freely attached to a node as needed. However, | |
38436 | when new attributes are attached during code generation, they should be | |
38437 | prepended with a namespace prefix. For example:</P> | |
38438 | <DIV class="code"> | |
38439 | <PRE> | |
38440 | ... | |
38441 | Setattr(n,"python:docstring", doc); /* Store docstring */ | |
38442 | ... | |
38443 | </PRE> | |
38444 | </DIV> | |
38445 | <P> A quick way to check the value of an attribute is to use the <TT> | |
38446 | checkAttribute()</TT> function like this:</P> | |
38447 | <DIV class="code"> | |
38448 | <PRE> | |
38449 | if (checkAttribute(n,"storage","virtual")) { | |
38450 | /* n is virtual */ | |
38451 | ... | |
38452 | } | |
38453 | </PRE> | |
38454 | </DIV> | |
38455 | <P> Changing the values of existing attributes is allowed and is | |
38456 | sometimes done to implement node transformations. However, if a | |
38457 | function/method modifies a node, it is required to restore modified | |
38458 | attributes to their original values. To simplify the task of | |
38459 | saving/restoring attributes, the following functions are used:</P> | |
38460 | <P><B> <TT>int Swig_save(const char *ns, Node *n, const char *name1, | |
38461 | const char *name2, ..., NIL)</TT></B></P> | |
38462 | <DIV class="indent"> Saves a copy of attributes <TT>name1</TT>, <TT> | |
38463 | name2</TT>, etc. from node <TT>n</TT>. Copies of the attributes are | |
38464 | actually resaved in the node in a different namespace which is set by | |
38465 | the <TT>ns</TT> argument. For example, if you call <TT> | |
38466 | Swig_save("foo",n,"type",NIL)</TT>, then the "type" attribute will be | |
38467 | copied and saved as "foo:type". The namespace name itself is stored in | |
38468 | the "view" attribute of the node. If necessary, this can be examined to | |
38469 | find out where previous values of attributes might have been saved.</DIV> | |
38470 | <P><B> <TT>int Swig_restore(Node *n)</TT></B></P> | |
38471 | <DIV class="indent"> | |
38472 | <P> Restores the attributes saved by the previous call to <TT> | |
38473 | Swig_save()</TT>. Those attributes that were supplied to <TT>Swig_save()</TT> | |
38474 | will be restored to their original values.</P> | |
38475 | <P> The <TT>Swig_save()</TT> and <TT>Swig_restore()</TT> functions must | |
38476 | always be used as a pair. That is, every call to <TT>Swig_save()</TT> | |
38477 | must have a matching call to <TT>Swig_restore()</TT>. Calls can be | |
38478 | nested if necessary. Here is an example that shows how the functions | |
38479 | might be used:</P> | |
38480 | <DIV class="code"> | |
38481 | <PRE> | |
38482 | int variableHandler(Node *n) { | |
38483 | Swig_save("variableHandler",n,"type","sym:name",NIL); | |
38484 | String *symname = Getattr(n,"sym:name"); | |
38485 | SwigType *type = Getattr(n,"type"); | |
38486 | ... | |
38487 | Append(symname,"_global"); // Change symbol name | |
38488 | SwigType_add_pointer(type); // Add pointer | |
38489 | ... | |
38490 | generate wrappers | |
38491 | ... | |
38492 | Swig_restore(n); // Restore original values | |
38493 | return SWIG_OK; | |
38494 | } | |
38495 | </PRE> | |
38496 | </DIV></DIV> | |
38497 | <P><B> <TT>int Swig_require(const char *ns, Node *n, const char *name1, | |
38498 | const char *name2, ..., NIL)</TT></B></P> | |
38499 | <DIV class="indent"> This is an enhanced version of <TT>Swig_save()</TT> | |
38500 | that adds error checking. If an attribute name is not present in <TT>n</TT> | |
38501 | , a failed assertion results and SWIG terminates with a fatal error. | |
38502 | Optionally, if an attribute name is specified as "*<EM>name</EM>", a | |
38503 | copy of the attribute is saved as with <TT>Swig_save()</TT>. If an | |
38504 | attribute is specified as "?<EM>name</EM>", the attribute is optional. <TT> | |
38505 | Swig_restore()</TT> must always be called after using this function.</DIV> | |
38506 | <H2><A name="Extending_nn23"></A>30.8 Type system</H2> | |
38507 | <P> SWIG implements the complete C++ type system including typedef, | |
38508 | inheritance, pointers, references, and pointers to members. A detailed | |
38509 | discussion of type theory is impossible here. However, let's cover the | |
38510 | highlights.</P> | |
38511 | <H3><A name="Extending_nn24"></A>30.8.1 String encoding of types</H3> | |
38512 | <P> All types in SWIG consist of a base datatype and a collection of | |
38513 | type operators that are applied to the base. A base datatype is almost | |
38514 | always some kind of primitive type such as <TT>int</TT> or <TT>double</TT> | |
38515 | . The operators consist of things like pointers, references, arrays, and | |
38516 | so forth. Internally, types are represented as strings that are | |
38517 | constructed in a very precise manner. Here are some examples:</P> | |
38518 | <DIV class="diagram"> | |
38519 | <PRE> | |
38520 | C datatype SWIG encoding (strings) | |
38521 | ----------------------------- -------------------------- | |
38522 | int "int" | |
38523 | int * "p.int" | |
38524 | const int * "p.q(const).int" | |
38525 | int (*x)(int,double) "p.f(int,double).int" | |
38526 | int [20][30] "a(20).a(30).int" | |
38527 | int (F::*)(int) "m(F).f(int).int" | |
38528 | vector<int> * "p.vector<(int)>" | |
38529 | </PRE> | |
38530 | </DIV> | |
38531 | <P> Reading the SWIG encoding is often easier than figuring out the C | |
38532 | code---just read it from left to right. For a type of | |
38533 | "p.f(int,double).int" is a "pointer to a function(int,double) that | |
38534 | returns int".</P> | |
38535 | <P> The following operator encodings are used in type strings:</P> | |
38536 | <DIV class="diagram"> | |
38537 | <PRE> | |
38538 | Operator Meaning | |
38539 | ------------------- ------------------------------- | |
38540 | p. Pointer to | |
38541 | a(n). Array of dimension n | |
38542 | r. C++ reference | |
38543 | m(class). Member pointer to class | |
38544 | f(args). Function. | |
38545 | q(qlist). Qualifiers | |
38546 | </PRE> | |
38547 | </DIV> | |
38548 | <P> In addition, type names may be parameterized by templates. This is | |
38549 | represented by enclosing the template parameters in <TT><( ... )></TT>. | |
38550 | Variable length arguments are represented by the special base type of <TT> | |
38551 | v(...)</TT>.</P> | |
38552 | <P> If you want to experiment with type encodings, the raw type strings | |
38553 | can be inserted into an interface file using backticks `` wherever a | |
38554 | type is expected. For instance, here is an extremely perverted example:</P> | |
38555 | <DIV class="diagram"> | |
38556 | <PRE> | |
38557 | `p.a(10).p.f(int,p.f(int).int)` foo(int, int (*x)(int)); | |
38558 | </PRE> | |
38559 | </DIV> | |
38560 | <P> This corresponds to the immediately obvious C declaration:</P> | |
38561 | <DIV class="diagram"> | |
38562 | <PRE> | |
38563 | (*(*foo(int,int (*)(int)))[10])(int,int (*)(int)); | |
38564 | </PRE> | |
38565 | </DIV> | |
38566 | <P> Aside from the potential use of this declaration on a C programming | |
38567 | quiz, it motivates the use of the special SWIG encoding of types. The | |
38568 | SWIG encoding is much easier to work with because types can be easily | |
38569 | examined, modified, and constructed using simple string operations | |
38570 | (comparison, substrings, concatenation, etc.). For example, in the | |
38571 | parser, a declaration like this</P> | |
38572 | <DIV class="code"> | |
38573 | <PRE> | |
38574 | int *a[30]; | |
38575 | </PRE> | |
38576 | </DIV> | |
38577 | <P> is processed in a few pieces. In this case, you have the base type "<TT> | |
38578 | int</TT>" and the declarator of type "<TT>a(30).p.</TT>". To make the | |
38579 | final type, the two parts are just joined together using string | |
38580 | concatenation.</P> | |
38581 | <H3><A name="Extending_nn25"></A>30.8.2 Type construction</H3> | |
38582 | <P> The following functions are used to construct types. You should use | |
38583 | these functions instead of trying to build the type strings yourself.</P> | |
38584 | <P><B> <TT>void SwigType_add_pointer(SwigType *ty)</TT></B></P> | |
38585 | <DIV class="indent"> Adds a pointer to <TT>ty</TT>.</DIV> | |
38586 | <P><B> <TT>void SwigType_del_pointer(SwigType *ty)</TT></B></P> | |
38587 | <DIV class="indent"> Removes a single pointer from <TT>ty</TT>.</DIV> | |
38588 | <P><B> <TT>void SwigType_add_reference(SwigType *ty)</TT></B></P> | |
38589 | <DIV class="indent"> Adds a reference to <TT>ty</TT>.</DIV> | |
38590 | <P><B> <TT>void SwigType_add_array(SwigType *ty, String_or_char *dim)</TT> | |
38591 | </B></P> | |
38592 | <DIV class="indent"> Adds an array with dimension <TT>dim</TT> to <TT>ty</TT> | |
38593 | .</DIV> | |
38594 | <P><B> <TT>void SwigType_del_array(SwigType *ty)</TT></B></P> | |
38595 | <DIV class="indent"> Removes a single array dimension from <TT>ty</TT>.</DIV> | |
38596 | <P><B> <TT>int SwigType_array_ndim(SwigType *ty)</TT></B></P> | |
38597 | <DIV class="indent"> Returns number of array dimensions of <TT>ty</TT>.</DIV> | |
38598 | <P><B> <TT>String* SwigType_array_getdim(SwigType *ty,int n)</TT></B></P> | |
38599 | <DIV class="indent"> Returns <TT>n</TT>th array dimension of <TT>ty</TT> | |
38600 | .</DIV> | |
38601 | <P><B> <TT>void SwigType_array_setdim(SwigType *ty, int n, const | |
38602 | String_or_char *rep)</TT></B></P> | |
38603 | <DIV class="indent"> Sets <TT>n</TT>th array dimensions of <TT>ty</TT> | |
38604 | to <TT>rep</TT>.</DIV> | |
38605 | <P><B> <TT>void SwigType_add_qualifier(SwigType *ty, String_or_char *q)</TT> | |
38606 | </B></P> | |
38607 | <DIV class="indent"> Adds a type qualifier <TT>q</TT> to <TT>ty</TT>. <TT> | |
38608 | q</TT> is typically <TT>"const"</TT> or <TT>"volatile"</TT>.</DIV> | |
38609 | <P><B> <TT>void SwigType_add_memberpointer(SwigType *ty, String_or_char | |
38610 | *cls)</TT></B></P> | |
38611 | <DIV class="indent"> Adds a pointer to a member of class <TT>cls</TT> to | |
38612 | <TT>ty</TT>.</DIV> | |
38613 | <P><B> <TT>void SwigType_add_function(SwigType *ty, ParmList *p)</TT></B> | |
38614 | </P> | |
38615 | <DIV class="indent"> Adds a function to <TT>ty</TT>. <TT>p</TT> is a | |
38616 | linked-list of parameter nodes as generated by the parser. See the | |
38617 | section on parameter lists for details about the representation.</DIV> | |
38618 | <P><B> <TT>void SwigType_add_template(SwigType *ty, ParmList *p)</TT></B> | |
38619 | </P> | |
38620 | <DIV class="indent"> Adds a template to <TT>ty</TT>. <TT>p</TT> is a | |
38621 | linked-list of parameter nodes as generated by the parser. See the | |
38622 | section on parameter lists for details about the representation.</DIV> | |
38623 | <P><B> <TT>SwigType *SwigType_pop(SwigType *ty)</TT></B></P> | |
38624 | <DIV class="indent"> Removes the last type constructor from <TT>ty</TT> | |
38625 | and returns it. <TT>ty</TT> is modified.</DIV> | |
38626 | <P><B> <TT>void SwigType_push(SwigType *ty, SwigType *op)</TT></B></P> | |
38627 | <DIV class="indent"> Pushes the type operators in <TT>op</TT> onto type <TT> | |
38628 | ty</TT>. The opposite of <TT>SwigType_pop()</TT>.</DIV> | |
38629 | <P><B> <TT>SwigType *SwigType_pop_arrays(SwigType *ty)</TT></B></P> | |
38630 | <DIV class="indent"> Removes all leading array operators from <TT>ty</TT> | |
38631 | and returns them. <TT>ty</TT> is modified. For example, if <TT>ty</TT> | |
38632 | is <TT>"a(20).a(10).p.int"</TT>, then this function would return <TT> | |
38633 | "a(20).a(10)."</TT> and modify <TT>ty</TT> so that it has the value <TT> | |
38634 | "p.int"</TT>.</DIV> | |
38635 | <P><B> <TT>SwigType *SwigType_pop_function(SwigType *ty)</TT></B></P> | |
38636 | <DIV class="indent"> Removes a function operator from <TT>ty</TT> | |
38637 | including any qualification. <TT>ty</TT> is modified. For example, if <TT> | |
38638 | ty</TT> is <TT>"f(int).int"</TT>, then this function would return <TT> | |
38639 | "f(int)."</TT> and modify <TT>ty</TT> so that it has the value <TT>"int"</TT> | |
38640 | .</DIV> | |
38641 | <P><B> <TT>SwigType *SwigType_base(SwigType *ty)</TT></B></P> | |
38642 | <DIV class="indent"> Returns the base type of a type. For example, if <TT> | |
38643 | ty</TT> is <TT>"p.a(20).int"</TT>, this function would return <TT>"int"</TT> | |
38644 | . <TT>ty</TT> is unmodified.</DIV> | |
38645 | <P><B> <TT>SwigType *SwigType_prefix(SwigType *ty)</TT></B></P> | |
38646 | <DIV class="indent"> Returns the prefix of a type. For example, if <TT> | |
38647 | ty</TT> is <TT>"p.a(20).int"</TT>, this function would return <TT> | |
38648 | "p.a(20)."</TT>. <TT>ty</TT> is unmodified.</DIV> | |
38649 | <H3><A name="Extending_nn26"></A>30.8.3 Type tests</H3> | |
38650 | <P> The following functions can be used to test properties of a | |
38651 | datatype.</P> | |
38652 | <P><B> <TT>int SwigType_ispointer(SwigType *ty)</TT></B></P> | |
38653 | <DIV class="indent"> Checks if <TT>ty</TT> is a standard pointer.</DIV> | |
38654 | <P><B> <TT>int SwigType_ismemberpointer(SwigType *ty)</TT></B></P> | |
38655 | <DIV class="indent"> Checks if <TT>ty</TT> is a member pointer.</DIV> | |
38656 | <P><B> <TT>int SwigType_isreference(SwigType *ty)</TT></B></P> | |
38657 | <DIV class="indent"> Checks if <TT>ty</TT> is a C++ reference.</DIV> | |
38658 | <P><B> <TT>int SwigType_isarray(SwigType *ty)</TT></B></P> | |
38659 | <DIV class="indent"> Checks if <TT>ty</TT> is an array.</DIV> | |
38660 | <P><B> <TT>int SwigType_isfunction(SwigType *ty)</TT></B></P> | |
38661 | <DIV class="indent"> Checks if <TT>ty</TT> is a function.</DIV> | |
38662 | <P><B> <TT>int SwigType_isqualifier(SwigType *ty)</TT></B></P> | |
38663 | <DIV class="indent"> Checks if <TT>ty</TT> is a qualifier.</DIV> | |
38664 | <P><B> <TT>int SwigType_issimple(SwigType *ty)</TT></B></P> | |
38665 | <DIV class="indent"> Checks if <TT>ty</TT> is a simple type. No | |
38666 | operators applied.</DIV> | |
38667 | <P><B> <TT>int SwigType_isconst(SwigType *ty)</TT></B></P> | |
38668 | <DIV class="indent"> Checks if <TT>ty</TT> is a const type.</DIV> | |
38669 | <P><B> <TT>int SwigType_isvarargs(SwigType *ty)</TT></B></P> | |
38670 | <DIV class="indent"> Checks if <TT>ty</TT> is a varargs type.</DIV> | |
38671 | <P><B> <TT>int SwigType_istemplate(SwigType *ty)</TT></B></P> | |
38672 | <DIV class="indent"> Checks if <TT>ty</TT> is a templatized type.</DIV> | |
38673 | <H3><A name="Extending_nn27"></A>30.8.4 Typedef and inheritance</H3> | |
38674 | <P> The behavior of <TT>typedef</TT> declaration is to introduce a type | |
38675 | alias. For instance, <TT>typedef int Integer</TT> makes the identifier <TT> | |
38676 | Integer</TT> an alias for <TT>int</TT>. The treatment of typedef in SWIG | |
38677 | is somewhat complicated due to the pattern matching rules that get | |
38678 | applied in typemaps and the fact that SWIG prefers to generate wrapper | |
38679 | code that closely matches the input to simplify debugging (a user will | |
38680 | see the typedef names used in their program instead of the low-level | |
38681 | primitive C datatypes).</P> | |
38682 | <P> To handle <TT>typedef</TT>, SWIG builds a collection of trees | |
38683 | containing typedef relations. For example,</P> | |
38684 | <DIV class="code"> | |
38685 | <PRE> | |
38686 | typedef int Integer; | |
38687 | typedef Integer *IntegerPtr; | |
38688 | typedef int Number; | |
38689 | typedef int Size; | |
38690 | </PRE> | |
38691 | </DIV> | |
38692 | <P> produces two trees like this:</P> | |
38693 | <DIV class="diagram"> | |
38694 | <PRE> | |
38695 | int p.Integer | |
38696 | ^ ^ ^ ^ | |
38697 | / | \ | | |
38698 | / | \ | | |
38699 | Integer Size Number IntegerPtr | |
38700 | </PRE> | |
38701 | </DIV> | |
38702 | <P> To resolve a single typedef relationship, the following function is | |
38703 | used:</P> | |
38704 | <P><B> <TT>SwigType *SwigType_typedef_resolve(SwigType *ty)</TT></B></P> | |
38705 | <DIV class="indent"> Checks if <TT>ty</TT> can be reduced to a new type | |
38706 | via typedef. If so, returns the new type. If not, returns NULL.</DIV> | |
38707 | <P> Typedefs are only resolved in simple typenames that appear in a | |
38708 | type. For example, the type base name and in function parameters. When | |
38709 | resolving types, the process starts in the leaf nodes and moves up the | |
38710 | tree towards the root. Here are a few examples that show how it works:</P> | |
38711 | <DIV class="diagram"> | |
38712 | <PRE> | |
38713 | Original type After typedef_resolve() | |
38714 | ------------------------ ----------------------- | |
38715 | Integer int | |
38716 | a(30).Integer int | |
38717 | p.IntegerPtr p.p.Integer | |
38718 | p.p.Integer p.p.int | |
38719 | </PRE> | |
38720 | </DIV> | |
38721 | <P> For complicated types, the process can be quite involved. Here is | |
38722 | the reduction of a function pointer:</P> | |
38723 | <DIV class="diagram"> | |
38724 | <PRE> | |
38725 | p.f(Integer, p.IntegerPtr, Size).Integer : Start | |
38726 | p.f(Integer, p.IntegerPtr, Size).int | |
38727 | p.f(int, p.IntegerPtr, Size).int | |
38728 | p.f(int, p.p.Integer, Size).int | |
38729 | p.f(int, p.p.int, Size).int | |
38730 | p.f(int, p.p.int, int).int : End | |
38731 | </PRE> | |
38732 | </DIV> | |
38733 | <P> Two types are equivalent if their full type reductions are the same. | |
38734 | The following function will fully reduce a datatype:</P> | |
38735 | <P><B> <TT>SwigType *SwigType_typedef_resolve_all(SwigType *ty)</TT></B></P> | |
38736 | <DIV class="indent"> Fully reduces <TT>ty</TT> according to typedef | |
38737 | rules. Resulting datatype will consist only of primitive typenames.</DIV> | |
38738 | <H3><A name="Extending_nn28"></A>30.8.5 Lvalues</H3> | |
38739 | <P> When generating wrapper code, it is necessary to emit datatypes that | |
38740 | can be used on the left-hand side of an assignment operator (an | |
38741 | lvalue). However, not all C datatypes can be used in this | |
38742 | way---especially arrays and const-qualified types. To generate a type | |
38743 | that can be used as an lvalue, use the following function:</P> | |
38744 | <P><B> <TT>SwigType *SwigType_ltype(SwigType *ty)</TT></B></P> | |
38745 | <DIV class="indent"> Converts type <TT>ty</TT> to a type that can be | |
38746 | used as an lvalue in assignment. The resulting type is stripped of | |
38747 | qualifiers and arrays are converted to a pointers.</DIV> | |
38748 | <P> The creation of lvalues is fully aware of typedef and other aspects | |
38749 | of the type system. Therefore, the creation of an lvalue may result in | |
38750 | unexpected results. Here are a few examples:</P> | |
38751 | <DIV class="code"> | |
38752 | <PRE> | |
38753 | typedef double Matrix4[4][4]; | |
38754 | Matrix4 x; // type = 'Matrix4', ltype='p.a(4).double' | |
38755 | ||
38756 | typedef const char * Literal; | |
38757 | Literal y; // type = 'Literal', ltype='p.char' | |
38758 | </PRE> | |
38759 | </DIV> | |
38760 | <H3><A name="Extending_nn29"></A>30.8.6 Output functions</H3> | |
38761 | <P> The following functions produce strings that are suitable for | |
38762 | output.</P> | |
38763 | <P><B> <TT>String *SwigType_str(SwigType *ty, String_or_char *id = 0)</TT> | |
38764 | </B></P> | |
38765 | <DIV class="indent"> Generates a C string for a datatype. <TT>id</TT> is | |
38766 | an optional declarator. For example, if <TT>ty</TT> is "p.f(int).int" | |
38767 | and <TT>id</TT> is "foo", then this function produces "<TT>int | |
38768 | (*foo)(int)</TT>". This function is used to convert string-encoded | |
38769 | types back into a form that is valid C syntax.</DIV> | |
38770 | <P><B> <TT>String *SwigType_lstr(SwigType *ty, String_or_char *id = 0)</TT> | |
38771 | </B></P> | |
38772 | <DIV class="indent"> This is the same as <TT>SwigType_str()</TT> except | |
38773 | that the result is generated from the type's lvalue (as generated from | |
38774 | SwigType_ltype).</DIV> | |
38775 | <P><B> <TT>String *SwigType_lcaststr(SwigType *ty, String_or_char *id = | |
38776 | 0)</TT></B></P> | |
38777 | <DIV class="indent"> Generates a casting operation that converts from | |
38778 | type <TT>ty</TT> to its lvalue. <TT>id</TT> is an optional name to | |
38779 | include in the cast. For example, if <TT>ty</TT> is "<TT> | |
38780 | q(const).p.char</TT>" and <TT>id</TT> is "<TT>foo</TT>", this function | |
38781 | produces the string "<TT>(char *) foo</TT>".</DIV> | |
38782 | <P><B> <TT>String *SwigType_rcaststr(SwigType *ty, String_or_char *id = | |
38783 | 0)</TT></B></P> | |
38784 | <DIV class="indent"> Generates a casting operation that converts from a | |
38785 | type's lvalue to a type equivalent to <TT>ty</TT>. <TT>id</TT> is an | |
38786 | optional name to include in the cast. For example, if <TT>ty</TT> is "<TT> | |
38787 | q(const).p.char</TT>" and <TT>id</TT> is "<TT>foo</TT>", this function | |
38788 | produces the string "<TT>(const char *) foo</TT>".</DIV> | |
38789 | <P><B> <TT>String *SwigType_manglestr(SwigType *ty)</TT></B></P> | |
38790 | <DIV class="indent"> Generates a mangled string encoding of type <TT>ty</TT> | |
38791 | . The mangled string only contains characters that are part of a valid C | |
38792 | identifier. The resulting string is used in various parts of SWIG, but | |
38793 | is most commonly associated with type-descriptor objects that appear in | |
38794 | wrappers (e.g., <TT>SWIGTYPE_p_double</TT>).</DIV> | |
38795 | <H2><A name="Extending_nn30"></A>30.9 Parameters</H2> | |
38796 | <P> Several type-related functions involve parameter lists. These | |
38797 | include functions and templates. Parameter list are represented as a | |
38798 | list of nodes with the following attributes:</P> | |
38799 | <DIV class="diagram"> | |
38800 | <PRE> | |
38801 | "type" - Parameter type (required) | |
38802 | "name" - Parameter name (optional) | |
38803 | "value" - Initializer (optional) | |
38804 | </PRE> | |
38805 | </DIV> | |
38806 | <P> Typically parameters are denoted in the source by using a typename | |
38807 | of <TT>Parm *</TT> or <TT>ParmList *</TT>. To walk a parameter list, | |
38808 | simply use code like this:</P> | |
38809 | <DIV class="diagram"> | |
38810 | <PRE> | |
38811 | Parm *parms; | |
38812 | Parm *p; | |
38813 | for (p = parms; p; p = nextSibling(p)) { | |
38814 | SwigType *type = Getattr(p,"type"); | |
38815 | String *name = Getattr(p,"name"); | |
38816 | String *value = Getattr(p,"value"); | |
38817 | ... | |
38818 | } | |
38819 | </PRE> | |
38820 | </DIV> | |
38821 | <P> Note: this code is exactly the same as what you would use to walk | |
38822 | parse tree nodes.</P> | |
38823 | <P> An empty list of parameters is denoted by a NULL pointer.</P> | |
38824 | <P> Since parameter lists are fairly common, the following utility | |
38825 | functions are provided to manipulate them:</P> | |
38826 | <P><B> <TT>Parm *CopyParm(Parm *p);</TT></B></P> | |
38827 | <DIV class="indent"> Copies a single parameter.</DIV> | |
38828 | <P><B> <TT>ParmList *CopyParmList(ParmList *p);</TT></B></P> | |
38829 | <DIV class="indent"> Copies an entire list of parameters.</DIV> | |
38830 | <P><B> <TT>int ParmList_len(ParmList *p);</TT></B></P> | |
38831 | <DIV class="indent"> Returns the number of parameters in a parameter | |
38832 | list.</DIV> | |
38833 | <P><B> <TT>String *ParmList_str(ParmList *p);</TT></B></P> | |
38834 | <DIV class="indent"> Converts a parameter list into a C string. For | |
38835 | example, produces a string like "<TT>(int *p, int n, double x);</TT>".</DIV> | |
38836 | <P><B> <TT>String *ParmList_protostr(ParmList *p);</TT></B></P> | |
38837 | <DIV class="indent"> The same as <TT>ParmList_str()</TT> except that | |
38838 | parameter names are not included. Used to emit prototypes.</DIV> | |
38839 | <P><B> <TT>int ParmList_numrequired(ParmList *p);</TT></B></P> | |
38840 | <DIV class="indent"> Returns the number of required (non-optional) | |
38841 | arguments in <TT>p</TT>.</DIV> | |
38842 | <H2><A name="Extending_nn31"></A>30.10 Writing a Language Module</H2> | |
38843 | <P> This section briefly outlines the steps needed to create a | |
38844 | bare-bones language module. For more advanced techniques, you should | |
38845 | look at the implementation of existing modules. Since the code is | |
38846 | relatively easy to read, this section describes the creation of a | |
38847 | minimal Python module. You should be able to extrapolate this to other | |
38848 | languages.</P> | |
38849 | <H3><A name="Extending_nn32"></A>30.10.1 Execution model</H3> | |
38850 | <P> Code generation modules are defined by inheriting from the <TT> | |
38851 | Language</TT> class, currently defined in the <TT>Source/Modules1.1</TT> | |
38852 | directory of SWIG. Starting from the parsing of command line options, | |
38853 | all aspects of code generation are controlled by different methods of | |
38854 | the <TT>Language</TT> that must be defined by your module.</P> | |
38855 | <H3><A name="Extending_nn33"></A>30.10.2 Starting out</H3> | |
38856 | <P> To define a new language module, first create a minimal | |
38857 | implementation using this example as a guide:</P> | |
38858 | <DIV class="code"> | |
38859 | <PRE> | |
38860 | #include "swigmod.h" | |
38861 | ||
38862 | #ifndef MACSWIG | |
38863 | #include "swigconfig.h" | |
38864 | #endif | |
38865 | ||
38866 | class PYTHON : public Language { | |
38867 | public: | |
38868 | ||
38869 | virtual void main(int argc, char *argv[]) { | |
38870 | printf("I'm the Python module.\n"); | |
38871 | } | |
38872 | ||
38873 | virtual int top(Node *n) { | |
38874 | printf("Generating code.\n"); | |
38875 | return SWIG_OK; | |
38876 | } | |
38877 | ||
38878 | }; | |
38879 | ||
38880 | extern "C" Language * | |
38881 | swig_python(void) { | |
38882 | return new PYTHON(); | |
38883 | } | |
38884 | </PRE> | |
38885 | </DIV> | |
38886 | <P> The "swigmod.h" header file contains, among other things, the | |
38887 | declaration of the <TT>Language</TT> base class and so you should | |
38888 | include it at the top of your language module's source file. Similarly, | |
38889 | the "swigconfig.h" header file contains some other useful definitions | |
38890 | that you may need. Note that you should<EM> not</EM> include any header | |
38891 | files that are installed with the target language. That is to say, the | |
38892 | implementation of the SWIG Python module shouldn't have any | |
38893 | dependencies on the Python header files. The wrapper code generated by | |
38894 | SWIG will almost always depend on some language-specific C/C++ header | |
38895 | files, but SWIG itself does not.</P> | |
38896 | <P> Give your language class a reasonable name, usually the same as the | |
38897 | target language. By convention, these class names are all uppercase | |
38898 | (e.g. "PYTHON" for the Python language module) but this is not a | |
38899 | requirement. This class will ultimately consist of a number of | |
38900 | overrides of the virtual functions declared in the <TT>Language</TT> | |
38901 | base class, in addition to any language-specific member functions and | |
38902 | data you need. For now, just use the dummy implementations shown above.</P> | |
38903 | <P> The language module ends with a factory function, <TT>swig_python()</TT> | |
38904 | , that simply returns a new instance of the language class. As shown, it | |
38905 | should be declared with the <TT>extern "C"</TT> storage qualifier so | |
38906 | that it can be called from C code. It should also return a pointer to | |
38907 | the base class (<TT>Language</TT>) so that only the interface (and not | |
38908 | the implementation) of your language module is exposed to the rest of | |
38909 | SWIG.</P> | |
38910 | <P> Save the code for your language module in a file named "<TT> | |
38911 | python.cxx</TT>" and. place this file in the <TT>Source/Modules1.1</TT> | |
38912 | directory of the SWIG distribution. To ensure that your module is | |
38913 | compiled into SWIG along with the other language modules, modify the | |
38914 | file <TT>Source/Modules1.1/Makefile.in</TT> to include the additional | |
38915 | source files. Look for the lines that define the <TT>SRCS</TT> and <TT> | |
38916 | OBJS</TT> variables and add entries for your language. In addition, | |
38917 | modify the file <TT>Source/Modules1.1/swigmain.cxx</TT> with an | |
38918 | additional command line option that activates the module. Read the | |
38919 | source---it's straightforward.</P> | |
38920 | <P> Next, at the top level of the SWIG distribution, re-run the <TT> | |
38921 | autogen.sh</TT> script to regenerate the various build files:</P> | |
38922 | <DIV class="shell"> | |
38923 | <PRE> | |
38924 | $ <B>sh autogen.sh</B> | |
38925 | </PRE> | |
38926 | </DIV> | |
38927 | <P> Next re-run <TT>configure</TT> to regenerate all of the Makefiles:</P> | |
38928 | <DIV class="shell"> | |
38929 | <PRE> | |
38930 | $ <B>./configure</B> | |
38931 | </PRE> | |
38932 | </DIV> | |
38933 | <P> Finally, rebuild SWIG with your module added:</P> | |
38934 | <DIV class="shell"> | |
38935 | <PRE> | |
38936 | $ <B>make</B> | |
38937 | </PRE> | |
38938 | </DIV> | |
38939 | <P> Once it finishes compiling, try running SWIG with the command-line | |
38940 | option that activates your module. For example, <TT>swig -python foo.i</TT> | |
38941 | . The messages from your new module should appear.</P> | |
38942 | <H3><A name="Extending_nn34"></A>30.10.3 Command line options</H3> | |
38943 | <P> When SWIG starts, the command line options are passed to your | |
38944 | language module. This occurs before any other processing occurs | |
38945 | (preprocessing, parsing, etc.). To capture the command line options, | |
38946 | simply use code similar to this:</P> | |
38947 | <DIV class="code"> | |
38948 | <PRE> | |
38949 | void Language::main(int argc, char *argv[]) { | |
38950 | for (int i = 1; i < argc; i++) { | |
38951 | if (argv[i]) { | |
38952 | if(strcmp(argv[i],"-interface") == 0) { | |
38953 | if (argv[i+1]) { | |
38954 | interface = NewString(argv[i+1]); | |
38955 | Swig_mark_arg(i); | |
38956 | Swig_mark_arg(i+1); | |
38957 | i++; | |
38958 | } else { | |
38959 | Swig_arg_error(); | |
38960 | } | |
38961 | } else if (strcmp(argv[i],"-globals") == 0) { | |
38962 | if (argv[i+1]) { | |
38963 | global_name = NewString(argv[i+1]); | |
38964 | Swig_mark_arg(i); | |
38965 | Swig_mark_arg(i+1); | |
38966 | i++; | |
38967 | } else { | |
38968 | Swig_arg_error(); | |
38969 | } | |
38970 | } else if ( (strcmp(argv[i],"-proxy") == 0)) { | |
38971 | proxy_flag = 1; | |
38972 | Swig_mark_arg(i); | |
38973 | } else if (strcmp(argv[i],"-keyword") == 0) { | |
38974 | use_kw = 1; | |
38975 | Swig_mark_arg(i); | |
38976 | } else if (strcmp(argv[i],"-help") == 0) { | |
38977 | fputs(usage,stderr); | |
38978 | } | |
38979 | ... | |
38980 | } | |
38981 | } | |
38982 | } | |
38983 | </PRE> | |
38984 | </DIV> | |
38985 | <P> The exact set of options depends on what you want to do in your | |
38986 | module. Generally, you would use the options to change code generation | |
38987 | modes or to print diagnostic information.</P> | |
38988 | <P> If a module recognizes an option, it should always call <TT> | |
38989 | Swig_mark_arg()</TT> to mark the option as valid. If you forget to do | |
38990 | this, SWIG will terminate with an unrecognized command line option | |
38991 | error.</P> | |
38992 | <H3><A name="Extending_nn35"></A>30.10.4 Configuration and preprocessing</H3> | |
38993 | <P> In addition to looking at command line options, the <TT>main()</TT> | |
38994 | method is responsible for some initial configuration of the SWIG | |
38995 | library and preprocessor. To do this, insert some code like this:</P> | |
38996 | <DIV class="code"> | |
38997 | <PRE> | |
38998 | void main(int argc, char *argv[]) { | |
38999 | ... command line options ... | |
39000 | ||
39001 | /* Set language-specific subdirectory in SWIG library */ | |
39002 | SWIG_library_directory("python"); | |
39003 | ||
39004 | /* Set language-specific preprocessing symbol */ | |
39005 | Preprocessor_define("SWIGPYTHON 1", 0); | |
39006 | ||
39007 | /* Set language-specific configuration file */ | |
39008 | SWIG_config_file("python.swg"); | |
39009 | ||
39010 | /* Set typemap language (historical) */ | |
39011 | SWIG_typemap_lang("python"); | |
39012 | } | |
39013 | </PRE> | |
39014 | </DIV> | |
39015 | <P> The above code does several things--it registers the name of the | |
39016 | language module with the core, it supplies some preprocessor macro | |
39017 | definitions for use in input files (so that they can determine the | |
39018 | target language), and it registers a start-up file. In this case, the | |
39019 | file <TT>python.swg</TT> will be parsed before any part of the | |
39020 | user-supplied input file.</P> | |
39021 | <P> Before proceeding any further, create a directory for your module in | |
39022 | the SWIG library (The <TT>Lib</TT> directory). Now, create a | |
39023 | configuration file in the directory. For example, <TT>python.swg</TT>.</P> | |
39024 | <P> Just to review, your language module should now consist of two | |
39025 | files-- an implementation file <TT>python.cxx</TT> and a configuration | |
39026 | file <TT>python.swg</TT>.</P> | |
39027 | <H3><A name="Extending_nn36"></A>30.10.5 Entry point to code generation</H3> | |
39028 | <P> SWIG is a multi-pass compiler. Once the <TT>main()</TT> method has | |
39029 | been invoked, the language module does not execute again until | |
39030 | preprocessing, parsing, and a variety of semantic analysis passes have | |
39031 | been performed. When the core is ready to start generating wrappers, it | |
39032 | invokes the <TT>top()</TT> method of your language class. The argument | |
39033 | to <TT>top</TT> is a single parse tree node that corresponds to the top | |
39034 | of the entire parse tree.</P> | |
39035 | <P> To get the code generation process started, the <TT>top()</TT> | |
39036 | procedure needs to do several things:</P> | |
39037 | <UL> | |
39038 | <LI>Initialize the wrapper code output.</LI> | |
39039 | <LI>Set the module name.</LI> | |
39040 | <LI>Emit common initialization code.</LI> | |
39041 | <LI>Emit code for all of the child nodes.</LI> | |
39042 | <LI>Finalize the wrapper module and cleanup.</LI> | |
39043 | </UL> | |
39044 | <P> An outline of <TT>top()</TT> might be as follows:</P> | |
39045 | <DIV class="code"> | |
39046 | <PRE> | |
39047 | int Python::top(Node *n) { | |
39048 | ||
39049 | /* Get the module name */ | |
39050 | String *module = Getattr(n,"name"); | |
39051 | ||
39052 | /* Get the output file name */ | |
39053 | String *outfile = Getattr(n,"outfile"); | |
39054 | ||
39055 | /* Initialize I/O (see next section) */ | |
39056 | ... | |
39057 | ||
39058 | /* Output module initialization code */ | |
39059 | ... | |
39060 | ||
39061 | /* Emit code for children */ | |
39062 | Language::top(n); | |
39063 | ||
39064 | ... | |
39065 | /* Cleanup files */ | |
39066 | ... | |
39067 | ||
39068 | return SWIG_OK; | |
39069 | } | |
39070 | </PRE> | |
39071 | </DIV> | |
39072 | <H3><A name="Extending_nn37"></A>30.10.6 Module I/O and wrapper skeleton</H3> | |
39073 | <H3><A name="Extending_nn38"></A>30.10.7 Low-level code generators</H3> | |
39074 | <H3><A name="Extending_nn39"></A>30.10.8 Configuration files</H3> | |
39075 | ||
39076 | <!-- please report bugs in this section to ttn --> | |
39077 | <P> At the time of this writing, SWIG supports nearly a dozen languages, | |
39078 | which means that for continued sanity in maintaining the configuration | |
39079 | files, the language modules need to follow some conventions. These are | |
39080 | outlined here along with the admission that, yes it is ok to violate | |
39081 | these conventions in minor ways, as long as you know where to apply the | |
39082 | proper kludge to keep the overall system regular and running. | |
39083 | Engineering is the art of compromise, see...</P> | |
39084 | <P> Much of the maintenance regularity depends on choosing a suitable | |
39085 | nickname for your language module (and then using it in a controlled | |
39086 | way). Nicknames should be all lower case letters with an optional | |
39087 | numeric suffix (no underscores, no dashes, no spaces). Some examples | |
39088 | are: <TT>foo</TT>, <TT>bar</TT>, <TT>qux99</TT>.</P> | |
39089 | <P> The numeric suffix variant, as in the last example, is somewhat | |
39090 | tricky to work with because sometimes people expect to refer to the | |
39091 | language without this number but sometimes that number is extremely | |
39092 | relevant (especially when it corresponds to language implementation | |
39093 | versions with incompatible interfaces). New language modules that | |
39094 | unavoidably require a numeric suffix in their nickname should include | |
39095 | that number in all uses, or be prepared to kludge.</P> | |
39096 | <P> The nickname is used in four places:</P> | |
39097 | <TABLE summary="nickname table"> | |
39098 | <TR><TD><B>usage</B></TD><TD><B>transform</B></TD></TR> | |
39099 | <TR><TD>"skip" tag</TD><TD>(none)</TD></TR> | |
39100 | <TR><TD>Examples/ subdir name</TD><TD>(none)</TD></TR> | |
39101 | <TR><TD>Examples/GIFPlot/ subdir name</TD><TD>capitalize (upcase first | |
39102 | letter)</TD></TR> | |
39103 | <TR><TD>Examples/test-suite/ subdir name</TD><TD>(none)</TD></TR> | |
39104 | ||
39105 | <!-- add more uses here (remember to adjust header) --> | |
39106 | </TABLE> | |
39107 | <P> As you can see, most usages are direct.</P> | |
39108 | <DL> | |
39109 | <DT><B> configure.in</B></DT> | |
39110 | <DD> This file is processed by | |
39111 | <P> <A HREF="http://www.gnu.org/software/autoconf/">autoconf</A> to | |
39112 | generate the <TT>configure</TT> script. This is where you need to add | |
39113 | shell script fragments and autoconf macros to detect the presence of | |
39114 | whatever development support your language module requires, typically | |
39115 | directories where headers and libraries can be found, and/or utility | |
39116 | programs useful for integrating the generated wrapper code.</P> | |
39117 | <P> Use the <TT>AC_ARG_WITH</TT>, <TT>AC_MSG_CHECKING</TT>, <TT>AC_SUBST</TT> | |
39118 | macros and so forth (see other languages for examples). Avoid using the | |
39119 | <TT>[</TT> and <TT>]</TT> character in shell script fragments. The | |
39120 | variable names passed to <TT>AC_SUBST</TT> should begin with the | |
39121 | nickname, entirely upcased.</P> | |
39122 | <P> At the end of the new section is the place to put the aforementioned | |
39123 | nickname kludges (should they be needed). See Perl5 and Php4 for | |
39124 | examples of what to do. [If this is still unclear after you've read the | |
39125 | code, ping me and I'll expand on this further. --ttn]</P> | |
39126 | </DD> | |
39127 | <DT><B> Makefile.in</B></DT> | |
39128 | <DD> | |
39129 | <P> Some of the variables AC_SUBSTitutued are essential to the support | |
39130 | of your language module. Fashion these into a shell script "test" | |
39131 | clause and assign that to a skip tag using "-z" and "-o":</P> | |
39132 | <DIV class="code"> <TT>skip-qux99 = [ -z "@QUX99INCLUDE@" -o -z | |
39133 | "@QUX99LIBS" ]</TT></DIV> | |
39134 | <P> This means if those vars should ever be empty, qux99 support should | |
39135 | be considered absent and so it would be a good idea to skip actions | |
39136 | that might rely on it.</P> | |
39137 | <P> Here is where you may also define an alias (but then you'll need to | |
39138 | kludge --- don't do this):</P> | |
39139 | <DIV class="code"> <TT>skip-qux = $(skip-qux99)</TT></DIV> | |
39140 | <P> Lastly, you need to modify each of <TT>check-aliveness</TT>, <TT> | |
39141 | check-examples</TT>, <TT>check-test-suite</TT>, <TT>check-gifplot</TT> | |
39142 | (all targets) and <TT>lib-languages</TT> (var). Use the nickname for | |
39143 | these, not the alias. Note that you can do this even before you have | |
39144 | any tests or examples set up; the Makefile rules do some sanity | |
39145 | checking and skip around these kinds of problems.</P> | |
39146 | </DD> | |
39147 | <DT><B> Examples/Makefile.in</B></DT> | |
39148 | <DD> Nothing special here; see comments at top the of this file and look | |
39149 | to the existing languages for examples.</DD> | |
39150 | <DT><B> Examples/qux99/check.list</B></DT> | |
39151 | <DD> Do <TT>cp ../python/check.list .</TT> and modify to taste. One | |
39152 | subdir per line.</DD> | |
39153 | <DT><B> Examples/GIFPlot/Qux99/check.list</B></DT> | |
39154 | <DD> Do <TT>cp ../Python/check.list .</TT> and modify to taste. One | |
39155 | subdir per line.</DD> | |
39156 | <DT><B> Lib/qux99/extra-install.list</B></DT> | |
39157 | <DD> If you add your language to the top-level Makefile.in var <TT> | |
39158 | lib-languages</TT>, then <TT>make install</TT> will install all <TT>*.i</TT> | |
39159 | and <TT>*.swg</TT> files from the language-specific subdirectory of <TT> | |
39160 | Lib</TT>. Use (optional) file <TT>extra-install.list</TT> in that | |
39161 | directory to name additional files to install (see ruby for example).</DD> | |
39162 | <DT><B> Runtime/Makefile.in</B></DT> | |
39163 | <DD> Add another <TT>make</TT> invocation to <TT>all</TT>, and a section | |
39164 | for your language module.</DD> | |
39165 | <DT><B> Source/Modules1.1/Makefile.in</B></DT> | |
39166 | <DD> Add appropriate entries for vars <TT>OBJS</TT> and <TT>SRCS</TT>. | |
39167 | That's it!</DD> | |
39168 | </DL> | |
39169 | <P> At some point it would be a good idea to use <A HREF="http://www.gnu.org/software/automake/"> | |
39170 | automake</A> to handle some of these configuration tasks, but that point | |
39171 | is now long past. If you are interested in working on that, feel free | |
39172 | to raise the issue in the context of a next-generation clean-slate | |
39173 | SWIG.</P> | |
39174 | <H3><A name="Extending_nn40"></A>30.10.9 Runtime support</H3> | |
39175 | <P> Discuss the kinds of functions typically needed for SWIG runtime | |
39176 | support (e.g. <TT>SWIG_ConvertPtr()</TT> and <TT>SWIG_NewPointerObj()</TT> | |
39177 | ) and the names of the SWIG files that implement those functions.</P> | |
39178 | <H3><A name="Extending_nn41"></A>30.10.10 Standard library files</H3> | |
39179 | <P> Discuss the standard library files that most language modules | |
39180 | provide, e.g.</P> | |
39181 | <UL> | |
39182 | <LI> typemaps.i</LI> | |
39183 | <LI> std_string.i</LI> | |
39184 | <LI> std_vector.i</LI> | |
39185 | <LI> stl.i</LI> | |
39186 | </UL> | |
39187 | <H3><A name="Extending_nn42"></A>30.10.11 Examples and test cases</H3> | |
39188 | <P> Each of the language modules provides one or more examples. These | |
39189 | examples are used to demonstrate different features of the language | |
39190 | module to SWIG end-users, but you'll find that they're useful during | |
39191 | development and testing of your language module as well. You can use | |
39192 | examples from the existing SWIG language modules for inspiration.</P> | |
39193 | <P> Each example is self-contained and consists of (at least) a <TT> | |
39194 | Makefile</TT>, a SWIG interface file for the example module, and a | |
39195 | script that demonstrates the functionality for that module. All of | |
39196 | these files are stored in the same subdirectory, and that directory | |
39197 | should be nested under <TT>Examples/python</TT>. For example, the files | |
39198 | for the Python "simple" example are found in <TT>Examples/python/simple</TT> | |
39199 | .</P> | |
39200 | <P> By default, all of the examples are built and run when the user | |
39201 | types <TT>make check</TT>. To ensure that your examples are | |
39202 | automatically run during this process, see the section on <A href="#n37a"> | |
39203 | configuration files</A>.</P> | |
39204 | <H3><A name="Extending_nn43"></A>30.10.12 Documentation</H3> | |
39205 | <P> Don't forget to write end-user documentation for your language | |
39206 | module. Currently, each language module has a dedicated chapter | |
39207 | (although this structure may change in the future). You shouldn't | |
39208 | rehash things that are already covered in sufficient detail in the <A href="#SWIG"> | |
39209 | SWIG Basics</A> and <A href="#SWIGPlus">SWIG and C++</A> chapters. There | |
39210 | is no fixed format for<EM> what</EM>, exactly, you should document | |
39211 | about your language module, but you'll obviously want to cover issues | |
39212 | that are unique to your language.</P> | |
39213 | <P> Some topics that you'll want to be sure to address include:</P> | |
39214 | <UL> | |
39215 | <LI> Command line options unique to your language module.</LI> | |
39216 | <LI> Non-obvious mappings between C/C++ and scripting language concepts. | |
39217 | For example, if your scripting language provides a single floating | |
39218 | point type, it should be no big surprise to find that C/C++ <TT>float</TT> | |
39219 | and <TT>double</TT> types are mapped to it. On the other hand, if your | |
39220 | scripting language doesn't provide support for "classes" or something | |
39221 | similar, you'd want to discuss how C++ classes are handled.</LI> | |
39222 | <LI> How to compile the SWIG-generated wrapper code into shared | |
39223 | libraries that can actually be used. For some languages, there are | |
39224 | well-defined procedures for doing this, but for others it's an ad hoc | |
39225 | process. Provide as much detail as appropriate, and links to other | |
39226 | resources if available.</LI> | |
39227 | </UL> | |
39228 | <H2><A name="Extending_nn44"></A>30.11 Typemaps</H2> | |
39229 | <H3><A name="Extending_nn45"></A>30.11.1 Proxy classes</H3> | |
39230 | <H2><A name="Extending_nn46"></A>30.12 Guide to parse tree nodes</H2> | |
39231 | <P> This section describes the different parse tree nodes and their | |
39232 | attributes.</P> | |
39233 | <P><B> cdecl</B></P> | |
39234 | <P> Describes general C declarations including variables, functions, and | |
39235 | typedefs. A declaration is parsed as "storage T D" where storage is a | |
39236 | storage class, T is a base type, and D is a declarator.</P> | |
39237 | <DIV class="diagram"> | |
39238 | <PRE> | |
39239 | "name" - Declarator name | |
39240 | "type" - Base type T | |
39241 | "decl" - Declarator type (abstract) | |
39242 | "storage" - Storage class (static, extern, typedef, etc.) | |
39243 | "parms" - Function parameters (if a function) | |
39244 | "code" - Function body code (if supplied) | |
39245 | "value" - Default value (if supplied) | |
39246 | </PRE> | |
39247 | </DIV> | |
39248 | <P><B> constructor</B></P> | |
39249 | <P> C++ constructor declaration.</P> | |
39250 | <DIV class="diagram"> | |
39251 | <PRE> | |
39252 | "name" - Name of constructor | |
39253 | "parms" - Parameters | |
39254 | "decl" - Declarator (function with parameters) | |
39255 | "code" - Function body code (if any) | |
39256 | "feature:new" - Set to indicate return of new object. | |
39257 | </PRE> | |
39258 | </DIV> | |
39259 | <P><B> destructor</B></P> | |
39260 | <P> C++ destructor declaration.</P> | |
39261 | <DIV class="diagram"> | |
39262 | <PRE> | |
39263 | "name" - Name of destructor | |
39264 | "code" - Function body code (if any) | |
39265 | "storage" - Storage class (set if virtual) | |
39266 | "value" - Default value (set if pure virtual). | |
39267 | </PRE> | |
39268 | </DIV> | |
39269 | <P><B> access</B></P> | |
39270 | <P> C++ access change.</P> | |
39271 | <DIV class="diagram"> | |
39272 | <PRE> | |
39273 | "kind" - public, protected, private | |
39274 | </PRE> | |
39275 | </DIV> | |
39276 | <P><B> constant</B></P> | |
39277 | <P> Constant created by %constant or #define.</P> | |
39278 | <DIV class="diagram"> | |
39279 | <PRE> | |
39280 | "name" - Name of constant. | |
39281 | "type" - Base type. | |
39282 | "value" - Value. | |
39283 | "storage" - Set to %constant | |
39284 | "feature:immutable" - Set to indicate read-only | |
39285 | </PRE> | |
39286 | </DIV> | |
39287 | <P><B> class</B></P> | |
39288 | <P> C++ class definition or C structure definition.</P> | |
39289 | <DIV class="diagram"> | |
39290 | <PRE> | |
39291 | "name" - Name of the class. | |
39292 | "kind" - Class kind ("struct", "union", "class") | |
39293 | "symtab" - Enclosing symbol table. | |
39294 | "tdname" - Typedef name. Use for typedef struct { ... } A. | |
39295 | "abstract" - Set if class has pure virtual methods. | |
39296 | "baselist" - List of base class names. | |
39297 | "storage" - Storage class (if any) | |
39298 | "unnamed" - Set if class is unnamed. | |
39299 | </PRE> | |
39300 | </DIV> | |
39301 | <P><B> enum</B></P> | |
39302 | <P> Enumeration.</P> | |
39303 | <DIV class="diagram"> | |
39304 | <PRE> | |
39305 | "name" - Name of the enum (if supplied). | |
39306 | "storage" - Storage class (if any) | |
39307 | "tdname" - Typedef name (typedef enum { ... } name). | |
39308 | "unnamed" - Set if enum is unnamed. | |
39309 | </PRE> | |
39310 | </DIV> | |
39311 | <P><B> enumitem</B></P> | |
39312 | <P> Enumeration value.</P> | |
39313 | <DIV class="diagram"> | |
39314 | <PRE> | |
39315 | "name" - Name of the enum value. | |
39316 | "type" - Type (integer or char) | |
39317 | "value" - Enum value (if given) | |
39318 | "feature:immutable" - Set to indicate read-only | |
39319 | </PRE> | |
39320 | </DIV> | |
39321 | <P><B> namespace</B></P> | |
39322 | <P> C++ namespace.</P> | |
39323 | <DIV class="diagram"> | |
39324 | <PRE> | |
39325 | "name" - Name of the namespace. | |
39326 | "symtab" - Symbol table for enclosed scope. | |
39327 | "unnamed" - Set if unnamed namespace | |
39328 | "alias" - Alias name. Set for namespace A = B; | |
39329 | </PRE> | |
39330 | </DIV> | |
39331 | <P><B> using</B></P> | |
39332 | <P> C++ using directive.</P> | |
39333 | <DIV class="diagram"> | |
39334 | <PRE> | |
39335 | "name" - Name of the object being referred to. | |
39336 | "uname" - Qualified name actually given to using. | |
39337 | "node" - Node being referenced. | |
39338 | "namespace" - Namespace name being reference (using namespace name) | |
39339 | </PRE> | |
39340 | </DIV> | |
39341 | <P><B> classforward</B></P> | |
39342 | <P> A forward C++ class declaration.</P> | |
39343 | <DIV class="diagram"> | |
39344 | <PRE> | |
39345 | "name" - Name of the class. | |
39346 | "kind" - Class kind ("union", "struct", "class") | |
39347 | </PRE> | |
39348 | </DIV> | |
39349 | <P><B> insert</B></P> | |
39350 | <P> Code insertion directive. For example, %{ ... %} or | |
39351 | %insert(section).</P> | |
39352 | <DIV class="diagram"> | |
39353 | <PRE> | |
39354 | "code" - Inserted code | |
39355 | "section" - Section name ("header", "wrapper", etc.) | |
39356 | </PRE> | |
39357 | </DIV> | |
39358 | <P><B> top</B></P> | |
39359 | <P> Top of the parse tree.</P> | |
39360 | <DIV class="diagram"> | |
39361 | <PRE> | |
39362 | "module" - Module name | |
39363 | </PRE> | |
39364 | </DIV> | |
39365 | <P><B> extend</B></P> | |
39366 | <P> %extend directive.</P> | |
39367 | <DIV class="diagram"> | |
39368 | <PRE> | |
39369 | "name" - Module name | |
39370 | "symtab" - Symbol table of enclosed scope. | |
39371 | </PRE> | |
39372 | </DIV> | |
39373 | <P><B> apply</B></P> | |
39374 | <P> %apply pattern { patternlist }.</P> | |
39375 | <DIV class="diagram"> | |
39376 | <PRE> | |
39377 | "pattern" - Source pattern. | |
39378 | "symtab" - Symbol table of enclosed scope. | |
39379 | </PRE> | |
39380 | </DIV> | |
39381 | <P><B> clear</B></P> | |
39382 | <P> %clear patternlist;</P> | |
39383 | <DIV class="diagram"> | |
39384 | <PRE> | |
39385 | "firstChild" - Patterns to clear | |
39386 | </PRE> | |
39387 | </DIV> | |
39388 | <P><B> include</B></P> | |
39389 | <P> %include directive.</P> | |
39390 | <DIV class="diagram"> | |
39391 | <PRE> | |
39392 | "name" - Filename | |
39393 | "firstChild" - Children | |
39394 | </PRE> | |
39395 | </DIV> | |
39396 | <P><B> import</B></P> | |
39397 | <P> %import directive.</P> | |
39398 | <DIV class="diagram"> | |
39399 | <PRE> | |
39400 | "name" - Filename | |
39401 | "firstChild" - Children | |
39402 | </PRE> | |
39403 | </DIV> | |
39404 | <P><B> module</B></P> | |
39405 | <P> %module directive.</P> | |
39406 | <DIV class="diagram"> | |
39407 | <PRE> | |
39408 | "name" - Name of the module | |
39409 | </PRE> | |
39410 | </DIV> | |
39411 | <P><B> typemap</B></P> | |
39412 | <P> %typemap directive.</P> | |
39413 | <DIV class="diagram"> | |
39414 | <PRE> | |
39415 | "method" - Typemap method name. | |
39416 | "code" - Typemap code. | |
39417 | "kwargs" - Keyword arguments (if any) | |
39418 | "firstChild" - Typemap patterns | |
39419 | </PRE> | |
39420 | </DIV> | |
39421 | <P><B> typemapcopy</B></P> | |
39422 | <P> %typemap directive with copy.</P> | |
39423 | <DIV class="diagram"> | |
39424 | <PRE> | |
39425 | "method" - Typemap method name. | |
39426 | "pattern" - Typemap source pattern. | |
39427 | "firstChild" - Typemap patterns | |
39428 | </PRE> | |
39429 | </DIV> | |
39430 | <P><B> typemapitem</B></P> | |
39431 | <P> %typemap pattern. Used with %apply, %clear, %typemap.</P> | |
39432 | <DIV class="diagram"> | |
39433 | <PRE> | |
39434 | "pattern" - Typemap pattern (a parameter list) | |
39435 | "parms" - Typemap parameters. | |
39436 | </PRE> | |
39437 | </DIV> | |
39438 | <P><B> types</B></P> | |
39439 | <P> %types directive.</P> | |
39440 | <DIV class="diagram"> | |
39441 | <PRE> | |
39442 | "parms" - List of parameter types. | |
39443 | </PRE> | |
39444 | </DIV> | |
39445 | <P><B> extern</B></P> | |
39446 | <P> extern "X" { ... } declaration.</P> | |
39447 | <DIV class="diagram"> | |
39448 | <PRE> | |
39449 | "name" - Name "C", "Fortran", etc. | |
39450 | </PRE> | |
39451 | </DIV></BODY> | |
39452 | </HTML> |