PageRenderTime 37ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/Doc/Manual/SWIGPlus.html

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