PageRenderTime 67ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/trunk/Doc/Manual/SWIG.html

#
HTML | 2032 lines | 1733 code | 295 blank | 4 comment | 0 complexity | 4ab2478ddd8445934616c2165844b179 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 Basics</title>
  5. <link rel="stylesheet" type="text/css" href="style.css">
  6. </head>
  7. <body bgcolor="#ffffff">
  8. <H1><a name="SWIG"></a>5 SWIG Basics</H1>
  9. <!-- INDEX -->
  10. <div class="sectiontoc">
  11. <ul>
  12. <li><a href="#SWIG_nn2">Running SWIG</a>
  13. <ul>
  14. <li><a href="#SWIG_nn3">Input format</a>
  15. <li><a href="#SWIG_output">SWIG Output</a>
  16. <li><a href="#SWIG_nn5">Comments</a>
  17. <li><a href="#SWIG_nn6">C Preprocessor</a>
  18. <li><a href="#SWIG_nn7">SWIG Directives</a>
  19. <li><a href="#SWIG_nn8">Parser Limitations</a>
  20. </ul>
  21. <li><a href="#SWIG_nn9">Wrapping Simple C Declarations</a>
  22. <ul>
  23. <li><a href="#SWIG_nn10">Basic Type Handling</a>
  24. <li><a href="#SWIG_nn11">Global Variables</a>
  25. <li><a href="#SWIG_nn12">Constants</a>
  26. <li><a href="#SWIG_nn13">A brief word about <tt>const</tt></a>
  27. <li><a href="#SWIG_nn14">A cautionary tale of <tt>char *</tt></a>
  28. </ul>
  29. <li><a href="#SWIG_nn15">Pointers and complex objects</a>
  30. <ul>
  31. <li><a href="#SWIG_nn16">Simple pointers</a>
  32. <li><a href="#SWIG_nn17">Run time pointer type checking</a>
  33. <li><a href="#SWIG_nn18">Derived types, structs, and classes</a>
  34. <li><a href="#SWIG_nn19">Undefined datatypes</a>
  35. <li><a href="#SWIG_nn20">Typedef</a>
  36. </ul>
  37. <li><a href="#SWIG_nn21">Other Practicalities</a>
  38. <ul>
  39. <li><a href="#SWIG_nn22">Passing structures by value</a>
  40. <li><a href="#SWIG_nn23">Return by value</a>
  41. <li><a href="#SWIG_nn24">Linking to structure variables</a>
  42. <li><a href="#SWIG_nn25">Linking to <tt>char *</tt></a>
  43. <li><a href="#SWIG_nn26">Arrays</a>
  44. <li><a href="#SWIG_readonly_variables">Creating read-only variables</a>
  45. <li><a href="#SWIG_rename_ignore">Renaming and ignoring declarations</a>
  46. <ul>
  47. <li><a href="#SWIG_nn29">Simple renaming of specific identifiers</a>
  48. <li><a href="#SWIG_advanced_renaming">Advanced renaming support</a>
  49. <li><a href="#SWIG_limiting_renaming">Limiting global renaming rules</a>
  50. <li><a href="#SWIG_chosen_unignore">Ignoring everything then wrapping a few selected symbols</a>
  51. </ul>
  52. <li><a href="#SWIG_default_args">Default/optional arguments</a>
  53. <li><a href="#SWIG_nn30">Pointers to functions and callbacks</a>
  54. </ul>
  55. <li><a href="#SWIG_nn31">Structures and unions</a>
  56. <ul>
  57. <li><a href="#SWIG_nn32">Typedef and structures</a>
  58. <li><a href="#SWIG_nn33">Character strings and structures</a>
  59. <li><a href="#SWIG_nn34">Array members</a>
  60. <li><a href="#SWIG_structure_data_members">Structure data members</a>
  61. <li><a href="#SWIG_nn36">C constructors and destructors</a>
  62. <li><a href="#SWIG_adding_member_functions">Adding member functions to C structures</a>
  63. <li><a href="#SWIG_nested_structs">Nested structures</a>
  64. <li><a href="#SWIG_nn39">Other things to note about structure wrapping</a>
  65. </ul>
  66. <li><a href="#SWIG_nn40">Code Insertion</a>
  67. <ul>
  68. <li><a href="#SWIG_nn41">The output of SWIG</a>
  69. <li><a href="#SWIG_nn42">Code insertion blocks</a>
  70. <li><a href="#SWIG_nn43">Inlined code blocks</a>
  71. <li><a href="#SWIG_nn44">Initialization blocks</a>
  72. </ul>
  73. <li><a href="#SWIG_nn45">An Interface Building Strategy</a>
  74. <ul>
  75. <li><a href="#SWIG_nn46">Preparing a C program for SWIG</a>
  76. <li><a href="#SWIG_nn47">The SWIG interface file</a>
  77. <li><a href="#SWIG_nn48">Why use separate interface files?</a>
  78. <li><a href="#SWIG_nn49">Getting the right header files</a>
  79. <li><a href="#SWIG_nn50">What to do with main()</a>
  80. </ul>
  81. </ul>
  82. </div>
  83. <!-- INDEX -->
  84. <p>
  85. This chapter describes the basic operation of SWIG, the structure of its
  86. input files, and how it handles standard ANSI C declarations. C++ support is
  87. described in the next chapter. However, C++ programmers should still read this
  88. chapter to understand the basics.
  89. Specific details about each target language are described in later
  90. chapters.
  91. </p>
  92. <H2><a name="SWIG_nn2"></a>5.1 Running SWIG</H2>
  93. <p>
  94. To run SWIG, use the <tt>swig</tt> command with options and a filename like this:
  95. </p>
  96. <div class="shell"><pre>
  97. swig [ <em>options</em> ] filename
  98. </pre></div>
  99. <p>
  100. where <tt>filename</tt> is a SWIG interface file or a C/C++ header file.
  101. Below is a subset of <em>options</em> that can be used.
  102. Additional options are also defined for each target language. A full list
  103. can be obtained by typing <tt>swig -help</tt> or <tt>swig
  104. -<em>lang</em> -help</tt>.
  105. </p>
  106. <div class="shell"><pre>
  107. -allegrocl Generate ALLEGROCL wrappers
  108. -chicken Generate CHICKEN wrappers
  109. -clisp Generate CLISP wrappers
  110. -cffi Generate CFFI wrappers
  111. -csharp Generate C# wrappers
  112. -go Generate Go wrappers
  113. -guile Generate Guile wrappers
  114. -java Generate Java wrappers
  115. -lua Generate Lua wrappers
  116. -modula3 Generate Modula 3 wrappers
  117. -mzscheme Generate Mzscheme wrappers
  118. -ocaml Generate Ocaml wrappers
  119. -perl Generate Perl wrappers
  120. -php Generate PHP wrappers
  121. -pike Generate Pike wrappers
  122. -python Generate Python wrappers
  123. -r Generate R (aka GNU S) wrappers
  124. -ruby Generate Ruby wrappers
  125. -sexp Generate Lisp S-Expressions wrappers
  126. -tcl Generate Tcl wrappers
  127. -uffi Generate Common Lisp / UFFI wrappers
  128. -xml Generate XML wrappers
  129. -c++ Enable C++ parsing
  130. -D<em>symbol</em> Define a preprocessor symbol
  131. -Fstandard Display error/warning messages in commonly used format
  132. -Fmicrosoft Display error/warning messages in Microsoft format
  133. -help Display all options
  134. -I<em>dir</em> Add a directory to the file include path
  135. -l<em>file</em> Include a SWIG library file.
  136. -module <em>name</em> Set the name of the SWIG module
  137. -o <em>outfile</em> Name of output file
  138. -outcurrentdir Set default output dir to current dir instead of input file's path
  139. -outdir <em>dir</em> Set language specific files output directory
  140. -pcreversion Display PCRE version information
  141. -swiglib Show location of SWIG library
  142. -version Show SWIG version number
  143. </pre></div>
  144. <H3><a name="SWIG_nn3"></a>5.1.1 Input format</H3>
  145. <p>
  146. As input, SWIG expects a file containing ANSI C/C++ declarations and
  147. special SWIG directives. More often than not, this is a special SWIG
  148. interface file which is usually denoted with a special <tt>.i</tt> or
  149. <tt>.swg</tt> suffix. In certain cases, SWIG can be used directly on
  150. raw header files or source files. However, this is not the most
  151. typical case and there are several reasons why you might not want to
  152. do this (described later).
  153. </p>
  154. <p>
  155. The most common format of a SWIG interface is as follows:
  156. </p>
  157. <div class="code"><pre>
  158. %module mymodule
  159. %{
  160. #include "myheader.h"
  161. %}
  162. // Now list ANSI C/C++ declarations
  163. int foo;
  164. int bar(int x);
  165. ...
  166. </pre></div>
  167. <p>
  168. The module name is supplied using the special <tt>%module</tt>
  169. directive. Modules are described further in the <a href="Modules.html#Modules_introduction">Modules Introduction</a> section.
  170. </p>
  171. <p>
  172. Everything in the <tt>%{ ... %}</tt> block is simply copied verbatim
  173. to the resulting wrapper file created by SWIG. This section is almost
  174. always used to include header files and other declarations that are
  175. required to make the generated wrapper code compile. It is important
  176. to emphasize that just because you include a declaration in a SWIG
  177. input file, that declaration does <em>not</em> automatically appear in
  178. the generated wrapper code---therefore you need to make sure you
  179. include the proper header files in the <tt>%{ ... %}</tt> section. It
  180. should be noted that the text enclosed in <tt>%{ ... %}</tt> is not
  181. parsed or interpreted by SWIG. The <tt>%{...%}</tt> syntax and
  182. semantics in SWIG is analogous to that of the declarations section
  183. used in input files to parser generation tools such as yacc or bison.
  184. </p>
  185. <H3><a name="SWIG_output"></a>5.1.2 SWIG Output</H3>
  186. <p>
  187. The output of SWIG is a C/C++ file that contains all of the wrapper
  188. code needed to build an extension module. SWIG may generate some
  189. additional files depending on the target language. By default, an input file
  190. with the name <tt>file.i</tt> is transformed into a file
  191. <tt>file_wrap.c</tt> or <tt>file_wrap.cxx</tt> (depending on whether
  192. or not the <tt>-c++</tt> option has been used). The name of the
  193. output file can be changed using the <tt>-o</tt> option. In certain
  194. cases, file suffixes are used by the compiler to determine the source
  195. language (C, C++, etc.). Therefore, you have to use the
  196. <tt>-o</tt> option to change the suffix of the SWIG-generated wrapper
  197. file if you want something different than the default. For example:
  198. </p>
  199. <div class="shell"><pre>
  200. $ swig -c++ -python -o example_wrap.cpp example.i
  201. </pre></div>
  202. <p>
  203. The C/C++ output file created by SWIG often
  204. contains everything that is needed to construct a extension module
  205. for the target scripting language. SWIG is not a stub compiler nor is it
  206. usually necessary to edit the output file (and if you look at the output,
  207. you probably won't want to). To build the final extension module, the
  208. SWIG output file is compiled and linked with the rest of your C/C++
  209. program to create a shared library.
  210. </p>
  211. <p>
  212. Many target languages will also generate proxy class files in the
  213. target language. The default output directory for these language
  214. specific files is the same directory as the generated C/C++ file. This
  215. can be modified using the <tt>-outdir</tt> option. For example:
  216. </p>
  217. <div class="shell"><pre>
  218. $ swig -c++ -python -outdir pyfiles -o cppfiles/example_wrap.cpp example.i
  219. </pre></div>
  220. <p>
  221. If the directories <tt>cppfiles</tt> and <tt>pyfiles</tt> exist, the following
  222. will be generated:</p>
  223. <div class="shell"><pre>
  224. cppfiles/example_wrap.cpp
  225. pyfiles/example.py
  226. </pre></div>
  227. <p>
  228. If the <tt>-outcurrentdir</tt> option is used (without <tt>-o</tt>)
  229. then SWIG behaves like a typical C/C++
  230. compiler and the default output directory is then the current directory. Without
  231. this option the default output directory is the path to the input file.
  232. If <tt>-o</tt> and
  233. <tt>-outcurrentdir</tt> are used together, <tt>-outcurrentdir</tt> is effectively ignored
  234. as the output directory for the language files is the same directory as the
  235. generated C/C++ file if not overidden with <tt>-outdir</tt>.
  236. </p>
  237. <H3><a name="SWIG_nn5"></a>5.1.3 Comments</H3>
  238. <p>
  239. C and C++ style comments may appear anywhere in interface files. In
  240. previous versions of SWIG, comments were used to generate
  241. documentation files. However, this feature is currently under repair
  242. and will reappear in a later SWIG release.
  243. </p>
  244. <H3><a name="SWIG_nn6"></a>5.1.4 C Preprocessor</H3>
  245. <p>
  246. Like C, SWIG preprocesses all input files through an enhanced version
  247. of the C preprocessor. All standard preprocessor features are
  248. supported including file inclusion, conditional compilation and
  249. macros. However, <tt>#include</tt> statements are ignored unless the
  250. <tt>-includeall</tt> command line option has been supplied. The
  251. reason for disabling includes is that SWIG is sometimes used to
  252. process raw C header files. In this case, you usually only want the
  253. extension module to include functions in the supplied header file
  254. rather than everything that might be included by that header file
  255. (i.e., system headers, C library functions, etc.).
  256. </p>
  257. <p>
  258. It should also be noted that the SWIG preprocessor skips all text
  259. enclosed inside a <tt>%{...%}</tt> block. In addition, the
  260. preprocessor includes a number of macro handling enhancements that
  261. make it more powerful than the normal C preprocessor. These
  262. extensions are described in the "<a href="Preprocessor.html#Preprocessor">Preprocessor</a>" chapter.
  263. </p>
  264. <H3><a name="SWIG_nn7"></a>5.1.5 SWIG Directives</H3>
  265. <p>
  266. Most of SWIG's operation is controlled by special directives that are
  267. always preceded by a "<tt>%</tt>" to distinguish them from normal C
  268. declarations. These directives are used to give SWIG hints or to alter
  269. SWIG's parsing behavior in some manner.
  270. </p>
  271. <p>
  272. Since SWIG directives are not legal C syntax, it is generally not
  273. possible to include them in header files. However, SWIG directives can be
  274. included in C header files using conditional compilation like this:
  275. </p>
  276. <div class="code"><pre>
  277. /* header.h --- Some header file */
  278. /* SWIG directives -- only seen if SWIG is running */
  279. #ifdef SWIG
  280. %module foo
  281. #endif
  282. </pre>
  283. </div>
  284. <p>
  285. <tt>SWIG</tt> is a special preprocessing symbol defined by SWIG when
  286. it is parsing an input file.
  287. </p>
  288. <H3><a name="SWIG_nn8"></a>5.1.6 Parser Limitations</H3>
  289. <p>
  290. Although SWIG can parse most C/C++ declarations, it does not
  291. provide a complete C/C++ parser implementation. Most of these
  292. limitations pertain to very complicated type declarations and certain
  293. advanced C++ features. Specifically, the following features are not
  294. currently supported:
  295. </p>
  296. <ul>
  297. <li>
  298. <p>
  299. Non-conventional type declarations.
  300. For example, SWIG does not support declarations such as the following
  301. (even though this is legal C):
  302. </p>
  303. <div class="code">
  304. <pre>
  305. /* Non-conventional placement of storage specifier (extern) */
  306. const int extern Number;
  307. /* Extra declarator grouping */
  308. Matrix (foo); // A global variable
  309. /* Extra declarator grouping in parameters */
  310. void bar(Spam (Grok)(Doh));
  311. </pre>
  312. </div>
  313. <p>
  314. In practice, few (if any) C programmers actually write code like
  315. this since this style is never featured in programming books. However,
  316. if you're feeling particularly obfuscated, you can certainly break SWIG (although why would you want to?).
  317. </p>
  318. </li>
  319. <li>
  320. <p>
  321. Running SWIG on C++ source files (the code in a .C, .cpp or .cxx file) is not recommended.
  322. The usual approach is to feed SWIG header files for parsing C++ definitions and declarations.
  323. The main reason is if SWIG parses a scoped definition or declaration (as is normal for C++ source files),
  324. it is ignored, unless a declaration for the symbol was parsed earlier.
  325. For example
  326. </p>
  327. <div class="code">
  328. <pre>
  329. /* bar not wrapped unless foo has been defined and
  330. the declaration of bar within foo has already been parsed */
  331. int foo::bar(int) {
  332. ... whatever ...
  333. }
  334. </pre>
  335. </div>
  336. </li>
  337. <li>
  338. <p>
  339. Certain advanced features of C++ such as nested classes
  340. are not yet fully supported. Please see the C++ <a href="SWIGPlus.html#SWIGPlus_nested_classes">Nested classes</a> section
  341. for more information.
  342. </p>
  343. </ul>
  344. <p>
  345. In the event of a parsing error, conditional compilation can be used to skip
  346. offending code. For example:
  347. </p>
  348. <div class="code">
  349. <pre>
  350. #ifndef SWIG
  351. ... some bad declarations ...
  352. #endif
  353. </pre>
  354. </div>
  355. <p>
  356. Alternatively, you can just delete the offending code from the interface file.
  357. </p>
  358. <p>
  359. One of the reasons why SWIG does not provide a full C++ parser
  360. implementation is that it has been designed to work with incomplete
  361. specifications and to be very permissive in its handling of C/C++
  362. datatypes (e.g., SWIG can generate interfaces even when there are
  363. missing class declarations or opaque datatypes). Unfortunately, this
  364. approach makes it extremely difficult to implement certain parts of a
  365. C/C++ parser as most compilers use type information to assist in the
  366. parsing of more complex declarations (for the truly curious, the
  367. primary complication in the implementation is that the SWIG parser
  368. does not utilize a separate <em>typedef-name</em> terminal symbol as
  369. described on p. 234 of K&amp;R).
  370. </p>
  371. <H2><a name="SWIG_nn9"></a>5.2 Wrapping Simple C Declarations</H2>
  372. <p>
  373. SWIG wraps simple C declarations by creating an interface that closely matches
  374. the way in which the declarations would be used in a C program.
  375. For example, consider the following interface file:
  376. </p>
  377. <div class="code"><pre>
  378. %module example
  379. %inline %{
  380. extern double sin(double x);
  381. extern int strcmp(const char *, const char *);
  382. extern int Foo;
  383. %}
  384. #define STATUS 50
  385. #define VERSION "1.1"
  386. </pre></div>
  387. <p>
  388. In this file, there are two functions <tt>sin()</tt> and <tt>strcmp()</tt>,
  389. a global variable <tt>Foo</tt>, and two constants <tt>STATUS</tt> and
  390. <tt>VERSION</tt>. When SWIG creates an extension module, these
  391. declarations are accessible as scripting language functions, variables, and
  392. constants respectively. For example, in Tcl:
  393. </p>
  394. <div class="targetlang"><pre>
  395. % sin 3
  396. 5.2335956
  397. % strcmp Dave Mike
  398. -1
  399. % puts $Foo
  400. 42
  401. % puts $STATUS
  402. 50
  403. % puts $VERSION
  404. 1.1
  405. </pre></div>
  406. <p>
  407. Or in Python:
  408. </p>
  409. <div class="targetlang"><pre>
  410. &gt;&gt;&gt; example.sin(3)
  411. 5.2335956
  412. &gt;&gt;&gt; example.strcmp('Dave','Mike')
  413. -1
  414. &gt;&gt;&gt; print example.cvar.Foo
  415. 42
  416. &gt;&gt;&gt; print example.STATUS
  417. 50
  418. &gt;&gt;&gt; print example.VERSION
  419. 1.1
  420. </pre></div>
  421. <p>
  422. Whenever possible, SWIG creates an interface that closely matches the underlying C/C++
  423. code. However, due to subtle differences between languages, run-time
  424. environments, and semantics, it is not always possible to do so. The
  425. next few sections describes various aspects of this mapping.
  426. </p>
  427. <H3><a name="SWIG_nn10"></a>5.2.1 Basic Type Handling</H3>
  428. <p>
  429. In order to build an interface, SWIG has to convert C/C++ datatypes to
  430. equivalent types in the target language. Generally,
  431. scripting languages provide a more limited set of primitive types than C.
  432. Therefore, this conversion process involves a certain amount of type
  433. coercion.
  434. </p>
  435. <p>
  436. Most scripting languages provide a single integer type that is implemented using
  437. the <tt>int</tt> or <tt>long</tt> datatype in C. The following list shows
  438. all of the C datatypes that SWIG will convert to and from integers in the target language:
  439. </p>
  440. <div class="code"><pre>
  441. int
  442. short
  443. long
  444. unsigned
  445. signed
  446. unsigned short
  447. unsigned long
  448. unsigned char
  449. signed char
  450. bool
  451. </pre></div>
  452. <p>
  453. When an integral value is converted from C, a cast is used to convert it to
  454. the representation in the target language.
  455. Thus, a 16 bit short in C may be promoted to a 32 bit integer. When integers are
  456. converted in the other direction, the value is cast back into the original C type.
  457. If the value is too large to fit, it is silently truncated.
  458. <!-- Dave: Maybe we should fix this -->
  459. </p>
  460. <p>
  461. <tt>unsigned char</tt> and <tt>signed char</tt> are special cases that
  462. are handled as small 8-bit integers. Normally, the <tt>char</tt>
  463. datatype is mapped as a one-character ASCII string. </p>
  464. <p>
  465. The <tt>bool</tt> datatype is cast to and from an integer value of 0
  466. and 1 unless the target language provides a special boolean type.</p>
  467. <p>
  468. Some care is required when working with large integer values. Most
  469. scripting languages use 32-bit integers so mapping a 64-bit long
  470. integer may lead to truncation errors. Similar problems may arise with
  471. 32 bit unsigned integers (which may appear as large negative
  472. numbers). As a rule of thumb, the <tt>int</tt> datatype and all
  473. variations of <tt>char</tt> and <tt>short</tt> datatypes are safe to
  474. use. For <tt>unsigned int</tt> and <tt>long</tt> datatypes, you will
  475. need to carefully check the correct operation of your program after
  476. it has been wrapped with SWIG.
  477. </p>
  478. <p>
  479. Although the SWIG parser supports the <tt>long long</tt> datatype, not
  480. all language modules support it. This is because <tt>long long</tt>
  481. usually exceeds the integer precision available in the target
  482. language. In certain modules such as Tcl and Perl5, <tt>long
  483. long</tt> integers are encoded as strings. This allows the full range
  484. of these numbers to be represented. However, it does not allow
  485. <tt>long long</tt> values to be used in arithmetic expressions. It
  486. should also be noted that although <tt>long long</tt> is part
  487. of the ISO C99 standard, it is not universally supported by all C
  488. compilers. Make sure you are using a compiler that supports <tt>long
  489. long</tt> before trying to use this type with SWIG.
  490. </p>
  491. <p>
  492. SWIG recognizes the following floating point types :</p>
  493. <div class="code"><pre>
  494. float
  495. double
  496. </pre></div>
  497. <p>
  498. Floating point numbers are mapped to and from the natural
  499. representation of floats in the target language. This is almost always
  500. a C <tt>double</tt>. The rarely used datatype of <tt>long double</tt>
  501. is not supported by SWIG.</p>
  502. <p>
  503. The <tt>char</tt> datatype is mapped into a NULL terminated ASCII
  504. string with a single character. When used in a scripting language it
  505. shows up as a tiny string containing the character value. When
  506. converting the value back into C, SWIG takes a character string
  507. from the scripting language and strips off the first character as the
  508. char value. Thus if the value "foo" is assigned to a
  509. <tt>char</tt> datatype, it gets the value `f'.</p>
  510. <p>
  511. The <tt>char *</tt> datatype is handled as a NULL-terminated ASCII
  512. string. SWIG maps this into a 8-bit character string in the target
  513. scripting language. SWIG converts character strings in the target
  514. language to NULL terminated strings before passing them into
  515. C/C++. The default handling of these strings does not allow them to
  516. have embedded NULL bytes. Therefore, the <tt>char *</tt> datatype is
  517. not generally suitable for passing binary data. However, it is
  518. possible to change this behavior by defining a SWIG typemap. See the chapter
  519. on <a href="Typemaps.html#Typemaps">Typemaps</a> for details about this.
  520. </p>
  521. <p>
  522. At this time, SWIG provides limited support for Unicode and
  523. wide-character strings (the C <tt>wchar_t</tt> type).
  524. Some languages provide typemaps for wchar_t, but bear in mind these
  525. might not be portable across different operating systems. This is a
  526. delicate topic that is poorly understood by many programmers and not
  527. implemented in a consistent manner across languages. For those
  528. scripting languages that provide Unicode support, Unicode strings are
  529. often available in an 8-bit representation such as UTF-8 that can be
  530. mapped to the <tt>char *</tt> type (in which case the SWIG interface
  531. will probably work). If the program you are wrapping uses Unicode,
  532. there is no guarantee that Unicode characters in the target language
  533. will use the same internal representation (e.g., UCS-2 vs. UCS-4).
  534. You may need to write some special conversion functions.
  535. </p>
  536. <H3><a name="SWIG_nn11"></a>5.2.2 Global Variables</H3>
  537. <p>
  538. Whenever possible, SWIG maps C/C++ global variables into scripting language
  539. variables. For example,
  540. </p>
  541. <div class="code"><pre>
  542. %module example
  543. double foo;
  544. </pre></div>
  545. <p>
  546. results in a scripting language variable like this:
  547. </p>
  548. <div class="code"><pre>
  549. # Tcl
  550. set foo [3.5] ;# Set foo to 3.5
  551. puts $foo ;# Print the value of foo
  552. # Python
  553. cvar.foo = 3.5 # Set foo to 3.5
  554. print cvar.foo # Print value of foo
  555. # Perl
  556. $foo = 3.5; # Set foo to 3.5
  557. print $foo,"\n"; # Print value of foo
  558. # Ruby
  559. Module.foo = 3.5 # Set foo to 3.5
  560. print Module.foo, "\n" # Print value of foo
  561. </pre></div>
  562. <p>
  563. Whenever the scripting language variable is used, the underlying C
  564. global variable is accessed. Although SWIG makes every
  565. attempt to make global variables work like scripting language
  566. variables, it is not always possible to do so. For instance, in
  567. Python, all global variables must be accessed through a special
  568. variable object known as <tt>cvar</tt> (shown above). In Ruby, variables are
  569. accessed as attributes of the module. Other languages may
  570. convert variables to a pair of accessor functions. For example, the
  571. Java module generates a pair of functions <tt>double get_foo()</tt>
  572. and <tt>set_foo(double val)</tt> that are used to manipulate the
  573. value.
  574. </p>
  575. <p>
  576. Finally, if a global variable has been declared as <tt>const</tt>, it
  577. only supports read-only access. Note: this behavior is new to SWIG-1.3.
  578. Earlier versions of SWIG incorrectly handled <tt>const</tt> and created
  579. constants instead.
  580. </p>
  581. <H3><a name="SWIG_nn12"></a>5.2.3 Constants</H3>
  582. <p>
  583. Constants can be created using <tt>#define</tt>, enumerations,
  584. or a special <tt>%constant</tt> directive. The following
  585. interface file shows a few valid constant declarations :</p>
  586. <div class="code"><pre>
  587. #define I_CONST 5 // An integer constant
  588. #define PI 3.14159 // A Floating point constant
  589. #define S_CONST "hello world" // A string constant
  590. #define NEWLINE '\n' // Character constant
  591. enum boolean {NO=0, YES=1};
  592. enum months {JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG,
  593. SEP, OCT, NOV, DEC};
  594. %constant double BLAH = 42.37;
  595. #define PI_4 PI/4
  596. #define FLAGS 0x04 | 0x08 | 0x40
  597. </pre></div>
  598. <p>
  599. In <tt>#define</tt> declarations, the type of a constant is inferred
  600. by syntax. For example, a number with a decimal point is assumed to be
  601. floating point. In addition, SWIG must be able to fully resolve all
  602. of the symbols used in a <tt>#define</tt> in order for a constant to
  603. actually be created. This restriction is necessary because
  604. <tt>#define</tt> is also used to define preprocessor macros that are
  605. definitely not meant to be part of the scripting language interface.
  606. For example:
  607. </p>
  608. <div class="code">
  609. <pre>
  610. #define EXTERN extern
  611. EXTERN void foo();
  612. </pre>
  613. </div>
  614. <p>
  615. In this case, you probably don't want to create a constant called
  616. <tt>EXTERN</tt> (what would the value be?). In general,
  617. SWIG will not create constants for macros unless the value can
  618. be completely determined by the preprocessor. For instance, in the above example,
  619. the declaration
  620. </p>
  621. <div class="code">
  622. <pre>
  623. #define PI_4 PI/4
  624. </pre>
  625. </div>
  626. <p>
  627. defines a constant because <tt>PI</tt> was already defined as a
  628. constant and the value is known.
  629. However, for the same conservative reasons even a constant with a simple cast will be ignored, such as
  630. </p>
  631. <div class="code">
  632. <pre>
  633. #define F_CONST (double) 5 // A floating pointer constant with cast
  634. </pre>
  635. </div>
  636. <p>
  637. The use of constant expressions is allowed, but SWIG does not evaluate
  638. them. Rather, it passes them through to the output file and lets the C
  639. compiler perform the final evaluation (SWIG does perform a limited
  640. form of type-checking however).</p>
  641. <p>
  642. For enumerations, it is critical that the original enum definition be
  643. included somewhere in the interface file (either in a header file or
  644. in the <tt>%{,%}</tt> block). SWIG only translates the enumeration
  645. into code needed to add the constants to a scripting language. It
  646. needs the original enumeration declaration in order to get the correct
  647. enum values as assigned by the C compiler.
  648. </p>
  649. <p>
  650. The <tt>%constant</tt> directive is used to more precisely create
  651. constants corresponding to different C datatypes. Although it is not
  652. usually not needed for simple values, it is more useful when working
  653. with pointers and other more complex datatypes. Typically, <tt>%constant</tt>
  654. is only used when you want to add constants to the scripting language
  655. interface that are not defined in the original header file.
  656. </p>
  657. <H3><a name="SWIG_nn13"></a>5.2.4 A brief word about <tt>const</tt></H3>
  658. <p>
  659. A common confusion with C programming is the semantic meaning of the
  660. <tt>const</tt> qualifier in declarations--especially when it is mixed
  661. with pointers and other type modifiers. In fact, previous versions of SWIG
  662. handled <tt>const</tt> incorrectly--a situation that SWIG-1.3.7 and newer
  663. releases have fixed.
  664. </p>
  665. <p>
  666. Starting with SWIG-1.3, all variable declarations, regardless of any
  667. use of <tt>const</tt>, are wrapped as global variables. If a
  668. declaration happens to be declared as <tt>const</tt>, it is wrapped as
  669. a read-only variable. To tell if a variable is <tt>const</tt> or not,
  670. you need to look at the right-most occurrence of the <tt>const</tt>
  671. qualifier (that appears before the variable name). If the right-most
  672. <tt>const</tt> occurs after all other type modifiers (such as
  673. pointers), then the variable is <tt>const</tt>. Otherwise, it is not.
  674. </p>
  675. <p>
  676. Here are some examples of <tt>const</tt> declarations.
  677. </p>
  678. <div class="code">
  679. <pre>
  680. const char a; // A constant character
  681. char const b; // A constant character (the same)
  682. char *const c; // A constant pointer to a character
  683. const char *const d; // A constant pointer to a constant character
  684. </pre>
  685. </div>
  686. <p>
  687. Here is an example of a declaration that is not <tt>const</tt>:
  688. </p>
  689. <div class="code">
  690. <pre>
  691. const char *e; // A pointer to a constant character. The pointer
  692. // may be modified.
  693. </pre>
  694. </div>
  695. <p>
  696. In this case, the pointer <tt>e</tt> can change---it's only the value
  697. being pointed to that is read-only.
  698. </p>
  699. <p>
  700. Please note that for const parameters or return types used in a function, SWIG pretty much ignores
  701. the fact that these are const, see the section on <a href="SWIGPlus.html#SWIGPlus_const">const-correctness</a>
  702. for more information.
  703. </p>
  704. <p>
  705. <b>Compatibility Note:</b> One reason for changing SWIG to handle
  706. <tt>const</tt> declarations as read-only variables is that there are
  707. many situations where the value of a <tt>const</tt> variable might
  708. change. For example, a library might export a symbol as
  709. <tt>const</tt> in its public API to discourage modification, but still
  710. allow the value to change through some other kind of internal
  711. mechanism. Furthermore, programmers often overlook the fact that with
  712. a constant declaration like <tt>char *const</tt>, the underlying data
  713. being pointed to can be modified--it's only the pointer itself that is
  714. constant. In an embedded system, a <tt>const</tt> declaration might
  715. refer to a read-only memory address such as the location of a
  716. memory-mapped I/O device port (where the value changes, but writing to
  717. the port is not supported by the hardware). Rather than trying to
  718. build a bunch of special cases into the <tt>const</tt> qualifier, the
  719. new interpretation of <tt>const</tt> as "read-only" is simple and
  720. exactly matches the actual semantics of <tt>const</tt> in C/C++. If
  721. you really want to create a constant as in older versions of SWIG, use
  722. the <tt>%constant</tt> directive instead. For example:
  723. </p>
  724. <div class="code">
  725. <pre>
  726. %constant double PI = 3.14159;
  727. </pre>
  728. </div>
  729. <p>
  730. or
  731. </p>
  732. <div class="code">
  733. <pre>
  734. #ifdef SWIG
  735. #define const %constant
  736. #endif
  737. const double foo = 3.4;
  738. const double bar = 23.4;
  739. const int spam = 42;
  740. #ifdef SWIG
  741. #undef const
  742. #endif
  743. ...
  744. </pre>
  745. </div>
  746. <H3><a name="SWIG_nn14"></a>5.2.5 A cautionary tale of <tt>char *</tt></H3>
  747. <p>
  748. Before going any further, there is one bit of caution involving
  749. <tt>char *</tt> that must now be mentioned. When strings are passed
  750. from a scripting language to a C <tt>char *</tt>, the pointer usually
  751. points to string data stored inside the interpreter. It is almost
  752. always a really bad idea to modify this data. Furthermore, some
  753. languages may explicitly disallow it. For instance, in Python,
  754. strings are supposed be immutable. If you violate this, you will probably
  755. receive a vast amount of wrath when you unleash your module on the world.
  756. </p>
  757. <p>
  758. The primary source of problems are functions that might modify string data in place.
  759. A classic example would be a function like this:
  760. </p>
  761. <div class="code">
  762. <pre>
  763. char *strcat(char *s, const char *t)
  764. </pre>
  765. </div>
  766. <p>
  767. Although SWIG will certainly generate a wrapper for this, its behavior
  768. will be undefined. In fact, it will probably cause your application
  769. to crash with a segmentation fault or other memory related problem.
  770. This is because <tt>s</tt> refers to some internal data in the target
  771. language---data that you shouldn't be touching.
  772. </p>
  773. <p>
  774. The bottom line: don't rely on <tt>char *</tt> for anything other than read-only
  775. input values. However, it must be noted that you could change the behavior of SWIG
  776. using <a href="Typemaps.html#Typemaps">typemaps</a>.
  777. </p>
  778. <H2><a name="SWIG_nn15"></a>5.3 Pointers and complex objects</H2>
  779. <p>
  780. Most C programs manipulate arrays, structures, and other types of objects. This section
  781. discusses the handling of these datatypes.
  782. </p>
  783. <H3><a name="SWIG_nn16"></a>5.3.1 Simple pointers</H3>
  784. <p>
  785. Pointers to primitive C datatypes such as </p>
  786. <div class="code"><pre>
  787. int *
  788. double ***
  789. char **
  790. </pre></div>
  791. <p>
  792. are fully supported by SWIG. Rather than trying to convert the data being pointed to into a scripting
  793. representation, SWIG simply encodes the pointer itself into a
  794. representation that contains the actual value of the pointer and a type-tag.
  795. Thus, the SWIG representation of the above
  796. pointers (in Tcl), might look like this:</p>
  797. <div class="targetlang"><pre>
  798. _10081012_p_int
  799. _1008e124_ppp_double
  800. _f8ac_pp_char
  801. </pre></div>
  802. <p>
  803. A NULL pointer is represented by the string "NULL" or the value 0
  804. encoded with type information.</p>
  805. <p>
  806. All pointers are treated as opaque objects by SWIG. Thus, a pointer
  807. may be returned by a function and passed around to other C functions
  808. as needed. For all practical purposes, the scripting language
  809. interface works in exactly the same way as you would use the
  810. pointer in a C program. The only difference is that there is no mechanism for
  811. dereferencing the pointer since this would require the target language
  812. to understand the memory layout of the underlying object.
  813. </p>
  814. <p>
  815. The scripting language representation of a pointer value should never be
  816. manipulated directly. Even though the values shown look like hexadecimal
  817. addresses, the numbers used may differ from the actual machine address (e.g.,
  818. on little-endian machines, the digits may appear in reverse order).
  819. Furthermore, SWIG does not
  820. normally map pointers into high-level objects such as associative
  821. arrays or lists (for example, converting an
  822. <tt>int *</tt> into an list of integers). There are several reasons
  823. why SWIG does not do this:</p>
  824. <ul>
  825. <li>There is not enough information in a C declaration to properly map
  826. pointers into higher level constructs. For example, an <tt>int *</tt>
  827. may indeed be an array of integers, but if it contains ten million
  828. elements, converting it into a list object is probably a bad idea.
  829. </li>
  830. <li>The underlying semantics associated with a pointer is not known
  831. by SWIG. For instance, an <tt>int *</tt> might not be an array at all--perhaps it
  832. is an output value!
  833. </li>
  834. <li>By handling all pointers in a consistent manner, the implementation of SWIG is greatly
  835. simplified and less prone to error.
  836. </li>
  837. </ul>
  838. <H3><a name="SWIG_nn17"></a>5.3.2 Run time pointer type checking</H3>
  839. <p>
  840. By allowing pointers to be manipulated from a scripting language, extension modules
  841. effectively bypass compile-time type checking in the C/C++
  842. compiler. To prevent errors, a type signature is encoded into all
  843. pointer values and is used to perform run-time type checking. This
  844. type-checking process is an integral part of SWIG and can not be
  845. disabled or modified without using typemaps (described in later
  846. chapters).
  847. </p>
  848. <p>
  849. Like C, <tt>void *</tt> matches any kind of pointer. Furthermore,
  850. <tt>NULL</tt> pointers can be passed to any function that expects to
  851. receive a pointer. Although this has the potential to cause a crash,
  852. <tt>NULL</tt> pointers are also sometimes used
  853. as sentinel values or to denote a missing/empty value. Therefore,
  854. SWIG leaves NULL pointer checking up to the application.
  855. </p>
  856. <H3><a name="SWIG_nn18"></a>5.3.3 Derived types, structs, and classes</H3>
  857. <p>
  858. For everything else (structs, classes, arrays, etc...) SWIG applies a
  859. very simple rule :</p>
  860. <center>
  861. <b>Everything else is a pointer</b>
  862. </center>
  863. <p>
  864. In other words, SWIG manipulates everything else by reference. This
  865. model makes sense because most C/C++ programs make heavy use of
  866. pointers and SWIG can use the type-checked pointer mechanism already
  867. present for handling pointers to basic datatypes.</p>
  868. <p>
  869. Although this probably sounds complicated, it's really quite
  870. simple. Suppose you have an interface file like this :</p>
  871. <div class="code"><pre>
  872. %module fileio
  873. FILE *fopen(char *, char *);
  874. int fclose(FILE *);
  875. unsigned fread(void *ptr, unsigned size, unsigned nobj, FILE *);
  876. unsigned fwrite(void *ptr, unsigned size, unsigned nobj, FILE *);
  877. void *malloc(int nbytes);
  878. void free(void *);
  879. </pre></div>
  880. <p>
  881. In this file, SWIG doesn't know what a <tt>FILE</tt> is, but since it's used
  882. as a pointer, so it doesn't really matter what it is. If you wrapped
  883. this module into Python, you can use the functions just like you
  884. expect :</p>
  885. <div class="targetlang"><pre>
  886. # Copy a file
  887. def filecopy(source,target):
  888. f1 = fopen(source,"r")
  889. f2 = fopen(target,"w")
  890. buffer = malloc(8192)
  891. nbytes = fread(buffer,8192,1,f1)
  892. while (nbytes &gt; 0):
  893. fwrite(buffer,8192,1,f2)
  894. nbytes = fread(buffer,8192,1,f1)
  895. free(buffer)
  896. </pre></div>
  897. <p>
  898. In this case <tt>f1</tt>,<tt> f2</tt>, and <tt>buffer</tt> are all
  899. opaque objects containing C pointers. It doesn't matter what value
  900. they contain--our program works just fine without this knowledge.</p>
  901. <H3><a name="SWIG_nn19"></a>5.3.4 Undefined datatypes</H3>
  902. <p>
  903. When SWIG encounters an undeclared datatype, it automatically assumes
  904. that it is a structure or class. For example, suppose the following
  905. function appeared in a SWIG input file:</p>
  906. <div class="code"><pre>
  907. void matrix_multiply(Matrix *a, Matrix *b, Matrix *c);
  908. </pre></div>
  909. <p>
  910. SWIG has no idea what a "<tt>Matrix</tt>" is. However, it is obviously
  911. a pointer to something so SWIG generates a wrapper using its generic pointer
  912. handling code.
  913. </p>
  914. <p>
  915. Unlike C or C++, SWIG does not actually care whether <tt>Matrix</tt>
  916. has been previously defined in the interface file or not. This
  917. allows SWIG to generate interfaces from
  918. only partial or limited information. In some cases, you may not care
  919. what a <tt>Matrix</tt> really is as long as you can pass an opaque reference to
  920. one around in the scripting language interface.
  921. </p>
  922. <p>
  923. An important detail to mention is that SWIG will gladly generate
  924. wrappers for an interface when there are unspecified type names.
  925. However, <b>all unspecified types are internally handled as pointers
  926. to structures or classes!</b> For example, consider the following declaration:
  927. </p>
  928. <div class="code">
  929. <pre>
  930. void foo(size_t num);
  931. </pre>
  932. </div>
  933. <p>
  934. If <tt>size_t</tt> is undeclared, SWIG generates wrappers
  935. that expect to receive a type of <tt>size_t *</tt> (this mapping is described shortly).
  936. As a result, the scripting interface might behave strangely. For example:
  937. </p>
  938. <div class="code">
  939. <pre>
  940. foo(40);
  941. TypeError: expected a _p_size_t.
  942. </pre>
  943. </div>
  944. <p>
  945. The only way to fix this problem is to make sure you properly declare type names using
  946. <tt>typedef</tt>.
  947. </p>
  948. <!-- We might want to add an error reporting flag to swig -->
  949. <H3><a name="SWIG_nn20"></a>5.3.5 Typedef</H3>
  950. <p>
  951. Like C, <tt>typedef</tt> can be used to define new type names in SWIG. For example:
  952. </p>
  953. <div class="code"><pre>
  954. typedef unsigned int size_t;
  955. </pre></div>
  956. <p>
  957. <tt>typedef</tt> definitions appearing in a SWIG interface
  958. are not propagated to the generated wrapper code. Therefore, they
  959. either need to be defined in an included header file or placed in the
  960. declarations section like this:
  961. </p>
  962. <div class="code">
  963. <pre>
  964. %{
  965. /* Include in the generated wrapper file */
  966. typedef unsigned int size_t;
  967. %}
  968. /* Tell SWIG about it */
  969. typedef unsigned int size_t;
  970. </pre>
  971. </div>
  972. <p>
  973. or
  974. </p>
  975. <div class="code">
  976. <pre>
  977. %inline %{
  978. typedef unsigned int size_t;
  979. %}
  980. </pre>
  981. </div>
  982. <p>
  983. In certain cases, you might be able to include other header files to collect type information.
  984. For example:
  985. </p>
  986. <div class="code">
  987. <pre>
  988. %module example
  989. %import "sys/types.h"
  990. </pre>
  991. </div>
  992. <p>
  993. In this case, you might run SWIG as follows:
  994. </p>
  995. <div class="shell">
  996. <pre>
  997. $ swig -I/usr/include -includeall example.i
  998. </pre>
  999. </div>
  1000. <p>
  1001. It should be noted that your mileage will vary greatly here.
  1002. System headers are notoriously complicated and may rely upon a variety
  1003. of non-standard C coding extensions (e.g., such as special directives
  1004. to GCC). Unless you exactly specify the right include directories and
  1005. preprocessor symbols, this may not work correctly (you will have to
  1006. experiment).
  1007. </p>
  1008. <p>
  1009. SWIG tracks <tt>typedef</tt> declarations and uses this information
  1010. for run-time type checking. For instance, if you use the above <tt>typedef</tt> and
  1011. had the following function declaration:
  1012. </p>
  1013. <div class="code">
  1014. <pre>
  1015. void foo(unsigned int *ptr);
  1016. </pre>
  1017. </div>
  1018. <p>
  1019. The corresponding wrapper function will accept arguments of
  1020. type <tt>unsigned int *</tt> or <tt>size_t *</tt>.
  1021. </p>
  1022. <H2><a name="SWIG_nn21"></a>5.4 Other Practicalities</H2>
  1023. <p>
  1024. So far, this chapter has presented almost everything you need to know to use SWIG
  1025. for simple interfaces. However, some C programs use idioms that are somewhat
  1026. more difficult to map to a scripting language interface. This section describes
  1027. some of these issues.
  1028. </p>
  1029. <H3><a name="SWIG_nn22"></a>5.4.1 Passing structures by value</H3>
  1030. <p>
  1031. Sometimes a C function takes structure parameters that are passed
  1032. by value. For example, consider the following function:
  1033. </p>
  1034. <div class="code"><pre>
  1035. double dot_product(Vector a, Vector b);
  1036. </pre></div>
  1037. <p>
  1038. To deal with this, SWIG transforms the function to use pointers by
  1039. creating a wrapper equivalent to the following:
  1040. </p>
  1041. <div class="code"><pre>
  1042. double wrap_dot_product(Vector *a, Vector *b) {
  1043. Vector x = *a;
  1044. Vector y = *b;
  1045. return dot_product(x,y);
  1046. }
  1047. </pre></div>
  1048. <p>
  1049. In the target language, the <tt>dot_product()</tt> function now accepts pointers
  1050. to Vectors instead of Vectors. For the most part, this transformation
  1051. is transparent so you might not notice.
  1052. </p>
  1053. <H3><a name="SWIG_nn23"></a>5.4.2 Return by value</H3>
  1054. <p>
  1055. C functions that return structures or classes datatypes by value are more difficult
  1056. to handle. Consider the following function:</p>
  1057. <div class="code"><pre>
  1058. Vector cross_product(Vector v1, Vector v2);
  1059. </pre></div>
  1060. <p>
  1061. This function wants to return <tt>Vector</tt>, but SWIG only really supports
  1062. pointers. As a result, SWIG creates a wrapper like this:
  1063. </p>
  1064. <div class="code"><pre>
  1065. Vector *wrap_cross_product(Vector *v1, Vector *v2) {
  1066. Vector x = *v1;
  1067. Vector y = *v2;
  1068. Vector *result;
  1069. result = (Vector *) malloc(sizeof(Vector));
  1070. *(result) = cross(x,y);
  1071. return result;
  1072. }
  1073. </pre></div>
  1074. <p>
  1075. or if SWIG was run with the <tt>-c++</tt> option:</p>
  1076. <div class="code"><pre>
  1077. Vector *wrap_cross(Vector *v1, Vector *v2) {
  1078. Vector x = *v1;
  1079. Vector y = *v2;
  1080. Vector *result = new Vector(cross(x,y)); // Uses default copy constructor
  1081. return result;
  1082. }
  1083. </pre></div>
  1084. <p>
  1085. In both cases, SWIG allocates a new object and returns a reference to it. It
  1086. is up to the user to delete the returned object when it is no longer
  1087. in use. Clearly, this will leak memory if you are unaware of the implicit
  1088. memory allocation and don't take steps to free the result. That said, it should be
  1089. noted that some language modules can now automatically track newly created objects and
  1090. reclaim memory for you. Consult the documentation for each language module for more details.
  1091. </p>
  1092. <p>
  1093. It should also be noted that the handling of pass/return by value in
  1094. C++ has some special cases. For example, the above code fragments
  1095. don't work correctly if <tt>Vector</tt> doesn't define a default
  1096. constructor. The section on SWIG and C++ has more information about this case.
  1097. </p>
  1098. <H3><a name="SWIG_nn24"></a>5.4.3 Linking to structure variables</H3>
  1099. <p>
  1100. When global variables or class members involving structures are
  1101. encountered, SWIG handles them as pointers. For example, a global
  1102. variable like this</p>
  1103. <div class="code"><pre>
  1104. Vector unit_i;
  1105. </pre></div>
  1106. <p>
  1107. gets mapped to an underlying pair of set/get functions like this :</p>
  1108. <div class="code"><pre>
  1109. Vector *unit_i_get() {
  1110. return &amp;unit_i;
  1111. }
  1112. void unit_i_set(Vector *value) {
  1113. unit_i = *value;
  1114. }
  1115. </pre></div>
  1116. <p>
  1117. Again some caution is in order. A global variable created in this
  1118. manner will show up as a pointer in the target scripting language. It
  1119. would be an extremely bad idea to free or destroy such a pointer. Also,
  1120. C++ classes must supply a properly defined copy constructor in order for
  1121. assignment to work correctly.
  1122. </p>
  1123. <H3><a name="SWIG_nn25"></a>5.4.4 Linking to <tt>char *</tt></H3>
  1124. <p>
  1125. When a global variable of type <tt>char *</tt> appears, SWIG uses <tt>malloc()</tt> or
  1126. <tt>new</tt> to allocate memory for the new value. Specifically, if you have a variable
  1127. like this
  1128. </p>
  1129. <div class="code">
  1130. <pre>
  1131. char *foo;
  1132. </pre>
  1133. </div>
  1134. <p>
  1135. SWIG generates the following code:
  1136. </p>
  1137. <div class="code">
  1138. <pre>
  1139. /* C mode */
  1140. void foo_set(char *value) {
  1141. if (foo) free(foo);
  1142. foo = (char *) malloc(strlen(value)+1);
  1143. strcpy(foo,value);
  1144. }
  1145. /* C++ mode. When -c++ option is used */
  1146. void foo_set(char *value) {
  1147. if (foo) delete [] foo;
  1148. foo = new char[strlen(value)+1];
  1149. strcpy(foo,value);
  1150. }
  1151. </pre>
  1152. </div>
  1153. <p>
  1154. If this is not the behavior that you want, consider making the variable read-only using the
  1155. <tt>%immutable</tt> directive. Alternatively, you might write a short assist-function to set the value
  1156. exactly like you want. For example:
  1157. </p>
  1158. <div class="code">
  1159. <pre>
  1160. %inline %{
  1161. void set_foo(char *value) {
  1162. strncpy(foo,value, 50);
  1163. }
  1164. %}
  1165. </pre>
  1166. </div>
  1167. <p>
  1168. Note: If you write an assist function like this, you will have to call
  1169. it as a function from the target scripting language (it does not work
  1170. like a variable). For example, in Python you will have to write:
  1171. </p>
  1172. <div class="targetlang">
  1173. <pre>
  1174. &gt;&gt;&gt; set_foo("Hello World")
  1175. </pre>
  1176. </div>
  1177. <p>
  1178. A common mistake with <tt>char *</tt> variables is to link to a variable declared like this:
  1179. </p>
  1180. <div class="code">
  1181. <pre>
  1182. char *VERSION = "1.0";
  1183. </pre>
  1184. </div>
  1185. <p>
  1186. In this case, the variable will be readable, but any attempt to change
  1187. the value results in a segmentation or general protection fault. This
  1188. is due to the fact that SWIG is trying to release the old value using
  1189. <tt>free</tt> or <tt>delete</tt> when the string literal value currently assigned to the variable wasn't
  1190. allocated using <tt>malloc()</tt> or <tt>new</tt>.
  1191. To fix this behavior, you can
  1192. either mark the variable as read-only, write a typemap (as described in Chapter 6),
  1193. or write a special set function as shown. Another alternative is to declare the
  1194. variable as an array:
  1195. </p>
  1196. <div class="code">
  1197. <pre>
  1198. char VERSION[64] = "1.0";
  1199. </pre>
  1200. </div>
  1201. <p>
  1202. When variables of type <tt>const char *</tt> are declared, SWIG still generates functions for setting and
  1203. getting the value. However, the default behavior does <em>not</em> release the previous contents (resulting in
  1204. a possible memory leak). In fact, you may get a warning message such as this when wrapping such a variable:
  1205. </p>
  1206. <div class="shell">
  1207. <pre>
  1208. example.i:20. Typemap warning. Setting const char * variable may leak memory
  1209. </pre>
  1210. </div>
  1211. <p>
  1212. The reason for this behavior is that <tt>const char *</tt> variables are often used to point to string literals.
  1213. For example:
  1214. </p>
  1215. <div class="code">
  1216. <pre>
  1217. const char *foo = "Hello World\n";
  1218. </pre>
  1219. </div>
  1220. <p>
  1221. Therefore, it's a really bad idea to call <tt>free()</tt> on such a
  1222. pointer. On the other hand, it <em>is</em> legal to change the
  1223. pointer to point to some other value. When setting a variable of this
  1224. type, SWIG allocates a new string (using malloc or new) and changes
  1225. the pointer to point to the new value. However, repeated
  1226. modifications of the value will result in a memory leak since the old
  1227. value is not released.
  1228. </p>
  1229. <H3><a name="SWIG_nn26"></a>5.4.5 Arrays</H3>
  1230. <p>
  1231. Arrays are fully supported by SWIG, but they are always handled as pointers instead
  1232. of mapping them to a special array object or list in the target language. Thus, the
  1233. following declarations :</p>
  1234. <div class="code"><pre>
  1235. int foobar(int a[40]);
  1236. void grok(char *argv[]);
  1237. void transpose(double a[20][20]);
  1238. </pre></div>
  1239. <p>
  1240. are processed as if they were really declared like this:
  1241. </p>
  1242. <div class="code"><pre>
  1243. int foobar(int *a);
  1244. void grok(char **argv);
  1245. void transpose(double (*a)[20]);
  1246. </pre></div>
  1247. <p>
  1248. Like C, SWIG does not perform array bounds checking.
  1249. It is up to the
  1250. user to make sure the pointer points a suitably allocated region of memory.
  1251. </p>
  1252. <p>
  1253. Multi-dimensional arrays are transformed into a pointer to an array of one less
  1254. dimension. For example:
  1255. </p>
  1256. <div class="code">
  1257. <pre>
  1258. int [10]; // Maps to int *
  1259. int [10][20]; // Maps to int (*)[20]
  1260. int [10][20][30]; // Maps to int (*)[20][30]
  1261. </pre>
  1262. </div>
  1263. <p>
  1264. It is important to note that in the C type system, a multidimensional
  1265. array <tt>a[][]</tt> is <b>NOT</b> equivalent to a single pointer
  1266. <tt>*a</tt> or a double pointer such as <tt>**a</tt>. Instead, a
  1267. pointer to an array is used (as shown above) where the actual value of
  1268. the pointer is the starting memory location of the array. The
  1269. reader is strongly advised to dust off their C book and re-read the
  1270. section on arrays before using them with SWIG.
  1271. </p>
  1272. <p>
  1273. Array variables are supported, but are read-only by default. For example:
  1274. </p>
  1275. <div class="code">
  1276. <pre>
  1277. int a[100][200];
  1278. </pre>
  1279. </div>
  1280. <p>
  1281. In this case, reading the variable 'a' returns a pointer of type <tt>int (*)[200]</tt>
  1282. that points to the first element of the array <tt>&amp;a[0][0]</tt>. Trying to modify 'a' results
  1283. in an error. This is because SWIG does not know how to copy data from the target
  1284. language into the array. To work around this limitation, you may want to write
  1285. a few simple assist functions like this:
  1286. </p>
  1287. <div class="code">
  1288. <pre>
  1289. %inline %{
  1290. void a_set(int i, int j, int val) {
  1291. a[i][j] = val;
  1292. }
  1293. int a_get(int i, int j) {
  1294. return a[i][j];
  1295. }
  1296. %}
  1297. </pre>
  1298. </div>
  1299. <p>
  1300. To dynamically create arrays of various sizes and shapes, it may be useful to write
  1301. some helper functions in your interface. For example:
  1302. </p>
  1303. <div class="code">
  1304. <pre>
  1305. // Some array helpers
  1306. %inline %{
  1307. /* Create any sort of [size] array */
  1308. int *int_array(int size) {
  1309. return (int *) malloc(size*sizeof(int));
  1310. }
  1311. /* Create a two-dimension array [size][10] */
  1312. int (*int_array_10(int size))[10] {
  1313. return (int (*)[10]) malloc(size*10*sizeof(int));
  1314. }
  1315. %}
  1316. </pre>
  1317. </div>
  1318. <p>
  1319. Arrays of <tt>char</tt> are handled as a special case by SWIG. In this case, strings in the
  1320. target language can be stored in the array. For example, if you have a declaration like this,
  1321. </p>
  1322. <div class="code">
  1323. <pre>
  1324. char pathname[256];
  1325. </pre>
  1326. </div>
  1327. <p>
  1328. SWIG generates functions for both getting and setting the value that are equivalent to the following
  1329. code:
  1330. </p>
  1331. <div class="code">
  1332. <pre>
  1333. char *pathname_get() {
  1334. return pathname;
  1335. }
  1336. void pathname_set(char *value) {
  1337. strncpy(pathname,value,256);
  1338. }
  1339. </pre>
  1340. </div>
  1341. <p>
  1342. In the target language, the value can be set like a normal variable.
  1343. </p>
  1344. <H3><a name="SWIG_readonly_variables"></a>5.4.6 Creating read-only variables</H3>
  1345. <p>
  1346. A read-only variable can be created by using the <tt>%immutable</tt>
  1347. directive as shown :</p>
  1348. <div class="code"><pre>
  1349. // File : interface.i
  1350. int a; // Can read/write
  1351. %immutable;
  1352. int b,c,d // Read only variables
  1353. %mutable;
  1354. double x,y // read/write
  1355. </pre></div>
  1356. <p>
  1357. The <tt>%immutable</tt> directive enables read-only mode until it is
  1358. explicitly disabled using the <tt>%mutable</tt> directive. As an alternative to turning
  1359. read-only mode off and on like this, individual declarations can also be tagged as
  1360. immutable. For example:
  1361. </p>
  1362. <div class="code"><pre>
  1363. %immutable x; // Make x read-only
  1364. ...
  1365. double x; // Read-only (from earlier %immutable directive)
  1366. double y; // Read-write
  1367. ...
  1368. </pre></div>
  1369. <p>
  1370. The <tt>%mutable</tt> and <tt>%immutable</tt> directives are actually
  1371. <a href="Customization.html#Customization_features">%feature directives</a> defined like this:
  1372. </p>
  1373. <div class="code"><pre>
  1374. #define %immutable %feature("immutable")
  1375. #define %mutable %feature("immutable","")
  1376. </pre></div>
  1377. <p>
  1378. If you wanted to make all wrapped variables read-only, barring one or two, it might be easier to take this approach:
  1379. </p>
  1380. <div class="code"><pre>
  1381. %immutable; // Make all variables read-only
  1382. %feature("immutable","0") x; // except, make x read/write
  1383. ...
  1384. double x;
  1385. double y;
  1386. double z;
  1387. ...
  1388. </pre></div>
  1389. <p>
  1390. Read-only variables are also created when declarations are declared as <tt>const</tt>.
  1391. For example:
  1392. </p>
  1393. <div class="code">
  1394. <pre>
  1395. const int foo; /* Read only variable */
  1396. char * const version="1.0"; /* Read only variable */
  1397. </pre></div>
  1398. <p>
  1399. <b>Compatibility note:</b> Read-only access used to be controlled by a pair of directives
  1400. <tt>%readonly</tt> and <tt>%readwrite</tt>. Although these directives still work, they
  1401. generate a warning message. Simply change the directives to <tt>%immutable;</tt> and
  1402. <tt>%mutable;</tt> to silence the warning. Don't forget the extra semicolon!
  1403. </p>
  1404. <H3><a name="SWIG_rename_ignore"></a>5.4.7 Renaming and ignoring declarations</H3>
  1405. <H4><a name="SWIG_nn29"></a>5.4.7.1 Simple renaming of specific identifiers</H4>
  1406. <p>
  1407. Normally, the name of a C declaration is used when that declaration is
  1408. wrapped into the target language. However, this may generate a
  1409. conflict with a keyword or already existing function in the scripting
  1410. language. To resolve a name conflict, you can use the <tt>%rename</tt>
  1411. directive as shown :</p>
  1412. <div class="code"><pre>
  1413. // interface.i
  1414. %rename(my_print) print;
  1415. extern void print(const char *);
  1416. %rename(foo) a_really_long_and_annoying_name;
  1417. extern int a_really_long_and_annoying_name;
  1418. </pre></div>
  1419. <p>
  1420. SWIG still calls the correct C function, but in this case the
  1421. function <tt>print()</tt> will really be called "<tt>my_print()</tt>"
  1422. in the target language. </p>
  1423. <p>
  1424. The placement of the <tt>%rename</tt> directive is arbitrary as long as it appears
  1425. before the declarations to be renamed. A common technique is to write code for
  1426. wrapping a header file like this:
  1427. </p>
  1428. <div class="code"><pre>
  1429. // interface.i
  1430. %rename(my_print) print;
  1431. %rename(foo) a_really_long_and_annoying_name;
  1432. %include "header.h"
  1433. </pre></div>
  1434. <p>
  1435. <tt>%rename </tt>applies a renaming operation to all future
  1436. occurrences of a name. The renaming applies to functions, variables,
  1437. class and structure names, member functions, and member data. For
  1438. example, if you had two-dozen C++ classes, all with a member function
  1439. named `print' (which is a keyword in Python), you could rename them
  1440. all to `output' by specifying :</p>
  1441. <div class="code"><pre>
  1442. %rename(output) print; // Rename all `print' functions to `output'
  1443. </pre></div>
  1444. <p>
  1445. SWIG does not normally perform any checks to see if the functions it wraps are
  1446. already defined in the target scripting language. However, if you are
  1447. careful about namespaces and your use of modules, you can usually
  1448. avoid these problems.</p>
  1449. <p>
  1450. Closely related to <tt>%rename</tt> is the <tt>%ignore</tt> directive. <tt>%ignore</tt> instructs SWIG
  1451. to ignore declarations that match a given identifier. For example:
  1452. </p>
  1453. <div class="code">
  1454. <pre>
  1455. %ignore print; // Ignore all declarations named print
  1456. %ignore MYMACRO; // Ignore a macro
  1457. ...
  1458. #define MYMACRO 123
  1459. void print(const char *);
  1460. ...
  1461. </pre>
  1462. </div>
  1463. <p>
  1464. Any function, variable etc which matches <tt>%ignore</tt> will not be wrapped and therefore will not be available from the target language.
  1465. A common usage of <tt>%ignore</tt> is to selectively remove certain declarations from a header file without having
  1466. to add conditional compilation to the header. However, it should be stressed that this only works for simple
  1467. declarations. If you need to remove a whole section of problematic code, the SWIG preprocessor should be used instead.
  1468. </p>
  1469. <p>
  1470. <b>Compatibility note: </b> Older versions of SWIG provided a special <tt>%name</tt> directive for renaming declarations.
  1471. For example:
  1472. </p>
  1473. <div class="code">
  1474. <pre>
  1475. %name(output) extern void print(const char *);
  1476. </pre>
  1477. </div>
  1478. <p>
  1479. This directive is still supported, but it is deprecated and should probably be avoided. The <tt>%rename</tt>
  1480. directive is more powerful and better supports wrapping of raw header file information.
  1481. </p>
  1482. <H4><a name="SWIG_advanced_renaming"></a>5.4.7.2 Advanced renaming support</H4>
  1483. <p>
  1484. While writing <tt>%rename</tt> for specific declarations is simple enough,
  1485. sometimes the same renaming rule needs to be applied to many, maybe all,
  1486. identifiers in the SWIG input. For example, it may be necessary to apply some
  1487. transformation to all the names in the target language to better follow its
  1488. naming conventions, like adding a specific prefix to all wrapped functions. Doing it individually
  1489. for each function is impractical so SWIG supports applying a renaming rule to
  1490. all declarations if the name of the identifier to be renamed is not specified:
  1491. </p>
  1492. <div class="code">
  1493. <pre>
  1494. %rename("myprefix_%s") ""; // print&nbsp;-&gt;&nbsp;myprefix_print
  1495. </pre>
  1496. </div>
  1497. <p>
  1498. This also shows that the argument of <tt>%rename</tt> doesn't have to be a
  1499. literal string but can be a <tt>printf()</tt>-like format string. In the
  1500. simplest form, <tt>"%s"</tt> is replaced with the name of the original
  1501. declaration, as shown above. However this is not always enough and SWIG
  1502. provides extensions to the usual format string syntax to allow applying a
  1503. (SWIG-defined) function to the argument. For example, to wrap all C functions
  1504. <tt>do_something_long()</tt> as more Java-like <tt>doSomethingLong()</tt> you
  1505. can use the <tt>"lowercamelcase"</tt> extended format specifier like this:
  1506. </p>
  1507. <div class="code">
  1508. <pre>
  1509. %rename("%(lowercamelcase)s") ""; // foo_bar -&gt; fooBar; FooBar -&gt; fooBar
  1510. </pre>
  1511. </div>
  1512. <p>
  1513. Some functions can be parametrized, for example the <tt>"strip"</tt> one
  1514. strips the provided prefix from its argument. The prefix is specified as part
  1515. of the format string, following a colon after the function name:
  1516. </p>
  1517. <div class="code">
  1518. <pre>
  1519. %rename("%(strip:[wx])s") ""; // wxHello -&gt; Hello; FooBar -&gt; FooBar
  1520. </pre>
  1521. </div>
  1522. <p>
  1523. Below is the table summarizing all currently defined functions with an example
  1524. of applying each one. Note that some of them have two names, a shorter one
  1525. and a more descriptive one, but the two functions are otherwise equivalent:
  1526. </p>
  1527. <table summary="Format string functions" border="1" cellpadding="5">
  1528. <tr>
  1529. <th>Function</th><th>Returns</th><th colspan=2>Example (in/out)</th>
  1530. </tr>
  1531. <tr>
  1532. <td><tt>uppercase</tt> or <tt>upper</tt></td>
  1533. <td>Upper case version of the string.</td>
  1534. <td><tt>Print</tt></td><td><tt>PRINT</tt></td>
  1535. </tr>
  1536. <tr>
  1537. <td><tt>lowercase</tt> or <tt>lower</tt></td>
  1538. <td>Lower case version of the string.</td>
  1539. <td><tt>Print</tt></td><td><tt>print</tt></td>
  1540. </tr>
  1541. <tr>
  1542. <td><tt>title</tt></td>
  1543. <td>String with first letter capitalized and the rest in lower case.</td>
  1544. <td><tt>print</tt></td><td><tt>Print</tt></td>
  1545. </tr>
  1546. <tr>
  1547. <td><tt>firstuppercase</tt></td>
  1548. <td>String with the first letter capitalized and the rest unchanged.</td>
  1549. <td><tt>printIt</tt></td><td><tt>PrintIt</tt></td>
  1550. </tr>
  1551. <tr>
  1552. <td><tt>firstlowercase</tt></td>
  1553. <td>String with the first letter in lower case and the rest unchanged.</td>
  1554. <td><tt>PrintIt</tt></td><td><tt>printIt</tt></td>
  1555. </tr>
  1556. <tr>
  1557. <td><tt>camelcase</tt> or <tt>ctitle</tt></td>
  1558. <td>String with capitalized first letter and any letter following an
  1559. underscore (which are removed in the process) and rest in lower case.</td>
  1560. <td><tt>print_it</tt></td><td><tt>PrintIt</tt></td>
  1561. </tr>
  1562. <tr>
  1563. <td><tt>lowercamelcase</tt> or <tt>lctitle</tt></td>
  1564. <td>String with every letter following an underscore (which is removed in
  1565. the process) capitalized and rest, including the first letter, in lower
  1566. case.</td>
  1567. <td><tt>print_it</tt></td><td><tt>printIt</tt></td>
  1568. </tr>
  1569. <tr>
  1570. <td><tt>undercase</tt> or <tt>utitle</tt></td>
  1571. <td>Lower case string with underscores inserted before every upper case
  1572. letter in the original string and any number not at the end of string.
  1573. Logically, this is the reverse of <tt>camelcase</tt>.</td>
  1574. <td><tt>PrintIt</tt></td><td><tt>print_it</tt></td>
  1575. </tr>
  1576. <tr>
  1577. <td><tt>schemify</tt></td>
  1578. <td>String with all underscores replaced with dashes, resulting in more
  1579. Lispers/Schemers-pleasing name.</td>
  1580. <td><tt>print_it</tt></td><td><tt>print-it</tt></td>
  1581. </tr>
  1582. <tr>
  1583. <td><tt>strip:[prefix]</tt></td>
  1584. <td>String without the given prefix or the original string if it doesn't
  1585. start with this prefix. Note that square brackets should be used
  1586. literally, e.g. <tt>%rename("strip:[wx]")</tt></td>
  1587. <td><tt>wxPrint</tt></td><td><tt>Print</tt></td>
  1588. </tr>
  1589. <tr>
  1590. <td><span style="white-space: nowrap;"><tt>regex:/pattern/subst/</tt></span></td>
  1591. <td>String after (Perl-like) regex substitution operation. This function
  1592. allows to apply arbitrary regular expressions to the identifier names. The
  1593. <i>pattern</i> part is a regular expression in Perl syntax (as supported
  1594. by the <a href="http://www.pcre.org/">Perl Compatible Regular Expressions (PCRE)</a>)
  1595. library and the <i>subst</i> string
  1596. can contain back-references introduced by <tt>'\'</tt> or, as backslashes need
  1597. to be escaped in C strings, rather by <tt>"\\"</tt>. For example, to remove
  1598. any alphabetic prefix before an underscore you could use the following directive:
  1599. <tt>%rename("regex:/(\\w+)_(.*)/\\2/")</tt></td>
  1600. <td><tt>Prefix_Print</tt></td><td><tt>Print</tt></td>
  1601. </tr>
  1602. <tr>
  1603. <td><tt>command:cmd</tt></td>
  1604. <td>Output of an external command <tt>cmd</tt> with the string passed to
  1605. it as input. Notice that this function is extremely slow compared to all
  1606. the other ones as it involves spawning a separate process and using it for
  1607. many declarations is not recommended. The <i>cmd</i> is not enclosed in
  1608. square brackets but must be terminated with a triple <tt>'&lt;'</tt> sign,
  1609. e.g. <tt>%rename("command:tr&nbsp;-d&nbsp;aeiou &lt;&lt;&lt;")</tt>
  1610. (nonsensical example removing all vowels)</td>
  1611. <td><tt>Print</tt></td><td><tt>Prnt</tt></td>
  1612. </tr>
  1613. </table>
  1614. <p>
  1615. The most general function of all of the above ones (not counting
  1616. <tt>command</tt> which is even more powerful in principle but which should
  1617. generally be avoided because of performance considerations) is the
  1618. <tt>regex</tt> one. Here are some more examples of its use:
  1619. </p>
  1620. <div class="code">
  1621. <pre>
  1622. // Strip the wx prefix from all identifiers except those starting with wxEVT
  1623. %rename("%(regex:/wx(?!EVT)(.*)/\\1/)s") ""; // wxSomeWidget -&gt; SomeWidget
  1624. // wxEVT_PAINT -&gt; wxEVT_PAINT
  1625. // Apply a rule for renaming the enum elements to avoid the common prefixes
  1626. // which are redundant in C#/Java
  1627. %rename("%(regex:/^([A-Z][a-z]+)+_(.*)/\\2/)s", %$isenumitem) ""; // Colour_Red -&gt; Red
  1628. // Remove all "Set/Get" prefixes.
  1629. %rename("%(regex:/^(Set|Get)(.*)/\\2/)s") ""; // SetValue -&gt; Value
  1630. // GetValue -&gt; Value
  1631. </pre>
  1632. </div>
  1633. <p>
  1634. As before, everything that was said above about <tt>%rename</tt> also applies to
  1635. <tt>%ignore</tt>. In fact, the latter is just a special case of the former and
  1636. ignoring an identifier is the same as renaming it to the special
  1637. <tt>"$ignore"</tt> value. So the following snippets
  1638. </p>
  1639. <div class="code">
  1640. <pre>
  1641. %ignore print;
  1642. </pre>
  1643. </div>
  1644. <p>
  1645. and
  1646. </p>
  1647. <div class="code">
  1648. <pre>
  1649. %rename("$ignore") print;
  1650. </pre>
  1651. </div>
  1652. <p>
  1653. are exactly equivalent and <tt>%rename</tt> can be used to selectively ignore
  1654. multiple declarations using the previously described matching possibilities.
  1655. </p>
  1656. <H4><a name="SWIG_limiting_renaming"></a>5.4.7.3 Limiting global renaming rules</H4>
  1657. <p>
  1658. As explained in the previous sections, it is possible to either rename
  1659. individual declarations or apply a rename rule to all of them at once. In
  1660. practice, the latter is however rarely appropriate as there are always some
  1661. exceptions to the general rules. To deal with them, the scope of an unnamed
  1662. <tt>%rename</tt> can be limited using subsequent <tt>match</tt> parameters.
  1663. They can be applied to any of the attributes associated by SWIG with the
  1664. declarations appearing in its input. For example:
  1665. </p>
  1666. <div class="code">
  1667. <pre>
  1668. %rename("foo", match$name="bar") "";
  1669. </pre>
  1670. </div>
  1671. <p>
  1672. can be used to achieve the same effect as the simpler
  1673. </p>
  1674. <div class="code">
  1675. <pre>
  1676. %rename("foo") bar;
  1677. </pre>
  1678. </div>
  1679. <p>
  1680. and so is not very interesting on its own. However <tt>match</tt> can also be
  1681. applied to the declaration type, for example <tt>match="class"</tt> restricts
  1682. the match to class declarations only (in C++) and <tt>match="enumitem"</tt>
  1683. restricts it to the enum elements. SWIG also provides convenience macros for
  1684. such match expressions, for example
  1685. </p>
  1686. <div class="code">
  1687. <pre>
  1688. %rename("%(title)s", %$isenumitem) "";
  1689. </pre>
  1690. </div>
  1691. <p>
  1692. will capitalize the names of all the enum elements but not change the case of
  1693. the other declarations. Similarly, <tt>%$isclass</tt>, <tt>%$isfunction</tt>,
  1694. <tt>%$isconstructor</tt>, <tt>%$isunion</tt>, <tt>%$istemplate</tt>,
  1695. and <tt>%$isvariable</tt> can be used. Many other checks are possible and this
  1696. documentation is not exhaustive, see the "%rename predicates" section in
  1697. <tt>swig.swg</tt> for the full list of supported match expressions.
  1698. </p>
  1699. <p>
  1700. In addition to literally matching some string with <tt>match</tt> you can
  1701. also use <tt>regexmatch</tt> or <tt>notregexmatch</tt> to match a string
  1702. against a regular expression. For example, to ignore all functions having
  1703. "Old" as a suffix you could use
  1704. </p>
  1705. <div class="code">
  1706. <pre>
  1707. %rename("$ignore", regexmatch$name="Old$") "";
  1708. </pre>
  1709. </div>
  1710. <p>
  1711. For simple cases like this, specifying the regular expression for the
  1712. declaration name directly can be preferable and can also be done using
  1713. <tt>regextarget</tt>:
  1714. </p>
  1715. <div class="code">
  1716. <pre>
  1717. %rename("$ignore", regextarget=1) "Old$";
  1718. </pre>
  1719. </div>
  1720. <p>
  1721. Notice that the check is done only against the name of the declaration
  1722. itself, if you need to match the full name of a C++ declaration you
  1723. must use <tt>ful