PageRenderTime 54ms CodeModel.GetById 36ms app.highlight 10ms RepoModel.GetById 1ms app.codeStats 0ms

/trunk/Doc/Manual/Customization.html

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