Commit | Line | Data |
---|---|---|
920dae64 AT |
1 | <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> |
2 | <html> | |
3 | <head> | |
4 | <title>SWIG and C++</title> | |
5 | <link rel="stylesheet" type="text/css" href="style.css"> | |
6 | </head> | |
7 | ||
8 | <body bgcolor="#ffffff"> | |
9 | <H1><a name="SWIGPlus"></a>6 SWIG and C++</H1> | |
10 | <!-- INDEX --> | |
11 | <div class="sectiontoc"> | |
12 | <ul> | |
13 | <li><a href="#SWIGPlus_nn2">Comments on C++ Wrapping</a> | |
14 | <li><a href="#SWIGPlus_nn3">Approach</a> | |
15 | <li><a href="#SWIGPlus_nn4">Supported C++ features</a> | |
16 | <li><a href="#SWIGPlus_nn5">Command line options and compilation</a> | |
17 | <li><a href="#SWIGPlus_nn6">Simple C++ wrapping</a> | |
18 | <ul> | |
19 | <li><a href="#SWIGPlus_nn7">Constructors and destructors</a> | |
20 | <li><a href="#SWIGPlus_nn8">Default constructors</a> | |
21 | <li><a href="#SWIGPlus_nn9">When constructor wrappers aren't created</a> | |
22 | <li><a href="#SWIGPlus_nn10">Copy constructors</a> | |
23 | <li><a href="#SWIGPlus_nn11">Member functions</a> | |
24 | <li><a href="#SWIGPlus_nn12">Static members</a> | |
25 | <li><a href="#SWIGPlus_nn13">Member data</a> | |
26 | </ul> | |
27 | <li><a href="#SWIGPlus_default_args">Default arguments</a> | |
28 | <li><a href="#SWIGPlus_nn15">Protection</a> | |
29 | <li><a href="#SWIGPlus_nn16">Enums and constants</a> | |
30 | <li><a href="#SWIGPlus_nn17">Friends</a> | |
31 | <li><a href="#SWIGPlus_nn18">References and pointers</a> | |
32 | <li><a href="#SWIGPlus_nn19">Pass and return by value</a> | |
33 | <li><a href="#SWIGPlus_nn20">Inheritance</a> | |
34 | <li><a href="#SWIGPlus_nn21">A brief discussion of multiple inheritance, pointers, and type checking</a> | |
35 | <li><a href="#SWIGPlus_nn22">Renaming</a> | |
36 | <li><a href="#SWIGPlus_overloaded_methods">Wrapping Overloaded Functions and Methods</a> | |
37 | <ul> | |
38 | <li><a href="#SWIGPlus_nn24">Dispatch function generation</a> | |
39 | <li><a href="#SWIGPlus_nn25">Ambiguity in Overloading</a> | |
40 | <li><a href="#ambiguity_resolution_renaming">Ambiguity resolution and renaming</a> | |
41 | <li><a href="#SWIGPlus_nn27">Comments on overloading</a> | |
42 | </ul> | |
43 | <li><a href="#SWIGPlus_nn28">Wrapping overloaded operators</a> | |
44 | <li><a href="#SWIGPlus_nn29">Class extension</a> | |
45 | <li><a href="#SWIGPlus_nn30">Templates</a> | |
46 | <li><a href="#SWIGPlus_nn31">Namespaces</a> | |
47 | <li><a href="#SWIGPlus_exception_specifications">Exception specifications</a> | |
48 | <li><a href="#SWIGPlus_nn33">Pointers to Members</a> | |
49 | <li><a href="#SWIGPlus_nn34">Smart pointers and operator->()</a> | |
50 | <li><a href="#SWIGPlus_nn35">Using declarations and inheritance</a> | |
51 | <li><a href="#SWIGPlus_nn36">Partial class definitions</a> | |
52 | <li><a href="#SWIGPlus_nn37">A brief rant about const-correctness</a> | |
53 | <li><a href="#SWIGPlus_nn38">Proxy classes</a> | |
54 | <ul> | |
55 | <li><a href="#SWIGPlus_nn39">Construction of proxy classes</a> | |
56 | <li><a href="#SWIGPlus_nn40">Resource management in proxies</a> | |
57 | <li><a href="#SWIGPlus_nn41">Language specific details</a> | |
58 | </ul> | |
59 | <li><a href="#SWIGPlus_nn42">Where to go for more information</a> | |
60 | </ul> | |
61 | </div> | |
62 | <!-- INDEX --> | |
63 | ||
64 | ||
65 | ||
66 | <p> | |
67 | This chapter describes SWIG's support for wrapping C++. As a prerequisite, | |
68 | you should first read the chapter <a href="SWIG.html#SWIG">SWIG Basics</a> to see | |
69 | how SWIG wraps ANSI C. Support for C++ builds upon ANSI C | |
70 | wrapping and that material will be useful in understanding this chapter. | |
71 | </p> | |
72 | ||
73 | <H2><a name="SWIGPlus_nn2"></a>6.1 Comments on C++ Wrapping</H2> | |
74 | ||
75 | ||
76 | <p> | |
77 | Because of its complexity and the fact that C++ can be | |
78 | difficult to integrate with itself let alone other languages, SWIG | |
79 | only provides support for a subset of C++ features. Fortunately, | |
80 | this is now a rather large subset. | |
81 | </p> | |
82 | ||
83 | <p> | |
84 | In part, the problem with C++ wrapping is that there is no | |
85 | semantically obvious (or automatic ) way to map many of its advanced | |
86 | features into other languages. As a simple example, consider the | |
87 | problem of wrapping C++ multiple inheritance to a target language with | |
88 | no such support. Similarly, the use of overloaded operators and | |
89 | overloaded functions can be problematic when no such capability exists | |
90 | in a target language. | |
91 | </p> | |
92 | ||
93 | <p> | |
94 | A more subtle issue with C++ has to do with the way that some C++ | |
95 | programmers think about programming libraries. In the world of SWIG, | |
96 | you are really trying to create binary-level software components for | |
97 | use in other languages. In order for this to work, a "component" has | |
98 | to contain real executable instructions and there has to be some kind | |
99 | of binary linking mechanism for accessing its functionality. In | |
100 | contrast, C++ has increasingly relied upon generic programming and | |
101 | templates for much of its functionality. | |
102 | Although templates are a powerful feature, they are largely orthogonal | |
103 | to the whole notion of binary components and libraries. For example, | |
104 | an STL <tt>vector</tt> does not define any kind of binary object for | |
105 | which SWIG can just create a wrapper. To further complicate matters, | |
106 | these libraries often utilize a lot of behind the scenes magic in | |
107 | which the semantics of seemingly basic operations (e.g., pointer | |
108 | dereferencing, procedure call, etc.) can be changed in dramatic and | |
109 | sometimes non-obvious ways. Although this "magic" may present few | |
110 | problems in a C++-only universe, it greatly complicates the problem of | |
111 | crossing language boundaries and provides many opportunities to shoot | |
112 | yourself in the foot. You will just have to be careful. | |
113 | </p> | |
114 | ||
115 | <H2><a name="SWIGPlus_nn3"></a>6.2 Approach</H2> | |
116 | ||
117 | ||
118 | <p> | |
119 | To wrap C++, SWIG uses a layered approach to code generation. | |
120 | At the lowest level, SWIG generates a collection of procedural ANSI-C style | |
121 | wrappers. These wrappers take care of basic type conversion, | |
122 | type checking, error handling, and other low-level details of the C++ binding. | |
123 | These wrappers are also sufficient to bind C++ into any target language | |
124 | that supports built-in procedures. In some sense, you might view this | |
125 | layer of wrapping as providing a C library interface to C++. | |
126 | Optionally, SWIG can also generate proxy classes | |
127 | that provide a natural OO interface to the underlying code. These proxies | |
128 | are built on top of the low-level procedural wrappers and are typically | |
129 | written in the target language itself. For instance, in Python, a real | |
130 | Python class is used to provide a wrapper around the underlying C++ object. | |
131 | </p> | |
132 | ||
133 | <p> | |
134 | It is important to emphasize that SWIG takes a deliberately | |
135 | conservative and non-intrusive approach to C++ wrapping. SWIG does not | |
136 | encapsulate C++ classes inside special C++ adaptor or proxy classes, | |
137 | it does not rely upon templates, nor does it use C++ inheritance when | |
138 | generating wrappers. The last thing that most C++ programs need is | |
139 | even more compiler magic. Therefore, SWIG tries to maintain a very | |
140 | strict and clean separation between the implementation of your C++ | |
141 | application and the resulting wrapper code. You might say that SWIG | |
142 | has been written to follow the principle of least surprise--it does | |
143 | not play sneaky tricks with the C++ type system, it doesn't mess with | |
144 | your class hierarchies, and it doesn't introduce new semantics. | |
145 | Although this approach might not provide the most seamless integration | |
146 | with C++, it is safe, simple, portable, and debuggable. | |
147 | </p> | |
148 | ||
149 | <p> | |
150 | Most of this chapter focuses on the low-level procedural interface to | |
151 | C++ that is used as the foundation for all language modules. Keep in | |
152 | mind that most target languages also provide a high-level OO interface via | |
153 | proxy classes. A few general details about proxies can be found at the end of | |
154 | this chapter. However, more detailed coverage can be found in the documentation | |
155 | for each target language. | |
156 | </p> | |
157 | ||
158 | <H2><a name="SWIGPlus_nn4"></a>6.3 Supported C++ features</H2> | |
159 | ||
160 | ||
161 | <p> | |
162 | SWIG's currently supports the following C++ features :</p> | |
163 | ||
164 | <ul> | |
165 | <li>Classes. | |
166 | <li>Constructors and destructors | |
167 | <li>Virtual functions | |
168 | <li>Public inheritance (including multiple inheritance) | |
169 | <li>Static functions | |
170 | <li>Function and method overloading. | |
171 | <li>Operator overloading for many standard operators | |
172 | <li>References | |
173 | <li>Templates (including specialization and member templates). | |
174 | <li>Pointers to members | |
175 | <li>Namespaces | |
176 | </ul> | |
177 | ||
178 | <p> | |
179 | The following C++ features are not currently supported :</p> | |
180 | ||
181 | <ul> | |
182 | <li>Nested classes | |
183 | <li>Overloaded versions of certain operators (new, delete, etc.) | |
184 | </ul> | |
185 | ||
186 | <p> | |
187 | SWIG's C++ support is an ongoing project so some of these limitations may be lifted | |
188 | in future releases. However, we make no promises. Also, submitting a bug report is a very | |
189 | good way to get problems fixed (wink). | |
190 | </p> | |
191 | ||
192 | <H2><a name="SWIGPlus_nn5"></a>6.4 Command line options and compilation</H2> | |
193 | ||
194 | ||
195 | <p> | |
196 | When wrapping C++ code, it is critical that SWIG be called with the | |
197 | `<tt>-c++</tt>' option. This changes the way a number of critical | |
198 | features such as memory management are handled. It | |
199 | also enables the recognition of C++ keywords. Without the <tt>-c++</tt> | |
200 | flag, SWIG will either issue a warning or a large number of syntax | |
201 | errors if it encounters C++ code in an interface file.</p> | |
202 | ||
203 | <p> | |
204 | When compiling and linking the resulting wrapper file, it is normal | |
205 | to use the C++ compiler. For example: | |
206 | </p> | |
207 | ||
208 | <div class="shell"> | |
209 | <pre> | |
210 | $ swig -c++ -tcl example.i | |
211 | $ c++ -c example_wrap.cxx | |
212 | $ c++ example_wrap.o $(OBJS) -o example.so | |
213 | </pre> | |
214 | </div> | |
215 | ||
216 | <p> | |
217 | Unfortunately, the process varies slightly on each machine. Make sure | |
218 | you refer to the documentation on each target language for further | |
219 | details. The SWIG Wiki also has further details. | |
220 | </p> | |
221 | ||
222 | <H2><a name="SWIGPlus_nn6"></a>6.5 Simple C++ wrapping</H2> | |
223 | ||
224 | ||
225 | <p> | |
226 | The following code shows a SWIG interface file for a simple C++ | |
227 | class.</p> | |
228 | ||
229 | <div class="code"><pre> | |
230 | %module list | |
231 | %{ | |
232 | #include "list.h" | |
233 | %} | |
234 | ||
235 | // Very simple C++ example for linked list | |
236 | ||
237 | class List { | |
238 | public: | |
239 | List(); | |
240 | ~List(); | |
241 | int search(char *value); | |
242 | void insert(char *); | |
243 | void remove(char *); | |
244 | char *get(int n); | |
245 | int length; | |
246 | static void print(List *l); | |
247 | }; | |
248 | </pre></div> | |
249 | ||
250 | <p> | |
251 | To generate wrappers for this class, SWIG first reduces the class to a collection of low-level C-style | |
252 | accessor functions. The next few sections describe this process. Later parts of the chapter describe a higher | |
253 | level interface based on proxy classes. | |
254 | </p> | |
255 | ||
256 | <H3><a name="SWIGPlus_nn7"></a>6.5.1 Constructors and destructors</H3> | |
257 | ||
258 | ||
259 | <p> | |
260 | C++ constructors and destructors are translated into accessor | |
261 | functions such as the following :</p> | |
262 | ||
263 | <div class="code"><pre> | |
264 | List * new_List(void) { | |
265 | return new List; | |
266 | } | |
267 | void delete_List(List *l) { | |
268 | delete l; | |
269 | } | |
270 | ||
271 | </pre></div> | |
272 | ||
273 | <H3><a name="SWIGPlus_nn8"></a>6.5.2 Default constructors</H3> | |
274 | ||
275 | ||
276 | <p> | |
277 | If a C++ class does not define any public constructors or | |
278 | destructors, SWIG will automatically create a default constructor or | |
279 | destructor. However, there are a few rules that define this behavior: | |
280 | </p> | |
281 | ||
282 | <ul> | |
283 | <li>A default constructor is not created if a class already defines a constructor with arguments. | |
284 | </li> | |
285 | ||
286 | <li>Default constructors are not generated for classes with pure virtual methods or for classes that | |
287 | inherit from an abstract class, but don't provide definitions for all of the pure methods. | |
288 | </li> | |
289 | ||
290 | <li>A default constructor is not created unless all bases classes support a | |
291 | default constructor. | |
292 | </li> | |
293 | ||
294 | <li>Default constructors and destructors are not created if a class | |
295 | defines constructors or destructors in a <tt>private</tt> or <tt>protected</tt> section. | |
296 | </li> | |
297 | ||
298 | <li>Default constructors and destructors are not created if any base | |
299 | class defines a private default constructor or a private destructor. | |
300 | </li> | |
301 | </ul> | |
302 | ||
303 | <p> | |
304 | SWIG should never generate a constructor or destructor for a class in which | |
305 | it is illegal to do so. However, if it is necessary to disable the | |
306 | default constructor/destructor creation, the <tt>%nodefault</tt> directive | |
307 | can be used: | |
308 | </p> | |
309 | ||
310 | <div class="code"> | |
311 | <pre> | |
312 | %nodefault; // Disable creation of constructor/destructor | |
313 | class Foo { | |
314 | ... | |
315 | }; | |
316 | %makedefault; | |
317 | </pre> | |
318 | </div> | |
319 | ||
320 | <p> | |
321 | <tt>%nodefault</tt> can also take a class name. For example: | |
322 | </p> | |
323 | ||
324 | <div class="code"> | |
325 | <pre> | |
326 | %nodefault Foo; // Disable for class Foo only. | |
327 | </pre> | |
328 | </div> | |
329 | ||
330 | <p> | |
331 | <b>Compatibility Note:</b> The generation of default | |
332 | constructors/destructors was made the default behavior in SWIG | |
333 | 1.3.7. This may break certain older modules, but the old behavior can | |
334 | be easily restored using <tt>%nodefault</tt> or the | |
335 | <tt>-nodefault</tt> command line option. Furthermore, in order for | |
336 | SWIG to properly generate (or not generate) default constructors, it | |
337 | must be able to gather information from both the <tt>private</tt> and | |
338 | <tt>protected</tt> sections (specifically, it needs to know if a private or | |
339 | protected constructor/destructor is defined). In older versions of | |
340 | SWIG, it was fairly common to simply remove or comment out | |
341 | the private and protected sections of a class due to parser limitations. | |
342 | However, this removal may now cause SWIG to erroneously generate constructors | |
343 | for classes that define a constructor in those sections. Consider restoring | |
344 | those sections in the interface or using <tt>%nodefault</tt> to fix the problem. | |
345 | </p> | |
346 | ||
347 | <H3><a name="SWIGPlus_nn9"></a>6.5.3 When constructor wrappers aren't created</H3> | |
348 | ||
349 | ||
350 | <p> | |
351 | If a class defines a constructor, SWIG normally tries to generate a wrapper for it. However, SWIG will | |
352 | not generate a constructor wrapper if it thinks that it will result in illegal wrapper code. There are really | |
353 | two cases where this might show up. | |
354 | </p> | |
355 | ||
356 | <p> | |
357 | First, SWIG won't generate wrappers for protected or private constructors. For example: | |
358 | </p> | |
359 | ||
360 | <div class="code"> | |
361 | <pre> | |
362 | class Foo { | |
363 | protected: | |
364 | Foo(); // Not wrapped. | |
365 | public: | |
366 | ... | |
367 | }; | |
368 | </pre> | |
369 | </div> | |
370 | ||
371 | <p> | |
372 | Next, SWIG won't generate wrappers for a class if it appears to be abstract--that is, it has undefined | |
373 | pure virtual methods. Here are some examples: | |
374 | </p> | |
375 | ||
376 | <div class="code"> | |
377 | <pre> | |
378 | class Bar { | |
379 | public: | |
380 | Bar(); // Not wrapped. Bar is abstract. | |
381 | virtual void spam(void) = 0; | |
382 | }; | |
383 | ||
384 | class Grok : public Bar { | |
385 | public: | |
386 | Grok(); // Not wrapped. No implementation of abstract spam(). | |
387 | }; | |
388 | </pre> | |
389 | </div> | |
390 | ||
391 | <p> | |
392 | Some users are surprised (or confused) to find missing constructor wrappers in their interfaces. In almost | |
393 | all cases, this is caused when classes are determined to be abstract. To see if this is the case, run SWIG with | |
394 | all of its warnings turned on: | |
395 | </p> | |
396 | ||
397 | <div class="shell"> | |
398 | <pre> | |
399 | % swig -Wall -python module.i | |
400 | </pre> | |
401 | </div> | |
402 | ||
403 | <p> | |
404 | In this mode, SWIG will issue a warning for all abstract classes. It is possible to force a class to be | |
405 | non-abstract using this: | |
406 | </p> | |
407 | ||
408 | <div class="code"> | |
409 | <pre> | |
410 | %feature("notabstract") Foo; | |
411 | ||
412 | class Foo : public Bar { | |
413 | public: | |
414 | Foo(); // Generated no matter what---not abstract. | |
415 | ... | |
416 | }; | |
417 | </pre> | |
418 | </div> | |
419 | ||
420 | <p> | |
421 | More information about <tt>%feature</tt> can be found in the <a href="Customization.html#Customization">Customization features</a> chapter. | |
422 | </p> | |
423 | ||
424 | <H3><a name="SWIGPlus_nn10"></a>6.5.4 Copy constructors</H3> | |
425 | ||
426 | ||
427 | <p> | |
428 | If a class defines more than one constructor, its behavior depends on the capabilities of the | |
429 | target language. If overloading is supported, the copy constructor is accessible using | |
430 | the normal constructor function. For example, if you have this: | |
431 | </p> | |
432 | ||
433 | <div class="code"> | |
434 | <pre> | |
435 | class List { | |
436 | public: | |
437 | List(); | |
438 | List(const List &); // Copy constructor | |
439 | ... | |
440 | }; | |
441 | </pre> | |
442 | </div> | |
443 | ||
444 | <p> | |
445 | then the copy constructor can be used as follows: | |
446 | </p> | |
447 | ||
448 | <div class="targetlang"> | |
449 | <pre> | |
450 | x = new_List() # Create a list | |
451 | y = new_List(x) # Copy list x | |
452 | </pre> | |
453 | </div> | |
454 | ||
455 | <p> | |
456 | If the target language does not support overloading, then the copy constructor is available | |
457 | through a special function like this: | |
458 | </p> | |
459 | ||
460 | <div class="code"> | |
461 | <pre> | |
462 | List *copy_List(List *f) { | |
463 | return new List(*f); | |
464 | } | |
465 | </pre> | |
466 | </div> | |
467 | ||
468 | <p> | |
469 | <b>Note:</b> For a class <tt>X</tt>, SWIG only treats a constructor as | |
470 | a copy constructor if it can be applied to an object of type | |
471 | <tt>X</tt> or <tt>X *</tt>. If more than one copy constructor is | |
472 | defined, only the first definition that appears is used as the copy | |
473 | constructor--other definitions will result in a name-clash. | |
474 | Constructors such as <tt>X(const X &)</tt>, <tt>X(X &)</tt>, and | |
475 | <tt>X(X *)</tt> are handled as copy constructors in SWIG. | |
476 | </p> | |
477 | ||
478 | <p> | |
479 | <b>Note:</b> SWIG does <em>not</em> generate a copy constructor | |
480 | wrapper unless one is explicitly declared in the class. This differs | |
481 | from the treatment of default constructors and destructors. | |
482 | </p> | |
483 | ||
484 | <p> | |
485 | <b>Compatibility note:</b> Special support for copy constructors was | |
486 | not added until SWIG-1.3.12. In previous versions, copy constructors | |
487 | could be wrapped, but they had to be renamed. For example: | |
488 | </p> | |
489 | ||
490 | <div class="code"> | |
491 | <pre> | |
492 | class Foo { | |
493 | public: | |
494 | Foo(); | |
495 | %name(CopyFoo) Foo(const Foo &); | |
496 | ... | |
497 | }; | |
498 | </pre> | |
499 | </div> | |
500 | ||
501 | <p> | |
502 | For backwards compatibility, SWIG does not perform any special | |
503 | copy-constructor handling if the constructor has been manually | |
504 | renamed. For instance, in the above example, the name of the | |
505 | constructor is set to <tt>new_CopyFoo()</tt>. This is the same as in | |
506 | older versions. | |
507 | </p> | |
508 | ||
509 | <H3><a name="SWIGPlus_nn11"></a>6.5.5 Member functions</H3> | |
510 | ||
511 | ||
512 | <p> | |
513 | All member functions are roughly translated into accessor functions like this :</p> | |
514 | ||
515 | <div class="code"><pre> | |
516 | int List_search(List *obj, char *value) { | |
517 | return obj->search(value); | |
518 | } | |
519 | ||
520 | </pre></div> | |
521 | ||
522 | <p> | |
523 | This translation is the same even if the member function has been | |
524 | declared as <tt>virtual</tt>. | |
525 | </p> | |
526 | ||
527 | <p> | |
528 | It should be noted that SWIG does not <em>actually</em> create a C accessor | |
529 | function in the code it generates. Instead, member access such as | |
530 | <tt>obj->search(value)</tt> is directly inlined into the generated | |
531 | wrapper functions. However, the name and calling convention of the | |
532 | wrappers match the accessor function prototype described above. | |
533 | </p> | |
534 | ||
535 | <H3><a name="SWIGPlus_nn12"></a>6.5.6 Static members</H3> | |
536 | ||
537 | ||
538 | <p> | |
539 | Static member functions are called directly without making any special | |
540 | transformations. For example, the static member function | |
541 | <tt>print(List *l)</tt> directly invokes <tt>List::print(List *l)</tt> | |
542 | in the generated wrapper code. | |
543 | </p> | |
544 | ||
545 | <p> | |
546 | Usually, static members are accessed as functions with names in which the class name has been | |
547 | prepended with an underscore. For example, <tt>List_print</tt>. | |
548 | </p> | |
549 | ||
550 | <H3><a name="SWIGPlus_nn13"></a>6.5.7 Member data</H3> | |
551 | ||
552 | ||
553 | <p> | |
554 | Member data is handled in exactly the same manner as for C | |
555 | structures. A pair of accessor functions are created. For example | |
556 | :</p> | |
557 | ||
558 | <div class="code"><pre> | |
559 | int List_length_get(List *obj) { | |
560 | return obj->length; | |
561 | } | |
562 | int List_length_set(List *obj, int value) { | |
563 | obj->length = value; | |
564 | return value; | |
565 | } | |
566 | ||
567 | </pre></div> | |
568 | ||
569 | <p> | |
570 | A read-only member can be created using the <tt>%immutable</tt> and | |
571 | <tt>%mutable</tt> directives. For example, we probably wouldn't want | |
572 | the user to change the length of a list so we could do the following | |
573 | to make the value available, but read-only.</p> | |
574 | ||
575 | <div class="code"><pre> | |
576 | class List { | |
577 | public: | |
578 | ... | |
579 | %immutable; | |
580 | int length; | |
581 | %mutable; | |
582 | ... | |
583 | }; | |
584 | </pre></div> | |
585 | ||
586 | <p> | |
587 | Alternatively, you can specify an immutable member in advance like this: | |
588 | </p> | |
589 | ||
590 | <div class="code"> | |
591 | <pre> | |
592 | %immutable List::length; | |
593 | ... | |
594 | class List { | |
595 | ... | |
596 | int length; // Immutable by above directive | |
597 | ... | |
598 | }; | |
599 | </pre> | |
600 | </div> | |
601 | ||
602 | <p> | |
603 | Similarly, all data attributes declared as <tt>const</tt> are wrapped as read-only members. | |
604 | </p> | |
605 | ||
606 | <p> | |
607 | There are some subtle issues when wrapping data members that are | |
608 | themselves classes. For instance, if you had another class like this, | |
609 | </p> | |
610 | ||
611 | <div class="code"> | |
612 | <pre> | |
613 | class Foo { | |
614 | public: | |
615 | List items; | |
616 | ... | |
617 | </pre> | |
618 | </div> | |
619 | ||
620 | <p> | |
621 | then access to the <tt>items</tt> member actually uses pointers. For example: | |
622 | </p> | |
623 | ||
624 | <div class="code"> | |
625 | <pre> | |
626 | List *Foo_items_get(Foo *self) { | |
627 | return &self->items; | |
628 | } | |
629 | void Foo_items_set(Foo *self, List *value) { | |
630 | self->items = *value; | |
631 | } | |
632 | </pre> | |
633 | </div> | |
634 | ||
635 | <p> | |
636 | More information about this can be found in the "Structure data | |
637 | members" section of the <a href="SWIG.html#SWIG">SWIG Basics</a> chapter. | |
638 | </p> | |
639 | ||
640 | <p> | |
641 | <b>Compatibility note:</b> Read-only access used to be controlled by a pair of directives | |
642 | <tt>%readonly</tt> and <tt>%readwrite</tt>. Although these directives still work, they | |
643 | generate a warning message. Simply change the directives to <tt>%immutable;</tt> and | |
644 | <tt>%mutable;</tt> to silence the warning. Don't forget the extra semicolon! | |
645 | </p> | |
646 | ||
647 | <p> | |
648 | <b>Compatibility note:</b> Prior to SWIG-1.3.12, all members of unknown type were | |
649 | wrapped into accessor functions using pointers. For example, if you had a structure | |
650 | like this | |
651 | </p> | |
652 | ||
653 | <div class="code"> | |
654 | <pre> | |
655 | struct Foo { | |
656 | size_t len; | |
657 | }; | |
658 | </pre> | |
659 | </div> | |
660 | ||
661 | <p> | |
662 | and nothing was known about <tt>size_t</tt>, then accessors would be | |
663 | written to work with <tt>size_t *</tt>. Starting in SWIG-1.3.12, this | |
664 | behavior has been modified. Specifically, pointers will <em>only</em> | |
665 | be used if SWIG knows that a datatype corresponds to a structure or | |
666 | class. Therefore, the above code would be wrapped into accessors | |
667 | involving <tt>size_t</tt>. This change is subtle, but it smooths over | |
668 | a few problems related to structure wrapping and some of SWIG's | |
669 | customization features. | |
670 | </p> | |
671 | ||
672 | <H2><a name="SWIGPlus_default_args"></a>6.6 Default arguments</H2> | |
673 | ||
674 | ||
675 | <p> | |
676 | SWIG will wrap all types of functions that have default arguments. For example member functions: | |
677 | </p> | |
678 | ||
679 | <div class="code"> | |
680 | <pre> | |
681 | class Foo { | |
682 | public: | |
683 | void bar(int x, int y = 3, int z = 4); | |
684 | }; | |
685 | </pre> | |
686 | </div> | |
687 | ||
688 | <p> | |
689 | SWIG handles default arguments by generating an extra overloaded method for each defaulted argument. | |
690 | SWIG is effectively handling methods with default arguments as if it had wrapped the equivalent overloaded methods. | |
691 | Thus for the example above, it is as if we had instead given the following to SWIG: | |
692 | </p> | |
693 | ||
694 | <div class="code"> | |
695 | <pre> | |
696 | class Foo { | |
697 | public: | |
698 | void bar(int x, int y, int z); | |
699 | void bar(int x, int y); | |
700 | void bar(int x); | |
701 | }; | |
702 | </pre> | |
703 | </div> | |
704 | ||
705 | <p> | |
706 | The wrappers produced are exactly the same as if the above code was instead fed into SWIG. | |
707 | Details of this is covered later in the <a href="#SWIGPlus_overloaded_methods">Wrapping Overloaded Functions and Methods</a> section. | |
708 | This approach allows SWIG to wrap all possible default arguments, but can be verbose. | |
709 | For example if a method has ten default arguments, then eleven wrapper methods are generated. | |
710 | </p> | |
711 | ||
712 | <p> | |
713 | Please see the <a href="Customization.html#Customization_features_default_args">Features and default arguments</a> | |
714 | section for more information on using <tt>%feature</tt> with functions with default arguments. | |
715 | The <a href="#ambiguity_resolution_renaming">Ambiguity resolution and renaming</a> section | |
716 | also deals with using <tt>%rename</tt> and <tt>%ignore</tt> on methods with default arguments. | |
717 | If you are writing your own typemaps for types used in methods with default arguments, you may also need to write a <tt>typecheck</tt> typemap. | |
718 | See the <a href="Typemaps.html#Typemaps_overloading">Typemaps and overloading</a> section for details or otherwise | |
719 | use the <tt>compactdefaultargs</tt> feature as mentioned below. | |
720 | </p> | |
721 | ||
722 | <p> | |
723 | <b>Compatibility note:</b> Versions of SWIG prior to SWIG-1.3.23 wrapped default arguments slightly differently. | |
724 | Instead a single wrapper method was generated and the default values were copied into the C++ wrappers | |
725 | so that the method being wrapped was then called with all the arguments specified. | |
726 | If the size of the wrappers are a concern then this approach to wrapping methods with default arguments | |
727 | can be re-activated by using the <tt>compactdefaultargs</tt> <a href="Customization.html#features">feature</a>. | |
728 | </p> | |
729 | ||
730 | <div class="code"> | |
731 | <pre> | |
732 | %feature("compactdefaultargs") Foo::bar; | |
733 | class Foo { | |
734 | public: | |
735 | void bar(int x, int y = 3, int z = 4); | |
736 | }; | |
737 | </pre> | |
738 | </div> | |
739 | ||
740 | ||
741 | <p> | |
742 | This is great for reducing the size of the wrappers, but the caveat is it does not work for the strongly typed languages | |
743 | which don't have optional arguments in the language, such as C# and Java. | |
744 | Another restriction of this feature is that it cannot handle default arguments that are not public. | |
745 | The following example illustrates this: | |
746 | </p> | |
747 | ||
748 | <div class="code"> | |
749 | <pre> | |
750 | class Foo { | |
751 | private: | |
752 | static const int spam; | |
753 | public: | |
754 | void bar(int x, int y = spam); // Won't work with %feature("compactdefaultargs") - | |
755 | // private default value | |
756 | }; | |
757 | </pre> | |
758 | </div> | |
759 | ||
760 | <p> | |
761 | This produces uncompileable wrapper code because default values in C++ are | |
762 | evaluated in the same scope as the member function whereas SWIG | |
763 | evaluates them in the scope of a wrapper function (meaning that the | |
764 | values have to be public). | |
765 | </p> | |
766 | ||
767 | <p> | |
768 | This feature is automatically turned on when wrapping <a href="SWIG.html#SWIG_default_args">C code with default arguments</a> | |
769 | and whenever keyword arguments (kwargs) are specified for either C or C++ code. | |
770 | Keyword arguments are a language feature of some scripting languages, for example Ruby and Python. | |
771 | SWIG is unable to support kwargs when wrapping overloaded methods, so the default approach cannot be used. | |
772 | </p> | |
773 | ||
774 | <H2><a name="SWIGPlus_nn15"></a>6.7 Protection</H2> | |
775 | ||
776 | ||
777 | <p> | |
778 | SWIG wraps class members that are public following the C++ | |
779 | conventions, i.e., by explicit public declaration or by the use of | |
780 | the <tt> using</tt> directive. In general, anything specified in a | |
781 | private or protected section will be ignored, although the internal | |
782 | code generator sometimes looks at the contents of the private and | |
783 | protected sections so that it can properly generate code for default | |
784 | constructors and destructors. Directors could also modify the way | |
785 | non-public virtual protected members are treated. | |
786 | </p> | |
787 | ||
788 | <p> | |
789 | By default, members of a class definition are assumed to be private | |
790 | until you explicitly give a `<tt>public:</tt>' declaration (This is | |
791 | the same convention used by C++). | |
792 | </p> | |
793 | ||
794 | <H2><a name="SWIGPlus_nn16"></a>6.8 Enums and constants</H2> | |
795 | ||
796 | ||
797 | <p> | |
798 | Enumerations and constants are handled differently by the different language modules and are described in detail in the appropriate language chapter. | |
799 | However, many languages map enums and constants in a class definition | |
800 | into constants with the classname as a prefix. For example :</p> | |
801 | ||
802 | <div class="code"><pre> | |
803 | class Swig { | |
804 | public: | |
805 | enum {ALE, LAGER, PORTER, STOUT}; | |
806 | }; | |
807 | ||
808 | </pre></div> | |
809 | <p> | |
810 | Generates the following set of constants in the target scripting language :</p> | |
811 | ||
812 | <div class="targetlang"><pre> | |
813 | Swig_ALE = Swig::ALE | |
814 | Swig_LAGER = Swig::LAGER | |
815 | Swig_PORTER = Swig::PORTER | |
816 | Swig_STOUT = Swig::STOUT | |
817 | ||
818 | </pre></div> | |
819 | ||
820 | <p> | |
821 | Members declared as <tt>const</tt> are wrapped as read-only members and do not create constants. | |
822 | </p> | |
823 | ||
824 | <H2><a name="SWIGPlus_nn17"></a>6.9 Friends</H2> | |
825 | ||
826 | ||
827 | <p> | |
828 | Friend declarations are not longer ignored by SWIG. For example, if | |
829 | you have this code: | |
830 | </p> | |
831 | ||
832 | <div class="code"> | |
833 | <pre> | |
834 | class Foo { | |
835 | public: | |
836 | ... | |
837 | friend void blah(Foo *f); | |
838 | ... | |
839 | }; | |
840 | </pre> | |
841 | </div> | |
842 | ||
843 | <p> | |
844 | then the <tt>friend</tt> declaration does result in a wrapper code | |
845 | equivalent to one generated for the following declaration | |
846 | </p> | |
847 | ||
848 | <div class="code"> | |
849 | <pre> | |
850 | class Foo { | |
851 | public: | |
852 | ... | |
853 | }; | |
854 | ||
855 | void blah(Foo *f); | |
856 | </pre> | |
857 | </div> | |
858 | ||
859 | <p> | |
860 | A friend declaration, as in C++, is understood to be in the same scope | |
861 | where the class is declared, hence, you can do | |
862 | </p> | |
863 | ||
864 | <div class="code"> | |
865 | <pre> | |
866 | ||
867 | %ignore bar::blah(Foo *f); | |
868 | ||
869 | namespace bar { | |
870 | ||
871 | class Foo { | |
872 | public: | |
873 | ... | |
874 | friend void blah(Foo *f); | |
875 | ... | |
876 | }; | |
877 | } | |
878 | </pre> | |
879 | </div> | |
880 | ||
881 | <p> | |
882 | and a wrapper for the method 'blah' will not be generated. | |
883 | </p> | |
884 | ||
885 | <H2><a name="SWIGPlus_nn18"></a>6.10 References and pointers</H2> | |
886 | ||
887 | ||
888 | <p> | |
889 | C++ references are supported, but SWIG transforms them back into pointers. For example, | |
890 | a declaration like this :</p> | |
891 | ||
892 | <div class="code"><pre> | |
893 | class Foo { | |
894 | public: | |
895 | double bar(double &a); | |
896 | } | |
897 | </pre></div> | |
898 | ||
899 | <p> | |
900 | is accessed using a function similar to this:</p> | |
901 | ||
902 | <div class="code"><pre> | |
903 | double Foo_bar(Foo *obj, double *a) { | |
904 | obj->bar(*a); | |
905 | } | |
906 | </pre></div> | |
907 | ||
908 | <p> | |
909 | As a special case, most language modules pass <tt>const</tt> references to primitive datatypes (<tt>int</tt>, <tt>short</tt>, | |
910 | <tt>float</tt>, etc.) by value instead of pointers. For example, if you have a function like this, | |
911 | </p> | |
912 | ||
913 | <div class="code"> | |
914 | <pre> | |
915 | void foo(const int &x); | |
916 | </pre> | |
917 | </div> | |
918 | ||
919 | <p> | |
920 | it is called from a script as follows: | |
921 | </p> | |
922 | ||
923 | <div class="targetlang"> | |
924 | <pre> | |
925 | foo(3) # Notice pass by value | |
926 | </pre> | |
927 | </div> | |
928 | ||
929 | <p> | |
930 | Functions that return a reference are remapped to return a pointer instead. | |
931 | For example: | |
932 | </p> | |
933 | ||
934 | <div class="code"><pre> | |
935 | class Bar { | |
936 | public: | |
937 | Foo &spam(); | |
938 | }; | |
939 | </pre> | |
940 | </div> | |
941 | ||
942 | <p> | |
943 | Generates code like this: | |
944 | </p> | |
945 | ||
946 | <div class="code"> | |
947 | <pre> | |
948 | Foo *Bar_spam(Bar *obj) { | |
949 | Foo &result = obj->spam(); | |
950 | return &result; | |
951 | } | |
952 | </pre> | |
953 | </div> | |
954 | ||
955 | <p> | |
956 | However, functions that return <tt>const</tt> references to primitive datatypes (<tt>int</tt>, <tt>short</tt>, etc.) normally | |
957 | return the result as a value rather than a pointer. For example, a function like this, | |
958 | </p> | |
959 | ||
960 | <div class="code"> | |
961 | <pre> | |
962 | const int &bar(); | |
963 | </pre> | |
964 | </div> | |
965 | ||
966 | <p> | |
967 | will return integers such as 37 or 42 in the target scripting language rather than a pointer to an integer. | |
968 | </p> | |
969 | ||
970 | <P> | |
971 | Don't return references to objects allocated as local variables on the | |
972 | stack. SWIG doesn't make a copy of the objects so this will probably | |
973 | cause your program to crash. | |
974 | ||
975 | ||
976 | ||
977 | <p> | |
978 | <b>Note:</b> The special treatment for references to primitive datatypes is necessary to provide | |
979 | more seamless integration with more advanced C++ wrapping applications---especially related to | |
980 | templates and the STL. This was first added in SWIG-1.3.12. | |
981 | </p> | |
982 | ||
983 | ||
984 | <H2><a name="SWIGPlus_nn19"></a>6.11 Pass and return by value</H2> | |
985 | ||
986 | ||
987 | <p> | |
988 | Occasionally, a C++ program will pass and return class objects by value. For example, a function | |
989 | like this might appear: | |
990 | </p> | |
991 | ||
992 | <div class="code"> | |
993 | <pre> | |
994 | Vector cross_product(Vector a, Vector b); | |
995 | </pre> | |
996 | </div> | |
997 | ||
998 | <p> | |
999 | If no information is supplied about <tt>Vector</tt>, SWIG creates a wrapper function similar to the | |
1000 | following: | |
1001 | </p> | |
1002 | ||
1003 | <div class="code"> | |
1004 | <pre> | |
1005 | Vector *wrap_cross_product(Vector *a, Vector *b) { | |
1006 | Vector x = *a; | |
1007 | Vector y = *b; | |
1008 | Vector r = cross_product(x,y); | |
1009 | return new Vector(r); | |
1010 | }</pre> | |
1011 | </div> | |
1012 | ||
1013 | <p> | |
1014 | In order for the wrapper code to compile, <tt>Vector</tt> must define a copy constructor and a | |
1015 | default constructor. | |
1016 | </p> | |
1017 | ||
1018 | <p> | |
1019 | If <tt>Vector</tt> is defined as class in the interface, but it does | |
1020 | not support a default constructor, SWIG changes the wrapper code by | |
1021 | encapsulating the arguments inside a special C++ template wrapper | |
1022 | class. This produces a wrapper that looks like this: | |
1023 | </p> | |
1024 | ||
1025 | <div class="code"> | |
1026 | <pre> | |
1027 | Vector cross_product(Vector *a, Vector *b) { | |
1028 | SwigValueWrapper<Vector> x = *a; | |
1029 | SwigValueWrapper<Vector> y = *b; | |
1030 | SwigValueWrapper<Vector> r = cross_product(x,y); | |
1031 | return new Vector(r); | |
1032 | } | |
1033 | </pre> | |
1034 | </div> | |
1035 | ||
1036 | <p> | |
1037 | This transformation is a little sneaky, but it provides support for | |
1038 | pass-by-value even when a class does not provide a default constructor | |
1039 | and it makes it possible to properly support a number of SWIG's | |
1040 | customization options. The definition of <tt>SwigValueWrapper</tt> | |
1041 | can be found by reading the SWIG wrapper code. This class is really nothing more than a thin | |
1042 | wrapper around a pointer. | |
1043 | </p> | |
1044 | ||
1045 | <p> | |
1046 | <b>Note:</b> this transformation has no effect on typemaps | |
1047 | or any other part of SWIG---it should be transparent except that you | |
1048 | may see this code when reading the SWIG output file. | |
1049 | </p> | |
1050 | ||
1051 | <p> | |
1052 | <b> | |
1053 | Note: </b>This template transformation is new in SWIG-1.3.11 and may be refined in | |
1054 | future SWIG releases. In practice, it is only necessary to do this for | |
1055 | classes that don't define a default constructor. | |
1056 | </p> | |
1057 | ||
1058 | <p> | |
1059 | <b>Note:</b> The use of this template only occurs when objects are passed or returned by value. | |
1060 | It is not used for C++ pointers or references. | |
1061 | </p> | |
1062 | ||
1063 | <p> | |
1064 | <b>Note:</b> The performance of pass-by-value is especially bad for large objects and should be avoided | |
1065 | if possible (consider using references instead). | |
1066 | </p> | |
1067 | ||
1068 | <H2><a name="SWIGPlus_nn20"></a>6.12 Inheritance</H2> | |
1069 | ||
1070 | ||
1071 | <p> | |
1072 | SWIG supports C++ inheritance of classes and allows both single and | |
1073 | multiple inheritance, as limited or allowed by the target | |
1074 | language. The SWIG type-checker knows about the relationship between | |
1075 | base and derived classes and allows pointers to any object of a | |
1076 | derived class to be used in functions of a base class. The | |
1077 | type-checker properly casts pointer values and is safe to use with | |
1078 | multiple inheritance. | |
1079 | </p> | |
1080 | ||
1081 | <p> SWIG treats private or protected inheritance as close to the C++ | |
1082 | spirit, and target language capabilities, as possible. In most of the | |
1083 | cases, this means that swig will parse the non-public inheritance | |
1084 | declarations, but that will have no effect in the generated code, | |
1085 | besides the implicit policies derived for constructor and | |
1086 | destructors. | |
1087 | </p> | |
1088 | ||
1089 | ||
1090 | <p> | |
1091 | The following example shows how SWIG handles inheritance. For clarity, | |
1092 | the full C++ code has been omitted.</p> | |
1093 | ||
1094 | <div class="code"><pre> | |
1095 | // shapes.i | |
1096 | %module shapes | |
1097 | %{ | |
1098 | #include "shapes.h" | |
1099 | %} | |
1100 | ||
1101 | class Shape { | |
1102 | public: | |
1103 | double x,y; | |
1104 | virtual double area() = 0; | |
1105 | virtual double perimeter() = 0; | |
1106 | void set_location(double x, double y); | |
1107 | }; | |
1108 | class Circle : public Shape { | |
1109 | public: | |
1110 | Circle(double radius); | |
1111 | ~Circle(); | |
1112 | double area(); | |
1113 | double perimeter(); | |
1114 | }; | |
1115 | class Square : public Shape { | |
1116 | public: | |
1117 | Square(double size); | |
1118 | ~Square(); | |
1119 | double area(); | |
1120 | double perimeter(); | |
1121 | } | |
1122 | </pre></div> | |
1123 | ||
1124 | <p> | |
1125 | When wrapped into Python, we can now perform the following operations | |
1126 | :</p> | |
1127 | ||
1128 | <div class="targetlang"><pre> | |
1129 | $ python | |
1130 | >>> import shapes | |
1131 | >>> circle = shapes.new_Circle(7) | |
1132 | >>> square = shapes.new_Square(10) | |
1133 | >>> print shapes.Circle_area(circle) | |
1134 | 153.93804004599999757 | |
1135 | >>> print shapes.Shape_area(circle) | |
1136 | 153.93804004599999757 | |
1137 | >>> print shapes.Shape_area(square) | |
1138 | 100.00000000000000000 | |
1139 | >>> shapes.Shape_set_location(square,2,-3) | |
1140 | >>> print shapes.Shape_perimeter(square) | |
1141 | 40.00000000000000000 | |
1142 | >>> | |
1143 | </pre></div> | |
1144 | ||
1145 | <p> | |
1146 | In this example, Circle and Square objects have been created. Member | |
1147 | functions can be invoked on each object by making calls to | |
1148 | <tt>Circle_area</tt>, <tt>Square_area</tt>, and so on. However, the same | |
1149 | results can be accomplished by simply using the <tt>Shape_area</tt> | |
1150 | function on either object. | |
1151 | </p> | |
1152 | ||
1153 | <p> | |
1154 | One important point concerning inheritance is that the low-level | |
1155 | accessor functions are only generated for classes in which they are | |
1156 | actually declared. For instance, in the above example, the method | |
1157 | <tt>set_location()</tt> is only accessible as | |
1158 | <tt>Shape_set_location()</tt> and not as | |
1159 | <tt>Circle_set_location()</tt> or <tt>Square_set_location()</tt>. Of | |
1160 | course, the <tt>Shape_set_location()</tt> function will accept any | |
1161 | kind of object derived from Shape. Similarly, accessor functions for | |
1162 | the attributes <tt>x</tt> and <tt>y</tt> are generated as | |
1163 | <tt>Shape_x_get()</tt>, <tt>Shape_x_set()</tt>, | |
1164 | <tt>Shape_y_get()</tt>, and <tt>Shape_y_set()</tt>. Functions such as | |
1165 | <tt>Circle_x_get()</tt> are not available--instead you should use | |
1166 | <tt>Shape_x_get()</tt>. | |
1167 | </p> | |
1168 | ||
1169 | <p> | |
1170 | Although the low-level C-like interface is functional, most language | |
1171 | modules also produce a higher level OO interface using proxy classes. | |
1172 | This approach is described later and can be used to provide a more natural C++ interface. | |
1173 | </p> | |
1174 | ||
1175 | <p> | |
1176 | <b>Note:</b> For the best results, SWIG requires all | |
1177 | base classes to be defined in an interface. Otherwise, you may get an | |
1178 | warning message like this: | |
1179 | </p> | |
1180 | ||
1181 | <div class="shell"> | |
1182 | <pre> | |
1183 | example:18. Nothing known about class 'Foo'. Ignored. | |
1184 | </pre> | |
1185 | </div> | |
1186 | ||
1187 | <p> | |
1188 | If any base class is undefined, SWIG still generates correct type | |
1189 | relationships. For instance, a function accepting a <tt>Foo *</tt> | |
1190 | will accept any object derived from <tt>Foo</tt> regardless of whether | |
1191 | or not SWIG actually wrapped the <tt>Foo</tt> class. If you really | |
1192 | don't want to generate wrappers for the base class, but you want to | |
1193 | silence the warning, you might consider using the <tt>%import</tt> | |
1194 | directive to include the file that defines <tt>Foo</tt>. | |
1195 | <tt>%import</tt> simply gathers type information, but doesn't generate | |
1196 | wrappers. Alternatively, you could just define <tt>Foo</tt> as an empty class | |
1197 | in the SWIG interface. | |
1198 | </p> | |
1199 | ||
1200 | <p> | |
1201 | <b>Note:</b> <tt>typedef</tt>-names <em>can</em> be used as base classes. For example: | |
1202 | </p> | |
1203 | ||
1204 | <div class="code"> | |
1205 | <pre> | |
1206 | class Foo { | |
1207 | ... | |
1208 | }; | |
1209 | ||
1210 | typedef Foo FooObj; | |
1211 | class Bar : public FooObj { // Ok. Base class is Foo | |
1212 | ... | |
1213 | }; | |
1214 | </pre> | |
1215 | </div> | |
1216 | ||
1217 | <p> | |
1218 | Similarly, <tt>typedef</tt> allows unnamed structures to be used as base classes. For example: | |
1219 | </p> | |
1220 | ||
1221 | <div class="code"> | |
1222 | <pre> | |
1223 | typedef struct { | |
1224 | ... | |
1225 | } Foo; | |
1226 | ||
1227 | class Bar : public Foo { // Ok. | |
1228 | ... | |
1229 | }; | |
1230 | </pre> | |
1231 | </div> | |
1232 | ||
1233 | <p> | |
1234 | <b>Compatibility Note:</b> Starting in version 1.3.7, SWIG only | |
1235 | generates low-level accessor wrappers for the declarations that are | |
1236 | actually defined in each class. This differs from SWIG1.1 which used | |
1237 | to inherit all of the declarations defined in base classes and | |
1238 | regenerate specialized accessor functions such as | |
1239 | <tt>Circle_x_get()</tt>, <tt>Square_x_get()</tt>, | |
1240 | <tt>Circle_set_location()</tt>, and <tt>Square_set_location()</tt>. | |
1241 | This behavior resulted in huge amounts of replicated code for large | |
1242 | class hierarchies and made it awkward to build applications spread | |
1243 | across multiple modules (since accessor functions are duplicated in | |
1244 | every single module). It is also unnecessary to have such wrappers | |
1245 | when advanced features like proxy classes are used. | |
1246 | ||
1247 | <b>Note:</b> Further optimizations are enabled when using the | |
1248 | <tt>-fvirtual</tt> option, which avoids the regenerating of wrapper | |
1249 | functions for virtual members that are already defined in a base | |
1250 | class. | |
1251 | </p> | |
1252 | ||
1253 | <H2><a name="SWIGPlus_nn21"></a>6.13 A brief discussion of multiple inheritance, pointers, and type checking</H2> | |
1254 | ||
1255 | ||
1256 | <p> | |
1257 | When a target scripting language refers to a C++ object, it normally | |
1258 | uses a tagged pointer object that contains both the value of the | |
1259 | pointer and a type string. For example, in Tcl, a C++ pointer might | |
1260 | be encoded as a string like this: | |
1261 | </p> | |
1262 | ||
1263 | <div class="diagram"> | |
1264 | <pre> | |
1265 | _808fea88_p_Circle | |
1266 | </pre> | |
1267 | </div> | |
1268 | ||
1269 | <p> | |
1270 | A somewhat common question is whether or not the type-tag could be safely | |
1271 | removed from the pointer. For instance, to get better performance, could you | |
1272 | strip all type tags and just use simple integers instead? | |
1273 | </p> | |
1274 | ||
1275 | <p> | |
1276 | In general, the answer to this question is no. In the wrappers, all | |
1277 | pointers are converted into a common data representation in the target | |
1278 | language. Typically this is the equivalent of casting a pointer to <tt>void *</tt>. | |
1279 | This means that any C++ type information associated with the pointer is | |
1280 | lost in the conversion. | |
1281 | </p> | |
1282 | ||
1283 | <p> | |
1284 | The problem with losing type information is that it is needed to | |
1285 | properly support many advanced C++ features--especially multiple | |
1286 | inheritance. For example, suppose you had code like this: | |
1287 | </p> | |
1288 | ||
1289 | <div class="code"> | |
1290 | <pre> | |
1291 | class A { | |
1292 | public: | |
1293 | int x; | |
1294 | }; | |
1295 | ||
1296 | class B { | |
1297 | public: | |
1298 | int y; | |
1299 | }; | |
1300 | ||
1301 | class C : public A, public B { | |
1302 | }; | |
1303 | ||
1304 | int A_function(A *a) { | |
1305 | return a->x; | |
1306 | } | |
1307 | ||
1308 | int B_function(B *b) { | |
1309 | return b->y; | |
1310 | } | |
1311 | </pre> | |
1312 | </div> | |
1313 | ||
1314 | <p> | |
1315 | Now, consider the following code that uses <tt>void *</tt>. | |
1316 | </p> | |
1317 | ||
1318 | <div class="code"> | |
1319 | <pre> | |
1320 | C *c = new C(); | |
1321 | void *p = (void *) c; | |
1322 | ... | |
1323 | int x = A_function((A *) p); | |
1324 | int y = B_function((B *) p); | |
1325 | </pre> | |
1326 | </div> | |
1327 | ||
1328 | <p> | |
1329 | In this code, both <tt>A_function()</tt> and <tt>B_function()</tt> may | |
1330 | legally accept an object of type <tt>C *</tt> (via inheritance). | |
1331 | However, one of the functions will always return the wrong result when | |
1332 | used as shown. The reason for this is that even though <tt>p</tt> | |
1333 | points to an object of type <tt>C</tt>, the casting operation doesn't | |
1334 | work like you would expect. Internally, this has to do with the data | |
1335 | representation of <tt>C</tt>. With multiple inheritance, the data from | |
1336 | each base class is stacked together. For example: | |
1337 | </p> | |
1338 | ||
1339 | <div class="diagram"> | |
1340 | <pre> | |
1341 | ------------ <--- (C *), (A *) | |
1342 | | A | | |
1343 | |------------| <--- (B *) | |
1344 | | B | | |
1345 | ------------ | |
1346 | </pre> | |
1347 | </div> | |
1348 | ||
1349 | <p> | |
1350 | Because of this stacking, a pointer of type <tt>C *</tt> may change | |
1351 | value when it is converted to a <tt>A *</tt> or <tt>B *</tt>. | |
1352 | However, this adjustment does <em>not</em> occur if you are converting from a | |
1353 | <tt>void *</tt>. | |
1354 | </p> | |
1355 | ||
1356 | <p> | |
1357 | The use of type tags marks all pointers with the real type of the | |
1358 | underlying object. This extra information is then used by SWIG | |
1359 | generated wrappers to correctly cast pointer values under inheritance | |
1360 | (avoiding the above problem). | |
1361 | </p> | |
1362 | ||
1363 | <p> | |
1364 | One might be inclined to fix this problem using some variation of | |
1365 | <tt>dynamic_cast<></tt>. The only problem is that it doesn't | |
1366 | work with <tt>void</tt> pointers, it requires RTTI support, and it | |
1367 | only works with polymorphic classes (i.e., classes that define one or | |
1368 | more virtual functions). | |
1369 | </p> | |
1370 | ||
1371 | <p> | |
1372 | The bottom line: learn to live with type-tagged pointers. | |
1373 | </p> | |
1374 | ||
1375 | <H2><a name="SWIGPlus_nn22"></a>6.14 Renaming</H2> | |
1376 | ||
1377 | ||
1378 | <p> | |
1379 | C++ member functions and data can be renamed with the <tt>%name</tt> | |
1380 | directive. The <tt>%name</tt> directive only replaces the member | |
1381 | function name. For example :</p> | |
1382 | ||
1383 | <div class="code"><pre> | |
1384 | class List { | |
1385 | public: | |
1386 | List(); | |
1387 | %name(ListSize) List(int maxsize); | |
1388 | ~List(); | |
1389 | int search(char *value); | |
1390 | %name(find) void insert(char *); | |
1391 | %name(delete) void remove(char *); | |
1392 | char *get(int n); | |
1393 | int length; | |
1394 | static void print(List *l); | |
1395 | }; | |
1396 | ||
1397 | </pre></div> | |
1398 | ||
1399 | <p> | |
1400 | This will create the functions <tt>List_find</tt>, | |
1401 | <tt>List_delete</tt>, and a function named <tt>new_ListSize</tt> for | |
1402 | the overloaded constructor.</p> | |
1403 | ||
1404 | <p> | |
1405 | The <tt>%name </tt>directive can be applied to all members including | |
1406 | constructors, destructors, static functions, data members, and | |
1407 | enumeration values.</p> | |
1408 | ||
1409 | <p> | |
1410 | The class name prefix can also be changed by specifying </p> | |
1411 | ||
1412 | <div class="code"><pre> | |
1413 | %name(newname) class List { | |
1414 | ... | |
1415 | } | |
1416 | </pre></div> | |
1417 | ||
1418 | <p> | |
1419 | Although the <tt>%name()</tt> directive can be used to help deal with | |
1420 | overloaded methods, it really doesn't work very well because it | |
1421 | requires a lot of additional markup in your interface. Keep reading | |
1422 | for a better solution. | |
1423 | </p> | |
1424 | ||
1425 | <H2><a name="SWIGPlus_overloaded_methods"></a>6.15 Wrapping Overloaded Functions and Methods</H2> | |
1426 | ||
1427 | ||
1428 | <p> | |
1429 | In many language modules, SWIG provides partial support for overloaded functions, methods, and | |
1430 | constructors. For example, if you supply SWIG with overloaded functions like this: | |
1431 | </p> | |
1432 | ||
1433 | <div class="code"> | |
1434 | <pre> | |
1435 | void foo(int x) { | |
1436 | printf("x is %d\n", x); | |
1437 | } | |
1438 | void foo(char *x) { | |
1439 | printf("x is '%s'\n", x); | |
1440 | } | |
1441 | </pre> | |
1442 | </div> | |
1443 | ||
1444 | <p> | |
1445 | The function is used in a completely natural way. For example: | |
1446 | </p> | |
1447 | ||
1448 | <div class="targetlang"> | |
1449 | <pre> | |
1450 | >>> foo(3) | |
1451 | x is 3 | |
1452 | >>> foo("hello") | |
1453 | x is 'hello' | |
1454 | >>> | |
1455 | </pre> | |
1456 | </div> | |
1457 | ||
1458 | <p> | |
1459 | Overloading works in a similar manner for methods and constructors. For example if you have | |
1460 | this code, | |
1461 | </p> | |
1462 | ||
1463 | <div class="code"> | |
1464 | <pre> | |
1465 | class Foo { | |
1466 | public: | |
1467 | Foo(); | |
1468 | Foo(const Foo &); // Copy constructor | |
1469 | void bar(int x); | |
1470 | void bar(char *s, int y); | |
1471 | }; | |
1472 | </pre> | |
1473 | </div> | |
1474 | ||
1475 | <p> | |
1476 | it might be used like this | |
1477 | </p> | |
1478 | ||
1479 | <div class="targetlang"> | |
1480 | <pre> | |
1481 | >>> f = Foo() # Create a Foo | |
1482 | >>> f.bar(3) | |
1483 | >>> g = Foo(f) # Copy Foo | |
1484 | >>> f.bar("hello",2) | |
1485 | </pre> | |
1486 | </div> | |
1487 | ||
1488 | <H3><a name="SWIGPlus_nn24"></a>6.15.1 Dispatch function generation</H3> | |
1489 | ||
1490 | ||
1491 | <p> | |
1492 | The implementation of overloaded functions and methods is somewhat | |
1493 | complicated due to the dynamic nature of scripting languages. Unlike | |
1494 | C++, which binds overloaded methods at compile time, SWIG must | |
1495 | determine the proper function as a runtime check for scripting language targets. This check is | |
1496 | further complicated by the typeless nature of certain scripting languages. For instance, | |
1497 | in Tcl, all types are simply strings. Therefore, if you have two overloaded functions | |
1498 | like this, | |
1499 | </p> | |
1500 | ||
1501 | <div class="code"> | |
1502 | <pre> | |
1503 | void foo(char *x); | |
1504 | void foo(int x); | |
1505 | </pre> | |
1506 | </div> | |
1507 | ||
1508 | <p> | |
1509 | the order in which the arguments are checked plays a rather critical role. | |
1510 | </p> | |
1511 | ||
1512 | <p> | |
1513 | For statically typed languages, SWIG uses the language's method overloading mechanism. | |
1514 | To implement overloading for the scripting languages, SWIG generates a dispatch function that checks the | |
1515 | number of passed arguments and their types. To create this function, SWIG | |
1516 | first examines all of the overloaded methods and ranks them according | |
1517 | to the following rules: | |
1518 | </p> | |
1519 | ||
1520 | <ol> | |
1521 | <li><b>Number of required arguments.</b> Methods are sorted by increasing number of | |
1522 | required arguments. | |
1523 | </li> | |
1524 | <li><p><b>Argument type precedence.</b> All C++ datatypes are assigned a numeric type precedence value | |
1525 | (which is determined by the language module).</p> | |
1526 | ||
1527 | <div class="diagram"> | |
1528 | <pre> | |
1529 | Type Precedence | |
1530 | ---------------- ---------- | |
1531 | TYPE * 0 (High) | |
1532 | void * 20 | |
1533 | Integers 40 | |
1534 | Floating point 60 | |
1535 | char 80 | |
1536 | Strings 100 (Low) | |
1537 | </pre> | |
1538 | </div> | |
1539 | ||
1540 | <p> | |
1541 | Using these precedence values, overloaded methods with the same number of required arguments are sorted in increased | |
1542 | order of precedence values. | |
1543 | </p> | |
1544 | </li> | |
1545 | </ol> | |
1546 | ||
1547 | <p> | |
1548 | This may sound very confusing, but an example will help. Consider the following collection of | |
1549 | overloaded methods: | |
1550 | </p> | |
1551 | ||
1552 | <div class="code"> | |
1553 | <pre> | |
1554 | void foo(double); | |
1555 | void foo(int); | |
1556 | void foo(Bar *); | |
1557 | void foo(); | |
1558 | void foo(int x, int y, int z, int w); | |
1559 | void foo(int x, int y, int z = 3); | |
1560 | void foo(double x, double y); | |
1561 | void foo(double x, Bar *z); | |
1562 | </pre> | |
1563 | </div> | |
1564 | ||
1565 | <p> | |
1566 | The first rule simply ranks the functions by required argument count. | |
1567 | This would produce the following list: | |
1568 | </p> | |
1569 | ||
1570 | <div class="diagram"> | |
1571 | <pre> | |
1572 | rank | |
1573 | ----- | |
1574 | [0] foo() | |
1575 | [1] foo(double); | |
1576 | [2] foo(int); | |
1577 | [3] foo(Bar *); | |
1578 | [4] foo(int x, int y, int z = 3); | |
1579 | [5] foo(double x, double y) | |
1580 | [6] foo(double x, Bar *z) | |
1581 | [7] foo(int x, int y, int z, int w); | |
1582 | </pre> | |
1583 | </div> | |
1584 | ||
1585 | <p> | |
1586 | The second rule, simply refines the ranking by looking at argument type precedence values. | |
1587 | </p> | |
1588 | ||
1589 | <div class="diagram"> | |
1590 | <pre> | |
1591 | rank | |
1592 | ----- | |
1593 | [0] foo() | |
1594 | [1] foo(Bar *); | |
1595 | [2] foo(int); | |
1596 | [3] foo(double); | |
1597 | [4] foo(int x, int y, int z = 3); | |
1598 | [5] foo(double x, Bar *z) | |
1599 | [6] foo(double x, double y) | |
1600 | [7] foo(int x, int y, int z, int w); | |
1601 | </pre> | |
1602 | </div> | |
1603 | ||
1604 | <p> | |
1605 | Finally, to generate the dispatch function, the arguments passed to an overloaded method are simply | |
1606 | checked in the same order as they appear in this ranking. | |
1607 | </p> | |
1608 | ||
1609 | <p> | |
1610 | If you're still confused, don't worry about it---SWIG is probably doing the right thing. | |
1611 | </p> | |
1612 | ||
1613 | <H3><a name="SWIGPlus_nn25"></a>6.15.2 Ambiguity in Overloading</H3> | |
1614 | ||
1615 | ||
1616 | <p> | |
1617 | Regrettably, SWIG is not able to support every possible use of valid C++ overloading. Consider | |
1618 | the following example: | |
1619 | </p> | |
1620 | ||
1621 | <div class="code"> | |
1622 | <pre> | |
1623 | void foo(int x); | |
1624 | void foo(long x); | |
1625 | </pre> | |
1626 | </div> | |
1627 | ||
1628 | <p> | |
1629 | In C++, this is perfectly legal. However, in a scripting language, there is generally only one kind of integer | |
1630 | object. Therefore, which one of these functions do you pick? Clearly, there is no way to truly make a distinction | |
1631 | just by looking at the value of the integer itself (<tt>int</tt> and <tt>long</tt> may even be the same precision). | |
1632 | Therefore, when SWIG encounters this situation, it may generate a warning message like this for scripting languages: | |
1633 | </p> | |
1634 | ||
1635 | <div class="shell"> | |
1636 | <pre> | |
1637 | example.i:4: Warning(509): Overloaded foo(long) is shadowed by foo(int) at example.i:3. | |
1638 | </pre> | |
1639 | </div> | |
1640 | ||
1641 | <p> | |
1642 | or for statically typed languages like Java: | |
1643 | </p> | |
1644 | ||
1645 | <div class="shell"> | |
1646 | <pre> | |
1647 | example.i:4: Warning(516): Overloaded method foo(long) ignored. Method foo(int) | |
1648 | at example.i:3 used. | |
1649 | </pre> | |
1650 | </div> | |
1651 | ||
1652 | <p> | |
1653 | This means that the second overloaded function will be inaccessible | |
1654 | from a scripting interface or the method won't be wrapped at all. | |
1655 | This is done as SWIG does not know how to disambiguate it from an earlier method. | |
1656 | </p> | |
1657 | ||
1658 | <p> | |
1659 | Ambiguity problems are known to arise in the following situations: | |
1660 | </p> | |
1661 | ||
1662 | <ul> | |
1663 | <li>Integer conversions. Datatypes such as <tt>int</tt>, <tt>long</tt>, and <tt>short</tt> cannot be disambiguated in some languages. Shown above. | |
1664 | </li> | |
1665 | ||
1666 | <li>Floating point conversion. <tt>float</tt> and <tt>double</tt> can not be disambiguated in some languages. | |
1667 | </li> | |
1668 | ||
1669 | <li>Pointers and references. For example, <tt>Foo *</tt> and <tt>Foo &</tt>. | |
1670 | </li> | |
1671 | ||
1672 | <li>Pointers and arrays. For example, <tt>Foo *</tt> and <tt>Foo [4]</tt>. | |
1673 | </li> | |
1674 | ||
1675 | <li>Pointers and instances. For example, <tt>Foo</tt> and <tt>Foo *</tt>. Note: SWIG converts all | |
1676 | instances to pointers. | |
1677 | </li> | |
1678 | ||
1679 | <li>Qualifiers. For example, <tt>const Foo *</tt> and <tt>Foo *</tt>. | |
1680 | </li> | |
1681 | ||
1682 | <li>Default vs. non default arguments. For example, <tt>foo(int a, int b)</tt> and <tt>foo(int a, int b = 3)</tt>. | |
1683 | </li> | |
1684 | </ul> | |
1685 | ||
1686 | <p> | |
1687 | When an ambiguity arises, methods are checked in the same order as they appear in the interface file. | |
1688 | Therefore, earlier methods will shadow methods that appear later. | |
1689 | </p> | |
1690 | ||
1691 | <p> | |
1692 | When wrapping an overloaded function, there is a chance that you will get an error message like this: | |
1693 | </p> | |
1694 | ||
1695 | <div class="shell"> | |
1696 | <pre> | |
1697 | example.i:3: Warning(467): Overloaded foo(int) not supported (no type checking | |
1698 | rule for 'int'). | |
1699 | </pre> | |
1700 | </div> | |
1701 | ||
1702 | <p> | |
1703 | This error means that the target language module supports overloading, | |
1704 | but for some reason there is no type-checking rule that can be used to | |
1705 | generate a working dispatch function. The resulting behavior is then | |
1706 | undefined. You should report this as a bug to the | |
1707 | <a href="http://www.swig.org/bugs.html">SWIG bug tracking database</a>. | |
1708 | </p> | |
1709 | ||
1710 | <p> | |
1711 | If you get an error message such as the following, | |
1712 | </p> | |
1713 | ||
1714 | <div class="shell"> | |
1715 | <pre> | |
1716 | foo.i:6. Overloaded declaration ignored. Spam::foo(double ) | |
1717 | foo.i:5. Previous declaration is Spam::foo(int ) | |
1718 | foo.i:7. Overloaded declaration ignored. Spam::foo(Bar *,Spam *,int ) | |
1719 | foo.i:5. Previous declaration is Spam::foo(int ) | |
1720 | </pre> | |
1721 | </div> | |
1722 | ||
1723 | <p> | |
1724 | it means that the target language module has not yet implemented support for overloaded | |
1725 | functions and methods. The only way to fix the problem is to read the next section. | |
1726 | </p> | |
1727 | ||
1728 | <H3><a name="ambiguity_resolution_renaming"></a>6.15.3 Ambiguity resolution and renaming</H3> | |
1729 | ||
1730 | ||
1731 | <p> | |
1732 | If an ambiguity in overload resolution occurs or if a module doesn't | |
1733 | allow overloading, there are a few strategies for dealing with the | |
1734 | problem. First, you can tell SWIG to ignore one of the methods. This | |
1735 | is easy---simply use the <tt>%ignore</tt> directive. For example: | |
1736 | </p> | |
1737 | ||
1738 | <div class="code"> | |
1739 | <pre> | |
1740 | %ignore foo(long); | |
1741 | ||
1742 | void foo(int); | |
1743 | void foo(long); // Ignored. Oh well. | |
1744 | </pre> | |
1745 | </div> | |
1746 | ||
1747 | <p> | |
1748 | The other alternative is to rename one of the methods. This can be | |
1749 | done using <tt>%rename</tt>. For example: | |
1750 | </p> | |
1751 | ||
1752 | <div class="code"> | |
1753 | <pre> | |
1754 | %rename(foo_long) foo(long); | |
1755 | ||
1756 | void foo(int); | |
1757 | void foo(long); // Accessed as foo_long() | |
1758 | </pre> | |
1759 | </div> | |
1760 | ||
1761 | <p> | |
1762 | The <tt>%ignore</tt> and <tt>%rename</tt> directives are both rather powerful | |
1763 | in their ability to match declarations. When used in their simple form, they apply to | |
1764 | both global functions and methods. For example: | |
1765 | </p> | |
1766 | ||
1767 | <div class="code"> | |
1768 | <pre> | |
1769 | /* Forward renaming declarations */ | |
1770 | %rename(foo_i) foo(int); | |
1771 | %rename(foo_d) foo(double); | |
1772 | ... | |
1773 | void foo(int); // Becomes 'foo_i' | |
1774 | void foo(char *c); // Stays 'foo' (not renamed) | |
1775 | ||
1776 | class Spam { | |
1777 | public: | |
1778 | void foo(int); // Becomes 'foo_i' | |
1779 | void foo(double); // Becomes 'foo_d' | |
1780 | ... | |
1781 | }; | |
1782 | </pre> | |
1783 | </div> | |
1784 | ||
1785 | <p> | |
1786 | If you only want the renaming to apply to a certain scope, the C++ scope resolution operator (::) can be used. | |
1787 | For example: | |
1788 | </p> | |
1789 | ||
1790 | <div class="code"> | |
1791 | <pre> | |
1792 | %rename(foo_i) ::foo(int); // Only rename foo(int) in the global scope. | |
1793 | // (will not rename class members) | |
1794 | ||
1795 | %rename(foo_i) Spam::foo(int); // Only rename foo(int) in class Spam | |
1796 | </pre> | |
1797 | </div> | |
1798 | ||
1799 | <p> | |
1800 | When a renaming operator is applied to a class as in <tt>Spam::foo(int)</tt>, it is applied to | |
1801 | that class and all derived classes. This can be used to apply a consistent renaming across | |
1802 | an entire class hierarchy with only a few declarations. For example: | |
1803 | </p> | |
1804 | ||
1805 | <div class="code"> | |
1806 | <pre> | |
1807 | %rename(foo_i) Spam::foo(int); | |
1808 | %rename(foo_d) Spam::foo(double); | |
1809 | ||
1810 | class Spam { | |
1811 | public: | |
1812 | virtual void foo(int); // Renamed to foo_i | |
1813 | virtual void foo(double); // Renamed to foo_d | |
1814 | ... | |
1815 | }; | |
1816 | ||
1817 | class Bar : public Spam { | |
1818 | public: | |
1819 | virtual void foo(int); // Renamed to foo_i | |
1820 | virtual void foo(double); // Renamed to foo_d | |
1821 | ... | |
1822 | }; | |
1823 | ||
1824 | class Grok : public Bar { | |
1825 | public: | |
1826 | virtual void foo(int); // Renamed to foo_i | |
1827 | virtual void foo(double); // Renamed to foo_d | |
1828 | ... | |
1829 | }; | |
1830 | </pre> | |
1831 | </div> | |
1832 | ||
1833 | <p> | |
1834 | It is also possible to include <tt>%rename</tt> specifications in the | |
1835 | class definition itself. For example: | |
1836 | </p> | |
1837 | ||
1838 | <div class="code"> | |
1839 | <pre> | |
1840 | class Spam { | |
1841 | %rename(foo_i) foo(int); | |
1842 | %rename(foo_d) foo(double); | |
1843 | public: | |
1844 | virtual void foo(int); // Renamed to foo_i | |
1845 | virtual void foo(double); // Renamed to foo_d | |
1846 | ... | |
1847 | }; | |
1848 | ||
1849 | class Bar : public Spam { | |
1850 | public: | |
1851 | virtual void foo(int); // Renamed to foo_i | |
1852 | virtual void foo(double); // Renamed to foo_d | |
1853 | ... | |
1854 | }; | |
1855 | </pre> | |
1856 | </div> | |
1857 | ||
1858 | <p> | |
1859 | In this case, the <tt>%rename</tt> directives still get applied across the entire | |
1860 | inheritance hierarchy, but it's no longer necessary to explicitly specify the | |
1861 | class prefix <tt>Spam::</tt>. | |
1862 | </p> | |
1863 | ||
1864 | <p> | |
1865 | A special form of <tt>%rename</tt> can be used to apply a renaming just to class | |
1866 | members (of all classes): | |
1867 | </p> | |
1868 | ||
1869 | <div class="code"> | |
1870 | <pre> | |
1871 | %rename(foo_i) *::foo(int); // Only rename foo(int) if it appears in a class. | |
1872 | </pre> | |
1873 | </div> | |
1874 | ||
1875 | <p> | |
1876 | Note: the <tt>*::</tt> syntax is non-standard C++, but the '*' is meant to be a | |
1877 | wildcard that matches any class name (we couldn't think of a better | |
1878 | alternative so if you have a better idea, send email to | |
1879 | the <a href="http://www.swig.org/mail.html">swig-dev mailing list</a>. | |
1880 | </p> | |
1881 | ||
1882 | <p> | |
1883 | Although this discussion has primarily focused on <tt>%rename</tt> all of the same rules | |
1884 | also apply to <tt>%ignore</tt>. For example: | |
1885 | </p> | |
1886 | ||
1887 | <div class="code"> | |
1888 | <pre> | |
1889 | %ignore foo(double); // Ignore all foo(double) | |
1890 | %ignore Spam::foo; // Ignore foo in class Spam | |
1891 | %ignore Spam::foo(double); // Ignore foo(double) in class Spam | |
1892 | %ignore *::foo(double); // Ignore foo(double) in all classes | |
1893 | </pre> | |
1894 | </div> | |
1895 | ||
1896 | <p> | |
1897 | When applied to a base class, <tt>%ignore</tt> forces all definitions in derived clases | |
1898 | to disappear. For example, <tt>%ignore Spam::foo(double)</tt> will eliminate <tt>foo(double)</tt> in | |
1899 | <tt>Spam</tt> and all classes derived from <tt>Spam</tt>. | |
1900 | </p> | |
1901 | ||
1902 | <p> | |
1903 | <b>Notes on %rename and %ignore:</b> | |
1904 | </p> | |
1905 | ||
1906 | <ul> | |
1907 | <li><p>Since, the <tt>%rename</tt> declaration is used to declare a renaming in advance, it can be | |
1908 | placed at the start of an interface file. This makes it possible to apply a consistent name | |
1909 | resolution without having to modify header files. For example:</p> | |
1910 | ||
1911 | <div class="code"> | |
1912 | <pre> | |
1913 | %module foo | |
1914 | ||
1915 | /* Rename these overloaded functions */ | |
1916 | %rename(foo_i) foo(int); | |
1917 | %rename(foo_d) foo(double); | |
1918 | ||
1919 | %include "header.h" | |
1920 | </pre> | |
1921 | </div> | |
1922 | </li> | |
1923 | ||
1924 | <li><p>The scope qualifier (::) can also be used on simple names. For example:</p> | |
1925 | <div class="code"> | |
1926 | <pre> | |
1927 | %rename(bar) ::foo; // Rename foo to bar in global scope only | |
1928 | %rename(bar) Spam::foo; // Rename foo to bar in class Spam only | |
1929 | %rename(bar) *::foo; // Rename foo in classes only | |
1930 | </pre> | |
1931 | </div> | |
1932 | </li> | |
1933 | ||
1934 | <li><p>Name matching tries to find the most specific match that is | |
1935 | defined. A qualified name such as <tt>Spam::foo</tt> always has | |
1936 | higher precedence than an unqualified name <tt>foo</tt>. | |
1937 | <tt>Spam::foo</tt> has higher precedence than <tt>*::foo</tt> and | |
1938 | <tt>*::foo</tt> has higher precedence than <tt>foo</tt>. A | |
1939 | parameterized name has higher precedence than an unparameterized name | |
1940 | within the same scope level. However, an unparameterized name with a | |
1941 | scope qualifier has higher precedence than a parameterized name in | |
1942 | global scope (e.g., a renaming of <tt>Spam::foo</tt> takes precedence | |
1943 | over a renaming of <tt>foo(int)</tt>).</p> | |
1944 | </li> | |
1945 | ||
1946 | <li><p> | |
1947 | The order in which <tt>%rename</tt> directives are defined does not matter | |
1948 | as long as they appear before the declarations to be renamed. Thus, there is no difference | |
1949 | between saying:</p> | |
1950 | ||
1951 | <div class="code"> | |
1952 | <pre> | |
1953 | %rename(bar) foo; | |
1954 | %rename(foo_i) Spam::foo(int); | |
1955 | %rename(Foo) Spam::foo; | |
1956 | </pre> | |
1957 | </div> | |
1958 | ||
1959 | <p> | |
1960 | and this | |
1961 | </p> | |
1962 | ||
1963 | <div class="code"> | |
1964 | <pre> | |
1965 | %rename(Foo) Spam::foo; | |
1966 | %rename(bar) foo; | |
1967 | %rename(foo_i) Spam::foo(int); | |
1968 | </pre> | |
1969 | </div> | |
1970 | ||
1971 | <p> | |
1972 | (the declarations are not stored in a linked list and order has no | |
1973 | importance). Of course, a repeated <tt>%rename</tt> directive will | |
1974 | change the setting for a previous <tt>%rename</tt> directive if exactly the | |
1975 | same name, scope, and parameters are supplied. | |
1976 | </p> | |
1977 | </li> | |
1978 | ||
1979 | <li>For multiple inheritance where renaming rules are defined for multiple base classes, | |
1980 | the first renaming rule found on a depth-first traversal of the class hierarchy | |
1981 | is used. | |
1982 | </li> | |
1983 | ||
1984 | <li><p>The name matching rules strictly follow member qualification rules. | |
1985 | For example, if you have a class like this:</p> | |
1986 | ||
1987 | <div class="code"> | |
1988 | <pre> | |
1989 | class Spam { | |
1990 | public: | |
1991 | ... | |
1992 | void bar() const; | |
1993 | ... | |
1994 | }; | |
1995 | </pre> | |
1996 | </div> | |
1997 | ||
1998 | <p> | |
1999 | the declaration | |
2000 | </p> | |
2001 | ||
2002 | <div class="code"> | |
2003 | <pre> | |
2004 | %rename(name) Spam::bar(); | |
2005 | </pre> | |
2006 | </div> | |
2007 | ||
2008 | <p> | |
2009 | will not apply as there is no unqualified member <tt>bar()</tt>. The following will apply as | |
2010 | the qualifier matches correctly: | |
2011 | </p> | |
2012 | ||
2013 | <div class="code"> | |
2014 | <pre> | |
2015 | %rename(name) Spam::bar() const; | |
2016 | </pre> | |
2017 | </div> | |
2018 | ||
2019 | <p> | |
2020 | An often overlooked C++ feature is that classes can define two different overloaded members | |
2021 | that differ only in their qualifiers, like this: | |
2022 | </p> | |
2023 | ||
2024 | <div class="code"> | |
2025 | <pre> | |
2026 | class Spam { | |
2027 | public: | |
2028 | ... | |
2029 | void bar(); // Unqualified member | |
2030 | void bar() const; // Qualified member | |
2031 | ... | |
2032 | }; | |
2033 | </pre> | |
2034 | </div> | |
2035 | ||
2036 | <p> | |
2037 | %rename can then be used to target each of the overloaded methods individually. | |
2038 | For example we can give them separate names in the target language: | |
2039 | </p> | |
2040 | ||
2041 | <div class="code"> | |
2042 | <pre> | |
2043 | %rename(name1) Spam::bar(); | |
2044 | %rename(name2) Spam::bar() const; | |
2045 | </pre> | |
2046 | </div> | |
2047 | ||
2048 | <p> | |
2049 | Similarly, if you | |
2050 | merely wanted to ignore one of the declarations, use <tt>%ignore</tt> | |
2051 | with the full qualification. For example, the following directive | |
2052 | would tell SWIG to ignore the <tt>const</tt> version of <tt>bar()</tt> | |
2053 | above: | |
2054 | </p> | |
2055 | ||
2056 | <div class="code"> | |
2057 | <pre> | |
2058 | %ignore Spam::bar() const; // Ignore bar() const, but leave other bar() alone | |
2059 | </pre> | |
2060 | </div> | |
2061 | ||
2062 | </li> | |
2063 | ||
2064 | <li><p> | |
2065 | The name matching rules also use default arguments for finer control when wrapping methods that have default arguments. | |
2066 | Recall that methods with default arguments are wrapped as if the equivalent overloaded methods had been parsed | |
2067 | (<a href="#SWIGPlus_default_args">Default arguments</a> section). | |
2068 | Let's consider the following example class:</p> | |
2069 | ||
2070 | <div class="code"> | |
2071 | <pre> | |
2072 | class Spam { | |
2073 | public: | |
2074 | ... | |
2075 | void bar(int i=-1, double d=0.0); | |
2076 | ... | |
2077 | }; | |
2078 | </pre> | |
2079 | </div> | |
2080 | ||
2081 | <p> | |
2082 | The following <tt>%rename</tt> will match exactly and apply to all the target language overloaded methods because the declaration with the default arguments | |
2083 | exactly matches the wrapped method: | |
2084 | </p> | |
2085 | ||
2086 | <div class="code"> | |
2087 | <pre> | |
2088 | %rename(newbar) Spam::bar(int i=-1, double d=0.0); | |
2089 | </pre> | |
2090 | </div> | |
2091 | ||
2092 | <p> | |
2093 | The C++ method can then be called from the target language with the new name no matter how many arguments are specified, for example: | |
2094 | <tt>newbar(2, 2.0)</tt>, <tt>newbar(2)</tt> or <tt>newbar()</tt>. | |
2095 | However, if the <tt>%rename</tt> does not contain the default arguments, it will only apply to the single equivalent target language overloaded method. | |
2096 | So if instead we have: | |
2097 | </p> | |
2098 | ||
2099 | <div class="code"> | |
2100 | <pre> | |
2101 | %rename(newbar) Spam::bar(int i, double d); | |
2102 | </pre> | |
2103 | </div> | |
2104 | ||
2105 | <p> | |
2106 | The C++ method must then be called from the target language with the new name <tt>newbar(2, 2.0)</tt> when both arguments are supplied | |
2107 | or with the original name as <tt>bar(2)</tt> (one argument) or <tt>bar()</tt> (no arguments). | |
2108 | In fact it is possible to use <tt>%rename</tt> on the equivalent overloaded methods, to rename all the equivalent overloaded methods: | |
2109 | </p> | |
2110 | ||
2111 | <div class="code"> | |
2112 | <pre> | |
2113 | %rename(bar_2args) Spam::bar(int i, double d); | |
2114 | %rename(bar_1arg) Spam::bar(int i); | |
2115 | %rename(bar_default) Spam::bar(); | |
2116 | </pre> | |
2117 | </div> | |
2118 | ||
2119 | <p> | |
2120 | Similarly, the extra overloaded methods can be selectively ignored using <tt>%ignore</tt>. | |
2121 | </p> | |
2122 | ||
2123 | <p> | |
2124 | <b>Compatibility note:</b> The <tt>%rename</tt> directive introduced the default argument matching rules in SWIG-1.3.23 at the same time as the changes | |
2125 | to wrapping methods with default arguments was introduced. | |
2126 | </p> | |
2127 | ||
2128 | </li> | |
2129 | ||
2130 | </ul> | |
2131 | ||
2132 | <H3><a name="SWIGPlus_nn27"></a>6.15.4 Comments on overloading</H3> | |
2133 | ||
2134 | ||
2135 | <p> | |
2136 | Support for overloaded methods was first added in SWIG-1.3.14. The implementation | |
2137 | is somewhat unusual when compared to similar tools. For instance, the order in which | |
2138 | declarations appear is largely irrelevant in SWIG. Furthermore, SWIG does not rely | |
2139 | upon trial execution or exception handling to figure out which method to invoke. | |
2140 | </p> | |
2141 | ||
2142 | <p> | |
2143 | Internally, the overloading mechanism is completely configurable by the target language | |
2144 | module. Therefore, the degree of overloading support may vary from language to language. | |
2145 | As a general rule, statically typed languages like Java are able to provide more support | |
2146 | than dynamically typed languages like Perl, Python, Ruby, and Tcl. | |
2147 | </p> | |
2148 | ||
2149 | <H2><a name="SWIGPlus_nn28"></a>6.16 Wrapping overloaded operators</H2> | |
2150 | ||
2151 | ||
2152 | <p> | |
2153 | Starting in SWIG-1.3.10, C++ overloaded operator declarations can be wrapped. | |
2154 | For example, consider a class like this: | |
2155 | </p> | |
2156 | ||
2157 | <div class="code"> | |
2158 | <pre> | |
2159 | class Complex { | |
2160 | private: | |
2161 | double rpart, ipart; | |
2162 | public: | |
2163 | Complex(double r = 0, double i = 0) : rpart(r), ipart(i) { } | |
2164 | Complex(const Complex &c) : rpart(c.rpart), ipart(c.ipart) { } | |
2165 | Complex &operator=(const Complex &c) { | |
2166 | rpart = c.rpart; | |
2167 | ipart = c.ipart; | |
2168 | return *this; | |
2169 | } | |
2170 | Complex operator+(const Complex &c) const { | |
2171 | return Complex(rpart+c.rpart, ipart+c.ipart); | |
2172 | } | |
2173 | Complex operator-(const Complex &c) const { | |
2174 | return Complex(rpart-c.rpart, ipart-c.ipart); | |
2175 | } | |
2176 | Complex operator*(const Complex &c) const { | |
2177 | return Complex(rpart*c.rpart - ipart*c.ipart, | |
2178 | rpart*c.ipart + c.rpart*ipart); | |
2179 | } | |
2180 | Complex operator-() const { | |
2181 | return Complex(-rpart, -ipart); | |
2182 | } | |
2183 | double re() const { return rpart; } | |
2184 | double im() const { return ipart; } | |
2185 | }; | |
2186 | </pre> | |
2187 | </div> | |
2188 | ||
2189 | <p> | |
2190 | When operator declarations appear, they are handled in | |
2191 | <em>exactly</em> the same manner as regular methods. However, the | |
2192 | names of these methods are set to strings like "<tt>operator +</tt>" | |
2193 | or "<tt>operator -</tt>". The problem with these names is that they | |
2194 | are illegal identifiers in most scripting languages. For instance, | |
2195 | you can't just create a method called "<tt>operator +</tt>" in | |
2196 | Python--there won't be any way to call it. | |
2197 | </p> | |
2198 | ||
2199 | <p> | |
2200 | Some language modules already know how to automatically handle certain | |
2201 | operators (mapping them into operators in the target language). | |
2202 | However, the underlying implementation of this is really managed in a | |
2203 | very general way using the <tt>%rename</tt> directive. For example, | |
2204 | in Python a declaration similar to this is used: | |
2205 | </p> | |
2206 | ||
2207 | <div class="code"> | |
2208 | <pre> | |
2209 | %rename(__add__) Complex::operator+; | |
2210 | </pre> | |
2211 | </div> | |
2212 | ||
2213 | <p> | |
2214 | This binds the + operator to a method called <tt>__add__</tt> (which | |
2215 | is conveniently the same name used to implement the Python + operator). | |
2216 | Internally, the generated wrapper code for a wrapped operator will look | |
2217 | something like this pseudocode: | |
2218 | </p> | |
2219 | ||
2220 | <div class="code"> | |
2221 | <pre> | |
2222 | _wrap_Complex___add__(args) { | |
2223 | ... get args ... | |
2224 | obj->operator+(args); | |
2225 | ... | |
2226 | } | |
2227 | </pre> | |
2228 | </div> | |
2229 | ||
2230 | <p> | |
2231 | When used in the target language, it may now be possible to use the overloaded | |
2232 | operator normally. For example: | |
2233 | </p> | |
2234 | ||
2235 | <div class="targetlang"> | |
2236 | <pre> | |
2237 | >>> a = Complex(3,4) | |
2238 | >>> b = Complex(5,2) | |
2239 | >>> c = a + b # Invokes __add__ method | |
2240 | </pre> | |
2241 | </div> | |
2242 | ||
2243 | <p> | |
2244 | It is important to realize that there is nothing magical happening | |
2245 | here. The <tt>%rename</tt> directive really only picks a valid method | |
2246 | name. If you wrote this: | |
2247 | </p> | |
2248 | ||
2249 | <div class="code"> | |
2250 | <pre> | |
2251 | %rename(add) operator+; | |
2252 | </pre> | |
2253 | </div> | |
2254 | ||
2255 | <p> | |
2256 | The resulting scripting interface might work like this: | |
2257 | </p> | |
2258 | ||
2259 | <div class="targetlang"> | |
2260 | <pre> | |
2261 | a = Complex(3,4) | |
2262 | b = Complex(5,2) | |
2263 | c = a.add(b) # Call a.operator+(b) | |
2264 | </pre> | |
2265 | </div> | |
2266 | ||
2267 | <p> | |
2268 | All of the techniques described to deal with overloaded functions also | |
2269 | apply to operators. For example: | |
2270 | </p> | |
2271 | ||
2272 | <div class="code"> | |
2273 | <pre> | |
2274 | %ignore Complex::operator=; // Ignore = in class Complex | |
2275 | %ignore *::operator=; // Ignore = in all classes | |
2276 | %ignore operator=; // Ignore = everywhere. | |
2277 | ||
2278 | %rename(__sub__) Complex::operator-; | |
2279 | %rename(__neg__) Complex::operator-(); // Unary - | |
2280 | </pre> | |
2281 | </div> | |
2282 | ||
2283 | <p> | |
2284 | The last part of this example illustrates how multiple definitions of | |
2285 | the <tt>operator-</tt> method might be handled. | |
2286 | </p> | |
2287 | ||
2288 | <p> | |
2289 | Handling operators in this manner is mostly straightforward. However, there are a few subtle | |
2290 | issues to keep in mind: | |
2291 | </p> | |
2292 | ||
2293 | <ul> | |
2294 | <li><p>In C++, it is fairly common to define different versions of the operators to account for | |
2295 | different types. For example, a class might also include a friend function like this:</p> | |
2296 | ||
2297 | <div class="code"> | |
2298 | <pre> | |
2299 | class Complex { | |
2300 | public: | |
2301 | friend Complex operator+(Complex &, double); | |
2302 | }; | |
2303 | Complex operator+(Complex &, double); | |
2304 | </pre> | |
2305 | </div> | |
2306 | ||
2307 | <p> | |
2308 | SWIG simply ignores all <tt>friend</tt> declarations. Furthermore, it | |
2309 | doesn't know how to associate the associated <tt>operator+</tt> with | |
2310 | the class (because it's not a member of the class). | |
2311 | </p> | |
2312 | ||
2313 | <p> | |
2314 | It's still possible to make a wrapper for this operator, but you'll | |
2315 | have to handle it like a normal function. For example: | |
2316 | </p> | |
2317 | ||
2318 | <div class="code"> | |
2319 | <pre> | |
2320 | %rename(add_complex_double) operator+(Complex &, double); | |
2321 | </pre> | |
2322 | </div> | |
2323 | </li> | |
2324 | ||
2325 | <li><p>Certain operators are ignored by default. For instance, <tt>new</tt> and <tt>delete</tt> operators | |
2326 | are ignored as well as conversion operators. | |
2327 | </p></li> | |
2328 | ||
2329 | <li>The semantics of certain C++ operators may not match those in the target language. | |
2330 | </li> | |
2331 | </ul> | |
2332 | ||
2333 | <H2><a name="SWIGPlus_nn29"></a>6.17 Class extension</H2> | |
2334 | ||
2335 | ||
2336 | <p> | |
2337 | New methods can be added to a class using the <tt>%extend</tt> | |
2338 | directive. This directive is primarily used in conjunction with proxy | |
2339 | classes to add additional functionality to an existing class. For | |
2340 | example : | |
2341 | </p> | |
2342 | ||
2343 | <div class="code"><pre> | |
2344 | %module vector | |
2345 | %{ | |
2346 | #include "vector.h" | |
2347 | %} | |
2348 | ||
2349 | class Vector { | |
2350 | public: | |
2351 | double x,y,z; | |
2352 | Vector(); | |
2353 | ~Vector(); | |
2354 | ... bunch of C++ methods ... | |
2355 | %extend { | |
2356 | char *__str__() { | |
2357 | static char temp[256]; | |
2358 | sprintf(temp,"[ %g, %g, %g ]", self->x,self->y,self->z); | |
2359 | return &temp[0]; | |
2360 | } | |
2361 | } | |
2362 | }; | |
2363 | </pre></div> | |
2364 | ||
2365 | <p> | |
2366 | This code adds a<tt> __str__</tt> method to our class for producing a | |
2367 | string representation of the object. In Python, such a method would | |
2368 | allow us to print the value of an object using the <tt>print</tt> | |
2369 | command. | |
2370 | </p> | |
2371 | ||
2372 | <div class="targetlang"><pre> | |
2373 | >>> | |
2374 | >>> v = Vector(); | |
2375 | >>> v.x = 3 | |
2376 | >>> v.y = 4 | |
2377 | >>> v.z = 0 | |
2378 | >>> print(v) | |
2379 | [ 3.0, 4.0, 0.0 ] | |
2380 | >>> | |
2381 | ||
2382 | </pre></div> | |
2383 | ||
2384 | <p> | |
2385 | The<tt> %extend</tt> directive follows all of the same conventions | |
2386 | as its use with C structures. Please refer to the <a href="SWIG.html#SWIG">SWIG Basics</a> | |
2387 | chapter for further details. | |
2388 | </p> | |
2389 | ||
2390 | <p> | |
2391 | <b>Compatibility note:</b> The <tt>%extend</tt> directive is a new | |
2392 | name for the <tt>%addmethods</tt> directive. Since <tt>%addmethods</tt> could | |
2393 | be used to extend a structure with more than just methods, a more suitable | |
2394 | directive name has been chosen. | |
2395 | </p> | |
2396 | ||
2397 | <H2><a name="SWIGPlus_nn30"></a>6.18 Templates</H2> | |
2398 | ||
2399 | ||
2400 | <p> | |
2401 | In all versions of SWIG, template type names may appear anywhere a type | |
2402 | is expected in an interface file. For example: | |
2403 | </p> | |
2404 | ||
2405 | <div class="code"> | |
2406 | <pre> | |
2407 | void foo(vector<int> *a, int n); | |
2408 | void bar(list<int,100> *x); | |
2409 | </pre> | |
2410 | </div> | |
2411 | ||
2412 | <p> | |
2413 | There are some restrictions on the use of non-type arguments. Specifically, | |
2414 | they have to be simple literals and not expressions. For example: | |
2415 | </p> | |
2416 | ||
2417 | <div class="code"> | |
2418 | <pre> | |
2419 | void bar(list<int,100> *x); // OK | |
2420 | void bar(list<int,2*50> *x); // Illegal | |
2421 | </pre> | |
2422 | </div> | |
2423 | ||
2424 | <p> | |
2425 | The type system is smart enough to figure out clever games | |
2426 | you might try to play with <tt>typedef</tt>. For instance, consider this code: | |
2427 | </p> | |
2428 | ||
2429 | <div class="code"> | |
2430 | <pre> | |
2431 | typedef int Integer; | |
2432 | void foo(vector<int> *x, vector<Integer> *y); | |
2433 | </pre> | |
2434 | </div> | |
2435 | ||
2436 | <p> | |
2437 | In this case, <tt>vector<Integer></tt> is exactly the same type | |
2438 | as <tt>vector<int></tt>. The wrapper for <tt>foo()</tt> will | |
2439 | accept either variant. | |
2440 | </p> | |
2441 | ||
2442 | <p> | |
2443 | Starting with SWIG-1.3.7, simple C++ template declarations can also be | |
2444 | wrapped. SWIG-1.3.12 greatly expands upon the earlier implementation. Before discussing this any further, there are a few things | |
2445 | you need to know about template wrapping. First, a bare C++ template | |
2446 | does not define any sort of runnable object-code for which SWIG can | |
2447 | normally create a wrapper. Therefore, in order to wrap a template, | |
2448 | you need to give SWIG information about a particular template | |
2449 | instantiation (e.g., <tt>vector<int></tt>, | |
2450 | <tt>array<double></tt>, etc.). Second, an instantiation name | |
2451 | such as <tt>vector<int></tt> is generally not a valid identifier | |
2452 | name in most target languages. Thus, you will need to give the | |
2453 | template instantiation a more suitable name such as <tt>intvector</tt> | |
2454 | when creating a wrapper. | |
2455 | </p> | |
2456 | ||
2457 | <p> | |
2458 | To illustrate, consider the following template definition: | |
2459 | </p> | |
2460 | ||
2461 | <div class="code"><pre> | |
2462 | template<class T> class List { | |
2463 | private: | |
2464 | T *data; | |
2465 | int nitems; | |
2466 | int maxitems; | |
2467 | public: | |
2468 | List(int max) { | |
2469 | data = new T [max]; | |
2470 | nitems = 0; | |
2471 | maxitems = max; | |
2472 | } | |
2473 | ~List() { | |
2474 | delete [] data; | |
2475 | }; | |
2476 | void append(T obj) { | |
2477 | if (nitems < maxitems) { | |
2478 | data[nitems++] = obj; | |
2479 | } | |
2480 | } | |
2481 | int length() { | |
2482 | return nitems; | |
2483 | } | |
2484 | T get(int n) { | |
2485 | return data[n]; | |
2486 | } | |
2487 | }; | |
2488 | </pre></div> | |
2489 | ||
2490 | <p> | |
2491 | By itself, this template declaration is useless--SWIG simply ignores it | |
2492 | because it doesn't know how to generate any code until unless a definition of | |
2493 | <tt>T</tt> is provided. | |
2494 | </p> | |
2495 | ||
2496 | <p> | |
2497 | One way to create wrappers for a specific template instantiation is to simply | |
2498 | provide an expanded version of the class directly like this: | |
2499 | </p> | |
2500 | ||
2501 | <div class="code"> | |
2502 | <pre> | |
2503 | %rename(intList) List<int>; // Rename to a suitable identifier | |
2504 | class List<int> { | |
2505 | private: | |
2506 | int *data; | |
2507 | int nitems; | |
2508 | int maxitems; | |
2509 | public: | |
2510 | List(int max); | |
2511 | ~List(); | |
2512 | void append(int obj); | |
2513 | int length(); | |
2514 | int get(int n); | |
2515 | }; | |
2516 | </pre> | |
2517 | </div> | |
2518 | ||
2519 | ||
2520 | <p> | |
2521 | The <tt>%rename</tt> directive is needed to give the template class an appropriate identifier | |
2522 | name in the target language (most languages would not recognize C++ template syntax as a valid | |
2523 | class name). The rest of the code is the same as what would appear in a normal | |
2524 | class definition. | |
2525 | </p> | |
2526 | ||
2527 | <p> | |
2528 | Since manual expansion of templates gets old in a hurry, the <tt>%template</tt> directive can | |
2529 | be used to create instantiations of a template class. Semantically, <tt>%template</tt> is | |
2530 | simply a shortcut---it expands template code in exactly the same way as shown above. Here | |
2531 | are some examples: | |
2532 | </p> | |
2533 | ||
2534 | <div class="code"> | |
2535 | <pre> | |
2536 | /* Instantiate a few different versions of the template */ | |
2537 | %template(intList) List<int>; | |
2538 | %template(doubleList) List<double>; | |
2539 | </pre> | |
2540 | </div> | |
2541 | ||
2542 | <p> | |
2543 | The argument to <tt>%template()</tt> is the name of the instantiation | |
2544 | in the target language. The name you choose should not conflict with | |
2545 | any other declarations in the interface file with one exception---it | |
2546 | is okay for the template name to match that of a typedef declaration. | |
2547 | For example: | |
2548 | </p> | |
2549 | ||
2550 | <div class="code"> | |
2551 | <pre> | |
2552 | %template(intList) List<int>; | |
2553 | ... | |
2554 | typedef List<int> intList; // OK | |
2555 | </pre> | |
2556 | </div> | |
2557 | ||
2558 | <p> | |
2559 | SWIG can also generate wrappers for function templates using a similar technique. | |
2560 | For example: | |
2561 | </p> | |
2562 | ||
2563 | <div class="code"> | |
2564 | <pre> | |
2565 | // Function template | |
2566 | template<class T> T max(T a, T b) { return a > b ? a : b; } | |
2567 | ||
2568 | // Make some different versions of this function | |
2569 | %template(maxint) max<int>; | |
2570 | %template(maxdouble) max<double>; | |
2571 | </pre> | |
2572 | </div> | |
2573 | ||
2574 | <p> | |
2575 | In this case, <tt>maxint</tt> and <tt>maxdouble</tt> become unique names for specific | |
2576 | instantiations of the function. | |
2577 | </p> | |
2578 | ||
2579 | <p> | |
2580 | The number of arguments supplied to <tt>%template</tt> should match that in the | |
2581 | original template definition. Template default arguments are supported. For example: | |
2582 | </p> | |
2583 | ||
2584 | <div class="code"> | |
2585 | <pre> | |
2586 | template vector<typename T, int max=100> class vector { | |
2587 | ... | |
2588 | }; | |
2589 | ||
2590 | %template(intvec) vector<int>; // OK | |
2591 | %template(vec1000) vector<int,1000>; // OK | |
2592 | </pre> | |
2593 | </div> | |
2594 | ||
2595 | <p> | |
2596 | The <tt>%template</tt> directive should not be used to wrap the same | |
2597 | template instantiation more than once in the same scope. This will | |
2598 | generate an error. For example: | |
2599 | </p> | |
2600 | ||
2601 | <div class="code"> | |
2602 | <pre> | |
2603 | %template(intList) List<int>; | |
2604 | %template(Listint) List<int>; // Error. Template already wrapped. | |
2605 | </pre> | |
2606 | </div> | |
2607 | ||
2608 | <p> | |
2609 | This error is caused because the template expansion results in two | |
2610 | identical classes with the same name. This generates a symbol table | |
2611 | conflict. Besides, it probably more efficient to only wrap a specific | |
2612 | instantiation only once in order to reduce the potential for code | |
2613 | bloat. | |
2614 | </p> | |
2615 | ||
2616 | <p> | |
2617 | Since the type system knows how to handle <tt>typedef</tt>, it is | |
2618 | generally not necessary to instantiate different versions of a template | |
2619 | for typenames that are equivalent. For instance, consider this code: | |
2620 | </p> | |
2621 | ||
2622 | <div class="code"> | |
2623 | <pre> | |
2624 | %template(intList) vector<int>; | |
2625 | typedef int Integer; | |
2626 | ... | |
2627 | void foo(vector<Integer> *x); | |
2628 | </pre> | |
2629 | </div> | |
2630 | ||
2631 | <p> | |
2632 | In this case, <tt>vector<Integer></tt> is exactly the same type as | |
2633 | <tt>vector<int></tt>. Any use of <tt>Vector<Integer></tt> is mapped back to the | |
2634 | instantiation of <tt>vector<int></tt> created earlier. Therefore, it is | |
2635 | not necessary to instantiate a new class for the type <tt>Integer</tt> (doing so is | |
2636 | redundant and will simply result in code bloat). | |
2637 | </p> | |
2638 | ||
2639 | <p> | |
2640 | When a template is instantiated using <tt>%template</tt>, information | |
2641 | about that class is saved by SWIG and used elsewhere in the program. | |
2642 | For example, if you wrote code like this, | |
2643 | </p> | |
2644 | ||
2645 | <div class="code"> | |
2646 | <pre> | |
2647 | ... | |
2648 | %template(intList) List<int>; | |
2649 | ... | |
2650 | class UltraList : public List<int> { | |
2651 | ... | |
2652 | }; | |
2653 | </pre> | |
2654 | </div> | |
2655 | ||
2656 | <p> | |
2657 | then SWIG knows that <tt>List<int></tt> was already wrapped as a class called | |
2658 | <tt>intList</tt> and arranges to handle the inheritance correctly. If, on the other hand, | |
2659 | nothing is known about <tt>List<int></tt>, you will get a warning message similar to this: | |
2660 | </p> | |
2661 | ||
2662 | <div class="shell"> | |
2663 | <pre> | |
2664 | example.h:42. Nothing known about class 'List<int >' (ignored). | |
2665 | example.h:42. Maybe you forgot to instantiate 'List<int >' using %template. | |
2666 | </pre> | |
2667 | </div> | |
2668 | ||
2669 | <p> | |
2670 | If a template class inherits from another template class, you need to | |
2671 | make sure that base classes are instantiated before derived classes. | |
2672 | For example: | |
2673 | </p> | |
2674 | ||
2675 | <div class="code"> | |
2676 | <pre> | |
2677 | template<class T> class Foo { | |
2678 | ... | |
2679 | }; | |
2680 | ||
2681 | template<class T> class Bar : public Foo<T> { | |
2682 | ... | |
2683 | }; | |
2684 | ||
2685 | // Instantiate base classes first | |
2686 | %template(intFoo) Foo<int>; | |
2687 | %template(doubleFoo) Foo<double>; | |
2688 | ||
2689 | // Now instantiate derived classes | |
2690 | %template(intBar) Bar<int>; | |
2691 | %template(doubleBar) Bar<double>; | |
2692 | </pre> | |
2693 | </div> | |
2694 | ||
2695 | <p> | |
2696 | The order is important since SWIG uses the instantiation names to | |
2697 | properly set up the inheritance hierarchy in the resulting wrapper | |
2698 | code (and base classes need to be wrapped before derived classes). | |
2699 | Don't worry--if you get the order wrong, SWIG should generate a warning message. | |
2700 | </p> | |
2701 | ||
2702 | <p> | |
2703 | Occassionally, you may need to tell SWIG about base classes that are defined by templates, | |
2704 | but which aren't supposed to be wrapped. Since SWIG is not able to automatically | |
2705 | instantiate templates for this purpose, you must do it manually. To do this, simply | |
2706 | use <tt>%template</tt> with no name. For example: | |
2707 | </p> | |
2708 | ||
2709 | <div class="code"> | |
2710 | <pre> | |
2711 | // Instantiate traits<double,double>, but don't wrap it. | |
2712 | %template() traits<double,double>; | |
2713 | </pre> | |
2714 | </div> | |
2715 | ||
2716 | <p> | |
2717 | If you have to instantiate a lot of different classes for many different types, | |
2718 | you might consider writing a SWIG macro. For example: | |
2719 | </p> | |
2720 | ||
2721 | <div class="code"> | |
2722 | <pre> | |
2723 | %define TEMPLATE_WRAP(T,prefix) | |
2724 | %template(prefix ## Foo) Foo<T>; | |
2725 | %template(prefix ## Bar) Bar<T>; | |
2726 | ... | |
2727 | %enddef | |
2728 | ||
2729 | TEMPLATE_WRAP(int, int) | |
2730 | TEMPLATE_WRAP(double, double) | |
2731 | TEMPLATE_WRAP(char *, String) | |
2732 | ... | |
2733 | </pre> | |
2734 | </div> | |
2735 | ||
2736 | <p> | |
2737 | The SWIG template mechanism <em>does</em> support specialization. For instance, if you define | |
2738 | a class like this, | |
2739 | </p> | |
2740 | ||
2741 | <div class="code"> | |
2742 | <pre> | |
2743 | template<> class List<int> { | |
2744 | private: | |
2745 | int *data; | |
2746 | int nitems; | |
2747 | int maxitems; | |
2748 | public: | |
2749 | List(int max); | |
2750 | ~List(); | |
2751 | void append(int obj); | |
2752 | int length(); | |
2753 | int get(int n); | |
2754 | }; | |
2755 | </pre> | |
2756 | </div> | |
2757 | ||
2758 | <p> | |
2759 | then SWIG will use this code whenever the user expands <tt>List<int></tt>. In practice, | |
2760 | this may have very little effect on the underlying wrapper code since | |
2761 | specialization is often used to provide slightly modified method bodies (which | |
2762 | are ignored by SWIG). However, special SWIG | |
2763 | directives such as <tt>%typemap</tt>, <tt>%extend</tt>, and so forth can be attached | |
2764 | to a specialization to provide customization for specific types. | |
2765 | </p> | |
2766 | ||
2767 | <p> | |
2768 | Partial template specialization is partially supported by SWIG. For example, this | |
2769 | code defines a template that is applied when the template argument is a pointer. | |
2770 | </p> | |
2771 | ||
2772 | <div class="code"> | |
2773 | <pre> | |
2774 | template<class T> class List<T*> { | |
2775 | private: | |
2776 | T *data; | |
2777 | int nitems; | |
2778 | int maxitems; | |
2779 | public: | |
2780 | List(int max); | |
2781 | ~List(); | |
2782 | void append(int obj); | |
2783 | int length(); | |
2784 | T get(int n); | |
2785 | }; | |
2786 | </pre> | |
2787 | </div> | |
2788 | ||
2789 | <p> | |
2790 | SWIG should be able to handle most simple uses of partial specialization. However, it may fail | |
2791 | to match templates properly in more complicated cases. For example, if you have this code, | |
2792 | </p> | |
2793 | ||
2794 | <div class="code"> | |
2795 | <pre> | |
2796 | template<class T1, class T2> class Foo<T1, T2 *> { }; | |
2797 | </pre> | |
2798 | </div> | |
2799 | ||
2800 | <p> | |
2801 | SWIG isn't able to match it properly for instantiations like <tt>Foo<int *, int *></tt>. | |
2802 | This problem is not due to parsing, but due to the fact that SWIG does not currently implement all | |
2803 | of the C++ argument deduction rules. | |
2804 | </p> | |
2805 | ||
2806 | <p> | |
2807 | Member function templates are supported. The underlying principle is the same | |
2808 | as for normal templates--SWIG can't create a wrapper unless you provide | |
2809 | more information about types. For example, a class with a member template might | |
2810 | look like this: | |
2811 | </p> | |
2812 | ||
2813 | <div class="code"> | |
2814 | <pre> | |
2815 | class Foo { | |
2816 | public: | |
2817 | template<class T> void bar(T x, T y) { ... }; | |
2818 | ... | |
2819 | }; | |
2820 | </pre> | |
2821 | </div> | |
2822 | ||
2823 | <p> | |
2824 | To expand the template, simply use <tt>%template</tt> inside the class. | |
2825 | </p> | |
2826 | ||
2827 | <div class="code"> | |
2828 | <pre> | |
2829 | class Foo { | |
2830 | public: | |
2831 | template<class T> void bar(T x, T y) { ... }; | |
2832 | ... | |
2833 | %template(barint) bar<int>; | |
2834 | %template(bardouble) bar<double>; | |
2835 | }; | |
2836 | </pre> | |
2837 | </div> | |
2838 | ||
2839 | <p> | |
2840 | Or, if you want to leave the original class definition alone, just do this: | |
2841 | </p> | |
2842 | ||
2843 | <div class="code"> | |
2844 | <pre> | |
2845 | class Foo { | |
2846 | public: | |
2847 | template<class T> void bar(T x, T y) { ... }; | |
2848 | ... | |
2849 | }; | |
2850 | ... | |
2851 | %extend Foo { | |
2852 | %template(barint) bar<int>; | |
2853 | %template(bardouble) bar<double>; | |
2854 | }; | |
2855 | </pre> | |
2856 | </div> | |
2857 | ||
2858 | <p> | |
2859 | or simply | |
2860 | </p> | |
2861 | ||
2862 | <div class="code"> | |
2863 | <pre> | |
2864 | class Foo { | |
2865 | public: | |
2866 | template<class T> void bar(T x, T y) { ... }; | |
2867 | ... | |
2868 | }; | |
2869 | ... | |
2870 | ||
2871 | %template(bari) Foo::bar<int>; | |
2872 | %template(bard) Foo::bar<double>; | |
2873 | </pre> | |
2874 | </div> | |
2875 | ||
2876 | <p> | |
2877 | In this case, the <tt>%extend</tt> directive is not needed, and | |
2878 | <tt>%template</tt> does the exactly same job, i.e., it adds two new | |
2879 | methods to the Foo class. | |
2880 | </p> | |
2881 | ||
2882 | ||
2883 | <p> | |
2884 | Note: because of the way that templates are handled, the <tt>%template</tt> directive | |
2885 | must always appear <em>after</em> the definition of the template to be expanded. | |
2886 | </p> | |
2887 | ||
2888 | <p> | |
2889 | Now, if your target language supports overloading, you can even try | |
2890 | </p> | |
2891 | ||
2892 | <div class="code"> | |
2893 | <pre> | |
2894 | %template(bar) Foo::bar<int>; | |
2895 | %template(bar) Foo::bar<double>; | |
2896 | </pre> | |
2897 | </div> | |
2898 | ||
2899 | <p> | |
2900 | and since the two new wrapped methods have the same name 'bar', they will be | |
2901 | overloaded, and when called, the correct method will be dispatched | |
2902 | depending on the argument type. | |
2903 | </p> | |
2904 | ||
2905 | ||
2906 | <p> | |
2907 | When used with members, the <tt>%template</tt> directive may be placed in another | |
2908 | template class. Here is a slightly perverse example: | |
2909 | </p> | |
2910 | ||
2911 | <div class="code"> | |
2912 | <pre> | |
2913 | // A template | |
2914 | template<class T> class Foo { | |
2915 | public: | |
2916 | // A member template | |
2917 | template<class S> T bar(S x, S y) { ... }; | |
2918 | ... | |
2919 | }; | |
2920 | ||
2921 | // Expand a few member templates | |
2922 | %extend Foo { | |
2923 | %template(bari) bar<int>; | |
2924 | %template(bard) bar<double>; | |
2925 | } | |
2926 | ||
2927 | // Create some wrappers for the template | |
2928 | %template(Fooi) Foo<int>; | |
2929 | %template(Food) Foo<double>; | |
2930 | </pre> | |
2931 | </div> | |
2932 | ||
2933 | <p> | |
2934 | Miraculously, you will find that each expansion of <tt>Foo</tt> has member | |
2935 | functions <tt>bari()</tt> and <tt>bard()</tt> added. | |
2936 | </p> | |
2937 | ||
2938 | <p> | |
2939 | A common use of member templates is to define constructors for copies | |
2940 | and conversions. For example: | |
2941 | </p> | |
2942 | ||
2943 | <div class="code"> | |
2944 | <pre> | |
2945 | template<class T1, class T2> struct pair { | |
2946 | T1 first; | |
2947 | T2 second; | |
2948 | pair() : first(T1()), second(T2()) { } | |
2949 | pair(const T1 &x, const T2 &y) : first(x), second(y) { } | |
2950 | template<class U1, class U2> pair(const pair<U1,U2> &x) | |
2951 | : first(x.first),second(x.second) { } | |
2952 | }; | |
2953 | </pre> | |
2954 | </div> | |
2955 | ||
2956 | <p> | |
2957 | This declaration is perfectly acceptable to SWIG, but the constructor template will be ignored | |
2958 | unless you explicitly expand it. To do that, you could expand a few versions of the constructor | |
2959 | in the template class itself. For example: | |
2960 | </p> | |
2961 | ||
2962 | <div class="code"> | |
2963 | <pre> | |
2964 | %extend pair { | |
2965 | %template(pair) pair<T1,T2>; // Generate default copy constructor | |
2966 | }; | |
2967 | </pre> | |
2968 | </div> | |
2969 | ||
2970 | <p> | |
2971 | When using <tt>%extend</tt> in this manner, notice how you can still use the template parameters in | |
2972 | the original template definition. | |
2973 | </p> | |
2974 | ||
2975 | <p> | |
2976 | Alternatively, you could expand the constructor template in selected instantiations. For example: | |
2977 | </p> | |
2978 | ||
2979 | <div class="code"> | |
2980 | <pre> | |
2981 | // Instantiate a few versions | |
2982 | %template(pairii) pair<int,int>; | |
2983 | %template(pairdd) pair<double,double>; | |
2984 | ||
2985 | // Create a default constructor only | |
2986 | %extend pair<int,int> { | |
2987 | %template(paird) pair<int,int>; // Default constructor | |
2988 | }; | |
2989 | ||
2990 | // Create default and conversion constructors | |
2991 | %extend pair<double,double> { | |
2992 | %template(paird) pair<double,dobule>; // Default constructor | |
2993 | %template(pairc) pair<int,int>; // Conversion constructor | |
2994 | }; | |
2995 | </pre> | |
2996 | </div> | |
2997 | ||
2998 | ||
2999 | <p>And if your target language supports overloading, then you can try | |
3000 | instead: | |
3001 | </p> | |
3002 | ||
3003 | <div class="code"> | |
3004 | <pre> | |
3005 | // Create default and conversion constructors | |
3006 | %extend pair<double,double> { | |
3007 | %template(pair) pair<double,dobule>; // Default constructor | |
3008 | %template(pair) pair<int,int>; // Conversion constructor | |
3009 | }; | |
3010 | </pre> | |
3011 | </div> | |
3012 | ||
3013 | <p> | |
3014 | In this case, the default and conversion constructors have the same | |
3015 | name. Hence, Swig will overload them and define an unique visible | |
3016 | constructor, that will dispatch the proper call depending on the argument | |
3017 | type. | |
3018 | </p> | |
3019 | ||
3020 | <p> | |
3021 | If all of this isn't quite enough and you really want to make | |
3022 | someone's head explode, SWIG directives such as | |
3023 | <tt>%rename</tt>, <tt>%extend</tt>, and <tt>%typemap</tt> can be | |
3024 | included directly in template definitions. For example: | |
3025 | </p> | |
3026 | ||
3027 | <div class="code"><pre> | |
3028 | // File : list.h | |
3029 | template<class T> class List { | |
3030 | ... | |
3031 | public: | |
3032 | %rename(__getitem__) get(int); | |
3033 | List(int max); | |
3034 | ~List(); | |
3035 | ... | |
3036 | T get(int index); | |
3037 | %extend { | |
3038 | char *__str__() { | |
3039 | /* Make a string representation */ | |
3040 | ... | |
3041 | } | |
3042 | } | |
3043 | }; | |
3044 | </pre></div> | |
3045 | ||
3046 | <p> | |
3047 | In this example, the extra SWIG directives are propagated to <em>every</em> template | |
3048 | instantiation. | |
3049 | </p> | |
3050 | ||
3051 | <p> | |
3052 | It is also possible to separate these declarations from the template class. For example: | |
3053 | </p> | |
3054 | ||
3055 | <div class="code"> | |
3056 | <pre> | |
3057 | %rename(__getitem__) List::get; | |
3058 | %extend List { | |
3059 | char *__str__() { | |
3060 | /* Make a string representation */ | |
3061 | ... | |
3062 | } | |
3063 | /* Make a copy */ | |
3064 | T *__copy__() { | |
3065 | return new List<T>(*self); | |
3066 | } | |
3067 | }; | |
3068 | ||
3069 | ... | |
3070 | template<class T> class List { | |
3071 | ... | |
3072 | public: | |
3073 | List() { }; | |
3074 | ... | |
3075 | }; | |
3076 | </pre> | |
3077 | </div> | |
3078 | ||
3079 | <p> | |
3080 | When <tt>%extend</tt> is decoupled from the class definition, it is | |
3081 | legal to use the same template parameters as provided in the class definition. | |
3082 | These are replaced when the template is expanded. | |
3083 | In addition, the <tt>%extend</tt> directive can be used to add | |
3084 | additional methods to a specific instantiation. For example: | |
3085 | </p> | |
3086 | ||
3087 | <div class="code"> | |
3088 | <pre> | |
3089 | %template(intList) List<int>; | |
3090 | ||
3091 | %extend List<int> { | |
3092 | void blah() { | |
3093 | printf("Hey, I'm an List<int>!\n"); | |
3094 | } | |
3095 | }; | |
3096 | </pre> | |
3097 | </div> | |
3098 | ||
3099 | <p> | |
3100 | SWIG even supports overloaded templated functions. As usual the <tt>%template</tt> directive | |
3101 | is used to wrap templated functions. For example: | |
3102 | </p> | |
3103 | ||
3104 | <div class="code"> | |
3105 | <pre> | |
3106 | template<class T> void foo(T x) { }; | |
3107 | template<class T> void foo(T x, T y) { }; | |
3108 | ||
3109 | %template(foo) foo<int>; | |
3110 | </pre> | |
3111 | </div> | |
3112 | ||
3113 | <p> | |
3114 | This will generate two overloaded wrapper methods, the first will take a single integer as an argument | |
3115 | and the second will take two integer arguments. | |
3116 | </p> | |
3117 | ||
3118 | <p> | |
3119 | Needless to say, SWIG's template support provides plenty of | |
3120 | opportunities to break the universe. That said, an important final | |
3121 | point is that <b>SWIG does not perform extensive error checking of | |
3122 | templates!</b> Specifically, SWIG does not perform type checking nor | |
3123 | does it check to see if the actual contents of the template | |
3124 | declaration make any sense. Since the C++ compiler will hopefully | |
3125 | check this when it compiles the resulting wrapper file, there is no | |
3126 | practical reason for SWIG to duplicate this functionality (besides, | |
3127 | none of the SWIG developers are masochistic enough to want to | |
3128 | implement this right now). | |
3129 | </p> | |
3130 | ||
3131 | <p> | |
3132 | <b>Compatibility Note</b>: The first implementation of template support relied heavily on | |
3133 | macro expansion in the preprocessor. Templates have been more tightly integrated into | |
3134 | the parser and type system in SWIG-1.3.12 and the preprocessor is no longer used. Code | |
3135 | that relied on preprocessing features in template expansion will no longer work. However, | |
3136 | SWIG still allows the # operator to be used to generate a string from a template argument. | |
3137 | </p> | |
3138 | ||
3139 | <p> | |
3140 | <b>Compatibility Note</b>: In earlier versions of SWIG, the <tt>%template</tt> directive | |
3141 | introduced a new class name. This name could then be used with other directives. For example: | |
3142 | </p> | |
3143 | ||
3144 | <div class="code"> | |
3145 | <pre> | |
3146 | %template(vectori) vector<int>; | |
3147 | %extend vectori { | |
3148 | void somemethod() { } | |
3149 | }; | |
3150 | </pre> | |
3151 | </div> | |
3152 | ||
3153 | <p> | |
3154 | This behavior is no longer supported. Instead, you should use the original template name | |
3155 | as the class name. For example: | |
3156 | </p> | |
3157 | ||
3158 | <div class="code"> | |
3159 | <pre> | |
3160 | %template(vectori) vector<int>; | |
3161 | %extend vector<int> { | |
3162 | void somemethod() { } | |
3163 | }; | |
3164 | </pre> | |
3165 | </div> | |
3166 | ||
3167 | <p> | |
3168 | Similar changes apply to typemaps and other customization features. | |
3169 | </p> | |
3170 | ||
3171 | <H2><a name="SWIGPlus_nn31"></a>6.19 Namespaces</H2> | |
3172 | ||
3173 | ||
3174 | <p> | |
3175 | Support for C++ namespaces is a relatively late addition to SWIG, | |
3176 | first appearing in SWIG-1.3.12. Before describing the implementation, | |
3177 | it is worth nothing that the semantics of C++ namespaces is extremely | |
3178 | non-trivial--especially with regard to the C++ type system and class | |
3179 | machinery. At a most basic level, namespaces are sometimes used to | |
3180 | encapsulate common functionality. For example: | |
3181 | </p> | |
3182 | ||
3183 | <div class="code"> | |
3184 | <pre> | |
3185 | namespace math { | |
3186 | double sin(double); | |
3187 | double cos(double); | |
3188 | ||
3189 | class Complex { | |
3190 | double im,re; | |
3191 | public: | |
3192 | ... | |
3193 | }; | |
3194 | ... | |
3195 | }; | |
3196 | </pre> | |
3197 | </div> | |
3198 | ||
3199 | <p> | |
3200 | Members of the namespace are accessed in C++ by prepending the namespace prefix | |
3201 | to names. For example: | |
3202 | </p> | |
3203 | ||
3204 | <div class="code"> | |
3205 | <pre> | |
3206 | double x = math::sin(1.0); | |
3207 | double magnitude(math::Complex *c); | |
3208 | math::Complex c; | |
3209 | ... | |
3210 | </pre> | |
3211 | </div> | |
3212 | ||
3213 | <p> | |
3214 | At this level, namespaces are relatively easy to manage. However, things start to get | |
3215 | very ugly when you throw in the other ways a namespace can be used. For example, | |
3216 | selective symbols can be exported from a namespace with <tt>using</tt>. | |
3217 | </p> | |
3218 | ||
3219 | <div class="code"> | |
3220 | <pre> | |
3221 | using math::Complex; | |
3222 | double magnitude(Complex *c); // Namespace prefix stripped | |
3223 | </pre> | |
3224 | </div> | |
3225 | ||
3226 | <p> | |
3227 | Similarly, the contents of an entire namespace can be made available like this: | |
3228 | </p> | |
3229 | ||
3230 | <div class="code"> | |
3231 | <pre> | |
3232 | using namespace math; | |
3233 | double x = sin(1.0); | |
3234 | double magnitude(Complex *c); | |
3235 | </pre> | |
3236 | </div> | |
3237 | ||
3238 | <p> | |
3239 | Alternatively, a namespace can be aliased: | |
3240 | </p> | |
3241 | ||
3242 | <div class="code"> | |
3243 | <pre> | |
3244 | namespace M = math; | |
3245 | double x = M::sin(1.0); | |
3246 | double magnitude(M::Complex *c); | |
3247 | </pre> | |
3248 | </div> | |
3249 | ||
3250 | <p> | |
3251 | Using combinations of these features, it is possible to write head-exploding code like this: | |
3252 | </p> | |
3253 | ||
3254 | <div class="code"> | |
3255 | <pre> | |
3256 | namespace A { | |
3257 | class Foo { | |
3258 | }; | |
3259 | } | |
3260 | ||
3261 | namespace B { | |
3262 | namespace C { | |
3263 | using namespace A; | |
3264 | } | |
3265 | typedef C::Foo FooClass; | |
3266 | } | |
3267 | ||
3268 | namespace BIGB = B; | |
3269 | ||
3270 | namespace D { | |
3271 | using BIGB::FooClass; | |
3272 | class Bar : public FooClass { | |
3273 | } | |
3274 | }; | |
3275 | ||
3276 | class Spam : public D::Bar { | |
3277 | }; | |
3278 | ||
3279 | void evil(A::Foo *a, B::FooClass *b, B::C::Foo *c, BIGB::FooClass *d, | |
3280 | BIGB::C::Foo *e, D::FooClass *f); | |
3281 | ||
3282 | </pre> | |
3283 | </div> | |
3284 | ||
3285 | <p> | |
3286 | Given the possibility for such perversion, it's hard to imagine how | |
3287 | every C++ programmer might want such code wrapped into the target | |
3288 | language. Clearly this code defines three different classes. However, one | |
3289 | of those classes is accessible under at least six different class names! | |
3290 | </p> | |
3291 | ||
3292 | <p> | |
3293 | SWIG fully supports C++ namespaces in its internal type system and | |
3294 | class handling code. If you feed SWIG the above code, it will be | |
3295 | parsed correctly, it will generate compilable wrapper code, and it | |
3296 | will produce a working scripting language module. However, the | |
3297 | default wrapping behavior is to flatten namespaces in the target | |
3298 | language. This means that the contents of all namespaces are merged | |
3299 | together in the resulting scripting language module. For example, if | |
3300 | you have code like this, | |
3301 | </p> | |
3302 | ||
3303 | <div class="code"> | |
3304 | <pre> | |
3305 | %module foo | |
3306 | namespace foo { | |
3307 | void bar(int); | |
3308 | void spam(); | |
3309 | } | |
3310 | ||
3311 | namespace bar { | |
3312 | void blah(); | |
3313 | } | |
3314 | ||
3315 | </pre> | |
3316 | </div> | |
3317 | ||
3318 | <p> | |
3319 | then SWIG simply creates three wrapper functions <tt>bar()</tt>, | |
3320 | <tt>spam()</tt>, and <tt>blah()</tt> in the target language. SWIG | |
3321 | does not prepend the names with a namespace prefix nor are the | |
3322 | functions packaged in any kind of nested scope. | |
3323 | </p> | |
3324 | ||
3325 | <p> | |
3326 | There is some rationale for taking this approach. Since C++ | |
3327 | namespaces are often used to define modules in C++, there is a natural | |
3328 | correlation between the likely contents of a SWIG module and the contents of | |
3329 | a namespace. For instance, it would not be unreasonable to assume | |
3330 | that a programmer might make a separate extension module for each C++ | |
3331 | namespace. In this case, it would be redundant to prepend everything | |
3332 | with an additional namespace prefix when the module itself already | |
3333 | serves as a namespace in the target language. Or put another way, if | |
3334 | you want SWIG to keep namespaces separate, simply wrap each namespace with its | |
3335 | own SWIG interface. | |
3336 | </p> | |
3337 | ||
3338 | <p> | |
3339 | Because namespaces are flattened, it is possible for symbols defined in different | |
3340 | namespaces to generate a name conflict in the target language. For example: | |
3341 | </p> | |
3342 | ||
3343 | <div class="code"> | |
3344 | <pre> | |
3345 | namespace A { | |
3346 | void foo(int); | |
3347 | } | |
3348 | namespace B { | |
3349 | void foo(double); | |
3350 | } | |
3351 | </pre> | |
3352 | </div> | |
3353 | ||
3354 | <p> | |
3355 | When this conflict occurs, you will get an error message that resembles this: | |
3356 | </p> | |
3357 | ||
3358 | <div class="shell"> | |
3359 | <pre> | |
3360 | example.i:26. Error. 'foo' is multiply defined in the generated module. | |
3361 | example.i:23. Previous declaration of 'foo' | |
3362 | </pre> | |
3363 | </div> | |
3364 | ||
3365 | <p> | |
3366 | To resolve this error, simply use <tt>%rename</tt> to disambiguate the declarations. For example: | |
3367 | </p> | |
3368 | ||
3369 | <div class="code"> | |
3370 | <pre> | |
3371 | %rename(B_foo) B::foo; | |
3372 | ... | |
3373 | namespace A { | |
3374 | void foo(int); | |
3375 | } | |
3376 | namespace B { | |
3377 | void foo(double); // Gets renamed to B_foo | |
3378 | } | |
3379 | </pre> | |
3380 | </div> | |
3381 | ||
3382 | <p> | |
3383 | Similarly, <tt>%ignore</tt> can be used to ignore declarations. | |
3384 | </p> | |
3385 | ||
3386 | <p> | |
3387 | <tt>using</tt> declarations do not have any effect on the generated wrapper | |
3388 | code. They are ignored by SWIG language modules and they do not result in any | |
3389 | code. However, these declarations <em>are</em> used by the internal type | |
3390 | system to track type-names. Therefore, if you have code like this: | |
3391 | </p> | |
3392 | ||
3393 | <div class="code"> | |
3394 | <pre> | |
3395 | namespace A { | |
3396 | typedef int Integer; | |
3397 | } | |
3398 | using namespace A; | |
3399 | void foo(Integer x); | |
3400 | </pre> | |
3401 | </div> | |
3402 | ||
3403 | <p> | |
3404 | SWIG knows that <tt>Integer</tt> is the same as <tt>A::Integer</tt> which | |
3405 | is the same as <tt>int</tt>. | |
3406 | </p> | |
3407 | ||
3408 | <P> | |
3409 | Namespaces may be combined with templates. If necessary, the | |
3410 | <tt>%template</tt> directive can be used to expand a template defined | |
3411 | in a different namespace. For example: | |
3412 | </p> | |
3413 | ||
3414 | <div class="code"> | |
3415 | <pre> | |
3416 | namespace foo { | |
3417 | template<typename T> T max(T a, T b) { return a > b ? a : b; } | |
3418 | } | |
3419 | ||
3420 | using foo::max; | |
3421 | ||
3422 | %template(maxint) max<int>; // Okay. | |
3423 | %template(maxfloat) foo::max<float>; // Okay (qualified name). | |
3424 | ||
3425 | namespace bar { | |
3426 | using namespace foo; | |
3427 | %template(maxdouble) max<double>; // Okay. | |
3428 | } | |
3429 | </pre> | |
3430 | </div> | |
3431 | ||
3432 | <p> | |
3433 | The combination of namespaces and other SWIG directives may introduce subtle scope-related problems. | |
3434 | The key thing to keep in mind is that all SWIG generated wrappers are produced | |
3435 | in the <em>global</em> namespace. Symbols from other namespaces are always accessed using fully | |
3436 | qualified names---names are never imported into the global space unless the interface happens to | |
3437 | do so with a <tt>using</tt> declaration. In almost all cases, SWIG adjusts typenames and symbols | |
3438 | to be fully qualified. However, this is not done in code fragments such as function bodies, | |
3439 | typemaps, exception handlers, and so forth. For example, consider the following: | |
3440 | </p> | |
3441 | ||
3442 | <div class="code"> | |
3443 | <pre> | |
3444 | namespace foo { | |
3445 | typedef int Integer; | |
3446 | class bar { | |
3447 | public: | |
3448 | ... | |
3449 | }; | |
3450 | } | |
3451 | ||
3452 | %extend foo::bar { | |
3453 | Integer add(Integer x, Integer y) { | |
3454 | Integer r = x + y; // Error. Integer not defined in this scope | |
3455 | return r; | |
3456 | } | |
3457 | }; | |
3458 | </pre> | |
3459 | </div> | |
3460 | ||
3461 | <p> | |
3462 | In this case, SWIG correctly resolves the added method parameters and return type to | |
3463 | <tt>foo::Integer</tt>. However, since function bodies aren't parsed and such code is | |
3464 | emitted in the global namespace, this code produces a compiler error about <tt>Integer</tt>. | |
3465 | To fix the problem, make sure you use fully qualified names. For example: | |
3466 | </p> | |
3467 | ||
3468 | <div class="code"> | |
3469 | <pre> | |
3470 | %extend foo::bar { | |
3471 | Integer add(Integer x, Integer y) { | |
3472 | foo::Integer r = x + y; // Ok. | |
3473 | return r; | |
3474 | } | |
3475 | }; | |
3476 | </pre> | |
3477 | </div> | |
3478 | ||
3479 | <p> | |
3480 | <b>Note:</b> SWIG does <em>not</em> propagate <tt>using</tt> declarations to | |
3481 | the resulting wrapper code. If these declarations appear in an interface, | |
3482 | they should <em>also</em> appear in any header files that might have been | |
3483 | included in a <tt>%{ ... %}</tt> section. In other words, don't insert extra | |
3484 | <tt>using</tt> declarations into a SWIG interface unless they also appear | |
3485 | in the underlying C++ code. | |
3486 | </p> | |
3487 | ||
3488 | <p> | |
3489 | <b>Note:</b> Code inclusion directives such as <tt>%{ ... %}</tt> or | |
3490 | <tt>%inline %{ ... %}</tt> should not be placed inside a namespace declaration. | |
3491 | The code emitted by these directives will not be enclosed in a namespace and | |
3492 | you may get very strange results. If you need to use namespaces with | |
3493 | these directives, consider the following: | |
3494 | </p> | |
3495 | ||
3496 | <div class="code"> | |
3497 | <pre> | |
3498 | // Good version | |
3499 | %inline %{ | |
3500 | namespace foo { | |
3501 | void bar(int) { ... } | |
3502 | ... | |
3503 | } | |
3504 | %} | |
3505 | ||
3506 | // Bad version. Emitted code not placed in namespace. | |
3507 | namespace foo { | |
3508 | %inline %{ | |
3509 | void bar(int) { ... } /* I'm bad */ | |
3510 | ... | |
3511 | %} | |
3512 | } | |
3513 | </pre> | |
3514 | </div> | |
3515 | ||
3516 | <p> | |
3517 | <b>Note:</b> When the <tt>%extend</tt> directive is used inside a namespace, the namespace name is | |
3518 | included in the generated functions. For example, if you have code like this, | |
3519 | </p> | |
3520 | ||
3521 | <div class="code"> | |
3522 | <pre> | |
3523 | namespace foo { | |
3524 | class bar { | |
3525 | public: | |
3526 | %extend { | |
3527 | int blah(int x); | |
3528 | }; | |
3529 | }; | |
3530 | } | |
3531 | </pre> | |
3532 | </div> | |
3533 | ||
3534 | <p> | |
3535 | the added method <tt>blah()</tt> is mapped to a function <tt>int foo_bar_blah(foo::bar *self, int x)</tt>. | |
3536 | This function resides in the global namespace. | |
3537 | </p> | |
3538 | ||
3539 | <p> | |
3540 | <b>Note:</b> Although namespaces are flattened in the target language, the SWIG generated wrapper | |
3541 | code observes the same namespace conventions as used in the input file. Thus, if there are no symbol | |
3542 | conflicts in the input, there will be no conflicts in the generated code. | |
3543 | </p> | |
3544 | ||
3545 | <p> | |
3546 | <b>Note:</b> Namespaces have a subtle effect on the wrapping of conversion operators. For | |
3547 | instance, suppose you had an interface like this: | |
3548 | </p> | |
3549 | ||
3550 | <div class="code"> | |
3551 | <pre> | |
3552 | namespace foo { | |
3553 | class bar; | |
3554 | class spam { | |
3555 | public: | |
3556 | ... | |
3557 | operator bar(); // Conversion of spam -> bar | |
3558 | ... | |
3559 | }; | |
3560 | } | |
3561 | </pre> | |
3562 | </div> | |
3563 | ||
3564 | <p> | |
3565 | To wrap the conversion function, you might be inclined to write this: | |
3566 | </p> | |
3567 | ||
3568 | <div class="code"> | |
3569 | <pre> | |
3570 | %rename(tofoo) foo::spam::operator bar(); | |
3571 | </pre> | |
3572 | </div> | |
3573 | ||
3574 | <p> | |
3575 | The only problem is that it doesn't work. The reason it doesn't work is that | |
3576 | <tt>bar</tt> is not defined in the global scope. Therefore, to make it work, do this | |
3577 | instead: | |
3578 | </p> | |
3579 | ||
3580 | <div class="code"> | |
3581 | <pre> | |
3582 | %rename(tofoo) foo::spam::operator <b>foo::</b>bar(); | |
3583 | </pre> | |
3584 | </div> | |
3585 | ||
3586 | <p> | |
3587 | <b>Note:</b> The flattening of namespaces is only intended to serve as | |
3588 | a basic namespace implementation. Since namespaces are a new addition | |
3589 | to SWIG, none of the target language modules are currently programmed | |
3590 | with any namespace awareness. In the future, language modules may or may not provide | |
3591 | more advanced namespace support. | |
3592 | </p> | |
3593 | ||
3594 | ||
3595 | <H2><a name="SWIGPlus_exception_specifications"></a>6.20 Exception specifications</H2> | |
3596 | ||
3597 | ||
3598 | <p> | |
3599 | When C++ programs utilize exceptions, exceptional behavior is sometimes specified as | |
3600 | part of a function or method declaration. For example: | |
3601 | </p> | |
3602 | ||
3603 | <div class="code"> | |
3604 | <pre> | |
3605 | class Error { }; | |
3606 | ||
3607 | class Foo { | |
3608 | public: | |
3609 | ... | |
3610 | void blah() throw(Error); | |
3611 | ... | |
3612 | }; | |
3613 | </pre> | |
3614 | </div> | |
3615 | ||
3616 | <p> | |
3617 | If an exception specification is used, SWIG automatically generates wrapper code for catching the | |
3618 | indicated exception and converting it into an error in the target language. In certain language | |
3619 | modules, wrapped exception classes themselves can be used to catch errors. For example, in Python, you can | |
3620 | write code like this: | |
3621 | </p> | |
3622 | ||
3623 | <div class="targetlang"> | |
3624 | <pre> | |
3625 | f = Foo() | |
3626 | try: | |
3627 | f.blah() | |
3628 | except Error,e: | |
3629 | # e is a wrapped instance of "Error" | |
3630 | </pre> | |
3631 | </div> | |
3632 | ||
3633 | <p> | |
3634 | Obviously, the exact details of how exceptions are handled depend on the target language module. | |
3635 | </p> | |
3636 | ||
3637 | <p> | |
3638 | Since exception specifications are sometimes only used sparingly, this alone may not be enough to | |
3639 | properly handle C++ exceptions. To do that, a different set of special SWIG directives are used. | |
3640 | Consult the "<a href="Customization.html#Customization">Customization features</a>" chapter for details. | |
3641 | </p> | |
3642 | ||
3643 | <H2><a name="SWIGPlus_nn33"></a>6.21 Pointers to Members</H2> | |
3644 | ||
3645 | ||
3646 | <p> | |
3647 | Starting with SWIG1.3.7, there is limited parsing support for pointers to C++ class members. | |
3648 | For example: | |
3649 | </p> | |
3650 | ||
3651 | <div class="code"> | |
3652 | <pre> | |
3653 | double do_op(Object *o, double (Object::*callback)(double,double)); | |
3654 | extern double (Object::*fooptr)(double,double); | |
3655 | %constant double (Object::*FOO)(double,double) = &Object::foo; | |
3656 | </pre> | |
3657 | </div> | |
3658 | ||
3659 | <p> | |
3660 | Although these kinds of pointers can be parsed and represented by the | |
3661 | SWIG type system, few language modules know how to handle them due to | |
3662 | implementation differences from standard C pointers. Readers are | |
3663 | <em>strongly</em> advised to consult an advanced text such as the "The | |
3664 | Annotated C++ Manual" for specific details. | |
3665 | </p> | |
3666 | ||
3667 | <p> | |
3668 | When pointers to members are supported, the pointer value might appear as a special | |
3669 | string like this: | |
3670 | </p> | |
3671 | ||
3672 | <div class="targetlang"> | |
3673 | <pre> | |
3674 | >>> print example.FOO | |
3675 | _ff0d54a800000000_m_Object__f_double_double__double | |
3676 | >>> | |
3677 | </pre> | |
3678 | </div> | |
3679 | ||
3680 | <p> | |
3681 | In this case, the hexadecimal digits represent the entire value of the | |
3682 | pointer which is usually the contents of a small C++ structure on most | |
3683 | machines. | |
3684 | </p> | |
3685 | ||
3686 | <p> | |
3687 | SWIG's type-checking mechanism is also more limited when working with | |
3688 | member pointers. Normally SWIG tries to keep track of inheritance | |
3689 | when checking types. However, no such support is currently provided | |
3690 | for member pointers. | |
3691 | </p> | |
3692 | ||
3693 | <H2><a name="SWIGPlus_nn34"></a>6.22 Smart pointers and operator->()</H2> | |
3694 | ||
3695 | ||
3696 | <p> | |
3697 | In some C++ programs, objects are often encapsulated by smart-pointers | |
3698 | or proxy classes. This is sometimes done to implement automatic memory management (reference counting) or | |
3699 | persistence. Typically a smart-pointer is defined by a template class where | |
3700 | the <tt>-></tt> operator has been overloaded. This class is then wrapped | |
3701 | around some other class. For example: | |
3702 | </p> | |
3703 | ||
3704 | <div class="code"> | |
3705 | <pre> | |
3706 | // Smart-pointer class | |
3707 | template<class T> class SmartPtr { | |
3708 | T *pointee; | |
3709 | public: | |
3710 | ... | |
3711 | T *operator->() { | |
3712 | return pointee; | |
3713 | } | |
3714 | ... | |
3715 | }; | |
3716 | ||
3717 | // Ordinary class | |
3718 | class Foo_Impl { | |
3719 | public: | |
3720 | int x; | |
3721 | virtual void bar(); | |
3722 | ... | |
3723 | }; | |
3724 | ||
3725 | // Smart-pointer wrapper | |
3726 | typedef SmartPtr<Foo_Impl> Foo; | |
3727 | ||
3728 | // Create smart pointer Foo | |
3729 | Foo make_Foo() { | |
3730 | return SmartPtr(new Foo_Impl()); | |
3731 | } | |
3732 | ||
3733 | // Do something with smart pointer Foo | |
3734 | void do_something(Foo f) { | |
3735 | printf("x = %d\n", f->x); | |
3736 | f->bar(); | |
3737 | } | |
3738 | </pre> | |
3739 | </div> | |
3740 | ||
3741 | <p> | |
3742 | A key feature of this approach is that by defining | |
3743 | <tt>operator-></tt> the methods and attributes of the object | |
3744 | wrapped by a smart pointer are transparently accessible. For example, | |
3745 | expressions such as these (from the previous example), | |
3746 | </p> | |
3747 | ||
3748 | <div class="code"> | |
3749 | <pre> | |
3750 | f->x | |
3751 | f->bar() | |
3752 | </pre> | |
3753 | </div> | |
3754 | ||
3755 | <p> | |
3756 | are transparently mapped to the following | |
3757 | </p> | |
3758 | ||
3759 | <div class="code"> | |
3760 | <pre> | |
3761 | (f.operator->())->x; | |
3762 | (f.operator->())->bar(); | |
3763 | </pre> | |
3764 | </div> | |
3765 | ||
3766 | <p> | |
3767 | When generating wrappers, SWIG tries to emulate this functionality to | |
3768 | the extent that it is possible. To do this, whenever | |
3769 | <tt>operator->()</tt> is encountered in a class, SWIG looks at its | |
3770 | returned type and uses it to generate wrappers for accessing | |
3771 | attributes of the underlying object. For example, wrapping the above | |
3772 | code produces wrappers like this: | |
3773 | </p> | |
3774 | ||
3775 | <div class="code"> | |
3776 | <pre> | |
3777 | int Foo_x_get(Foo *f) { | |
3778 | return (*f)->x; | |
3779 | } | |
3780 | void Foo_x_set(Foo *f, int value) { | |
3781 | (*f)->x = value; | |
3782 | } | |
3783 | void Foo_bar(Foo *f) { | |
3784 | (*f)->bar(); | |
3785 | } | |
3786 | </pre> | |
3787 | </div> | |
3788 | ||
3789 | <p> | |
3790 | These wrappers take a smart-pointer instance as an argument, but | |
3791 | dereference it in a way to gain access to the object returned by | |
3792 | <tt>operator->()</tt>. You should carefully compare these wrappers | |
3793 | to those in the first part of this chapter (they are slightly | |
3794 | different). | |
3795 | </p> | |
3796 | ||
3797 | <p> | |
3798 | The end result is that access looks very similar to C++. For | |
3799 | example, you could do this in Python: | |
3800 | </p> | |
3801 | ||
3802 | <div class="targetlang"> | |
3803 | <pre> | |
3804 | >>> f = make_Foo() | |
3805 | >>> print f.x | |
3806 | 0 | |
3807 | >>> f.bar() | |
3808 | >>> | |
3809 | </pre> | |
3810 | </div> | |
3811 | ||
3812 | <p> | |
3813 | When generating wrappers through a smart-pointer, SWIG tries to | |
3814 | generate wrappers for all methods and attributes that might be | |
3815 | accessible through <tt>operator->()</tt>. This includes any methods | |
3816 | that might be accessible through inheritance. However, there are a number of restrictions: | |
3817 | </p> | |
3818 | ||
3819 | <ul> | |
3820 | <li>Member variables and methods are wrapped through a smart | |
3821 | pointer. Enumerations, constructors, and destructors are not wrapped. | |
3822 | </li> | |
3823 | ||
3824 | <li><p>If the smart-pointer class and the underlying object both define a method or | |
3825 | variable of the same name, then the smart-pointer version has precedence. For | |
3826 | example, if you have this code</p> | |
3827 | ||
3828 | <div class="code"> | |
3829 | <pre> | |
3830 | class Foo { | |
3831 | public: | |
3832 | int x; | |
3833 | }; | |
3834 | ||
3835 | class Bar { | |
3836 | public: | |
3837 | int x; | |
3838 | Foo *operator->(); | |
3839 | }; | |
3840 | </pre> | |
3841 | </div> | |
3842 | ||
3843 | <p> | |
3844 | then the wrapper for <tt>Bar::x</tt> accesses the <tt>x</tt> defined in <tt>Bar</tt>, and | |
3845 | not the <tt>x</tt> defined in <tt>Foo</tt>.</p> | |
3846 | </li> | |
3847 | </ul> | |
3848 | ||
3849 | <p> | |
3850 | If your intent is to only expose the smart-pointer class in the interface, it is not necessary to wrap both | |
3851 | the smart-pointer class and the class for the underlying object. However, you must still tell SWIG about both | |
3852 | classes if you want the technique described in this section to work. To only generate wrappers for the | |
3853 | smart-pointer class, you can use the %ignore directive. For example: | |
3854 | </p> | |
3855 | ||
3856 | <div class="code"> | |
3857 | <pre> | |
3858 | %ignore Foo; | |
3859 | class Foo { // Ignored | |
3860 | }; | |
3861 | ||
3862 | class Bar { | |
3863 | public: | |
3864 | Foo *operator->(); | |
3865 | ... | |
3866 | }; | |
3867 | </pre> | |
3868 | </div> | |
3869 | ||
3870 | <p> | |
3871 | Alternatively, you can import the definition of <tt>Foo</tt> from a separate file using | |
3872 | <tt>%import</tt>. | |
3873 | </p> | |
3874 | ||
3875 | <p> | |
3876 | <b>Note:</b> When a class defines <tt>operator->()</tt>, the operator itself is wrapped | |
3877 | as a method <tt>__deref__()</tt>. For example: | |
3878 | </p> | |
3879 | ||
3880 | <div class="targetlang"> | |
3881 | <pre> | |
3882 | f = Foo() # Smart-pointer | |
3883 | p = f.__deref__() # Raw pointer from operator-> | |
3884 | </pre> | |
3885 | </div> | |
3886 | ||
3887 | <p> | |
3888 | <b>Note:</b> To disable the smart-pointer behavior, use <tt>%ignore</tt> to ignore | |
3889 | <tt>operator->()</tt>. For example: | |
3890 | </p> | |
3891 | ||
3892 | <div class="code"> | |
3893 | <pre> | |
3894 | %ignore Bar::operator->; | |
3895 | </pre> | |
3896 | </div> | |
3897 | ||
3898 | <p> | |
3899 | <b>Note:</b> Smart pointer support was first added in SWIG-1.3.14. | |
3900 | </p> | |
3901 | ||
3902 | ||
3903 | <H2><a name="SWIGPlus_nn35"></a>6.23 Using declarations and inheritance</H2> | |
3904 | ||
3905 | ||
3906 | <p> | |
3907 | <tt>using</tt> declarations are sometimes used to adjust access to members of | |
3908 | base classes. For example: | |
3909 | </p> | |
3910 | ||
3911 | <div class="code"> | |
3912 | <pre> | |
3913 | class Foo { | |
3914 | public: | |
3915 | int blah(int x); | |
3916 | }; | |
3917 | ||
3918 | class Bar { | |
3919 | public: | |
3920 | double blah(double x); | |
3921 | }; | |
3922 | ||
3923 | class FooBar : public Foo, public Bar { | |
3924 | public: | |
3925 | using Foo::blah; | |
3926 | using Bar::blah; | |
3927 | char *blah(const char *x); | |
3928 | }; | |
3929 | </pre> | |
3930 | </div> | |
3931 | ||
3932 | <p> | |
3933 | In this example, the <tt>using</tt> declarations make different | |
3934 | versions of the overloaded <tt>blah()</tt> method accessible from the | |
3935 | derived class. For example: | |
3936 | </p> | |
3937 | ||
3938 | <div class="code"> | |
3939 | <pre> | |
3940 | FooBar *f; | |
3941 | f->blah(3); // Ok. Invokes Foo::blah(int) | |
3942 | f->blah(3.5); // Ok. Invokes Bar::blah(double) | |
3943 | f->blah("hello"); // Ok. Invokes FooBar::blah(const char *); | |
3944 | </pre> | |
3945 | </div> | |
3946 | ||
3947 | <p> | |
3948 | SWIG emulates the same functionality when creating wrappers. For example, if | |
3949 | you wrap this code in Python, the module works just like you would expect: | |
3950 | </p> | |
3951 | ||
3952 | <div class="targetlang"> | |
3953 | <pre> | |
3954 | >>> import example | |
3955 | >>> f = example.FooBar() | |
3956 | >>> f.blah(3) | |
3957 | >>> f.blah(3.5) | |
3958 | >>> f.blah("hello") | |
3959 | </pre> | |
3960 | </div> | |
3961 | ||
3962 | <p> | |
3963 | <tt>using</tt> declarations can also be used to change access when applicable. For example: | |
3964 | </p> | |
3965 | ||
3966 | <div class="code"> | |
3967 | <pre> | |
3968 | class Foo { | |
3969 | protected: | |
3970 | int x; | |
3971 | int blah(int x); | |
3972 | }; | |
3973 | ||
3974 | class Bar : public Foo { | |
3975 | public: | |
3976 | using Foo::x; // Make x public | |
3977 | using Foo::blah; // Make blah public | |
3978 | }; | |
3979 | </pre> | |
3980 | </div> | |
3981 | ||
3982 | <p> | |
3983 | This also works in SWIG---the exposed declarations will be wrapped normally. | |
3984 | </p> | |
3985 | ||
3986 | <p> | |
3987 | When <tt>using</tt> declarations are used as shown in these examples, declarations | |
3988 | from the base classes are copied into the derived class and wrapped normally. When | |
3989 | copied, the declarations retain any properties that might have been attached using | |
3990 | <tt>%rename</tt>, <tt>%ignore</tt>, or <tt>%feature</tt>. Thus, if a method is | |
3991 | ignored in a base class, it will also be ignored by a <tt>using</tt> declaration. | |
3992 | </p> | |
3993 | ||
3994 | <p> | |
3995 | Because a <tt>using</tt> declaration does not provide fine-grained | |
3996 | control over the declarations that get imported, it may be difficult | |
3997 | to manage such declarations in applications that make heavy use of | |
3998 | SWIG customization features. If you can't get <tt>using</tt> to work | |
3999 | correctly, you can always change the interface to the following: | |
4000 | </p> | |
4001 | ||
4002 | <div class="code"> | |
4003 | <pre> | |
4004 | ||
4005 | class FooBar : public Foo, public Bar { | |
4006 | public: | |
4007 | #ifndef SWIG | |
4008 | using Foo::blah; | |
4009 | using Bar::blah; | |
4010 | #else | |
4011 | int blah(int x); // explicitly tell SWIG about other declarations | |
4012 | double blah(double x); | |
4013 | #endif | |
4014 | ||
4015 | char *blah(const char *x); | |
4016 | }; | |
4017 | </pre> | |
4018 | </div> | |
4019 | ||
4020 | <p> | |
4021 | <b>Notes:</b> | |
4022 | </p> | |
4023 | ||
4024 | <ul> | |
4025 | <li><p>If a derived class redefines a method defined in a base class, then a <tt>using</tt> declaration | |
4026 | won't cause a conflict. For example:</p> | |
4027 | ||
4028 | <div class="code"> | |
4029 | <pre> | |
4030 | class Foo { | |
4031 | public: | |
4032 | int blah(int ); | |
4033 | double blah(double); | |
4034 | }; | |
4035 | ||
4036 | class Bar : public Foo { | |
4037 | public: | |
4038 | using Foo::blah; // Only imports blah(double); | |
4039 | int blah(int); | |
4040 | }; | |
4041 | </pre> | |
4042 | </div> | |
4043 | ||
4044 | <li><p>Resolving ambiguity in overloading may prevent declarations from being | |
4045 | imported by <tt>using</tt>. For example: | |
4046 | </p> | |
4047 | ||
4048 | <div class="code"> | |
4049 | <pre> | |
4050 | %rename(blah_long) Foo::blah(long); | |
4051 | class Foo { | |
4052 | public: | |
4053 | int blah(int); | |
4054 | long blah(long); // Renamed to blah_long | |
4055 | }; | |
4056 | ||
4057 | class Bar : public Foo { | |
4058 | public: | |
4059 | using Foo::blah; // Only imports blah(int) | |
4060 | double blah(double x); | |
4061 | }; | |
4062 | </pre> | |
4063 | </div> | |
4064 | </ul> | |
4065 | ||
4066 | <H2><a name="SWIGPlus_nn36"></a>6.24 Partial class definitions</H2> | |
4067 | ||
4068 | ||
4069 | <p> | |
4070 | Since SWIG is still limited in its support of C++, it may be necessary | |
4071 | to use partial class information in an interface file. However, since | |
4072 | SWIG does not need the entire class specification to work, conditional | |
4073 | compilation can be used to comment out problematic parts. For example, if you had a nested | |
4074 | class definition, you might do this: | |
4075 | </p> | |
4076 | ||
4077 | <div class="code"> | |
4078 | <pre> | |
4079 | class Foo { | |
4080 | public: | |
4081 | #ifndef SWIG | |
4082 | class Bar { | |
4083 | public: | |
4084 | ... | |
4085 | }; | |
4086 | #endif | |
4087 | Foo(); | |
4088 | ~Foo(); | |
4089 | ... | |
4090 | }; | |
4091 | </pre> | |
4092 | </div> | |
4093 | ||
4094 | <p> | |
4095 | Also, as a rule of thumb, SWIG should not be used on raw C++ source | |
4096 | files. | |
4097 | </p> | |
4098 | ||
4099 | <H2><a name="SWIGPlus_nn37"></a>6.25 A brief rant about const-correctness</H2> | |
4100 | ||
4101 | ||
4102 | <p> | |
4103 | A common issue when working with C++ programs is dealing with all | |
4104 | possible ways in which the <tt>const</tt> qualifier (or lack thereof) | |
4105 | will break your program, all programs linked against your program, and | |
4106 | all programs linked against those programs. | |
4107 | </p> | |
4108 | ||
4109 | <p> | |
4110 | Although SWIG knows how to correctly deal with <tt>const</tt> in its | |
4111 | internal type system and it knows how to generate wrappers that are | |
4112 | free of const-related warnings, SWIG does not make any attempt to preserve | |
4113 | const-correctness in the target language. Thus, it is possible to | |
4114 | pass <tt>const</tt> qualified objects to non-const methods and functions. | |
4115 | For example, consider the following code in C++: | |
4116 | </p> | |
4117 | ||
4118 | <div class="code"> | |
4119 | <pre> | |
4120 | const Object * foo(); | |
4121 | void bar(Object *); | |
4122 | ||
4123 | ... | |
4124 | // C++ code | |
4125 | void blah() { | |
4126 | bar(foo()); // Error: bar discards const | |
4127 | }; | |
4128 | </pre> | |
4129 | </div> | |
4130 | ||
4131 | <p> | |
4132 | Now, consider the behavior when wrapped into a Python module: | |
4133 | </p> | |
4134 | ||
4135 | <div class="targetlang"> | |
4136 | <pre> | |
4137 | >>> bar(foo()) # Okay | |
4138 | >>> | |
4139 | </pre> | |
4140 | </div> | |
4141 | ||
4142 | <p> | |
4143 | Although this is clearly a violation of the C++ type-system, fixing | |
4144 | the problem doesn't seem to be worth the added implementation | |
4145 | complexity that would be required to support it in the SWIG run-time type | |
4146 | system. There are no plans to change this in future releases | |
4147 | (although we'll never rule anything out entirely). | |
4148 | </p> | |
4149 | ||
4150 | <p> | |
4151 | The bottom line is that this particular issue does not appear to be a problem | |
4152 | for most SWIG projects. Of course, you might want to consider | |
4153 | using another tool if maintaining constness is the most important part | |
4154 | of your project. | |
4155 | </p> | |
4156 | ||
4157 | <H2><a name="SWIGPlus_nn38"></a>6.26 Proxy classes</H2> | |
4158 | ||
4159 | ||
4160 | <p> | |
4161 | In order to provide a more natural API, SWIG's target | |
4162 | languages wrap C++ classes with special proxy classes. These | |
4163 | proxy classes are typically implemented in the target language itself. | |
4164 | For example, if you're building a Python module, each C++ class is | |
4165 | wrapped by a Python class. Or if you're building a Java module, each | |
4166 | C++ class is wrapped by a Java class. | |
4167 | </p> | |
4168 | ||
4169 | <H3><a name="SWIGPlus_nn39"></a>6.26.1 Construction of proxy classes</H3> | |
4170 | ||
4171 | ||
4172 | <p> | |
4173 | Proxy classes are always constructed as an extra layer of wrapping that uses the low-level | |
4174 | accessor functions described in the previous section. To illustrate, suppose you had a | |
4175 | C++ class like this: | |
4176 | </p> | |
4177 | ||
4178 | <div class="code"> | |
4179 | <pre> | |
4180 | class Foo { | |
4181 | public: | |
4182 | Foo(); | |
4183 | ~Foo(); | |
4184 | int bar(int x); | |
4185 | int x; | |
4186 | }; | |
4187 | </pre> | |
4188 | </div> | |
4189 | ||
4190 | <p> | |
4191 | Using C++ as pseudocode, a proxy class looks something like this: | |
4192 | </p> | |
4193 | ||
4194 | <div class="code"> | |
4195 | <pre> | |
4196 | class FooProxy { | |
4197 | private: | |
4198 | Foo *self; | |
4199 | public: | |
4200 | FooProxy() { | |
4201 | self = new_Foo(); | |
4202 | } | |
4203 | ~FooProxy() { | |
4204 | delete_Foo(self); | |
4205 | } | |
4206 | int bar(int x) { | |
4207 | return Foo_bar(self,x); | |
4208 | } | |
4209 | int x_get() { | |
4210 | return Foo_x_get(self); | |
4211 | } | |
4212 | void x_set(int x) { | |
4213 | Foo_x_set(self,x); | |
4214 | } | |
4215 | }; | |
4216 | </pre> | |
4217 | </div> | |
4218 | ||
4219 | <p> | |
4220 | Of course, always keep in mind that the real proxy class is written in the target language. | |
4221 | For example, in Python, the proxy might look roughly like this: | |
4222 | </p> | |
4223 | ||
4224 | <div class="targetlang"> | |
4225 | <pre> | |
4226 | class Foo: | |
4227 | def __init__(self): | |
4228 | self.this = new_Foo() | |
4229 | def __del__(self): | |
4230 | delete_Foo(self.this) | |
4231 | def bar(self,x): | |
4232 | return Foo_bar(self.this,x) | |
4233 | def __getattr__(self,name): | |
4234 | if name == 'x': | |
4235 | return Foo_x_get(self.this) | |
4236 | ... | |
4237 | def __setattr__(self,name,value): | |
4238 | if name == 'x': | |
4239 | Foo_x_set(self.this,value) | |
4240 | ... | |
4241 | </pre> | |
4242 | </div> | |
4243 | ||
4244 | <p> | |
4245 | Again, it's important to emphasize that the low-level accessor functions are always used to construct the | |
4246 | proxy classes. | |
4247 | </p> | |
4248 | ||
4249 | <p> | |
4250 | Whenever possible, proxies try to take advantage of language features that are similar to C++. This | |
4251 | might include operator overloading, exception handling, and other features. | |
4252 | </p> | |
4253 | ||
4254 | <H3><a name="SWIGPlus_nn40"></a>6.26.2 Resource management in proxies</H3> | |
4255 | ||
4256 | ||
4257 | <p> | |
4258 | A major issue with proxies concerns the memory management of wrapped objects. Consider the following | |
4259 | C++ code: | |
4260 | </p> | |
4261 | ||
4262 | <div class="code"> | |
4263 | <pre> | |
4264 | class Foo { | |
4265 | public: | |
4266 | Foo(); | |
4267 | ~Foo(); | |
4268 | int bar(int x); | |
4269 | int x; | |
4270 | }; | |
4271 | ||
4272 | class Spam { | |
4273 | public: | |
4274 | Foo *value; | |
4275 | ... | |
4276 | }; | |
4277 | </pre> | |
4278 | </div> | |
4279 | ||
4280 | <p> | |
4281 | Now, consider some script code that uses these classes: | |
4282 | </p> | |
4283 | ||
4284 | <div class="targetlang"> | |
4285 | <pre> | |
4286 | f = Foo() # Creates a new Foo | |
4287 | s = Spam() # Creates a new Spam | |
4288 | s.value = f # Stores a reference to f inside s | |
4289 | g = s.value # Returns stored reference | |
4290 | g = 4 # Reassign g to some other value | |
4291 | del f # Destroy f | |
4292 | </pre> | |
4293 | </div> | |
4294 | ||
4295 | <p> | |
4296 | Now, ponder the resulting memory management issues. When objects are | |
4297 | created in the script, the objects are wrapped by newly created proxy | |
4298 | classes. That is, there is both a new proxy class instance and a new | |
4299 | instance of the underlying C++ class. In this example, both | |
4300 | <tt>f</tt> and <tt>s</tt> are created in this way. However, the | |
4301 | statement <tt>s.value</tt> is rather curious---when executed, a | |
4302 | pointer to <tt>f</tt> is stored inside another object. This means | |
4303 | that the scripting proxy class <em>AND</em> another C++ class share a | |
4304 | reference to the same object. To make matters even more interesting, | |
4305 | consider the statement <tt>g = s.value</tt>. When executed, this | |
4306 | creates a new proxy class <tt>g</tt> that provides a wrapper around the | |
4307 | C++ object stored in <tt>s.value</tt>. In general, there is no way to | |
4308 | know where this object came from---it could have been created by the | |
4309 | script, but it could also have been generated internally. In this | |
4310 | particular example, the assignment of <tt>g</tt> results in a second | |
4311 | proxy class for <tt>f</tt>. In other words, a reference to <tt>f</tt> | |
4312 | is now shared by two proxy classes <em>and</em> a C++ class. | |
4313 | </p> | |
4314 | ||
4315 | <p> | |
4316 | Finally, consider what happens when objects are destroyed. In the | |
4317 | statement, <tt>g=4</tt>, the variable <tt>g</tt> is reassigned. In | |
4318 | many languages, this makes the old value of <tt>g</tt> available for | |
4319 | garbage collection. Therefore, this causes one of the proxy classes | |
4320 | to be destroyed. Later on, the statement <tt>del f</tt> destroys the | |
4321 | other proxy class. Of course, there is still a reference to the | |
4322 | original object stored inside another C++ object. What happens to it? | |
4323 | Is it the object still valid? | |
4324 | </p> | |
4325 | ||
4326 | <p> | |
4327 | To deal with memory management problems, proxy classes always provide an API | |
4328 | for controlling ownership. In C++ pseudocode, ownership control might look | |
4329 | roughly like this: | |
4330 | </p> | |
4331 | ||
4332 | <div class="code"> | |
4333 | <pre> | |
4334 | class FooProxy { | |
4335 | public: | |
4336 | Foo *self; | |
4337 | int thisown; | |
4338 | ||
4339 | FooProxy() { | |
4340 | self = new_Foo(); | |
4341 | thisown = 1; // Newly created object | |
4342 | } | |
4343 | ~FooProxy() { | |
4344 | if (thisown) delete_Foo(self); | |
4345 | } | |
4346 | ... | |
4347 | // Ownership control API | |
4348 | void disown() { | |
4349 | thisown = 0; | |
4350 | } | |
4351 | void acquire() { | |
4352 | thisown = 1; | |
4353 | } | |
4354 | }; | |
4355 | ||
4356 | class FooPtrProxy: public FooProxy { | |
4357 | public: | |
4358 | FooPtrProxy(Foo *s) { | |
4359 | self = s; | |
4360 | thisown = 0; | |
4361 | } | |
4362 | }; | |
4363 | ||
4364 | class SpamProxy { | |
4365 | ... | |
4366 | FooProxy *value_get() { | |
4367 | return FooPtrProxy(Spam_value_get(self)); | |
4368 | } | |
4369 | void value_set(FooProxy *v) { | |
4370 | Spam_value_set(self,v->self); | |
4371 | v->disown(); | |
4372 | } | |
4373 | ... | |
4374 | }; | |
4375 | </pre> | |
4376 | </div> | |
4377 | ||
4378 | <p> | |
4379 | Looking at this code, there are a few central features: | |
4380 | </p> | |
4381 | ||
4382 | <ul> | |
4383 | <li>Each proxy class keeps an extra flag to indicate ownership. C++ objects are only destroyed | |
4384 | if the ownership flag is set. | |
4385 | </li> | |
4386 | ||
4387 | <li>When new objects are created in the target language, the ownership flag is set. | |
4388 | </li> | |
4389 | ||
4390 | <li>When a reference to an internal C++ object is returned, it is wrapped by a proxy | |
4391 | class, but the proxy class does not have ownership. | |
4392 | </li> | |
4393 | ||
4394 | <li>In certain cases, ownership is adjusted. For instance, when a value is assigned to the member of | |
4395 | a class, ownership is lost. | |
4396 | </li> | |
4397 | ||
4398 | <li>Manual ownership control is provided by special <tt>disown()</tt> and <tt>acquire()</tt> methods. | |
4399 | </li> | |
4400 | </ul> | |
4401 | ||
4402 | <p> | |
4403 | Given the tricky nature of C++ memory management, it is impossible for proxy classes to automatically handle | |
4404 | every possible memory management problem. However, proxies do provide a mechanism for manual control that | |
4405 | can be used (if necessary) to address some of the more tricky memory management problems. | |
4406 | </p> | |
4407 | ||
4408 | <H3><a name="SWIGPlus_nn41"></a>6.26.3 Language specific details</H3> | |
4409 | ||
4410 | ||
4411 | <p> | |
4412 | Language specific details on proxy classes are contained in the chapters describing each target language. This | |
4413 | chapter has merely introduced the topic in a very general way. | |
4414 | </p> | |
4415 | ||
4416 | <H2><a name="SWIGPlus_nn42"></a>6.27 Where to go for more information</H2> | |
4417 | ||
4418 | ||
4419 | <p> | |
4420 | If you're wrapping serious C++ code, you might want to pick up a copy | |
4421 | of "The Annotated C++ Reference Manual" by Ellis and Stroustrup. This | |
4422 | is the reference document we use to guide a lot of SWIG's C++ support. | |
4423 | </p> | |
4424 | ||
4425 | </body> | |
4426 | </html> | |
4427 | ||
4428 | <!-- LocalWords: destructors Enums Namespaces const SWIG's STL OO adaptor tcl | |
4429 | --> | |
4430 | <!-- LocalWords: debuggable cxx OBJS Wiki accessor nodefault makedefault | |
4431 | --> | |
4432 | <!-- LocalWords: notabstract CopyFoo | |
4433 | --> |