PageRenderTime 79ms CodeModel.GetById 13ms app.highlight 54ms RepoModel.GetById 2ms app.codeStats 0ms

/trunk/Doc/Manual/Library.html

#
HTML | 1939 lines | 1557 code | 380 blank | 2 comment | 0 complexity | aa02b5113c3320dc461dab9fc6c6d5f7 MD5 | raw file
   1<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
   2<html>
   3<head>
   4<title>SWIG Library</title>
   5<link rel="stylesheet" type="text/css" href="style.css">
   6</head>
   7
   8<body bgcolor="#ffffff">
   9<H1><a name="Library"></a>8 SWIG library</H1>
  10<!-- INDEX -->
  11<div class="sectiontoc">
  12<ul>
  13<li><a href="#Library_nn2">The %include directive and library search path</a>
  14<li><a href="#Library_nn3">C Arrays and Pointers</a>
  15<ul>
  16<li><a href="#Library_nn4">cpointer.i</a>
  17<li><a href="#Library_carrays">carrays.i</a>
  18<li><a href="#Library_nn6">cmalloc.i</a>
  19<li><a href="#Library_nn7">cdata.i</a>
  20</ul>
  21<li><a href="#Library_nn8">C String Handling</a>
  22<ul>
  23<li><a href="#Library_nn9">Default string handling</a>
  24<li><a href="#Library_nn10">Passing binary data</a>
  25<li><a href="#Library_nn11">Using %newobject to release memory</a>
  26<li><a href="#Library_nn12">cstring.i</a>
  27</ul>
  28<li><a href="#Library_stl_cpp_library">STL/C++ Library</a>
  29<ul>
  30<li><a href="#Library_std_string">std::string</a>
  31<li><a href="#Library_std_vector">std::vector</a>
  32<li><a href="#Library_stl_exceptions">STL exceptions</a>
  33<li><a href="#Library_std_shared_ptr">shared_ptr smart pointer</a>
  34</ul>
  35<li><a href="#Library_nn16">Utility Libraries</a>
  36<ul>
  37<li><a href="#Library_nn17">exception.i</a>
  38</ul>
  39</ul>
  40</div>
  41<!-- INDEX -->
  42
  43
  44
  45<p>
  46To help build extension modules, SWIG is packaged with a library of
  47support files that you can include in your own interfaces.  These
  48files often define new SWIG directives or provide utility
  49functions that can be used to access parts of the standard C and C++ libraries.
  50This chapter provides a reference to the current set of supported library files.
  51</p>
  52
  53<p>
  54<b>Compatibility note:</b> Older versions of SWIG included a number of
  55library files for manipulating pointers, arrays, and other structures.  Most
  56these files are now deprecated and have been removed from the distribution.
  57Alternative libraries provide similar functionality.  Please read this chapter
  58carefully if you used the old libraries.
  59</p>
  60
  61<H2><a name="Library_nn2"></a>8.1 The %include directive and library search path</H2>
  62
  63
  64<p>
  65Library files are included using the <tt>%include</tt> directive.
  66When searching for files, directories are searched in the following order:
  67</p>
  68
  69<ul>
  70<li>The current directory
  71<li>Directories specified with the <tt>-I</tt> command line option
  72<li>.<tt>/swig_lib</tt>
  73<li>SWIG library install location as reported by <tt>swig -swiglib</tt>, for example <tt>/usr/local/share/swig/1.3.30</tt>
  74<li>On Windows, a directory <tt>Lib</tt> relative to the location of <tt>swig.exe</tt> is also searched.
  75</ul>
  76
  77<p>
  78Within each directory, SWIG first looks for a subdirectory corresponding to a target language (e.g., <tt>python</tt>,
  79<tt>tcl</tt>, etc.).   If found, SWIG will search the language specific directory first.  This allows
  80for language-specific implementations of library files.
  81</p>
  82
  83<p>
  84You can ignore the installed SWIG library by setting the <tt>SWIG_LIB</tt> environment variable.
  85Set the environment variable to hold an alternative library directory.
  86</p>
  87
  88<p>
  89The directories that are searched are displayed when using <tt>-verbose</tt> commandline option.
  90</p>
  91
  92<H2><a name="Library_nn3"></a>8.2 C Arrays and Pointers</H2>
  93
  94
  95<p>
  96This section describes library modules for manipulating low-level C arrays and pointers.
  97The primary use of these modules is in supporting C declarations that manipulate bare
  98pointers such as <tt>int *</tt>, <tt>double *</tt>, or <tt>void *</tt>.  The modules can be
  99used to allocate memory, manufacture pointers, dereference memory, and wrap
 100pointers as class-like objects.   Since these functions provide direct access to
 101memory, their use is potentially unsafe and you should exercise caution.
 102</p>
 103
 104<H3><a name="Library_nn4"></a>8.2.1 cpointer.i</H3>
 105
 106
 107<p>
 108The <tt>cpointer.i</tt> module defines macros that can be used to used
 109to generate wrappers around simple C pointers.  The primary use of
 110this module is in generating pointers to primitive datatypes such as
 111<tt>int</tt> and <tt>double</tt>.
 112</p>
 113
 114<p>
 115<b><tt>%pointer_functions(type,name)</tt></b>
 116</p>
 117
 118<div class="indent">
 119<p>Generates a collection of four functions for manipulating a pointer <tt>type *</tt>:</p>
 120
 121<p>
 122<tt>type *new_name()</tt>
 123</p>
 124
 125<div class="indent"><p>
 126Creates a new object of type <tt>type</tt> and returns a pointer to it.  In C, the
 127object is created using <tt>calloc()</tt>. In C++, <tt>new</tt> is used.
 128</p></div>
 129
 130<p>
 131<tt>type *copy_name(type value)</tt>
 132</p>
 133
 134<div class="indent"><p>
 135Creates a new object of type <tt>type</tt> and returns a pointer to it.
 136An initial value is set by copying it from <tt>value</tt>. In C, the
 137object is created using <tt>calloc()</tt>. In C++, <tt>new</tt> is used.
 138</p></div>
 139
 140<p>
 141<tt>type *delete_name(type *obj)</tt>
 142</p>
 143
 144<div class="indent"><p>
 145Deletes an object type <tt>type</tt>.
 146</p></div>
 147
 148<p>
 149<tt>void name_assign(type *obj, type value)</tt>
 150</p>
 151
 152<div class="indent"><p>
 153Assigns <tt>*obj = value</tt>.
 154</p></div>
 155
 156<p>
 157<tt>type name_value(type *obj)</tt>
 158</p>
 159
 160<div class="indent"><p>
 161Returns the value of <tt>*obj</tt>.
 162</p></div>
 163
 164<p>
 165When using this macro, <tt>type</tt> may be any type and <tt>name</tt> must be a legal identifier in the target
 166language.  <tt>name</tt> should not correspond to any other name used in the interface file.
 167</p>
 168
 169
 170<p>
 171Here is a simple example of using <tt>%pointer_functions()</tt>:
 172</p>
 173
 174<div class="code">
 175<pre>
 176%module example
 177%include "cpointer.i"
 178
 179/* Create some functions for working with "int *" */
 180%pointer_functions(int, intp);
 181
 182/* A function that uses an "int *" */
 183void add(int x, int y, int *result);
 184</pre>
 185</div>
 186
 187<p>
 188Now, in Python:
 189</p>
 190
 191<div class="targetlang">
 192<pre>
 193&gt;&gt;&gt; import example
 194&gt;&gt;&gt; c = example.new_intp()     # Create an "int" for storing result
 195&gt;&gt;&gt; example.add(3,4,c)         # Call function
 196&gt;&gt;&gt; example.intp_value(c)      # Dereference
 1977
 198&gt;&gt;&gt; example.delete_intp(c)     # Delete
 199</pre>
 200</div>
 201
 202</div>
 203
 204<p>
 205<b><tt>%pointer_class(type,name)</tt></b>
 206</p>
 207
 208<div class="indent">
 209
 210<p>
 211Wraps a pointer of <tt>type *</tt> inside a class-based interface.  This
 212interface is as follows:
 213</p>
 214
 215<div class="code">
 216<pre>
 217struct name {
 218   name();                            // Create pointer object
 219  ~name();                            // Delete pointer object
 220   void assign(type value);           // Assign value
 221   type value();                      // Get value
 222   type *cast();                      // Cast the pointer to original type
 223   static name *frompointer(type *);  // Create class wrapper from existing
 224                                      // pointer
 225};
 226</pre>
 227</div>
 228
 229<p>
 230When using this macro, <tt>type</tt> is restricted to a simple type
 231name like <tt>int</tt>, <tt>float</tt>, or <tt>Foo</tt>.  Pointers and
 232other complicated types are not allowed.  <tt>name</tt> must be a
 233valid identifier not already in use.  When a pointer is wrapped as a class,
 234the "class"  may be transparently passed to any function that expects the pointer.
 235</p>
 236
 237<p>
 238If the target language does not support proxy classes, the use of this macro will produce the example
 239same functions as <tt>%pointer_functions()</tt> macro.
 240</p>
 241
 242
 243<p>
 244It should be noted that the class interface does introduce a new object or wrap a pointer inside a special
 245structure.  Instead, the raw pointer is used directly.
 246</p>
 247
 248
 249
 250<p>
 251Here is the same example using a class instead:
 252</p>
 253
 254<div class="code">
 255<pre>
 256%module example
 257%include "cpointer.i"
 258
 259/* Wrap a class interface around an "int *" */
 260%pointer_class(int, intp);
 261
 262/* A function that uses an "int *" */
 263void add(int x, int y, int *result);
 264</pre>
 265</div>
 266
 267<p>
 268Now, in Python (using proxy classes)
 269</p>
 270
 271<div class="targetlang">
 272<pre>
 273&gt;&gt;&gt; import example
 274&gt;&gt;&gt; c = example.intp()         # Create an "int" for storing result
 275&gt;&gt;&gt; example.add(3,4,c)         # Call function
 276&gt;&gt;&gt; c.value()                  # Dereference
 2777
 278</pre>
 279</div>
 280
 281<p>
 282Of the two macros, <tt>%pointer_class</tt> is probably the most convenient when working with simple
 283pointers.  This is because the pointers are access like objects and they can be easily garbage collected
 284(destruction of the pointer object destroys the underlying object).
 285</p>
 286
 287</div>
 288
 289<p>
 290<b><tt>%pointer_cast(type1, type2, name)</tt></b>
 291</p>
 292
 293<div class="indent">
 294
 295<p>
 296Creates a casting function that converts <tt>type1</tt> to <tt>type2</tt>.  The name of the function is <tt>name</tt>.
 297For example:
 298</p>
 299
 300<div class="code">
 301<pre>
 302%pointer_cast(int *, unsigned int *, int_to_uint);
 303</pre>
 304</div>
 305
 306<p>
 307In this example,  the function <tt>int_to_uint()</tt> would be used to cast types in the target language.
 308</p>
 309
 310</div>
 311
 312<p>
 313<b>Note:</b> None of these macros can be used to safely work with strings (<tt>char *</tt> or <tt>char **</tt>).
 314</p>
 315
 316<P>
 317<b>Note:</b> When working with simple pointers, typemaps can often be used to provide more seamless operation.
 318</p>
 319
 320<H3><a name="Library_carrays"></a>8.2.2 carrays.i</H3>
 321
 322
 323<p>
 324This module defines macros that assist in wrapping ordinary C pointers as arrays.
 325The module does not provide any safety or an extra layer of wrapping--it merely
 326provides functionality for creating, destroying, and modifying the contents of
 327raw C array data.
 328</p>
 329
 330<p>
 331<b><tt>%array_functions(type,name)</tt></b>
 332</p>
 333
 334<div class="indent">
 335<p>Creates four functions.</p>
 336
 337<p>
 338<tt>type *new_name(int nelements)</tt>
 339</p>
 340
 341<div class="indent"><p>
 342Creates a new array of objects of type <tt>type</tt>.   In C, the array is allocated using
 343<tt>calloc()</tt>.  In C++, <tt>new []</tt> is used.
 344</p></div>
 345
 346<p>
 347<tt>type *delete_name(type *ary)</tt>
 348</p>
 349
 350<div class="indent"><p>
 351Deletes an array. In C, <tt>free()</tt> is used.  In C++, <tt>delete []</tt> is used.
 352</p></div>
 353
 354<p>
 355<tt>type name_getitem(type *ary, int index)</tt>
 356</p>
 357
 358<div class="indent"><p>
 359Returns the value <tt>ary[index]</tt>.
 360</p></div>
 361
 362<p>
 363<tt>void name_setitem(type *ary, int index, type value)</tt>
 364</p>
 365
 366<div class="indent"><p>
 367Assigns <tt>ary[index] = value</tt>.
 368</p></div>
 369
 370<p>
 371When using this macro, <tt>type</tt> may be any type and <tt>name</tt>
 372must be a legal identifier in the target language.  <tt>name</tt>
 373should not correspond to any other name used in the interface file.
 374</p>
 375
 376<p>
 377Here is an example of <tt>%array_functions()</tt>.  Suppose you had a
 378function like this:
 379</p>
 380
 381<div class="code">
 382<pre>
 383void print_array(double x[10]) {
 384   int i;
 385   for (i = 0; i &lt; 10; i++) {
 386      printf("[%d] = %g\n", i, x[i]);
 387   }
 388}
 389</pre>
 390</div>
 391
 392<p>
 393To wrap it, you might write this:
 394</p>
 395
 396<div class="code">
 397<pre>
 398%module example
 399
 400%include "carrays.i"
 401%array_functions(double, doubleArray);
 402
 403void print_array(double x[10]);
 404</pre>
 405</div>
 406
 407<p>
 408Now, in a scripting language, you might write this:
 409</p>
 410
 411<div class="code">
 412<pre>
 413a = new_doubleArray(10)           # Create an array
 414for i in range(0,10):
 415    doubleArray_setitem(a,i,2*i)  # Set a value
 416print_array(a)                    # Pass to C
 417delete_doubleArray(a)             # Destroy array
 418</pre>
 419</div>
 420
 421</div>
 422
 423<p>
 424<b><tt>%array_class(type,name)</tt></b>
 425</p>
 426<div class="indent">
 427
 428<p>
 429Wraps a pointer of <tt>type *</tt> inside a class-based interface.  This
 430interface is as follows:
 431</p>
 432
 433<div class="code">
 434<pre>
 435struct name {
 436   name(int nelements);                  // Create an array
 437  ~name();                               // Delete array
 438   type getitem(int index);              // Return item
 439   void setitem(int index, type value);  // Set item
 440   type *cast();                         // Cast to original type
 441   static name *frompointer(type *);     // Create class wrapper from
 442                                         // existing pointer
 443};
 444</pre>
 445</div>
 446
 447<p>
 448When using this macro, <tt>type</tt> is restricted to a simple type
 449name like <tt>int</tt> or <tt>float</tt>. Pointers and
 450other complicated types are not allowed.  <tt>name</tt> must be a
 451valid identifier not already in use.  When a pointer is wrapped as a class,
 452it can be transparently passed to any function that expects the pointer.
 453</p>
 454
 455
 456<p>
 457When combined with proxy classes, the <tt>%array_class()</tt> macro can be especially useful.
 458For example:
 459</p>
 460
 461<div class="code">
 462<pre>
 463%module example
 464%include "carrays.i"
 465%array_class(double, doubleArray);
 466
 467void print_array(double x[10]);
 468</pre>
 469</div>
 470
 471<p>
 472Allows you to do this:
 473</p>
 474
 475<div class="code">
 476<pre>
 477import example
 478c = example.doubleArray(10)  # Create double[10]
 479for i in range(0,10):
 480    c[i] = 2*i               # Assign values
 481example.print_array(c)       # Pass to C
 482</pre>
 483</div>
 484
 485</div>
 486
 487<p>
 488<b>Note:</b> These macros do not encapsulate C arrays inside a special data structure
 489or proxy. There is no bounds checking or safety of any kind.   If you want this,
 490you should consider using a special array object rather than a bare pointer.
 491</p>
 492
 493<p>
 494<b>Note:</b> <tt>%array_functions()</tt> and <tt>%array_class()</tt> should not be
 495used with types of <tt>char</tt> or <tt>char *</tt>.
 496</p>
 497
 498<H3><a name="Library_nn6"></a>8.2.3 cmalloc.i</H3>
 499
 500
 501<p>
 502This module defines macros for wrapping the low-level C memory allocation functions
 503<tt>malloc()</tt>, <tt>calloc()</tt>, <tt>realloc()</tt>, and <tt>free()</tt>.
 504</p>
 505
 506<p>
 507<b><tt>%malloc(type [,name=type])</tt></b>
 508</p>
 509
 510<div class="indent">
 511
 512<p>
 513Creates a wrapper around <tt>malloc()</tt> with the following prototype:
 514</p>
 515
 516<div class="code"><pre>
 517<em>type</em> *malloc_<em>name</em>(int nbytes = sizeof(<em>type</em>));
 518</pre>
 519</div>
 520
 521<p>
 522If <tt>type</tt> is <tt>void</tt>, then the size parameter <tt>nbytes</tt> is required.
 523The <tt>name</tt> parameter only needs to be specified when wrapping a type that
 524is not a valid identifier (e.g., "<tt>int *</tt>", "<tt>double **</tt>", etc.).
 525</p>
 526
 527</div>
 528
 529<p>
 530<b><tt>%calloc(type [,name=type])</tt></b>
 531</p>
 532
 533<div class="indent">
 534
 535<p>
 536Creates a wrapper around <tt>calloc()</tt> with the following prototype:
 537</p>
 538
 539<div class="code"><pre>
 540<em>type</em> *calloc_<em>name</em>(int nobj =1, int sz = sizeof(<em>type</em>));
 541</pre>
 542</div>
 543
 544<p>
 545If <tt>type</tt> is <tt>void</tt>, then the size parameter <tt>sz</tt> is required.
 546</p>
 547
 548</div>
 549
 550<p>
 551<b><tt>%realloc(type [,name=type])</tt></b>
 552</p>
 553
 554<div class="indent">
 555
 556<p>
 557Creates a wrapper around <tt>realloc()</tt> with the following prototype:
 558</p>
 559
 560<div class="code"><pre>
 561<em>type</em> *realloc_<em>name</em>(<em>type</em> *ptr, int nitems);
 562</pre>
 563</div>
 564
 565<p>
 566Note: unlike the C <tt>realloc()</tt>, the wrapper generated by this macro implicitly includes the
 567size of the corresponding type.   For example, <tt>realloc_int(p, 100)</tt> reallocates <tt>p</tt> so that
 568it holds 100 integers.
 569</p>
 570
 571</div>
 572
 573<p>
 574<b><tt>%free(type [,name=type])</tt></b>
 575</p>
 576
 577<div class="indent">
 578
 579<p>
 580Creates a wrapper around <tt>free()</tt> with the following prototype:
 581</p>
 582
 583<div class="code"><pre>
 584void free_<em>name</em>(<em>type</em> *ptr);
 585</pre>
 586</div>
 587</div>
 588
 589<p>
 590<b><tt>%sizeof(type [,name=type])</tt></b>
 591</p>
 592
 593<div class="indent">
 594
 595<p>
 596Creates the constant:
 597</p>
 598
 599<div class="code"><pre>
 600%constant int sizeof_<em>name</em> = sizeof(<em>type</em>);
 601</pre>
 602</div>
 603</div>
 604
 605<p>
 606<b><tt>%allocators(type [,name=type])</tt></b>
 607</p>
 608
 609<div class="indent"><p>
 610Generates wrappers for all five of the above operations.
 611</p></div>
 612
 613<p>
 614Here is a simple example that illustrates the use of these macros:
 615</p>
 616
 617<div class="code">
 618<pre>
 619// SWIG interface
 620%module example
 621%include "cmalloc.i"
 622
 623%malloc(int);
 624%free(int);
 625
 626%malloc(int *, intp);
 627%free(int *, intp);
 628
 629%allocators(double);
 630</pre>
 631</div>
 632
 633<p>
 634Now, in a script:
 635</p>
 636
 637<div class="targetlang">
 638<pre>
 639&gt;&gt;&gt; from example import *
 640&gt;&gt;&gt; a = malloc_int()
 641&gt;&gt;&gt; a
 642'_000efa70_p_int'
 643&gt;&gt;&gt; free_int(a)
 644&gt;&gt;&gt; b = malloc_intp()
 645&gt;&gt;&gt; b
 646'_000efb20_p_p_int'
 647&gt;&gt;&gt; free_intp(b)
 648&gt;&gt;&gt; c = calloc_double(50)
 649&gt;&gt;&gt; c
 650'_000fab98_p_double'
 651&gt;&gt;&gt; c = realloc_double(100000)
 652&gt;&gt;&gt; free_double(c)
 653&gt;&gt;&gt; print sizeof_double
 6548
 655&gt;&gt;&gt;
 656</pre>
 657</div>
 658
 659<H3><a name="Library_nn7"></a>8.2.4 cdata.i</H3>
 660
 661
 662<p>
 663The <tt>cdata.i</tt> module defines functions for converting raw C data to and from strings
 664in the target language.  The primary applications of this module would be packing/unpacking of
 665binary data structures---for instance, if you needed to extract data from a buffer.
 666The target language must support strings with embedded binary data
 667in order for this to work.
 668</p>
 669
 670<p>
 671<b><tt>const char *cdata(void *ptr, size_t nbytes)</tt></b>
 672</p>
 673
 674<div class="indent"><p>
 675Converts <tt>nbytes</tt> of data at <tt>ptr</tt> into a string.   <tt>ptr</tt> can be any
 676pointer.
 677</p></div>
 678
 679<p>
 680<b><tt>void memmove(void *ptr, const char *s)</tt></b>
 681</p>
 682
 683<div class="indent"><p>
 684Copies all of the string data in <tt>s</tt> into the memory pointed to by
 685<tt>ptr</tt>.  The string may contain embedded NULL bytes.  
 686This is actually a wrapper to the standard C library <tt>memmove</tt> function, which is
 687declared as 
 688<b><tt>void memmove(void *ptr, const void *src, size_t n)</tt></b>.
 689The <tt>src</tt> and length <tt>n</tt> parameters are
 690extracted from the language specific string <tt>s</tt> in the underlying wrapper code.
 691</p></div>
 692
 693<p>
 694One use of these functions is packing and unpacking data from memory.
 695Here is a short example:
 696</p>
 697
 698<div class="code">
 699<pre>
 700// SWIG interface
 701%module example
 702%include "carrays.i"
 703%include "cdata.i"
 704
 705%array_class(int, intArray);
 706</pre>
 707</div>
 708
 709<p>
 710Python example:
 711</p>
 712
 713<div class="targetlang">
 714<pre>
 715&gt;&gt;&gt; a = intArray(10)
 716&gt;&gt;&gt; for i in range(0,10):
 717...    a[i] = i
 718&gt;&gt;&gt; b = cdata(a,40)
 719&gt;&gt;&gt; b
 720'\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04
 721\x00\x00\x00\x05\x00\x00\x00\x06\x00\x00\x00\x07\x00\x00\x00\x08\x00\x00\x00\t'
 722&gt;&gt;&gt; c = intArray(10)
 723&gt;&gt;&gt; memmove(c,b)
 724&gt;&gt;&gt; print c[4]
 7254
 726&gt;&gt;&gt;
 727</pre>
 728</div>
 729
 730<p>
 731Since the size of data is not always known, the following macro is also defined:
 732</p>
 733
 734<p>
 735<b><tt>%cdata(type [,name=type])</tt></b>
 736</p>
 737
 738<div class="indent">
 739
 740<p>
 741Generates the following function for extracting C data for a given type.
 742</p>
 743
 744<div class="code">
 745<pre>
 746char *cdata_<em>name</em>(type* ptr, int nitems)
 747</pre>
 748</div>
 749
 750<p>
 751<tt>nitems</tt> is the number of items of the given type to extract.
 752</p>
 753
 754</div>
 755
 756<p>
 757<b>Note:</b> These functions provide direct access to memory and can be used to overwrite data.
 758Clearly they are unsafe.
 759</p>
 760
 761<H2><a name="Library_nn8"></a>8.3 C String Handling</H2>
 762
 763
 764<p>
 765A common problem when working with C programs is dealing with
 766functions that manipulate raw character data using <tt>char *</tt>.
 767In part, problems arise because there are different interpretations of
 768<tt>char *</tt>---it could be a NULL-terminated string or it could
 769point to binary data.  Moreover, functions that manipulate raw strings
 770may mutate data, perform implicit memory allocations, or utilize
 771fixed-sized buffers.
 772</p>
 773
 774<p>
 775The problems (and perils) of using <tt>char *</tt> are
 776well-known. However, SWIG is not in the business of enforcing
 777morality.  The modules in this section provide basic functionality
 778for manipulating raw C strings.
 779</p>
 780
 781<H3><a name="Library_nn9"></a>8.3.1 Default string handling</H3>
 782
 783
 784<p>
 785Suppose you have a C function with this prototype:
 786</p>
 787
 788<div class="code">
 789<pre>
 790char *foo(char *s);
 791</pre>
 792</div>
 793
 794<p>
 795The default wrapping behavior for this function is to set <tt>s</tt>
 796to a raw <tt>char *</tt> that refers to the internal string data in the
 797target language.  In other words, if you were using a language like Tcl,
 798and you wrote this,
 799</p>
 800
 801<div class="code">
 802<pre>
 803% foo Hello
 804</pre>
 805</div>
 806
 807<p>
 808then <tt>s</tt> would point to the representation of "Hello" inside
 809the Tcl interpreter.  When returning a <tt>char *</tt>, SWIG assumes
 810that it is a NULL-terminated string and makes a copy of it.  This
 811gives the target language its own copy of the result.
 812</p>
 813
 814<p>
 815There are obvious problems with the default behavior.  First, since
 816a <tt>char *</tt> argument points to data inside the target language, it is
 817<b>NOT</b> safe for a function to modify this data (doing so may corrupt the
 818interpreter and lead to a crash).  Furthermore, the default behavior does
 819not work well with binary data. Instead, strings are assumed to be NULL-terminated.
 820</p>
 821
 822<H3><a name="Library_nn10"></a>8.3.2 Passing binary data</H3>
 823
 824
 825<p>
 826If you have a function that expects binary data,
 827</p>
 828
 829<div class="code">
 830<pre>
 831size_t parity(char *str, size_t len, size_t initial);
 832</pre>
 833</div>
 834
 835<p>
 836you can wrap the parameters <tt>(char *str, size_t len)</tt> as a single
 837argument using a typemap.   Just do this:
 838</p>
 839
 840<div class="code">
 841<pre>
 842%apply (char *STRING, size_t LENGTH) { (char *str, size_t len) };
 843...
 844size_t parity(char *str, size_t len, size_t initial);
 845</pre>
 846</div>
 847
 848<p>
 849Now, in the target language, you can use binary string data like this:
 850</p>
 851
 852<div class="code">
 853<pre>
 854&gt;&gt;&gt; s = "H\x00\x15eg\x09\x20"
 855&gt;&gt;&gt; parity(s,0)
 856</pre>
 857</div>
 858
 859<p>
 860In the wrapper function, the passed string will be expanded to a pointer and length parameter.
 861The <tt>(char *STRING, int LENGTH)</tt> multi-argument typemap is also available in addition to <tt>(char *STRING, size_t LENGTH)</tt>.
 862</p>
 863
 864<H3><a name="Library_nn11"></a>8.3.3 Using %newobject to release memory</H3>
 865
 866
 867<p>
 868If you have a function that allocates memory like this,
 869</p>
 870
 871<div class="code">
 872<pre>
 873char *foo() {
 874   char *result = (char *) malloc(...);
 875   ...
 876   return result;
 877}
 878</pre>
 879</div>
 880
 881<p>
 882then the SWIG generated wrappers will have a memory leak--the returned data will be copied
 883into a string object and the old contents ignored.
 884</p>
 885
 886<p>
 887To fix the memory leak, use the <tt>%newobject</tt> directive.
 888</p>
 889
 890<div class="code">
 891<pre>
 892%newobject foo;
 893...
 894char *foo();
 895</pre>
 896</div>
 897
 898<p>
 899This will release the result if the appropriate target language support is available.
 900SWIG provides the appropriate "newfree" typemap for <tt>char *</tt> so that the memory is released,
 901however, you may need to provide your own "newfree" typemap for other types.
 902See <a href="Customization.html#Customization_ownership">Object ownership and %newobject</a> for more details.
 903</p>
 904
 905<H3><a name="Library_nn12"></a>8.3.4 cstring.i</H3>
 906
 907
 908<p>
 909The <tt>cstring.i</tt> library file provides a collection of macros
 910for dealing with functions that either mutate string arguments or
 911which try to output string data through their arguments.  An
 912example of such a function might be this rather questionable
 913implementation:
 914</p>
 915
 916<div class="code">
 917<pre>
 918void get_path(char *s) {
 919    // Potential buffer overflow---uh, oh.
 920    sprintf(s,"%s/%s", base_directory, sub_directory);
 921}
 922...
 923// Somewhere else in the C program
 924{
 925    char path[1024];
 926    ...
 927    get_path(path);
 928    ...
 929}
 930</pre>
 931</div>
 932
 933<p>
 934(Off topic rant: If your program really has functions like this, you
 935would be well-advised to replace them with safer alternatives
 936involving bounds checking).
 937</p>
 938
 939<p>
 940The macros defined in this module all expand to various combinations of
 941typemaps.  Therefore, the same pattern matching rules and ideas apply.
 942</p>
 943
 944<p>
 945<b>%cstring_bounded_output(parm, maxsize)</b>
 946</p>
 947
 948<div class="indent">
 949
 950<p>
 951Turns parameter <tt><em>parm</em></tt> into an output value.  The
 952output string is assumed to be NULL-terminated and smaller than
 953<tt><em>maxsize</em></tt> characters.  Here is an example:
 954</p>
 955
 956<div class="code">
 957<pre>
 958%cstring_bounded_output(char *path, 1024);
 959...
 960void get_path(char *path);
 961</pre>
 962</div>
 963
 964<p>
 965In the target language:
 966</p>
 967
 968<div class="targetlang">
 969<pre>
 970&gt;&gt;&gt; get_path()
 971/home/beazley/packages/Foo/Bar
 972&gt;&gt;&gt;
 973</pre>
 974</div>
 975
 976<p>
 977Internally, the wrapper function allocates a small buffer (on the stack) of the
 978requested size and passes it as the pointer value.  Data stored in the buffer is then
 979returned as a function return value.
 980If the function already returns a value, then the return value and the output string
 981are returned together (multiple return values).  <b>If more than <tt><em>maxsize</em></tt>
 982bytes are written, your program will crash with a buffer overflow!</b>
 983</p>
 984
 985</div>
 986
 987<p>
 988<b>%cstring_chunk_output(parm, chunksize)</b>
 989</p>
 990
 991<div class="indent">
 992
 993<p>
 994Turns parameter <tt><em>parm</em></tt> into an output value.  The
 995output string is always <tt><em>chunksize</em></tt> and may contain
 996binary data.  Here is an example:
 997</p>
 998
 999<div class="code">
