This file is indexed.

/usr/share/doc/swig3.0-doc/Manual/Customization.html is in swig3.0-doc 3.0.8-0ubuntu3.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Customization Features</title>
<link rel="stylesheet" type="text/css" href="style.css">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>

<body bgcolor="#ffffff">
<H1><a name="Customization">12 Customization Features</a></H1>
<!-- INDEX -->
<div class="sectiontoc">
<ul>
<li><a href="#Customization_exception">Exception handling with %exception</a>
<ul>
<li><a href="#Customization_nn3">Handling exceptions in C code</a>
<li><a href="#Customization_nn4">Exception handling with longjmp()</a>
<li><a href="#Customization_nn5">Handling C++ exceptions</a>
<li><a href="#Customization_allowexcept">Exception handlers for variables</a>
<li><a href="#Customization_nn6">Defining different exception handlers</a>
<li><a href="#Customization_exception_special_variables">Special variables for %exception</a>
<li><a href="#Customization_nn7">Using The SWIG exception library</a>
</ul>
<li><a href="#Customization_ownership">Object ownership and %newobject</a>
<li><a href="#Customization_features">Features and the %feature directive</a>
<ul>
<li><a href="#Customization_feature_attributes">Feature attributes</a>
<li><a href="#Customization_feature_flags">Feature flags</a>
<li><a href="#Customization_clearing_features">Clearing features</a>
<li><a href="#Customization_features_default_args">Features and default arguments</a>
<li><a href="#Customization_features_example">Feature example</a>
</ul>
</ul>
</div>
<!-- INDEX -->



<p>
In many cases, it is desirable to change the default wrapping of
particular declarations in an interface.  For example, you might want
to provide hooks for catching C++ exceptions, add assertions, or
provide hints to the underlying code generator.  This chapter
describes some of these customization techniques.  First, a discussion
of exception handling is presented.  Then, a more general-purpose
customization mechanism known as "features" is described.
</p>

<H2><a name="Customization_exception">12.1 Exception handling with %exception</a></H2>


<p>
The <tt>%exception</tt> directive allows you to define a general purpose exception
handler. For example, you can specify the following:
</p>

<div class="code"><pre>
%exception {
    try {
        $action
    }
    catch (RangeError) {
        ... handle error ...
    }
}
</pre></div>

<p>
How the exception is handled depends on the target language, for example, Python:
</p>

<div class="code"><pre>
%exception {
    try {
        $action
    }
    catch (RangeError) {
        PyErr_SetString(PyExc_IndexError,"index out-of-bounds");
        SWIG_fail;
    }
}
</pre></div>

<p>
When defined, the code enclosed in braces is inserted directly into the low-level wrapper
functions.  The special variable <tt>$action</tt> is one of a few
<a href="Customization.html#Customization_exception_special_variables">%exception special variables</a>
supported and gets replaced with the actual operation
to be performed (a function call, method invocation, attribute access, etc.).  An exception handler
remains in effect until it is explicitly deleted.  This is done by using either <tt>%exception</tt> 
or <tt>%noexception</tt> with no code. For example:
</p>

<div class="code"><pre>
%exception;   // Deletes any previously defined handler
</pre></div>

<p>
<b>Compatibility note:</b>  Previous versions of SWIG used a special directive <tt>%except</tt>
for exception handling.   That directive is deprecated--<tt>%exception</tt>
provides the same functionality, but is substantially more flexible.
</p>

<H3><a name="Customization_nn3">12.1.1 Handling exceptions in C code</a></H3>


<p>
C has no formal exception handling mechanism so there are several approaches that might be
used.  A somewhat common technique is to simply set a special error code.  For example:
</p>

<div class="code"><pre>
/* File : except.c */

static char error_message[256];
static int error_status = 0;

void throw_exception(char *msg) {
  strncpy(error_message,msg,256);
  error_status = 1;
}

