PageRenderTime 530ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 1ms

/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

Large files files are truncated, but you can click here to view the full file

  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 mo

Large files files are truncated, but you can click here to view the full file