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

/trunk/Doc/Manual/Customization.html

#
HTML | 1167 lines | 964 code | 201 blank | 2 comment | 0 complexity | 48eb27f3f1c72fdd4693f5b41178078e MD5 | raw file
Possible License(s): LGPL-2.1, Cube, GPL-3.0, 0BSD, GPL-2.0
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
  2. <html>
  3. <head>
  4. <title>Customization Features</title>
  5. <link rel="stylesheet" type="text/css" href="style.css">
  6. </head>
  7. <body bgcolor="#ffffff">
  8. <H1><a name="Customization"></a>11 Customization Features</H1>
  9. <!-- INDEX -->
  10. <div class="sectiontoc">
  11. <ul>
  12. <li><a href="#Customization_exception">Exception handling with %exception</a>
  13. <ul>
  14. <li><a href="#Customization_nn3">Handling exceptions in C code</a>
  15. <li><a href="#Customization_nn4">Exception handling with longjmp()</a>
  16. <li><a href="#Customization_nn5">Handling C++ exceptions</a>
  17. <li><a href="#Customization_allowexcept">Exception handlers for variables</a>
  18. <li><a href="#Customization_nn6">Defining different exception handlers</a>
  19. <li><a href="#Customization_exception_special_variables">Special variables for %exception</a>
  20. <li><a href="#Customization_nn7">Using The SWIG exception library</a>
  21. </ul>
  22. <li><a href="#Customization_ownership">Object ownership and %newobject</a>
  23. <li><a href="#Customization_features">Features and the %feature directive</a>
  24. <ul>
  25. <li><a href="#Customization_feature_attributes">Feature attributes</a>
  26. <li><a href="#Customization_feature_flags">Feature flags</a>
  27. <li><a href="#Customization_clearing_features">Clearing features</a>
  28. <li><a href="#Customization_features_default_args">Features and default arguments</a>
  29. <li><a href="#Customization_features_example">Feature example</a>
  30. </ul>
  31. </ul>
  32. </div>
  33. <!-- INDEX -->
  34. <p>
  35. In many cases, it is desirable to change the default wrapping of
  36. particular declarations in an interface. For example, you might want
  37. to provide hooks for catching C++ exceptions, add assertions, or
  38. provide hints to the underlying code generator. This chapter
  39. describes some of these customization techniques. First, a discussion
  40. of exception handling is presented. Then, a more general-purpose
  41. customization mechanism known as "features" is described.
  42. </p>
  43. <H2><a name="Customization_exception"></a>11.1 Exception handling with %exception</H2>
  44. <p>
  45. The <tt>%exception</tt> directive allows you to define a general purpose exception
  46. handler. For example, you can specify the following:
  47. </p>
  48. <div class="code"><pre>
  49. %exception {
  50. try {
  51. $action
  52. }
  53. catch (RangeError) {
  54. ... handle error ...
  55. }
  56. }
  57. </pre></div>
  58. <p>
  59. How the exception is handled depends on the target language, for example, Python:
  60. </p>
  61. <div class="code"><pre>
  62. %exception {
  63. try {
  64. $action
  65. }
  66. catch (RangeError) {
  67. PyErr_SetString(PyExc_IndexError,"index out-of-bounds");
  68. SWIG_fail;
  69. }
  70. }
  71. </pre></div>
  72. <p>
  73. When defined, the code enclosed in braces is inserted directly into the low-level wrapper
  74. functions. The special variable <tt>$action</tt> is one of a few
  75. <a href="Customization.html#Customization_exception_special_variables">%exception special variables</a>
  76. supported and gets replaced with the actual operation
  77. to be performed (a function call, method invocation, attribute access, etc.). An exception handler
  78. remains in effect until it is explicitly deleted. This is done by using either <tt>%exception</tt>
  79. or <tt>%noexception</tt> with no code. For example:
  80. </p>
  81. <div class="code"><pre>
  82. %exception; // Deletes any previously defined handler
  83. </pre></div>
  84. <p>
  85. <b>Compatibility note:</b> Previous versions of SWIG used a special directive <tt>%except</tt>
  86. for exception handling. That directive is deprecated--<tt>%exception</tt>
  87. provides the same functionality, but is substantially more flexible.
  88. </p>
  89. <H3><a name="Customization_nn3"></a>11.1.1 Handling exceptions in C code</H3>
  90. <p>
  91. C has no formal exception handling mechanism so there are several approaches that might be
  92. used. A somewhat common technique is to simply set a special error code. For example:
  93. </p>
  94. <div class="code"><pre>
  95. /* File : except.c */
  96. static char error_message[256];
  97. static int error_status = 0;
  98. void throw_exception(char *msg) {
  99. strncpy(error_message,msg,256);
  100. error_status = 1;
  101. }
  102. void clear_exception() {
  103. error_status = 0;
  104. }
  105. char *check_exception() {
  106. if (error_status) return error_message;
  107. else return NULL;
  108. }
  109. </pre></div>
  110. <p>
  111. To use these functions, functions simply call
  112. <tt>throw_exception()</tt> to indicate an error occurred. For example
  113. :</p>
  114. <div class="code"><pre>
  115. double inv(double x) {
  116. if (x != 0) return 1.0/x;
  117. else {
  118. throw_exception("Division by zero");
  119. return 0;
  120. }
  121. }
  122. </pre></div>
  123. <p>
  124. To catch the exception, you can write a simple exception handler such
  125. as the following (shown for Perl5) :</p>
  126. <div class="code"><pre>
  127. %exception {
  128. char *err;
  129. clear_exception();
  130. $action
  131. if ((err = check_exception())) {
  132. croak(err);
  133. }
  134. }
  135. </pre></div>
  136. <p>
  137. In this case, when an error occurs, it is translated into a Perl error.
  138. Each target language has its own approach to creating a runtime error/exception in
  139. and for Perl it is the <tt>croak</tt> method shown above.
  140. </p>
  141. <H3><a name="Customization_nn4"></a>11.1.2 Exception handling with longjmp()</H3>
  142. <p>
  143. Exception handling can also be added to C code using the
  144. <tt>&lt;setjmp.h&gt;</tt> library. Here is a minimalistic implementation that
  145. relies on the C preprocessor :
  146. </p>
  147. <div class="code"><pre>
  148. /* File : except.c
  149. Just the declaration of a few global variables we're going to use */
  150. #include &lt;setjmp.h&gt;
  151. jmp_buf exception_buffer;
  152. int exception_status;
  153. /* File : except.h */
  154. #include &lt;setjmp.h&gt;
  155. extern jmp_buf exception_buffer;
  156. extern int exception_status;
  157. #define try if ((exception_status = setjmp(exception_buffer)) == 0)
  158. #define catch(val) else if (exception_status == val)
  159. #define throw(val) longjmp(exception_buffer,val)
  160. #define finally else
  161. /* Exception codes */
  162. #define RangeError 1
  163. #define DivisionByZero 2
  164. #define OutOfMemory 3
  165. </pre></div>
  166. <p>
  167. Now, within a C program, you can do the following :</p>
  168. <div class="code"><pre>
  169. double inv(double x) {
  170. if (x) return 1.0/x;
  171. else throw(DivisionByZero);
  172. }
  173. </pre></div>
  174. <p>
  175. Finally, to create a SWIG exception handler, write the following :</p>
  176. <div class="code"><pre>
  177. %{
  178. #include "except.h"
  179. %}
  180. %exception {
  181. try {
  182. $action
  183. } catch(RangeError) {
  184. croak("Range Error");
  185. } catch(DivisionByZero) {
  186. croak("Division by zero");
  187. } catch(OutOfMemory) {
  188. croak("Out of memory");
  189. } finally {
  190. croak("Unknown exception");
  191. }
  192. }
  193. </pre></div>
  194. <p>
  195. Note: This implementation is only intended to illustrate the general idea. To make it work better, you'll need to
  196. modify it to handle nested <tt>try</tt> declarations.
  197. </p>
  198. <H3><a name="Customization_nn5"></a>11.1.3 Handling C++ exceptions</H3>
  199. <p>
  200. Handling C++ exceptions is also straightforward. For example:
  201. </p>
  202. <div class="code"><pre>
  203. %exception {
  204. try {
  205. $action
  206. } catch(RangeError) {
  207. croak("Range Error");
  208. } catch(DivisionByZero) {
  209. croak("Division by zero");
  210. } catch(OutOfMemory) {
  211. croak("Out of memory");
  212. } catch(...) {
  213. croak("Unknown exception");
  214. }
  215. }
  216. </pre></div>
  217. <p>
  218. The exception types need to be declared as classes elsewhere, possibly
  219. in a header file :</p>
  220. <div class="code"><pre>
  221. class RangeError {};
  222. class DivisionByZero {};
  223. class OutOfMemory {};
  224. </pre>
  225. </div>
  226. <H3><a name="Customization_allowexcept"></a>11.1.4 Exception handlers for variables</H3>
  227. <p>
  228. By default all variables will ignore <tt>%exception</tt>, so it is effectively turned off for all variables wrappers.
  229. This applies to global variables, member variables and static member variables.
  230. The approach is certainly a logical one when wrapping variables in C.
  231. However, in C++, it is quite possible for an exception to be thrown while the variable is being assigned.
  232. To ensure <tt>%exception</tt> is used when wrapping variables, it needs to be 'turned on' using the <tt>%allowexception</tt> feature.
  233. Note that <tt>%allowexception</tt> is just a macro for <tt>%feature("allowexcept")</tt>, that is, it is a feature called "allowexcept".
  234. Any variable which has this feature attached to it, will then use the <tt>%exception</tt> feature, but of course,
  235. only if there is a <tt>%exception</tt> attached to the variable in the first place.
  236. The <tt>%allowexception</tt> feature works like any other feature and so can be used globally or for selective variables.
  237. </p>
  238. <div class="code">
  239. <pre>
  240. %allowexception; // turn on globally
  241. %allowexception Klass::MyVar; // turn on for a specific variable
  242. %noallowexception Klass::MyVar; // turn off for a specific variable
  243. %noallowexception; // turn off globally
  244. </pre>
  245. </div>
  246. <H3><a name="Customization_nn6"></a>11.1.5 Defining different exception handlers</H3>
  247. <p>
  248. By default, the <tt>%exception</tt> directive creates an exception
  249. handler that is used for all wrapper functions that follow it. Unless
  250. there is a well-defined (and simple) error handling mechanism in place,
  251. defining one universal exception handler may be unwieldy and result
  252. in excessive code bloat since the handler is inlined into each wrapper function.
  253. </p>
  254. <p>
  255. To fix this, you can be more selective about how you use the
  256. <tt>%exception</tt> directive. One approach is to only place it around
  257. critical pieces of code. For example:
  258. </p>
  259. <div class="code"><pre>
  260. %exception {
  261. ... your exception handler ...
  262. }
  263. /* Define critical operations that can throw exceptions here */
  264. %exception;
  265. /* Define non-critical operations that don't throw exceptions */
  266. </pre></div>
  267. <p>
  268. More precise control over exception handling can be obtained by attaching an exception handler
  269. to specific declaration name. For example:
  270. </p>
  271. <div class="code">
  272. <pre>
  273. %exception allocate {
  274. try {
  275. $action
  276. }
  277. catch (MemoryError) {
  278. croak("Out of memory");
  279. }
  280. }
  281. </pre>
  282. </div>
  283. <p>
  284. In this case, the exception handler is only attached to declarations
  285. named "allocate". This would include both global and member
  286. functions. The names supplied to <tt>%exception</tt> follow the same
  287. rules as for <tt>%rename</tt> described in the section on
  288. <a href="SWIGPlus.html#SWIGPlus_ambiguity_resolution_renaming">Ambiguity resolution and renaming</a>.
  289. For example, if you wanted to define
  290. an exception handler for a specific class, you might write this:
  291. </p>
  292. <div class="code">
  293. <pre>
  294. %exception Object::allocate {
  295. try {
  296. $action
  297. }
  298. catch (MemoryError) {
  299. croak("Out of memory");
  300. }
  301. }
  302. </pre>
  303. </div>
  304. <p>
  305. When a class prefix is supplied, the exception handler is applied to the corresponding declaration
  306. in the specified class as well as for identically named functions appearing in derived classes.
  307. </p>
  308. <p>
  309. <tt>%exception</tt> can even be used to pinpoint a precise declaration when overloading is used. For example:
  310. </p>
  311. <div class="code">
  312. <pre>
  313. %exception Object::allocate(int) {
  314. try {
  315. $action
  316. }
  317. catch (MemoryError) {
  318. croak("Out of memory");
  319. }
  320. }
  321. </pre>
  322. </div>
  323. <p>
  324. Attaching exceptions to specific declarations is a good way to reduce code bloat. It can also be a useful way
  325. to attach exceptions to specific parts of a header file. For example:
  326. </p>
  327. <div class="code">
  328. <pre>
  329. %module example
  330. %{
  331. #include "someheader.h"
  332. %}
  333. // Define a few exception handlers for specific declarations
  334. %exception Object::allocate(int) {
  335. try {
  336. $action
  337. }
  338. catch (MemoryError) {
  339. croak("Out of memory");
  340. }
  341. }
  342. %exception Object::getitem {
  343. try {
  344. $action
  345. }
  346. catch (RangeError) {
  347. croak("Index out of range");
  348. }
  349. }
  350. ...
  351. // Read a raw header file
  352. %include "someheader.h"
  353. </pre>
  354. </div>
  355. <p>
  356. <b>Compatibility note:</b> The <tt>%exception</tt> directive replaces
  357. the functionality provided by the deprecated "except" typemap.
  358. The typemap would allow exceptions to be thrown in the target
  359. language based on the return type of a function and
  360. was intended to be a mechanism for pinpointing specific
  361. declarations. However, it never really worked that well and the new
  362. %exception directive is much better.
  363. </p>
  364. <H3><a name="Customization_exception_special_variables"></a>11.1.6 Special variables for %exception</H3>
  365. <p>
  366. The %exception directive supports a few special variables which are placeholders for
  367. code substitution.
  368. The following table shows the available special variables and details what the special
  369. variables are replaced with.
  370. </p>
  371. <table summary="Special variables for %exception">
  372. <tr>
  373. <td>$action</td>
  374. <td>The actual operation to be performed (a function call, method invocation, variable access, etc.)</td>
  375. </tr>
  376. <tr>
  377. <td>$symname</td>
  378. <td>The symbol name used internally by SWIG</td>
  379. </tr>
  380. <tr>
  381. <td>$overname</td>
  382. <td>The extra mangling used in the symbol name for overloaded method. Expands to nothing if the wrapped method is not overloaded.</td>
  383. </tr>
  384. <tr>
  385. <td>$wrapname</td>
  386. <td>The language specific wrapper name (usually a C function name exported from the shared object/dll)</td>
  387. </tr>
  388. <tr>
  389. <td>$decl</td>
  390. <td>The fully qualified C/C++ declaration of the method being wrapped without the return type</td>
  391. </tr>
  392. <tr>
  393. <td>$fulldecl</td>
  394. <td>The fully qualified C/C++ declaration of the method being wrapped including the return type</td>
  395. </tr>
  396. </table>
  397. <p>
  398. The special variables are often used in situations where method calls are logged. Exactly which form of the method call needs logging is up to individual requirements, but the example code below shows all the possible expansions, plus how an exception message could be tailored to show the C++ method declaration:
  399. </p>
  400. <div class="code"><pre>
  401. %exception Special::something {
  402. log("symname: $symname");
  403. log("overname: $overname");
  404. log("wrapname: $wrapname");
  405. log("decl: $decl");
  406. log("fulldecl: $fulldecl");
  407. try {
  408. $action
  409. }
  410. catch (MemoryError) {
  411. croak("Out of memory in $decl");
  412. }
  413. }
  414. void log(const char *message);
  415. struct Special {
  416. void something(const char *c);
  417. void something(int i);
  418. };
  419. </pre></div>
  420. <p>
  421. Below shows the expansions for the 1st of the overloaded <tt>something</tt> wrapper methods for Perl:
  422. </p>
  423. <div class="code"><pre>
  424. log("symname: Special_something");
  425. log("overname: __SWIG_0");
  426. log("wrapname: _wrap_Special_something__SWIG_0");
  427. log("decl: Special::something(char const *)");
  428. log("fulldecl: void Special::something(char const *)");
  429. try {
  430. (arg1)-&gt;something((char const *)arg2);
  431. }
  432. catch (MemoryError) {
  433. croak("Out of memory in Special::something(char const *)");
  434. }
  435. </pre></div>
  436. <H3><a name="Customization_nn7"></a>11.1.7 Using The SWIG exception library</H3>
  437. <p>
  438. The <tt>exception.i</tt> library file provides support for creating
  439. language independent exceptions in your interfaces. To use it, simply
  440. put an "<tt>%include exception.i</tt>" in your interface file. This
  441. creates a function<tt> SWIG_exception()</tt> that can be used to raise
  442. common scripting language exceptions in a portable manner. For example :</p>
  443. <div class="code"><pre>
  444. // Language independent exception handler
  445. %include exception.i
  446. %exception {
  447. try {
  448. $action
  449. } catch(RangeError) {
  450. SWIG_exception(SWIG_ValueError, "Range Error");
  451. } catch(DivisionByZero) {
  452. SWIG_exception(SWIG_DivisionByZero, "Division by zero");
  453. } catch(OutOfMemory) {
  454. SWIG_exception(SWIG_MemoryError, "Out of memory");
  455. } catch(...) {
  456. SWIG_exception(SWIG_RuntimeError,"Unknown exception");
  457. }
  458. }
  459. </pre></div>
  460. <p>
  461. As arguments, <tt>SWIG_exception()</tt> takes an error type code (an
  462. integer) and an error message string. The currently supported error
  463. types are :</p>
  464. <div class="diagram"><pre>
  465. SWIG_UnknownError
  466. SWIG_IOError
  467. SWIG_RuntimeError
  468. SWIG_IndexError
  469. SWIG_TypeError
  470. SWIG_DivisionByZero
  471. SWIG_OverflowError
  472. SWIG_SyntaxError
  473. SWIG_ValueError
  474. SWIG_SystemError
  475. SWIG_AttributeError
  476. SWIG_MemoryError
  477. SWIG_NullReferenceError
  478. </pre></div>
  479. <p>
  480. Since the <tt>SWIG_exception()</tt> function is defined at the C-level
  481. it can be used elsewhere in SWIG. This includes typemaps and helper
  482. functions.
  483. </p>
  484. <H2><a name="Customization_ownership"></a>11.2 Object ownership and %newobject</H2>
  485. <p>
  486. A common problem in some applications is managing proper ownership of objects. For
  487. example, consider a function like this:
  488. </p>
  489. <div class="code">
  490. <pre>
  491. Foo *blah() {
  492. Foo *f = new Foo();
  493. return f;
  494. }
  495. </pre>
  496. </div>
  497. <p>
  498. If you wrap the function <tt>blah()</tt>, SWIG has no idea that the
  499. return value is a newly allocated object. As a result, the resulting
  500. extension module may produce a memory leak (SWIG is conservative and
  501. will never delete objects unless it knows for certain that the
  502. returned object was newly created).
  503. </p>
  504. <p>
  505. To fix this, you can provide an extra hint to the code generator using
  506. the <tt>%newobject</tt> directive. For example:
  507. </p>
  508. <div class="code">
  509. <pre>
  510. %newobject blah;
  511. Foo *blah();
  512. </pre>
  513. </div>
  514. <p>
  515. <tt>%newobject</tt> works exactly like <tt>%rename</tt> and <tt>%exception</tt>. In other words,
  516. you can attach it to class members and parameterized declarations as before. For example:
  517. </p>
  518. <div class="code">
  519. <pre>
  520. %newobject ::blah(); // Only applies to global blah
  521. %newobject Object::blah(int,double); // Only blah(int,double) in Object
  522. %newobject *::copy; // Copy method in all classes
  523. ...
  524. </pre>
  525. </div>
  526. <p>
  527. When <tt>%newobject</tt> is supplied, many language modules will
  528. arrange to take ownership of the return value. This allows the value
  529. to be automatically garbage-collected when it is no longer in use. However,
  530. this depends entirely on the target language (a language module may also choose to ignore
  531. the <tt>%newobject</tt> directive).
  532. </p>
  533. <p>
  534. Closely related to <tt>%newobject</tt> is a special typemap. The "newfree" typemap
  535. can be used to deallocate a newly allocated return value. It is only available on
  536. methods for which <tt>%newobject</tt> has been applied and is commonly used to clean-up string
  537. results. For example:
  538. </p>
  539. <div class="code">
  540. <pre>
  541. %typemap(newfree) char * "free($1);";
  542. ...
  543. %newobject strdup;
  544. ...
  545. char *strdup(const char *s);
  546. </pre>
  547. </div>
  548. <p>
  549. In this case, the result of the function is a string in the target language. Since this string
  550. is a copy of the original result, the data returned by <tt>strdup()</tt> is no longer needed.
  551. The "newfree" typemap in the example simply releases this memory.
  552. </p>
  553. <p>
  554. As a complement to the <tt>%newobject</tt>, from SWIG 1.3.28, you can
  555. use the <tt>%delobject</tt> directive. For example, if you have two
  556. methods, one to create objects and one to destroy them, you can use:
  557. </p>
  558. <div class="code">
  559. <pre>
  560. %newobject create_foo;
  561. %delobject destroy_foo;
  562. ...
  563. Foo *create_foo();
  564. void destroy_foo(Foo *foo);
  565. </pre>
  566. </div>
  567. <p> or in a member method as: </p>
  568. <div class="code">
  569. <pre>
  570. %delobject Foo::destroy;
  571. class Foo {
  572. public:
  573. void destroy() { delete this;}
  574. private:
  575. ~Foo();
  576. };
  577. </pre>
  578. </div>
  579. <p>
  580. <tt>%delobject</tt> instructs SWIG that the first argument passed to
  581. the method will be destroyed, and therefore, the target language
  582. should not attempt to deallocate it twice. This is similar to use the
  583. DISOWN typemap in the first method argument, and in fact, it also
  584. depends on the target language on implementing the 'disown' mechanism
  585. properly.
  586. </p>
  587. <p>
  588. The use of <tt>%newobject</tt> is also integrated with reference counting and is covered in the
  589. <a href="SWIGPlus.html#SWIGPlus_ref_unref">C++ reference counted objects</a> section.
  590. </p>
  591. <p>
  592. <b>Compatibility note:</b> Previous versions of SWIG had a special <tt>%new</tt> directive. However, unlike <tt>%newobject</tt>,
  593. it only applied to the next declaration. For example:
  594. </p>
  595. <div class="code">
  596. <pre>
  597. %new char *strdup(const char *s);
  598. </pre>
  599. </div>
  600. <p>
  601. For now this is still supported but is deprecated.
  602. </p>
  603. <p>
  604. <b>How to shoot yourself in the foot:</b> The <tt>%newobject</tt> directive is not a declaration modifier like the old
  605. <tt>%new</tt> directive. Don't write code like this:
  606. </p>
  607. <div class="code">
  608. <pre>
  609. %newobject
  610. char *strdup(const char *s);
  611. </pre>
  612. </div>
  613. <p>
  614. The results might not be what you expect.
  615. </p>
  616. <H2><a name="Customization_features"></a>11.3 Features and the %feature directive</H2>
  617. <p>
  618. Both <tt>%exception</tt> and <tt>%newobject</tt> are examples of a
  619. more general purpose customization mechanism known as "features." A
  620. feature is simply a user-definable property that is attached to
  621. specific declarations. Features are attached
  622. using the <tt>%feature</tt> directive. For example:
  623. </p>
  624. <div class="code">
  625. <pre>
  626. %feature("except") Object::allocate {
  627. try {
  628. $action
  629. }
  630. catch (MemoryError) {
  631. croak("Out of memory");
  632. }
  633. }
  634. %feature("new","1") *::copy;
  635. </pre>
  636. </div>
  637. <p>
  638. In fact, the <tt>%exception</tt> and <tt>%newobject</tt> directives are really nothing more than macros
  639. involving <tt>%feature</tt>:
  640. </p>
  641. <div class="code">
  642. <pre>
  643. #define %exception %feature("except")
  644. #define %newobject %feature("new","1")
  645. </pre>
  646. </div>
  647. <p>
  648. The name matching rules outlined in the <a href="SWIGPlus.html#SWIGPlus_ambiguity_resolution_renaming">Ambiguity resolution and renaming</a>
  649. section applies to all <tt>%feature</tt> directives.
  650. In fact the <tt>%rename</tt> directive is just a special form of <tt>%feature</tt>.
  651. The matching rules mean that features are very flexible and can be applied with
  652. pinpoint accuracy to specific declarations if needed.
  653. Additionally, if no declaration name is given, a global feature is said to be defined.
  654. This feature is then
  655. attached to <em>every</em> declaration that follows. This is how global exception handlers
  656. are defined. For example:
  657. </p>
  658. <div class="code">
  659. <pre>
  660. /* Define a global exception handler */
  661. %feature("except") {
  662. try {
  663. $action
  664. }
  665. ...
  666. }
  667. ... bunch of declarations ...
  668. </pre>
  669. </div>
  670. <p>
  671. The <tt>%feature</tt> directive can be used with different syntax.
  672. The following are all equivalent:
  673. </p>
  674. <div class="code">
  675. <pre>
  676. %feature("except") Object::method { $action };
  677. %feature("except") Object::method %{ $action %};
  678. %feature("except") Object::method " $action ";
  679. %feature("except","$action") Object::method;
  680. </pre>
  681. </div>
  682. <p>
  683. The syntax in the first variation will generate the <tt>{ }</tt> delimiters used whereas the other variations will not.
  684. </p>
  685. <H3><a name="Customization_feature_attributes"></a>11.3.1 Feature attributes</H3>
  686. <p>
  687. The <tt>%feature</tt> directive also accepts XML style attributes in the same way that typemaps do.
  688. Any number of attributes can be specified.
  689. The following is the generic syntax for features:
  690. </p>
  691. <div class="code">
  692. <pre>
  693. %feature("name","value", attribute1="AttributeValue1") symbol;
  694. %feature("name", attribute1="AttributeValue1") symbol {value};
  695. %feature("name", attribute1="AttributeValue1") symbol %{value%};
  696. %feature("name", attribute1="AttributeValue1") symbol "value";
  697. </pre>
  698. </div>
  699. <p>
  700. More than one attribute can be specified using a comma separated list.
  701. The Java module is an example that uses attributes in <tt>%feature("except")</tt>.
  702. The <tt>throws</tt> attribute specifies the name of a Java class to add to a proxy method's throws clause.
  703. In the following example, <tt>MyExceptionClass</tt> is the name of the Java class for adding to the throws clause.
  704. </p>
  705. <div class="code">
  706. <pre>
  707. %feature("except", throws="MyExceptionClass") Object::method {
  708. try {
  709. $action
  710. } catch (...) {
  711. ... code to throw a MyExceptionClass Java exception ...
  712. }
  713. };
  714. </pre>
  715. </div>
  716. <p>
  717. Further details can be obtained from the <a href="Java.html#Java_exception_handling">Java exception handling</a> section.
  718. </p>
  719. <H3><a name="Customization_feature_flags"></a>11.3.2 Feature flags</H3>
  720. <p>
  721. Feature flags are used to enable or disable a particular feature. Feature flags are a common but simple usage of <tt>%feature</tt>
  722. and the feature value should be either <tt>1</tt> to enable or <tt>0</tt> to disable the feature.
  723. </p>
  724. <div class="code">
  725. <pre>
  726. %feature("featurename") // enables feature
  727. %feature("featurename", "1") // enables feature
  728. %feature("featurename", "x") // enables feature
  729. %feature("featurename", "0") // disables feature
  730. %feature("featurename", "") // clears feature
  731. </pre>
  732. </div>
  733. <p>
  734. Actually any value other than zero will enable the feature.
  735. Note that if the value is omitted completely, the default value becomes <tt>1</tt>, thereby enabling the feature.
  736. A feature is cleared by specifying no value, see <a href="#Customization_clearing_features">Clearing features</a>.
  737. The <tt>%immutable</tt> directive described in the <a href="SWIG.html#SWIG_readonly_variables">Creating read-only variables</a> section,
  738. is just a macro for <tt>%feature("immutable")</tt>, and can be used to demonstrates feature flags:
  739. </p>
  740. <div class="code">
  741. <pre>
  742. // features are disabled by default
  743. int red; // mutable
  744. %feature("immutable"); // global enable
  745. int orange; // immutable
  746. %feature("immutable","0"); // global disable
  747. int yellow; // mutable
  748. %feature("immutable","1"); // another form of global enable
  749. int green; // immutable
  750. %feature("immutable",""); // clears the global feature
  751. int blue; // mutable
  752. </pre>
  753. </div>
  754. <p>
  755. Note that features are disabled by default and must be explicitly enabled either globally or by specifying a targeted declaration.
  756. The above intersperses SWIG directives with C code. Of course you can target features explicitly, so the above could also be rewritten as:
  757. </p>
  758. <div class="code">
  759. <pre>
  760. %feature("immutable","1") orange;
  761. %feature("immutable","1") green;
  762. int red; // mutable
  763. int orange; // immutable
  764. int yellow; // mutable
  765. int green; // immutable
  766. int blue; // mutable
  767. </pre>
  768. </div>
  769. <p>
  770. The above approach allows for the C declarations to be separated from the SWIG directives for when the C declarations are parsed from a C header file.
  771. The logic above can of course be inverted and rewritten as:
  772. </p>
  773. <div class="code">
  774. <pre>
  775. %feature("immutable","1");
  776. %feature("immutable","0") red;
  777. %feature("immutable","0") yellow;
  778. %feature("immutable","0") blue;
  779. int red; // mutable
  780. int orange; // immutable
  781. int yellow; // mutable
  782. int green; // immutable
  783. int blue; // mutable
  784. </pre>
  785. </div>
  786. <p>
  787. As hinted above for <tt>%immutable</tt>, most feature flags can also be specified via alternative syntax. The alternative syntax is just a macro
  788. in the <tt>swig.swg</tt> Library file. The following shows the alternative syntax for the imaginary <tt>featurename</tt> feature:
  789. </p>
  790. <div class="code">
  791. <pre>
  792. %featurename // equivalent to %feature("featurename", "1") ie enables feature
  793. %nofeaturename // equivalent to %feature("featurename", "0") ie disables feature
  794. %clearfeaturename // equivalent to %feature("featurename", "") ie clears feature
  795. </pre>
  796. </div>
  797. <p>
  798. The concept of clearing features is discussed next.
  799. </p>
  800. <H3><a name="Customization_clearing_features"></a>11.3.3 Clearing features</H3>
  801. <p>
  802. A feature stays in effect until it is explicitly cleared. A feature is cleared by
  803. supplying a <tt>%feature</tt> directive with no value. For example <tt>%feature("name","")</tt>.
  804. A cleared feature means that any feature exactly matching any previously defined feature is no longer used in the name matching rules.
  805. So if a feature is cleared, it might mean that another name matching rule will apply.
  806. To clarify, let's consider the <tt>except</tt> feature again (<tt>%exception</tt>):
  807. </p>
  808. <div class="code">
  809. <pre>
  810. // Define global exception handler
  811. %feature("except") {
  812. try {
  813. $action
  814. } catch (...) {
  815. croak("Unknown C++ exception");
  816. }
  817. }
  818. // Define exception handler for all clone methods to log the method calls
  819. %feature("except") *::clone() {
  820. try {
  821. logger.info("$action");
  822. $action
  823. } catch (...) {
  824. croak("Unknown C++ exception");
  825. }
  826. }
  827. ... initial set of class declarations with clone methods ...
  828. // clear the previously defined feature
  829. %feature("except","") *::clone();
  830. ... final set of class declarations with clone methods ...
  831. </pre>
  832. </div>
  833. <p>
  834. In the above scenario, the initial set of clone methods will log all method invocations from the target language.
  835. This specific feature is cleared for the final set of clone methods.
  836. However, these clone methods will still have an exception handler (without logging) as the next best feature match for them is the global exception handler.
  837. </p>
  838. <p>
  839. Note that clearing a feature is not always the same as disabling it.
  840. Clearing the feature above with <tt>%feature("except","") *::clone()</tt> is not the same as specifying
  841. <tt>%feature("except","0") *::clone()</tt>. The former will disable the feature for clone methods -
  842. the feature is still a better match than the global feature.
  843. If on the other hand, no global exception handler had been defined at all,
  844. then clearing the feature would be the same as disabling it as no other feature would have matched.
  845. </p>
  846. <p>
  847. Note that the feature must match exactly for it to be cleared by any previously defined feature.
  848. For example the following attempt to clear the initial feature will not work:
  849. </p>
  850. <div class="code">
  851. <pre>
  852. %feature("except") clone() { logger.info("$action"); $action }
  853. %feature("except","") *::clone();
  854. </pre>
  855. </div>
  856. <p>
  857. but this will:
  858. </p>
  859. <div class="code">
  860. <pre>
  861. %feature("except") clone() { logger.info("$action"); $action }
  862. %feature("except","") clone();
  863. </pre>
  864. </div>
  865. <p>
  866. SWIG provides macros for disabling and clearing features. Many of these can be found in the <tt>swig.swg</tt> library file.
  867. The typical pattern is to define three macros; one to define the feature itself, one to disable the feature and one to clear the feature.
  868. The three macros below show this for the "except" feature:
  869. </p>
  870. <div class="code">
  871. <pre>
  872. #define %exception %feature("except")
  873. #define %noexception %feature("except","0")
  874. #define %clearexception %feature("except","")
  875. </pre>
  876. </div>
  877. <H3><a name="Customization_features_default_args"></a>11.3.4 Features and default arguments</H3>
  878. <p>
  879. SWIG treats methods with default arguments as separate overloaded methods as detailed
  880. in the <a href="SWIGPlus.html#SWIGPlus_default_args">default arguments</a> section.
  881. Any <tt>%feature</tt> targeting a method with default arguments
  882. will apply to all the extra overloaded methods that SWIG generates if the
  883. default arguments are specified in the feature. If the default arguments are
  884. not specified in the feature, then the feature will match that exact
  885. wrapper method only and not the extra overloaded methods that SWIG generates.
  886. For example:
  887. </p>
  888. <div class="code">
  889. <pre>
  890. %feature("except") void hello(int i=0, double d=0.0) { ... }
  891. void hello(int i=0, double d=0.0);
  892. </pre>
  893. </div>
  894. <p>
  895. will apply the feature to all three wrapper methods, that is:
  896. </p>
  897. <div class="code">
  898. <pre>
  899. void hello(int i, double d);
  900. void hello(int i);
  901. void hello();
  902. </pre>
  903. </div>
  904. <p>
  905. If the default arguments are not specified in the feature:
  906. </p>
  907. <div class="code">
  908. <pre>
  909. %feature("except") void hello(int i, double d) { ... }
  910. void hello(int i=0, double d=0.0);
  911. </pre>
  912. </div>
  913. <p>
  914. then the feature will only apply to this wrapper method:
  915. </p>
  916. <div class="code">
  917. <pre>
  918. void hello(int i, double d);
  919. </pre>
  920. </div>
  921. <p>
  922. and not these wrapper methods:
  923. </p>
  924. <div class="code">
  925. <pre>
  926. void hello(int i);
  927. void hello();
  928. </pre>
  929. </div>
  930. <p>
  931. If <a href="SWIGPlus.html#SWIGPlus_default_args">compactdefaultargs</a> are being used, then the difference between
  932. specifying or not specifying default arguments in a feature is not applicable as just one wrapper is generated.
  933. </p>
  934. <p>
  935. <b>Compatibility note:</b> The different behaviour of features specified with or without default arguments was introduced
  936. in SWIG-1.3.23 when the approach to wrapping methods with default arguments was changed.
  937. </p>
  938. <H3><a name="Customization_features_example"></a>11.3.5 Feature example</H3>
  939. <p>
  940. As has been shown earlier, the intended use for the <tt>%feature</tt> directive is as a highly flexible customization mechanism that can be used to annotate
  941. declarations with additional information for use by specific target language modules. Another example is
  942. in the Python module. You might use <tt>%feature</tt> to rewrite proxy/shadow class code as follows:
  943. </p>
  944. <div class="code">
  945. <pre>
  946. %module example
  947. %rename(bar_id) bar(int,double);
  948. // Rewrite bar() to allow some nice overloading
  949. %feature("shadow") Foo::bar(int) %{
  950. def bar(*args):
  951. if len(args) == 3:
  952. return apply(examplec.Foo_bar_id,args)
  953. return apply(examplec.Foo_bar,args)
  954. %}
  955. class Foo {
  956. public:
  957. int bar(int x);
  958. int bar(int x, double y);
  959. }
  960. </pre>
  961. </div>
  962. <p>
  963. Further details of <tt>%feature</tt> usage is described in the documentation for specific language modules.
  964. </p>
  965. </body>
  966. </html>