void clear_exception() {
  error_status = 0;
}
char *check_exception() {
  if (error_status)
    return error_message;
  else
    return NULL;
}

</pre></div>

<p>
To use these functions, functions simply call
<tt>throw_exception()</tt> to indicate an error occurred. For example
:</p>

<div class="code"><pre>
double inv(double x) {
  if (x != 0)
    return 1.0/x;
  else {
    throw_exception("Division by zero");
    return 0;
  }
}
</pre></div>

<p>
To catch the exception, you can write a simple exception handler such
as the following (shown for Perl5) :</p>

<div class="code"><pre>
%exception {
  char *err;
  clear_exception();
  $action
  if ((err = check_exception())) {
    croak(err);
  }
}
</pre></div>

<p>
In this case, when an error occurs, it is translated into a Perl error.
Each target language has its own approach to creating a runtime error/exception in
and for Perl it is the <tt>croak</tt> method shown above.
</p>

<H3><a name="Customization_nn4">12.1.2 Exception handling with longjmp()</a></H3>


<p>
Exception handling can also be added to C code using the
<tt>&lt;setjmp.h&gt;</tt> library.  Here is a minimalistic implementation that
relies on the C preprocessor :
</p>

<div class="code"><pre>
/* File : except.c
   Just the declaration of a few global variables we're going to use */

#include &lt;setjmp.h&gt;
jmp_buf exception_buffer;
int exception_status;

/* File : except.h */
#include &lt;setjmp.h&gt;
extern jmp_buf exception_buffer;
extern int exception_status;

#define try if ((exception_status = setjmp(exception_buffer)) == 0)
#define catch(val) else if (exception_status == val)
#define throw(val) longjmp(exception_buffer,val)
#define finally else

/* Exception codes */

#define RangeError     1
#define DivisionByZero 2
#define OutOfMemory    3

</pre></div>

<p>
Now, within a C program, you can do the following :</p>

<div class="code"><pre>
double inv(double x) {
  if (x)
    return 1.0/x;
  else
    throw(DivisionByZero);
}

</pre></div>

<p>
Finally, to create a SWIG exception handler, write the following :</p>

<div class="code"><pre>
%{
#include "except.h"
%}

%exception {
  try {
    $action
  } catch(RangeError) {
    croak("Range Error");
  } catch(DivisionByZero) {
    croak("Division by zero");
  } catch(OutOfMemory) {
    croak("Out of memory");
  } finally {
    croak("Unknown exception");
  }
}
</pre></div>

<p>
Note: This implementation is only intended to illustrate the general idea.  To make it work better, you'll need to
modify it to handle nested <tt>try</tt> declarations.
</p>

<H3><a name="Customization_nn5">12.1.3 Handling C++ exceptions</a></H3>


<p>
Handling C++ exceptions is also straightforward.  For example: 
</p>

<div class="code"><pre>
%exception {
  try {
    $action
  } catch(RangeError) {
    croak("Range Error");
  } catch(DivisionByZero) {
    croak("Division by zero");
  } catch(OutOfMemory) {
    croak("Out of memory");
  } catch(...) {
    croak("Unknown exception");
  }
}

</pre></div>

<p>
The exception types need to be declared as classes elsewhere, possibly
in a header file :</p>

<div class="code"><pre>
class RangeError {};
class DivisionByZero {};
class OutOfMemory {};
</pre>
</div>

<H3><a name="Customization_allowexcept">12.1.4 Exception handlers for variables</a></H3>


<p>
By default all variables will ignore <tt>%exception</tt>, so it is effectively turned off for all variables wrappers.
This applies to global variables, member variables and static member variables.
The approach is certainly a logical one when wrapping variables in C.
However, in C++, it is quite possible for an exception to be thrown while the variable is being assigned.
To ensure <tt>%exception</tt> is used when wrapping variables, it needs to be 'turned on' using the <tt>%allowexception</tt> feature.
Note that <tt>%allowexception</tt> is just a macro for <tt>%feature("allowexcept")</tt>, that is, it is a feature called "allowexcept".
Any variable which has this feature attached to it, will then use the <tt>%exception</tt> feature, but of course,
only if there is a <tt>%exception</tt> attached to the variable in the first place.
The <tt>%allowexception</tt> feature works like any other feature and so can be used globally or for selective variables.
</p>

