PageRenderTime 38ms CodeModel.GetById 18ms app.highlight 11ms RepoModel.GetById 1ms app.codeStats 1ms

/trunk/Doc/Devel/internals.html

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