SWIG Internals Manual

Thien-Thi Nguyen
ttn@glug.org

David M. Beazley
beazley@cs.uchicago.edu

$Header: /cvsroot/swig/SWIG/Doc/Devel/internals.html,v 1.7 2004/08/12 20:53:26 wsfulton Exp $

(Note : This is a work in progress.)

Table of Contents

1. Introduction

This document details SWIG internals: architecture and sometimes implementation. The first few sections concentrate on data structures, interfaces, conventions and code shared by all language targets. Subsequent sections focus on a particular language.

The audience is assumed to be SWIG developers (who should also read the SWIG Engineering Manual before starting to code).

1.1 Directory Guide

Doc HTML documentation. If you find a documentation bug, please let us know.
Examples This subdir tree contains examples of using SWIG w/ different scripting languages, including makefiles. Typically, there are the "simple" and "matrix" examples, w/ some languages offering additional examples. The GIFPlot example has its own set of per-language subdirectories. See the README more index.html file in each directory for more info. [FIXME: Ref SWIG user manual.]
Lib These are the .i (interface) files that form the SWIG installed library. Language-specific files are in subdirectories (for example, guile/typemaps.i). Each language also has a .swg file implementing runtime type support for that language. The SWIG library is not versioned.
Misc Currently this subdir only contains file fileheader. See the Engineering Manual for more info.
Source SWIG source code is in this subdir tree. Directories marked w/ "(*)" are used in building the swig executable.
DOH (*) C library providing memory allocation, file access and generic containers. Result: libdoh.a
Experiment [TODO]
Include (*) Configuration .h files
LParse Parser (lex / yacc) files and support [why not (*)?!]
Modules [TODO]
Modules1.1 (*) Language-specific callbacks that does actual code generation (each language has a .cxx and a .h file). Result: libmodules11.a
Preprocessor (*) SWIG-specialized C/C++ preprocessor. Result: libcpp.a
SWIG1.1 (*) Parts of SWIG that are not language-specific, including option processing and the type-mapping system. Result: libswig11.a. Note: This directory is currently being phased out.
SWIG1.3 [TODO] [funny, nothing here is presently used for swig-1.3]. This directory might turn into a compatibility interface between SWIG1.3 and the SWIG1.1 modules.
Swig (*) This directory contains the new ANSI C core of the system and contains generic functions related to types, file handling, scanning, and so forth.
Tools Libtool support and the mkdist.py script.
Win This improperly-named (spit spit) subdir only has README.txt.

1.2 Overall Program Flow

Here is the general control flow and where under subdir Source to look for code:

2. DOH

DOH is a collection of low-level objects such as strings, lists, and hash tables upon which the rest of SWIG is built. The name 'DOH' unofficially stands for "Dave's Object Hack", but it's also a good expletive to use when things don't work (as in "SWIG core dumped---DOH!").

2.1 Motivation and Background

The development of DOH is influenced heavily by the problems encountered during earlier attempts to create a C++ based version of SWIG2.0. In each of these attempts (over a 3 year period), the resulting system always ended up growing into a collossal nightmare of large inheritance hierarchies and dozens of specialized classes for different types of objects (functions, variables, constants, etc.). The end result was that the system was tremendously complicated, difficult to understand, difficult to maintain, and fairly inflexible in the grand scheme of things.

DOH takes a different approach to tackling the complexity problem. First, rather than going overboard with dozens of types and class definitions, DOH only defines a handful of simple yet very useful objects that are easy to remember. Second, DOH uses dynamic typing---one of the features that make scripting languages so useful and which make it possible to accomplish things with much less code. Finally, DOH utilizes a few coding tricks that allow it to perform a limited form of function overloading for certain C datatypes (more on that a little later).

The key point to using DOH is that instead of thinking about code in terms of highly specialized C data structures, just about everything ends up being represented in terms of a just a few datatypes. For example, structures are replaced by DOH hash tables whereas arrays are replaced by DOH lists. At first, this is probably a little strange to most C/C++ programmers, but in the long run in makes the system extremely flexible and highly extensible. Also, in terms of coding, many of the newly DOH-based subsystems are less than half the size (in lines of code) of the earlier C++ implementation.

2.2 Basic Types

The following built-in types are currently provided by DOH: Due to dynamic typing, all of the objects in DOH are represented by pointers of type DOH *. Furthermore, all objects are completely opaque--that means that the only way to access the internals of an object is through a well-defined public API. For convenience, the following symbolic names are sometimes used to improve readability: It should be stressed that all of these names are merely symbolic aliases to the type DOH * and that no compile-time type checking is performed (of course, a runtime error may occur if you screw up).

2.3 Creating, Copying, and Destroying Objects

The following functions can be used to create new DOH objects Any object can be copied using the Copy() function. For example:
DOH *a, *b, *c, *d;
a = NewString("Hello World");
b = NewList();
c = Copy(a);         /* Copy the string a */
d = Copy(b);         /* Copy the list b */
Copies of lists and hash tables are shallow. That is, their contents are only copied by reference.

Objects can be deleted using the Delete() function. For example:

DOH *a = NewString("Hello World");
...
Delete(a);              /* Destroy a */
All objects are referenced counted and given a reference count of 1 when initially created. The Delete() function only destroys an object when the reference count reaches zero. When an object is placed in a list or hash table, it's reference count is automatically increased. For example:
DOH *a, *b;
a = NewString("Hello World");
b = NewList();
Append(b,a);         /* Increases refcnt of a to 2 */
Delete(a);           /* Decreases refcnt of a to 1 */
Delete(b);           /* Destroys b, and destroys a */
Should it ever be necessary to manually increase the reference count of an object, the DohIncref() function can be used:
DOH *a = NewString("Hello");
DohIncref(a);