<div class="code">
<pre>
%allowexception;                // turn on globally
%allowexception Klass::MyVar;   // turn on for a specific variable

%noallowexception Klass::MyVar; // turn off for a specific variable
%noallowexception;              // turn off globally
</pre>
</div>

<H3><a name="Customization_nn6">12.1.5 Defining different exception handlers</a></H3>


<p>
By default, the <tt>%exception</tt> directive creates an exception
handler that is used for all wrapper functions that follow it.  Unless
there is a well-defined (and simple) error handling mechanism in place,
defining one universal exception handler may be unwieldy and result
in excessive code bloat since the handler is inlined into each wrapper function.
</p>

<p>
To fix this, you can be more selective about how you use the
<tt>%exception</tt> directive.  One approach is to only place it around
critical pieces of code.  For example:
</p>

<div class="code"><pre>
%exception {
  ... your exception handler ...
}
/* Define critical operations that can throw exceptions here */

%exception;

/* Define non-critical operations that don't throw exceptions */
</pre></div>

<p>
More precise control over exception handling can be obtained by attaching an exception handler
to specific declaration name. For example:
</p>

<div class="code">
<pre>
%exception allocate {
    try {
        $action
    } 
    catch (MemoryError) {
        croak("Out of memory");
    }
}
</pre>
</div>

<p>
In this case, the exception handler is only attached to declarations
named "allocate".  This would include both global and member
functions.  The names supplied to <tt>%exception</tt> follow the same
rules as for <tt>%rename</tt> described in the section on 
<a href="SWIGPlus.html#SWIGPlus_ambiguity_resolution_renaming">Ambiguity resolution and renaming</a>.
For example, if you wanted to define
an exception handler for a specific class, you might write this:
</p>

<div class="code">
<pre>
%exception Object::allocate {
    try {
        $action
    } 
    catch (MemoryError) {
        croak("Out of memory");
    }
}
</pre>
</div>

<p>
When a class prefix is supplied, the exception handler is applied to the corresponding declaration
in the specified class as well as for identically named functions appearing in derived classes.  
</p>

<p>
<tt>%exception</tt> can even be used to pinpoint a precise declaration when overloading is used. For example:
</p>

<div class="code">
<pre>
%exception Object::allocate(int) {
    try {
        $action
    } 
    catch (MemoryError) {
        croak("Out of memory");
    }
}
</pre>
</div>

<p>
Attaching exceptions to specific declarations is a good way to reduce code bloat.  It can also be a useful way 
to attach exceptions to specific parts of a header file. For example:
</p>

<div class="code">
<pre>
%module example
%{
#include "someheader.h"
%}

// Define a few exception handlers for specific declarations
%exception Object::allocate(int) {
    try {
        $action
    } 
    catch (MemoryError) {
        croak("Out of memory");
    }
}

%exception Object::getitem {
    try {
       $action
    }
    catch (RangeError) {
       croak("Index out of range");
    }
}
...
// Read a raw header file
%include "someheader.h"
</pre>
</div>

<p>
<b>Compatibility note:</b> The <tt>%exception</tt> directive replaces
the functionality provided by the deprecated "except" typemap.
The typemap would allow exceptions to be thrown in the target 
language based on the return type of a function and 
was intended to be a mechanism for pinpointing specific
declarations.  However, it never really worked that well and the new
%exception directive is much better.
</p>

<H3><a name="Customization_exception_special_variables">12.1.6 Special variables for %exception</a></H3>


