PageRenderTime 51ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/trunk/Doc/Devel/internals.html

#
HTML | 1186 lines | 974 code | 212 blank | 0 comment | 0 complexity | de3f3ad5683b4efc3ea2ad9dca478c68 MD5 | raw file
Possible License(s): LGPL-2.1, Cube, GPL-3.0, 0BSD, GPL-2.0
  1. <html>
  2. <head>
  3. <title>SWIG Internals</title>
  4. </head>
  5. <body>
  6. <center>
  7. <h1>SWIG Internals Manual</h1>
  8. </b>
  9. </center>
  10. <p>
  11. <p>
  12. (Note : This is a work in progress.)
  13. <h2>Table of Contents</h2>
  14. <ul>
  15. <li><a name="i1" href="#1">1. Introduction</a>
  16. <ul>
  17. <li><a name="i1.1" href="#1.1">1.1 Directory Guide</a>
  18. <li><a name="i1.2" href="#1.2">1.2 Overall Program Flow</a>
  19. </ul>
  20. <li><a name="i2" href="#2">2. DOH</a>
  21. <ul>
  22. <li><a name="i2.1" href="#2.1">2.1 Motivation and Background</a>
  23. <li><a name="i2.2" href="#2.2">2.2 Basic Types</a>
  24. <li><a name="i2.3" href="#2.3">2.3 Creating, Copying and Destroying Objects</a>
  25. <li><a name="i2.4" href="#2.4">2.4 A Word About Mutability and Copying</a>
  26. <li><a name="i2.5" href="#2.5">2.5 Strings</a>
  27. <li><a name="i2.6" href="#2.6">2.6 Lists</a>
  28. <li><a name="i2.7" href="#2.7">2.7 Hash Tables</a>
  29. <li><a name="i2.8" href="#2.8">2.8 Files</a>
  30. <li><a name="i2.9" href="#2.9">2.9 Void Objects</a>
  31. <li><a name="i2.10" href="#2.10">2.10 Utility Functions</a>
  32. </ul>
  33. <li><a name="i3" href="#3">3. Types and Typemaps</a>
  34. <li><a name="i4" href="#4">4. Parsing</a>
  35. <li><a name="i5" href="#5">5. C/C++ Wrapper Support Functions</a>
  36. <li><a name="i6" href="#6">6. Symbol Naming Guidelines for Generated C/C++ Code</a>
  37. <li><a name="i7" href="#7">7. Debugging SWIG</a>
  38. <ul>
  39. <li><a name="i7.1" href="#7.1">7.1 Debugging DOH Types The Hard Way</a>
  40. </ul>
  41. </ul>
  42. <a name="1" href="#i1">
  43. <h2>1. Introduction</h2>
  44. </a>
  45. This document details SWIG internals: architecture and sometimes
  46. implementation. The first few sections concentrate on data structures,
  47. interfaces, conventions and code shared by all language targets.
  48. Subsequent sections focus on a particular language.
  49. <p>
  50. The audience is assumed to be SWIG developers (who should also read the
  51. <a href="engineering.html">SWIG Engineering Manual</a> before starting
  52. to code).
  53. <a name="1.1" href="#i1.1">
  54. <h3>1.1 Directory Guide</h3>
  55. </a>
  56. <table border=1>
  57. <tr><td><a href="index.html">Doc</a></td>
  58. <td>HTML documentation. If you find a documentation bug, please
  59. <a href="mailto:bug-swig-doc@glug.org">let us know</a>.</td>
  60. </tr>
  61. <tr><td>Examples</td>
  62. <td>This subdir tree contains examples of using SWIG w/ different
  63. scripting languages, including makefiles. Typically, there are the
  64. "simple" and "class" examples, w/ some languages offering additional
  65. examples. See the README more index.html file in each directory
  66. for more info. [FIXME: Ref SWIG user manual.]</td>
  67. </tr>
  68. <tr><td>Lib</td>
  69. <td>These are the <tt>.i</tt> (interface) files that form the SWIG
  70. installed library. Language-specific files are in subdirectories (for
  71. example, guile/typemaps.i). Each language also has a <tt>.swg</tt> file
  72. implementing runtime type support for that language. The SWIG library
  73. is not versioned.</td>
  74. </tr>
  75. <tr><td>Misc</td>
  76. <td>Currently this subdir only contains file <tt>fileheader</tt>. See
  77. the <a href="engineering.html">Engineering Manual</a> for more
  78. info.</td>
  79. </tr>
  80. <tr><td>Source</td>
  81. <td>The C and C++ source code for the <tt>swig</tt> executable is in this
  82. subdir tree.</td>
  83. <table border=1>
  84. <tr><td>DOH</td>
  85. <td>C library providing memory allocation, file access and generic
  86. containers.</td>
  87. </tr>
  88. <tr><td>Include</td>
  89. <td>Configuration .h files</td>
  90. </tr>
  91. <tr><td>CParse</td>
  92. <td>Parser (lex / yacc) files and support</td>
  93. </tr>
  94. <tr><td>Modules</td>
  95. <td>Language-specific callbacks that does actual code generation (each
  96. language has a .cxx and a .h file).</td>
  97. </tr>
  98. <tr><td>Preprocessor</td>
  99. <td>SWIG-specialized C/C++ preprocessor.</td>
  100. </tr>
  101. <tr><td>Swig</td>
  102. <td>This directory contains the ANSI C core of the system
  103. and contains generic functions related to types, file handling,
  104. scanning, and so forth.</td>
  105. </tr>
  106. </table></td>
  107. </tr>
  108. <tr><td>Tools</td>
  109. <td>The mkdist.py script and other tools.</td>
  110. </tr>
  111. <tr><td>Win</td>
  112. <td>This improperly-named (spit spit) subdir only has README.txt.</td>
  113. </tr>
  114. </table>
  115. <a name="1.2" href="#1.2">
  116. <h3>1.2 Overall Program Flow</h3>
  117. </a>
  118. Here is the general control flow and where under subdir <tt>Source</tt>
  119. to look for code:
  120. <ul>
  121. <li> <tt>Modules/swigmain.cxx:main()</tt> is the program entry
  122. point. It parses the language-specifying command-line option (for
  123. example, <tt>-java</tt>), creating a new language-specific wrapping
  124. object (each language is a C++ class derived from base class
  125. <tt>Language</tt>). This object and the command-line is passed to
  126. <tt>SWIG_main()</tt>, whose return value is the program exit value.
  127. <li> <tt>Modules/main.cxx:SWIG_main()</tt> is the "real" main. It
  128. initializes the preprocessor and typemap machinery, defines some
  129. preprocessor symbols, locates the SWIG library, processes common
  130. command-line options, and then calls the language-specific command-line
  131. parser. From here there are three paths: "help", "checkout" and
  132. everything else.
  133. <ul>
  134. <li> In "help" mode, clean up open files and exit.
  135. <li> In "checkout" mode, copy specified files from the SWIG library
  136. to the current directory. Errors cause error messages but no
  137. non-local exits.
  138. <li> Otherwise, do wrapping: determine output file name(s), define
  139. some preprocessor symbols and run the preprocessor, initialize
  140. the interface-definition parser, set up the typemap for handling
  141. new return strings, and finally do the language-specific parse
  142. (by calling the language object's <tt>parse()</tt> method), which
  143. creates output files by side-effect.
  144. </ul>
  145. Afterwards, remove temporary files, and clean up. If the command-line
  146. included <tt>-freeze</tt>, go into an infinite loop; otherwise return the
  147. error count.
  148. <li> The language-specific <tt>parse()</tt> (and all other
  149. language-specific code) lives in <tt>Modules/foo.{h,cxx}</tt> for
  150. language Foo. Typically, <tt>FOO::parse()</tt> calls
  151. <tt>FOO::headers()</tt> and then the global function <tt>yyparse()</tt>,
  152. which uses the callbacks registered by <tt>SWIG_main()</tt> above.
  153. </ul>
  154. <a name="2" href="#i2">
  155. <h2>2. DOH</h2>
  156. </a>
  157. DOH is a collection of low-level objects such as strings, lists, and
  158. hash tables upon which the rest of SWIG is built. The name 'DOH'
  159. unofficially stands for "Dave's Object Hack", but it's also a good
  160. expletive to use when things don't work (as in "SWIG core
  161. dumped---DOH!").
  162. <a name="2.1" href="#2.1">
  163. <h3>2.1 Motivation and Background</h3>
  164. </a>
  165. The development of DOH is influenced heavily by the problems
  166. encountered during earlier attempts to create a C++ based version of
  167. SWIG2.0. In each of these attempts (over a 3 year period), the
  168. resulting system always ended up growing into a colossal nightmare of
  169. large inheritance hierarchies and dozens of specialized classes for
  170. different types of objects (functions, variables, constants, etc.).
  171. The end result was that the system was tremendously complicated,
  172. difficult to understand, difficult to maintain, and fairly inflexible
  173. in the grand scheme of things.
  174. <p>
  175. DOH takes a different approach to tackling the complexity problem.
  176. First, rather than going overboard with dozens of types and class
  177. definitions, DOH only defines a handful of simple yet very useful
  178. objects that are easy to remember. Second, DOH uses dynamic
  179. typing---one of the features that make scripting languages so useful
  180. and which make it possible to accomplish things with much less code.
  181. Finally, DOH utilizes a few coding tricks that allow it to perform
  182. a limited form of function overloading for certain C datatypes (more
  183. on that a little later).
  184. <p>
  185. The key point to using DOH is that instead of thinking about code in
  186. terms of highly specialized C data structures, just about everything
  187. ends up being represented in terms of a just a few datatypes. For
  188. example, structures are replaced by DOH hash tables whereas arrays are
  189. replaced by DOH lists. At first, this is probably a little strange to
  190. most C/C++ programmers, but in the long run in makes the system
  191. extremely flexible and highly extensible. Also, in terms of coding,
  192. many of the newly DOH-based subsystems are less than half the size (in
  193. lines of code) of the earlier C++ implementation.
  194. <a name="2.2" href="#i2.2">
  195. <h3>2.2 Basic Types</h3>
  196. </a>
  197. The following built-in types are currently provided by DOH:
  198. <ul>
  199. <li><b>String</b>. A string of characters with automatic memory
  200. management and high-level operations such as string replacement. In addition,
  201. strings support file I/O operations that make it possible to use them just
  202. about anyplace a file can be used.
  203. <p>
  204. <li><b>List</b>. A list of arbitrary DOH objects (of possibly mixed types).
  205. <p>
  206. <li><b>Hash</b>. A hash table that maps a set of string keys to a set of arbitrary
  207. DOH objects. The DOH version of an associative array for all of you Perl fans.
  208. <p>
  209. <li><b>File</b>. A DOH wrapper around the C FILE * structure. This is provided
  210. since other objects sometimes want to behave like files (strings for instance).
  211. <p>
  212. <li><b>Void</b>. A DOH wrapper around an arbitrary C pointer. This can be used
  213. if you want to place arbitrary C data structures in DOH lists and hash tables.
  214. </ul>
  215. Due to dynamic typing, all of the objects in DOH are represented by pointers
  216. of type <tt>DOH *</tt>. Furthermore, all objects are completely
  217. opaque--that means that the only way to access the internals of an
  218. object is through a well-defined public API. For convenience, the following
  219. symbolic names are sometimes used to improve readability:
  220. <ul>
  221. <Li><tt>DOHString *</tt>. A String object.
  222. <li><tt>DOHList *</tt>. A list object.
  223. <li><tt>DOHHash *</tt>. A hash object.
  224. <li><tt>DOHFile *</tt>. A file object.
  225. <li><tt>DOHVoid *</tt>. A void object.
  226. <li><tt>DOHString_or_char *</tt>. A DOH String object or a raw C "char *".
  227. </ul>
  228. It should be stressed that all of these names are merely symbolic aliases to the
  229. type <tt>DOH *</tt> and that no compile-time type checking is performed (of course,
  230. a runtime error may occur if you screw up).
  231. <a name="2.3" href="#i2.3">
  232. <h3>2.3 Creating, Copying, and Destroying Objects </h3>
  233. </a>
  234. The following functions can be used to create new DOH objects
  235. <ul>
  236. <Li><tt>NewString(DOHString_or_char *value)</tt><br>
  237. Create a new string object with contents initially
  238. set to value. value can be either a C string or a DOH string object.
  239. <p>
  240. <li><tt>NewStringf(char *fmt, ...)</tt><br>
  241. Create a new string object with contents initially set to
  242. a formatted string. Think of this as being sprintf() combined with an object constructor.
  243. <p>
  244. <li><tt>NewList()</tt><br>
  245. Create a new list object that is initially empty.
  246. <p>
  247. <Li><tt>NewHash()</tt><br>
  248. Create a new hash object that is initially empty.
  249. <p>
  250. <li><tt>NewFile(DOHString_or_char *filename, char *mode)</tt><br>
  251. Open a file and return a file object. This is a
  252. wrapper around the C <tt>fopen()</tt> library call.
  253. <p>
  254. <li><tt>NewFileFromFile(FILE *f)</tt><br>
  255. Create a new file object given an already opened <tt>FILE *</tt> object.
  256. <p>
  257. <li><tt>NewVoid(void *obj, void (*del)(void *))</tt><br>
  258. Create a new DOH object that is a wrapper around an
  259. arbitrary C pointer. <tt>del</tt> is an optional destructor function that will be called when the object
  260. is destroyed.
  261. </ul>
  262. Any object can be copied using the <tt>Copy()</tt> function. For example:
  263. <blockquote>
  264. <pre>
  265. DOH *a, *b, *c, *d;
  266. a = NewString("Hello World");
  267. b = NewList();
  268. c = Copy(a); /* Copy the string a */
  269. d = Copy(b); /* Copy the list b */
  270. </pre>
  271. </blockquote>
  272. Copies of lists and hash tables are shallow. That is, their contents are only copied by reference.
  273. <p>
  274. Objects can be deleted using the <tt>Delete()</tt> function. For example:
  275. <blockquote>
  276. <pre>
  277. DOH *a = NewString("Hello World");
  278. ...
  279. Delete(a); /* Destroy a */
  280. </pre>
  281. </blockquote>
  282. All objects are referenced counted and given a reference count of 1 when initially created. The
  283. <tt>Delete()</tt> function only destroys an object when the reference count reaches zero. When
  284. an object is placed in a list or hash table, it's reference count is automatically increased. For example:
  285. <blockquote>
  286. <pre>
  287. DOH *a, *b;
  288. a = NewString("Hello World");
  289. b = NewList();
  290. Append(b,a); /* Increases refcnt of a to 2 */
  291. Delete(a); /* Decreases refcnt of a to 1 */
  292. Delete(b); /* Destroys b, and destroys a */
  293. </pre>
  294. </blockquote>
  295. Should it ever be necessary to manually increase the reference count of an object, the DohIncref() function
  296. can be used:
  297. <blockquote>
  298. <pre>
  299. DOH *a = NewString("Hello");
  300. DohIncref(a);
  301. </pre>
  302. </blockquote>
  303. <a name="2.4" href="#i2.4">
  304. <h3>2.4 A Word About Mutability and Copying</h3>
  305. </a>
  306. All DOH objects are mutable regardless of their current reference
  307. count. For example, if you create a string and then create a 1000
  308. references to it (in lists and hash tables), changes to the string
  309. will be reflected in all of the references. Therefore, if you need to
  310. make any kind of local change, you should first make a copy using the
  311. Copy() function. Caveat: when copying lists and hash tables, elements
  312. are copied by reference.
  313. <a name="2.5" href="#i2.5">
  314. <h3>2.5 Strings</h3>
  315. </a>
  316. The DOH String type is perhaps the most flexible object. First, it supports a variety of string-oriented
  317. operations. Second, it supports many of the same operations as lists. Finally, strings provide file I/O
  318. operations that allow them to be used interchangeably with DOH file objects.
  319. [ TODO ]
  320. <a name="2.6" href="#i2.6">
  321. <h3>2.6 Lists</h3>
  322. </a>
  323. <p>
  324. Example usage of lists:
  325. </p>
  326. <blockquote>
  327. <pre>
  328. /* Create and populate */
  329. List *list = NewList();
  330. Append(list, NewString("listval1"));
  331. Append(list, NewString("listval2"));
  332. Append(list, NewString("listval3"));
  333. Append(list, NewString("listval4"));
  334. Append(list, NewString("listval5"));
  335. /* Size */
  336. Printf(stdout, "list len: %d\n", Len(list));
  337. /* Delete */
  338. Delitem(list, 3);
  339. /* Replace */
  340. Setitem(list, 0, NewString("newlistval1"));
  341. /* Get */
  342. String *item = Getitem(list,1);
  343. if (item)
  344. Printf(stdout, "get: %s\n", item);
  345. else
  346. Printf(stdout, "get: [non-existent]\n");
  347. /* Iterate through the container */
  348. int len = Len(list);
  349. for (int i=0; i&lt;len; i++) {
  350. String *item = Getitem(list,i);
  351. Printf(stdout, "list item: %s\n", item);
  352. }
  353. </blockquote>
  354. </pre>
  355. <p>
  356. Resulting output:
  357. </p>
  358. <blockquote>
  359. <pre>
  360. hash len: 5
  361. get: hashval2
  362. hash item: hashval5 [h5]
  363. hash item: hashval1 [h1]
  364. hash item: hashval2 [h2]
  365. hash item: hashval3 [h3]
  366. </pre>
  367. </blockquote>
  368. <a name="2.7" href="#i2.7">
  369. <h3>2.7 Hash tables </h3>
  370. </a>
  371. <p>
  372. Example usage of hash tables:
  373. </p>
  374. <blockquote>
  375. <pre>
  376. /* Create and populate */
  377. Hash *hash = NewHash();
  378. Setattr(hash, "h1", NewString("hashval1"));
  379. Setattr(hash, "h2", NewString("hashval2"));
  380. Setattr(hash, "h3", NewString("hashval3"));
  381. Setattr(hash, "h4", NewString("hashval4"));
  382. Setattr(hash, "h5", NewString("hashval5"));
  383. /* Size */
  384. Printf(stdout, "hash len: %d\n", Len(hash));
  385. /* Delete */
  386. Delattr(hash, "h4");
  387. /* Get */
  388. String *item = Getattr(hash, "h2");
  389. if (item)
  390. Printf(stdout, "get: %s\n", item);
  391. else
  392. Printf(stdout, "get: [non-existent]\n");
  393. /* Iterate through the container */
  394. Iterator it;
  395. for (it = First(hash); it.key; it= Next(it))
  396. Printf(stdout, "hash item: %s [%s]\n", (it.item), (it.key));
  397. </pre>
  398. </blockquote>
  399. <p>
  400. Resulting output:
  401. </p>
  402. <blockquote>
  403. <pre>
  404. list len: 5
  405. get: listval2
  406. list item: newlistval1
  407. list item: listval2
  408. list item: listval3
  409. list item: listval5
  410. </pre>
  411. </blockquote>
  412. <a name="2.8" href="#i2.8">
  413. <h3>2.8 Files </h3>
  414. </a>
  415. [ TODO ]
  416. <a name="2.9" href="#i2.9">
  417. <h3>2.9 Void objects </h3>
  418. </a>
  419. [ TODO ]
  420. <a name="2.10" href="#i2.10">
  421. <h3>2.10 Utility functions </h3>
  422. </a>
  423. [ TODO ]
  424. <a name="3" href="#i3">
  425. <h2>3. Types and Typemaps</h2>
  426. </a>
  427. <p>
  428. The representation and manipulation of types is currently in the
  429. process of being reorganized and (hopefully) simplified. The
  430. following list describes the current set of functions that are used to
  431. manipulate datatypes.
  432. <ul>
  433. <li><tt>SwigType_str(SwigType *t, char *name)</tt>.<br>
  434. This function produces the exact string
  435. representation of the datatype <tt>t</tt>. <tt>name</tt> is an optional parameter that
  436. specifies a declaration name. This is used when dealing with more complicated datatypes
  437. such as arrays and pointers to functions where the output might look something like
  438. "<tt>int (*name)(int, double)</tt>".
  439. <p>
  440. <li><tt>SwigType_lstr(SwigType *t, char *name)</tt>.<br>
  441. This function produces a string
  442. representation of a datatype that can be safely be assigned a value (i.e., can be used as the
  443. "lvalue" of an expression). To do this, qualifiers such as "const", arrays, and references
  444. are stripped away or converted into pointers. For example:
  445. <blockquote>
  446. <pre>
  447. Original Datatype lstr()
  448. ------------------ --------
  449. const char *a char *a
  450. double a[20] double *a
  451. double a[20][30] double *a
  452. double &amp;a double *a
  453. </pre>
  454. </blockquote>
  455. The intent of the lstr() function is to produce local variables inside wrapper functions--all
  456. of which must be reassignable types since they are the targets of conversions from a scripting
  457. representation.
  458. <p>
  459. <li><tt>SwigType_rcaststr(SwigType *t, char *name)</tt>.
  460. <br> This function produces a string
  461. that casts a type produced by the <tt>lstr()</tt> function to the type produced by the
  462. <tt>str()</tt> function. You might view it as the inverse of lstr(). This function only produces
  463. output when it needs to (when str() and lstr() produce different results). Furthermore, an optional
  464. name can be supplied when the cast is to be applied to a specific name. Examples:
  465. <blockquote>
  466. <pre>
  467. Original Datatype rcaststr()
  468. ------------------ ---------
  469. char *a
  470. const char *a (const char *) name
  471. double a[20] (double *) name
  472. double a[20][30] (double (*)[30]) name
  473. double &amp;a (double &amp;) *name
  474. </pre>
  475. </blockquote>
  476. <p>
  477. <li><tt>SwigType_lcaststr(SwigType *t, char *name)</tt>.
  478. <br> This function produces a string
  479. that casts a type produced by the <tt>str()</tt> function to the type produced by the
  480. <tt>lstr()</tt> function. This function only produces
  481. output when it needs to (when str() and lstr() produce different results). Furthermore, an optional
  482. name can be supplied when the cast is to be applied to a specific name.
  483. <blockquote>
  484. <pre>
  485. Original Datatype lcaststr()
  486. ------------------ ---------
  487. char *a
  488. const char *a (char *) name
  489. double a[20] (double *) name
  490. double a[20][30] (double *) name
  491. double &amp;a (double *) &amp;name
  492. </pre>
  493. </blockquote>
  494. <p>
  495. <li><tt>SwigType_manglestr(SwigType *t)</tt>. <br>
  496. Produces a type-string that is used to identify this datatype in the target scripting language.
  497. Usually this string looks something like "<tt>_p_p_double</tt>" although the target language
  498. may redefine the output for its own purposes. Normally this function strips all qualifiers,
  499. references, and arrays---producing a mangled version of the type produced by the <tt>lstr()</tt> function.
  500. </ul>
  501. The following example illustrates the intended use of the above functions when creating wrapper
  502. functions using shorthand pseudocode. Suppose you had a function like this:
  503. <blockquote>
  504. <pre>
  505. int foo(int a, double b[20][30], const char *c, double &amp;d);
  506. </pre>
  507. </blockquote>
  508. Here's how a wrapper function would be generated using the type generation functions above:
  509. <blockquote>
  510. <pre>
  511. wrapper_foo() {
  512. lstr("int","result")
  513. lstr("int","arg0")
  514. lstr("double [20][30]", "arg1")
  515. lstr("const char *", "arg2")
  516. lstr("double &amp;", "arg3")
  517. ...
  518. get arguments
  519. ...
  520. result = (lcaststr("int")) foo(rcaststr("int","arg0"),
  521. rcaststr("double [20][30]","arg1"),
  522. rcaststr("const char *", "arg2"),
  523. rcaststr("double &amp;", "arg3"))
  524. ...
  525. }
  526. </pre>
  527. </blockquote>
  528. Here's how it would look with the corresponding output filled in:
  529. <blockquote>
  530. <pre>
  531. wrapper_foo() {
  532. int result;
  533. int arg0;
  534. double *arg1;
  535. char *arg2;
  536. double *arg3;
  537. ...
  538. get arguments
  539. ...
  540. result = (int) foo(arg0,
  541. (double (*)[30]) arg1,
  542. (const char *) arg2,
  543. (double &amp;) *arg3);
  544. ...
  545. }
  546. </pre>
  547. </blockquote>
  548. <b>Notes:</b>
  549. <ul>
  550. <li>For convenience, the string generation functions return a
  551. "<tt>char *</tt>" that points to statically allocated memory living
  552. inside the type library. Therefore, it is never necessary (and it's
  553. an error) to free the pointer returned by the functions. Also, if you
  554. need to save the result, you should make a copy of it. However, with
  555. that said, it is probably worth nothing that these functions do cache
  556. the last 8 results. Therefore, it's fairly safe to make a handful of
  557. repeated calls without making any copies.
  558. </ul>
  559. [TODO]
  560. <a name="4" href="#i4">
  561. <h2>4. Parsing</h2>
  562. </a>
  563. [TODO]
  564. <a name="5" href="#i5">
  565. <h2>5. The C/C++ Wrapping Layer</h2>
  566. </a>
  567. Added: Dave Beazley (July 22, 2000)
  568. <p>
  569. When SWIG generates wrappers, it tries to provide a mostly seamless integration
  570. with the original code. However, there are a number of problematic features
  571. of C/C++ programs that complicate this interface.
  572. <ul>
  573. <li><b>Passing and returning structures by value.</b> When used, SWIG converts
  574. all pass-by-value functions into wrappers that pass by reference. For example:
  575. <blockquote>
  576. <pre>
  577. double dot_product(Vector a, Vector b);
  578. </pre>
  579. </blockquote>
  580. gets turned into a wrapper like this:
  581. <blockquote>
  582. <pre>
  583. double wrap_dot_product(Vector *a, Vector *b) {
  584. return dot_product(*a,*b);
  585. }
  586. </pre>
  587. </blockquote>
  588. Functions that return by value require a memory allocation to store the result. For example:
  589. <blockquote>
  590. <pre>
  591. Vector cross_product(Vector *a, Vector *b);
  592. </pre>
  593. </blockquote>
  594. become
  595. <blockquote>
  596. <pre>
  597. Vector *wrap_cross_product(Vector *a, Vector *b) {
  598. Vector *result = (Vector *) malloc(sizeof(Vector));
  599. *result = cross_product(a,b);
  600. return result;
  601. }
  602. </pre>
  603. </blockquote>
  604. Note: If C++ is being wrapped, the default copy constructor is used
  605. instead of malloc() to create a copy of the return result.
  606. <p>
  607. <li><b>C++ references</b>. C++ references are handled exactly the same as
  608. pass/return by value except that a memory allocation is not made for functions
  609. that return a reference.
  610. <p>
  611. <li><b>Qualifiers such as "const" and "volatile".</b> SWIG strips all
  612. qualifiers from the interface presented to the target language.
  613. Besides, what in the heck is "const" in Perl anyways?
  614. <p>
  615. <li><b>Instance Methods</b>. Method invocations are handled as a function call in which
  616. a pointer to the object (the "this" pointer) appears as the first argument. For example, in
  617. the following class:
  618. <blockquote>
  619. <pre>
  620. class Foo {
  621. public:
  622. double bar(double);
  623. };
  624. </pre>
  625. </blockquote>
  626. The "bar" method is wrapped by a function like this:
  627. <blockquote>
  628. <pre>
  629. double Foo_bar(Foo *self, double arg0) {
  630. return self-&gt;bar(arg0);
  631. }
  632. </pre>
  633. </blockquote>
  634. <p>
  635. <li><b>Structure/class data members</b>. Data members are handled by creating a pair
  636. of wrapper functions that set and get the value respectively. For example:
  637. <blockquote>
  638. <pre>
  639. struct Foo {
  640. int x;
  641. };
  642. </pre>
  643. </blockquote>
  644. gets wrapped as follows:
  645. <blockquote>
  646. <pre>
  647. int Foo_x_get(Foo *self) {
  648. return self-&gt;x;
  649. }
  650. int Foo_x_set(Foo *self, int value) {
  651. return (self-&gt;x = value);
  652. }
  653. </pre>
  654. </blockquote>
  655. <p>
  656. <li><b>Constructors</b>. Constructors for C/C++ data structures are wrapped by
  657. a function like this:
  658. <blockquote>
  659. <pre>
  660. Foo *new_Foo() {
  661. return new Foo;
  662. }
  663. </pre>
  664. </blockquote>
  665. Note: For C, new objects are created using the calloc() function.
  666. <p>
  667. <li><b>Destructors</b>. Destructors for C/C++ data structures are wrapper like this:
  668. <blockquote>
  669. <pre>
  670. void delete_Foo(Foo *self) {
  671. delete self;
  672. }
  673. </pre>
  674. </blockquote>
  675. Note: For C, objects are destroyed using free().
  676. </ul>
  677. The creation of wrappers and various type transformations are handled by a collection of functions
  678. found in the file <tt>Source/Swig/cwrap.c</tt>.
  679. <ul>
  680. <li>
  681. <tt>char *Swig_clocal(DataType *t, char *name, char *value)</tt><br>
  682. This function creates a string containing the declaration of a local variable with
  683. type <tt>t</tt>, name <tt>name</tt>, and default value <tt>value</tt>. This local
  684. variable is stripped of all qualifiers and will be a pointer if the type is a reference
  685. or user defined type.
  686. <p>
  687. <li>
  688. <tt>DataType *Swig_clocal_type(DataType *t)</tt><br>
  689. Returns a type object corresponding to the type string produced by the Swig_clocal() function.
  690. <p>
  691. <li><tt>char *Swig_clocal_deref(DataType *t, char *name)</tt><br>
  692. This function is the inverse of the <tt>clocal()</tt> function. Given a type and a name,
  693. it produces a string containing the code needed to cast/convert the type produced by
  694. <tt>Swig_clocal()</tt> back into it's original type.
  695. <p>
  696. <li><tt>char *Swig_clocal_assign(DataType *t, char *name)</tt><br>
  697. Given a type and name, this produces a string containing the code (and an optional cast)
  698. needed to make an assignment from the real datatype to the local datatype produced
  699. by <tt>Swig_clocal()</tt>. Kind of the opposite of deref().
  700. <p>
  701. <li><tt>int Swig_cargs(Wrapper *w, ParmList *l)</tt><br>
  702. Given a wrapper function object and a list of parameters, this function declares a set
  703. of local variables for holding all of the parameter values (using Swig_clocal()). Returns
  704. the number of parameters. In addition, this function sets the local name of each parameter
  705. which can be retrieved using the <tt>Parm_Getlname()</tt> function.
  706. <p>
  707. <li><tt>void Swig_cresult(Wrapper *w, DataType *t, char *resultname, char *decl)</tt><br>
  708. Generates the code needed to set the result of a wrapper function and performs all of
  709. the needed memory allocations for ANSI C (if necessary). <tt>t</tt> is the type of the
  710. result, <tt>resultname</tt> is the name of the result variable, and <tt>decl</tt> is
  711. a string that contains the C code which produces the result.
  712. <p>
  713. <li><tt>void Swig_cppresult(Wrapper *w, DataType *t, char *resultname, char *decl)</tt><br>
  714. Generates the code needed to set the result of a wrapper function and performs all of
  715. the needed memory allocations for C++ (if necessary). <tt>t</tt> is the type of the
  716. result, <tt>resultname</tt> is the name of the result variable, and <tt>decl</tt> is
  717. a string that contains the C code which produces the result.
  718. <p>
  719. <li><tt>Wrapper *Swig_cfunction_wrapper(char *fname, DataType *rtype, ParmList *parms, char *code)</tt><br>
  720. Create a wrapper around a normal function declaration. <tt>fname</tt> is the name of the wrapper,
  721. <tt>rtype</tt> is the return type, <tt>parms</tt> are the function parameters, and <tt>code</tt> is a
  722. string containing the code in the function body.
  723. <p>
  724. <li><tt>Wrapper *Swig_cmethod_wrapper(char *classname, char *methodname, DataType *rtype, DataType *parms, char *code)</tt><br>
  725. <p>
  726. <li><tt>char *Swig_cfunction_call(char *name, ParmList *parms)</tt>
  727. This function produces a string containing the code needed to call a C function.
  728. The string that is produced contains all of the transformations needed to convert
  729. pass-by-value into pass-by-reference as well as handle C++ references. Produces
  730. a string like "name(arg0, arg1, ..., argn)".
  731. </ul>
  732. Here is a short example showing how these functions could be used. Suppose you had a
  733. C function like this:
  734. <blockquote>
  735. <pre>
  736. double dot_product(Vector a, Vector b);
  737. </pre>
  738. </blockquote>
  739. Here's how you might write a really simple wrapper function
  740. <blockquote>
  741. <pre>
  742. ParmList *l = ... parameter list of the function ...
  743. DataType *t = ... return type of the function ...
  744. char *name = ... name of the function ...
  745. Wrapper *w = NewWrapper();
  746. Printf(w-&gt;def,"void wrap_%s() {\n", name);
  747. /* Declare all of the local variables */
  748. Swig_cargs(w, l);
  749. /* Convert all of the arguments */
  750. ...
  751. /* Make the function call and declare the result variable */
  752. Swig_cresult(w,t,"result",Swig_cfunction(name,l));
  753. /* Convert the result into whatever */
  754. ...
  755. Printf(w-&gt;code,"}\n");
  756. Wrapper_print(w,out);
  757. </pre>
  758. </blockquote>
  759. The output of this would appear as follows:
  760. <blockquote>
  761. <pre>
  762. void wrap_dot_product() {
  763. Vector *arg0;
  764. Vector *arg1;
  765. double result;
  766. ...
  767. result = dot_product(*arg0, *arg1);
  768. ...
  769. }
  770. </pre>
  771. </blockquote>
  772. Notice that the <tt>Swig_cargs()</tt>, <tt>Swig_cresult()</tt>, and <tt>Swig_cfunction()</tt> functions
  773. have taken care of the type conversions for the <tt>Vector</tt> type automatically.
  774. <p>
  775. <b>Notes:</b>
  776. <ul>
  777. <Li>The intent of these functions is to provide <em>consistent</em> handling of function parameters
  778. and return values so that language module writers don't have to worry about it too much.
  779. <p>
  780. <li>These functions may be superseded by features in the new typemap system which provide hooks
  781. for specifying local variable declarations and argument conversions.
  782. </ul>
  783. <a name="6" href="#i6">
  784. <h2>6. Symbol Naming Guidelines for Generated C/C++ Code</h2>
  785. </a>
  786. The C++ standard (ISO/IEC 14882:1998(E)) states:
  787. <blockquote>
  788. <pre>
  789. <i>
  790. 17.4.3.1.2 Global names [lib.global.names]
  791. 1 Certain sets of names and function signatures are always reserved to the implementation:
  792. * Each name that contains a double underscore (__) or begins with an underscore followed
  793. by an upper case letter (2.11) is reserved to the implementation for any use.
  794. * Each name that begins with an underscore is reserved to the implementation for use as
  795. a name in the global namespace.165)
  796. 165) Such names are also reserved in namespace ::std (17.4.3.1). [back to text]
  797. </i>
  798. </pre>
  799. </blockquote>
  800. When generating code it is important not to generate symbols that might clash with the code being wrapped. It is tempting to flout the standard or just use a symbol which starts with a single underscore followed by a lowercase letter in order to avoid name clashes. However even these legal symbols can also clash with symbols being wrapped. The following guidelines should be used when generating code in order to meet the standard and make it highly unlikely that symbol clashes will occur:
  801. <p>
  802. For C++ code that doesn't attempt to mangle a symbol being wrapped (for example SWIG convenience functions):
  803. <ul>
  804. <li> Put symbols in the <tt>Swig</tt> namespace, for example class <tt>Swig::Director</tt>. Qualify using the <tt>Swig</tt> namespace whenever the symbol is referenced, even within the <tt>Swig</tt> namespace, for example <tt>new Swig::Director()</tt> not <tt>new Director()</tt>.</li>
  805. <li> Use <tt>swig_</tt> as a prefix for all member variables and member functions that are involved in an inheritance chain with wrapped classes, for example <tt>Swig::Director::swig_get_up()</tt> and <tt>bool Swig::Director::swig_up</tt>.</li>
  806. <li> Alternatively class names can be prefixed with <tt>Swig</tt> in the global namespace for example <tt>template&lt;class T&gt; class SwigValueWrapper</tt>.</li>
  807. </ul>
  808. <p>
  809. For code compiled as C or C++ that doesn't attempt to mangle a symbol being wrapped (for example SWIG convenience functions):
  810. <ul>
  811. <li> Use <tt>SWIG_</tt> as a prefix for structures for example <tt>SWIG_JavaExceptions_t</tt>.</li>
  812. <li> Use <tt>SWIG_</tt> as a prefix for global functions for example <tt>SWIG_TypeRegister</tt>. </li>
  813. <li> Use <tt>SWIG_</tt> as a prefix for macros for example <tt>#define SWIG_PY_INT 1</tt></li>
  814. </ul>
  815. For code compiled as C or C++ that attempts to mangle a wrapped symbol:
  816. <ul>
  817. <li> Use <tt>SWIGxxx</tt> or <tt>Swigxxx</tt> as a prefix where xxx is chosen which would make <tt>SWIGxxx</tt>/<tt>Swigxxx</tt> a unique symbol in the global namespace, for example <tt>class SwigDirectorFoo</tt> when wrapping <tt>class Foo</tt>. Don't use a trailing underscore for the prefix as this may generate a double underscore when wrapping a symbol which starts with a single underscore.</li>
  818. </ul>
  819. In the past SWIG has generated many symbols which flout the standard especially double underscores. In fact they may not all be rooted out yet, so please fix them when you see them.
  820. <a name="7" href="#i7">
  821. <h2>7. Debugging SWIG</h2>
  822. </a>
  823. <p>
  824. The DOH types used in the SWIG source code are all typedefined to void.
  825. Consequently, it is impossible for debuggers to automatically extract any information about DOH objects.
  826. The easiest approach to debugging and viewing the contents of DOH objects is to make a call into one of the family of SWIG print functions from the debugger.
  827. The "Debugging Functions" section in <a href="tree.html">SWIG Parse Tree Handling</a> lists them.
  828. It is sometimes easier to debug by placing a few calls to these functions in code of interest and recompile, especially if your debugger cannot easily make calls into functions within a debugged binary.
  829. </p>
  830. <p>
  831. The SWIG distribution comes with some additional support for the gdb debugger in the <tt>Tools/swig.gdb</tt> file.
  832. Follow the instructions in this file for 'installing'.
  833. This support file provides an easy way to call into some of the family of SWIG print functions via additional user-defined gdb commands.
  834. Some usage of the <tt>swigprint</tt> and <tt>locswigprint</tt> user-defined commands are demonstrated below.
  835. </p>
  836. <p>
  837. More often than not, a parse tree node needs to be examined.
  838. The session below displays the node <tt>n</tt> in one of the Java language module wrapper functions.
  839. The <tt>swigprint</tt> method is used to show the symbol name (<tt>symname</tt> - a DOH String type) and the node (<tt>n</tt> - a DOH Hash type).
  840. </p>
  841. <blockquote>
  842. <pre>
  843. Breakpoint 1, JAVA::functionWrapper (this=0x97ea5f0, n=0xb7d2afc8) at Modules/java.cxx:799
  844. 799 String *symname = Getattr(n, "sym:name");
  845. (gdb) next
  846. 800 SwigType *t = Getattr(n, "type");
  847. (gdb) swigprint symname
  848. Shape_x_set
  849. (gdb) swigprint n
  850. Hash(0xb7d2afc8) {
  851. 'membervariableHandler:view' : variableHandler,
  852. 'feature:except' : 0,
  853. 'name' : x,
  854. 'ismember' : 1,
  855. 'sym:symtab' : Hash(0xb7d2aca8) {......},
  856. 'nodeType' : cdecl,
  857. 'nextSibling' : Hash(0xb7d2af98) {.............},
  858. 'kind' : variable,
  859. 'variableHandler:feature:immutable' : &lt;Object 'VoidObj' at 0xb7cfa008&gt;,
  860. 'sym:name' : Shape_x_set,
  861. 'view' : membervariableHandler,
  862. 'membervariableHandler:sym:name' : x,
  863. 'membervariableHandler:type' : double,
  864. 'membervariableHandler:parms' : &lt;Object 'VoidObj' at 0xb7cfa008&gt;,
  865. 'parentNode' : Hash(0xb7d2abc8) {..............................},
  866. 'feature:java:enum' : typesafe,
  867. 'access' : public,
  868. 'parms' : Hash(0xb7cb9408) {......},
  869. 'wrap:action' : if (arg1) (arg1)-&gt;x = arg2;,
  870. 'type' : void,
  871. 'memberset' : 1,
  872. 'sym:overname' : __SWIG_0,
  873. 'membervariableHandler:name' : x,
  874. }
  875. </pre>
  876. </blockquote>
  877. <p>
  878. Note that all the attributes in the Hash are shown, including the 'sym:name' attribute which was assigned to the <tt>symname</tt> variable.
  879. </p>
  880. <p>
  881. Hash types can be shown either expanded or collapsed.
  882. When a Hash is shown expanded, all the attributes are displayed along with their values, otherwise a '.' replaces each attribute when collapsed.
  883. Therefore a count of the dots provides the number of attributes within an unexpanded Hash.
  884. Below shows the 'parms' Hash being displayed with the default Hash expansion of 1, then with 2 provided as the second argument to <tt>swigprint</tt> to expand to two Hash levels in order to view the contents of the collapsed 'nextSibling' Hash.
  885. </p>
  886. <blockquote>
  887. <pre>
  888. (gdb) swigprint 0xb7cb9408
  889. Hash(0xb7cb9408) {
  890. 'name' : self,
  891. 'type' : p.Shape,
  892. 'self' : 1,
  893. 'nextSibling' : Hash(0xb7cb9498) {...},
  894. 'hidden' : 1,
  895. 'nodeType' : parm,
  896. }
  897. (gdb) swigprint 0xb7cb9408 2
  898. Hash(0xb7cb9408) {
  899. 'name' : self,
  900. 'type' : p.Shape,
  901. 'self' : 1,
  902. 'nextSibling' : Hash(0xb7cb9498) {
  903. 'name' : x,
  904. 'type' : double,
  905. 'nodeType' : parm,
  906. },
  907. 'hidden' : 1,
  908. 'nodeType' : parm,
  909. }
  910. </pre>
  911. </blockquote>
  912. <p>
  913. The same Hash can also be displayed with file and line location information via the <tt>locswigprint</tt> command.
  914. </p>
  915. <blockquote>
  916. <pre>
  917. (gdb) locswigprint 0xb7cb9408
  918. example.h:11: [Hash(0xb7cb9408) {
  919. Hash(0xb7cb9408) {
  920. 'name' : self,
  921. 'type' : p.Shape,
  922. 'self' : 1,
  923. 'nextSibling' : Hash(0xb7cb9498) {...},
  924. 'hidden' : 1,
  925. 'nodeType' : parm,
  926. }]
  927. </pre>
  928. </blockquote>
  929. <p>
  930. <b>Tip</b>: Commands in gdb can be shortened with whatever makes them unique and can be command completed with the tab key.
  931. Thus <tt>swigprint</tt> can usually be shortened to <tt>sw</tt> and <tt>locswigprint</tt> to <tt>loc</tt>.
  932. The help for each command can also be obtained within the debugging session, for example, 'help swigprint'.
  933. </p>
  934. <p>
  935. The sub-section below gives pointers for debugging DOH objects using casts and provides an insight into why it can be hard to debug SWIG without the family of print functions.
  936. <p>
  937. <a name="7.1" href="#i7.1">
  938. <h3>7.1 Debugging DOH Types The Hard Way</h3>
  939. </a>
  940. The DOH types used in SWIG are all typedefined to void and hence the lack of type information for inspecting types within a debugger.
  941. Most debuggers will however be able to display useful variable information when an object is cast to the appropriate type.
  942. Getting at the underlying C string within DOH types is cumbersome, but possible with appropriate casts.
  943. The casts below can be used in a debugger windows, but be sure to compile with compiler optimisations turned off before attempting the casts else they are unlikely to work.
  944. Even displaying the underlying string in a String * doesn't work straight off in all debuggers due to the multiple definitions of String as a struct and a void.
  945. <p>
  946. Below are a list of common SWIG types.
  947. With each is the cast that can be used in the debugger to extract the underlying type information and the underlying char * string.
  948. <ul>
  949. <p>
  950. <li>String *s;</li>
  951. <tt>(struct String *)((DohBase *)s)-&gt;data</tt>
  952. <br>
  953. The underlying char * string can be displayed with
  954. <br>
  955. <tt>(*(struct String *)(((DohBase *)s)-&gt;data)).str</tt>
  956. <p>
  957. <li>SwigType *t;</li>
  958. <tt>(struct String *)((DohBase *)t)-&gt;data</tt>
  959. <br>
  960. The underlying char * string can be displayed with
  961. <br>
  962. <tt>(*(struct String *)(((DohBase *)t)-&gt;data)).str</tt>
  963. <p>
  964. <li>const_String_or_char_ptr sc;</li>
  965. Either <br>
  966. <tt>(*(struct String *)(((DohBase *)sc)-&gt;data)).str</tt>
  967. <br> or <br>
  968. <tt>(char *)sc</tt>
  969. <br> will work depending on whether the underlying type is really a String * or char *.
  970. </ul>
  971. <hr>
  972. Copyright (C) 1999-2010 SWIG Development Team.
  973. </body>
  974. </html>