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