<p>
The %exception directive supports a few special variables which are placeholders for
code substitution.
The following table shows the available special variables and details what the special
variables are replaced with.
</p>

<table summary="Special variables for %exception">

<tr>
<td>$action</td>
<td>The actual operation to be performed (a function call, method invocation, variable access, etc.)</td>
</tr>

<tr>
<td>$name</td>
<td>The C/C++ symbol name for the function.</td>
</tr>

<tr>
<td>$symname</td>
<td>The symbol name used internally by SWIG</td>
</tr>

<tr>
<td>$overname</td>
<td>The extra mangling used in the symbol name for overloaded method. Expands to nothing if the wrapped method is not overloaded.</td>
</tr>

<tr>
<td>$wrapname</td>
<td>The language specific wrapper name (usually a C function name exported from the shared object/dll)</td>
</tr>

<tr>
<td>$decl</td>
<td>The fully qualified C/C++ declaration of the method being wrapped without the return type</td>
</tr>

<tr>
<td>$fulldecl</td>
<td>The fully qualified C/C++ declaration of the method being wrapped including the return type</td>
</tr>

<tr>
<td>$parentclassname</td>
<td>The parent class name (if any) for a method.</td>
</tr>

<tr>
<td>$parentclasssymname</td>
<td>The target language parent class name (if any) for a method.</td>
</tr>

</table>

<p>
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:
</p>

<div class="code"><pre>
%exception Special::something {
  log("symname: $symname");
  log("overname: $overname");
  log("wrapname: $wrapname");
  log("decl: $decl");
  log("fulldecl: $fulldecl");
  try {
    $action
  } 
  catch (MemoryError) {
      croak("Out of memory in $decl");
  }
}
void log(const char *message);
struct Special {
  void something(const char *c);
  void something(int i);
};
</pre></div>

<p>
Below shows the expansions for the 1st of the overloaded <tt>something</tt> wrapper methods for Perl:
</p>

<div class="code"><pre>
  log("symname: Special_something");
  log("overname: __SWIG_0");
  log("wrapname: _wrap_Special_something__SWIG_0");
  log("decl: Special::something(char const *)");
  log("fulldecl: void Special::something(char const *)");
  try {
    (arg1)-&gt;something((char const *)arg2);
  } 
  catch (MemoryError) {
    croak("Out of memory in Special::something(char const *)");
  }
</pre></div>


<H3><a name="Customization_nn7">12.1.7 Using The SWIG exception library</a></H3>


<p>
The <tt>exception.i</tt> library file provides support for creating
language independent exceptions in your interfaces.  To use it, simply
put an "<tt>%include exception.i</tt>" in your interface file.  This
provides a function <tt>SWIG_exception()</tt> that can be used to raise
common scripting language exceptions in a portable manner.  For example :</p>

<div class="code"><pre>
// Language independent exception handler
%include exception.i       

%exception {
    try {
        $action
    } catch(RangeError) {
        SWIG_exception(SWIG_ValueError, "Range Error");
    } catch(DivisionByZero) {
        SWIG_exception(SWIG_DivisionByZero, "Division by zero");
    } catch(OutOfMemory) {
        SWIG_exception(SWIG_MemoryError, "Out of memory");
    } catch(...) {
        SWIG_exception(SWIG_RuntimeError,"Unknown exception");
    }
}

</pre></div>

<p>
As arguments, <tt>SWIG_exception()</tt> takes an error type code (an
integer) and an error message string.  The currently supported error
types are :</p>

<div class="diagram"><pre>
SWIG_UnknownError
SWIG_IOError
SWIG_RuntimeError
SWIG_IndexError
SWIG_TypeError
SWIG_DivisionByZero
SWIG_OverflowError
SWIG_SyntaxError
SWIG_ValueError
SWIG_SystemError
SWIG_AttributeError
SWIG_MemoryError
SWIG_NullReferenceError
</pre></div>