2.4 A Word About Mutability and Copying

All DOH objects are mutable regardless of their current reference count. For example, if you create a string and then create a 1000 references to it (in lists and hash tables), changes to the string will be reflected in all of the references. Therefore, if you need to make any kind of local change, you should first make a copy using the Copy() function. Caveat: when copying lists and hash tables, elements are copied by reference.

2.5 Strings

The DOH String type is perhaps the most flexible object. First, it supports a variety of string-oriented operations. Second, it supports many of the same operations as lists. Finally, strings provide file I/O operations that allow them to be used interchangably with DOH file objects. [ TODO ]

2.6 Lists

[ TODO ]

2.7 Hash tables

[ TODO ]

2.8 Files

[ TODO ]

2.9 Void objects

[ TODO ]

2.10 Utility functions

[ TODO ]

3. Types and Typemaps

Revised: Dave Beazley (8/14/00)

The representation and manipulation of types is currently in the process of being reorganized and (hopefully) simplified. The following list describes the current set of functions that are used to manipulate datatypes. These functions are different than in SWIG1.1 and may change names in the final SWIG1.3 release.

The following example illustrates the intended use of the above functions when creating wrapper functions using shorthand pseudocode. Suppose you had a function like this:
int foo(int a, double b[20][30], const char *c, double &d);
Here's how a wrapper function would be generated using the type generation functions above:
wrapper_foo() {
   lstr("int","result")
   lstr("int","arg0")
   lstr("double [20][30]", "arg1")
   lstr("const char *", "arg2")
   lstr("double &", "arg3")
   ...
   get arguments
   ...
   result = (lcaststr("int"))  foo(rcaststr("int","arg0"),
                               rcaststr("double [20][30]","arg1"),
                               rcaststr("const char *", "arg2"),
                               rcaststr("double &", "arg3"))
   ...
}
Here's how it would look with the corresponding output filled in:
wrapper_foo() {
   int      result;
   int      arg0;
   double  *arg1;
   char    *arg2;
   double  *arg3;
   ...
   get arguments
   ...
   result = (int) foo(arg0,
                      (double (*)[30]) arg1,
                      (const char *) arg2,
                      (double &) *arg3);
   ...
}
Notes: [TODO]

4. Parsing

[TODO]

5. Difference Between SWIG 1.1 and SWIG 1.3

[TODO]

6. Plans for SWIG 2.0

[TODO]

7. The C/C++ Wrapping Layer

Added: Dave Beazley (July 22, 2000)

When SWIG generates wrappers, it tries to provide a mostly seamless integration with the original code. However, there are a number of problematic features of C/C++ programs that complicate this interface.

The creation of wrappers and various type transformations are handled by a collection of functions found in the file Source/Swig/cwrap.c. Here is a short example showing how these functions could be used. Suppose you had a C function like this:
double dot_product(Vector a, Vector b);
Here's how you might write a really simple wrapper function
ParmList *l = ... parameter list of the function ...
DataType *t = ... return type of the function ...
char     *name = ... name of the function ...
Wrapper *w = NewWrapper();
Printf(w->def,"void wrap_%s() {\n", name);

/* Declare all of the local variables */
Swig_cargs(w, l);

/* Convert all of the arguments */
...

/* Make the function call and declare the result variable */
Swig_cresult(w,t,"result",Swig_cfunction(name,l));

/* Convert the result into whatever */
...

Printf(w->code,"}\n");
Wrapper_print(w,out);
The output of this would appear as follows:
void wrap_dot_product() {
    Vector *arg0;
    Vector *arg1;
    double  result;

    ...
    result = dot_product(*arg0, *arg1);
    ...
}
Notice that the Swig_cargs(), Swig_cresult(), and Swig_cfunction() functions have taken care of the type conversions for the Vector type automatically.

Notes:

8. Symbol Naming Guidelines for Generated C/C++ Code

The C++ standard (ISO/IEC 14882:1998(E)) states:

17.4.3.1.2 Global names [lib.global.names]

1 Certain sets of names and function signatures are always reserved to the implementation:

    * Each name that contains a double underscore (__) or begins with an underscore followed 
      by an upper case letter (2.11) is reserved to the implementation for any use.
    * Each name that begins with an underscore is reserved to the implementation for use as 
      a name in the global namespace.165)

    165) Such names are also reserved in namespace ::std (17.4.3.1). [back to text] 

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:

For C++ code that doesn't attempt to mangle a symbol being wrapped (for example SWIG convenience functions):

For code compiled as C or C++ that doesn't attempt to mangle a symbol being wrapped (for example SWIG convenience functions):

For code compiled as C or C++ that attempts to mangle a wrapped symbol: 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.

9. Debugging SWIG

Warning. Debugging SWIG is for the very patient.

The DOH types are all typedefined to void. Consequently, it is impossible for debuggers to extract any information about DOH objects. Most debuggers will be able to display useful variable information when an object is cast to the appropriate type. Below are some tips for displaying some of the DOH objects. Be sure to compile with compiler optimisations turned off before attempting the casts shown in a debugger window else they are unlikely to work. 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.

Below are a list of common SWIG types. With each is the cast that can be used in the debugger to extract the underlying type information and the underlying char * string.


Copyright (C) 1999-2004 SWIG Development Team.