1 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
4 <title>SWIG Library</title>
5 <link rel="stylesheet" type="text/css" href="style.css">
8 <body bgcolor="#ffffff">
9 <H1><a name="Library"></a>8 SWIG library</H1>
11 <div class="sectiontoc">
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>
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>
21 <li><a href="#Library_nn8">C String Handling</a>
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>
28 <li><a href="#Library_stl_cpp_library">STL/C++ Library</a>
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>
34 <li><a href="#Library_nn16">Utility Libraries</a>
36 <li><a href="#Library_nn17">exception.i</a>
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.
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.
60 <H2><a name="Library_nn2"></a>8.1 The %include directive and library search path</H2>
64 Library files are included using the <tt>%include</tt> directive.
65 When searching for files, directories are searched in the following order:
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.
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.
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.
88 The directories that are searched are displayed when using <tt>-verbose</tt> commandline option.
91 <H2><a name="Library_nn3"></a>8.2 C Arrays and Pointers</H2>
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.
103 <H3><a name="Library_nn4"></a>8.2.1 cpointer.i</H3>
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>.
114 <b><tt>%pointer_functions(type,name)</tt></b>
118 <p>Generates a collection of four functions for manipulating a pointer <tt>type *</tt>:</p>
121 <tt>type *new_name()</tt>
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.
130 <tt>type *copy_name(type value)</tt>
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.
140 <tt>type *delete_name(type *obj)</tt>
143 <div class="indent"><p>
144 Deletes an object type <tt>type</tt>.
148 <tt>void name_assign(type *obj, type value)</tt>
151 <div class="indent"><p>
152 Assigns <tt>*obj = value</tt>.
156 <tt>type name_value(type *obj)</tt>
159 <div class="indent"><p>
160 Returns the value of <tt>*obj</tt>.
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.
170 Here is a simple example of using <tt>%pointer_functions()</tt>:
176 %include "cpointer.i"
178 /* Create some functions for working with "int *" */
179 %pointer_functions(int, intp);
181 /* A function that uses an "int *" */
182 void add(int x, int y, int *result);
190 <div class="targetlang">
192 >>> import example
193 >>> c = example.new_intp() # Create an "int" for storing result
194 >>> example.add(3,4,c) # Call function
195 >>> example.intp_value(c) # Dereference
197 >>> example.delete_intp(c) # Delete
204 <b><tt>%pointer_class(type,name)</tt></b>
210 Wraps a pointer of <tt>type *</tt> inside a class-based interface. This
211 interface is as follows:
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
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.
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.
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.
250 Here is the same example using a class instead:
256 %include "cpointer.i"
258 /* Wrap a class interface around an "int *" */
259 %pointer_class(int, intp);
261 /* A function that uses an "int *" */
262 void add(int x, int y, int *result);
267 Now, in Python (using proxy classes)
270 <div class="targetlang">
272 >>> import example
273 >>> c = example.intp() # Create an "int" for storing result
274 >>> example.add(3,4,c) # Call function
275 >>> c.value() # Dereference
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).
289 <b><tt>%pointer_cast(type1, type2, name)</tt></b>
295 Creates a casting function that converts <tt>type1</tt> to <tt>type2</tt>. The name of the function is <tt>name</tt>.
301 %pointer_cast(int *, unsigned int *, int_to_uint);
306 In this example, the function <tt>int_to_uint()</tt> would be used to cast types in the target language.
312 <b>Note:</b> None of these macros can be used to safely work with strings (<tt>char *</tt> or <tt>char **</tt>).
316 <b>Note:</b> When working with simple pointers, typemaps can often be used to provide more seamless operation.
319 <H3><a name="Library_carrays"></a>8.2.2 carrays.i</H3>
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
330 <b><tt>%array_functions(type,name)</tt></b>
334 <p>Creates four functions.</p>
337 <tt>type *new_name(int nelements)</tt>
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.
346 <tt>type *delete_name(type *ary)</tt>
349 <div class="indent"><p>
350 Deletes an array. In C, <tt>free()</tt> is used. In C++, <tt>delete []</tt> is used.
354 <tt>type name_getitem(type *ary, int index)</tt>
357 <div class="indent"><p>
358 Returns the value <tt>ary[index]</tt>.
362 <tt>void name_setitem(type *ary, int index, type value)</tt>
365 <div class="indent"><p>
366 Assigns <tt>ary[index] = value</tt>.
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.
376 Here is an example of <tt>%array_functions()</tt>. Suppose you had a
382 void print_array(double x[10]) {
384 for (i = 0; i < 10; i++) {
385 printf("[%d] = %g\n", i, x[i]);
392 To wrap it, you might write this:
400 %array_functions(double, doubleArray);
402 void print_array(double x[10]);
407 Now, in a scripting language, you might write this:
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
423 <b><tt>%array_class(type,name)</tt></b>
428 Wraps a pointer of <tt>type *</tt> inside a class-based interface. This
429 interface is as follows:
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
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.
456 When combined with proxy classes, the <tt>%array_class()</tt> macro can be especially useful.
464 %array_class(double, doubleArray);
466 void print_array(double x[10]);
471 Allows you to do this:
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
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.
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>.
497 <H3><a name="Library_nn6"></a>8.2.3 cmalloc.i</H3>
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>.
506 <b><tt>%malloc(type [,name=type])</tt></b>
512 Creates a wrapper around <tt>malloc()</tt> with the following prototype:
515 <div class="code"><pre>
516 <em>type</em> *malloc_<em>name</em>(int nbytes = sizeof(<em>type</em>));
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.).
529 <b><tt>%calloc(type [,name=type])</tt></b>
535 Creates a wrapper around <tt>calloc()</tt> with the following prototype:
538 <div class="code"><pre>
539 <em>type</em> *calloc_<em>name</em>(int nobj =1, int sz = sizeof(<em>type</em>));
544 If <tt>type</tt> is <tt>void</tt>, then the size parameter <tt>sz</tt> is required.
550 <b><tt>%realloc(type [,name=type])</tt></b>
556 Creates a wrapper around <tt>realloc()</tt> with the following prototype:
559 <div class="code"><pre>
560 <em>type</em> *realloc_<em>name</em>(<em>type</em> *ptr, int nitems);
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.
573 <b><tt>%free(type [,name=type])</tt></b>
579 Creates a wrapper around <tt>free()</tt> with the following prototype:
582 <div class="code"><pre>
583 void free_<em>name</em>(<em>type</em> *ptr);
589 <b><tt>%sizeof(type [,name=type])</tt></b>
595 Creates the constant:
598 <div class="code"><pre>
599 %constant int sizeof_<em>name</em> = sizeof(<em>type</em>);
605 <b><tt>%allocators(type [,name=type])</tt></b>
608 <div class="indent"><p>
609 Generates wrappers for all five of the above operations.
613 Here is a simple example that illustrates the use of these macros:
625 %malloc(int *, intp);
636 <div class="targetlang">
638 >>> from example import *
639 >>> a = malloc_int()
642 >>> free_int(a)
643 >>> b = malloc_intp()
646 >>> free_intp(b)
647 >>> c = calloc_double(50)
650 >>> c = realloc_double(100000)
651 >>> free_double(c)
652 >>> print sizeof_double
658 <H3><a name="Library_nn7"></a>8.2.4 cdata.i</H3>
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.
670 <b><tt>char *cdata(void *ptr, int nbytes)</tt></b>
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
679 <b><tt>void memmove(void *ptr, char *s)</tt></b>
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.
689 One use of these functions is packing and unpacking data from memory.
690 Here is a short example:
700 %array_class(int, intArray);
708 <div class="targetlang">
710 >>> a = intArray(10)
711 >>> for i in range(0,10):
713 >>> b = cdata(a,40)
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 >>> c = intArray(10)
718 >>> memmove(c,b)
719 >>> print c[4]
726 Since the size of data is not always known, the following macro is also defined:
730 <b><tt>%cdata(type [,name=type])</tt></b>
736 Generates the following function for extracting C data for a given type.
741 char *cdata_<em>name</em>(type* ptr, int nitems)
746 <tt>nitems</tt> is the number of items of the given type to extract.
752 <b>Note:</b> These functions provide direct access to memory and can be used to overwrite data.
753 Clearly they are unsafe.
756 <H2><a name="Library_nn8"></a>8.3 C String Handling</H2>
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
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.
776 <H3><a name="Library_nn9"></a>8.3.1 Default string handling</H3>
780 Suppose you have a C function with this prototype:
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,
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.
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.
817 <H3><a name="Library_nn10"></a>8.3.2 Passing binary data</H3>
821 If you have a function that expects binary data,
826 int parity(char *str, int len, int initial);
831 you can wrap the parameters <tt>(char *str, int len)</tt> as a single
832 argument using a typemap. Just do this:
837 %apply (char *STRING, int LENGTH) { (char *str, int len) };
839 int parity(char *str, int len, int initial);
844 Now, in the target language, you can use binary string data like this:
849 >>> s = "H\x00\x15eg\x09\x20"
850 >>> parity(s,0)
855 In the wrapper function, the passed string will be expanded to a pointer and length parameter.
858 <H3><a name="Library_nn11"></a>8.3.3 Using %newobject to release memory</H3>
862 If you have a function that allocates memory like this,
868 char *result = (char *) malloc(...);
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.
881 To fix the memory leak, use the <tt>%newobject</tt> directive.
893 This will release the result.
896 <H3><a name="Library_nn12"></a>8.3.4 cstring.i</H3>
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
909 void get_path(char *s) {
910 // Potential buffer overflow---uh, oh.
911 sprintf(s,"%s/%s", base_directory, sub_directory);
914 // Somewhere else in the C program
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).
931 The macros defined in this module all expand to various combinations of
932 typemaps. Therefore, the same pattern matching rules and ideas apply.
936 <b>%cstring_bounded_output(parm, maxsize)</b>
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:
949 %cstring_bounded_output(char *path, 1024);
951 void get_path(char *path);
956 In the target language:
959 <div class="targetlang">
961 >>> get_path()
962 /home/beazley/packages/Foo/Bar
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>
979 <b>%cstring_chunk_output(parm, chunksize)</b>
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:
992 %cstring_chunk_output(char *packet, PACKETSIZE);
994 void get_packet(char *packet);
999 In the target language:
1002 <div class="targetlang">
1004 >>> get_packet()
1005 '\xa9Y:\xf6\xd7\xe1\x87\xdbH;y\x97\x7f\xd3\x99\x14V\xec\x06\xea\xa2\x88'
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>
1021 <b>%cstring_bounded_mutable(parm, maxsize)</b>
1024 <div class="indent">
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.
1035 %cstring_bounded_mutable(char *ustr, 1024);
1037 void make_upper(char *ustr);
1042 In the target language:
1045 <div class="targetlang">
1047 >>> make_upper("hello world")
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>
1067 <b>%cstring_mutable(parm [, expansion])</b>
1070 <div class="indent">
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.
1083 %cstring_mutable(char *ustr);
1085 void make_upper(char *ustr);
1087 %cstring_mutable(char *hstr, HEADER_SIZE);
1089 void attach_header(char *hstr);
1094 In the target language:
1097 <div class="targetlang">
1099 >>> make_upper("hello world")
1101 >>> attach_header("Hello world")
1102 'header: Hello world'
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
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>
1124 <b>%cstring_output_maxsize(parm, maxparm)</b>
1127 <div class="indent">
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.
1138 %cstring_output_maxsize(char *path, int maxpath);
1140 void get_path(char *path, int maxpath);
1145 In the target language:
1148 <div class="targetlang">
1150 >>> get_path(1024)
1151 '/home/beazley/Packages/Foo/Bar'
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.
1168 <b>%cstring_output_withsize(parm, maxparm)</b>
1171 <div class="indent">
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.
1184 %cstring_output_withsize(char *data, int *maxdata);
1186 void get_data(char *data, int *maxdata);
1191 In the target language:
1194 <div class="targetlang">
1196 >>> get_data(1024)
1198 >>> get_data(1024)
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.
1214 <b>%cstring_output_allocate(parm, release)</b>
1217 <div class="indent">
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:
1226 void foo(char **s) {
1227 *s = (char *) malloc(64);
1228 sprintf(*s, "Hello world\n");
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
1241 %cstring_output_allocate(char **s, free(*$1));
1248 In the target language:
1251 <div class="targetlang">
1262 <b>%cstring_output_allocate_size(parm, szparm, release)</b>
1265 <div class="indent">
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:
1274 void foo(char **s, int *sz) {
1275 *s = (char *) malloc(64);
1277 // Write some binary data
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
1291 %cstring_output_allocate_size(char **s, int *slen, free(*$1));
1293 void foo(char **s, int *slen);
1298 In the target language:
1301 <div class="targetlang">
1304 '\xa9Y:\xf6\xd7\xe1\x87\xdbH;y\x97\x7f\xd3\x99\x14V\xec\x06\xea\xa2\x88'
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:
1317 char *get_data(int *len);
1322 You could wrap it with a function like this:
1327 void my_get_data(char **result, int *len) {
1328 *result = get_data(len);
1339 <li>Support for the <tt>cstring.i</tt> module depends on the target language. Not all
1340 SWIG modules currently support this library.
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.
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>.
1351 <li>Rather than manipulating <tt>char *</tt> directly, you might consider using a special string
1352 structure or class instead.
1356 <H2><a name="Library_stl_cpp_library"></a>8.4 STL/C++ Library</H2>
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.
1366 The following table shows which C++ classes are supported and the equivalent SWIG interface library file for the C++ library.
1369 <table BORDER summary="SWIG C++ library files">
1371 <td><b>C++ class</b></td>
1372 <td><b>C++ Library file</b></td>
1373 <td><b>SWIG Interface library file</b></td>
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>
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.
1392 <H3><a name="Library_nn14"></a>8.4.1 std_string.i</H3>
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:
1403 %include "std_string.i"
1406 void bar(const std::string &x);
1411 In the target language:
1414 <div class="targetlang">
1416 x = foo(); # Returns a string object
1417 bar("Hello World"); # Pass string as std::string
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.
1430 %include "std_string.i"
1432 %apply const std::string& {std::string* foo};
1442 In the target language:
1445 <div class="targetlang">
1448 x.foo="Hello World"; # assign with string
1449 print x.foo; # print as string
1454 This module only supports types <tt>std::string</tt> and
1455 <tt>const std::string &</tt>. Pointers and non-const references
1456 are left unmodified and returned as SWIG pointers.
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:
1467 %include "std_string.i"
1469 using namespace std;
1470 typedef std::string String;
1472 void foo(string s, const String &t); // std_string typemaps still applied
1477 <b>Note:</b> The <tt>std_string</tt> library is incompatible with Perl on some platforms.
1478 We're looking into it.
1481 <H3><a name="Library_nn15"></a>8.4.2 std_vector.i</H3>
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:
1493 %include "std_vector.i"
1496 %template(vectori) vector<int>;
1497 %template(vectord) vector<double>;
1503 When a template <tt>vector<X></tt> is instantiated a number of things happen:
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.
1512 <li>Input typemaps are defined for <tt>vector<X></tt>, <tt>const vector<X> &</tt>, and
1513 <tt>const vector<X> *</tt>. For each of these, a pointer <tt>vector<X> *</tt> may be passed or
1514 a native list object in the target language.
1517 <li>An output typemap is defined for <tt>vector<X></tt>. In this case, the values in the
1518 vector are expanded into a list object in the target language.
1521 <li>For all other variations of the type, the wrappers expect to receive a <tt>vector<X> *</tt>
1522 object in the usual manner.
1525 <li>An exception handler for <tt>std::out_of_range</tt> is defined.
1528 <li>Optionally, special methods for indexing, item retrieval, slicing, and element assignment
1529 may be defined. This depends on the target language.
1534 To illustrate the use of this library, consider the following functions:
1539 /* File : example.h */
1541 #include <vector>
1542 #include <algorithm>
1543 #include <functional>
1544 #include <numeric>
1546 double average(std::vector<int> v) {
1547 return std::accumulate(v.begin(),v.end(),0.0)/v.size();
1550 std::vector<double> half(const std::vector<double>& v) {
1551 std::vector<double> w(v);
1552 for (unsigned int i=0; i<w.size(); i++)
1557 void halve_in_place(std::vector<double>& v) {
1558 std::transform(v.begin(),v.end(),v.begin(),
1559 std::bind2nd(std::divides<double>(),2.0));
1565 To wrap with SWIG, you might write the following:
1572 #include "example.h"
1575 %include "std_vector.i"
1576 // Instantiate templates used by example
1578 %template(IntVector) vector<int>;
1579 %template(DoubleVector) vector<double>;
1582 // Include the header file with above prototypes
1583 %include "example.h"
1588 Now, to illustrate the behavior in the scripting interpreter, consider this Python example:
1591 <div class="targetlang">
1593 >>> from example import *
1594 >>> iv = IntVector(4) # Create an vector<int>
1595 >>> for i in range(0,4):
1597 >>> average(iv) # Call method
1599 >>> average([0,1,2,3]) # Call with list
1601 >>> half([1,2,3]) # Half a list
1603 >>> halve_in_place([1,2,3]) # Oops
1604 Traceback (most recent call last):
1605 File "<stdin>", line 1, in ?
1606 TypeError: Type error. Expected _p_std__vectorTdouble_t
1607 >>> dv = DoubleVector(4)
1608 >>> for i in range(0,4):
1610 >>> halve_in_place(dv) # Ok
1611 >>> for i in dv:
1618 >>> dv[20] = 4.5
1619 Traceback (most recent call last):
1620 File "<stdin>", 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
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:
1635 %include "std_vector.i"
1638 %template(IntVector) vector<int>;
1641 using namespace std;
1642 typedef std::vector Vector;
1644 void foo(vector<int> *x, const Vector &x);
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.
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.
1661 <b>Note:</b> <tt>std_vector.i</tt> was written by Luigi "The Amazing" Ballabio.
1665 <H3><a name="Library_stl_exceptions"></a>8.4.3 STL exceptions</H3>
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.
1680 %include "std_vector.i"
1681 %typemap(throws) std::out_of_range {
1682 // custom exception handler
1684 %template(VectInt) std::vector<int>;
1689 The custom exception handler might, for example, log the exception then convert it into a specific error/exception for the target language.
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:
1699 %include "exception.i"
1704 } catch (const std::exception& e) {
1705 SWIG_exception(SWIG_RuntimeError, e.what());
1712 Any thrown STL exceptions will then be gracefully handled instead of causing a crash.
1716 <H2><a name="Library_nn16"></a>8.5 Utility Libraries</H2>
1719 <H3><a name="Library_nn17"></a>8.5.1 exception.i</H3>
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.
1730 <b><tt>SWIG_exception(int code, const char *message)</tt></b>
1733 <div class="indent">
1736 Raises an exception in the target language. <tt>code</tt> is one of the following symbolic
1756 <tt>message</tt> is a string indicating more information about the problem.
1762 The primary use of this module is in writing language-independent exception handlers.
1768 %include "exception.i"
1769 %exception std::vector::getitem {
1772 } catch (std::out_of_range& e) {
1773 SWIG_exception(SWIG_IndexError,const_cast<char*>(e.what()));