<p>
The <tt>SWIG_exception()</tt> function can also be used in typemaps.
</p>

<H2><a name="Customization_ownership">12.2 Object ownership and %newobject</a></H2>


<p>
A common problem in some applications is managing proper ownership of objects.  For
example, consider a function like this:
</p>

<div class="code">
<pre>
Foo *blah() {
   Foo *f = new Foo();
   return f;
}
</pre>
</div>

<p>
If you wrap the function <tt>blah()</tt>, SWIG has no idea that the
return value is a newly allocated object.  As a result, the resulting
extension module may produce a memory leak (SWIG is conservative and
will never delete objects unless it knows for certain that the
returned object was newly created).
</p>

<p>
To fix this, you can provide an extra hint to the code generator using
the <tt>%newobject</tt> directive.  For example:
</p>

<div class="code">
<pre>
%newobject blah;
Foo *blah();
</pre>
</div>

<p>
<tt>%newobject</tt> works exactly like <tt>%rename</tt> and <tt>%exception</tt>.  In other words,
you can attach it to class members and parameterized declarations as before.  For example:
</p>

<div class="code">
<pre>
%newobject ::blah();                   // Only applies to global blah
%newobject Object::blah(int,double);   // Only blah(int,double) in Object
%newobject *::copy;                    // Copy method in all classes
...
</pre>
</div>

<p>
When <tt>%newobject</tt> is supplied, many language modules will
arrange to take ownership of the return value.  This allows the value
to be automatically garbage-collected when it is no longer in use.  However,
this depends entirely on the target language (a language module may also choose to ignore
the <tt>%newobject</tt> directive).
</p>

<p>
Closely related to <tt>%newobject</tt> is a special typemap.  The "newfree" typemap
can be used to deallocate a newly allocated return value.  It is only available on
methods for which <tt>%newobject</tt> has been applied and is commonly used to clean-up string
results.  For example:
</p>

<div class="code">
<pre>
%typemap(newfree) char * "free($1);";
...
%newobject strdup;
...
char *strdup(const char *s);
</pre>
</div>

<p>
In this case, the result of the function is a string in the target language.  Since this string
is a copy of the original result, the data returned by <tt>strdup()</tt> is no longer needed.  
The "newfree" typemap in the example simply releases this memory.
</p>

<p>
As a complement to the <tt>%newobject</tt>, from SWIG 1.3.28, you can
use the <tt>%delobject</tt> directive. For example, if you have two
methods, one to create objects and one to destroy them, you can use:
</p>

<div class="code">
<pre>
%newobject create_foo;
%delobject destroy_foo;
...
Foo *create_foo();
void destroy_foo(Foo *foo);
</pre>
</div>

<p> or in a member method as: </p>
<div class="code">
<pre>
%delobject Foo::destroy;

class Foo {
public:
  void destroy() { delete this;}

private:
  ~Foo();
};
</pre>
</div>

<p>
<tt>%delobject</tt> instructs SWIG that the first argument passed to
the method will be destroyed, and therefore, the target language
should not attempt to deallocate it twice. This is similar to use the
DISOWN typemap in the first method argument, and in fact, it also
depends on the target language on implementing the 'disown' mechanism
properly.
</p>

<p>
The use of <tt>%newobject</tt> is also integrated with reference counting and is covered in the
<a href="SWIGPlus.html#SWIGPlus_ref_unref">C++ reference counted objects</a> section.
</p>

<p>
<b>Compatibility note:</b>  Previous versions of SWIG had a special <tt>%new</tt> directive.  However, unlike <tt>%newobject</tt>,
it only applied to the next declaration.  For example:
</p>

<div class="code">
<pre>
%new char *strdup(const char *s);
</pre>
</div>

<p>
For now this is still supported but is deprecated.  
</p>

<p>
<b>How to shoot yourself in the foot:</b>  The <tt>%newobject</tt> directive is not a declaration modifier like the old
<tt>%new</tt> directive.   Don't write code like this:
</p>

