PageRenderTime 60ms CodeModel.GetById 5ms RepoModel.GetById 0ms app.codeStats 0ms

/trunk/Doc/Manual/Library.html

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