Initial commit of OpenSPARC T2 architecture model.
[OpenSPARC-T2-SAM] / sam-t2 / devtools / v8plus / html / swig / SWIGPlus.html
CommitLineData
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-&gt;()</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>
67This chapter describes SWIG's support for wrapping C++. As a prerequisite,
68you should first read the chapter <a href="SWIG.html#SWIG">SWIG Basics</a> to see
69how SWIG wraps ANSI C. Support for C++ builds upon ANSI C
70wrapping 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>
77Because of its complexity and the fact that C++ can be
78difficult to integrate with itself let alone other languages, SWIG
79only provides support for a subset of C++ features. Fortunately,
80this is now a rather large subset.
81</p>
82
83<p>
84In part, the problem with C++ wrapping is that there is no
85semantically obvious (or automatic ) way to map many of its advanced
86features into other languages. As a simple example, consider the
87problem of wrapping C++ multiple inheritance to a target language with
88no such support. Similarly, the use of overloaded operators and
89overloaded functions can be problematic when no such capability exists
90in a target language.
91</p>
92
93<p>
94A more subtle issue with C++ has to do with the way that some C++
95programmers think about programming libraries. In the world of SWIG,
96you are really trying to create binary-level software components for
97use in other languages. In order for this to work, a "component" has
98to contain real executable instructions and there has to be some kind
99of binary linking mechanism for accessing its functionality. In
100contrast, C++ has increasingly relied upon generic programming and
101templates for much of its functionality.
102Although templates are a powerful feature, they are largely orthogonal
103to the whole notion of binary components and libraries. For example,
104an STL <tt>vector</tt> does not define any kind of binary object for
105which SWIG can just create a wrapper. To further complicate matters,
106these libraries often utilize a lot of behind the scenes magic in
107which the semantics of seemingly basic operations (e.g., pointer
108dereferencing, procedure call, etc.) can be changed in dramatic and
109sometimes non-obvious ways. Although this "magic" may present few
110problems in a C++-only universe, it greatly complicates the problem of
111crossing language boundaries and provides many opportunities to shoot
112yourself 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>
119To wrap C++, SWIG uses a layered approach to code generation.
120At the lowest level, SWIG generates a collection of procedural ANSI-C style
121wrappers. These wrappers take care of basic type conversion,
122type checking, error handling, and other low-level details of the C++ binding.
123These wrappers are also sufficient to bind C++ into any target language
124that supports built-in procedures. In some sense, you might view this
125layer of wrapping as providing a C library interface to C++.
126Optionally, SWIG can also generate proxy classes
127that provide a natural OO interface to the underlying code. These proxies
128are built on top of the low-level procedural wrappers and are typically
129written in the target language itself. For instance, in Python, a real
130Python class is used to provide a wrapper around the underlying C++ object.
131</p>
132
133<p>
134It is important to emphasize that SWIG takes a deliberately
135conservative and non-intrusive approach to C++ wrapping. SWIG does not
136encapsulate C++ classes inside special C++ adaptor or proxy classes,
137it does not rely upon templates, nor does it use C++ inheritance when
138generating wrappers. The last thing that most C++ programs need is
139even more compiler magic. Therefore, SWIG tries to maintain a very
140strict and clean separation between the implementation of your C++
141application and the resulting wrapper code. You might say that SWIG
142has been written to follow the principle of least surprise--it does
143not play sneaky tricks with the C++ type system, it doesn't mess with
144your class hierarchies, and it doesn't introduce new semantics.
145Although this approach might not provide the most seamless integration
146with C++, it is safe, simple, portable, and debuggable.
147</p>
148
149<p>
150Most of this chapter focuses on the low-level procedural interface to
151C++ that is used as the foundation for all language modules. Keep in
152mind that most target languages also provide a high-level OO interface via
153proxy classes. A few general details about proxies can be found at the end of
154this chapter. However, more detailed coverage can be found in the documentation
155for each target language.
156</p>
157
158<H2><a name="SWIGPlus_nn4"></a>6.3 Supported C++ features</H2>
159
160
161<p>
162SWIG'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>
179The 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>
187SWIG's C++ support is an ongoing project so some of these limitations may be lifted
188in future releases. However, we make no promises. Also, submitting a bug report is a very
189good 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>
196When 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
198features such as memory management are handled. It
199also enables the recognition of C++ keywords. Without the <tt>-c++</tt>
200flag, SWIG will either issue a warning or a large number of syntax
201errors if it encounters C++ code in an interface file.</p>
202
203<p>
204When compiling and linking the resulting wrapper file, it is normal
205to 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>
217Unfortunately, the process varies slightly on each machine. Make sure
218you refer to the documentation on each target language for further
219details. 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>
226The following code shows a SWIG interface file for a simple C++
227class.</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
237class List {
238public:
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;
246static void print(List *l);
247};
248</pre></div>
249
250<p>
251To generate wrappers for this class, SWIG first reduces the class to a collection of low-level C-style
252accessor functions. The next few sections describe this process. Later parts of the chapter describe a higher
253level 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>
260C++ constructors and destructors are translated into accessor
261functions such as the following :</p>
262
263<div class="code"><pre>
264List * new_List(void) {
265 return new List;
266}
267void 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>
277If a C++ class does not define any public constructors or
278destructors, SWIG will automatically create a default constructor or
279destructor. 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
287inherit 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
291default constructor.
292</li>
293
294<li>Default constructors and destructors are not created if a class
295defines 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
299class defines a private default constructor or a private destructor.
300</li>
301</ul>
302
303<p>
304SWIG should never generate a constructor or destructor for a class in which
305it is illegal to do so. However, if it is necessary to disable the
306default constructor/destructor creation, the <tt>%nodefault</tt> directive
307can be used:
308</p>
309
310<div class="code">
311<pre>
312%nodefault; // Disable creation of constructor/destructor
313class 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
332constructors/destructors was made the default behavior in SWIG
3331.3.7. This may break certain older modules, but the old behavior can
334be easily restored using <tt>%nodefault</tt> or the
335<tt>-nodefault</tt> command line option. Furthermore, in order for
336SWIG to properly generate (or not generate) default constructors, it
337must 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
339protected constructor/destructor is defined). In older versions of
340SWIG, it was fairly common to simply remove or comment out
341the private and protected sections of a class due to parser limitations.
342However, this removal may now cause SWIG to erroneously generate constructors
343for classes that define a constructor in those sections. Consider restoring
344those 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>
351If a class defines a constructor, SWIG normally tries to generate a wrapper for it. However, SWIG will
352not generate a constructor wrapper if it thinks that it will result in illegal wrapper code. There are really
353two cases where this might show up.
354</p>
355
356<p>
357First, SWIG won't generate wrappers for protected or private constructors. For example:
358</p>
359
360<div class="code">
361<pre>
362class Foo {
363protected:
364 Foo(); // Not wrapped.
365public:
366 ...
367};
368</pre>
369</div>
370
371<p>
372Next, SWIG won't generate wrappers for a class if it appears to be abstract--that is, it has undefined
373pure virtual methods. Here are some examples:
374</p>
375
376<div class="code">
377<pre>
378class Bar {
379public:
380 Bar(); // Not wrapped. Bar is abstract.
381 virtual void spam(void) = 0;
382};
383
384class Grok : public Bar {
385public:
386 Grok(); // Not wrapped. No implementation of abstract spam().
387};
388</pre>
389</div>
390
391<p>
392Some users are surprised (or confused) to find missing constructor wrappers in their interfaces. In almost
393all cases, this is caused when classes are determined to be abstract. To see if this is the case, run SWIG with
394all 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>
404In this mode, SWIG will issue a warning for all abstract classes. It is possible to force a class to be
405non-abstract using this:
406</p>
407
408<div class="code">
409<pre>
410%feature("notabstract") Foo;
411
412class Foo : public Bar {
413public:
414 Foo(); // Generated no matter what---not abstract.
415 ...
416};
417</pre>
418</div>
419
420<p>
421More 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>
428If a class defines more than one constructor, its behavior depends on the capabilities of the
429target language. If overloading is supported, the copy constructor is accessible using
430the normal constructor function. For example, if you have this:
431</p>
432
433<div class="code">
434<pre>
435class List {
436public:
437 List();
438 List(const List &amp;); // Copy constructor
439 ...
440};
441</pre>
442</div>
443
444<p>
445then the copy constructor can be used as follows:
446</p>
447
448<div class="targetlang">
449<pre>
450x = new_List() # Create a list
451y = new_List(x) # Copy list x
452</pre>
453</div>
454
455<p>
456If the target language does not support overloading, then the copy constructor is available
457through a special function like this:
458</p>
459
460<div class="code">
461<pre>
462List *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
470a 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
472defined, only the first definition that appears is used as the copy
473constructor--other definitions will result in a name-clash.
474Constructors such as <tt>X(const X &amp;)</tt>, <tt>X(X &amp;)</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
480wrapper unless one is explicitly declared in the class. This differs
481from the treatment of default constructors and destructors.
482</p>
483
484<p>
485<b>Compatibility note:</b> Special support for copy constructors was
486not added until SWIG-1.3.12. In previous versions, copy constructors
487could be wrapped, but they had to be renamed. For example:
488</p>
489
490<div class="code">
491<pre>
492class Foo {
493public:
494 Foo();
495 %name(CopyFoo) Foo(const Foo &amp;);
496 ...
497};
498</pre>
499</div>
500
501<p>
502For backwards compatibility, SWIG does not perform any special
503copy-constructor handling if the constructor has been manually
504renamed. For instance, in the above example, the name of the
505constructor is set to <tt>new_CopyFoo()</tt>. This is the same as in
506older versions.
507</p>
508
509<H3><a name="SWIGPlus_nn11"></a>6.5.5 Member functions</H3>
510
511
512<p>
513All member functions are roughly translated into accessor functions like this :</p>
514
515<div class="code"><pre>
516int List_search(List *obj, char *value) {
517 return obj-&gt;search(value);
518}
519
520</pre></div>
521
522<p>
523This translation is the same even if the member function has been
524declared as <tt>virtual</tt>.
525</p>
526
527<p>
528It should be noted that SWIG does not <em>actually</em> create a C accessor
529function in the code it generates. Instead, member access such as
530<tt>obj-&gt;search(value)</tt> is directly inlined into the generated
531wrapper functions. However, the name and calling convention of the
532wrappers 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>
539Static member functions are called directly without making any special
540transformations. For example, the static member function
541<tt>print(List *l)</tt> directly invokes <tt>List::print(List *l)</tt>
542in the generated wrapper code.
543</p>
544
545<p>
546Usually, static members are accessed as functions with names in which the class name has been
547prepended 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>
554Member data is handled in exactly the same manner as for C
555structures. A pair of accessor functions are created. For example
556:</p>
557
558<div class="code"><pre>
559int List_length_get(List *obj) {
560 return obj-&gt;length;
561}
562int List_length_set(List *obj, int value) {
563 obj-&gt;length = value;
564 return value;
565}
566
567</pre></div>
568
569<p>
570A read-only member can be created using the <tt>%immutable</tt> and
571<tt>%mutable</tt> directives. For example, we probably wouldn't want
572the user to change the length of a list so we could do the following
573to make the value available, but read-only.</p>
574
575<div class="code"><pre>
576class List {
577public:
578...
579%immutable;
580 int length;
581%mutable;
582...
583};
584</pre></div>
585
586<p>
587Alternatively, you can specify an immutable member in advance like this:
588</p>
589
590<div class="code">
591<pre>
592%immutable List::length;
593...
594class List {
595 ...
596 int length; // Immutable by above directive
597 ...
598};
599</pre>
600</div>
601
602<p>
603Similarly, all data attributes declared as <tt>const</tt> are wrapped as read-only members.
604</p>
605
606<p>
607There are some subtle issues when wrapping data members that are
608themselves classes. For instance, if you had another class like this,
609</p>
610
611<div class="code">
612<pre>
613class Foo {
614public:
615 List items;
616 ...
617</pre>
618</div>
619
620<p>
621then access to the <tt>items</tt> member actually uses pointers. For example:
622</p>
623
624<div class="code">
625<pre>
626List *Foo_items_get(Foo *self) {
627 return &amp;self-&gt;items;
628}
629void Foo_items_set(Foo *self, List *value) {
630 self-&gt;items = *value;
631}
632</pre>
633</div>
634
635<p>
636More information about this can be found in the "Structure data
637members" 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
643generate 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
649wrapped into accessor functions using pointers. For example, if you had a structure
650like this
651</p>
652
653<div class="code">
654<pre>
655struct Foo {
656 size_t len;
657};
658</pre>
659</div>
660
661<p>
662and nothing was known about <tt>size_t</tt>, then accessors would be
663written to work with <tt>size_t *</tt>. Starting in SWIG-1.3.12, this
664behavior has been modified. Specifically, pointers will <em>only</em>
665be used if SWIG knows that a datatype corresponds to a structure or
666class. Therefore, the above code would be wrapped into accessors
667involving <tt>size_t</tt>. This change is subtle, but it smooths over
668a few problems related to structure wrapping and some of SWIG's
669customization features.
670</p>
671
672<H2><a name="SWIGPlus_default_args"></a>6.6 Default arguments</H2>
673
674
675<p>
676SWIG will wrap all types of functions that have default arguments. For example member functions:
677</p>
678
679<div class="code">
680<pre>
681class Foo {
682public:
683 void bar(int x, int y = 3, int z = 4);
684};
685</pre>
686</div>
687
688<p>
689SWIG handles default arguments by generating an extra overloaded method for each defaulted argument.
690SWIG is effectively handling methods with default arguments as if it had wrapped the equivalent overloaded methods.
691Thus 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>
696class Foo {
697public:
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>
706The wrappers produced are exactly the same as if the above code was instead fed into SWIG.
707Details of this is covered later in the <a href="#SWIGPlus_overloaded_methods">Wrapping Overloaded Functions and Methods</a> section.
708This approach allows SWIG to wrap all possible default arguments, but can be verbose.
709For example if a method has ten default arguments, then eleven wrapper methods are generated.
710</p>
711
712<p>
713Please see the <a href="Customization.html#Customization_features_default_args">Features and default arguments</a>
714section for more information on using <tt>%feature</tt> with functions with default arguments.
715The <a href="#ambiguity_resolution_renaming">Ambiguity resolution and renaming</a> section
716also deals with using <tt>%rename</tt> and <tt>%ignore</tt> on methods with default arguments.
717If 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.
718See the <a href="Typemaps.html#Typemaps_overloading">Typemaps and overloading</a> section for details or otherwise
719use 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.
724Instead a single wrapper method was generated and the default values were copied into the C++ wrappers
725so that the method being wrapped was then called with all the arguments specified.
726If the size of the wrappers are a concern then this approach to wrapping methods with default arguments
727can 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;
733class Foo {
734public:
735 void bar(int x, int y = 3, int z = 4);
736};
737</pre>
738</div>
739
740
741<p>
742This is great for reducing the size of the wrappers, but the caveat is it does not work for the strongly typed languages
743which don't have optional arguments in the language, such as C# and Java.
744Another restriction of this feature is that it cannot handle default arguments that are not public.
745The following example illustrates this:
746</p>
747
748<div class="code">
749<pre>
750class Foo {
751private:
752 static const int spam;
753public:
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>
761This produces uncompileable wrapper code because default values in C++ are
762evaluated in the same scope as the member function whereas SWIG
763evaluates them in the scope of a wrapper function (meaning that the
764values have to be public).
765</p>
766
767<p>
768This feature is automatically turned on when wrapping <a href="SWIG.html#SWIG_default_args">C code with default arguments</a>
769and whenever keyword arguments (kwargs) are specified for either C or C++ code.
770Keyword arguments are a language feature of some scripting languages, for example Ruby and Python.
771SWIG 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>
789By default, members of a class definition are assumed to be private
790until you explicitly give a `<tt>public:</tt>' declaration (This is
791the 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>
798Enumerations and constants are handled differently by the different language modules and are described in detail in the appropriate language chapter.
799However, many languages map enums and constants in a class definition
800into constants with the classname as a prefix. For example :</p>
801
802<div class="code"><pre>
803class Swig {
804public:
805 enum {ALE, LAGER, PORTER, STOUT};
806};
807
808</pre></div>
809<p>
810Generates the following set of constants in the target scripting language :</p>
811
812<div class="targetlang"><pre>
813Swig_ALE = Swig::ALE
814Swig_LAGER = Swig::LAGER
815Swig_PORTER = Swig::PORTER
816Swig_STOUT = Swig::STOUT
817
818</pre></div>
819
820<p>
821Members 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>
828Friend declarations are not longer ignored by SWIG. For example, if
829you have this code:
830</p>
831
832<div class="code">
833<pre>
834class Foo {
835public:
836 ...
837 friend void blah(Foo *f);
838 ...
839};
840</pre>
841</div>
842
843<p>
844then the <tt>friend</tt> declaration does result in a wrapper code
845equivalent to one generated for the following declaration
846</p>
847
848<div class="code">
849<pre>
850class Foo {
851public:
852 ...
853};
854
855void blah(Foo *f);
856</pre>
857</div>
858
859<p>
860A friend declaration, as in C++, is understood to be in the same scope
861where 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
869namespace bar {
870
871 class Foo {
872 public:
873 ...
874 friend void blah(Foo *f);
875 ...
876 };
877}
878</pre>
879</div>
880
881<p>
882and 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>
889C++ references are supported, but SWIG transforms them back into pointers. For example,
890a declaration like this :</p>
891
892<div class="code"><pre>
893class Foo {
894public:
895 double bar(double &amp;a);
896}
897</pre></div>
898
899<p>
900is accessed using a function similar to this:</p>
901
902<div class="code"><pre>
903double Foo_bar(Foo *obj, double *a) {
904 obj-&gt;bar(*a);
905}
906</pre></div>
907
908<p>
909As 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>
915void foo(const int &amp;x);
916</pre>
917</div>
918
919<p>
920it is called from a script as follows:
921</p>
922
923<div class="targetlang">
924<pre>
925foo(3) # Notice pass by value
926</pre>
927</div>
928
929<p>
930Functions that return a reference are remapped to return a pointer instead.
931For example:
932</p>
933
934<div class="code"><pre>
935class Bar {
936public:
937 Foo &amp;spam();
938};
939</pre>
940</div>
941
942<p>
943Generates code like this:
944</p>
945
946<div class="code">
947<pre>
948Foo *Bar_spam(Bar *obj) {
949 Foo &amp;result = obj-&gt;spam();
950 return &amp;result;
951}
952</pre>
953</div>
954
955<p>
956However, functions that return <tt>const</tt> references to primitive datatypes (<tt>int</tt>, <tt>short</tt>, etc.) normally
957return the result as a value rather than a pointer. For example, a function like this,
958</p>
959
960<div class="code">
961<pre>
962const int &amp;bar();
963</pre>
964</div>
965
966<p>
967will return integers such as 37 or 42 in the target scripting language rather than a pointer to an integer.
968</p>
969
970<P>
971Don't return references to objects allocated as local variables on the
972stack. SWIG doesn't make a copy of the objects so this will probably
973cause 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
979more seamless integration with more advanced C++ wrapping applications---especially related to
980templates 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>
988Occasionally, a C++ program will pass and return class objects by value. For example, a function
989like this might appear:
990</p>
991
992<div class="code">
993<pre>
994Vector cross_product(Vector a, Vector b);
995</pre>
996</div>
997
998<p>
999If no information is supplied about <tt>Vector</tt>, SWIG creates a wrapper function similar to the
1000following:
1001</p>
1002
1003<div class="code">
1004<pre>
1005Vector *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>
1014In order for the wrapper code to compile, <tt>Vector</tt> must define a copy constructor and a
1015default constructor.
1016</p>
1017
1018<p>
1019If <tt>Vector</tt> is defined as class in the interface, but it does
1020not support a default constructor, SWIG changes the wrapper code by
1021encapsulating the arguments inside a special C++ template wrapper
1022class. This produces a wrapper that looks like this:
1023</p>
1024
1025<div class="code">
1026<pre>
1027Vector cross_product(Vector *a, Vector *b) {
1028 SwigValueWrapper&lt;Vector&gt; x = *a;
1029 SwigValueWrapper&lt;Vector&gt; y = *b;
1030 SwigValueWrapper&lt;Vector&gt; r = cross_product(x,y);
1031 return new Vector(r);
1032}
1033</pre>
1034</div>
1035
1036<p>
1037This transformation is a little sneaky, but it provides support for
1038pass-by-value even when a class does not provide a default constructor
1039and it makes it possible to properly support a number of SWIG's
1040customization options. The definition of <tt>SwigValueWrapper</tt>
1041can be found by reading the SWIG wrapper code. This class is really nothing more than a thin
1042wrapper around a pointer.
1043</p>
1044
1045<p>
1046<b>Note:</b> this transformation has no effect on typemaps
1047or any other part of SWIG---it should be transparent except that you
1048may see this code when reading the SWIG output file.
1049</p>
1050
1051<p>
1052<b>
1053Note: </b>This template transformation is new in SWIG-1.3.11 and may be refined in
1054future SWIG releases. In practice, it is only necessary to do this for
1055classes 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.
1060It 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
1065if possible (consider using references instead).
1066</p>
1067
1068<H2><a name="SWIGPlus_nn20"></a>6.12 Inheritance</H2>
1069
1070
1071<p>
1072SWIG supports C++ inheritance of classes and allows both single and
1073multiple inheritance, as limited or allowed by the target
1074language. The SWIG type-checker knows about the relationship between
1075base and derived classes and allows pointers to any object of a
1076derived class to be used in functions of a base class. The
1077type-checker properly casts pointer values and is safe to use with
1078multiple inheritance.
1079</p>
1080
1081<p> SWIG treats private or protected inheritance as close to the C++
1082spirit, and target language capabilities, as possible. In most of the
1083cases, this means that swig will parse the non-public inheritance
1084declarations, but that will have no effect in the generated code,
1085besides the implicit policies derived for constructor and
1086destructors.
1087</p>
1088
1089
1090<p>
1091The following example shows how SWIG handles inheritance. For clarity,
1092the 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
1101class Shape {
1102public:
1103 double x,y;
1104 virtual double area() = 0;
1105 virtual double perimeter() = 0;
1106 void set_location(double x, double y);
1107};
1108class Circle : public Shape {
1109public:
1110 Circle(double radius);
1111 ~Circle();
1112 double area();
1113 double perimeter();
1114};
1115class Square : public Shape {
1116public:
1117 Square(double size);
1118 ~Square();
1119 double area();
1120 double perimeter();
1121}
1122</pre></div>
1123
1124<p>
1125When wrapped into Python, we can now perform the following operations
1126:</p>
1127
1128<div class="targetlang"><pre>
1129$ python
1130&gt;&gt;&gt; import shapes
1131&gt;&gt;&gt; circle = shapes.new_Circle(7)
1132&gt;&gt;&gt; square = shapes.new_Square(10)
1133&gt;&gt;&gt; print shapes.Circle_area(circle)
1134153.93804004599999757
1135&gt;&gt;&gt; print shapes.Shape_area(circle)
1136153.93804004599999757
1137&gt;&gt;&gt; print shapes.Shape_area(square)
1138100.00000000000000000
1139&gt;&gt;&gt; shapes.Shape_set_location(square,2,-3)
1140&gt;&gt;&gt; print shapes.Shape_perimeter(square)
114140.00000000000000000
1142&gt;&gt;&gt;
1143</pre></div>
1144
1145<p>
1146In this example, Circle and Square objects have been created. Member
1147functions 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
1149results can be accomplished by simply using the <tt>Shape_area</tt>
1150function on either object.
1151</p>
1152
1153<p>
1154One important point concerning inheritance is that the low-level
1155accessor functions are only generated for classes in which they are
1156actually 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
1160course, the <tt>Shape_set_location()</tt> function will accept any
1161kind of object derived from Shape. Similarly, accessor functions for
1162the 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>
1170Although the low-level C-like interface is functional, most language
1171modules also produce a higher level OO interface using proxy classes.
1172This 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
1177base classes to be defined in an interface. Otherwise, you may get an
1178warning message like this:
1179</p>
1180
1181<div class="shell">
1182<pre>
1183example:18. Nothing known about class 'Foo'. Ignored.
1184</pre>
1185</div>
1186
1187<p>
1188If any base class is undefined, SWIG still generates correct type
1189relationships. For instance, a function accepting a <tt>Foo *</tt>
1190will accept any object derived from <tt>Foo</tt> regardless of whether
1191or not SWIG actually wrapped the <tt>Foo</tt> class. If you really
1192don't want to generate wrappers for the base class, but you want to
1193silence the warning, you might consider using the <tt>%import</tt>
1194directive to include the file that defines <tt>Foo</tt>.
1195<tt>%import</tt> simply gathers type information, but doesn't generate
1196wrappers. Alternatively, you could just define <tt>Foo</tt> as an empty class
1197in 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>
1206class Foo {
1207...
1208};
1209
1210typedef Foo FooObj;
1211class Bar : public FooObj { // Ok. Base class is Foo
1212...
1213};
1214</pre>
1215</div>
1216
1217<p>
1218Similarly, <tt>typedef</tt> allows unnamed structures to be used as base classes. For example:
1219</p>
1220
1221<div class="code">
1222<pre>
1223typedef struct {
1224 ...
1225} Foo;
1226
1227class 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
1235generates low-level accessor wrappers for the declarations that are
1236actually defined in each class. This differs from SWIG1.1 which used
1237to inherit all of the declarations defined in base classes and
1238regenerate 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>.
1241This behavior resulted in huge amounts of replicated code for large
1242class hierarchies and made it awkward to build applications spread
1243across multiple modules (since accessor functions are duplicated in
1244every single module). It is also unnecessary to have such wrappers
1245when 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
1249functions for virtual members that are already defined in a base
1250class.
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>
1257When a target scripting language refers to a C++ object, it normally
1258uses a tagged pointer object that contains both the value of the
1259pointer and a type string. For example, in Tcl, a C++ pointer might
1260be 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>
1270A somewhat common question is whether or not the type-tag could be safely
1271removed from the pointer. For instance, to get better performance, could you
1272strip all type tags and just use simple integers instead?
1273</p>
1274
1275<p>
1276In general, the answer to this question is no. In the wrappers, all
1277pointers are converted into a common data representation in the target
1278language. Typically this is the equivalent of casting a pointer to <tt>void *</tt>.
1279This means that any C++ type information associated with the pointer is
1280lost in the conversion.
1281</p>
1282
1283<p>
1284The problem with losing type information is that it is needed to
1285properly support many advanced C++ features--especially multiple
1286inheritance. For example, suppose you had code like this:
1287</p>
1288
1289<div class="code">
1290<pre>
1291class A {
1292public:
1293 int x;
1294};
1295
1296class B {
1297public:
1298 int y;
1299};
1300
1301class C : public A, public B {
1302};
1303
1304int A_function(A *a) {
1305 return a-&gt;x;
1306}
1307
1308int B_function(B *b) {
1309 return b-&gt;y;
1310}
1311</pre>
1312</div>
1313
1314<p>
1315Now, consider the following code that uses <tt>void *</tt>.
1316</p>
1317
1318<div class="code">
1319<pre>
1320C *c = new C();
1321void *p = (void *) c;
1322...
1323int x = A_function((A *) p);
1324int y = B_function((B *) p);
1325</pre>
1326</div>
1327
1328<p>
1329In this code, both <tt>A_function()</tt> and <tt>B_function()</tt> may
1330legally accept an object of type <tt>C *</tt> (via inheritance).
1331However, one of the functions will always return the wrong result when
1332used as shown. The reason for this is that even though <tt>p</tt>
1333points to an object of type <tt>C</tt>, the casting operation doesn't
1334work like you would expect. Internally, this has to do with the data
1335representation of <tt>C</tt>. With multiple inheritance, the data from
1336each base class is stacked together. For example:
1337</p>
1338
1339<div class="diagram">
1340<pre>
1341 ------------ &lt;--- (C *), (A *)
1342 | A |
1343 |------------| &lt;--- (B *)
1344 | B |
1345 ------------
1346</pre>
1347</div>
1348
1349<p>
1350Because of this stacking, a pointer of type <tt>C *</tt> may change
1351value when it is converted to a <tt>A *</tt> or <tt>B *</tt>.
1352However, this adjustment does <em>not</em> occur if you are converting from a
1353<tt>void *</tt>.
1354</p>
1355
1356<p>
1357The use of type tags marks all pointers with the real type of the
1358underlying object. This extra information is then used by SWIG
1359generated wrappers to correctly cast pointer values under inheritance
1360(avoiding the above problem).
1361</p>
1362
1363<p>
1364One might be inclined to fix this problem using some variation of
1365<tt>dynamic_cast&lt;&gt;</tt>. The only problem is that it doesn't
1366work with <tt>void</tt> pointers, it requires RTTI support, and it
1367only works with polymorphic classes (i.e., classes that define one or
1368more virtual functions).
1369</p>
1370
1371<p>
1372The 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>
1379C++ member functions and data can be renamed with the <tt>%name</tt>
1380directive. The <tt>%name</tt> directive only replaces the member
1381function name. For example :</p>
1382
1383<div class="code"><pre>
1384class List {
1385public:
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;
1394static void print(List *l);
1395};
1396
1397</pre></div>
1398
1399<p>
1400This will create the functions <tt>List_find</tt>,
1401<tt>List_delete</tt>, and a function named <tt>new_ListSize</tt> for
1402the overloaded constructor.</p>
1403
1404<p>
1405The <tt>%name </tt>directive can be applied to all members including
1406constructors, destructors, static functions, data members, and
1407enumeration values.</p>
1408
1409<p>
1410The 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>
1419Although the <tt>%name()</tt> directive can be used to help deal with
1420overloaded methods, it really doesn't work very well because it
1421requires a lot of additional markup in your interface. Keep reading
1422for 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>
1429In many language modules, SWIG provides partial support for overloaded functions, methods, and
1430constructors. For example, if you supply SWIG with overloaded functions like this:
1431</p>
1432
1433<div class="code">
1434<pre>
1435void foo(int x) {
1436 printf("x is %d\n", x);
1437}
1438void foo(char *x) {
1439 printf("x is '%s'\n", x);
1440}
1441</pre>
1442</div>
1443
1444<p>
1445The function is used in a completely natural way. For example:
1446</p>
1447
1448<div class="targetlang">
1449<pre>
1450&gt;&gt;&gt; foo(3)
1451x is 3
1452&gt;&gt;&gt; foo("hello")
1453x is 'hello'
1454&gt;&gt;&gt;
1455</pre>
1456</div>
1457
1458<p>
1459Overloading works in a similar manner for methods and constructors. For example if you have
1460this code,
1461</p>
1462
1463<div class="code">
1464<pre>
1465class Foo {
1466public:
1467 Foo();
1468 Foo(const Foo &amp;); // Copy constructor
1469 void bar(int x);
1470 void bar(char *s, int y);
1471};
1472</pre>
1473</div>
1474
1475<p>
1476it might be used like this
1477</p>
1478
1479<div class="targetlang">
1480<pre>
1481&gt;&gt;&gt; f = Foo() # Create a Foo
1482&gt;&gt;&gt; f.bar(3)
1483&gt;&gt;&gt; g = Foo(f) # Copy Foo
1484&gt;&gt;&gt; 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>
1492The implementation of overloaded functions and methods is somewhat
1493complicated due to the dynamic nature of scripting languages. Unlike
1494C++, which binds overloaded methods at compile time, SWIG must
1495determine the proper function as a runtime check for scripting language targets. This check is
1496further complicated by the typeless nature of certain scripting languages. For instance,
1497in Tcl, all types are simply strings. Therefore, if you have two overloaded functions
1498like this,
1499</p>
1500
1501<div class="code">
1502<pre>
1503void foo(char *x);
1504void foo(int x);
1505</pre>
1506</div>
1507
1508<p>
1509the order in which the arguments are checked plays a rather critical role.
1510</p>
1511
1512<p>
1513For statically typed languages, SWIG uses the language's method overloading mechanism.
1514To implement overloading for the scripting languages, SWIG generates a dispatch function that checks the
1515number of passed arguments and their types. To create this function, SWIG
1516first examines all of the overloaded methods and ranks them according
1517to the following rules:
1518</p>
1519
1520<ol>
1521<li><b>Number of required arguments.</b> Methods are sorted by increasing number of
1522required 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>
1529Type Precedence
1530---------------- ----------
1531TYPE * 0 (High)
1532void * 20
1533Integers 40
1534Floating point 60
1535char 80
1536Strings 100 (Low)
1537</pre>
1538</div>
1539
1540<p>
1541Using these precedence values, overloaded methods with the same number of required arguments are sorted in increased
1542order of precedence values.
1543</p>
1544</li>
1545</ol>
1546
1547<p>
1548This may sound very confusing, but an example will help. Consider the following collection of
1549overloaded methods:
1550</p>
1551
1552<div class="code">
1553<pre>
1554void foo(double);
1555void foo(int);
1556void foo(Bar *);
1557void foo();
1558void foo(int x, int y, int z, int w);
1559void foo(int x, int y, int z = 3);
1560void foo(double x, double y);
1561void foo(double x, Bar *z);
1562</pre>
1563</div>
1564
1565<p>
1566The first rule simply ranks the functions by required argument count.
1567This would produce the following list:
1568</p>
1569
1570<div class="diagram">
1571<pre>
1572rank
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>
1586The second rule, simply refines the ranking by looking at argument type precedence values.
1587</p>
1588
1589<div class="diagram">
1590<pre>
1591rank
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>
1605Finally, to generate the dispatch function, the arguments passed to an overloaded method are simply
1606checked in the same order as they appear in this ranking.
1607</p>
1608
1609<p>
1610If 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>
1617Regrettably, SWIG is not able to support every possible use of valid C++ overloading. Consider
1618the following example:
1619</p>
1620
1621<div class="code">
1622<pre>
1623void foo(int x);
1624void foo(long x);
1625</pre>
1626</div>
1627
1628<p>
1629In C++, this is perfectly legal. However, in a scripting language, there is generally only one kind of integer
1630object. Therefore, which one of these functions do you pick? Clearly, there is no way to truly make a distinction
1631just by looking at the value of the integer itself (<tt>int</tt> and <tt>long</tt> may even be the same precision).
1632Therefore, 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>
1637example.i:4: Warning(509): Overloaded foo(long) is shadowed by foo(int) at example.i:3.
1638</pre>
1639</div>
1640
1641<p>
1642or for statically typed languages like Java:
1643</p>
1644
1645<div class="shell">
1646<pre>
1647example.i:4: Warning(516): Overloaded method foo(long) ignored. Method foo(int)
1648at example.i:3 used.
1649</pre>
1650</div>
1651
1652<p>
1653This means that the second overloaded function will be inaccessible
1654from a scripting interface or the method won't be wrapped at all.
1655This is done as SWIG does not know how to disambiguate it from an earlier method.
1656</p>
1657
1658<p>
1659Ambiguity 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 &amp;</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
1676instances 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>
1687When an ambiguity arises, methods are checked in the same order as they appear in the interface file.
1688Therefore, earlier methods will shadow methods that appear later.
1689</p>
1690
1691<p>
1692When 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>
1697example.i:3: Warning(467): Overloaded foo(int) not supported (no type checking
1698rule for 'int').
1699</pre>
1700</div>
1701
1702<p>
1703This error means that the target language module supports overloading,
1704but for some reason there is no type-checking rule that can be used to
1705generate a working dispatch function. The resulting behavior is then
1706undefined. 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>
1711If you get an error message such as the following,
1712</p>
1713
1714<div class="shell">
1715<pre>
1716foo.i:6. Overloaded declaration ignored. Spam::foo(double )
1717foo.i:5. Previous declaration is Spam::foo(int )
1718foo.i:7. Overloaded declaration ignored. Spam::foo(Bar *,Spam *,int )
1719foo.i:5. Previous declaration is Spam::foo(int )
1720</pre>
1721</div>
1722
1723<p>
1724it means that the target language module has not yet implemented support for overloaded
1725functions 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>
1732If an ambiguity in overload resolution occurs or if a module doesn't
1733allow overloading, there are a few strategies for dealing with the
1734problem. First, you can tell SWIG to ignore one of the methods. This
1735is easy---simply use the <tt>%ignore</tt> directive. For example:
1736</p>
1737
1738<div class="code">
1739<pre>
1740%ignore foo(long);
1741
1742void foo(int);
1743void foo(long); // Ignored. Oh well.
1744</pre>
1745</div>
1746
1747<p>
1748The other alternative is to rename one of the methods. This can be
1749done using <tt>%rename</tt>. For example:
1750</p>
1751
1752<div class="code">
1753<pre>
1754%rename(foo_long) foo(long);
1755
1756void foo(int);
1757void foo(long); // Accessed as foo_long()
1758</pre>
1759</div>
1760
1761<p>
1762The <tt>%ignore</tt> and <tt>%rename</tt> directives are both rather powerful
1763in their ability to match declarations. When used in their simple form, they apply to
1764both 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...
1773void foo(int); // Becomes 'foo_i'
1774void foo(char *c); // Stays 'foo' (not renamed)
1775
1776class Spam {
1777public:
1778 void foo(int); // Becomes 'foo_i'
1779 void foo(double); // Becomes 'foo_d'
1780 ...
1781};
1782</pre>
1783</div>
1784
1785<p>
1786If you only want the renaming to apply to a certain scope, the C++ scope resolution operator (::) can be used.
1787For 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>
1800When a renaming operator is applied to a class as in <tt>Spam::foo(int)</tt>, it is applied to
1801that class and all derived classes. This can be used to apply a consistent renaming across
1802an 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
1810class Spam {
1811public:
1812 virtual void foo(int); // Renamed to foo_i
1813 virtual void foo(double); // Renamed to foo_d
1814 ...
1815};
1816
1817class Bar : public Spam {
1818public:
1819 virtual void foo(int); // Renamed to foo_i
1820 virtual void foo(double); // Renamed to foo_d
1821...
1822};
1823
1824class Grok : public Bar {
1825public:
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>
1834It is also possible to include <tt>%rename</tt> specifications in the
1835class definition itself. For example:
1836</p>
1837
1838<div class="code">
1839<pre>
1840class Spam {
1841 %rename(foo_i) foo(int);
1842 %rename(foo_d) foo(double);
1843public:
1844 virtual void foo(int); // Renamed to foo_i
1845 virtual void foo(double); // Renamed to foo_d
1846 ...
1847};
1848
1849class Bar : public Spam {
1850public:
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>
1859In this case, the <tt>%rename</tt> directives still get applied across the entire
1860inheritance hierarchy, but it's no longer necessary to explicitly specify the
1861class prefix <tt>Spam::</tt>.
1862</p>
1863
1864<p>
1865A special form of <tt>%rename</tt> can be used to apply a renaming just to class
1866members (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>
1876Note: the <tt>*::</tt> syntax is non-standard C++, but the '*' is meant to be a
1877wildcard that matches any class name (we couldn't think of a better
1878alternative so if you have a better idea, send email to
1879the <a href="http://www.swig.org/mail.html">swig-dev mailing list</a>.
1880</p>
1881
1882<p>
1883Although this discussion has primarily focused on <tt>%rename</tt> all of the same rules
1884also 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>
1897When applied to a base class, <tt>%ignore</tt> forces all definitions in derived clases
1898to 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
1908placed at the start of an interface file. This makes it possible to apply a consistent name
1909resolution 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
1935defined. A qualified name such as <tt>Spam::foo</tt> always has
1936higher 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
1939parameterized name has higher precedence than an unparameterized name
1940within the same scope level. However, an unparameterized name with a
1941scope qualifier has higher precedence than a parameterized name in
1942global scope (e.g., a renaming of <tt>Spam::foo</tt> takes precedence
1943over a renaming of <tt>foo(int)</tt>).</p>
1944</li>
1945
1946<li><p>
1947The order in which <tt>%rename</tt> directives are defined does not matter
1948as long as they appear before the declarations to be renamed. Thus, there is no difference
1949between 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>
1960and 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
1973importance). Of course, a repeated <tt>%rename</tt> directive will
1974change the setting for a previous <tt>%rename</tt> directive if exactly the
1975same 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,
1980the first renaming rule found on a depth-first traversal of the class hierarchy
1981is used.
1982</li>
1983
1984<li><p>The name matching rules strictly follow member qualification rules.
1985For example, if you have a class like this:</p>
1986
1987<div class="code">
1988<pre>
1989class Spam {
1990public:
1991 ...
1992 void bar() const;
1993 ...
1994};
1995</pre>
1996</div>
1997
1998<p>
1999the declaration
2000</p>
2001
2002<div class="code">
2003<pre>
2004%rename(name) Spam::bar();
2005</pre>
2006</div>
2007
2008<p>
2009will not apply as there is no unqualified member <tt>bar()</tt>. The following will apply as
2010the 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>
2020An often overlooked C++ feature is that classes can define two different overloaded members
2021that differ only in their qualifiers, like this:
2022</p>
2023
2024<div class="code">
2025<pre>
2026class Spam {
2027public:
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.
2038For 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>
2049Similarly, if you
2050merely wanted to ignore one of the declarations, use <tt>%ignore</tt>
2051with the full qualification. For example, the following directive
2052would tell SWIG to ignore the <tt>const</tt> version of <tt>bar()</tt>
2053above:
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>
2065The name matching rules also use default arguments for finer control when wrapping methods that have default arguments.
2066Recall 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).
2068Let's consider the following example class:</p>
2069
2070<div class="code">
2071<pre>
2072class Spam {
2073public:
2074 ...
2075 void bar(int i=-1, double d=0.0);
2076 ...
2077};
2078</pre>
2079</div>
2080
2081<p>
2082The following <tt>%rename</tt> will match exactly and apply to all the target language overloaded methods because the declaration with the default arguments
2083exactly 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>
2093The 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>.
2095However, if the <tt>%rename</tt> does not contain the default arguments, it will only apply to the single equivalent target language overloaded method.
2096So 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>
2106The 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
2107or with the original name as <tt>bar(2)</tt> (one argument) or <tt>bar()</tt> (no arguments).
2108In 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>
2120Similarly, 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
2125to 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>
2136Support for overloaded methods was first added in SWIG-1.3.14. The implementation
2137is somewhat unusual when compared to similar tools. For instance, the order in which
2138declarations appear is largely irrelevant in SWIG. Furthermore, SWIG does not rely
2139upon trial execution or exception handling to figure out which method to invoke.
2140</p>
2141
2142<p>
2143Internally, the overloading mechanism is completely configurable by the target language
2144module. Therefore, the degree of overloading support may vary from language to language.
2145As a general rule, statically typed languages like Java are able to provide more support
2146than 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>
2153Starting in SWIG-1.3.10, C++ overloaded operator declarations can be wrapped.
2154For example, consider a class like this:
2155</p>
2156
2157<div class="code">
2158<pre>
2159class Complex {
2160private:
2161 double rpart, ipart;
2162public:
2163 Complex(double r = 0, double i = 0) : rpart(r), ipart(i) { }
2164 Complex(const Complex &amp;c) : rpart(c.rpart), ipart(c.ipart) { }
2165 Complex &amp;operator=(const Complex &amp;c) {
2166 rpart = c.rpart;
2167 ipart = c.ipart;
2168 return *this;
2169 }
2170 Complex operator+(const Complex &amp;c) const {
2171 return Complex(rpart+c.rpart, ipart+c.ipart);
2172 }
2173 Complex operator-(const Complex &amp;c) const {
2174 return Complex(rpart-c.rpart, ipart-c.ipart);
2175 }
2176 Complex operator*(const Complex &amp;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>
2190When operator declarations appear, they are handled in
2191<em>exactly</em> the same manner as regular methods. However, the
2192names of these methods are set to strings like "<tt>operator +</tt>"
2193or "<tt>operator -</tt>". The problem with these names is that they
2194are illegal identifiers in most scripting languages. For instance,
2195you can't just create a method called "<tt>operator +</tt>" in
2196Python--there won't be any way to call it.
2197</p>
2198
2199<p>
2200Some language modules already know how to automatically handle certain
2201operators (mapping them into operators in the target language).
2202However, the underlying implementation of this is really managed in a
2203very general way using the <tt>%rename</tt> directive. For example,
2204in 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>
2214This binds the + operator to a method called <tt>__add__</tt> (which
2215is conveniently the same name used to implement the Python + operator).
2216Internally, the generated wrapper code for a wrapped operator will look
2217something like this pseudocode:
2218</p>
2219
2220<div class="code">
2221<pre>
2222_wrap_Complex___add__(args) {
2223 ... get args ...
2224 obj-&gt;operator+(args);
2225 ...
2226}
2227</pre>
2228</div>
2229
2230<p>
2231When used in the target language, it may now be possible to use the overloaded
2232operator normally. For example:
2233</p>
2234
2235<div class="targetlang">
2236<pre>
2237&gt;&gt;&gt; a = Complex(3,4)
2238&gt;&gt;&gt; b = Complex(5,2)
2239&gt;&gt;&gt; c = a + b # Invokes __add__ method
2240</pre>
2241</div>
2242
2243<p>
2244It is important to realize that there is nothing magical happening
2245here. The <tt>%rename</tt> directive really only picks a valid method
2246name. If you wrote this:
2247</p>
2248
2249<div class="code">
2250<pre>
2251%rename(add) operator+;
2252</pre>
2253</div>
2254
2255<p>
2256The resulting scripting interface might work like this:
2257</p>
2258
2259<div class="targetlang">
2260<pre>
2261a = Complex(3,4)
2262b = Complex(5,2)
2263c = a.add(b) # Call a.operator+(b)
2264</pre>
2265</div>
2266
2267<p>
2268All of the techniques described to deal with overloaded functions also
2269apply 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>
2284The last part of this example illustrates how multiple definitions of
2285the <tt>operator-</tt> method might be handled.
2286</p>
2287
2288<p>
2289Handling operators in this manner is mostly straightforward. However, there are a few subtle
2290issues 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
2295different types. For example, a class might also include a friend function like this:</p>
2296
2297<div class="code">
2298<pre>
2299class Complex {
2300public:
2301 friend Complex operator+(Complex &amp;, double);
2302};
2303Complex operator+(Complex &amp;, double);
2304</pre>
2305</div>
2306
2307<p>
2308SWIG simply ignores all <tt>friend</tt> declarations. Furthermore, it
2309doesn't know how to associate the associated <tt>operator+</tt> with
2310the class (because it's not a member of the class).
2311</p>
2312
2313<p>
2314It's still possible to make a wrapper for this operator, but you'll
2315have 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 &amp;, 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
2326are 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>
2337New methods can be added to a class using the <tt>%extend</tt>
2338directive. This directive is primarily used in conjunction with proxy
2339classes to add additional functionality to an existing class. For
2340example :
2341</p>
2342
2343<div class="code"><pre>
2344%module vector
2345%{
2346#include "vector.h"
2347%}
2348
2349class Vector {
2350public:
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-&gt;x,self-&gt;y,self-&gt;z);
2359 return &amp;temp[0];
2360 }
2361 }
2362};
2363</pre></div>
2364
2365<p>
2366This code adds a<tt> __str__</tt> method to our class for producing a
2367string representation of the object. In Python, such a method would
2368allow us to print the value of an object using the <tt>print</tt>
2369command.
2370</p>
2371
2372<div class="targetlang"><pre>
2373&gt;&gt;&gt;
2374&gt;&gt;&gt; v = Vector();
2375&gt;&gt;&gt; v.x = 3
2376&gt;&gt;&gt; v.y = 4
2377&gt;&gt;&gt; v.z = 0
2378&gt;&gt;&gt; print(v)
2379[ 3.0, 4.0, 0.0 ]
2380&gt;&gt;&gt;
2381
2382</pre></div>
2383
2384<p>
2385The<tt> %extend</tt> directive follows all of the same conventions
2386as its use with C structures. Please refer to the <a href="SWIG.html#SWIG">SWIG Basics</a>
2387chapter for further details.
2388</p>
2389
2390<p>
2391<b>Compatibility note:</b> The <tt>%extend</tt> directive is a new
2392name for the <tt>%addmethods</tt> directive. Since <tt>%addmethods</tt> could
2393be used to extend a structure with more than just methods, a more suitable
2394directive name has been chosen.
2395</p>
2396
2397<H2><a name="SWIGPlus_nn30"></a>6.18 Templates</H2>
2398
2399
2400<p>
2401In all versions of SWIG, template type names may appear anywhere a type
2402is expected in an interface file. For example:
2403</p>
2404
2405<div class="code">
2406<pre>
2407void foo(vector&lt;int&gt; *a, int n);
2408void bar(list&lt;int,100&gt; *x);
2409</pre>
2410</div>
2411
2412<p>
2413There are some restrictions on the use of non-type arguments. Specifically,
2414they have to be simple literals and not expressions. For example:
2415</p>
2416
2417<div class="code">
2418<pre>
2419void bar(list&lt;int,100&gt; *x); // OK
2420void bar(list&lt;int,2*50&gt; *x); // Illegal
2421</pre>
2422</div>
2423
2424<p>
2425The type system is smart enough to figure out clever games
2426you might try to play with <tt>typedef</tt>. For instance, consider this code:
2427</p>
2428
2429<div class="code">
2430<pre>
2431typedef int Integer;
2432void foo(vector&lt;int&gt; *x, vector&lt;Integer&gt; *y);
2433</pre>
2434</div>
2435
2436<p>
2437In this case, <tt>vector&lt;Integer&gt;</tt> is exactly the same type
2438as <tt>vector&lt;int&gt;</tt>. The wrapper for <tt>foo()</tt> will
2439accept either variant.
2440</p>
2441
2442<p>
2443Starting with SWIG-1.3.7, simple C++ template declarations can also be
2444wrapped. SWIG-1.3.12 greatly expands upon the earlier implementation. Before discussing this any further, there are a few things
2445you need to know about template wrapping. First, a bare C++ template
2446does not define any sort of runnable object-code for which SWIG can
2447normally create a wrapper. Therefore, in order to wrap a template,
2448you need to give SWIG information about a particular template
2449instantiation (e.g., <tt>vector&lt;int&gt;</tt>,
2450<tt>array&lt;double&gt;</tt>, etc.). Second, an instantiation name
2451such as <tt>vector&lt;int&gt;</tt> is generally not a valid identifier
2452name in most target languages. Thus, you will need to give the
2453template instantiation a more suitable name such as <tt>intvector</tt>
2454when creating a wrapper.
2455</p>
2456
2457<p>
2458To illustrate, consider the following template definition:
2459</p>
2460
2461<div class="code"><pre>
2462template&lt;class T&gt; class List {
2463private:
2464 T *data;
2465 int nitems;
2466 int maxitems;
2467public:
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 &lt; 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>
2491By itself, this template declaration is useless--SWIG simply ignores it
2492because 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>
2497One way to create wrappers for a specific template instantiation is to simply
2498provide an expanded version of the class directly like this:
2499</p>
2500
2501<div class="code">
2502<pre>
2503%rename(intList) List&lt;int&gt;; // Rename to a suitable identifier
2504class List&lt;int&gt; {
2505private:
2506 int *data;
2507 int nitems;
2508 int maxitems;
2509public:
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>
2521The <tt>%rename</tt> directive is needed to give the template class an appropriate identifier
2522name in the target language (most languages would not recognize C++ template syntax as a valid
2523class name). The rest of the code is the same as what would appear in a normal
2524class definition.
2525</p>
2526
2527<p>
2528Since manual expansion of templates gets old in a hurry, the <tt>%template</tt> directive can
2529be used to create instantiations of a template class. Semantically, <tt>%template</tt> is
2530simply a shortcut---it expands template code in exactly the same way as shown above. Here
2531are some examples:
2532</p>
2533
2534<div class="code">
2535<pre>
2536/* Instantiate a few different versions of the template */
2537%template(intList) List&lt;int&gt;;
2538%template(doubleList) List&lt;double&gt;;
2539</pre>
2540</div>
2541
2542<p>
2543The argument to <tt>%template()</tt> is the name of the instantiation
2544in the target language. The name you choose should not conflict with
2545any other declarations in the interface file with one exception---it
2546is okay for the template name to match that of a typedef declaration.
2547For example:
2548</p>
2549
2550<div class="code">
2551<pre>
2552%template(intList) List&lt;int&gt;;
2553...
2554typedef List&lt;int&gt; intList; // OK
2555</pre>
2556</div>
2557
2558<p>
2559SWIG can also generate wrappers for function templates using a similar technique.
2560For example:
2561</p>
2562
2563<div class="code">
2564<pre>
2565// Function template
2566template&lt;class T&gt; T max(T a, T b) { return a &gt; b ? a : b; }
2567
2568// Make some different versions of this function
2569%template(maxint) max&lt;int&gt;;
2570%template(maxdouble) max&lt;double&gt;;
2571</pre>
2572</div>
2573
2574<p>
2575In this case, <tt>maxint</tt> and <tt>maxdouble</tt> become unique names for specific
2576instantiations of the function.
2577</p>
2578
2579<p>
2580The number of arguments supplied to <tt>%template</tt> should match that in the
2581original template definition. Template default arguments are supported. For example:
2582</p>
2583
2584<div class="code">
2585<pre>
2586template vector&lt;typename T, int max=100&gt; class vector {
2587...
2588};
2589
2590%template(intvec) vector&lt;int&gt;; // OK
2591%template(vec1000) vector&lt;int,1000&gt;; // OK
2592</pre>
2593</div>
2594
2595<p>
2596The <tt>%template</tt> directive should not be used to wrap the same
2597template instantiation more than once in the same scope. This will
2598generate an error. For example:
2599</p>
2600
2601<div class="code">
2602<pre>
2603%template(intList) List&lt;int&gt;;
2604%template(Listint) List&lt;int&gt;; // Error. Template already wrapped.
2605</pre>
2606</div>
2607
2608<p>
2609This error is caused because the template expansion results in two
2610identical classes with the same name. This generates a symbol table
2611conflict. Besides, it probably more efficient to only wrap a specific
2612instantiation only once in order to reduce the potential for code
2613bloat.
2614</p>
2615
2616<p>
2617Since the type system knows how to handle <tt>typedef</tt>, it is
2618generally not necessary to instantiate different versions of a template
2619for typenames that are equivalent. For instance, consider this code:
2620</p>
2621
2622<div class="code">
2623<pre>
2624%template(intList) vector&lt;int&gt;;
2625typedef int Integer;
2626...
2627void foo(vector&lt;Integer&gt; *x);
2628</pre>
2629</div>
2630
2631<p>
2632In this case, <tt>vector&lt;Integer&gt;</tt> is exactly the same type as
2633<tt>vector&lt;int&gt;</tt>. Any use of <tt>Vector&lt;Integer&gt;</tt> is mapped back to the
2634instantiation of <tt>vector&lt;int&gt;</tt> created earlier. Therefore, it is
2635not necessary to instantiate a new class for the type <tt>Integer</tt> (doing so is
2636redundant and will simply result in code bloat).
2637</p>
2638
2639<p>
2640When a template is instantiated using <tt>%template</tt>, information
2641about that class is saved by SWIG and used elsewhere in the program.
2642For example, if you wrote code like this,
2643</p>
2644
2645<div class="code">
2646<pre>
2647...
2648%template(intList) List&lt;int&gt;;
2649...
2650class UltraList : public List&lt;int&gt; {
2651 ...
2652};
2653</pre>
2654</div>
2655
2656<p>
2657then SWIG knows that <tt>List&lt;int&gt;</tt> was already wrapped as a class called
2658<tt>intList</tt> and arranges to handle the inheritance correctly. If, on the other hand,
2659nothing is known about <tt>List&lt;int&gt;</tt>, you will get a warning message similar to this:
2660</p>
2661
2662<div class="shell">
2663<pre>
2664example.h:42. Nothing known about class 'List&lt;int &gt;' (ignored).
2665example.h:42. Maybe you forgot to instantiate 'List&lt;int &gt;' using %template.
2666</pre>
2667</div>
2668
2669<p>
2670If a template class inherits from another template class, you need to
2671make sure that base classes are instantiated before derived classes.
2672For example:
2673</p>
2674
2675<div class="code">
2676<pre>
2677template&lt;class T&gt; class Foo {
2678...
2679};
2680
2681template&lt;class T&gt; class Bar : public Foo&lt;T&gt; {
2682...
2683};
2684
2685// Instantiate base classes first
2686%template(intFoo) Foo&lt;int&gt;;
2687%template(doubleFoo) Foo&lt;double&gt;;
2688
2689// Now instantiate derived classes
2690%template(intBar) Bar&lt;int&gt;;
2691%template(doubleBar) Bar&lt;double&gt;;
2692</pre>
2693</div>
2694
2695<p>
2696The order is important since SWIG uses the instantiation names to
2697properly set up the inheritance hierarchy in the resulting wrapper
2698code (and base classes need to be wrapped before derived classes).
2699Don't worry--if you get the order wrong, SWIG should generate a warning message.
2700</p>
2701
2702<p>
2703Occassionally, you may need to tell SWIG about base classes that are defined by templates,
2704but which aren't supposed to be wrapped. Since SWIG is not able to automatically
2705instantiate templates for this purpose, you must do it manually. To do this, simply
2706use <tt>%template</tt> with no name. For example:
2707</p>
2708
2709<div class="code">
2710<pre>
2711// Instantiate traits&lt;double,double&gt;, but don't wrap it.
2712%template() traits&lt;double,double&gt;;
2713</pre>
2714</div>
2715
2716<p>
2717If you have to instantiate a lot of different classes for many different types,
2718you 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&lt;T&gt;;
2725%template(prefix ## Bar) Bar&lt;T&gt;;
2726...
2727%enddef
2728
2729TEMPLATE_WRAP(int, int)
2730TEMPLATE_WRAP(double, double)
2731TEMPLATE_WRAP(char *, String)
2732...
2733</pre>
2734</div>
2735
2736<p>
2737The SWIG template mechanism <em>does</em> support specialization. For instance, if you define
2738a class like this,
2739</p>
2740
2741<div class="code">
2742<pre>
2743template&lt;&gt; class List&lt;int&gt; {
2744private:
2745 int *data;
2746 int nitems;
2747 int maxitems;
2748public:
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>
2759then SWIG will use this code whenever the user expands <tt>List&lt;int&gt;</tt>. In practice,
2760this may have very little effect on the underlying wrapper code since
2761specialization is often used to provide slightly modified method bodies (which
2762are ignored by SWIG). However, special SWIG
2763directives such as <tt>%typemap</tt>, <tt>%extend</tt>, and so forth can be attached
2764to a specialization to provide customization for specific types.
2765</p>
2766
2767<p>
2768Partial template specialization is partially supported by SWIG. For example, this
2769code defines a template that is applied when the template argument is a pointer.
2770</p>
2771
2772<div class="code">
2773<pre>
2774template&lt;class T&gt; class List&lt;T*&gt; {
2775private:
2776 T *data;
2777 int nitems;
2778 int maxitems;
2779public:
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>
2790SWIG should be able to handle most simple uses of partial specialization. However, it may fail
2791to match templates properly in more complicated cases. For example, if you have this code,
2792</p>
2793
2794<div class="code">
2795<pre>
2796template&lt;class T1, class T2&gt; class Foo&lt;T1, T2 *&gt; { };
2797</pre>
2798</div>
2799
2800<p>
2801SWIG isn't able to match it properly for instantiations like <tt>Foo&lt;int *, int *&gt;</tt>.
2802This problem is not due to parsing, but due to the fact that SWIG does not currently implement all
2803of the C++ argument deduction rules.
2804</p>
2805
2806<p>
2807Member function templates are supported. The underlying principle is the same
2808as for normal templates--SWIG can't create a wrapper unless you provide
2809more information about types. For example, a class with a member template might
2810look like this:
2811</p>
2812
2813<div class="code">
2814<pre>
2815class Foo {
2816public:
2817 template&lt;class T&gt; void bar(T x, T y) { ... };
2818 ...
2819};
2820</pre>
2821</div>
2822
2823<p>
2824To expand the template, simply use <tt>%template</tt> inside the class.
2825</p>
2826
2827<div class="code">
2828<pre>
2829class Foo {
2830public:
2831 template&lt;class T&gt; void bar(T x, T y) { ... };
2832 ...
2833 %template(barint) bar&lt;int&gt;;
2834 %template(bardouble) bar&lt;double&gt;;
2835};
2836</pre>
2837</div>
2838
2839<p>
2840Or, if you want to leave the original class definition alone, just do this:
2841</p>
2842
2843<div class="code">
2844<pre>
2845class Foo {
2846public:
2847 template&lt;class T&gt; void bar(T x, T y) { ... };
2848 ...
2849};
2850...
2851%extend Foo {
2852 %template(barint) bar&lt;int&gt;;
2853 %template(bardouble) bar&lt;double&gt;;
2854};
2855</pre>
2856</div>
2857
2858<p>
2859or simply
2860</p>
2861
2862<div class="code">
2863<pre>
2864class Foo {
2865public:
2866 template&lt;class T&gt; void bar(T x, T y) { ... };
2867 ...
2868};
2869...
2870
2871%template(bari) Foo::bar&lt;int&gt;;
2872%template(bard) Foo::bar&lt;double&gt;;
2873</pre>
2874</div>
2875
2876<p>
2877In 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
2879methods to the Foo class.
2880</p>
2881
2882
2883<p>
2884Note: because of the way that templates are handled, the <tt>%template</tt> directive
2885must always appear <em>after</em> the definition of the template to be expanded.
2886</p>
2887
2888<p>
2889Now, if your target language supports overloading, you can even try
2890</p>
2891
2892<div class="code">
2893<pre>
2894%template(bar) Foo::bar&lt;int&gt;;
2895%template(bar) Foo::bar&lt;double&gt;;
2896</pre>
2897</div>
2898
2899<p>
2900and since the two new wrapped methods have the same name 'bar', they will be
2901overloaded, and when called, the correct method will be dispatched
2902depending on the argument type.
2903</p>
2904
2905
2906<p>
2907When used with members, the <tt>%template</tt> directive may be placed in another
2908template class. Here is a slightly perverse example:
2909</p>
2910
2911<div class="code">
2912<pre>
2913// A template
2914template&lt;class T&gt; class Foo {
2915public:
2916 // A member template
2917 template&lt;class S&gt; T bar(S x, S y) { ... };
2918 ...
2919};
2920
2921// Expand a few member templates
2922%extend Foo {
2923 %template(bari) bar&lt;int&gt;;
2924 %template(bard) bar&lt;double&gt;;
2925}
2926
2927// Create some wrappers for the template
2928%template(Fooi) Foo&lt;int&gt;;
2929%template(Food) Foo&lt;double&gt;;
2930</pre>
2931</div>
2932
2933<p>
2934Miraculously, you will find that each expansion of <tt>Foo</tt> has member
2935functions <tt>bari()</tt> and <tt>bard()</tt> added.
2936</p>
2937
2938<p>
2939A common use of member templates is to define constructors for copies
2940and conversions. For example:
2941</p>
2942
2943<div class="code">
2944<pre>
2945template&lt;class T1, class T2&gt; struct pair {
2946 T1 first;
2947 T2 second;
2948 pair() : first(T1()), second(T2()) { }
2949 pair(const T1 &amp;x, const T2 &amp;y) : first(x), second(y) { }
2950 template&lt;class U1, class U2&gt; pair(const pair&lt;U1,U2&gt; &amp;x)
2951 : first(x.first),second(x.second) { }
2952};
2953</pre>
2954</div>
2955
2956<p>
2957This declaration is perfectly acceptable to SWIG, but the constructor template will be ignored
2958unless you explicitly expand it. To do that, you could expand a few versions of the constructor
2959in the template class itself. For example:
2960</p>
2961
2962<div class="code">
2963<pre>
2964%extend pair {
2965 %template(pair) pair&lt;T1,T2&gt;; // Generate default copy constructor
2966};
2967</pre>
2968</div>
2969
2970<p>
2971When using <tt>%extend</tt> in this manner, notice how you can still use the template parameters in
2972the original template definition.
2973</p>
2974
2975<p>
2976Alternatively, 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&lt;int,int&gt;;
2983%template(pairdd) pair&lt;double,double&gt;;
2984
2985// Create a default constructor only
2986%extend pair&lt;int,int&gt; {
2987 %template(paird) pair&lt;int,int&gt;; // Default constructor
2988};
2989
2990// Create default and conversion constructors
2991%extend pair&lt;double,double&gt; {
2992 %template(paird) pair&lt;double,dobule&gt;; // Default constructor
2993 %template(pairc) pair&lt;int,int&gt;; // Conversion constructor
2994};
2995</pre>
2996</div>
2997
2998
2999<p>And if your target language supports overloading, then you can try
3000instead:
3001</p>
3002
3003<div class="code">
3004<pre>
3005// Create default and conversion constructors
3006%extend pair&lt;double,double&gt; {
3007 %template(pair) pair&lt;double,dobule&gt;; // Default constructor
3008 %template(pair) pair&lt;int,int&gt;; // Conversion constructor
3009};
3010</pre>
3011</div>
3012
3013<p>
3014In this case, the default and conversion constructors have the same
3015name. Hence, Swig will overload them and define an unique visible
3016constructor, that will dispatch the proper call depending on the argument
3017type.
3018</p>
3019
3020<p>
3021If all of this isn't quite enough and you really want to make
3022someone's head explode, SWIG directives such as
3023<tt>%rename</tt>, <tt>%extend</tt>, and <tt>%typemap</tt> can be
3024included directly in template definitions. For example:
3025</p>
3026
3027<div class="code"><pre>
3028// File : list.h
3029template&lt;class T&gt; class List {
3030 ...
3031public:
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>
3047In this example, the extra SWIG directives are propagated to <em>every</em> template
3048instantiation.
3049</p>
3050
3051<p>
3052It 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&lt;T&gt;(*self);
3066 }
3067};
3068
3069...
3070template&lt;class T&gt; class List {
3071 ...
3072 public:
3073 List() { };
3074 ...
3075};
3076</pre>
3077</div>
3078
3079<p>
3080When <tt>%extend</tt> is decoupled from the class definition, it is
3081legal to use the same template parameters as provided in the class definition.
3082These are replaced when the template is expanded.
3083In addition, the <tt>%extend</tt> directive can be used to add
3084additional methods to a specific instantiation. For example:
3085</p>
3086
3087<div class="code">
3088<pre>
3089%template(intList) List&lt;int&gt;;
3090
3091%extend List&lt;int&gt; {
3092 void blah() {
3093 printf("Hey, I'm an List&lt;int&gt;!\n");
3094 }
3095};
3096</pre>
3097</div>
3098
3099<p>
3100SWIG even supports overloaded templated functions. As usual the <tt>%template</tt> directive
3101is used to wrap templated functions. For example:
3102</p>
3103
3104<div class="code">
3105<pre>
3106template&lt;class T&gt; void foo(T x) { };
3107template&lt;class T&gt; void foo(T x, T y) { };
3108
3109%template(foo) foo&lt;int&gt;;
3110</pre>
3111</div>
3112
3113<p>
3114This will generate two overloaded wrapper methods, the first will take a single integer as an argument
3115and the second will take two integer arguments.
3116</p>
3117
3118<p>
3119Needless to say, SWIG's template support provides plenty of
3120opportunities to break the universe. That said, an important final
3121point is that <b>SWIG does not perform extensive error checking of
3122templates!</b> Specifically, SWIG does not perform type checking nor
3123does it check to see if the actual contents of the template
3124declaration make any sense. Since the C++ compiler will hopefully
3125check this when it compiles the resulting wrapper file, there is no
3126practical reason for SWIG to duplicate this functionality (besides,
3127none of the SWIG developers are masochistic enough to want to
3128implement this right now).
3129</p>
3130
3131<p>
3132<b>Compatibility Note</b>: The first implementation of template support relied heavily on
3133macro expansion in the preprocessor. Templates have been more tightly integrated into
3134the parser and type system in SWIG-1.3.12 and the preprocessor is no longer used. Code
3135that relied on preprocessing features in template expansion will no longer work. However,
3136SWIG 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
3141introduced 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&lt;int&gt;;
3147%extend vectori {
3148 void somemethod() { }
3149};
3150</pre>
3151</div>
3152
3153<p>
3154This behavior is no longer supported. Instead, you should use the original template name
3155as the class name. For example:
3156</p>
3157
3158<div class="code">
3159<pre>
3160%template(vectori) vector&lt;int&gt;;
3161%extend vector&lt;int&gt; {
3162 void somemethod() { }
3163};
3164</pre>
3165</div>
3166
3167<p>
3168Similar 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>
3175Support for C++ namespaces is a relatively late addition to SWIG,
3176first appearing in SWIG-1.3.12. Before describing the implementation,
3177it is worth nothing that the semantics of C++ namespaces is extremely
3178non-trivial--especially with regard to the C++ type system and class
3179machinery. At a most basic level, namespaces are sometimes used to
3180encapsulate common functionality. For example:
3181</p>
3182
3183<div class="code">
3184<pre>
3185namespace 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>
3200Members of the namespace are accessed in C++ by prepending the namespace prefix
3201to names. For example:
3202</p>
3203
3204<div class="code">
3205<pre>
3206double x = math::sin(1.0);
3207double magnitude(math::Complex *c);
3208math::Complex c;
3209...
3210</pre>
3211</div>
3212
3213<p>
3214At this level, namespaces are relatively easy to manage. However, things start to get
3215very ugly when you throw in the other ways a namespace can be used. For example,
3216selective symbols can be exported from a namespace with <tt>using</tt>.
3217</p>
3218
3219<div class="code">
3220<pre>
3221using math::Complex;
3222double magnitude(Complex *c); // Namespace prefix stripped
3223</pre>
3224</div>
3225
3226<p>
3227Similarly, the contents of an entire namespace can be made available like this:
3228</p>
3229
3230<div class="code">
3231<pre>
3232using namespace math;
3233double x = sin(1.0);
3234double magnitude(Complex *c);
3235</pre>
3236</div>
3237
3238<p>
3239Alternatively, a namespace can be aliased:
3240</p>
3241
3242<div class="code">
3243<pre>
3244namespace M = math;
3245double x = M::sin(1.0);
3246double magnitude(M::Complex *c);
3247</pre>
3248</div>
3249
3250<p>
3251Using combinations of these features, it is possible to write head-exploding code like this:
3252</p>
3253
3254<div class="code">
3255<pre>
3256namespace A {
3257 class Foo {
3258 };
3259}
3260
3261namespace B {
3262 namespace C {
3263 using namespace A;
3264 }
3265 typedef C::Foo FooClass;
3266}
3267
3268namespace BIGB = B;
3269
3270namespace D {
3271 using BIGB::FooClass;
3272 class Bar : public FooClass {
3273 }
3274};
3275
3276class Spam : public D::Bar {
3277};
3278
3279void 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>
3286Given the possibility for such perversion, it's hard to imagine how
3287every C++ programmer might want such code wrapped into the target
3288language. Clearly this code defines three different classes. However, one
3289of those classes is accessible under at least six different class names!
3290</p>
3291
3292<p>
3293SWIG fully supports C++ namespaces in its internal type system and
3294class handling code. If you feed SWIG the above code, it will be
3295parsed correctly, it will generate compilable wrapper code, and it
3296will produce a working scripting language module. However, the
3297default wrapping behavior is to flatten namespaces in the target
3298language. This means that the contents of all namespaces are merged
3299together in the resulting scripting language module. For example, if
3300you have code like this,
3301</p>
3302
3303<div class="code">
3304<pre>
3305%module foo
3306namespace foo {
3307 void bar(int);
3308 void spam();
3309}
3310
3311namespace bar {
3312 void blah();
3313}
3314
3315</pre>
3316</div>
3317
3318<p>
3319then SWIG simply creates three wrapper functions <tt>bar()</tt>,
3320<tt>spam()</tt>, and <tt>blah()</tt> in the target language. SWIG
3321does not prepend the names with a namespace prefix nor are the
3322functions packaged in any kind of nested scope.
3323</p>
3324
3325<p>
3326There is some rationale for taking this approach. Since C++
3327namespaces are often used to define modules in C++, there is a natural
3328correlation between the likely contents of a SWIG module and the contents of
3329a namespace. For instance, it would not be unreasonable to assume
3330that a programmer might make a separate extension module for each C++
3331namespace. In this case, it would be redundant to prepend everything
3332with an additional namespace prefix when the module itself already
3333serves as a namespace in the target language. Or put another way, if
3334you want SWIG to keep namespaces separate, simply wrap each namespace with its
3335own SWIG interface.
3336</p>
3337
3338<p>
3339Because namespaces are flattened, it is possible for symbols defined in different
3340namespaces to generate a name conflict in the target language. For example:
3341</p>
3342
3343<div class="code">
3344<pre>
3345namespace A {
3346 void foo(int);
3347}
3348namespace B {
3349 void foo(double);
3350}
3351</pre>
3352</div>
3353
3354<p>
3355When this conflict occurs, you will get an error message that resembles this:
3356</p>
3357
3358<div class="shell">
3359<pre>
3360example.i:26. Error. 'foo' is multiply defined in the generated module.
3361example.i:23. Previous declaration of 'foo'
3362</pre>
3363</div>
3364
3365<p>
3366To 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...
3373namespace A {
3374 void foo(int);
3375}
3376namespace B {
3377 void foo(double); // Gets renamed to B_foo
3378}
3379</pre>
3380</div>
3381
3382<p>
3383Similarly, <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
3388code. They are ignored by SWIG language modules and they do not result in any
3389code. However, these declarations <em>are</em> used by the internal type
3390system to track type-names. Therefore, if you have code like this:
3391</p>
3392
3393<div class="code">
3394<pre>
3395namespace A {
3396 typedef int Integer;
3397}
3398using namespace A;
3399void foo(Integer x);
3400</pre>
3401</div>
3402
3403<p>
3404SWIG knows that <tt>Integer</tt> is the same as <tt>A::Integer</tt> which
3405is the same as <tt>int</tt>.
3406</p>
3407
3408<P>
3409Namespaces may be combined with templates. If necessary, the
3410<tt>%template</tt> directive can be used to expand a template defined
3411in a different namespace. For example:
3412</p>
3413
3414<div class="code">
3415<pre>
3416namespace foo {
3417 template&lt;typename T&gt; T max(T a, T b) { return a &gt; b ? a : b; }
3418}
3419
3420using foo::max;
3421
3422%template(maxint) max&lt;int&gt;; // Okay.
3423%template(maxfloat) foo::max&lt;float&gt;; // Okay (qualified name).
3424
3425namespace bar {
3426 using namespace foo;
3427 %template(maxdouble) max&lt;double&gt;; // Okay.
3428}
3429</pre>
3430</div>
3431
3432<p>
3433The combination of namespaces and other SWIG directives may introduce subtle scope-related problems.
3434The key thing to keep in mind is that all SWIG generated wrappers are produced
3435in the <em>global</em> namespace. Symbols from other namespaces are always accessed using fully
3436qualified names---names are never imported into the global space unless the interface happens to
3437do so with a <tt>using</tt> declaration. In almost all cases, SWIG adjusts typenames and symbols
3438to be fully qualified. However, this is not done in code fragments such as function bodies,
3439typemaps, exception handlers, and so forth. For example, consider the following:
3440</p>
3441
3442<div class="code">
3443<pre>
3444namespace 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>
3462In 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
3464emitted in the global namespace, this code produces a compiler error about <tt>Integer</tt>.
3465To 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
3481the resulting wrapper code. If these declarations appear in an interface,
3482they should <em>also</em> appear in any header files that might have been
3483included 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
3485in 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.
3491The code emitted by these directives will not be enclosed in a namespace and
3492you may get very strange results. If you need to use namespaces with
3493these directives, consider the following:
3494</p>
3495
3496<div class="code">
3497<pre>
3498// Good version
3499%inline %{
3500namespace foo {
3501 void bar(int) { ... }
3502 ...
3503}
3504%}
3505
3506// Bad version. Emitted code not placed in namespace.
3507namespace 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
3518included in the generated functions. For example, if you have code like this,
3519</p>
3520
3521<div class="code">
3522<pre>
3523namespace foo {
3524 class bar {
3525 public:
3526 %extend {
3527 int blah(int x);
3528 };
3529 };
3530}
3531</pre>
3532</div>
3533
3534<p>
3535the added method <tt>blah()</tt> is mapped to a function <tt>int foo_bar_blah(foo::bar *self, int x)</tt>.
3536This 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
3541code observes the same namespace conventions as used in the input file. Thus, if there are no symbol
3542conflicts 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
3547instance, suppose you had an interface like this:
3548</p>
3549
3550<div class="code">
3551<pre>
3552namespace foo {
3553 class bar;
3554 class spam {
3555 public:
3556 ...
3557 operator bar(); // Conversion of spam -&gt; bar
3558 ...
3559 };
3560}
3561</pre>
3562</div>
3563
3564<p>
3565To 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>
3575The 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
3577instead:
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
3588a basic namespace implementation. Since namespaces are a new addition
3589to SWIG, none of the target language modules are currently programmed
3590with any namespace awareness. In the future, language modules may or may not provide
3591more advanced namespace support.
3592</p>
3593
3594
3595<H2><a name="SWIGPlus_exception_specifications"></a>6.20 Exception specifications</H2>
3596
3597
3598<p>
3599When C++ programs utilize exceptions, exceptional behavior is sometimes specified as
3600part of a function or method declaration. For example:
3601</p>
3602
3603<div class="code">
3604<pre>
3605class Error { };
3606
3607class Foo {
3608public:
3609 ...
3610 void blah() throw(Error);
3611 ...
3612};
3613</pre>
3614</div>
3615
3616<p>
3617If an exception specification is used, SWIG automatically generates wrapper code for catching the
3618indicated exception and converting it into an error in the target language. In certain language
3619modules, wrapped exception classes themselves can be used to catch errors. For example, in Python, you can
3620write code like this:
3621</p>
3622
3623<div class="targetlang">
3624<pre>
3625f = Foo()
3626try:
3627 f.blah()
3628except Error,e:
3629 # e is a wrapped instance of "Error"
3630</pre>
3631</div>
3632
3633<p>
3634Obviously, the exact details of how exceptions are handled depend on the target language module.
3635</p>
3636
3637<p>
3638Since exception specifications are sometimes only used sparingly, this alone may not be enough to
3639properly handle C++ exceptions. To do that, a different set of special SWIG directives are used.
3640Consult 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>
3647Starting with SWIG1.3.7, there is limited parsing support for pointers to C++ class members.
3648For example:
3649</p>
3650
3651<div class="code">
3652<pre>
3653double do_op(Object *o, double (Object::*callback)(double,double));
3654extern double (Object::*fooptr)(double,double);
3655%constant double (Object::*FOO)(double,double) = &amp;Object::foo;
3656</pre>
3657</div>
3658
3659<p>
3660Although these kinds of pointers can be parsed and represented by the
3661SWIG type system, few language modules know how to handle them due to
3662implementation differences from standard C pointers. Readers are
3663<em>strongly</em> advised to consult an advanced text such as the "The
3664Annotated C++ Manual" for specific details.
3665</p>
3666
3667<p>
3668When pointers to members are supported, the pointer value might appear as a special
3669string like this:
3670</p>
3671
3672<div class="targetlang">
3673<pre>
3674&gt;&gt;&gt; print example.FOO
3675_ff0d54a800000000_m_Object__f_double_double__double
3676&gt;&gt;&gt;
3677</pre>
3678</div>
3679
3680<p>
3681In this case, the hexadecimal digits represent the entire value of the
3682pointer which is usually the contents of a small C++ structure on most
3683machines.
3684</p>
3685
3686<p>
3687SWIG's type-checking mechanism is also more limited when working with
3688member pointers. Normally SWIG tries to keep track of inheritance
3689when checking types. However, no such support is currently provided
3690for member pointers.
3691</p>
3692
3693<H2><a name="SWIGPlus_nn34"></a>6.22 Smart pointers and operator-&gt;()</H2>
3694
3695
3696<p>
3697In some C++ programs, objects are often encapsulated by smart-pointers
3698or proxy classes. This is sometimes done to implement automatic memory management (reference counting) or
3699persistence. Typically a smart-pointer is defined by a template class where
3700the <tt>-&gt;</tt> operator has been overloaded. This class is then wrapped
3701around some other class. For example:
3702</p>
3703
3704<div class="code">
3705<pre>
3706// Smart-pointer class
3707template&lt;class T&gt; class SmartPtr {
3708 T *pointee;
3709public:
3710 ...
3711 T *operator-&gt;() {
3712 return pointee;
3713 }
3714 ...
3715};
3716
3717// Ordinary class
3718class Foo_Impl {
3719public:
3720 int x;
3721 virtual void bar();
3722 ...
3723};
3724
3725// Smart-pointer wrapper
3726typedef SmartPtr&lt;Foo_Impl&gt; Foo;
3727
3728// Create smart pointer Foo
3729Foo make_Foo() {
3730 return SmartPtr(new Foo_Impl());
3731}
3732
3733// Do something with smart pointer Foo
3734void do_something(Foo f) {
3735 printf("x = %d\n", f-&gt;x);
3736 f-&gt;bar();
3737}
3738</pre>
3739</div>
3740
3741<p>
3742A key feature of this approach is that by defining
3743<tt>operator-&gt;</tt> the methods and attributes of the object
3744wrapped by a smart pointer are transparently accessible. For example,
3745expressions such as these (from the previous example),
3746</p>
3747
3748<div class="code">
3749<pre>
3750f-&gt;x
3751f-&gt;bar()
3752</pre>
3753</div>
3754
3755<p>
3756are transparently mapped to the following
3757</p>
3758
3759<div class="code">
3760<pre>
3761(f.operator-&gt;())-&gt;x;
3762(f.operator-&gt;())-&gt;bar();
3763</pre>
3764</div>
3765
3766<p>
3767When generating wrappers, SWIG tries to emulate this functionality to
3768the extent that it is possible. To do this, whenever
3769<tt>operator-&gt;()</tt> is encountered in a class, SWIG looks at its
3770returned type and uses it to generate wrappers for accessing
3771attributes of the underlying object. For example, wrapping the above
3772code produces wrappers like this:
3773</p>
3774
3775<div class="code">
3776<pre>
3777int Foo_x_get(Foo *f) {
3778 return (*f)-&gt;x;
3779}
3780void Foo_x_set(Foo *f, int value) {
3781 (*f)-&gt;x = value;
3782}
3783void Foo_bar(Foo *f) {
3784 (*f)-&gt;bar();
3785}
3786</pre>
3787</div>
3788
3789<p>
3790These wrappers take a smart-pointer instance as an argument, but
3791dereference it in a way to gain access to the object returned by
3792<tt>operator-&gt;()</tt>. You should carefully compare these wrappers
3793to those in the first part of this chapter (they are slightly
3794different).
3795</p>
3796
3797<p>
3798The end result is that access looks very similar to C++. For
3799example, you could do this in Python:
3800</p>
3801
3802<div class="targetlang">
3803<pre>
3804&gt;&gt;&gt; f = make_Foo()
3805&gt;&gt;&gt; print f.x
38060
3807&gt;&gt;&gt; f.bar()
3808&gt;&gt;&gt;
3809</pre>
3810</div>
3811
3812<p>
3813When generating wrappers through a smart-pointer, SWIG tries to
3814generate wrappers for all methods and attributes that might be
3815accessible through <tt>operator-&gt;()</tt>. This includes any methods
3816that 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
3821pointer. 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
3825variable of the same name, then the smart-pointer version has precedence. For
3826example, if you have this code</p>
3827
3828<div class="code">
3829<pre>
3830class Foo {
3831public:
3832 int x;
3833};
3834
3835class Bar {
3836public:
3837 int x;
3838 Foo *operator-&gt;();
3839};
3840</pre>
3841</div>
3842
3843<p>
3844then the wrapper for <tt>Bar::x</tt> accesses the <tt>x</tt> defined in <tt>Bar</tt>, and
3845not the <tt>x</tt> defined in <tt>Foo</tt>.</p>
3846</li>
3847</ul>
3848
3849<p>
3850If your intent is to only expose the smart-pointer class in the interface, it is not necessary to wrap both
3851the smart-pointer class and the class for the underlying object. However, you must still tell SWIG about both
3852classes if you want the technique described in this section to work. To only generate wrappers for the
3853smart-pointer class, you can use the %ignore directive. For example:
3854</p>
3855
3856<div class="code">
3857<pre>
3858%ignore Foo;
3859class Foo { // Ignored
3860};
3861
3862class Bar {
3863public:
3864 Foo *operator-&gt;();
3865 ...
3866};
3867</pre>
3868</div>
3869
3870<p>
3871Alternatively, 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-&gt;()</tt>, the operator itself is wrapped
3877as a method <tt>__deref__()</tt>. For example:
3878</p>
3879
3880<div class="targetlang">
3881<pre>
3882f = Foo() # Smart-pointer
3883p = f.__deref__() # Raw pointer from operator-&gt;
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-&gt;()</tt>. For example:
3890</p>
3891
3892<div class="code">
3893<pre>
3894%ignore Bar::operator-&gt;;
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
3908base classes. For example:
3909</p>
3910
3911<div class="code">
3912<pre>
3913class Foo {
3914public:
3915 int blah(int x);
3916};
3917
3918class Bar {
3919public:
3920 double blah(double x);
3921};
3922
3923class FooBar : public Foo, public Bar {
3924public:
3925 using Foo::blah;
3926 using Bar::blah;
3927 char *blah(const char *x);
3928};
3929</pre>
3930</div>
3931
3932<p>
3933In this example, the <tt>using</tt> declarations make different
3934versions of the overloaded <tt>blah()</tt> method accessible from the
3935derived class. For example:
3936</p>
3937
3938<div class="code">
3939<pre>
3940FooBar *f;
3941f-&gt;blah(3); // Ok. Invokes Foo::blah(int)
3942f-&gt;blah(3.5); // Ok. Invokes Bar::blah(double)
3943f-&gt;blah("hello"); // Ok. Invokes FooBar::blah(const char *);
3944</pre>
3945</div>
3946
3947<p>
3948SWIG emulates the same functionality when creating wrappers. For example, if
3949you wrap this code in Python, the module works just like you would expect:
3950</p>
3951
3952<div class="targetlang">
3953<pre>
3954&gt;&gt;&gt; import example
3955&gt;&gt;&gt; f = example.FooBar()
3956&gt;&gt;&gt; f.blah(3)
3957&gt;&gt;&gt; f.blah(3.5)
3958&gt;&gt;&gt; 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>
3968class Foo {
3969protected:
3970 int x;
3971 int blah(int x);
3972};
3973
3974class Bar : public Foo {
3975public:
3976 using Foo::x; // Make x public
3977 using Foo::blah; // Make blah public
3978};
3979</pre>
3980</div>
3981
3982<p>
3983This also works in SWIG---the exposed declarations will be wrapped normally.
3984</p>
3985
3986<p>
3987When <tt>using</tt> declarations are used as shown in these examples, declarations
3988from the base classes are copied into the derived class and wrapped normally. When
3989copied, 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
3991ignored in a base class, it will also be ignored by a <tt>using</tt> declaration.
3992</p>
3993
3994<p>
3995Because a <tt>using</tt> declaration does not provide fine-grained
3996control over the declarations that get imported, it may be difficult
3997to manage such declarations in applications that make heavy use of
3998SWIG customization features. If you can't get <tt>using</tt> to work
3999correctly, you can always change the interface to the following:
4000</p>
4001
4002<div class="code">
4003<pre>
4004
4005class FooBar : public Foo, public Bar {
4006public:
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
4026won't cause a conflict. For example:</p>
4027
4028<div class="code">
4029<pre>
4030class Foo {
4031public:
4032 int blah(int );
4033 double blah(double);
4034};
4035
4036class Bar : public Foo {
4037public:
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
4045imported by <tt>using</tt>. For example:
4046</p>
4047
4048<div class="code">
4049<pre>
4050%rename(blah_long) Foo::blah(long);
4051class Foo {
4052public:
4053 int blah(int);
4054 long blah(long); // Renamed to blah_long
4055};
4056
4057class Bar : public Foo {
4058public:
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>
4070Since SWIG is still limited in its support of C++, it may be necessary
4071to use partial class information in an interface file. However, since
4072SWIG does not need the entire class specification to work, conditional
4073compilation can be used to comment out problematic parts. For example, if you had a nested
4074class definition, you might do this:
4075</p>
4076
4077<div class="code">
4078<pre>
4079class Foo {
4080public:
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>
4095Also, as a rule of thumb, SWIG should not be used on raw C++ source
4096files.
4097</p>
4098
4099<H2><a name="SWIGPlus_nn37"></a>6.25 A brief rant about const-correctness</H2>
4100
4101
4102<p>
4103A common issue when working with C++ programs is dealing with all
4104possible ways in which the <tt>const</tt> qualifier (or lack thereof)
4105will break your program, all programs linked against your program, and
4106all programs linked against those programs.
4107</p>
4108
4109<p>
4110Although SWIG knows how to correctly deal with <tt>const</tt> in its
4111internal type system and it knows how to generate wrappers that are
4112free of const-related warnings, SWIG does not make any attempt to preserve
4113const-correctness in the target language. Thus, it is possible to
4114pass <tt>const</tt> qualified objects to non-const methods and functions.
4115For example, consider the following code in C++:
4116</p>
4117
4118<div class="code">
4119<pre>
4120const Object * foo();
4121void bar(Object *);
4122
4123...
4124// C++ code
4125void blah() {
4126 bar(foo()); // Error: bar discards const
4127};
4128</pre>
4129</div>
4130
4131<p>
4132Now, consider the behavior when wrapped into a Python module:
4133</p>
4134
4135<div class="targetlang">
4136<pre>
4137&gt;&gt;&gt; bar(foo()) # Okay
4138&gt;&gt;&gt;
4139</pre>
4140</div>
4141
4142<p>
4143Although this is clearly a violation of the C++ type-system, fixing
4144the problem doesn't seem to be worth the added implementation
4145complexity that would be required to support it in the SWIG run-time type
4146system. There are no plans to change this in future releases
4147(although we'll never rule anything out entirely).
4148</p>
4149
4150<p>
4151The bottom line is that this particular issue does not appear to be a problem
4152for most SWIG projects. Of course, you might want to consider
4153using another tool if maintaining constness is the most important part
4154of your project.
4155</p>
4156
4157<H2><a name="SWIGPlus_nn38"></a>6.26 Proxy classes</H2>
4158
4159
4160<p>
4161In order to provide a more natural API, SWIG's target
4162languages wrap C++ classes with special proxy classes. These
4163proxy classes are typically implemented in the target language itself.
4164For example, if you're building a Python module, each C++ class is
4165wrapped by a Python class. Or if you're building a Java module, each
4166C++ 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>
4173Proxy classes are always constructed as an extra layer of wrapping that uses the low-level
4174accessor functions described in the previous section. To illustrate, suppose you had a
4175C++ class like this:
4176</p>
4177
4178<div class="code">
4179<pre>
4180class Foo {
4181public:
4182 Foo();
4183 ~Foo();
4184 int bar(int x);
4185 int x;
4186};
4187</pre>
4188</div>
4189
4190<p>
4191Using C++ as pseudocode, a proxy class looks something like this:
4192</p>
4193
4194<div class="code">
4195<pre>
4196class FooProxy {
4197private:
4198 Foo *self;
4199public:
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>
4220Of course, always keep in mind that the real proxy class is written in the target language.
4221For example, in Python, the proxy might look roughly like this:
4222</p>
4223
4224<div class="targetlang">
4225<pre>
4226class 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>
4245Again, it's important to emphasize that the low-level accessor functions are always used to construct the
4246proxy classes.
4247</p>
4248
4249<p>
4250Whenever possible, proxies try to take advantage of language features that are similar to C++. This
4251might 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>
4258A major issue with proxies concerns the memory management of wrapped objects. Consider the following
4259C++ code:
4260</p>
4261
4262<div class="code">
4263<pre>
4264class Foo {
4265public:
4266 Foo();
4267 ~Foo();
4268 int bar(int x);
4269 int x;
4270};
4271
4272class Spam {
4273public:
4274 Foo *value;
4275 ...
4276};
4277</pre>
4278</div>
4279
4280<p>
4281Now, consider some script code that uses these classes:
4282</p>
4283
4284<div class="targetlang">
4285<pre>
4286f = Foo() # Creates a new Foo
4287s = Spam() # Creates a new Spam
4288s.value = f # Stores a reference to f inside s
4289g = s.value # Returns stored reference
4290g = 4 # Reassign g to some other value
4291del f # Destroy f
4292</pre>
4293</div>
4294
4295<p>
4296Now, ponder the resulting memory management issues. When objects are
4297created in the script, the objects are wrapped by newly created proxy
4298classes. That is, there is both a new proxy class instance and a new
4299instance of the underlying C++ class. In this example, both
4300<tt>f</tt> and <tt>s</tt> are created in this way. However, the
4301statement <tt>s.value</tt> is rather curious---when executed, a
4302pointer to <tt>f</tt> is stored inside another object. This means
4303that the scripting proxy class <em>AND</em> another C++ class share a
4304reference to the same object. To make matters even more interesting,
4305consider the statement <tt>g = s.value</tt>. When executed, this
4306creates a new proxy class <tt>g</tt> that provides a wrapper around the
4307C++ object stored in <tt>s.value</tt>. In general, there is no way to
4308know where this object came from---it could have been created by the
4309script, but it could also have been generated internally. In this
4310particular example, the assignment of <tt>g</tt> results in a second
4311proxy class for <tt>f</tt>. In other words, a reference to <tt>f</tt>
4312is now shared by two proxy classes <em>and</em> a C++ class.
4313</p>
4314
4315<p>
4316Finally, consider what happens when objects are destroyed. In the
4317statement, <tt>g=4</tt>, the variable <tt>g</tt> is reassigned. In
4318many languages, this makes the old value of <tt>g</tt> available for
4319garbage collection. Therefore, this causes one of the proxy classes
4320to be destroyed. Later on, the statement <tt>del f</tt> destroys the
4321other proxy class. Of course, there is still a reference to the
4322original object stored inside another C++ object. What happens to it?
4323Is it the object still valid?
4324</p>
4325
4326<p>
4327To deal with memory management problems, proxy classes always provide an API
4328for controlling ownership. In C++ pseudocode, ownership control might look
4329roughly like this:
4330</p>
4331
4332<div class="code">
4333<pre>
4334class FooProxy {
4335public:
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
4356class FooPtrProxy: public FooProxy {
4357public:
4358 FooPtrProxy(Foo *s) {
4359 self = s;
4360 thisown = 0;
4361 }
4362};
4363
4364class 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-&gt;self);
4371 v-&gt;disown();
4372 }
4373 ...
4374};
4375</pre>
4376</div>
4377
4378<p>
4379Looking 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
4384if 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
4391class, 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
4395a 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>
4403Given the tricky nature of C++ memory management, it is impossible for proxy classes to automatically handle
4404every possible memory management problem. However, proxies do provide a mechanism for manual control that
4405can 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>
4412Language specific details on proxy classes are contained in the chapters describing each target language. This
4413chapter 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>
4420If you're wrapping serious C++ code, you might want to pick up a copy
4421of "The Annotated C++ Reference Manual" by Ellis and Stroustrup. This
4422is 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 -->