<div class="code">
<pre>
%newobject
char *strdup(const char *s);
</pre>
</div>
<p>
The results might not be what you expect.
</p>

<H2><a name="Customization_features">12.3 Features and the %feature directive</a></H2>


<p>
Both <tt>%exception</tt> and <tt>%newobject</tt> are examples of a
more general purpose customization mechanism known as "features."  A
feature is simply a user-definable property that is attached to
specific declarations.  Features are attached
using the <tt>%feature</tt> directive. For example:
</p>

<div class="code">
<pre>
%feature("except") Object::allocate {
    try {
        $action
    } 
    catch (MemoryError) {
        croak("Out of memory");
    }
}

%feature("new","1") *::copy;
</pre>
</div>

<p>
In fact, the <tt>%exception</tt> and <tt>%newobject</tt> directives are really nothing more than macros 
involving <tt>%feature</tt>:
</p>

<div class="code">
<pre>
#define %exception %feature("except")
#define %newobject %feature("new","1")
</pre>
</div>

<p>
The name matching rules outlined in the <a href="SWIGPlus.html#SWIGPlus_ambiguity_resolution_renaming">Ambiguity resolution and renaming</a>
section applies to all <tt>%feature</tt> directives.
In fact the <tt>%rename</tt> directive is just a special form of <tt>%feature</tt>. 
The matching rules mean that features are very flexible and can be applied with
pinpoint accuracy to specific declarations if needed.
Additionally, if no declaration name is given, a global feature is said to be defined.
This feature is then
attached to <em>every</em> declaration that follows.  This is how global exception handlers
are defined.  For example:
</p>

<div class="code">
<pre>
/* Define a global exception handler */
%feature("except") {
   try {
     $action
   }
   ...
}

... bunch of declarations ...
</pre>
</div>

<p>
The <tt>%feature</tt> directive can be used with different syntax.
The following are all equivalent:
</p>

<div class="code">
<pre>
%feature("except") Object::method { $action };
%feature("except") Object::method %{ $action %};
%feature("except") Object::method " $action ";
%feature("except","$action") Object::method;
</pre>
</div>

<p>
The syntax in the first variation will generate the <tt>{ }</tt> delimiters used whereas the other variations will not.
</p>

<H3><a name="Customization_feature_attributes">12.3.1 Feature attributes</a></H3>


<p>
The <tt>%feature</tt> directive also accepts XML style attributes in the same way that typemaps do.
Any number of attributes can be specified.
The following is the generic syntax for features:
</p>

<div class="code">
<pre>
%feature("name","value", attribute1="AttributeValue1") symbol;
%feature("name", attribute1="AttributeValue1") symbol {value};
%feature("name", attribute1="AttributeValue1") symbol %{value%};
%feature("name", attribute1="AttributeValue1") symbol "value";
</pre>
</div>

<p>
More than one attribute can be specified using a comma separated list. 
The Java module is an example that uses attributes in <tt>%feature("except")</tt>.
The <tt>throws</tt> attribute specifies the name of a Java class to add to a proxy method's throws clause.
In the following example, <tt>MyExceptionClass</tt> is the name of the Java class for adding to the throws clause.
</p>

<div class="code">
<pre>
%feature("except", throws="MyExceptionClass") Object::method { 
   try {
     $action
   } catch (...) {
     ... code to throw a MyExceptionClass Java exception ...
   }
};
</pre>
</div>

<p>
Further details can be obtained from the <a href="Java.html#Java_exception_handling">Java exception handling</a> section.
</p>

<H3><a name="Customization_feature_flags">12.3.2 Feature flags</a></H3>


<p>
Feature flags are used to enable or disable a particular feature. Feature flags are a common but simple usage of <tt>%feature</tt>
and the feature value should be either <tt>1</tt> to enable or <tt>0</tt> to disable the feature. 
</p>

