PageRenderTime 71ms CodeModel.GetById 26ms RepoModel.GetById 1ms app.codeStats 0ms

/Doc/Manual/Library.html

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