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