<div class="code">
<pre>
%feature("featurename")          // enables feature
%feature("featurename", "1")     // enables feature
%feature("featurename", "x")     // enables feature
%feature("featurename", "0")     // disables feature
%feature("featurename", "")      // clears feature
</pre>
</div>

<p>
Actually any value other than zero will enable the feature.
Note that if the value is omitted completely, the default value becomes <tt>1</tt>, thereby enabling the feature.
A feature is cleared by specifying no value, see <a href="#Customization_clearing_features">Clearing features</a>.
The <tt>%immutable</tt> directive described in the <a href="SWIG.html#SWIG_readonly_variables">Creating read-only variables</a> section,
is just a macro for <tt>%feature("immutable")</tt>, and can be used to demonstrates feature flags:
</p>

<div class="code">
<pre>
                                // features are disabled by default
int red;                        // mutable

%feature("immutable");          // global enable
int orange;                     // immutable

%feature("immutable","0");      // global disable
int yellow;                     // mutable

%feature("immutable","1");      // another form of global enable
int green;                      // immutable

%feature("immutable","");       // clears the global feature
int blue;                       // mutable
</pre>
</div>

<p>
Note that features are disabled by default and must be explicitly enabled either globally or by specifying a targeted declaration.
The above intersperses SWIG directives with C code. Of course you can target features explicitly, so the above could also be rewritten as:
</p>

<div class="code">
<pre>
%feature("immutable","1") orange;
%feature("immutable","1") green;
int red;                        // mutable
int orange;                     // immutable
int yellow;                     // mutable
int green;                      // immutable
int blue;                       // mutable
</pre>
</div>

<p>
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.
The logic above can of course be inverted and rewritten as:
</p>

<div class="code">
<pre>
%feature("immutable","1");
%feature("immutable","0") red;
%feature("immutable","0") yellow;
%feature("immutable","0") blue;
int red;                        // mutable
int orange;                     // immutable
int yellow;                     // mutable
int green;                      // immutable
int blue;                       // mutable
</pre>
</div>

<p>
As hinted above for <tt>%immutable</tt>, most feature flags can also be specified via alternative syntax. The alternative syntax is just a macro
in the <tt>swig.swg</tt> Library file. The following shows the alternative syntax for the imaginary <tt>featurename</tt> feature:
</p>

<div class="code">
<pre>
%featurename       // equivalent to %feature("featurename", "1") ie enables feature
%nofeaturename     // equivalent to %feature("featurename", "0") ie disables feature
%clearfeaturename  // equivalent to %feature("featurename", "")  ie clears feature
</pre>
</div>

<p>
The concept of clearing features is discussed next.
</p>

<H3><a name="Customization_clearing_features">12.3.3 Clearing features</a></H3>


<p>
A feature stays in effect until it is explicitly cleared.  A feature is cleared by
supplying a <tt>%feature</tt> directive with no value.  For example <tt>%feature("name","")</tt>.
A cleared feature means that any feature exactly matching any previously defined feature is no longer used in the name matching rules.
So if a feature is cleared, it might mean that another name matching rule will apply.
To clarify, let's consider the <tt>except</tt> feature again (<tt>%exception</tt>):
</p>

<div class="code">
<pre>
// Define global exception handler
%feature("except") {
    try {
        $action
    } catch (...) {
        croak("Unknown C++ exception");
    }
}

// Define exception handler for all clone methods to log the method calls
%feature("except") *::clone() {
    try {
        logger.info("$action");
        $action
    } catch (...) {
        croak("Unknown C++ exception");
    }
}

... initial set of class declarations with clone methods ...

// clear the previously defined feature
%feature("except","") *::clone();

... final set of class declarations with clone methods ...
</pre>
</div>

<p>
In the above scenario, the initial set of clone methods will log all method invocations from the target language.
This specific feature is cleared for the final set of clone methods.
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.
</p>

