PageRenderTime 93ms CodeModel.GetById 4ms RepoModel.GetById 0ms app.codeStats 0ms

/Doc/Devel/internals.html

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