1 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
4 <title>SWIG and C++</title>
5 <link rel="stylesheet" type="text/css" href="style.css">
8 <body bgcolor="#ffffff">
9 <H1><a name="SWIGPlus"></a>6 SWIG and C++</H1>
11 <div class="sectiontoc">
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_nn38">Proxy classes</a>
19 <li><a href="#SWIGPlus_nn39">Construction of proxy classes</a>
20 <li><a href="#SWIGPlus_nn40">Resource management in proxies</a>
21 <li><a href="#SWIGPlus_nn41">Language specific details</a>
23 <li><a href="#SWIGPlus_nn6">Simple C++ wrapping</a>
25 <li><a href="#SWIGPlus_nn7">Constructors and destructors</a>
26 <li><a href="#SWIGPlus_nn8">Default constructors, copy constructors and implicit destructors</a>
27 <li><a href="#SWIGPlus_nn9">When constructor wrappers aren't created</a>
28 <li><a href="#SWIGPlus_nn10">Copy constructors</a>
29 <li><a href="#SWIGPlus_nn11">Member functions</a>
30 <li><a href="#SWIGPlus_nn12">Static members</a>
31 <li><a href="#SWIGPlus_member_data">Member data</a>
33 <li><a href="#SWIGPlus_default_args">Default arguments</a>
34 <li><a href="#SWIGPlus_nn15">Protection</a>
35 <li><a href="#SWIGPlus_nn16">Enums and constants</a>
36 <li><a href="#SWIGPlus_nn17">Friends</a>
37 <li><a href="#SWIGPlus_nn18">References and pointers</a>
38 <li><a href="#SWIGPlus_nn19">Pass and return by value</a>
39 <li><a href="#SWIGPlus_nn20">Inheritance</a>
40 <li><a href="#SWIGPlus_nn21">A brief discussion of multiple inheritance, pointers, and type checking</a>
41 <li><a href="#SWIGPlus_overloaded_methods">Wrapping Overloaded Functions and Methods</a>
43 <li><a href="#SWIGPlus_nn24">Dispatch function generation</a>
44 <li><a href="#SWIGPlus_nn25">Ambiguity in Overloading</a>
45 <li><a href="#ambiguity_resolution_renaming">Ambiguity resolution and renaming</a>
46 <li><a href="#SWIGPlus_nn27">Comments on overloading</a>
48 <li><a href="#SWIGPlus_nn28">Wrapping overloaded operators</a>
49 <li><a href="#SWIGPlus_class_extension">Class extension</a>
50 <li><a href="#SWIGPlus_nn30">Templates</a>
51 <li><a href="#SWIGPlus_nn31">Namespaces</a>
52 <li><a href="#SWIGPlus_renaming_templated_types_namespaces">Renaming templated types in namespaces</a>
53 <li><a href="#SWIGPlus_exception_specifications">Exception specifications</a>
54 <li><a href="#SWIGPlus_catches">Exception handling with %catches</a>
55 <li><a href="#SWIGPlus_nn33">Pointers to Members</a>
56 <li><a href="#SWIGPlus_nn34">Smart pointers and operator->()</a>
57 <li><a href="#SWIGPlus_nn35">Using declarations and inheritance</a>
58 <li><a href="#SWIGPlus_nested_classes">Nested classes</a>
59 <li><a href="#SWIGPlus_nn37">A brief rant about const-correctness</a>
60 <li><a href="#SWIGPlus_nn42">Where to go for more information</a>
68 This chapter describes SWIG's support for wrapping C++. As a prerequisite,
69 you should first read the chapter <a href="SWIG.html#SWIG">SWIG Basics</a> to see
70 how SWIG wraps ANSI C. Support for C++ builds upon ANSI C
71 wrapping and that material will be useful in understanding this chapter.
74 <H2><a name="SWIGPlus_nn2"></a>6.1 Comments on C++ Wrapping</H2>
78 Because of its complexity and the fact that C++ can be
79 difficult to integrate with itself let alone other languages, SWIG
80 only provides support for a subset of C++ features. Fortunately,
81 this is now a rather large subset.
85 In part, the problem with C++ wrapping is that there is no
86 semantically obvious (or automatic ) way to map many of its advanced
87 features into other languages. As a simple example, consider the
88 problem of wrapping C++ multiple inheritance to a target language with
89 no such support. Similarly, the use of overloaded operators and
90 overloaded functions can be problematic when no such capability exists
95 A more subtle issue with C++ has to do with the way that some C++
96 programmers think about programming libraries. In the world of SWIG,
97 you are really trying to create binary-level software components for
98 use in other languages. In order for this to work, a "component" has
99 to contain real executable instructions and there has to be some kind
100 of binary linking mechanism for accessing its functionality. In
101 contrast, C++ has increasingly relied upon generic programming and
102 templates for much of its functionality.
103 Although templates are a powerful feature, they are largely orthogonal
104 to the whole notion of binary components and libraries. For example,
105 an STL <tt>vector</tt> does not define any kind of binary object for
106 which SWIG can just create a wrapper. To further complicate matters,
107 these libraries often utilize a lot of behind the scenes magic in
108 which the semantics of seemingly basic operations (e.g., pointer
109 dereferencing, procedure call, etc.) can be changed in dramatic and
110 sometimes non-obvious ways. Although this "magic" may present few
111 problems in a C++-only universe, it greatly complicates the problem of
112 crossing language boundaries and provides many opportunities to shoot
113 yourself in the foot. You will just have to be careful.
116 <H2><a name="SWIGPlus_nn3"></a>6.2 Approach</H2>
120 To wrap C++, SWIG uses a layered approach to code generation.
121 At the lowest level, SWIG generates a collection of procedural ANSI-C style
122 wrappers. These wrappers take care of basic type conversion,
123 type checking, error handling, and other low-level details of the C++ binding.
124 These wrappers are also sufficient to bind C++ into any target language
125 that supports built-in procedures. In some sense, you might view this
126 layer of wrapping as providing a C library interface to C++.
127 On top of the low-level procedural (flattened) interface, SWIG generates proxy classes
128 that provide a natural object-oriented (OO) interface to the underlying code. The proxy classes are typically
129 written in the target language itself. For instance, in Python, a real
130 Python class is used to provide a wrapper around the underlying C++ object.
134 It is important to emphasize that SWIG takes a deliberately
135 conservative and non-intrusive approach to C++ wrapping. SWIG does not
136 encapsulate C++ classes inside a special C++ adaptor, it does not rely
137 upon templates, nor does it add in additional C++ inheritance when
138 generating wrappers. The last thing that most C++ programs need is
139 even more compiler magic. Therefore, SWIG tries to maintain a very
140 strict and clean separation between the implementation of your C++
141 application and the resulting wrapper code. You might say that SWIG
142 has been written to follow the principle of least surprise--it does
143 not play sneaky tricks with the C++ type system, it doesn't mess with
144 your class hierarchies, and it doesn't introduce new semantics.
145 Although this approach might not provide the most seamless integration
146 with C++, it is safe, simple, portable, and debuggable.
150 Some of this chapter focuses on the low-level procedural interface to
151 C++ that is used as the foundation for all language modules. Keep in
152 mind that the target languages also provide the high-level OO interface via
153 proxy classes. More detailed coverage can be found in the documentation
154 for each target language.
157 <H2><a name="SWIGPlus_nn4"></a>6.3 Supported C++ features</H2>
161 SWIG currently supports most C++ features including the following:</p>
165 <li>Constructors and destructors
166 <li>Virtual functions
167 <li>Public inheritance (including multiple inheritance)
169 <li>Function and method overloading
170 <li>Operator overloading for many standard operators
172 <li>Templates (including specialization and member templates)
173 <li>Pointers to members
175 <li>Default parameters
180 The following C++ features are not currently supported:</p>
183 <li>Overloaded versions of certain operators (new, delete, etc.)
184 <li>Nested classes, see <a href="#SWIGPlus_nested_classes">Nested classes</a> for workarounds.
188 As a rule of thumb, SWIG should not be used on raw C++ source files, use header files only.
192 SWIG's C++ support is an ongoing project so some of these limitations may be lifted
193 in future releases. However, we make no promises. Also, submitting a bug report is a very
194 good way to get problems fixed (wink).
197 <H2><a name="SWIGPlus_nn5"></a>6.4 Command line options and compilation</H2>
201 When wrapping C++ code, it is critical that SWIG be called with the
202 `<tt>-c++</tt>' option. This changes the way a number of critical
203 features such as memory management are handled. It
204 also enables the recognition of C++ keywords. Without the <tt>-c++</tt>
205 flag, SWIG will either issue a warning or a large number of syntax
206 errors if it encounters C++ code in an interface file.</p>
209 When compiling and linking the resulting wrapper file, it is normal
210 to use the C++ compiler. For example:
215 $ swig -c++ -tcl example.i
216 $ c++ -c example_wrap.cxx
217 $ c++ example_wrap.o $(OBJS) -o example.so
222 Unfortunately, the process varies slightly on each platform. Make sure
223 you refer to the documentation on each target language for further
224 details. The SWIG Wiki also has further details.
227 <b>Compatibility Note:</b> Early versions of SWIG generated just a flattened low-level C style API to C++ classes by default.
228 The <tt>-noproxy</tt> commandline option is recognised by many target languages and will generate just this
229 interface as in earlier versions.
231 <H2><a name="SWIGPlus_nn38"></a>6.5 Proxy classes</H2>
235 In order to provide a natural mapping from C++ classes to the target language classes, SWIG's target
236 languages mostly wrap C++ classes with special proxy classes. These
237 proxy classes are typically implemented in the target language itself.
238 For example, if you're building a Python module, each C++ class is
239 wrapped by a Python proxy class. Or if you're building a Java module, each
240 C++ class is wrapped by a Java proxy class.
243 <H3><a name="SWIGPlus_nn39"></a>6.5.1 Construction of proxy classes</H3>
247 Proxy classes are always constructed as an extra layer of wrapping that uses low-level
248 accessor functions. To illustrate, suppose you had a
265 Using C++ as pseudocode, a proxy class looks something like this:
281 return Foo_bar(self,x);
284 return Foo_x_get(self);
294 Of course, always keep in mind that the real proxy class is written in the target language.
295 For example, in Python, the proxy might look roughly like this:
298 <div class="targetlang">
302 self.this = new_Foo()
304 delete_Foo(self.this)
306 return Foo_bar(self.this,x)
307 def __getattr__(self,name):
309 return Foo_x_get(self.this)
311 def __setattr__(self,name,value):
313 Foo_x_set(self.this,value)
319 Again, it's important to emphasize that the low-level accessor functions are always used by the
321 Whenever possible, proxies try to take advantage of language features that are similar to C++. This
322 might include operator overloading, exception handling, and other features.
325 <H3><a name="SWIGPlus_nn40"></a>6.5.2 Resource management in proxies</H3>
329 A major issue with proxies concerns the memory management of wrapped objects. Consider the following
352 Consider some script code that uses these classes:
355 <div class="targetlang">
357 f = Foo() # Creates a new Foo
358 s = Spam() # Creates a new Spam
359 s.value = f # Stores a reference to f inside s
360 g = s.value # Returns stored reference
361 g = 4 # Reassign g to some other value
367 Now, ponder the resulting memory management issues. When objects are
368 created in the script, the objects are wrapped by newly created proxy
369 classes. That is, there is both a new proxy class instance and a new
370 instance of the underlying C++ class. In this example, both
371 <tt>f</tt> and <tt>s</tt> are created in this way. However, the
372 statement <tt>s.value</tt> is rather curious---when executed, a
373 pointer to <tt>f</tt> is stored inside another object. This means
374 that the scripting proxy class <em>AND</em> another C++ class share a
375 reference to the same object. To make matters even more interesting,
376 consider the statement <tt>g = s.value</tt>. When executed, this
377 creates a new proxy class <tt>g</tt> that provides a wrapper around the
378 C++ object stored in <tt>s.value</tt>. In general, there is no way to
379 know where this object came from---it could have been created by the
380 script, but it could also have been generated internally. In this
381 particular example, the assignment of <tt>g</tt> results in a second
382 proxy class for <tt>f</tt>. In other words, a reference to <tt>f</tt>
383 is now shared by two proxy classes <em>and</em> a C++ class.
387 Finally, consider what happens when objects are destroyed. In the
388 statement, <tt>g=4</tt>, the variable <tt>g</tt> is reassigned. In
389 many languages, this makes the old value of <tt>g</tt> available for
390 garbage collection. Therefore, this causes one of the proxy classes
391 to be destroyed. Later on, the statement <tt>del f</tt> destroys the
392 other proxy class. Of course, there is still a reference to the
393 original object stored inside another C++ object. What happens to it?
394 Is the object still valid?
398 To deal with memory management problems, proxy classes provide an API
399 for controlling ownership. In C++ pseudocode, ownership control might look
412 thisown = 1; // Newly created object
415 if (thisown) delete_Foo(self);
418 // Ownership control API
427 class FooPtrProxy: public FooProxy {
429 FooPtrProxy(Foo *s) {
437 FooProxy *value_get() {
438 return FooPtrProxy(Spam_value_get(self));
440 void value_set(FooProxy *v) {
441 Spam_value_set(self,v->self);
450 Looking at this code, there are a few central features:
454 <li>Each proxy class keeps an extra flag to indicate ownership. C++ objects are only destroyed
455 if the ownership flag is set.
458 <li>When new objects are created in the target language, the ownership flag is set.
461 <li>When a reference to an internal C++ object is returned, it is wrapped by a proxy
462 class, but the proxy class does not have ownership.
465 <li>In certain cases, ownership is adjusted. For instance, when a value is assigned to the member of
466 a class, ownership is lost.
469 <li>Manual ownership control is provided by special <tt>disown()</tt> and <tt>acquire()</tt> methods.
474 Given the tricky nature of C++ memory management, it is impossible for proxy classes to automatically handle
475 every possible memory management problem. However, proxies do provide a mechanism for manual control that
476 can be used (if necessary) to address some of the more tricky memory management problems.
479 <H3><a name="SWIGPlus_nn41"></a>6.5.3 Language specific details</H3>
483 Language specific details on proxy classes are contained in the chapters describing each target language. This
484 chapter has merely introduced the topic in a very general way.
487 <H2><a name="SWIGPlus_nn6"></a>6.6 Simple C++ wrapping</H2>
491 The following code shows a SWIG interface file for a simple C++
494 <div class="code"><pre>
500 // Very simple C++ example for linked list
506 int search(char *value);
511 static void print(List *l);
516 To generate wrappers for this class, SWIG first reduces the class to a collection of low-level C-style
517 accessor functions which are then used by the proxy classes.
520 <H3><a name="SWIGPlus_nn7"></a>6.6.1 Constructors and destructors</H3>
524 C++ constructors and destructors are translated into accessor
525 functions such as the following :</p>
527 <div class="code"><pre>
528 List * new_List(void) {
531 void delete_List(List *l) {
537 <H3><a name="SWIGPlus_nn8"></a>6.6.2 Default constructors, copy constructors and implicit destructors</H3>
541 Following the C++ rules for implicit constructor and destructors, SWIG
542 will automatically assume there is one even when they are not
543 explicitly declared in the class interface.
552 If a C++ class does not declare any explicit constructor, SWIG will
553 automatically generate a wrapper for one.
557 If a C++ class does not declare an explicit copy constructor, SWIG will
558 automatically generate a wrapper for one if the <tt>%copyctor</tt> is used.
562 If a C++ class does not declare an explicit destructor, SWIG will
563 automatically generate a wrapper for one.
568 And as in C++, a few rules that alters the previous behavior:
572 <li>A default constructor is not created if a class already defines a constructor with arguments.
575 <li>Default constructors are not generated for classes with pure virtual methods or for classes that
576 inherit from an abstract class, but don't provide definitions for all of the pure methods.
579 <li>A default constructor is not created unless all base classes support a
583 <li>Default constructors and implicit destructors are not created if a class
584 defines them in a <tt>private</tt> or <tt>protected</tt> section.
587 <li>Default constructors and implicit destructors are not created if any base
588 class defines a non-public default constructor or destructor.
593 SWIG should never generate a default constructor, copy constructor or
594 default destructor wrapper for a class in which it is illegal to do so. In
595 some cases, however, it could be necessary (if the complete class
596 declaration is not visible from SWIG, and one of the above rules is
597 violated) or desired (to reduce the size of the final interface) by
598 manually disabling the implicit constructor/destructor generation.
602 To manually disable these, the <tt>%nodefaultctor</tt> and <tt>%nodefaultdtor</tt>
603 <a href="Customization.html#Customization_feature_flags">feature flag</a> directives
604 can be used. Note that these directives only affects the
605 implicit generation, and they have no effect if the default/copy
606 constructors or destructor are explicitly declared in the class
616 %nodefaultctor Foo; // Disable the default constructor for class Foo.
617 class Foo { // No default constructor is generated, unless one is declared
620 class Bar { // A default constructor is generated, if possible
627 The directive <tt>%nodefaultctor</tt> can also be applied "globally", as in:
632 %nodefaultctor; // Disable creation of default constructors
633 class Foo { // No default constructor is generated, unless one is declared
638 Bar(); // The default constructor is generated, since one is declared
640 %clearnodefaultctor; // Enable the creation of default constructors again
645 The corresponding <tt>%nodefaultdtor</tt> directive can be used
646 to disable the generation of the default or implicit destructor, if
647 needed. Be aware, however, that this could lead to memory leaks in the
648 target language. Hence, it is recommended to use this directive only
649 in well known cases. For example:
654 %nodefaultdtor Foo; // Disable the implicit/default destructor for class Foo.
655 class Foo { // No destructor is generated, unless one is declared
662 <b>Compatibility Note:</b> The generation of default
663 constructors/implicit destructors was made the default behavior in SWIG
664 1.3.7. This may break certain older modules, but the old behavior can
665 be easily restored using <tt>%nodefault</tt> or the
666 <tt>-nodefault</tt> command line option. Furthermore, in order for
667 SWIG to properly generate (or not generate) default constructors, it
668 must be able to gather information from both the <tt>private</tt> and
669 <tt>protected</tt> sections (specifically, it needs to know if a private or
670 protected constructor/destructor is defined). In older versions of
671 SWIG, it was fairly common to simply remove or comment out
672 the private and protected sections of a class due to parser limitations.
673 However, this removal may now cause SWIG to erroneously generate constructors
674 for classes that define a constructor in those sections. Consider restoring
675 those sections in the interface or using <tt>%nodefault</tt> to fix the problem.
679 <b>Note:</b> The <tt>%nodefault</tt>
680 directive/<tt>-nodefault</tt> options described above, which disable both the default
681 constructor and the implicit destructors, could lead to memory
682 leaks, and so it is strongly recommended to not use them.
686 <H3><a name="SWIGPlus_nn9"></a>6.6.3 When constructor wrappers aren't created</H3>
690 If a class defines a constructor, SWIG normally tries to generate a wrapper for it. However, SWIG will
691 not generate a constructor wrapper if it thinks that it will result in illegal wrapper code. There are really
692 two cases where this might show up.
696 First, SWIG won't generate wrappers for protected or private constructors. For example:
703 Foo(); // Not wrapped.
711 Next, SWIG won't generate wrappers for a class if it appears to be abstract--that is, it has undefined
712 pure virtual methods. Here are some examples:
719 Bar(); // Not wrapped. Bar is abstract.
720 virtual void spam(void) = 0;
723 class Grok : public Bar {
725 Grok(); // Not wrapped. No implementation of abstract spam().
731 Some users are surprised (or confused) to find missing constructor wrappers in their interfaces. In almost
732 all cases, this is caused when classes are determined to be abstract. To see if this is the case, run SWIG with
733 all of its warnings turned on:
738 % swig -Wall -python module.i
743 In this mode, SWIG will issue a warning for all abstract classes. It is possible to force a class to be
744 non-abstract using this:
749 %feature("notabstract") Foo;
751 class Foo : public Bar {
753 Foo(); // Generated no matter what---not abstract.
760 More information about <tt>%feature</tt> can be found in the <a href="Customization.html#Customization">Customization features</a> chapter.
763 <H3><a name="SWIGPlus_nn10"></a>6.6.4 Copy constructors</H3>
767 If a class defines more than one constructor, its behavior depends on the capabilities of the
768 target language. If overloading is supported, the copy constructor is accessible using
769 the normal constructor function. For example, if you have this:
777 List(const List &); // Copy constructor
784 then the copy constructor can be used as follows:
787 <div class="targetlang">
789 x = List() # Create a list
790 y = List(x) # Copy list x
795 If the target language does not support overloading, then the copy constructor is available
796 through a special function like this:
801 List *copy_List(List *f) {
808 <b>Note:</b> For a class <tt>X</tt>, SWIG only treats a constructor as
809 a copy constructor if it can be applied to an object of type
810 <tt>X</tt> or <tt>X *</tt>. If more than one copy constructor is
811 defined, only the first definition that appears is used as the copy
812 constructor--other definitions will result in a name-clash.
813 Constructors such as <tt>X(const X &)</tt>, <tt>X(X &)</tt>, and
814 <tt>X(X *)</tt> are handled as copy constructors in SWIG.
818 <b>Note:</b> SWIG does <em>not</em> generate a copy constructor
819 wrapper unless one is explicitly declared in the class. This differs
820 from the treatment of default constructors and destructors.
821 However, copy constructor wrappers can be generated if using the <tt>copyctor</tt>
822 <a href="Customization.html#Customization_feature_flags">feature flag</a>. For example:
837 Will generate a copy constructor wrapper for <tt>List</tt>.
841 <b>Compatibility note:</b> Special support for copy constructors was
842 not added until SWIG-1.3.12. In previous versions, copy constructors
843 could be wrapped, but they had to be renamed. For example:
851 %name(CopyFoo) Foo(const Foo &);
858 For backwards compatibility, SWIG does not perform any special
859 copy-constructor handling if the constructor has been manually
860 renamed. For instance, in the above example, the name of the
861 constructor is set to <tt>new_CopyFoo()</tt>. This is the same as in
865 <H3><a name="SWIGPlus_nn11"></a>6.6.5 Member functions</H3>
869 All member functions are roughly translated into accessor functions like this :</p>
871 <div class="code"><pre>
872 int List_search(List *obj, char *value) {
873 return obj->search(value);
879 This translation is the same even if the member function has been
880 declared as <tt>virtual</tt>.
884 It should be noted that SWIG does not <em>actually</em> create a C accessor
885 function in the code it generates. Instead, member access such as
886 <tt>obj->search(value)</tt> is directly inlined into the generated
887 wrapper functions. However, the name and calling convention of the
888 low-level procedural wrappers match the accessor function prototype described above.
891 <H3><a name="SWIGPlus_nn12"></a>6.6.6 Static members</H3>
895 Static member functions are called directly without making any special
896 transformations. For example, the static member function
897 <tt>print(List *l)</tt> directly invokes <tt>List::print(List *l)</tt>
898 in the generated wrapper code.
901 <H3><a name="SWIGPlus_member_data"></a>6.6.7 Member data</H3>
905 Member data is handled in exactly the same manner as for C
906 structures. A pair of accessor functions are effectively created. For example
909 <div class="code"><pre>
910 int List_length_get(List *obj) {
911 return obj->length;
913 int List_length_set(List *obj, int value) {
914 obj->length = value;
921 A read-only member can be created using the <tt>%immutable</tt> and <tt>%mutable</tt>
922 <a href="Customization.html#Customization_feature_flags">feature flag</a> directive.
923 For example, we probably wouldn't want
924 the user to change the length of a list so we could do the following
925 to make the value available, but read-only.</p>
927 <div class="code"><pre>
939 Alternatively, you can specify an immutable member in advance like this:
944 %immutable List::length;
948 int length; // Immutable by above directive
955 Similarly, all data attributes declared as <tt>const</tt> are wrapped as read-only members.
959 There are some subtle issues when wrapping data members that are
960 themselves classes. For instance, if you had another class like this,
973 then the low-level accessor to the <tt>items</tt> member actually uses pointers. For example:
978 List *Foo_items_get(Foo *self) {
979 return &self->items;
981 void Foo_items_set(Foo *self, List *value) {
982 self->items = *value;
988 More information about this can be found in the SWIG Basics chapter,
989 <a href="SWIG.html#SWIG_structure_data_members">Structure data members</a> section.
993 The wrapper code to generate the accessors for classes comes from the pointer typemaps.
994 This can be somewhat unnatural for some types.
995 For example, a user would expect the STL std::string class member variables to be wrapped as a string in the target language,
996 rather than a pointer to this class.
997 The const reference typemaps offer this type of marshalling, so there is a feature to tell SWIG to use the const reference typemaps rather than the pointer typemaps.
998 It is the <tt>%naturalvar</tt> directive and is used as follows:
1003 // All List variables will use const List& typemaps
1006 // Only Foo::myList will use const List& typemaps
1007 %naturalvar Foo::myList;
1012 // All variables will use const reference typemaps
1018 The observant reader will notice that <tt>%naturalvar</tt> works like any other
1019 <a href="Customization.html#Customization_feature_flags">feature flag</a> directive,
1020 except it can also be attached to class types.
1021 The first of the example usages above show <tt>%naturalvar</tt> attaching to the <tt>List</tt> class.
1022 Effectively this feature changes the way accessors are generated to the following:
1027 const List &Foo_items_get(Foo *self) {
1028 return self->items;
1030 void Foo_items_set(Foo *self, const List &value) {
1031 self->items = value;
1037 In fact it is generally a good idea to use this feature globally as the reference typemaps have extra NULL checking compared to the pointer typemaps.
1038 A pointer can be NULL, whereas a reference cannot, so the extra checking ensures that the target language user does not pass in a value that translates
1039 to a NULL pointer and thereby preventing any potential NULL pointer dereferences.
1040 The <tt>%naturalvar</tt> feature will apply to global variables in addition to member variables in some language modules, eg C# and Java.
1044 Other alternatives for turning this feature on globally are to use the <tt>swig -naturalvar</tt> commandline option
1045 or the module mode option, <tt>%module(naturalvar=1)</tt>
1049 <b>Compatibility note:</b> The <tt>%naturalvar</tt> feature was introduced in SWIG-1.3.28, prior to which it was necessary to manually apply the const reference
1050 typemaps, eg <tt>%apply const std::string & { std::string * }</tt>, but this example would also apply the typemaps to methods taking a <tt>std::string</tt> pointer.
1054 <b>Compatibility note:</b> Read-only access used to be controlled by a pair of directives
1055 <tt>%readonly</tt> and <tt>%readwrite</tt>. Although these directives still work, they
1056 generate a warning message. Simply change the directives to <tt>%immutable;</tt> and
1057 <tt>%mutable;</tt> to silence the warning. Don't forget the extra semicolon!
1061 <b>Compatibility note:</b> Prior to SWIG-1.3.12, all members of unknown type were
1062 wrapped into accessor functions using pointers. For example, if you had a structure
1075 and nothing was known about <tt>size_t</tt>, then accessors would be
1076 written to work with <tt>size_t *</tt>. Starting in SWIG-1.3.12, this
1077 behavior has been modified. Specifically, pointers will <em>only</em>
1078 be used if SWIG knows that a datatype corresponds to a structure or
1079 class. Therefore, the above code would be wrapped into accessors
1080 involving <tt>size_t</tt>. This change is subtle, but it smooths over
1081 a few problems related to structure wrapping and some of SWIG's
1082 customization features.
1085 <H2><a name="SWIGPlus_default_args"></a>6.7 Default arguments</H2>
1089 SWIG will wrap all types of functions that have default arguments. For example member functions:
1096 void bar(int x, int y = 3, int z = 4);
1102 SWIG handles default arguments by generating an extra overloaded method for each defaulted argument.
1103 SWIG is effectively handling methods with default arguments as if it was wrapping the equivalent overloaded methods.
1104 Thus for the example above, it is as if we had instead given the following to SWIG:
1111 void bar(int x, int y, int z);
1112 void bar(int x, int y);
1119 The wrappers produced are exactly the same as if the above code was instead fed into SWIG.
1120 Details of this are covered later in the <a href="#SWIGPlus_overloaded_methods">Wrapping Overloaded Functions and Methods</a> section.
1121 This approach allows SWIG to wrap all possible default arguments, but can be verbose.
1122 For example if a method has ten default arguments, then eleven wrapper methods are generated.
1126 Please see the <a href="Customization.html#Customization_features_default_args">Features and default arguments</a>
1127 section for more information on using <tt>%feature</tt> with functions with default arguments.
1128 The <a href="#ambiguity_resolution_renaming">Ambiguity resolution and renaming</a> section
1129 also deals with using <tt>%rename</tt> and <tt>%ignore</tt> on methods with default arguments.
1130 If you are writing your own typemaps for types used in methods with default arguments, you may also need to write a <tt>typecheck</tt> typemap.
1131 See the <a href="Typemaps.html#Typemaps_overloading">Typemaps and overloading</a> section for details or otherwise
1132 use the <tt>compactdefaultargs</tt> feature flag as mentioned below.
1136 <b>Compatibility note:</b> Versions of SWIG prior to SWIG-1.3.23 wrapped default arguments slightly differently.
1137 Instead a single wrapper method was generated and the default values were copied into the C++ wrappers
1138 so that the method being wrapped was then called with all the arguments specified.
1139 If the size of the wrappers are a concern then this approach to wrapping methods with default arguments
1140 can be re-activated by using the <tt>compactdefaultargs</tt>
1141 <a href="Customization.html#Customization_feature_flags">feature flag</a>.
1146 %feature("compactdefaultargs") Foo::bar;
1149 void bar(int x, int y = 3, int z = 4);
1156 This is great for reducing the size of the wrappers, but the caveat is it does not work for the statically typed languages,
1157 such as C# and Java,
1158 which don't have optional arguments in the language,
1159 Another restriction of this feature is that it cannot handle default arguments that are not public.
1160 The following example illustrates this:
1167 static const int spam;
1169 void bar(int x, int y = spam); // Won't work with %feature("compactdefaultargs") -
1170 // private default value
1176 This produces uncompileable wrapper code because default values in C++ are
1177 evaluated in the same scope as the member function whereas SWIG
1178 evaluates them in the scope of a wrapper function (meaning that the
1179 values have to be public).
1183 This feature is automatically turned on when wrapping <a href="SWIG.html#SWIG_default_args">C code with default arguments</a>
1184 and whenever keyword arguments (kwargs) are specified for either C or C++ code.
1185 Keyword arguments are a language feature of some scripting languages, for example Ruby and Python.
1186 SWIG is unable to support kwargs when wrapping overloaded methods, so the default approach cannot be used.
1189 <H2><a name="SWIGPlus_nn15"></a>6.8 Protection</H2>
1193 SWIG wraps class members that are public following the C++
1194 conventions, i.e., by explicit public declaration or by the use of
1195 the <tt> using</tt> directive. In general, anything specified in a
1196 private or protected section will be ignored, although the internal
1197 code generator sometimes looks at the contents of the private and
1198 protected sections so that it can properly generate code for default
1199 constructors and destructors. Directors could also modify the way
1200 non-public virtual protected members are treated.
1204 By default, members of a class definition are assumed to be private
1205 until you explicitly give a `<tt>public:</tt>' declaration (This is
1206 the same convention used by C++).
1209 <H2><a name="SWIGPlus_nn16"></a>6.9 Enums and constants</H2>
1213 Enumerations and constants are handled differently by the different language modules and are described in detail in the appropriate language chapter.
1214 However, many languages map enums and constants in a class definition
1215 into constants with the classname as a prefix. For example :</p>
1217 <div class="code"><pre>
1220 enum {ALE, LAGER, PORTER, STOUT};
1225 Generates the following set of constants in the target scripting language :</p>
1227 <div class="targetlang"><pre>
1228 Swig_ALE = Swig::ALE
1229 Swig_LAGER = Swig::LAGER
1230 Swig_PORTER = Swig::PORTER
1231 Swig_STOUT = Swig::STOUT
1236 Members declared as <tt>const</tt> are wrapped as read-only members and do not create constants.
1239 <H2><a name="SWIGPlus_nn17"></a>6.10 Friends</H2>
1243 Friend declarations are recognised by SWIG. For example, if
1252 friend void blah(Foo *f);
1259 then the <tt>friend</tt> declaration does result in a wrapper code
1260 equivalent to one generated for the following declaration
1275 A friend declaration, as in C++, is understood to be in the same scope
1276 where the class is declared, hence, you can have
1282 %ignore bar::blah(Foo *f);
1289 friend void blah(Foo *f);
1297 and a wrapper for the method 'blah' will not be generated.
1300 <H2><a name="SWIGPlus_nn18"></a>6.11 References and pointers</H2>
1304 C++ references are supported, but SWIG transforms them back into pointers. For example,
1305 a declaration like this :</p>
1307 <div class="code"><pre>
1310 double bar(double &a);
1315 has a low-level accessor
1318 <div class="code"><pre>
1319 double Foo_bar(Foo *obj, double *a) {
1325 As a special case, most language modules pass <tt>const</tt> references to primitive datatypes (<tt>int</tt>, <tt>short</tt>,
1326 <tt>float</tt>, etc.) by value instead of pointers. For example, if you have a function like this,
1331 void foo(const int &x);
1336 it is called from a script as follows:
1339 <div class="targetlang">
1341 foo(3) # Notice pass by value
1346 Functions that return a reference are remapped to return a pointer instead.
1350 <div class="code"><pre>
1359 Generates an accessor like this:
1364 Foo *Bar_spam(Bar *obj) {
1365 Foo &result = obj->spam();
1372 However, functions that return <tt>const</tt> references to primitive datatypes (<tt>int</tt>, <tt>short</tt>, etc.) normally
1373 return the result as a value rather than a pointer. For example, a function like this,
1378 const int &bar();
1383 will return integers such as 37 or 42 in the target scripting language rather than a pointer to an integer.
1387 Don't return references to objects allocated as local variables on the
1388 stack. SWIG doesn't make a copy of the objects so this will probably
1389 cause your program to crash.
1394 <b>Note:</b> The special treatment for references to primitive datatypes is necessary to provide
1395 more seamless integration with more advanced C++ wrapping applications---especially related to
1396 templates and the STL. This was first added in SWIG-1.3.12.
1400 <H2><a name="SWIGPlus_nn19"></a>6.12 Pass and return by value</H2>
1404 Occasionally, a C++ program will pass and return class objects by value. For example, a function
1405 like this might appear:
1410 Vector cross_product(Vector a, Vector b);
1415 If no information is supplied about <tt>Vector</tt>, SWIG creates a wrapper function similar to the
1421 Vector *wrap_cross_product(Vector *a, Vector *b) {
1424 Vector r = cross_product(x,y);
1425 return new Vector(r);
1430 In order for the wrapper code to compile, <tt>Vector</tt> must define a copy constructor and a
1431 default constructor.
1435 If <tt>Vector</tt> is defined as a class in the interface, but it does not
1436 support a default constructor, SWIG changes the wrapper code by encapsulating
1437 the arguments inside a special C++ template wrapper class, through a process
1438 called the "Fulton Transform". This produces a wrapper that looks like this:
1443 Vector cross_product(Vector *a, Vector *b) {
1444 SwigValueWrapper<Vector> x = *a;
1445 SwigValueWrapper<Vector> y = *b;
1446 SwigValueWrapper<Vector> r = cross_product(x,y);
1447 return new Vector(r);
1453 This transformation is a little sneaky, but it provides support for
1454 pass-by-value even when a class does not provide a default constructor
1455 and it makes it possible to properly support a number of SWIG's
1456 customization options. The definition of <tt>SwigValueWrapper</tt>
1457 can be found by reading the SWIG wrapper code. This class is really nothing more than a thin
1458 wrapper around a pointer.
1462 Although SWIG usually detects the classes to which the Fulton Transform should
1463 be applied, in some situations it's necessary to override it. That's done with
1464 <tt>%feature("valuewrapper")</tt> to ensure it is used and <tt>%feature("novaluewrapper")</tt>
1465 to ensure it is not used:
1468 <div class="code"><pre>
1469 %feature("novaluewrapper") A;
1472 %feature("valuewrapper") B;
1480 It is well worth considering turning this feature on for classes that do have a default constructor.
1481 It will remove a redundant constructor call at the point of the variable declaration in the wrapper,
1482 so will generate notably better performance for large objects or for classes with expensive construction.
1483 Alternatively consider returning a reference or a pointer.
1487 <b>Note:</b> this transformation has no effect on typemaps
1488 or any other part of SWIG---it should be transparent except that you
1489 may see this code when reading the SWIG output file.
1494 Note: </b>This template transformation is new in SWIG-1.3.11 and may be refined in
1495 future SWIG releases. In practice, it is only absolutely necessary to do this for
1496 classes that don't define a default constructor.
1500 <b>Note:</b> The use of this template only occurs when objects are passed or returned by value.
1501 It is not used for C++ pointers or references.
1504 <H2><a name="SWIGPlus_nn20"></a>6.13 Inheritance</H2>
1508 SWIG supports C++ inheritance of classes and allows both single and
1509 multiple inheritance, as limited or allowed by the target
1510 language. The SWIG type-checker knows about the relationship between
1511 base and derived classes and allows pointers to any object of a
1512 derived class to be used in functions of a base class. The
1513 type-checker properly casts pointer values and is safe to use with
1514 multiple inheritance.
1517 <p> SWIG treats private or protected inheritance as close to the C++
1518 spirit, and target language capabilities, as possible. In most
1519 cases, this means that SWIG will parse the non-public inheritance
1520 declarations, but that will have no effect in the generated code,
1521 besides the implicit policies derived for constructor and
1527 The following example shows how SWIG handles inheritance. For clarity,
1528 the full C++ code has been omitted.</p>
1530 <div class="code"><pre>
1540 virtual double area() = 0;
1541 virtual double perimeter() = 0;
1542 void set_location(double x, double y);
1544 class Circle : public Shape {
1546 Circle(double radius);
1551 class Square : public Shape {
1553 Square(double size);
1561 When wrapped into Python, we can perform the following operations (shown using the low level Python accessors):
1564 <div class="targetlang"><pre>
1566 >>> import shapes
1567 >>> circle = shapes.new_Circle(7)
1568 >>> square = shapes.new_Square(10)
1569 >>> print shapes.Circle_area(circle)
1570 153.93804004599999757
1571 >>> print shapes.Shape_area(circle)
1572 153.93804004599999757
1573 >>> print shapes.Shape_area(square)
1574 100.00000000000000000
1575 >>> shapes.Shape_set_location(square,2,-3)
1576 >>> print shapes.Shape_perimeter(square)
1577 40.00000000000000000
1582 In this example, Circle and Square objects have been created. Member
1583 functions can be invoked on each object by making calls to
1584 <tt>Circle_area</tt>, <tt>Square_area</tt>, and so on. However, the same
1585 results can be accomplished by simply using the <tt>Shape_area</tt>
1586 function on either object.
1590 One important point concerning inheritance is that the low-level
1591 accessor functions are only generated for classes in which they are
1592 actually declared. For instance, in the above example, the method
1593 <tt>set_location()</tt> is only accessible as
1594 <tt>Shape_set_location()</tt> and not as
1595 <tt>Circle_set_location()</tt> or <tt>Square_set_location()</tt>. Of
1596 course, the <tt>Shape_set_location()</tt> function will accept any
1597 kind of object derived from Shape. Similarly, accessor functions for
1598 the attributes <tt>x</tt> and <tt>y</tt> are generated as
1599 <tt>Shape_x_get()</tt>, <tt>Shape_x_set()</tt>,
1600 <tt>Shape_y_get()</tt>, and <tt>Shape_y_set()</tt>. Functions such as
1601 <tt>Circle_x_get()</tt> are not available--instead you should use
1602 <tt>Shape_x_get()</tt>.
1606 Note that there is a one to one correlation between the low-level accessor functions and
1607 the proxy methods and therefore there is also a one to one correlation between
1608 the C++ class methods and the generated proxy class methods.
1612 <b>Note:</b> For the best results, SWIG requires all
1613 base classes to be defined in an interface. Otherwise, you may get a
1614 warning message like this:
1619 example.i:18: Warning(401): Nothing known about base class 'Foo'. Ignored.
1624 If any base class is undefined, SWIG still generates correct type
1625 relationships. For instance, a function accepting a <tt>Foo *</tt>
1626 will accept any object derived from <tt>Foo</tt> regardless of whether
1627 or not SWIG actually wrapped the <tt>Foo</tt> class. If you really
1628 don't want to generate wrappers for the base class, but you want to
1629 silence the warning, you might consider using the <tt>%import</tt>
1630 directive to include the file that defines <tt>Foo</tt>.
1631 <tt>%import</tt> simply gathers type information, but doesn't generate
1632 wrappers. Alternatively, you could just define <tt>Foo</tt> as an empty class
1633 in the SWIG interface or use
1634 <a href="Warnings.html#Warnings_suppression">warning suppression</a>.
1638 <b>Note:</b> <tt>typedef</tt>-names <em>can</em> be used as base classes. For example:
1648 class Bar : public FooObj { // Ok. Base class is Foo
1655 Similarly, <tt>typedef</tt> allows unnamed structures to be used as base classes. For example:
1664 class Bar : public Foo { // Ok.
1671 <b>Compatibility Note:</b> Starting in version 1.3.7, SWIG only
1672 generates low-level accessor wrappers for the declarations that are
1673 actually defined in each class. This differs from SWIG1.1 which used
1674 to inherit all of the declarations defined in base classes and
1675 regenerate specialized accessor functions such as
1676 <tt>Circle_x_get()</tt>, <tt>Square_x_get()</tt>,
1677 <tt>Circle_set_location()</tt>, and <tt>Square_set_location()</tt>.
1678 This behavior resulted in huge amounts of replicated code for large
1679 class hierarchies and made it awkward to build applications spread
1680 across multiple modules (since accessor functions are duplicated in
1681 every single module). It is also unnecessary to have such wrappers
1682 when advanced features like proxy classes are used.
1684 <b>Note:</b> Further optimizations are enabled when using the
1685 <tt>-fvirtual</tt> option, which avoids the regenerating of wrapper
1686 functions for virtual members that are already defined in a base
1690 <H2><a name="SWIGPlus_nn21"></a>6.14 A brief discussion of multiple inheritance, pointers, and type checking</H2>
1694 When a target scripting language refers to a C++ object, it normally
1695 uses a tagged pointer object that contains both the value of the
1696 pointer and a type string. For example, in Tcl, a C++ pointer might
1697 be encoded as a string like this:
1700 <div class="diagram">
1707 A somewhat common question is whether or not the type-tag could be safely
1708 removed from the pointer. For instance, to get better performance, could you
1709 strip all type tags and just use simple integers instead?
1713 In general, the answer to this question is no. In the wrappers, all
1714 pointers are converted into a common data representation in the target
1715 language. Typically this is the equivalent of casting a pointer to <tt>void *</tt>.
1716 This means that any C++ type information associated with the pointer is
1717 lost in the conversion.
1721 The problem with losing type information is that it is needed to
1722 properly support many advanced C++ features--especially multiple
1723 inheritance. For example, suppose you had code like this:
1738 class C : public A, public B {
1741 int A_function(A *a) {
1745 int B_function(B *b) {
1752 Now, consider the following code that uses <tt>void *</tt>.
1758 void *p = (void *) c;
1760 int x = A_function((A *) p);
1761 int y = B_function((B *) p);
1766 In this code, both <tt>A_function()</tt> and <tt>B_function()</tt> may
1767 legally accept an object of type <tt>C *</tt> (via inheritance).
1768 However, one of the functions will always return the wrong result when
1769 used as shown. The reason for this is that even though <tt>p</tt>
1770 points to an object of type <tt>C</tt>, the casting operation doesn't
1771 work like you would expect. Internally, this has to do with the data
1772 representation of <tt>C</tt>. With multiple inheritance, the data from
1773 each base class is stacked together. For example:
1776 <div class="diagram">
1778 ------------ <--- (C *), (A *)
1780 |------------| <--- (B *)
1787 Because of this stacking, a pointer of type <tt>C *</tt> may change
1788 value when it is converted to a <tt>A *</tt> or <tt>B *</tt>.
1789 However, this adjustment does <em>not</em> occur if you are converting from a
1794 The use of type tags marks all pointers with the real type of the
1795 underlying object. This extra information is then used by SWIG
1796 generated wrappers to correctly cast pointer values under inheritance
1797 (avoiding the above problem).
1801 Some of the language modules are able to solve the problem by storing multiple instances of the pointer, for example, <tt>A *</tt>,
1802 in the A proxy class as well as <tt>C *</tt> in the C proxy class. The correct cast can then be made by choosing the correct <tt>void *</tt>
1803 pointer to use and is guaranteed to work as the cast to a void pointer and back to the same type does not lose any type information:
1809 void *p = (void *) c;
1810 void *pA = (void *) c;
1811 void *pB = (void *) c;
1813 int x = A_function((A *) pA);
1814 int y = B_function((B *) pB);
1819 In practice, the pointer is held as an integral number in the target language proxy class.
1822 <H2><a name="SWIGPlus_overloaded_methods"></a>6.15 Wrapping Overloaded Functions and Methods</H2>
1826 In many language modules, SWIG provides partial support for overloaded functions, methods, and
1827 constructors. For example, if you supply SWIG with overloaded functions like this:
1833 printf("x is %d\n", x);
1836 printf("x is '%s'\n", x);
1842 The function is used in a completely natural way. For example:
1845 <div class="targetlang">
1849 >>> foo("hello")
1856 Overloading works in a similar manner for methods and constructors. For example if you have
1865 Foo(const Foo &); // Copy constructor
1867 void bar(char *s, int y);
1873 it might be used like this
1876 <div class="targetlang">
1878 >>> f = Foo() # Create a Foo
1879 >>> f.bar(3)
1880 >>> g = Foo(f) # Copy Foo
1881 >>> f.bar("hello",2)
1885 <H3><a name="SWIGPlus_nn24"></a>6.15.1 Dispatch function generation</H3>
1889 The implementation of overloaded functions and methods is somewhat
1890 complicated due to the dynamic nature of scripting languages. Unlike
1891 C++, which binds overloaded methods at compile time, SWIG must
1892 determine the proper function as a runtime check for scripting language targets. This check is
1893 further complicated by the typeless nature of certain scripting languages. For instance,
1894 in Tcl, all types are simply strings. Therefore, if you have two overloaded functions
1906 the order in which the arguments are checked plays a rather critical role.
1910 For statically typed languages, SWIG uses the language's method overloading mechanism.
1911 To implement overloading for the scripting languages, SWIG generates a dispatch function that checks the
1912 number of passed arguments and their types. To create this function, SWIG
1913 first examines all of the overloaded methods and ranks them according
1914 to the following rules:
1918 <li><b>Number of required arguments.</b> Methods are sorted by increasing number of
1921 <li><p><b>Argument type precedence.</b> All C++ datatypes are assigned a numeric type precedence value
1922 (which is determined by the language module).</p>
1924 <div class="diagram">
1927 ---------------- ----------
1938 Using these precedence values, overloaded methods with the same number of required arguments are sorted in increased
1939 order of precedence values.
1945 This may sound very confusing, but an example will help. Consider the following collection of
1955 void foo(int x, int y, int z, int w);
1956 void foo(int x, int y, int z = 3);
1957 void foo(double x, double y);
1958 void foo(double x, Bar *z);
1963 The first rule simply ranks the functions by required argument count.
1964 This would produce the following list:
1967 <div class="diagram">
1975 [4] foo(int x, int y, int z = 3);
1976 [5] foo(double x, double y)
1977 [6] foo(double x, Bar *z)
1978 [7] foo(int x, int y, int z, int w);
1983 The second rule, simply refines the ranking by looking at argument type precedence values.
1986 <div class="diagram">
1994 [4] foo(int x, int y, int z = 3);
1995 [5] foo(double x, Bar *z)
1996 [6] foo(double x, double y)
1997 [7] foo(int x, int y, int z, int w);
2002 Finally, to generate the dispatch function, the arguments passed to an overloaded method are simply
2003 checked in the same order as they appear in this ranking.
2007 If you're still confused, don't worry about it---SWIG is probably doing the right thing.
2010 <H3><a name="SWIGPlus_nn25"></a>6.15.2 Ambiguity in Overloading</H3>
2014 Regrettably, SWIG is not able to support every possible use of valid C++ overloading. Consider
2015 the following example:
2026 In C++, this is perfectly legal. However, in a scripting language, there is generally only one kind of integer
2027 object. Therefore, which one of these functions do you pick? Clearly, there is no way to truly make a distinction
2028 just by looking at the value of the integer itself (<tt>int</tt> and <tt>long</tt> may even be the same precision).
2029 Therefore, when SWIG encounters this situation, it may generate a warning message like this for scripting languages:
2034 example.i:4: Warning(509): Overloaded foo(long) is shadowed by foo(int) at example.i:3.
2039 or for statically typed languages like Java:
2044 example.i:4: Warning(516): Overloaded method foo(long) ignored. Method foo(int)
2045 at example.i:3 used.
2050 This means that the second overloaded function will be inaccessible
2051 from a scripting interface or the method won't be wrapped at all.
2052 This is done as SWIG does not know how to disambiguate it from an earlier method.
2056 Ambiguity problems are known to arise in the following situations:
2060 <li>Integer conversions. Datatypes such as <tt>int</tt>, <tt>long</tt>, and <tt>short</tt> cannot be disambiguated in some languages. Shown above.
2063 <li>Floating point conversion. <tt>float</tt> and <tt>double</tt> can not be disambiguated in some languages.
2066 <li>Pointers and references. For example, <tt>Foo *</tt> and <tt>Foo &</tt>.
2069 <li>Pointers and arrays. For example, <tt>Foo *</tt> and <tt>Foo [4]</tt>.
2072 <li>Pointers and instances. For example, <tt>Foo</tt> and <tt>Foo *</tt>. Note: SWIG converts all
2073 instances to pointers.
2076 <li>Qualifiers. For example, <tt>const Foo *</tt> and <tt>Foo *</tt>.
2079 <li>Default vs. non default arguments. For example, <tt>foo(int a, int b)</tt> and <tt>foo(int a, int b = 3)</tt>.
2084 When an ambiguity arises, methods are checked in the same order as they appear in the interface file.
2085 Therefore, earlier methods will shadow methods that appear later.
2089 When wrapping an overloaded function, there is a chance that you will get an error message like this:
2094 example.i:3: Warning(467): Overloaded foo(int) not supported (no type checking
2100 This error means that the target language module supports overloading,
2101 but for some reason there is no type-checking rule that can be used to
2102 generate a working dispatch function. The resulting behavior is then
2103 undefined. You should report this as a bug to the
2104 <a href="http://www.swig.org/bugs.html">SWIG bug tracking database</a>.
2108 If you get an error message such as the following,
2113 foo.i:6. Overloaded declaration ignored. Spam::foo(double )
2114 foo.i:5. Previous declaration is Spam::foo(int )
2115 foo.i:7. Overloaded declaration ignored. Spam::foo(Bar *,Spam *,int )
2116 foo.i:5. Previous declaration is Spam::foo(int )
2121 it means that the target language module has not yet implemented support for overloaded
2122 functions and methods. The only way to fix the problem is to read the next section.
2125 <H3><a name="ambiguity_resolution_renaming"></a>6.15.3 Ambiguity resolution and renaming</H3>
2129 If an ambiguity in overload resolution occurs or if a module doesn't
2130 allow overloading, there are a few strategies for dealing with the
2131 problem. First, you can tell SWIG to ignore one of the methods. This
2132 is easy---simply use the <tt>%ignore</tt> directive. For example:
2140 void foo(long); // Ignored. Oh well.
2145 The other alternative is to rename one of the methods. This can be
2146 done using <tt>%rename</tt>. For example:
2151 %rename("foo_short") foo(short);
2152 %rename(foo_long) foo(long);
2155 void foo(short); // Accessed as foo_short()
2156 void foo(long); // Accessed as foo_long()
2161 Note that the quotes around the new name are optional, however,
2162 should the new name be a C/C++ keyword they would be essential in order to avoid a parsing error.
2163 The <tt>%ignore</tt> and <tt>%rename</tt> directives are both rather powerful
2164 in their ability to match declarations. When used in their simple form, they apply to
2165 both global functions and methods. For example:
2170 /* Forward renaming declarations */
2171 %rename(foo_i) foo(int);
2172 %rename(foo_d) foo(double);
2174 void foo(int); // Becomes 'foo_i'
2175 void foo(char *c); // Stays 'foo' (not renamed)
2179 void foo(int); // Becomes 'foo_i'
2180 void foo(double); // Becomes 'foo_d'
2187 If you only want the renaming to apply to a certain scope, the C++ scope resolution operator (::) can be used.
2193 %rename(foo_i) ::foo(int); // Only rename foo(int) in the global scope.
2194 // (will not rename class members)
2196 %rename(foo_i) Spam::foo(int); // Only rename foo(int) in class Spam
2201 When a renaming operator is applied to a class as in <tt>Spam::foo(int)</tt>, it is applied to
2202 that class and all derived classes. This can be used to apply a consistent renaming across
2203 an entire class hierarchy with only a few declarations. For example:
2208 %rename(foo_i) Spam::foo(int);
2209 %rename(foo_d) Spam::foo(double);
2213 virtual void foo(int); // Renamed to foo_i
2214 virtual void foo(double); // Renamed to foo_d
2218 class Bar : public Spam {
2220 virtual void foo(int); // Renamed to foo_i
2221 virtual void foo(double); // Renamed to foo_d
2225 class Grok : public Bar {
2227 virtual void foo(int); // Renamed to foo_i
2228 virtual void foo(double); // Renamed to foo_d
2235 It is also possible to include <tt>%rename</tt> specifications in the
2236 class definition itself. For example:
2242 %rename(foo_i) foo(int);
2243 %rename(foo_d) foo(double);
2245 virtual void foo(int); // Renamed to foo_i
2246 virtual void foo(double); // Renamed to foo_d
2250 class Bar : public Spam {
2252 virtual void foo(int); // Renamed to foo_i
2253 virtual void foo(double); // Renamed to foo_d
2260 In this case, the <tt>%rename</tt> directives still get applied across the entire
2261 inheritance hierarchy, but it's no longer necessary to explicitly specify the
2262 class prefix <tt>Spam::</tt>.
2266 A special form of <tt>%rename</tt> can be used to apply a renaming just to class
2267 members (of all classes):
2272 %rename(foo_i) *::foo(int); // Only rename foo(int) if it appears in a class.
2277 Note: the <tt>*::</tt> syntax is non-standard C++, but the '*' is meant to be a
2278 wildcard that matches any class name (we couldn't think of a better
2279 alternative so if you have a better idea, send email to
2280 the <a href="http://www.swig.org/mail.html">swig-devel mailing list</a>.
2284 Although this discussion has primarily focused on <tt>%rename</tt> all of the same rules
2285 also apply to <tt>%ignore</tt>. For example:
2290 %ignore foo(double); // Ignore all foo(double)
2291 %ignore Spam::foo; // Ignore foo in class Spam
2292 %ignore Spam::foo(double); // Ignore foo(double) in class Spam
2293 %ignore *::foo(double); // Ignore foo(double) in all classes
2298 When applied to a base class, <tt>%ignore</tt> forces all definitions in derived classes
2299 to disappear. For example, <tt>%ignore Spam::foo(double)</tt> will eliminate <tt>foo(double)</tt> in
2300 <tt>Spam</tt> and all classes derived from <tt>Spam</tt>.
2304 <b>Notes on %rename and %ignore:</b>
2308 <li><p>Since, the <tt>%rename</tt> declaration is used to declare a renaming in advance, it can be
2309 placed at the start of an interface file. This makes it possible to apply a consistent name
2310 resolution without having to modify header files. For example:</p>
2316 /* Rename these overloaded functions */
2317 %rename(foo_i) foo(int);
2318 %rename(foo_d) foo(double);
2325 <li><p>The scope qualifier (::) can also be used on simple names. For example:</p>
2328 %rename(bar) ::foo; // Rename foo to bar in global scope only
2329 %rename(bar) Spam::foo; // Rename foo to bar in class Spam only
2330 %rename(bar) *::foo; // Rename foo in classes only
2335 <li><p>Name matching tries to find the most specific match that is
2336 defined. A qualified name such as <tt>Spam::foo</tt> always has
2337 higher precedence than an unqualified name <tt>foo</tt>.
2338 <tt>Spam::foo</tt> has higher precedence than <tt>*::foo</tt> and
2339 <tt>*::foo</tt> has higher precedence than <tt>foo</tt>. A
2340 parameterized name has higher precedence than an unparameterized name
2341 within the same scope level. However, an unparameterized name with a
2342 scope qualifier has higher precedence than a parameterized name in
2343 global scope (e.g., a renaming of <tt>Spam::foo</tt> takes precedence
2344 over a renaming of <tt>foo(int)</tt>).</p>
2348 The order in which <tt>%rename</tt> directives are defined does not matter
2349 as long as they appear before the declarations to be renamed. Thus, there is no difference
2355 %rename(foo_i) Spam::foo(int);
2356 %rename(Foo) Spam::foo;
2366 %rename(Foo) Spam::foo;
2368 %rename(foo_i) Spam::foo(int);
2373 (the declarations are not stored in a linked list and order has no
2374 importance). Of course, a repeated <tt>%rename</tt> directive will
2375 change the setting for a previous <tt>%rename</tt> directive if exactly the
2376 same name, scope, and parameters are supplied.
2380 <li>For multiple inheritance where renaming rules are defined for multiple base classes,
2381 the first renaming rule found on a depth-first traversal of the class hierarchy
2385 <li><p>The name matching rules strictly follow member qualification rules.
2386 For example, if you have a class like this:</p>
2405 %rename(name) Spam::bar();
2410 will not apply as there is no unqualified member <tt>bar()</tt>. The following will apply as
2411 the qualifier matches correctly:
2416 %rename(name) Spam::bar() const;
2421 An often overlooked C++ feature is that classes can define two different overloaded members
2422 that differ only in their qualifiers, like this:
2430 void bar(); // Unqualified member
2431 void bar() const; // Qualified member
2438 %rename can then be used to target each of the overloaded methods individually.
2439 For example we can give them separate names in the target language:
2444 %rename(name1) Spam::bar();
2445 %rename(name2) Spam::bar() const;
2451 merely wanted to ignore one of the declarations, use <tt>%ignore</tt>
2452 with the full qualification. For example, the following directive
2453 would tell SWIG to ignore the <tt>const</tt> version of <tt>bar()</tt>
2459 %ignore Spam::bar() const; // Ignore bar() const, but leave other bar() alone
2466 Currently no resolution is performed in order to match function parameters. This means function parameter types must match exactly.
2467 For example, namespace qualifiers and typedefs will not work. The following usage of typedefs demonstrates this:
2471 typedef int Integer;
2473 %rename(foo_i) foo(int);
2477 void foo(Integer); // Stays 'foo' (not renamed)
2481 void foo(int); // Renamed to foo_i
2487 The name matching rules also use default arguments for finer control when wrapping methods that have default arguments.
2488 Recall that methods with default arguments are wrapped as if the equivalent overloaded methods had been parsed
2489 (<a href="#SWIGPlus_default_args">Default arguments</a> section).
2490 Let's consider the following example class:</p>
2497 void bar(int i=-1, double d=0.0);
2504 The following <tt>%rename</tt> will match exactly and apply to all the target language overloaded methods because the declaration with the default arguments
2505 exactly matches the wrapped method:
2510 %rename(newbar) Spam::bar(int i=-1, double d=0.0);
2515 The C++ method can then be called from the target language with the new name no matter how many arguments are specified, for example:
2516 <tt>newbar(2, 2.0)</tt>, <tt>newbar(2)</tt> or <tt>newbar()</tt>.
2517 However, if the <tt>%rename</tt> does not contain the default arguments, it will only apply to the single equivalent target language overloaded method.
2518 So if instead we have:
2523 %rename(newbar) Spam::bar(int i, double d);
2528 The C++ method must then be called from the target language with the new name <tt>newbar(2, 2.0)</tt> when both arguments are supplied
2529 or with the original name as <tt>bar(2)</tt> (one argument) or <tt>bar()</tt> (no arguments).
2530 In fact it is possible to use <tt>%rename</tt> on the equivalent overloaded methods, to rename all the equivalent overloaded methods:
2535 %rename(bar_2args) Spam::bar(int i, double d);
2536 %rename(bar_1arg) Spam::bar(int i);
2537 %rename(bar_default) Spam::bar();
2542 Similarly, the extra overloaded methods can be selectively ignored using <tt>%ignore</tt>.
2546 <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
2547 to wrapping methods with default arguments was introduced.
2554 <H3><a name="SWIGPlus_nn27"></a>6.15.4 Comments on overloading</H3>
2558 Support for overloaded methods was first added in SWIG-1.3.14. The implementation
2559 is somewhat unusual when compared to similar tools. For instance, the order in which
2560 declarations appear is largely irrelevant in SWIG. Furthermore, SWIG does not rely
2561 upon trial execution or exception handling to figure out which method to invoke.
2565 Internally, the overloading mechanism is completely configurable by the target language
2566 module. Therefore, the degree of overloading support may vary from language to language.
2567 As a general rule, statically typed languages like Java are able to provide more support
2568 than dynamically typed languages like Perl, Python, Ruby, and Tcl.
2571 <H2><a name="SWIGPlus_nn28"></a>6.16 Wrapping overloaded operators</H2>
2575 C++ overloaded operator declarations can be wrapped.
2576 For example, consider a class like this:
2583 double rpart, ipart;
2585 Complex(double r = 0, double i = 0) : rpart(r), ipart(i) { }
2586 Complex(const Complex &c) : rpart(c.rpart), ipart(c.ipart) { }
2587 Complex &operator=(const Complex &c) {
2592 Complex operator+(const Complex &c) const {
2593 return Complex(rpart+c.rpart, ipart+c.ipart);
2595 Complex operator-(const Complex &c) const {
2596 return Complex(rpart-c.rpart, ipart-c.ipart);
2598 Complex operator*(const Complex &c) const {
2599 return Complex(rpart*c.rpart - ipart*c.ipart,
2600 rpart*c.ipart + c.rpart*ipart);
2602 Complex operator-() const {
2603 return Complex(-rpart, -ipart);
2605 double re() const { return rpart; }
2606 double im() const { return ipart; }
2612 When operator declarations appear, they are handled in
2613 <em>exactly</em> the same manner as regular methods. However, the
2614 names of these methods are set to strings like "<tt>operator +</tt>"
2615 or "<tt>operator -</tt>". The problem with these names is that they
2616 are illegal identifiers in most scripting languages. For instance,
2617 you can't just create a method called "<tt>operator +</tt>" in
2618 Python--there won't be any way to call it.
2622 Some language modules already know how to automatically handle certain
2623 operators (mapping them into operators in the target language).
2624 However, the underlying implementation of this is really managed in a
2625 very general way using the <tt>%rename</tt> directive. For example,
2626 in Python a declaration similar to this is used:
2631 %rename(__add__) Complex::operator+;
2636 This binds the + operator to a method called <tt>__add__</tt> (which
2637 is conveniently the same name used to implement the Python + operator).
2638 Internally, the generated wrapper code for a wrapped operator will look
2639 something like this pseudocode:
2644 _wrap_Complex___add__(args) {
2646 obj->operator+(args);
2653 When used in the target language, it may now be possible to use the overloaded
2654 operator normally. For example:
2657 <div class="targetlang">
2659 >>> a = Complex(3,4)
2660 >>> b = Complex(5,2)
2661 >>> c = a + b # Invokes __add__ method
2666 It is important to realize that there is nothing magical happening
2667 here. The <tt>%rename</tt> directive really only picks a valid method
2668 name. If you wrote this:
2673 %rename(add) operator+;
2678 The resulting scripting interface might work like this:
2681 <div class="targetlang">
2685 c = a.add(b) # Call a.operator+(b)
2690 All of the techniques described to deal with overloaded functions also
2691 apply to operators. For example:
2696 %ignore Complex::operator=; // Ignore = in class Complex
2697 %ignore *::operator=; // Ignore = in all classes
2698 %ignore operator=; // Ignore = everywhere.
2700 %rename(__sub__) Complex::operator-;
2701 %rename(__neg__) Complex::operator-(); // Unary -
2706 The last part of this example illustrates how multiple definitions of
2707 the <tt>operator-</tt> method might be handled.
2711 Handling operators in this manner is mostly straightforward. However, there are a few subtle
2712 issues to keep in mind:
2716 <li><p>In C++, it is fairly common to define different versions of the operators to account for
2717 different types. For example, a class might also include a friend function like this:</p>
2723 friend Complex operator+(Complex &, double);
2725 Complex operator+(Complex &, double);
2730 SWIG simply ignores all <tt>friend</tt> declarations. Furthermore, it
2731 doesn't know how to associate the associated <tt>operator+</tt> with
2732 the class (because it's not a member of the class).
2736 It's still possible to make a wrapper for this operator, but you'll
2737 have to handle it like a normal function. For example:
2742 %rename(add_complex_double) operator+(Complex &, double);
2747 <li><p>Certain operators are ignored by default. For instance, <tt>new</tt> and <tt>delete</tt> operators
2748 are ignored as well as conversion operators.
2751 <li>The semantics of certain C++ operators may not match those in the target language.
2755 <H2><a name="SWIGPlus_class_extension"></a>6.17 Class extension</H2>
2759 New methods can be added to a class using the <tt>%extend</tt>
2760 directive. This directive is primarily used in conjunction with proxy
2761 classes to add additional functionality to an existing class. For
2765 <div class="code"><pre>
2776 ... bunch of C++ methods ...
2779 static char temp[256];
2780 sprintf(temp,"[ %g, %g, %g ]", $self->x,$self->y,$self->z);
2781 return &temp[0];
2788 This code adds a<tt> __str__</tt> method to our class for producing a
2789 string representation of the object. In Python, such a method would
2790 allow us to print the value of an object using the <tt>print</tt>
2794 <div class="targetlang"><pre>
2796 >>> v = Vector();
2797 >>> v.x = 3
2798 >>> v.y = 4
2799 >>> v.z = 0
2800 >>> print(v)
2807 The C++ 'this' pointer is often needed to access member variables, methods etc.
2808 The <tt>$self</tt> special variable should be used wherever you could use 'this'.
2809 The example above demonstrates this for accessing member variables.
2810 Note that the members dereferenced by <tt>$self</tt> must be public members as the code is ultimately generated
2811 into a global function and so will not have any access to non-public members.
2812 The implicit 'this' pointer that is present in C++ methods is not present in <tt>%extend</tt> methods.
2813 In order to access anything in the extended class or its base class, an explicit 'this' is required.
2814 The following example shows how one could access base class members:
2817 <div class="code"><pre>
2819 virtual void method(int v) {
2824 struct Derived : Base {
2827 virtual void method(int v) {
2828 $self->Base::method(v); // akin to this->Base::method(v);
2829 $self->value = v; // akin to this->value = v;
2836 The<tt> %extend</tt> directive follows all of the same conventions
2837 as its use with C structures. Please refer to the <a href="SWIG.html#SWIG_adding_member_functions">Adding member functions to C structures</a>
2838 section for further details.
2842 <b>Compatibility note:</b> The <tt>%extend</tt> directive is a new
2843 name for the <tt>%addmethods</tt> directive in SWIG1.1. Since <tt>%addmethods</tt> could
2844 be used to extend a structure with more than just methods, a more suitable
2845 directive name has been chosen.
2848 <H2><a name="SWIGPlus_nn30"></a>6.18 Templates</H2>
2852 Template type names may appear anywhere a type
2853 is expected in an interface file. For example:
2858 void foo(vector<int> *a, int n);
2859 void bar(list<int,100> *x);
2864 There are some restrictions on the use of non-type arguments. Simple literals
2865 are supported, and so are some constant expressions. However, use of '<'
2866 and '>' within a constant expressions currently is not supported by SWIG
2867 ('<=' and '>=' are though). For example:
2872 void bar(list<int,100> *x); // OK
2873 void bar(list<int,2*50> *x); // OK
2874 void bar(list<int,(2>1 ? 100 : 50)> *x) // Not supported
2879 The type system is smart enough to figure out clever games
2880 you might try to play with <tt>typedef</tt>. For instance, consider this code:
2885 typedef int Integer;
2886 void foo(vector<int> *x, vector<Integer> *y);
2891 In this case, <tt>vector<Integer></tt> is exactly the same type
2892 as <tt>vector<int></tt>. The wrapper for <tt>foo()</tt> will
2893 accept either variant.
2897 Starting with SWIG-1.3.7, simple C++ template declarations can also be
2898 wrapped. SWIG-1.3.12 greatly expands upon the earlier implementation. Before discussing this any further, there are a few things
2899 you need to know about template wrapping. First, a bare C++ template
2900 does not define any sort of runnable object-code for which SWIG can
2901 normally create a wrapper. Therefore, in order to wrap a template,
2902 you need to give SWIG information about a particular template
2903 instantiation (e.g., <tt>vector<int></tt>,
2904 <tt>array<double></tt>, etc.). Second, an instantiation name
2905 such as <tt>vector<int></tt> is generally not a valid identifier
2906 name in most target languages. Thus, you will need to give the
2907 template instantiation a more suitable name such as <tt>intvector</tt>
2908 when creating a wrapper.
2912 To illustrate, consider the following template definition:
2915 <div class="code"><pre>
2916 template<class T> class List {
2930 void append(T obj) {
2931 if (nitems < maxitems) {
2932 data[nitems++] = obj;
2945 By itself, this template declaration is useless--SWIG simply ignores it
2946 because it doesn't know how to generate any code until unless a definition of
2947 <tt>T</tt> is provided.
2951 One way to create wrappers for a specific template instantiation is to simply
2952 provide an expanded version of the class directly like this:
2957 %rename(intList) List<int>; // Rename to a suitable identifier
2958 class List<int> {
2966 void append(int obj);
2975 The <tt>%rename</tt> directive is needed to give the template class an appropriate identifier
2976 name in the target language (most languages would not recognize C++ template syntax as a valid
2977 class name). The rest of the code is the same as what would appear in a normal
2982 Since manual expansion of templates gets old in a hurry, the <tt>%template</tt> directive can
2983 be used to create instantiations of a template class. Semantically, <tt>%template</tt> is
2984 simply a shortcut---it expands template code in exactly the same way as shown above. Here
2990 /* Instantiate a few different versions of the template */
2991 %template(intList) List<int>;
2992 %template(doubleList) List<double>;
2997 The argument to <tt>%template()</tt> is the name of the instantiation
2998 in the target language. The name you choose should not conflict with
2999 any other declarations in the interface file with one exception---it
3000 is okay for the template name to match that of a typedef declaration.
3006 %template(intList) List<int>;
3008 typedef List<int> intList; // OK
3013 SWIG can also generate wrappers for function templates using a similar technique.
3019 // Function template
3020 template<class T> T max(T a, T b) { return a > b ? a : b; }
3022 // Make some different versions of this function
3023 %template(maxint) max<int>;
3024 %template(maxdouble) max<double>;
3029 In this case, <tt>maxint</tt> and <tt>maxdouble</tt> become unique names for specific
3030 instantiations of the function.
3034 The number of arguments supplied to <tt>%template</tt> should match that in the
3035 original template definition. Template default arguments are supported. For example:
3040 template vector<typename T, int max=100> class vector {
3044 %template(intvec) vector<int>; // OK
3045 %template(vec1000) vector<int,1000>; // OK
3050 The <tt>%template</tt> directive should not be used to wrap the same
3051 template instantiation more than once in the same scope. This will
3052 generate an error. For example:
3057 %template(intList) List<int>;
3058 %template(Listint) List<int>; // Error. Template already wrapped.
3063 This error is caused because the template expansion results in two
3064 identical classes with the same name. This generates a symbol table
3065 conflict. Besides, it probably more efficient to only wrap a specific
3066 instantiation only once in order to reduce the potential for code
3071 Since the type system knows how to handle <tt>typedef</tt>, it is
3072 generally not necessary to instantiate different versions of a template
3073 for typenames that are equivalent. For instance, consider this code:
3078 %template(intList) vector<int>;
3079 typedef int Integer;
3081 void foo(vector<Integer> *x);
3086 In this case, <tt>vector<Integer></tt> is exactly the same type as
3087 <tt>vector<int></tt>. Any use of <tt>Vector<Integer></tt> is mapped back to the
3088 instantiation of <tt>vector<int></tt> created earlier. Therefore, it is
3089 not necessary to instantiate a new class for the type <tt>Integer</tt> (doing so is
3090 redundant and will simply result in code bloat).
3094 When a template is instantiated using <tt>%template</tt>, information
3095 about that class is saved by SWIG and used elsewhere in the program.
3096 For example, if you wrote code like this,
3102 %template(intList) List<int>;
3104 class UltraList : public List<int> {
3111 then SWIG knows that <tt>List<int></tt> was already wrapped as a class called
3112 <tt>intList</tt> and arranges to handle the inheritance correctly. If, on the other hand,
3113 nothing is known about <tt>List<int></tt>, you will get a warning message similar to this:
3118 example.h:42. Nothing known about class 'List<int >' (ignored).
3119 example.h:42. Maybe you forgot to instantiate 'List<int >' using %template.
3124 If a template class inherits from another template class, you need to
3125 make sure that base classes are instantiated before derived classes.
3131 template<class T> class Foo {
3135 template<class T> class Bar : public Foo<T> {
3139 // Instantiate base classes first
3140 %template(intFoo) Foo<int>;
3141 %template(doubleFoo) Foo<double>;
3143 // Now instantiate derived classes
3144 %template(intBar) Bar<int>;
3145 %template(doubleBar) Bar<double>;
3150 The order is important since SWIG uses the instantiation names to
3151 properly set up the inheritance hierarchy in the resulting wrapper
3152 code (and base classes need to be wrapped before derived classes).
3153 Don't worry--if you get the order wrong, SWIG should generate a warning message.
3157 Occasionally, you may need to tell SWIG about base classes that are defined by templates,
3158 but which aren't supposed to be wrapped. Since SWIG is not able to automatically
3159 instantiate templates for this purpose, you must do it manually. To do this, simply
3160 use <tt>%template</tt> with no name. For example:
3165 // Instantiate traits<double,double>, but don't wrap it.
3166 %template() traits<double,double>;
3171 If you have to instantiate a lot of different classes for many different types,
3172 you might consider writing a SWIG macro. For example:
3177 %define TEMPLATE_WRAP(prefix, T...)
3178 %template(prefix ## Foo) Foo<T >;
3179 %template(prefix ## Bar) Bar<T >;
3183 TEMPLATE_WRAP(int, int)
3184 TEMPLATE_WRAP(double, double)
3185 TEMPLATE_WRAP(String, char *)
3186 TEMPLATE_WRAP(PairStringInt, std::pair<string, int>)
3192 Note the use of a vararg macro for the type T. If this wasn't used, the comma in the templated type in the last example would not be possible.
3196 The SWIG template mechanism <em>does</em> support specialization. For instance, if you define
3202 template<> class List<int> {
3210 void append(int obj);
3218 then SWIG will use this code whenever the user expands <tt>List<int></tt>. In practice,
3219 this may have very little effect on the underlying wrapper code since
3220 specialization is often used to provide slightly modified method bodies (which
3221 are ignored by SWIG). However, special SWIG
3222 directives such as <tt>%typemap</tt>, <tt>%extend</tt>, and so forth can be attached
3223 to a specialization to provide customization for specific types.
3227 Partial template specialization is partially supported by SWIG. For example, this
3228 code defines a template that is applied when the template argument is a pointer.
3233 template<class T> class List<T*> {
3241 void append(int obj);
3249 SWIG should be able to handle most simple uses of partial specialization. However, it may fail
3250 to match templates properly in more complicated cases. For example, if you have this code,
3255 template<class T1, class T2> class Foo<T1, T2 *> { };
3260 SWIG isn't able to match it properly for instantiations like <tt>Foo<int *, int *></tt>.
3261 This problem is not due to parsing, but due to the fact that SWIG does not currently implement all
3262 of the C++ argument deduction rules.
3266 Member function templates are supported. The underlying principle is the same
3267 as for normal templates--SWIG can't create a wrapper unless you provide
3268 more information about types. For example, a class with a member template might
3276 template<class T> void bar(T x, T y) { ... };
3283 To expand the template, simply use <tt>%template</tt> inside the class.
3290 template<class T> void bar(T x, T y) { ... };
3292 %template(barint) bar<int>;
3293 %template(bardouble) bar<double>;
3299 Or, if you want to leave the original class definition alone, just do this:
3306 template<class T> void bar(T x, T y) { ... };
3311 %template(barint) bar<int>;
3312 %template(bardouble) bar<double>;
3325 template<class T> void bar(T x, T y) { ... };
3330 %template(bari) Foo::bar<int>;
3331 %template(bard) Foo::bar<double>;
3336 In this case, the <tt>%extend</tt> directive is not needed, and
3337 <tt>%template</tt> does the exactly same job, i.e., it adds two new
3338 methods to the Foo class.
3343 Note: because of the way that templates are handled, the <tt>%template</tt> directive
3344 must always appear <em>after</em> the definition of the template to be expanded.
3348 Now, if your target language supports overloading, you can even try
3353 %template(bar) Foo::bar<int>;
3354 %template(bar) Foo::bar<double>;
3359 and since the two new wrapped methods have the same name 'bar', they will be
3360 overloaded, and when called, the correct method will be dispatched
3361 depending on the argument type.
3366 When used with members, the <tt>%template</tt> directive may be placed in another
3367 template class. Here is a slightly perverse example:
3373 template<class T> class Foo {
3375 // A member template
3376 template<class S> T bar(S x, S y) { ... };
3380 // Expand a few member templates
3382 %template(bari) bar<int>;
3383 %template(bard) bar<double>;
3386 // Create some wrappers for the template
3387 %template(Fooi) Foo<int>;
3388 %template(Food) Foo<double>;
3393 Miraculously, you will find that each expansion of <tt>Foo</tt> has member
3394 functions <tt>bari()</tt> and <tt>bard()</tt> added.
3398 A common use of member templates is to define constructors for copies
3399 and conversions. For example:
3404 template<class T1, class T2> struct pair {
3407 pair() : first(T1()), second(T2()) { }
3408 pair(const T1 &x, const T2 &y) : first(x), second(y) { }
3409 template<class U1, class U2> pair(const pair<U1,U2> &x)
3410 : first(x.first),second(x.second) { }
3416 This declaration is perfectly acceptable to SWIG, but the constructor template will be ignored
3417 unless you explicitly expand it. To do that, you could expand a few versions of the constructor
3418 in the template class itself. For example:
3424 %template(pair) pair<T1,T2>; // Generate default copy constructor
3430 When using <tt>%extend</tt> in this manner, notice how you can still use the template parameters in
3431 the original template definition.
3435 Alternatively, you could expand the constructor template in selected instantiations. For example:
3440 // Instantiate a few versions
3441 %template(pairii) pair<int,int>;
3442 %template(pairdd) pair<double,double>;
3444 // Create a default constructor only
3445 %extend pair<int,int> {
3446 %template(paird) pair<int,int>; // Default constructor
3449 // Create default and conversion constructors
3450 %extend pair<double,double> {
3451 %template(paird) pair<double,dobule>; // Default constructor
3452 %template(pairc) pair<int,int>; // Conversion constructor
3458 <p>And if your target language supports overloading, then you can try
3464 // Create default and conversion constructors
3465 %extend pair<double,double> {
3466 %template(pair) pair<double,dobule>; // Default constructor
3467 %template(pair) pair<int,int>; // Conversion constructor
3473 In this case, the default and conversion constructors have the same
3474 name. Hence, Swig will overload them and define an unique visible
3475 constructor, that will dispatch the proper call depending on the argument
3480 If all of this isn't quite enough and you really want to make
3481 someone's head explode, SWIG directives such as
3482 <tt>%rename</tt>, <tt>%extend</tt>, and <tt>%typemap</tt> can be
3483 included directly in template definitions. For example:
3486 <div class="code"><pre>
3488 template<class T> class List {
3491 %rename(__getitem__) get(int);
3498 /* Make a string representation */
3506 In this example, the extra SWIG directives are propagated to <em>every</em> template
3511 It is also possible to separate these declarations from the template class. For example:
3516 %rename(__getitem__) List::get;
3519 /* Make a string representation */
3524 return new List<T>(*$self);
3529 template<class T> class List {
3540 When <tt>%extend</tt> is decoupled from the class definition, it is
3541 legal to use the same template parameters as provided in the class definition.
3542 These are replaced when the template is expanded.
3543 In addition, the <tt>%extend</tt> directive can be used to add
3544 additional methods to a specific instantiation. For example:
3549 %template(intList) List<int>;
3551 %extend List<int> {
3553 printf("Hey, I'm an List<int>!\n");
3560 SWIG even supports overloaded templated functions. As usual the <tt>%template</tt> directive
3561 is used to wrap templated functions. For example:
3566 template<class T> void foo(T x) { };
3567 template<class T> void foo(T x, T y) { };
3569 %template(foo) foo<int>;
3574 This will generate two overloaded wrapper methods, the first will take a single integer as an argument
3575 and the second will take two integer arguments.
3579 Needless to say, SWIG's template support provides plenty of
3580 opportunities to break the universe. That said, an important final
3581 point is that <b>SWIG does not perform extensive error checking of
3582 templates!</b> Specifically, SWIG does not perform type checking nor
3583 does it check to see if the actual contents of the template
3584 declaration make any sense. Since the C++ compiler will hopefully
3585 check this when it compiles the resulting wrapper file, there is no
3586 practical reason for SWIG to duplicate this functionality (besides,
3587 none of the SWIG developers are masochistic enough to want to
3588 implement this right now).
3592 <b>Compatibility Note</b>: The first implementation of template support relied heavily on
3593 macro expansion in the preprocessor. Templates have been more tightly integrated into
3594 the parser and type system in SWIG-1.3.12 and the preprocessor is no longer used. Code
3595 that relied on preprocessing features in template expansion will no longer work. However,
3596 SWIG still allows the # operator to be used to generate a string from a template argument.
3600 <b>Compatibility Note</b>: In earlier versions of SWIG, the <tt>%template</tt> directive
3601 introduced a new class name. This name could then be used with other directives. For example:
3606 %template(vectori) vector<int>;
3608 void somemethod() { }
3614 This behavior is no longer supported. Instead, you should use the original template name
3615 as the class name. For example:
3620 %template(vectori) vector<int>;
3621 %extend vector<int> {
3622 void somemethod() { }
3628 Similar changes apply to typemaps and other customization features.
3631 <H2><a name="SWIGPlus_nn31"></a>6.19 Namespaces</H2>
3635 Support for C++ namespaces is a relatively late addition to SWIG,
3636 first appearing in SWIG-1.3.12. Before describing the implementation,
3637 it is worth noting that the semantics of C++ namespaces is extremely
3638 non-trivial--especially with regard to the C++ type system and class
3639 machinery. At a most basic level, namespaces are sometimes used to
3640 encapsulate common functionality. For example:
3660 Members of the namespace are accessed in C++ by prepending the namespace prefix
3661 to names. For example:
3666 double x = math::sin(1.0);
3667 double magnitude(math::Complex *c);
3674 At this level, namespaces are relatively easy to manage. However, things start to get
3675 very ugly when you throw in the other ways a namespace can be used. For example,
3676 selective symbols can be exported from a namespace with <tt>using</tt>.
3681 using math::Complex;
3682 double magnitude(Complex *c); // Namespace prefix stripped
3687 Similarly, the contents of an entire namespace can be made available like this:
3692 using namespace math;
3693 double x = sin(1.0);
3694 double magnitude(Complex *c);
3699 Alternatively, a namespace can be aliased:
3705 double x = M::sin(1.0);
3706 double magnitude(M::Complex *c);
3711 Using combinations of these features, it is possible to write head-exploding code like this:
3725 typedef C::Foo FooClass;
3731 using BIGB::FooClass;
3732 class Bar : public FooClass {
3736 class Spam : public D::Bar {
3739 void evil(A::Foo *a, B::FooClass *b, B::C::Foo *c, BIGB::FooClass *d,
3740 BIGB::C::Foo *e, D::FooClass *f);
3746 Given the possibility for such perversion, it's hard to imagine how
3747 every C++ programmer might want such code wrapped into the target
3748 language. Clearly this code defines three different classes. However, one
3749 of those classes is accessible under at least six different names!
3753 SWIG fully supports C++ namespaces in its internal type system and
3754 class handling code. If you feed SWIG the above code, it will be
3755 parsed correctly, it will generate compilable wrapper code, and it
3756 will produce a working scripting language module. However, the
3757 default wrapping behavior is to flatten namespaces in the target
3758 language. This means that the contents of all namespaces are merged
3759 together in the resulting scripting language module. For example, if
3760 you have code like this,
3779 then SWIG simply creates three wrapper functions <tt>bar()</tt>,
3780 <tt>spam()</tt>, and <tt>blah()</tt> in the target language. SWIG
3781 does not prepend the names with a namespace prefix nor are the
3782 functions packaged in any kind of nested scope.
3786 There is some rationale for taking this approach. Since C++
3787 namespaces are often used to define modules in C++, there is a natural
3788 correlation between the likely contents of a SWIG module and the contents of
3789 a namespace. For instance, it would not be unreasonable to assume
3790 that a programmer might make a separate extension module for each C++
3791 namespace. In this case, it would be redundant to prepend everything
3792 with an additional namespace prefix when the module itself already
3793 serves as a namespace in the target language. Or put another way, if
3794 you want SWIG to keep namespaces separate, simply wrap each namespace with its
3799 Because namespaces are flattened, it is possible for symbols defined in different
3800 namespaces to generate a name conflict in the target language. For example:
3815 When this conflict occurs, you will get an error message that resembles this:
3820 example.i:26. Error. 'foo' is multiply defined in the generated module.
3821 example.i:23. Previous declaration of 'foo'
3826 To resolve this error, simply use <tt>%rename</tt> to disambiguate the declarations. For example:
3831 %rename(B_foo) B::foo;
3837 void foo(double); // Gets renamed to B_foo
3843 Similarly, <tt>%ignore</tt> can be used to ignore declarations.
3847 <tt>using</tt> declarations do not have any effect on the generated wrapper
3848 code. They are ignored by SWIG language modules and they do not result in any
3849 code. However, these declarations <em>are</em> used by the internal type
3850 system to track type-names. Therefore, if you have code like this:
3856 typedef int Integer;
3859 void foo(Integer x);
3864 SWIG knows that <tt>Integer</tt> is the same as <tt>A::Integer</tt> which
3865 is the same as <tt>int</tt>.
3869 Namespaces may be combined with templates. If necessary, the
3870 <tt>%template</tt> directive can be used to expand a template defined
3871 in a different namespace. For example:
3877 template<typename T> T max(T a, T b) { return a > b ? a : b; }
3882 %template(maxint) max<int>; // Okay.
3883 %template(maxfloat) foo::max<float>; // Okay (qualified name).
3886 using namespace foo;
3887 %template(maxdouble) max<double>; // Okay.
3893 The combination of namespaces and other SWIG directives may introduce subtle scope-related problems.
3894 The key thing to keep in mind is that all SWIG generated wrappers are produced
3895 in the <em>global</em> namespace. Symbols from other namespaces are always accessed using fully
3896 qualified names---names are never imported into the global space unless the interface happens to
3897 do so with a <tt>using</tt> declaration. In almost all cases, SWIG adjusts typenames and symbols
3898 to be fully qualified. However, this is not done in code fragments such as function bodies,
3899 typemaps, exception handlers, and so forth. For example, consider the following:
3905 typedef int Integer;
3913 Integer add(Integer x, Integer y) {
3914 Integer r = x + y; // Error. Integer not defined in this scope
3922 In this case, SWIG correctly resolves the added method parameters and return type to
3923 <tt>foo::Integer</tt>. However, since function bodies aren't parsed and such code is
3924 emitted in the global namespace, this code produces a compiler error about <tt>Integer</tt>.
3925 To fix the problem, make sure you use fully qualified names. For example:
3931 Integer add(Integer x, Integer y) {
3932 foo::Integer r = x + y; // Ok.
3940 <b>Note:</b> SWIG does <em>not</em> propagate <tt>using</tt> declarations to
3941 the resulting wrapper code. If these declarations appear in an interface,
3942 they should <em>also</em> appear in any header files that might have been
3943 included in a <tt>%{ ... %}</tt> section. In other words, don't insert extra
3944 <tt>using</tt> declarations into a SWIG interface unless they also appear
3945 in the underlying C++ code.
3949 <b>Note:</b> Code inclusion directives such as <tt>%{ ... %}</tt> or
3950 <tt>%inline %{ ... %}</tt> should not be placed inside a namespace declaration.
3951 The code emitted by these directives will not be enclosed in a namespace and
3952 you may get very strange results. If you need to use namespaces with
3953 these directives, consider the following:
3961 void bar(int) { ... }
3966 // Bad version. Emitted code not placed in namespace.
3969 void bar(int) { ... } /* I'm bad */
3977 <b>Note:</b> When the <tt>%extend</tt> directive is used inside a namespace, the namespace name is
3978 included in the generated functions. For example, if you have code like this,
3995 the added method <tt>blah()</tt> is mapped to a function <tt>int foo_bar_blah(foo::bar *self, int x)</tt>.
3996 This function resides in the global namespace.
4000 <b>Note:</b> Although namespaces are flattened in the target language, the SWIG generated wrapper
4001 code observes the same namespace conventions as used in the input file. Thus, if there are no symbol
4002 conflicts in the input, there will be no conflicts in the generated code.
4006 <b>Note:</b> In the same way that no resolution is performed on parameters, a conversion operator name must match exactly to how it is defined. Do not change the qualification of the operator. For example, suppose you had an interface like this:
4016 operator bar(); // Conversion of spam -> bar
4024 The following is how the feature is expected to be written for a successful match:
4029 %rename(tofoo) foo::spam::operator bar();
4034 The following does not work as no namespace resolution is performed in the matching of conversion operator names:
4039 %rename(tofoo) foo::spam::operator <b>foo::</b>bar();
4044 Note, however, that if the operator is defined using a qualifier in its name, then the feature must use it too...
4049 %rename(tofoo) foo::spam::operator bar(); // will not match
4050 %rename(tofoo) foo::spam::operator foo::bar(); // will match
4056 operator foo::bar();
4064 <b>Compatibility Note:</b> Versions of SWIG prior to 1.3.32 were inconsistent in this approach. A fully qualified name was usually required, but would not work in some situations.
4069 <b>Note:</b> The flattening of namespaces is only intended to serve as
4070 a basic namespace implementation.
4071 None of the target language modules are currently programmed
4072 with any namespace awareness. In the future, language modules may or may not provide
4073 more advanced namespace support.
4076 <H2><a name="SWIGPlus_renaming_templated_types_namespaces"></a>6.20 Renaming templated types in namespaces</H2>
4080 As has been mentioned, when %rename includes parameters, the parameter types must match exactly (no typedef or namespace resolution is performed).
4081 SWIG treats templated types slightly differently and has an additional matching rule so unlike non-templated types, an exact match is not always required.
4082 If the fully qualified templated type is specified, it will have a higher precedence over the generic template type.
4083 In the example below, the generic template type is used to rename to <tt>bbb</tt> and the fully qualified type is used to rename to <tt>ccc</tt>.
4088 %rename(bbb) Space::ABC::aaa(T t); // will match but with lower precedence than ccc
4089 %rename(ccc) Space::ABC<Space::XYZ>::aaa(Space::XYZ t); // will match but with higher precedence than bbb
4093 template<typename T> struct ABC {
4097 %template(ABCXYZ) Space::ABC<Space::XYZ>;
4102 It should now be apparent that there are many ways to achieve a renaming with %rename. This is demonstrated
4103 by the following two examples, which are effectively the same as the above example.
4104 Below shows how %rename can be placed inside a namespace.
4110 %rename(bbb) ABC::aaa(T t); // will match but with lower precedence than ccc
4111 %rename(ccc) ABC<Space::XYZ>::aaa(Space::XYZ t); // will match but with higher precedence than bbb
4112 %rename(ddd) ABC<Space::XYZ>::aaa(XYZ t); // will not match
4117 template<typename T> struct ABC {
4121 %template(ABCXYZ) Space::ABC<Space::XYZ>;
4126 Note that <tt>ddd</tt> does not match as there is no namespace resolution for parameter types and the fully qualified type must be specified for template type expansion.
4127 The following example shows how %rename can be placed within %extend.
4134 %rename(bbb) aaa(T t); // will match but with lower precedence than ccc
4136 %extend ABC<Space::XYZ> {
4137 %rename(ccc) aaa(Space::XYZ t); // will match but with higher precedence than bbb
4138 %rename(ddd) aaa(XYZ t); // will not match
4144 template<typename T> struct ABC {
4148 %template(ABCXYZ) Space::ABC<Space::XYZ>;
4153 <H2><a name="SWIGPlus_exception_specifications"></a>6.21 Exception specifications</H2>
4157 When C++ programs utilize exceptions, exceptional behavior is sometimes specified as
4158 part of a function or method declaration. For example:
4168 void blah() throw(Error);
4175 If an exception specification is used, SWIG automatically generates
4176 wrapper code for catching the indicated exception and, when possible,
4177 rethrowing it into the target language, or converting it into an error
4178 in the target language otherwise. For example, in Python, you can
4179 write code like this:
4182 <div class="targetlang">
4188 # e is a wrapped instance of "Error"
4193 Details of how to tailor code for handling the caught C++ exception and converting it into the target language's exception/error handling mechanism
4194 is outlined in the <a href="Typemaps.html#throws_typemap">"throws" typemap</a> section.
4198 Since exception specifications are sometimes only used sparingly, this alone may not be enough to
4199 properly handle C++ exceptions. To do that, a different set of special SWIG directives are used.
4200 Consult the "<a href="Customization.html#exception">Exception handling with %exception</a>" section for details.
4201 The next section details a way of simulating an exception specification or replacing an existing one.
4204 <H2><a name="SWIGPlus_catches"></a>6.22 Exception handling with %catches</H2>
4208 Exceptions are automatically handled for methods with an exception specification.
4209 Similar handling can be achieved for methods without exception specifications through the <tt>%catches</tt> feature.
4210 It is also possible to replace any declared exception specification using the <tt>%catches</tt> feature.
4211 In fact, <tt>%catches</tt> uses the same <a href="Typemaps.html#throws_typemap">"throws" typemaps</a> that SWIG uses for exception specifications in handling exceptions.
4212 The <tt>%catches</tt> feature must contain a list of possible types that can be thrown.
4213 For each type that is in the list, SWIG will generate a catch handler, in the same way that it would for types declared in the exception specification.
4214 Note that the list can also include the catch all specification "...".
4220 struct EBase { virtual ~EBase(); };
4221 struct Error1 : EBase { };
4222 struct Error2 : EBase { };
4223 struct Error3 : EBase { };
4224 struct Error4 : EBase { };
4226 %catches(Error1,Error2,...) Foo::bar();
4227 %catches(EBase) Foo::blah();
4233 void blah() throw(Error1,Error2,Error3,Error4);
4240 For the <tt>Foo::bar()</tt> method, which can throw anything,
4241 SWIG will generate catch handlers for <tt>Error1</tt>, <tt>Error2</tt> as well as a catch all handler (...).
4242 Each catch handler will convert the caught exception and convert it into a target language error/exception.
4243 The catch all handler will convert the caught exception into an unknown error/exception.
4247 Without the <tt>%catches</tt> feature being attached to <tt>Foo::blah()</tt>,
4248 SWIG will generate catch handlers for all of the types in the exception specification, that is, <tt>Error1, Error2, Error3, Error4</tt>.
4249 However, with the <tt>%catches</tt> feature above,
4250 just a single catch handler for the base class, <tt>EBase</tt> will be generated to convert the C++ exception into a target language error/exception.
4254 <H2><a name="SWIGPlus_nn33"></a>6.23 Pointers to Members</H2>
4258 Starting with SWIG-1.3.7, there is limited parsing support for pointers to C++ class members.
4264 double do_op(Object *o, double (Object::*callback)(double,double));
4265 extern double (Object::*fooptr)(double,double);
4266 %constant double (Object::*FOO)(double,double) = &Object::foo;
4271 Although these kinds of pointers can be parsed and represented by the
4272 SWIG type system, few language modules know how to handle them due to
4273 implementation differences from standard C pointers. Readers are
4274 <em>strongly</em> advised to consult an advanced text such as the "The
4275 Annotated C++ Manual" for specific details.
4279 When pointers to members are supported, the pointer value might appear as a special
4283 <div class="targetlang">
4285 >>> print example.FOO
4286 _ff0d54a800000000_m_Object__f_double_double__double
4292 In this case, the hexadecimal digits represent the entire value of the
4293 pointer which is usually the contents of a small C++ structure on most
4298 SWIG's type-checking mechanism is also more limited when working with
4299 member pointers. Normally SWIG tries to keep track of inheritance
4300 when checking types. However, no such support is currently provided
4301 for member pointers.
4304 <H2><a name="SWIGPlus_nn34"></a>6.24 Smart pointers and operator->()</H2>
4308 In some C++ programs, objects are often encapsulated by smart-pointers
4309 or proxy classes. This is sometimes done to implement automatic memory management (reference counting) or
4310 persistence. Typically a smart-pointer is defined by a template class where
4311 the <tt>-></tt> operator has been overloaded. This class is then wrapped
4312 around some other class. For example:
4317 // Smart-pointer class
4318 template<class T> class SmartPtr {
4322 T *operator->() {
4336 // Smart-pointer wrapper
4337 typedef SmartPtr<Foo_Impl> Foo;
4339 // Create smart pointer Foo
4341 return SmartPtr(new Foo_Impl());
4344 // Do something with smart pointer Foo
4345 void do_something(Foo f) {
4346 printf("x = %d\n", f->x);
4353 A key feature of this approach is that by defining
4354 <tt>operator-></tt> the methods and attributes of the object
4355 wrapped by a smart pointer are transparently accessible. For example,
4356 expressions such as these (from the previous example),
4367 are transparently mapped to the following
4372 (f.operator->())->x;
4373 (f.operator->())->bar();
4378 When generating wrappers, SWIG tries to emulate this functionality to
4379 the extent that it is possible. To do this, whenever
4380 <tt>operator->()</tt> is encountered in a class, SWIG looks at its
4381 returned type and uses it to generate wrappers for accessing
4382 attributes of the underlying object. For example, wrapping the above
4383 code produces wrappers like this:
4388 int Foo_x_get(Foo *f) {
4391 void Foo_x_set(Foo *f, int value) {
4394 void Foo_bar(Foo *f) {
4401 These wrappers take a smart-pointer instance as an argument, but
4402 dereference it in a way to gain access to the object returned by
4403 <tt>operator->()</tt>. You should carefully compare these wrappers
4404 to those in the first part of this chapter (they are slightly
4409 The end result is that access looks very similar to C++. For
4410 example, you could do this in Python:
4413 <div class="targetlang">
4415 >>> f = make_Foo()
4416 >>> print f.x
4418 >>> f.bar()
4424 When generating wrappers through a smart-pointer, SWIG tries to
4425 generate wrappers for all methods and attributes that might be
4426 accessible through <tt>operator->()</tt>. This includes any methods
4427 that might be accessible through inheritance. However, there are a number of restrictions:
4431 <li>Member variables and methods are wrapped through a smart
4432 pointer. Enumerations, constructors, and destructors are not wrapped.
4435 <li><p>If the smart-pointer class and the underlying object both define a method or
4436 variable of the same name, then the smart-pointer version has precedence. For
4437 example, if you have this code</p>
4449 Foo *operator->();
4455 then the wrapper for <tt>Bar::x</tt> accesses the <tt>x</tt> defined in <tt>Bar</tt>, and
4456 not the <tt>x</tt> defined in <tt>Foo</tt>.</p>
4461 If your intent is to only expose the smart-pointer class in the interface, it is not necessary to wrap both
4462 the smart-pointer class and the class for the underlying object. However, you must still tell SWIG about both
4463 classes if you want the technique described in this section to work. To only generate wrappers for the
4464 smart-pointer class, you can use the %ignore directive. For example:
4470 class Foo { // Ignored
4475 Foo *operator->();
4482 Alternatively, you can import the definition of <tt>Foo</tt> from a separate file using
4487 <b>Note:</b> When a class defines <tt>operator->()</tt>, the operator itself is wrapped
4488 as a method <tt>__deref__()</tt>. For example:
4491 <div class="targetlang">
4493 f = Foo() # Smart-pointer
4494 p = f.__deref__() # Raw pointer from operator->
4499 <b>Note:</b> To disable the smart-pointer behavior, use <tt>%ignore</tt> to ignore
4500 <tt>operator->()</tt>. For example:
4505 %ignore Bar::operator->;
4510 <b>Note:</b> Smart pointer support was first added in SWIG-1.3.14.
4514 <H2><a name="SWIGPlus_nn35"></a>6.25 Using declarations and inheritance</H2>
4518 <tt>using</tt> declarations are sometimes used to adjust access to members of
4519 base classes. For example:
4531 double blah(double x);
4534 class FooBar : public Foo, public Bar {
4538 char *blah(const char *x);
4544 In this example, the <tt>using</tt> declarations make different
4545 versions of the overloaded <tt>blah()</tt> method accessible from the
4546 derived class. For example:
4552 f->blah(3); // Ok. Invokes Foo::blah(int)
4553 f->blah(3.5); // Ok. Invokes Bar::blah(double)
4554 f->blah("hello"); // Ok. Invokes FooBar::blah(const char *);
4559 SWIG emulates the same functionality when creating wrappers. For example, if
4560 you wrap this code in Python, the module works just like you would expect:
4563 <div class="targetlang">
4565 >>> import example
4566 >>> f = example.FooBar()
4567 >>> f.blah(3)
4568 >>> f.blah(3.5)
4569 >>> f.blah("hello")
4574 <tt>using</tt> declarations can also be used to change access when applicable. For example:
4585 class Bar : public Foo {
4587 using Foo::x; // Make x public
4588 using Foo::blah; // Make blah public
4594 This also works in SWIG---the exposed declarations will be wrapped normally.
4598 When <tt>using</tt> declarations are used as shown in these examples, declarations
4599 from the base classes are copied into the derived class and wrapped normally. When
4600 copied, the declarations retain any properties that might have been attached using
4601 <tt>%rename</tt>, <tt>%ignore</tt>, or <tt>%feature</tt>. Thus, if a method is
4602 ignored in a base class, it will also be ignored by a <tt>using</tt> declaration.
4606 Because a <tt>using</tt> declaration does not provide fine-grained
4607 control over the declarations that get imported, it may be difficult
4608 to manage such declarations in applications that make heavy use of
4609 SWIG customization features. If you can't get <tt>using</tt> to work
4610 correctly, you can always change the interface to the following:
4616 class FooBar : public Foo, public Bar {
4622 int blah(int x); // explicitly tell SWIG about other declarations
4623 double blah(double x);
4626 char *blah(const char *x);
4636 <li><p>If a derived class redefines a method defined in a base class, then a <tt>using</tt> declaration
4637 won't cause a conflict. For example:</p>
4644 double blah(double);
4647 class Bar : public Foo {
4649 using Foo::blah; // Only imports blah(double);
4655 <li><p>Resolving ambiguity in overloading may prevent declarations from being
4656 imported by <tt>using</tt>. For example:
4661 %rename(blah_long) Foo::blah(long);
4665 long blah(long); // Renamed to blah_long
4668 class Bar : public Foo {
4670 using Foo::blah; // Only imports blah(int)
4671 double blah(double x);
4677 <H2><a name="SWIGPlus_nested_classes"></a>6.26 Nested classes</H2>
4681 There is limited support for nested structs and unions when wrapping C code, see <a href="SWIG.html#SWIG_nested_structs">Nested structures</a> for further details.
4682 However, there is no nested class/struct/union support when wrapping C++ code (using the -c++ commandline option).
4683 This may be added at a future date, however, until then some of the following workarounds can be applied.
4687 It might be possible to use partial class information. Since
4688 SWIG does not need the entire class specification to work, conditional
4689 compilation can be used to comment out the problematic nested class definition, you might do this:
4710 The next workaround assumes you cannot modify the source code as was done above and it provides a solution for methods that use nested class types.
4711 Imagine we are wrapping the <tt>Outer</tt> class which contains a nested class <tt>Inner</tt>:
4722 Inner(int v = 0) : var(v) {}
4724 void method(Inner inner);
4730 The following interface file works around SWIG nested class limitations by redefining the nested class as a global class.
4731 A typedef for the compiler is also required in order for the generated wrappers to compile.
4739 // Suppress SWIG warning
4740 #pragma SWIG nowarn=SWIGWARN_PARSE_NESTED_CLASS
4742 // Redefine nested class in global scope in order for SWIG to generate
4743 // a proxy class. Only SWIG parses this definition.
4747 Inner(int v = 0) : var(v) {}
4756 // SWIG thinks that Inner is a global class, so we need to trick the C++
4757 // compiler into understanding this so called global type.
4758 typedef Outer::Inner Inner;
4765 The downside to this approach is having to maintain two definitions of <tt>Inner</tt>, the real one and the one in the interface file that SWIG parses.
4768 <H2><a name="SWIGPlus_nn37"></a>6.27 A brief rant about const-correctness</H2>
4772 A common issue when working with C++ programs is dealing with all
4773 possible ways in which the <tt>const</tt> qualifier (or lack thereof)
4774 will break your program, all programs linked against your program, and
4775 all programs linked against those programs.
4779 Although SWIG knows how to correctly deal with <tt>const</tt> in its
4780 internal type system and it knows how to generate wrappers that are
4781 free of const-related warnings, SWIG does not make any attempt to preserve
4782 const-correctness in the target language. Thus, it is possible to
4783 pass <tt>const</tt> qualified objects to non-const methods and functions.
4784 For example, consider the following code in C++:
4789 const Object * foo();
4795 bar(foo()); // Error: bar discards const
4801 Now, consider the behavior when wrapped into a Python module:
4804 <div class="targetlang">
4806 >>> bar(foo()) # Okay
4812 Although this is clearly a violation of the C++ type-system, fixing
4813 the problem doesn't seem to be worth the added implementation
4814 complexity that would be required to support it in the SWIG run-time type
4815 system. There are no plans to change this in future releases
4816 (although we'll never rule anything out entirely).
4820 The bottom line is that this particular issue does not appear to be a problem
4821 for most SWIG projects. Of course, you might want to consider
4822 using another tool if maintaining constness is the most important part
4826 <H2><a name="SWIGPlus_nn42"></a>6.28 Where to go for more information</H2>
4830 If you're wrapping serious C++ code, you might want to pick up a copy
4831 of "The Annotated C++ Reference Manual" by Ellis and Stroustrup. This
4832 is the reference document we use to guide a lot of SWIG's C++ support.
4838 <!-- LocalWords: destructors Enums Namespaces const SWIG's STL OO adaptor tcl
4840 <!-- LocalWords: debuggable cxx OBJS Wiki accessor nodefault makedefault
4842 <!-- LocalWords: notabstract CopyFoo