1000<pre>
1001%cstring_chunk_output(char *packet, PACKETSIZE);
1002...
1003void get_packet(char *packet);
1004</pre>
1005</div>
1006
1007<p>
1008In the target language:
1009</p>
1010
1011<div class="targetlang">
1012<pre>
1013&gt;&gt;&gt; get_packet()
1014'\xa9Y:\xf6\xd7\xe1\x87\xdbH;y\x97\x7f\xd3\x99\x14V\xec\x06\xea\xa2\x88'
1015&gt;&gt;&gt;
1016</pre>
1017</div>
1018
1019<p>
1020This macro is essentially identical to <tt>%cstring_bounded_output</tt>.  The
1021only difference is that the result is always <tt><em>chunksize</em></tt> characters.
1022Furthermore, the result can contain binary data.
1023<b>If more than <tt><em>maxsize</em></tt>
1024bytes are written, your program will crash with a buffer overflow!</b>
1025</p>
1026
1027</div>
1028
1029<p>
1030<b>%cstring_bounded_mutable(parm, maxsize)</b>
1031</p>
1032
1033<div class="indent">
1034
1035<p>
1036Turns parameter <tt><em>parm</em></tt> into a mutable string argument.
1037The input string is assumed to be NULL-terminated and smaller than
1038<tt><em>maxsize</em></tt> characters. The output string is also assumed
1039to be NULL-terminated and less than <tt><em>maxsize</em></tt> characters.
1040</p>
1041
1042<div class="code">
1043<pre>
1044%cstring_bounded_mutable(char *ustr, 1024);
1045...
1046void make_upper(char *ustr);
1047</pre>
1048</div>
1049
1050<p>
1051In the target language:
1052</p>
1053
1054<div class="targetlang">
1055<pre>
1056&gt;&gt;&gt; make_upper("hello world")
1057'HELLO WORLD'
1058&gt;&gt;&gt;
1059</pre>
1060</div>
1061
1062<p>
1063Internally, this macro is almost exactly the same as
1064<tt>%cstring_bounded_output</tt>.  The only difference is that the
1065parameter accepts an input value that is used to initialize the
1066internal buffer. It is important to emphasize that this function
1067does not mutate the string value passed---instead it makes a copy of the
1068input value, mutates it, and returns it as a result.
1069<b>If more than <tt><em>maxsize</em></tt> bytes are
1070written, your program will crash with a buffer overflow!</b>
1071</p>
1072
1073</div>
1074
1075<p>
1076<b>%cstring_mutable(parm [, expansion])</b>
1077</p>
1078
1079<div class="indent">
1080
1081<p>
1082Turns parameter <tt><em>parm</em></tt> into a mutable string argument.
1083The input string is assumed to be NULL-terminated.  An optional
1084parameter <tt><em>expansion</em></tt> specifies the number of
1085extra characters by which the string might grow when it is modified.
1086The output string is assumed to be NULL-terminated and less than
1087the size of the input string plus any expansion characters.
1088</p>
1089
1090<div class="code">
1091<pre>
1092%cstring_mutable(char *ustr);
1093...
1094void make_upper(char *ustr);
1095
1096%cstring_mutable(char *hstr, HEADER_SIZE);
1097...
1098void attach_header(char *hstr);
1099</pre>
1100</div>
1101
1102<p>
1103In the target language:
1104</p>
1105
1106<div class="targetlang">
1107<pre>
1108&gt;&gt;&gt; make_upper("hello world")
1109'HELLO WORLD'
1110&gt;&gt;&gt; attach_header("Hello world")
1111'header: Hello world'
1112&gt;&gt;&gt;
1113</pre>
1114</div>
1115
1116<p>
1117This macro differs from <tt>%cstring_bounded_mutable()</tt> in that a
1118buffer is dynamically allocated (on the heap using
1119<tt>malloc/new</tt>).  This buffer is always large enough to store a
1120copy of the input value plus any expansion bytes that might have been
1121requested.
1122It is important to emphasize that this function
1123does not directly mutate the string value passed---instead it makes a copy of the
1124input value, mutates it, and returns it as a result.
1125<b>If the function expands the result by more than <tt><em>expansion</em></tt> extra
1126bytes, then the program will crash with a buffer overflow!</b>
1127</p>
1128
1129</div>
1130
1131
1132<p>
1133<b>%cstring_output_maxsize(parm, maxparm)</b>
1134</p>
1135
1136<div class="indent">
1137
1138<p>
1139This macro is used to handle bounded character output functions where
1140both a <tt>char *</tt> and a maximum length parameter are provided.
1141As input, a user simply supplies the maximum length.
1142The return value is assumed to be a NULL-terminated string.
1143</p>
1144
1145<div class="code">
1146<pre>
1147%cstring_output_maxsize(char *path, int maxpath);
1148...
1149void get_path(char *path, int maxpath);
1150</pre>
1151</div>
1152
1153<p>
1154In the target language:
1155</p>
1156
1157<div class="targetlang">
1158<pre>
1159&gt;&gt;&gt; get_path(1024)
1160'/home/beazley/Packages/Foo/Bar'
1161&gt;&gt;&gt;
1162</pre>
1163</div>
1164
1165<p>
1166This macro provides a safer alternative for functions that need to
1167write string data into a buffer.  User supplied buffer size is
1168used to dynamically allocate memory on heap.  Results are placed
1169into that buffer and returned as a string object.
1170</p>
1171
1172</div>
1173
1174
1175
1176<p>
1177<b>%cstring_output_withsize(parm, maxparm)</b>
1178</p>
1179
1180<div class="indent">
1181
1182<p>
1183This macro is used to handle bounded character output functions where
1184both a <tt>char *</tt> and a pointer <tt>int *</tt> are passed.  Initially,
1185the <tt>int *</tt> parameter points to a value containing the maximum size.
1186On return, this value is assumed to contain the actual number of bytes.
1187As input, a user simply supplies the maximum length.  The output value is a
1188string that may contain binary data.
1189</p>
1190
1191<div class="code">
1192<pre>
1193%cstring_output_withsize(char *data, int *maxdata);
1194...
1195void get_data(char *data, int *maxdata);
1196</pre>
1197</div>
1198
1199<p>
1200In the target language:
1201</p>
1202
1203<div class="targetlang">
1204<pre>
1205&gt;&gt;&gt; get_data(1024)
1206'x627388912'
1207&gt;&gt;&gt; get_data(1024)
1208'xyzzy'
1209&gt;&gt;&gt;
1210</pre>
1211</div>
1212
1213<p>
1214This macro is a somewhat more powerful version of <tt>%cstring_output_chunk()</tt>.  Memory
1215is dynamically allocated and can be arbitrary large.  Furthermore, a function can control
1216how much data is actually returned by changing the value of the <tt>maxparm</tt> argument.
1217</p>
1218
1219</div>
1220
1221
1222<p>
1223<b>%cstring_output_allocate(parm, release)</b>
1224</p>
1225
1226<div class="indent">
1227
1228<p>
1229This macro is used to return strings that are allocated within the program and
1230returned in a parameter of type <tt>char **</tt>.  For example:
1231</p>
1232
1233<div class="code">
1234<pre>
1235void foo(char **s) {
1236    *s = (char *) malloc(64);
1237    sprintf(*s, "Hello world\n");
1238}
1239</pre>
1240</div>
1241
1242<p>
1243The returned string is assumed to be NULL-terminated.  <tt><em>release</em></tt>
1244specifies how the allocated memory is to be released (if applicable).  Here is an
1245example:
1246</p>
1247
1248<div class="code">
1249<pre>
1250%cstring_output_allocate(char **s, free(*$1));
1251...
1252void foo(char **s);
1253</pre>
1254</div>
1255
1256<p>
1257In the target language:
1258</p>
1259
1260<div class="targetlang">
1261<pre>
1262&gt;&gt;&gt; foo()
1263'Hello world\n'
1264&gt;&gt;&gt;
1265</pre>
1266</div>
1267</div>
1268
1269
1270<p>
1271<b>%cstring_output_allocate_size(parm, szparm, release)</b>
1272</p>
1273
1274<div class="indent">
1275
1276<p>
1277This macro is used to return strings that are allocated within the program and
1278returned in two parameters of type <tt>char **</tt> and <tt>int *</tt>.  For example:
1279</p>
1280
1281<div class="code">
1282<pre>
1283void foo(char **s, int *sz) {
1284    *s = (char *) malloc(64);
1285    *sz = 64;
1286    // Write some binary data
1287    ...
1288}
1289</pre>
1290</div>
1291
1292<p>
1293The returned string may contain binary data. <tt><em>release</em></tt>
1294specifies how the allocated memory is to be released (if applicable).  Here is an
1295example:
1296</p>
1297
1298<div class="code">
1299<pre>
1300%cstring_output_allocate_size(char **s, int *slen, free(*$1));
1301...
1302void foo(char **s, int *slen);
1303</pre>
1304</div>
1305
1306<p>
1307In the target language:
1308</p>
1309
1310<div class="targetlang">
1311<pre>
1312&gt;&gt;&gt; foo()
1313'\xa9Y:\xf6\xd7\xe1\x87\xdbH;y\x97\x7f\xd3\x99\x14V\xec\x06\xea\xa2\x88'
1314&gt;&gt;&gt;
1315</pre>
1316</div>
1317
1318<p>
1319This is the safest and most reliable way to return binary string data in
1320SWIG.  If you have functions that conform to another prototype, you might
1321consider wrapping them with a helper function.   For example, if you had this:
1322</p>
1323
1324<div class="code">
1325<pre>
1326char  *get_data(int *len);
1327</pre>
1328</div>
1329
1330<p>
1331You could wrap it with a function like this:
1332</p>
1333
1334<div class="code">
1335<pre>
1336void my_get_data(char **result, int *len) {
1337   *result = get_data(len);
1338}
1339</pre>
1340</div>
1341</div>
1342
1343<p>
1344<b>Comments:</b>
1345</p>
1346
1347<ul>
1348<li>Support for the <tt>cstring.i</tt> module depends on the target language. Not all
1349SWIG modules currently support this library.
1350</li>
1351
1352<li>Reliable handling of raw C strings is a delicate topic.  There are many ways
1353to accomplish this in SWIG.  This library provides support for a few common techniques.
1354</li>
1355
1356<li>If used in C++, this library uses <tt>new</tt> and <tt>delete []</tt> for memory
1357allocation.  If using ANSI C, the library uses <tt>malloc()</tt> and <tt>free()</tt>.
1358</li>
1359
1360<li>Rather than manipulating <tt>char *</tt> directly, you might consider using a special string
1361structure or class instead.
1362</li>
1363</ul>
1364
1365<H2><a name="Library_stl_cpp_library"></a>8.4 STL/C++ Library</H2>
1366
1367
1368<p>
1369The library modules in this section provide access to parts of the standard C++ library including the STL.
1370SWIG support for the STL is an ongoing effort. Support is quite comprehensive for some language modules
1371but some of the lesser used modules do not have quite as much library code written.
1372</p>
1373
1374<p>
1375The following table shows which C++ classes are supported and the equivalent SWIG interface library file for the C++ library.
1376</p>
1377
1378<table BORDER summary="SWIG C++ library files">
1379<tr VALIGN=TOP>
1380<td><b>C++ class</b></td>
1381<td><b>C++ Library file</b></td>
1382<td><b>SWIG Interface library file</b></td>
1383</tr>
1384
1385<tr> <td>std::deque</td>           <td>deque</td>             <td>std_deque.i</td> </tr>
1386<tr> <td>std::list</td>           <td>list</td>             <td>std_list.i</td> </tr>
1387<tr> <td>std::map</td>           <td>map</td>             <td>std_map.i</td> </tr>
1388<tr> <td>std::pair</td>           <td>utility</td>             <td>std_pair.i</td> </tr>
1389<tr> <td>std::set</td>           <td>set</td>             <td>std_set.i</td> </tr>
1390<tr> <td>std::string</td>           <td>string</td>             <td>std_string.i</td> </tr>
1391<tr> <td>std::vector</td>           <td>vector</td>             <td>std_vector.i</td> </tr>
1392<tr> <td>std::shared_ptr</td>           <td>shared_ptr</td>             <td>std_shared_ptr.i</td> </tr>
1393
1394</table>
1395
1396<p>
1397The list is by no means complete; some language modules support a subset of the above and some support additional STL classes.
1398Please look for the library files in the appropriate language library directory.
1399</p>
1400
1401
1402<H3><a name="Library_std_string"></a>8.4.1 std::string</H3>
1403
1404
1405<p>
1406The <tt>std_string.i</tt> library provides typemaps for converting C++ <tt>std::string</tt>
1407objects to and from strings in the target scripting language.  For example:
1408</p>
1409
1410<div class="code">
1411<pre>
1412%module example
1413%include "std_string.i"
1414
1415std::string foo();
1416void        bar(const std::string &amp;x);
1417</pre>
1418</div>
1419
1420<p>
1421In the target language:
1422</p>
1423
1424<div class="targetlang">
1425<pre>
1426x = foo();                # Returns a string object
1427bar("Hello World");       # Pass string as std::string
1428</pre>
1429</div>
1430
1431<p>
1432A common problem that people encounter is that of classes/structures
1433containing a <tt>std::string</tt>. This can be overcome by defining a typemap.
1434For example:
1435</p>
1436
1437<div class="code">
1438<pre>
1439%module example
1440%include "std_string.i"
1441
1442%apply const std::string&amp; {std::string* foo};
1443
1444struct my_struct
1445{
1446  std::string foo;
1447};
1448</pre>
1449</div>
1450
1451<p>
1452In the target language:
1453</p>
1454
1455<div class="targetlang">
1456<pre>
1457x = my_struct();
1458x.foo="Hello World";      # assign with string
1459print x.foo;              # print as string
1460</pre>
1461</div>
1462
1463<p>
1464This module only supports types <tt>std::string</tt> and
1465<tt>const std::string &amp;</tt>.    Pointers and non-const references
1466are left unmodified and returned as SWIG pointers.
1467</p>
1468
1469<p>
1470This library file is fully aware of C++ namespaces.  If you export <tt>std::string</tt> or rename
1471it with a typedef, make sure you include those declarations in your interface.  For example:
1472</p>
1473
1474<div class="code">
1475<pre>
1476%module example
1477%include "std_string.i"
1478
1479using namespace std;
1480typedef std::string String;
1481...
1482void foo(string s, const String &amp;t);     // std_string typemaps still applied
1483</pre>
1484</div>
1485
1486<H3><a name="Library_std_vector"></a>8.4.2 std::vector</H3>
1487
1488
1489<p>
1490The <tt>std_vector.i</tt> library provides support for the C++ <tt>std::vector</tt> class in the STL.
1491Using this library involves the use of the <tt>%template</tt> directive.  All you need to do is to
1492instantiate different versions of <tt>vector</tt> for the types that you want to use.  For example:
1493</p>
1494
1495<div class="code">
1496<pre>
1497%module example
1498%include "std_vector.i"
1499
1500namespace std {
1501   %template(vectori) vector&lt;int&gt;;
1502   %template(vectord) vector&lt;double&gt;;
1503};
1504</pre>
1505</div>
1506
1507<p>
1508When a template <tt>vector&lt;X&gt;</tt> is instantiated a number of things happen:
1509</p>
1510
1511<ul>
1512<li>A class that exposes the C++ API is created in the target language .
1513This can be used to create objects, invoke methods, etc.  This class is
1514currently a subset of the real STL vector class.
1515</li>
1516
1517<li>Input typemaps are defined for <tt>vector&lt;X&gt;</tt>, <tt>const vector&lt;X&gt; &amp;</tt>, and
1518<tt>const vector&lt;X&gt; *</tt>.  For each of these, a pointer <tt>vector&lt;X&gt; *</tt> may be passed or
1519a native list object in the target language.
1520</li>
1521
1522<li>An output typemap is defined for <tt>vector&lt;X&gt;</tt>.  In this case, the values in the
1523vector are expanded into a list object in the target language.
1524</li>
1525
1526<li>For all other variations of the type, the wrappers expect to receive a <tt>vector&lt;X&gt; *</tt>
1527object in the usual manner.
1528</li>
1529
1530<li>An exception handler for <tt>std::out_of_range</tt> is defined.
1531</li>
1532
1533<li>Optionally, special methods for indexing, item retrieval, slicing, and element assignment
1534may be defined.  This depends on the target language.
1535</li>
1536</ul>
1537
1538<p>
1539To illustrate the use of this library, consider the following functions:
1540</p>
1541
1542<div class="code">
1543<pre>
1544/* File : example.h */
1545
1546#include &lt;vector&gt;
1547#include &lt;algorithm&gt;
1548#include &lt;functional&gt;
1549#include &lt;numeric&gt;
1550
1551double average(std::vector&lt;int&gt; v) {
1552    return std::accumulate(v.begin(),v.end(),0.0)/v.size();
1553}
1554
1555std::vector&lt;double&gt; half(const std::vector&lt;double&gt;&amp; v) {
1556    std::vector&lt;double&gt; w(v);
1557    for (unsigned int i=0; i&lt;w.size(); i++)
1558        w[i] /= 2.0;
1559    return w;
1560}
1561
1562void halve_in_place(std::vector&lt;double&gt;&amp; v) {
1563    std::transform(v.begin(),v.end(),v.begin(),
1564                   std::bind2nd(std::divides&lt;double&gt;(),2.0));
1565}
1566</pre>
1567</div>
1568
1569<p>
1570To wrap with SWIG, you might write the following:
1571</p>
1572
1573<div class="code">
1574<pre>
1575%module example
1576%{
1577#include "example.h"
1578%}
1579
1580%include "std_vector.i"
1581// Instantiate templates used by example
1582namespace std {
1583   %template(IntVector) vector&lt;int&gt;;
1584   %template(DoubleVector) vector&lt;double&gt;;
1585}
1586
1587// Include the header file with above prototypes
1588%include "example.h"
1589</pre>
1590</div>
1591
1592<p>
1593Now, to illustrate the behavior in the scripting interpreter, consider this Python example:
1594</p>
1595
1596<div class="targetlang">
1597<pre>
1598&gt;&gt;&gt; from example import *
1599&gt;&gt;&gt; iv = IntVector(4)         # Create an vector&lt;int&gt;
1600&gt;&gt;&gt; for i in range(0,4):
1601...      iv[i] = i
1602&gt;&gt;&gt; average(iv)               # Call method
16031.5
1604&gt;&gt;&gt; average([0,1,2,3])        # Call with list
16051.5
1606&gt;&gt;&gt; half([1,2,3])             # Half a list
1607(0.5,1.0,1.5)
1608&gt;&gt;&gt; halve_in_place([1,2,3])   # Oops
1609Traceback (most recent call last):
1610  File "&lt;stdin&gt;", line 1, in ?
1611TypeError: Type error. Expected _p_std__vectorTdouble_t
1612&gt;&gt;&gt; dv = DoubleVector(4)
1613&gt;&gt;&gt; for i in range(0,4):
1614...       dv[i] = i
1615&gt;&gt;&gt; halve_in_place(dv)       # Ok
1616&gt;&gt;&gt; for i in dv:
1617...       print i
1618...
16190.0
16200.5
16211.0
16221.5
1623&gt;&gt;&gt; dv[20] = 4.5
1624Traceback (most recent call last):
1625  File "&lt;stdin&gt;", line 1, in ?
1626  File "example.py", line 81, in __setitem__
1627    def __setitem__(*args): return apply(examplec.DoubleVector___setitem__,args)
1628IndexError: vector index out of range
1629&gt;&gt;&gt;
1630</pre>
1631</div>
1632
1633<p>
1634This library module is fully aware of C++ namespaces.  If you use vectors with other names,
1635make sure you include the appropriate <tt>using</tt> or typedef directives.  For example:
1636</p>
1637
1638<div class="code">
1639<pre>
1640%include "std_vector.i"
1641
1642namespace std {
1643    %template(IntVector) vector&lt;int&gt;;
1644}
1645
1646using namespace std;
1647typedef std::vector Vector;
1648
1649void foo(vector&lt;int&gt; *x, const Vector &amp;x);
1650</pre>
1651</div>
1652
1653<p>
1654<b>Note:</b> This module makes use of several advanced SWIG features including templatized typemaps
1655and template partial specialization.  If you are trying to wrap other C++ code with templates, you
1656might look at the code contained in <tt>std_vector.i</tt>.  Alternatively, you can show them the code
1657if you want to make their head explode.
1658</p>
1659
1660<p>
1661<b>Note:</b> This module is defined for all SWIG target languages.  However argument conversion
1662details and the public API exposed to the interpreter vary.
1663</p>
1664
1665<H3><a name="Library_stl_exceptions"></a>8.4.3 STL exceptions</H3>
1666
1667
1668<p>
1669Many of the STL wrapper functions add parameter checking and will throw a language dependent error/exception
1670should the values not be valid. The classic example is array bounds checking.
1671The library wrappers are written to throw a C++ exception in the case of error.
1672The C++ exception in turn gets converted into an appropriate error/exception for the target language.
1673By and large this handling should not need customising, however, customisation can easily be achieved by supplying appropriate "throws" typemaps.
1674For example:
1675</p>
1676
1677<div class="code">
1678<pre>
1679%module example
1680%include "std_vector.i"
1681%typemap(throws) std::out_of_range {
1682  // custom exception handler
1683}
1684%template(VectInt) std::vector&lt;int&gt;;
1685</pre>
1686</div>
1687
1688<p>
1689The custom exception handler might, for example, log the exception then convert it into a specific error/exception for the target language.
1690</p>
1691
1692<p>
1693When using the STL it is advisable to add in an exception handler to catch all STL exceptions.
1694The <tt>%exception</tt> directive can be used by placing the following code before any other methods or libraries to be wrapped:
1695</p>
1696
1697<div class="code">
1698<pre>
1699%include "exception.i"
1700
1701%exception {
1702  try {
1703    $action
1704  } catch (const std::exception&amp; e) {
1705    SWIG_exception(SWIG_RuntimeError, e.what());
1706  }
1707}
1708</pre>
1709</div>
1710
1711<p>
1712Any thrown STL exceptions will then be gracefully handled instead of causing a crash.
1713</p>
1714
1715<H3><a name="Library_std_shared_ptr"></a>8.4.4 shared_ptr smart pointer</H3>
1716
1717
1718<p>
1719Some target languages have support for handling the widely used <tt>boost::shared_ptr</tt> smart pointer.
1720This smart pointer is also available as <tt>std::tr1::shared_ptr</tt> before it becomes fully standardized as <tt>std::shared_ptr</tt>. 
1721The <tt>boost_shared_ptr.i</tt> library provides support for <tt>boost::shared_ptr</tt> and <tt>std_shared_ptr.i</tt> provides support for <tt>std::shared_ptr</tt>, but if the following macro is defined as shown, it can be used for <tt>std::tr1::shared_ptr</tt>:
1722</p>
1723
1724<div class="code">
1725<pre>
1726#define SWIG_SHARED_PTR_SUBNAMESPACE tr1
1727%include &lt;std_shared_ptr.i&gt;
1728</pre>
1729</div>
1730
1731<p>
1732You can only use one of these variants of shared_ptr in your interface file at a time.
1733and all three variants must be used in conjunction with the <tt>%shared_ptr(T)</tt> macro,
1734where <tt>T</tt> is the underlying pointer type equating to usage <tt>shared_ptr&lt;T&gt;</tt>.
1735The type <tt>T</tt> must be non-primitive.
1736A simple example demonstrates usage:
1737</p>
1738
1739<div class="code">
1740<pre>
1741%module example
1742%include &lt;boost_shared_ptr.i&gt;
1743%shared_ptr(IntValue)
1744
1745%inline %{
1746#include &lt;boost/shared_ptr.hpp&gt;
1747
1748struct IntValue {
1749  int value;
1750  IntValue(int v) : value(v) {}
1751};
1752
1753static int extractValue(const IntValue &amp;t) {
1754  return t.value;
1755}
1756
1757static int extractValueSmart(boost::shared_ptr&lt;IntValue&gt; t) {
1758  return t-&gt;value;
1759}
1760%}
1761</pre>
1762</div>
1763
1764<p>
1765Note that the <tt>%shared_ptr(IntValue)</tt> declaration occurs after the inclusion of the <tt>boost_shared_ptr.i</tt>
1766library which provides the macro and, very importantly, before any usage or declaration of the type, <tt>IntValue</tt>.
1767The <tt>%shared_ptr</tt> macro provides, a few things for handling this smart pointer, but mostly a number of
1768typemaps. These typemaps override the default typemaps so that the underlying proxy class is stored and passed around
1769as a pointer to a <tt>shared_ptr</tt> instead of a plain pointer to the underlying type.
1770This approach means that any instantiation of the type can be passed to methods taking the type by value, reference, pointer
1771or as a smart pointer.
1772The interested reader might want to look at the generated code, however, usage is simple and no different
1773handling is required from the target language.
1774For example, a simple use case of the above code from Java would be:
1775</p>
1776
1777<div class="targetlang">
1778<pre>
1779IntValue iv = new IntValue(1234);
1780int val1 = example.extractValue(iv);
1781int val2 = example.extractValueSmart(iv);
1782System.out.println(val1 + " " + val2);
1783</pre>
1784</div>
1785
1786<p>
1787This shared_ptr library works quite differently to SWIG's normal, but somewhat limited, 
1788<a href="SWIGPlus.html#SWIGPlus_smart_pointers">smart pointer handling</a>.
1789The shared_ptr library does not generate extra wrappers, just for smart pointer handling, in addition to the proxy class.
1790The normal proxy class including inheritance relationships is generated as usual.
1791The only real change introduced by the <tt>%shared_ptr</tt> macro is that the proxy class stores a pointer to the shared_ptr instance instead of a raw pointer to the instance.
1792A proxy class derived from a base which is being wrapped with shared_ptr can and <b>must</b> be wrapped as a shared_ptr too.
1793In other words all classes in an inheritance hierarchy must all be used with the <tt>%shared_ptr</tt> macro.
1794For example the following code can be used with the base class shown earlier:
1795</p>
1796
1797<div class="code">
1798<pre>
1799%shared_ptr(DerivedIntValue)
1800%inline %{
1801struct DerivedIntValue : IntValue {
1802  DerivedIntValue(int value) : IntValue(value) {}
1803  ...
1804};
1805%}
1806</pre>
1807</div>
1808
1809<p>
1810A shared_ptr of the derived class can now be passed to a method where the base is expected in the target language, just as it can in C++:
1811</p>
1812
1813<div class="targetlang">
1814<pre>
1815DerivedIntValue div = new DerivedIntValue(5678);
1816int val3 = example.extractValue(div);
1817int val4 = example.extractValueSmart(div);
1818</pre>
1819</div>
1820
1821<p>
1822If the <tt>%shared_ptr</tt> macro is omitted for any class in the inheritance hierarchy, SWIG will warn about this and the generated code may or may not result in a C++ compilation error.
1823For example, the following input: 
1824</p>
1825
1826<div class="code">
1827<pre>
1828%include "boost_shared_ptr.i"
1829%shared_ptr(Parent);
1830
1831%inline %{
1832  #include &lt;boost/shared_ptr.hpp&gt;
1833  struct GrandParent {
1834    virtual ~GrandParent() {}
1835  };
1836
1837  struct Parent : GrandParent {
1838    virtual ~Parent() {}
1839  };
1840
1841  struct Child : Parent {
1842    virtual ~Child() {}
1843  };
1844%}
1845</pre>
1846</div>
1847
1848<p>
1849warns about the missing smart pointer information:
1850</p>
1851
1852<div class="shell">
1853<pre>
1854example.i:12: Warning 520: Base class 'GrandParent' of 'Parent' is not similarly marked as a smart pointer.
1855example.i:16: Warning 520: Derived class 'Child' of 'Parent' is not similarly marked as a smart pointer.
1856</pre>
1857</div>
1858
1859<p>
1860Adding the missing <tt>%shared_ptr</tt> macros will fix this:
1861</p>
1862
1863<div class="code">
1864<pre>
1865%include "boost_shared_ptr.i"
1866%shared_ptr(GrandParent);
1867%shared_ptr(Parent);
1868%shared_ptr(Child);
1869
1870... as before ...
1871</pre>
1872</div>
1873
1874<H2><a name="Library_nn16"></a>8.5 Utility Libraries</H2>
1875
1876
1877<H3><a name="Library_nn17"></a>8.5.1 exception.i</H3>
1878
1879
1880<p>
1881The <tt>exception.i</tt> library provides a language-independent function for raising a run-time
1882exception in the target language. This library is largely used by the SWIG library writers.
1883If possible, use the error handling scheme available to your target language as there is greater
1884flexibility in what errors/exceptions can be thrown.
1885</p>
1886
1887<p>
1888<b><tt>SWIG_exception(int code, const char *message)</tt></b>
1889</p>
1890
1891<div class="indent">
1892
1893<p>
1894Raises an exception in the target language.  <tt>code</tt> is one of the following symbolic
1895constants:
1896</p>
1897
1898<div class="code">
1899<pre>
1900SWIG_MemoryError
1901SWIG_IOError
1902SWIG_RuntimeError
1903SWIG_IndexError
1904SWIG_TypeError
1905SWIG_DivisionByZero
1906SWIG_OverflowError
1907SWIG_SyntaxError
1908SWIG_ValueError
1909SWIG_SystemError
1910</pre>
1911</div>
1912
1913<p>
1914<tt>message</tt> is a string indicating more information about the problem.
1915</p>
1916
1917</div>
1918
1919<p>
1920The primary use of this module is in writing language-independent exception handlers.
1921For example:
1922</p>
1923
1924<div class="code">
1925<pre>
1926%include "exception.i"
1927%exception std::vector::getitem {
1928    try {
1929        $action
1930    } catch (std::out_of_range&amp; e) {
1931        SWIG_exception(SWIG_IndexError,const_cast&lt;char*&gt;(e.what()));
1932    }
1933}
1934</pre>
1935</div>
1936
1937
1938</body>
1939</html>