"Fossies" - the Fresh Open Source Software Archive

Member "swig-4.1.1/Doc/Manual/Customization.html" (30 Nov 2022, 33008 Bytes) of package /linux/misc/swig-4.1.1.tar.gz:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) HTML source code syntax highlighting (style: standard) with prefixed line numbers. Alternatively you can here view or download the uninterpreted source code file.

A hint: This file contains one or more very long lines, so maybe it is better readable using the pure text view mode that shows the contents as wrapped lines within the browser window.


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