<p>
Note that clearing a feature is not always the same as disabling it.
Clearing the feature above with <tt>%feature("except","") *::clone()</tt> is not the same as specifying
<tt>%feature("except","0") *::clone()</tt>. The former will disable the feature for clone methods -
the feature is still a better match than the global feature.
If on the other hand, no global exception handler had been defined at all,
then clearing the feature would be the same as disabling it as no other feature would have matched.
</p>

<p>
Note that the feature must match exactly for it to be cleared by any previously defined feature.
For example the following attempt to clear the initial feature will not work:
</p>

<div class="code">
<pre>
%feature("except") clone() { logger.info("$action"); $action }
%feature("except","") *::clone();
</pre>
</div>

<p>
but this will:
</p>

<div class="code">
<pre>
%feature("except") clone() { logger.info("$action"); $action }
%feature("except","") clone();
</pre>
</div>

<p>
SWIG provides macros for disabling and clearing features. Many of these can be found in the <tt>swig.swg</tt> library file.
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.
The three macros below show this for the "except" feature:
</p>

<div class="code">
<pre>
#define %exception      %feature("except")
#define %noexception    %feature("except","0")
#define %clearexception %feature("except","")
</pre>
</div>

<H3><a name="Customization_features_default_args">12.3.4 Features and default arguments</a></H3>


<p>
SWIG treats methods with default arguments as separate overloaded methods as detailed
in the <a href="SWIGPlus.html#SWIGPlus_default_args">default arguments</a> section.
Any <tt>%feature</tt> targeting a method with default arguments
will apply to all the extra overloaded methods that SWIG generates if the
default arguments are specified in the feature. If the default arguments are
not specified in the feature, then the feature will match that exact
wrapper method only and not the extra overloaded methods that SWIG generates.
For example:
</p>

<div class="code">
<pre>
%feature("except") hello(int i=0, double d=0.0) { ... }
void hello(int i=0, double d=0.0);
</pre>
</div>

<p>
will apply the feature to all three wrapper methods, that is:
</p>

<div class="code">
<pre>
void hello(int i, double d);
void hello(int i);
void hello();
</pre>
</div>

<p>
If the default arguments are not specified in the feature:
</p>

<div class="code">
<pre>
%feature("except") hello(int i, double d) { ... }
void hello(int i=0, double d=0.0);
</pre>
</div>

<p>
then the feature will only apply to this wrapper method:
</p>

<div class="code">
<pre>
void hello(int i, double d);
</pre>
</div>

<p>
and not these wrapper methods:
</p>

<div class="code">
<pre>
void hello(int i);
void hello();
</pre>
</div>

<p>
If <a href="SWIGPlus.html#SWIGPlus_default_args">compactdefaultargs</a> are being used, then the difference between
specifying or not specifying default arguments in a feature is not applicable as just one wrapper is generated.
</p>

<p>
<b>Compatibility note:</b> The different behaviour of features specified with or without default arguments was introduced
in SWIG-1.3.23 when the approach to wrapping methods with default arguments was changed.
</p>

<H3><a name="Customization_features_example">12.3.5 Feature example</a></H3>


<p>
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
declarations with additional information for use by specific target language modules.  Another example is
in the Python module. You might use <tt>%feature</tt> to rewrite proxy/shadow class code as follows:
</p>

<div class="code">
<pre>
%module example
%rename(bar_id) bar(int,double);

// Rewrite bar() to allow some nice overloading

%feature("shadow") Foo::bar(int) %{
def bar(*args):
    if len(args) == 3:
         return apply(examplec.Foo_bar_id,args)
    return apply(examplec.Foo_bar,args)
%}
    
class Foo {
public:
    int bar(int x);
    int bar(int x, double y);
}
</pre>
</div>

<p>
Further details of <tt>%feature</tt> usage is described in the documentation for specific language modules.
</p>

</body>
</html>