The great merge

git-svn-id: https://swig.svn.sourceforge.net/svnroot/swig/trunk@4141 626c5289-ae23-0410-ae9c-e8d60b6d4f22
This commit is contained in:
Dave Beazley 2002-11-30 22:01:28 +00:00
commit 516036631c
1508 changed files with 125431 additions and 43485 deletions

View file

@ -3,3 +3,6 @@ Makefile
swig
*.tar.gz
configure
swig.spec
autom4te.cache
.gdbinit

View file

@ -1,54 +1,45 @@
*** ANNOUNCE: SWIG 1.3.16 ***
*** ANNOUNCE : SWIG1.3 (Alpha 5) ***
http://www.swig.org
September 22, 2000
October 14, 2002
Overview
--------
We're pleased to announce the next installment of the SWIG1.3
redevelopment effort. This release represents a reasonably stable
snapshot of the CVS repository that has undergone extensive testing
and debugging. However, this release also represents work in progress
so there may be obscure bugs and problems that we haven't found yet.
Please send us your feedback.
We're pleased to announce SWIG 1.3.16, the latest installment in the
SWIG development effort. SWIG-1.3.16 is mostly a bug-fix release to
SWIG-1.3.15.
What is SWIG?
-------------
SWIG is a software development tool that reads C/C++ header files and
generates the wrapper code needed to make C and C++ code accessible
from other languages including Perl, Python, Tcl, Ruby, PHP, Java,
Guile, Mzscheme, and Ocaml. Major applications of SWIG include
generation of scripting language extension modules, rapid prototyping,
testing, and user interface development for large C/C++ systems.
Availability:
-------------
The release is available for download on Sourceforge at
http://download.sourceforge.net/swig/swig1.3a5.tar.gz
http://prdownloads.sourceforge.net/swig/swig-1.3.16.tar.gz
What's new?
-----------
On the surface, this release still looks a lot like SWIG1.1p5 except
that a lot of bugs have been fixed and the language modules tend to
generate smaller and more efficient wrappers. New modules have also
been added to support Ruby and Mzscheme. In addition, Python, Perl,
and Guile support has been enhanced to support new releases such as
Python1.6 and Perl5.6.
Within the next day, a Windows version will also be made available at
Under the hood, you will find that this release is an almost complete
reimplementation of SWIG's internals. In fact the only code that
still remains from SWIG1.1 is the C/C++ parser and the language
modules (all of which have undergone significant changes as well). As
a result, a lot of minor improvements can be found throughout the
system and things that used to cause problems may now work (for
instance, pointers to functions are now supported). In addition, this
release incorporates a number of feature requests that have been made
on the mailing list.
http://prdownloads.sourceforge.net/swig/swigwin-1.3.16.zip
What's broken?
--------------
As this is a work in progress, a number of features are still missing
or incomplete. The documentation system is still missing and won't be
reimplemented for some time. The Java module is also temporarily out
of service for this release. In addition, C++ programmers who make
extensive use of typemaps may encounter a few strange problems
(although SWIG will generate warning messages).
Release numbers
---------------
With SWIG1.3, we are adopting an odd/even version numbering scheme for
SWIG. Odd version numbers (1.3, 1.5, 1.7, etc...) are considered to
be development releases. Even numbers (1.4,1.6,1.8) are stable
releases. The current 1.3 effort is working to produce a stable 2.0
release. A stable 2.0 release will not be made until it can
accompanied by fully updated documentation. In the meantime, we will
continue to make periodic 1.3.x releases.
We need your help!
------------------
Even if you are perfectly happy with SWIG1.1, we can use your
Even if you are perfectly happy with SWIG1.1, we can still use your
feedback. First, we like to know about compilation problems and other
issues concerning the building of SWIG. Second, if SWIG1.3 is unable
to compile your old interface files, we would like to get information
@ -56,18 +47,28 @@ about the features you are using. This information will help us find
bugs in the SWIG1.3 release, develop techniques for supporting
backwards compatibility, and write documentation that addresses
specific issues related to migrating from SWIG1.1 to SWIG1.3.
Finally, we are still looking for volunteers to work on aspects of
SWIG development. Please send email to beazley@cs.uchicago.edu for
details.
We are also looking for volunteers who would like to work on various
aspects of SWIG development. SWIG is an unfunded project that would
not exist without volunteers. We are also looking for the developers
of other SWIG language modules. If you have developed a SWIG module
and would like to see it incorporated into the new release, please
contact us to obtain SWIG-CVS access. We are also more than willing
to help port your module from SWIG1.1 to SWIG1.3. Please send email
to beazley@cs.uchicago.edu for further information.
Please report problems with this release to swig-dev@cs.uchicago.edu.
--- The SWIG Developers
David Beazley
Thien-Thi Nguyen
Matthias Köppe
Masaki Fukushima
Harco de Hilster
Loic Dachary
Oleg Tolmatcev

232
SWIG/CHANGES.current Normal file
View file

@ -0,0 +1,232 @@
Version 1.3.17 (November 22, 2002)
==================================
11/19/2002: beazley
Fixed [ 613922 ] preprocessor errors with HAVE_LONG_LONG.
11/19/2002: beazley
Fixed [ 615480 ] mzscheme SWIG_MustGetPtr_.
11/19/2002: beazley
Fixed [ 635119 ] SWIG_croak causes compiler warning.
11/16/2002: cheetah (William Fulton)
[Java] Added typemaps for pointers to class members.
11/15/2002: cheetah (William Fulton)
[Java] Bug fix: Overloaded C++ functions which cannot be overloaded in Java
once again issue a warning.
11/14/2002: cheetah (William Fulton)
[Java] Handling of NULL pointers is improved. A java null object will now
be translated to and from a NULL C/C++ pointer by default. Previously when
wrapping:
class SomeClass {...};
void foo(SomeClass *s);
and it was called from Java with null:
modulename.foo(null)
a Java NullPointerException was thrown. Extra typemaps had to be written in
order to obtain a NULL pointer to pass to functions like this one. Now the
default wrapping will detect 'null' and translate it into a NULL pointer.
Also if a function returns a NULL pointer, eg:
SomeClass *bar() { return NULL; }
Then this used to be wrapped with a SomeClass proxy class holding a NULL
pointer. Now null is returned instead. These changes are subtle but useful.
The original behaviour can be obtained by using the original typemaps:
%typemap(javaout) SWIGTYPE {
return new $&javaclassname($jnicall, true);
}
%typemap(javaout) SWIGTYPE *, SWIGTYPE &, SWIGTYPE [] {
return new $javaclassname($jnicall, $owner);
}
%typemap(javagetcptr) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE [] %{
protected static long getCPtr($javaclassname obj) {
return obj.swigCPtr;
}
%}
*** POTENTIAL INCOMPATIBILITY FOR JAVA MODULE ***
11/12/2002: beazley
Fixed problem with abstract methods and signatures. For example:
class abstract_foo {
public:
virtual int meth(int meth_param) = 0;
};
class abstract_bar : public abstract_foo {
public:
int meth(int meth_param_1, int meth_param_2) { return 0; }
};
In this case, abstract_bar is still abstract.
Fixes [ 628438 ] Derived abstract class not abstract.
Reported and patched by Scott Michel.
11/11/2002: beazley
Fixed a matching problem with typemaps and array dimensions. For example, if you
had this:
typedef char blah[20];
and a typemap:
%typemap() char [ANY] {
... $1_dim0 ...
}
then $1_dim* variables weren't be expanded properly. It should work now.
Problem reported by Pankaj Kumar Goel.
11/07/2002: mkoeppe
Added an experimental new module that dumps SWIG's parse
tree as (Common) Lisp s-expressions. The module is
invoked with SWIG's -sexp command-line switch. The output
can be read into Common Lisp. There is (prototype)
example Lisp code that generates Foreign Function Interface
definitions for use with Kevin Rosenberg's UFFI.
*** EXPERIMENTAL NEW FEATURE ***
11/07/2002: mkoeppe
Removed duplicate declaration of "cpp_template_decl" in
parser.y; bison 1.75 complained.
11/06/2002: cheetah (William Fulton)
[Java] Default primitive array handling has changed like arrays of classes.
C primitive arrays are no longer wrapped by a Java array but with a pointer
(type wrapper class). Again the changes have been made for efficiency reasons.
The original typemaps have been moved into arrays_java.i, so the original
behaviour can be obtained merely including this file:
%include "arrays_java.i"
The array support functions are no longer generated by default. They are only
generated when including this file, thus this often unused code is only
generated when specifically requiring this type of array support.
*** POTENTIAL INCOMPATIBILITY FOR JAVA MODULE ***
11/05/2002: ljohnson (Lyle Johnson)
[Ruby] Added support for nested module declarations (as was
previously added for the Perl module). So a %module directive
of the form:
%module "Outer::Inner::Foo"
will nest everything as (in Ruby code):
module Outer
module Inner
module Foo
# stuff goes here
end
end
end
11/05/2002: mkoeppe
[MzScheme] Add an argument (-declaremodule) that generates
code to correctly declare a primitive module extension.
Patch submitted by Bruce Butterfield.
11/02/2002: cheetah (William Fulton)
[Java] Added patch submitted by Michael Cahill to remove unused parameter
warnings for the jenv and cls parameters. This patch also also allows one
to use "void" in the jni typemap for any type without code being generated
attempting to return a value.
10/29/2002: cheetah (William Fulton)
[Java] Array handling is different. Arrays of classes are no longer wrapped
with proxy arrays, eg wrapping
class X {...};
X foo[10];
used to be wrapped with these Java getters and setters:
public static void setFoo(X[] value) {...}
public static X[] getFoo() {...}
This approach is very inefficient as the entire array is copied numerous
times on each invocation of the getter or setter. These arrays are now
wrapped with a pointer so it is only possible to access the first array element
using a proxy class:
public static void setFoo(X value) {...}
public static X getFoo() {...}
Arrays of enums have also been similarly changed. This behaviour is now like the
other SWIG language's implementation and the array library should be used to
access the other elements. The original behaviour can be achieved using the
macros and typemaps in arrays_java.i, for example:
%include "arrays_java.i"
JAVA_ARRAYSOFCLASSES(X)
class X {...};
X foo[10];
*** POTENTIAL INCOMPATIBILITY FOR JAVA MODULE ***
10/29/2002: cheetah (William Fulton)
[Java] Two new typemaps javain and javaout for generating the proxy class
and type wrapper class method calls to the JNI class. The new typemaps are
really used for transforming the jstype (used in proxy class and type wrapper
classes) to the jtype (used in the JNI class) and visa versa. A javain typemap
is required whenever an in typemap is written and similarly javaout for an out
typemap. An example is probably best to show them working:
%typemap(javain) Class "Class.getCPtr($javainput)"
%typemap(javain) unsigned short "$javainput"
%typemap(javaout) Class * {
return new Class($jnicall, $owner);
}
%inline %{
class Class {};
Class * bar(Class cls, unsigned short ush) { return new Class(); };
%}
The generated proxy code is then:
public static Class bar(Class cls, int ush) {
return new Class(exampleJNI.bar(Class.getCPtr(cls), ush), false);
}
Some new special variables have been introduced in order to use these typemaps.
Here $javainput has been replaced by 'cls' and 'ush'. $jnicall has been replaced by
the native method call, 'exampleJNI.bar(...)' and $owner has been replaced by 'false'.
$javainput is analogous to the $input special variable. It is replaced by the parameter name.
$jnicall is analogous to $action in %exception. It is replaced by the call to the native
method in the JNI class.
$owner is replaced by either true if %newobject has been used otherwise false.
The java.swg file contains default javain and javout typemaps which will produce the same code
as previously. This change is only of concern to those who have written their own typemaps as
you will then most likely have to write your own javain and javaout typemaps.
The javaout typemap also makes it possible to use a Java downcast to be used on abstract
proxy base classes. See the Java documentation on dynamic_cast.
*** POTENTIAL INCOMPATIBILITY FOR JAVA MODULE ***
10/24/2002: ttn
[Methodology] Upgaded to libtool 1.4.3, presumably w/ better
support for newish platforms (like MacOS X).
10/21/2002: ttn
Fixed Runtime/Makefile.in bug -- thanks to Richard Calmbach.
10/18/2002: ttn
Fixed typo in doh.h -- thanks to Max Horn.

View file

@ -0,0 +1,480 @@
<html>
<head>
<title>SWIG Engineering Manual</title>
</head>
<body bgcolor="#ffffff">
<center>
<h1>SWIG Engineering Manual</h1>
<b>David Beazley <br>
Department of Computer Science <br>
University of Chicago <br>
Chicago, IL 60637 <br>
beazley@cs.uchicago.edu <br>
</b>
</center>
<p>
<b>$Header$</b>
<p>
(Note : This is a work in progress.)
<h2>Table of Contents</h2>
<ul>
<li><a name="i1" href="#1">1. Introduction</a>
<li><a name="i2" href="#2">2. Programming Languages and Libraries</a>
<li><a name="i3" href="#3">3. The Source Directory and Module Names</a>
<li><a name="i4" href="#4">4. Include Files</a>
<li><a name="i5" href="#5">5. File Structure</a>
<li><a name="i6" href="#6">6. Bottom-Up Design</a>
<li><a name="i7" href="#7">7. Functions</a>
<li><a name="i8" href="#8">8. Naming Conventions</a>
<li><a name="i9" href="#9">9. Visibility</a>
<li><a name="i10" href="#10">10. Miscellaneous Coding Guidelines</a>
<li><a name="i11" href="#11">11. CVS Tagging Conventions</a>
</ul>
<a name="1" href="#i1">
<h2>1. Introduction</h2>
</a>
The purpose of this document is to describe various coding conventions
and organizational aspects for SWIG developers. The idea for this
document is largely borrowed from John Ousterhout's Tcl/Tk Engineering
Manual. It is not my intent to overly managerial about matters--rather I'm
hoping to make life a little less chaotic for everyone.
<p>
First a little background: SWIG was started in 1995 as a one-person
project and continued in this mode of operation until about 1998.
Most of this development was driven by ideas submitted by early SWIG
users as opposed to being motivated by a grand design. As a result,
the code ended up being a pretty horrible C++ coding disaster. A
mostly working disaster perhaps, but a disaster nonetheless.
<p>
With that said, the primary goal of future SWIG development is to
reengineer the original system, fix most of its inherent design flaws,
and to produce what I hope will become a highly extensible and modular
interface compiler framework. To this do this, there are a few
critical areas of work. First, I want to restructure SWIG as a
collection of loosely coupled modules written in either ANSI C or an
scripting language. Second, I want the system to be minimalistic in
its use of data structures and interconnections. The primary reason
for this is that the fewer data structures there are, the less users
will have to remember. This will also make the system more accessible
to non-experts. Finally, I want to reevaluate the whole idea of a
SWIG module is and expand the definition to include just about
anything from parsers, preprocessors, optimizers, interface editors,
and code generators.
<p>
The rest of this document outlines a few general rules of how code
should be developed within the SWIG project. These rules are
primarily drawn from my own experience developing software and
observing the practices of other successful projects.
<a name="2" href="#i2">
<h2>2. Programming Languages and Libraries </h2>
</a>
All SWIG modules must be written in either ANSI C or one of the
scripting languages for which SWIG can generate an interface (e.g.,
Perl, Python, or Tcl). C++ is currently being used to write
SWIG modules, but it is only being utilized to avoid working with
a lot of pointers to functions. <b>Advanced C++ features like namespaces, templates,
and overloading should not be used.</b>.
<p>
Module writers should make every attempt to use only those functions
described in the POSIX.1 standard. This includes most of the
functions contained the Kernighan and Ritchie C programming book. Use
of operating system dependent functionality such as socket libraries
should always be included inside a conditional compilation block so
that it can be omitted on problematic platforms. If you are unsure
about a library call, check the man page or contact Dave.
<a name="3" href="#i3">
<h2>3. The Source Directory and Module Names</h2>
</a>
All SWIG modules are contained within the "Source" directory. Within
this directory, each module is placed into its own subdirectory. The
name of this subdirectory should exactly match the name of the module.
For example, if you are creating a module called "Tcl", all of your
files should be placed in a directory "Tcl".
<p>
When choosing a module name, please pick a name that is not
currently in use. As a general convention, the first letter of a
module name is capitalized such as "Perl". Alternatives such as
"perl" or "PERL" should be avoided. In certain instances, the first
two letters may be capitalized as in "CParse." The exact usage of
this is somewhat inconsistent and isn't terribly important--just make
sure the first letter is capitalized. Also, module names should not
start with numbers, include underscores or any other special
non-alphanumeric characters.
<a name="4" href="#i4">
<h2>4. Include Files </h2>
</a>
All modules should include a header file that defines the public interface.
The name of this header file should be of the form "swigmodule.h" where
"module" is the name of your module. For example, if you created a
module "Perl", the header file should be named "swigperl.h". This scheme
should prevent header-file naming conflicts both within SWIG and when linking
parts of SWIG to the outside world.
<p>
All header files should include a short description, author information, copyright message,
CVS version, include guards, and be C++ aware. For example:
<blockquote>
<pre>
/* -------------------------------------------------------------------------
* swigperl.h
*
* All of the externally visible functions in the Perl module.
*
* Author(s) : David Beazley (beazley@cs.uchicago.edu)
*
* Copyright (C) 1999-2000, The University of Chicago.
* See the file LICENSE for information on usage and redistribution.
*
* $Header$
* ------------------------------------------------------------------------- */
#ifndef _SWIGPERL_H
#define _SWIGPERL_H 1
#ifdef __cplusplus
extern "C" {
#endif
/* Your declarations here */
...
#ifdef __cplusplus
}
#endif
#endif /* _SWIGPERL_H */
</pre>
</blockquote>
<p>
To minimize compilation time, please include as few other header files as possible.
<a name="5" href="#i5">
<h2>5. File Structure </h2>
</a>
Each file in a module should be given a filename that is all lowercase letters
such as "parser.c", not "Parser.c" or "PARSER.c". Please note that filenames
are case-insensitive on Windows so this convention will prevent you from inadvertantly
creating two files that differ in case-only.
<p>
Each file should include a short abstract, author information, copyright information, and
a CVS revision tag like this:
<blockquote>
<pre>
/* -----------------------------------------------------------------------------
* include.c
*
* This file implements the functions used to locate and include files in
* the SWIG library. Functions for maintaining the library search path are
* also located here.
*
* Author(s) : David Beazley (beazley@cs.uchicago.edu)
*
* Copyright (C) 1999-2000, The University of Chicago.
* See the file LICENSE for information on usage and redistribution.
* ----------------------------------------------------------------------------- */
static char cvsroot[] = "$Header$";
#include "swig.h"
/* Declarations */
typedef struct {
int x, y;
} Foo;
...
/* Private Declarations (used only in this file) */
static int avariable;
...
/* Functions */
...
</pre>
</blockquote>
The CVS revision tag should be placed into a static string as shown
above. This adds the revision information to the SWIG executable and
makes it possible to extract version information from a raw binary
(sometimes useful in debugging).
<p>
As a general rule, files start to get unmanagable once they exceed
about 2000 lines. Files larger than this should be broken up into
multiple files. Similarly, you should avoid the temptation to create
many small files as this increases compilation time and makes the
directory structure too complicated.
<a name="6" href="#i6">
<h2>6. Bottom-Up Design </h2>
</a>
Within each source file, the preferred organization is to use what is
known as "bottom-up" design. Under this scheme, lower-level functions
appear first and the highest level function appears last. The easy
way to remember is that the "main" function of your module should
always appear last in the source file. For example:
<blockquote>
<pre>
/* Simple bottom-up program */
#include &lt;stdio.h&gt;
int foo(int x, int y) {
/* Implement foo */
...
}
int bar() {
...
foo(i,j);
...
}
...
int main(int argc, char **argv) {
...
bar();
...
}
</pre>
</blockquote>
This choice of design is somewhat arbitrary however it has a number of
benefits particular to C. In particular, a bottom-up design generally
eliminates the need to include forward references--resulting in
cleaner code and fewer compilation errors.
<a name="7" href="#i7">
<h2>7. Functions</h2>
</a>
All functions should have a function header that gives the function name
and a short description like this:
<blockquote>
<pre>
/* -------------------------------------------------------------------------
* Swig_add_directory()
*
* Adds a directory to the SWIG search path.
* ------------------------------------------------------------------------- */
void
Swig_add_directory(DOH *dirname) {
...
}
</pre>
</blockquote>
In the function declaration, the return type and any specifiers
(extern or static) should appear on a separate line followed by the
function name and arguments as shown above. The left curly brace
should appear on the same line as the function name.
<p>
Function declarations should <b>NOT</b> use the pre-ANSI function
declaration syntax. The ANSI standard has been around long enough for
this to be a non-issue.
<a name="8" href="#i8">
<h2>8. Naming Conventions</h2>
</a>
The following conventions are used to name various objects throughout SWIG.
<h4>Functions</h4>
Functions should consist of the module name and the function name separated by an underscore like this:
<blockquote>
<pre>
Preprocessor_define()
Swig_add_directory()
</pre>
</blockquote>
In general, the module name should match the name of the module
subdirectory and the function name should be in all lowercase with
words separated by underscores.
<h4>Structures and Types</h4>
If your module defines new structures, the structure name should include the name of the
module and the name of the structure appended together like this:
<blockquote>
<pre>
typedef struct SwigScanner {
...
} SwigScanner;
typedef struct LParseType {
...
} LParseType;
</pre>
</blockquote>
In this case, both the name of the module and the type should be capitalized. Also, whenever
possible, you should use the "typedef struct Name { ... } Name" form when defining new
data structures.
<h4>Global Variables</h4>
Global variables should be avoided if at all possible. However, if you must use a global
variable, please prepend the module name and use the same naming scheme as for functions.
<h4>Constants</h4>
Constants should be created using #define and should be in all caps like this:
<blockquote>
<pre>
#define SWIG_TOKEN_LPAREN 1
</pre>
</blockquote>
Separate words in a constant should be separated by underscores as with functions.
<h4>Structure members</h4>
Structure members should be in all lower-case and follow the same word-separation convention
as for function names. However, the module name does not have to be included.
For example:
<blockquote>
<pre>
typedef struct SwigScanner {
DOH *text; /* Current token value */
DOH *scanobjs; /* Objects being scanned */
DOH *str; /* Current object being scanned */
char *idstart; /* Optional identifier start characters */
int next_token; /* Next token to be returned */
int start_line; /* Starting line of certain declarations */
int yylen; /* Length of text pushed into text */
DOH *file; /* Current file name */
} SwigScanner;
</pre>
</blockquote>
<h4>Static Functions and Variables </h4>
Static declarations are free to use any naming convention that is appropriate. However, most
existing parts of SWIG use lower-case names and follow the same convention as described for functions.
<a name="9" href="#i9">
<h2>9. Visibility</h2>
</a>
Modules should keep the following rules in mind when exposing their internals:
<ul>
<li>Only publicly accessible functions should be included in the module header file.
<li>All non-static declarations must be prepended with some form of the module name
to avoid potential linker namespace conflicts with other modules.
<li>Modules should not expose global variables or use global variables in their
public interface.
<li>Similarly, modules should discourage the direct manipulation of data contained
within data structures in favor of using function calls instead. For example,
instead of providing a user with a structure like this:
<blockquote>
<pre>
typedef struct Foo {
int line;
} Foo;
</pre>
</blockquote>
It is better to hide the implementation of Foo and provide an
function-call interface like this:
<blockquote>
<pre>
typedef struct Foo Foo;
extern int Foo_getline(Foo *f);
extern void Foo_setline(Foo *f, int line);
</pre>
</blockquote>
Although this results in worse performance, there are many practical
reasons for doing this. The most important reason is that it allows
you to change the internal representation of Foo without breaking all
of the other modules or having to recompile the entire universe after
making your changes.
</ul>
<a name="10" href="#i10">
<h2>10. Miscellaneous Coding Guidelines</h2>
</a>
<ul>
<li> Do not use the ternary ?: operator. It is unnecessarily error prone,
hard for people to read, and hard to maintain code that uses it.
[I don't agree w/ this guideline. ?: operator can be abused
just like everything else, but it can also be used cleanly. In some styles of
programming, it is the best tool for the job. --ttn]
</ul>
<a name="11" href="#i11">
<h2>11. CVS Tagging Conventions</h2>
</a>
Use <tt>cvs tag</tt> to declare some set of file revisions as related in some
symbolic way. This eases reference, retrieval and manipulation of these files
later. At the moment (2001/01/16 14:02:53), the conventions are very simple;
let's hope they stay that way!
<p>
There are two types of tags, internal (aka personal) and external.
Internal tags are used by SWIG developers primarily, whereas external
tags are used when communicating with people w/ anonymous cvs access.
<ul>
<li> Internal tags should start with the developer name and a hyphen.
<li> External tags should start with "v-".
</ul>
That's all there is to it. Some example tags:
<ul>
<li> ttn-pre-xml-patch
<li> ttn-post-xml-patch
<li> ttn-going-on-vacation-so-dutifully-tagging-now
<li> v-1-3-a37-fixes-bug-2432
<li> v-1-3-a37-fixes-bug-2433
<li> v-1-3-a37-fixes-bug-2432-again
<li> v-1-3-a37-release
</ul>
<hr>
Copyright (C) 1999-2001
<a href="mailto:swig-dev@cs.uchicago.edu">SWIG Development Team</a>
</body>
</html>

20
SWIG/Doc/Devel/index.html Normal file
View file

@ -0,0 +1,20 @@
<html>
<head>
<title>SWIG Documentation</title>
</head>
<body>
This directory contains SWIG documentation:
<ul>
<li><a href="engineering.html">Engineering Manual</a>
<li><a href="internals.html">Internals Manual</a>
<li><a href="migrate.txt">SWIG1.3 Migration Guide</a>
</ul>
<hr>
Copyright (C) 1999-2001
<a href="mailto:swig-dev@cs.uchicago.edu">SWIG Development Team</a>
</body>
</html>

View file

@ -0,0 +1,959 @@
<html>
<head>
<title>SWIG Internals</title>
</head>
<body>
<center>
<h1>SWIG Internals Manual</h1>
<b>Thien-Thi Nguyen <br>
ttn@glug.org <br>
<p>
David M. Beazley <br>
beazley@cs.uchicago.edu </br>
</b>
</center>
<p>
<b>$Header$</b>
<p>
(Note : This is a work in progress.)
<h2>Table of Contents</h2>
<ul>
<li><a name="i1" href="#1">1. Introduction</a>
<ul>
<li><a name="i1.1" href="#1.1">1.1 Directory Guide</a>
<li><a name="i1.2" href="#1.2">1.2 Overall Program Flow</a>
</ul>
<li><a name="i2" href="#2">2. DOH</a>
<ul>
<li><a name="i2.1" href="#2.1">2.1 Motivation and Background</a>
<li><a name="i2.2" href="#2.2">2.2 Basic Types</a>
<li><a name="i2.3" href="#2.3">2.3 Creating, Copying and Destroying Objects</a>
<li><a name="i2.4" href="#2.4">2.4 A Word About Mutability and Copying</a>
<li><a name="i2.5" href="#2.5">2.5 Strings</a>
<li><a name="i2.6" href="#2.6">2.6 Lists</a>
<li><a name="i2.7" href="#2.7">2.7 Hash Tables</a>
<li><a name="i2.8" href="#2.8">2.8 Files</a>
<li><a name="i2.9" href="#2.9">2.9 Void Objects</a>
<li><a name="i2.10" href="#2.10">2.10 Utility Functions</a>
</ul>
<li><a name="i3" href="#3">3. Types and Typemaps</a>
<li><a name="i4" href="#4">4. Parsing</a>
<li><a name="i5" href="#5">5. Difference Between SWIG 1.1 and SWIG 1.3</a>
<li><a name="i6" href="#6">6. Plans for SWIG 2.0</a>
<li><a name="i7" href="#7">7. C/C++ Wrapper Support Functions</a>
<li><a name="i8" href="#8">8. Reserved</a>
<li><a name="i9" href="#9">9. Reserved</a>
<li><a name="i10" href="#10">10. Guile Support</a>
<li><a name="i11" href="#11">11. Python Support</a>
<li><a name="i12" href="#12">12. Perl Support</a>
<li><a name="i13" href="#13">13. Java Support</a>
</ul>
<a name="1" href="#i1">
<h2>1. Introduction</h2>
</a>
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.
<p>
The audience is assumed to be SWIG developers (who should also read the
<a href="engineering.html">SWIG Engineering Manual</a> before starting
to code).
<a name="1.1" href="#i1.1">
<h3>1.1 Directory Guide</h3>
</a>
<table border=1>
<tr><td><a href="index.html">Doc</a></td>
<td>HTML documentation. If you find a documentation bug, please
<a href="mailto:bug-swig-doc@glug.org">let us know</a>.</td>
</tr>
<tr><td>Examples</td>
<td>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.]</td>
</tr>
<tr><td>Lib</td>
<td>These are the <tt>.i</tt> (interface) files that form the SWIG
installed library. Language-specific files are in subdirectories (for
example, guile/typemaps.i). Each language also has a <tt>.swg</tt> file
implementing runtime type support for that language. The SWIG library
is not versioned.</td>
</tr>
<tr><td>Misc</td>
<td>Currently this subdir only contains file <tt>fileheader</tt>. See
the <a href="engineering.html">Engineering Manual</a> for more
info.</td>
</tr>
<tr><td>Runtime</td>
<td>This subdir contains scripts and a makefile for creating runtime
shared-object libraries used by various languages. Runtime/make.sh
says: "The runtime libraries are only needed if you are building
multiple extension modules that need to share information."</td>
</tr>
<tr><td>Source</td>
<td>SWIG source code is in this subdir tree. Directories marked w/ "(*)"
are used in building the <tt>swig</tt> executable.
<table border=1>
<tr><td>DOH (*)</td>
<td>C library providing memory allocation, file access and generic
containers. Result: libdoh.a</td>
</tr>
<tr><td>Experiment</td>
<td>[TODO]</td>
</tr>
<tr><td>Include (*)</td>
<td>Configuration .h files</td>
</tr>
<tr><td>LParse</td>
<td>Parser (lex / yacc) files and support [why not (*)?!]</td>
</tr>
<tr><td>Modules</td>
<td>[TODO]</td>
</tr>
<tr><td>Modules1.1 (*)</td>
<td>Language-specific callbacks that does actual code generation (each
language has a .cxx and a .h file). Result: libmodules11.a</td>
</tr>
<tr><td>Preprocessor (*)</td>
<td>SWIG-specialized C/C++ preprocessor. Result: libcpp.a</td>
</tr>
<tr><td>SWIG1.1 (*)</td>
<td>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. </td>
</tr>
<tr><td>SWIG1.3</td>
<td>[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.</td>
</tr>
<tr><td>Swig (*)</td>
<td>This directory contains the new ANSI C core of the system
and contains generic functions related to types, file handling,
scanning, and so forth.</td>
</tr>
</table></td>
</tr>
<tr><td>Tools</td>
<td>Libtool support and the mkdist.py script.</td>
</tr>
<tr><td>Win</td>
<td>This improperly-named (spit spit) subdir only has README.txt.</td>
</tr>
</table>
<a name="1.2" href="#1.2">
<h3>1.2 Overall Program Flow</h3>
</a>
Here is the general control flow and where under subdir <tt>Source</tt>
to look for code:
<ul>
<li> <tt>Modules1.1/swigmain.cxx:main()</tt> is the program entry
point. It parses the language-specifying command-line option (for
example, <tt>-java</tt>), creating a new language-specific wrapping
object (each language is a C++ class derived from base class
<tt>Language</tt>). This object and the command-line is passed to
<tt>SWIG_main()</tt>, whose return value is the program exit value.
<li> <tt>SWIG1.1/main.cxx:SWIG_main()</tt> is the "real" main. It
initializes the preprocessor and typemap machinery, defines some
preprocessor symbols, locates the SWIG library, processes common
command-line options, and then calls the language-specific command-line
parser. From here there are three paths: "help", "checkout" and
everything else.
<ul>
<li> In "help" mode, clean up open files and exit.
<li> In "checkout" mode, copy specified files from the SWIG library
to the current directory. Errors cause error messages but no
non-lcoal exits.
<li> Otherwise, do wrapping: determine output file name(s), define
some preprocessor symbols and run the preprocessor, initialize
the interface-definition parser, set up the typemap for handling
new return strings, and finally do the language-specific parse
(by calling the language object's <tt>parse()</tt> method), which
creates output files by side-effect.
</ul>
Afterwards, remove temporary files, and clean up. If the command-line
included <tt>-freeze</tt>, go into an infinite loop; otherwise return the
error count.
<li> The language-specific <tt>parse()</tt> (and all other
language-specific code) lives in <tt>Modules1.1/foo.{h,cxx}</tt> for
language Foo. Typically, <tt>FOO::parse()</tt> calls
<tt>FOO::headers()</tt> and then the global function <tt>yyparse()</tt>,
which uses the callbacks registered by <tt>SWIG_main()</tt> above.
</ul>
<a name="2" href="#i2">
<h2>2. DOH</h2>
</a>
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!").
<a name="2.1" href="#2.1">
<h3>2.1 Motivation and Background</h3>
</a>
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.
<p>
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).
<p>
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.
<a name="2.2" href="#i2.2">
<h3>2.2 Basic Types</h3>
</a>
The following built-in types are currently provided by DOH:
<ul>
<li><b>String</b>. A string of characters with automatic memory
management and high-level operations such as string replacement. In addition,
strings support file I/O operations that make it possible to use them just
about anyplace a file can be used.
<p>
<li><b>List</b>. A list of arbitrary DOH objects (of possibly mixed types).
<p>
<li><b>Hash</b>. A hash table that maps a set of string keys to a set of arbitrary
DOH objects. The DOH version of an associative array for all of you Perl fans.
<p>
<li><b>File</b>. A DOH wrapper around the C FILE * structure. This is provided
since other objects sometimes want to behave like files (strings for instance).
<p>
<li><b>Void</b>. A DOH wrapper around an arbitrary C pointer. This can be used
if you want to place arbitrary C data structures in DOH lists and hash tables.
</ul>
Due to dynamic typing, all of the objects in DOH are represented by pointers
of type <tt>DOH *</tt>. 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:
<ul>
<Li><tt>DOHString *</tt>. A String object.
<li><tt>DOHList *</tt>. A list object.
<li><tt>DOHHash *</tt>. A hash object.
<li><tt>DOHFile *</tt>. A file object.
<li><tt>DOHVoid *</tt>. A void object.
<li><tt>DOHString_or_char *</tt>. A DOH String object or a raw C "char *".
</ul>
It should be stressed that all of these names are merely symbolic aliases to the
type <tt>DOH *</tt> and that no compile-time type checking is performed (of course,
a runtime error may occur if you screw up).
<a name="2.3" href="#i2.3">
<h3>2.3 Creating, Copying, and Destroying Objects </h2>
</a>
The following functions can be used to create new DOH objects
<ul>
<Li><tt>NewString(DOHString_or_char *value)</tt><br>
Create a new string object with contents initially
set to value. value can be either a C string or a DOH string object.
<p>
<li><tt>NewStringf(char *fmt, ...)</tt><br>
Create a new string object with contents initially set to
a formatted string. Think of this as being sprintf() combined with an object constructor.
<p>
<li><tt>NewList()</tt><br>
Create a new list object that is initially empty.
<p>
<Li><tt>NewHash()</tt><br>
Create a new hash object that is initially empty.
<p>
<li><tt>NewFile(DOHString_or_char *filename, char *mode)</tt><br>
Open a file and return a file object. This is a
wrapper around the C <tt>fopen()</tt> library call.
<p>
<li><tt>NewFileFromFile(FILE *f)</tt><br>
Create a new file object given an already opened <tt>FILE *</tt> object.
<p>
<li><tt>NewVoid(void *obj, void (*del)(void *))</tt><br>
Create a new DOH object that is a wrapper around an
arbitrary C pointer. <tt>del</tt> is an optional destructor function that will be called when the object
is destroyed.
</ul>
Any object can be copied using the <tt>Copy()</tt> function. For example:
<blockquote>
<pre>
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 */
</pre>
</blockquote>
Copies of lists and hash tables are shallow. That is, their contents are only copied by reference.
<p>
Objects can be deleted using the <tt>Delete()</tt> function. For example:
<blockquote>
<pre>
DOH *a = NewString("Hello World");
...
Delete(a); /* Destroy a */
</pre>
</blockquote>
All objects are referenced counted and given a reference count of 1 when initially created. The
<tt>Delete()</tt> 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:
<blockquote>
<pre>
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 */
</pre>
</blockquote>
Should it ever be necessary to manually increase the reference count of an object, the DohIncref() function
can be used:
<blockquote>
<pre>
DOH *a = NewString("Hello");
DohIncref(a);
</pre>
</blockquote>
<a name="2.4" href="#i2.4">
<h3>2.4 A Word About Mutability and Copying</h3>
</a>
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.
<a name="2.5" href="#i2.5">
<h3>2.5 Strings</h3>
</a>
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 ]
<a name="2.6" href="#i2.6">
<h3>2.6 Lists</h3>
</a>
[ TODO ]
<a name="2.7" href="#i2.7">
<h3>2.7 Hash tables </h3>
</a>
[ TODO ]
<a name="2.8" href="#i2.8">
<h3>2.8 Files </h3>
</a>
[ TODO ]
<a name="2.9" href="#i2.9">
<h3>2.9 Void objects </h3>
</a>
[ TODO ]
<a name="2.10" href="#i2.10">
<h3>2.10 Utility functions </h3>
</a>
[ TODO ]
<a name="3" href="#i3">
<h2>3. Types and Typemaps</h2>
</a>
Revised: Dave Beazley (8/14/00)
<p>
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.
<ul>
<li><tt>SwigType_str(SwigType *t, char *name)</tt>.<br>
This function produces the exact string
representation of the datatype <tt>t</tt>. <tt>name</tt> is an optional parameter that
specifies a declaration name. This is used when dealing with more complicated datatypes
such as arrays and pointers to functions where the output might look something like
"<tt>int (*name)(int, double)</tt>".
<p>
<li><tt>SwigType_lstr(SwigType *t, char *name)</tt>.<br>
This function produces a string
representation of a datatype that can be safely be assigned a value (i.e., can be used as the
"lvalue" of an expression). To do this, qualifiers such as "const", arrays, and references
are stripped away or converted into pointers. For example:
<blockquote>
<pre>
Original Datatype lstr()
------------------ --------
const char *a char *a
double a[20] double *a
double a[20][30] double *a
double &a double *a
</pre>
</blockquote>
The intent of the lstr() function is to produce local variables inside wrapper functions--all
of which must be reassignable types since they are the targets of conversions from a scripting
representation.
<p>
<li><tt>SwigType_rcaststr(SwigType *t, char *name)</tt>.
<br> This function produces a string
that casts a type produced by the <tt>lstr()</tt> function to the type produced by the
<tt>str()</tt> function. You might view it as the inverse of lstr(). This function only produces
output when it needs to (when str() and lstr() produce different results). Furthermore, an optional
name can be supplied when the cast is to be applied to a specific name. Examples:
<blockquote>
<pre>
Original Datatype rcaststr()
------------------ ---------
char *a
const char *a (const char *) name
double a[20] (double *) name
double a[20][30] (double (*)[30]) name
double &a (double &) *name
</pre>
</blockquote>
<p>
<li><tt>SwigType_lcaststr(SwigType *t, char *name)</tt>.
<br> This function produces a string
that casts a type produced by the <tt>str()</tt> function to the type produced by the
<tt>lstr()</tt> function. This function only produces
output when it needs to (when str() and lstr() produce different results). Furthermore, an optional
name can be supplied when the cast is to be applied to a specific name.
<blockquote>
<pre>
Original Datatype lcaststr()
------------------ ---------
char *a
const char *a (char *) name
double a[20] (double *) name
double a[20][30] (double *) name
double &a (double *) &name
</pre>
</blockquote>
<p>
<li><tt>SwigType_manglestr(SwigType *t)</tt>. <br>
Produces a type-string that is used to identify this datatype in the target scripting language.
Usually this string looks something like "<tt>_p_p_double</tt>" although the target language
may redefine the output for its own purposes. Normally this function strips all qualifiers,
references, and arrays---producing a mangled version of the type produced by the <tt>lstr()</tt> function.
</ul>
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:
<blockquote>
<pre>
int foo(int a, double b[20][30], const char *c, double &amp;d);
</pre>
</blockquote>
Here's how a wrapper function would be generated using the type generation functions above:
<blockquote>
<pre>
wrapper_foo() {
lstr("int","result")
lstr("int","arg0")
lstr("double [20][30]", "arg1")
lstr("const char *", "arg2")
lstr("double &amp;", "arg3")
...
get arguments
...
result = (lcaststr("int")) foo(rcaststr("int","arg0"),
rcaststr("double [20][30]","arg1"),
rcaststr("const char *", "arg2"),
rcaststr("double &amp;", "arg3"))
...
}
</pre>
</blockquote>
Here's how it would look with the corresponding output filled in:
<blockquote>
<pre>
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 &amp;) *arg3);
...
}
</pre>
</blockquote>
<b>Notes:</b>
<ul>
<li>For convenience, the string generation functions return a
"<tt>char *</tt>" that points to statically allocated memory living
inside the type library. Therefore, it is never necessary (and it's
an error) to free the pointer returned by the functions. Also, if you
need to save the result, you should make a copy of it. However, with
that said, it is probably worth nothing that these functions do cache
the last 8 results. Therefore, it's fairly safe to make a handful of
repeated calls without making any copies.
</ul>
[TODO]
<a name="4" href="#i4">
<h2>4. Parsing</h2>
</a>
[TODO]
<a name="5" href="#i5">
<h2>5. Difference Between SWIG 1.1 and SWIG 1.3</h2>
</a>
[TODO]
<a name="6" href="#i6">
<h2>6. Plans for SWIG 2.0</h2>
</a>
[TODO]
<a name="7" href="#i7">
<h2>7. The C/C++ Wrapping Layer</h2>
</a>
Added: Dave Beazley (July 22, 2000)
<p>
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.
<ul>
<li><b>Passing and returning structures by value.</b> When used, SWIG converts
all pass-by-value functions into wrappers that pass by reference. For example:
<blockquote>
<pre>
double dot_product(Vector a, Vector b);
</pre>
</blockquote>
gets turned into a wrapper like this:
<blockquote>
<pre>
double wrap_dot_product(Vector *a, Vector *b) {
return dot_product(*a,*b);
}
</pre>
</blockquote>
Functions that return by value require a memory allocation to store the result. For example:
<blockquote>
<pre>
Vector cross_product(Vector *a, Vector *b);
</pre>
</blockquote>
become
<blockquote>
<pre>
Vector *wrap_cross_product(Vector *a, Vector *b) {
Vector *result = (Vector *) malloc(sizeof(Vector));
*result = cross_product(a,b);
return result;
}
</pre>
</blockquote>
Note: If C++ is being wrapped, the default copy constructor is used
instead of malloc() to create a copy of the return result.
<p>
<li><b>C++ references</b>. C++ references are handled exactly the same as
pass/return by value except that a memory allocation is not made for functions
that return a reference.
<p>
<li><b>Qualifiers such as "const" and "volatile".</b> SWIG strips all
qualifiers from the interface presented to the target language.
Besides, what in the heck is "const" in Perl anyways?
<p>
<li><b>Instance Methods</b>. Method invocations are handled as a function call in which
a pointer to the object (the "this" pointer) appears as the first argument. For example, in
the following class:
<blockquote>
<pre>
class Foo {
public:
double bar(double);
};
</pre>
</blockquote>
The "bar" method is wrapped by a function like this:
<blockquote>
<pre>
double Foo_bar(Foo *self, double arg0) {
return self->bar(arg0);
}
</pre>
</blockquote>
<p>
<li><b>Structure/class data members</b>. Data members are handled by creating a pair
of wrapper functions that set and get the value respectively. For example:
<blockquote>
<pre>
struct Foo {
int x;
};
</pre>
</blockquote>
gets wrapped as follows:
<blockquote>
<pre>
int Foo_x_get(Foo *self) {
return self->x;
}
int Foo_x_set(Foo *self, int value) {
return (self->x = value);
}
</pre>
</blockquote>
<p>
<li><b>Constructors</b>. Constructors for C/C++ data structures are wrapped by
a function like this:
<blockquote>
<pre>
Foo *new_Foo() {
return new Foo;
}
</pre>
</blockquote>
Note: For C, new objects are created using the calloc() function.
<p>
<li><b>Destructors</b>. Destructors for C/C++ data structures are wrapper like this:
<blockquote>
<pre>
void delete_Foo(Foo *self) {
delete self;
}
</pre>
</blockquote>
Note: For C, objects are destroyed using free().
</ul>
The creation of wrappers and various type transformations are handled by a collection of functions
found in the file <tt>Source/Swig/cwrap.c</tt>.
<ul>
<li>
<tt>char *Swig_clocal(DataType *t, char *name, char *value)</tt><br>
This function creates a string containing the declaration of a local variable with
type <tt>t</tt>, name <tt>name</tt>, and default value <tt>value</tt>. This local
variable is stripped of all qualifiers and will be a pointer if the type is a reference
or user defined type.
<p>
<li>
<tt>DataType *Swig_clocal_type(DataType *t)</tt><br>
Returns a type object corresponding to the type string produced by the Swig_clocal() function.
<p>
<li><tt>char *Swig_clocal_deref(DataType *t, char *name)</tt><br>
This function is the inverse of the <tt>clocal()</tt> function. Given a type and a name,
it produces a string containing the code needed to cast/convert the type produced by
<tt>Swig_clocal()</tt> back into it's original type.
<p>
<li><tt>char *Swig_clocal_assign(DataType *t, char *name)</tt><br>
Given a type and name, this produces a string containing the code (and an optional cast)
needed to make an assignment from the real datatype to the local datatype produced
by <tt>Swig_clocal()</tt>. Kind of the opposite of deref().
<p>
<li><tt>int Swig_cargs(Wrapper *w, ParmList *l)</tt><br>
Given a wrapper function object and a list of parameters, this function declares a set
of local variables for holding all of the parameter values (using Swig_clocal()). Returns
the number of parameters. In addition, this function sets the local name of each parameter
which can be retrieved using the <tt>Parm_Getlname()</tt> function.
<p>
<li><tt>void Swig_cresult(Wrapper *w, DataType *t, char *resultname, char *decl)</tt><br>
Generates the code needed to set the result of a wrapper function and performs all of
the needed memory allocations for ANSI C (if necessary). <tt>t</tt> is the type of the
result, <tt>resultname</tt> is the name of the result variable, and <tt>decl</tt> is
a string that contains the C code which produces the result.
<p>
<li><tt>void Swig_cppresult(Wrapper *w, DataType *t, char *resultname, char *decl)</tt><br>
Generates the code needed to set the result of a wrapper function and performs all of
the needed memory allocations for C++ (if necessary). <tt>t</tt> is the type of the
result, <tt>resultname</tt> is the name of the result variable, and <tt>decl</tt> is
a string that contains the C code which produces the result.
<p>
<li><tt>Wrapper *Swig_cfunction_wrapper(char *fname, DataType *rtype, ParmList *parms, char *code)</tt><br>
Create a wrapper around a normal function declaration. <tt>fname</tt> is the name of the wrapper,
<tt>rtype</tt> is the return type, <tt>parms</tt> are the function parameters, and <tt>code</tt> is a
string containing the code in the function body.
<p>
<li><tt>Wrapper *Swig_cmethod_wrapper(char *classname, char *methodname, DataType *rtype, DataType *parms, char *code)</tt><br>
<p>
<li><tt>char *Swig_cfunction_call(char *name, ParmList *parms)</tt>
This function produces a string containing the code needed to call a C function.
The string that is produced contains all of the transformations needed to convert
pass-by-value into pass-by-reference as well as handle C++ references. Produces
a string like "name(arg0, arg1, ..., argn)".
</ul>
Here is a short example showing how these functions could be used. Suppose you had a
C function like this:
<blockquote>
<pre>
double dot_product(Vector a, Vector b);
</pre>
</blockquote>
Here's how you might write a really simple wrapper function
<blockquote>
<pre>
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);
</pre>
</blockquote>
The output of this would appear as follows:
<blockquote>
<pre>
void wrap_dot_product() {
Vector *arg0;
Vector *arg1;
double result;
...
result = dot_product(*arg0, *arg1);
...
}
</pre>
</blockquote>
Notice that the <tt>Swig_cargs()</tt>, <tt>Swig_cresult()</tt>, and <tt>Swig_cfunction()</tt> functions
have taken care of the type conversions for the <tt>Vector</tt> type automatically.
<p>
<b>Notes:</b>
<ul>
<Li>The intent of these functions is to provide <em>consistent</em> handling of function parameters
and return values so that language module writers don't have to worry about it too much.
<p>
<li>These functions may be superceded by features in the new typemap system which provide hooks
for specifying local variable declarations and argument conversions.
</ul>
<a name="8" href="#i8">
<h2>8. Reserved</h2>
</a>
<a name="9" href="#i9">
<h2>9. Reserved</h2>
</a>
<a name="10" href="#i10">
<h2>10. Guile Support</h2>
</a>
The information that used to live here has moved to the user
documentation, file <code>Guile.html</code>.
<a name="11" href="#i11">
<h2>11. Python Support</h2>
</a>
[TODO]
<a name="12" href="#i12">
<h2>12. Perl Support</h2>
</a>
[TODO]
<a name="13" href="#i13">
<h2>13. Java Support</h2>
</a>
[TODO]
<hr>
Copyright (C) 1999-2001
<a href="mailto:swig-dev@cs.uchicago.edu">SWIG Development Team</a>
</body>
</html>

140
SWIG/Doc/Devel/migrate.txt Normal file
View file

@ -0,0 +1,140 @@
SWIG1.3 Migration Guide
(The not entirely complete guide to updating language modules to work with SWIG1.3).
Dave Beazley
August 15, 2000
1. Introduction
---------------
Virtually all of SWIG's internal data structures have now been
rewritten. Take everything you thought you knew about SWIG1.1 and
throw it out.
2. DataTypes
------------
The old 'DataType' data structure is gone. Therefore, direct
manipulation of 'is_pointer', 'implicit_ptr', and 'arraystr'
attributes no longer applies. Sorry.
Datatypes are now represented by the type 'SwigType' which has no
public attributes. Actually, if you look at it closely, 'SwigType' is
really just an alias for 'void' and if you look at it even closer than
that you will realize that it's nothing more than a string!
The string encoding of types is described in more detail in the file
Source/Swig/stype.c and is not so important here. What is important is
the functions used to produce various types of output:
SwigType_str(type,name = 0);
This produces an exact C representation of the datatype with all
qualifiers, arrays, references, and so forth. name is an optional
name that is given if you wanted to associate the type with a
parameter name or something.
SwigType_lstr(type,name = 0);
This function takes a type and produces a C string containing
a type suitable for assignment (appearing as an lvalue in an
expression). To do this, certain things such as 'const',
arrays, and references are stripped away or converted into
pointers.
SwigType_ltype(type);
Returns a SwigType object corresponding to the type created
by SwigType_lstr().
SwigType_lcaststr(type,name);
Produces a string casting a value 'name' from the real datatype
to the assignable type created by SwigType_lstr().
SwigType_rcaststr(type,name)
Produces a string that casts a value 'name' from the type
created by SwigType_lstr() to the real datatype.
SwigType_manglestr(type)
Produces the 'mangled' version of a datatype.
Getting the 'type' code. Most language modules still operate by
looking at special integer type codes. This interface is a little
ragged and will probably go away at some point. However, for now the
following function can be used to get the type code:
int SwigType_type(type)
The codes are the same as the before, except that there are a few
special codes:
T_STRING - The 'char *' type and variations.
T_POINTER - Any pointer type (not char * though)
T_REFERENCE - Any C++ reference
T_ARRAY - Any array
T_FUNCTION - A function (this is usually an error).
Because of the special codes, it is no longer necessary to have code like this:
if ((t->is_pointer == 1) and (t->type == T_CHAR)) {
... get a string ...
}
Instead, just use the type code above like this:
switch(SwigType_type(type)) {
case T_STRING:
... get a string ...
break;
case T_POINTER:
... get a pointer ...
break;
}
There are about 2-dozen type manipulation functions that could also be useful.
See Source/Swig/swig.h and Source/Swig/stype.c.
3. Parameter Lists
------------------
The ParmList data structure is gone. In reality, parameter lists are nothing more than
a linked list of parameters. The proper way to iterate over this list and get
parameter values is as follows:
ParmList *l;
Parm *p;
for (p = l; p; p = Getnext(p)) {
SwigType *pt = Gettype(p); /* Get parameter type */
String *pn = Getname(p); /* Get parameter name */
String *value = Getvalue(p); /* Get parameter value */
...
do whatever
...
}
4. Typemaps
-----------
Typemaps more or less work. However, the interface has changed slightly. Instead of
typemap_lookup("in","python",type,pname,"$source","$target",wrapper);
the function is
Swig_typemap_lookup("in",type,pname,"$source","$target",wrapper);
There are a variety of other changes to typemaps (see CHANGES).
5. Use of new types
-------------------
When possible, language modules should try to use the built in String,
List, and Hash objects instead of C arrays or 'char *'. This will probably require a
detailed pass through the code with an eye towards cleanup.
6. Miscellaneous
----------------
Language modules no longer need to concern themselves with formatting the
wrapper code they produce (provided you are using the special Wrapper object).
The function Wrapper_print() passes everything through a pretty-printer that
automatically performs indentation and tries to clean things up. This especially
works well when there are lots of typemaps.

View file

@ -0,0 +1,54 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>About this manual</title>
</head>
<body bgcolor="#ffffff">
<h1>About This Manual</h1><p>
The HTML version of the SWIG Users Manual is a direct translation
of the printed version which is produced using Framemaker 5. The
conversion process was roughly as follows :
<ul>
<li> Raw HTML was produced using Framemaker 5 and Quadralay WebWorks Lite.
<li> Tables and figures were converted into GIF images.
<li> All of this output was fed into a magic Python script that cleaned
up the HTML source and merged the GIF figures into the text.
<li> A table of contents and alphabetized topic index were produced from
HTML heading tags by the same script.
<li> Each <TT>.html</TT> file was manually prefixed with the
"<!DOCTYPE html ..." jazz (boilerplate).
</ul>
While the conversion process is mostly complete, there are a few things
to keep in mind :
<ul>
<li> Some sections of preformatted text may have weird formatting
problems.
<li> Framemaker tables were converted into GIF images instead
of HTML tables--this is a little weird, but the easiest
approach for now.
<li> There may be a few minor formatting problems throughout
due to minor "glitches" that slipped through the conversion process
(although I've tried to correct as many as these as possible).
<li> The printed version of the SWIG manual is more than
300 pages long--resulting in about 670 Kbytes of HTML. The HTML version
is broken up into chapters. Each chapter is fairly well-contained, but
some may contain as many as 50 pages of printed text.
</ul>
Please report any problems with the documentation to beazley@cs.utah.edu.
<hr>
<address>
Last Modified : August 3, 1997</address>
</body>
</html>

View file

@ -0,0 +1,350 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<!-- Published by Quadralay WebWorks HTML Lite 1.5.1 -->
<!-- And munged by Dave's special Python script -->
<html>
<head>
<title>Advanced Topics</title>
</head>
<body bgcolor="#ffffff">
<a name="n1"></a><H1>13 Advanced Topics</H1>
<!-- INDEX -->
<ul>
<li><a href="#n2">Creating multi-module packages</a>
<ul>
<li><a href="#n3">Runtime support (and potential problems)</a>
<li><a href="#n4">Why doesn't C++ inheritance work between modules?</a>
<li><a href="#n5">The SWIG runtime library</a>
<li><a href="#n6">A few dynamic loading gotchas</a>
</ul>
<li><a href="#n7">Dynamic Loading of C++ modules</a>
<li><a href="#n8">Inside the SWIG type-checker</a>
<ul>
<li><a href="#n9">Type equivalence</a>
<li><a href="#n10">Type casting</a>
<li><a href="#n11">Why a name based approach?</a>
<li><a href="#n12">Performance of the type-checker</a>
</ul>
</ul>
<!-- INDEX -->
<b>Caution: This chapter is under repair!</b>
<a name="n2"></a><H2>13.1 Creating multi-module packages</H2>
SWIG can be used to create packages consisting of many different modules. However, there are some technical aspects of doing this and techniques for managing the problem.<p>
<a name="n3"></a><H3>13.1.1 Runtime support (and potential problems)</H3>
All SWIG generated modules rely upon a small collection of functions that are used during run-time. These functions are primarily used for pointer type-checking, exception handling, and so on. When you run SWIG, these functions are included in the wrapper file (and declared as static). If you create a system consisting of many modules, each one will have an identical copy of these runtime libraries :<p>
<center><img src="ch11.1.png"></center><p>
<p>
This duplication of runtime libraries is usually harmless since there are no namespace conflicts and memory overhead is minimal. However, there is serious problem related to the fact that modules do not share type-information. This is particularly a problem when working with C++ (as described next).<p>
<a name="n4"></a><H3>13.1.2 Why doesn't C++ inheritance work between modules?</H3>
Consider for a moment the following two interface files :<p>
<p>
<blockquote><pre>// File : a.i
%module a
// Here is a base class
class a {
public:
a();
~a();
void foo(double);
};
// File : b.i
%module b
// Here is a derived class
%import a.i // Gets definition of base class
class b : public a {
public:
bar();
};
</pre></blockquote>
When compiled into two separate modules, the code does not work properly. In fact, you get a type error such as the following:<p>
<p>
<blockquote><pre>
[beazley@guinness shadow]$ <b>python</b>
Python 1.4 (Jan 16 1997) [GCC 2.7.2]
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
&gt;&gt;&gt; <b>from a import *</b>
&gt;&gt;&gt; <b>from b import *</b>
&gt;&gt;&gt; <b># Create a new "b"</b>
&gt;&gt;&gt; <b>b = new_b()</b>
&gt;&gt;&gt; <b># Call a function in the base class</b>
...
&gt;&gt;&gt; <b>a_foo(b,3)</b>
Traceback (innermost last):
File "&lt;stdin&gt;", line 1, in ?
TypeError: Type error in argument 1 of a_foo. Expected _a_p.
&gt;&gt;&gt;
</pre></blockquote>
<p>
However, from our class definitions we know that "b" is an "a" by inheritance and there should be no type-error. This problem is directly due to the lack of type-sharing between modules. If we look closely at the module modules created here, they look like this :<p>
<center><img src="ch11.2.png"></center><p>
<p>
The type information listed shows the acceptable values for various C datatypes. In the "a" module, we see that "a" can only accept instances of itself. In the "b" module, we see that "a" can accept both "a" and "b" instances--which is correct given that a "b" is an "a" by inheritance.<p>
<p>
Unfortunately, this problem is inherent in the method by which SWIG makes modules. When we made the "a" module, we had no idea what derived classes might be used at a later time. However, it's impossible to produce the proper type information until after we know all of the derived classes. A nice problem to be sure, but one that can be fixed by making all modules share a single copy of the SWIG run-time library.<p>
<a name="n5"></a><H3>13.1.3 The SWIG runtime library</H3>
To reduce overhead and to fix type-handling problems, it is possible to share the SWIG run-time functions between multiple modules. This requires the use of the SWIG runtime library which is optionally built during SWIG installation. To use the runtime libraries, follow these steps:<p>
<p>
1. Build the SWIG run-time libraries. The <tt>SWIG/Runtime</tt> directory contains a makefile for doing this. If successfully built, you will end up with 8 files that are usually installed in <tt>/usr/local/lib</tt>.<p>
<p>
<blockquote><pre>
libswigpl.a # Perl library (static)
libswigpl.so # Perl library (shared)
libswigpy.a # Python library (static)
libswigpy.so # Python library (shared)
libswigtcl8.a # Tcl 8.x library (static)
libswigtcl8.so # Tcl 8.x library (shared)
libswigrb.a # Ruby library (static)
libswigrb.so # Ruby library (shared)
</pre></blockquote>
<p>
Note that certain libraries may be missing due to missing packages or unsupported features (like dynamic loading) on your machine.<p>
<p>
2. Compile all SWIG modules using the <tt>-c</tt> option. For example :<p>
<p>
<blockquote><pre>
% <b>swig -c -python a.i</b>
% <b>swig -c -python b.i</b>
</pre></blockquote>
The <tt>-c</tt> option tells SWIG to omit runtime support. It's now up to you to provide it separately--which we will do using our libraries.<p>
<p>
3. Build SWIG modules by linking against the appropriate runtime libraries.<p>
<p>
<blockquote><pre>
% <b>swig -c -python a.i</b>
% <b>swig -c -python b.i</b>
% <b>gcc -c a_wrap.c b_wrap.c -I/usr/local/include</b>
% <b>ld -shared a_wrap.o b_wrap.o -lswigpy -o a.so</b>
</pre></blockquote>
or if building a new executable (static linking)<p>
<p>
<blockquote><pre>
% <b>swig -c -tcl -ltclsh.i a.i</b>
% <b>gcc a_wrap.c -I/usr/local/include -L/usr/local/lib -ltcl -lswigtcl -lm -o mytclsh</b>
</pre></blockquote>
<p>
When completed you should now end up with a collection of modules like this:<p>
<center><img src="ch11.3.png"></center><p>
<p>
<p>
In this configuration, the runtime library manages all datatypes and other information between modules. This management process is dynamic in nature--when new modules are loaded, they contribute information to the run-time system. In the C++ world, one could incrementally load classes as needed. As this process occurs, type information is updated and base-classes learn about derived classes as needed.<p>
<a name="n6"></a><H3>13.1.4 A few dynamic loading gotchas</H3>
When working with dynamic loading, it is critical to check that only one copy of the run-time library is being loaded into the system. When working with <tt>.a</tt> library files, problems can sometimes occur so there are a few approaches to the problem.<p>
<p>
1. Rebuild the scripting language executable with the SWIG runtime library attached to it. This is actually, fairly easy to do using SWIG. For example :<p>
<p>
<blockquote><pre>%module mytclsh
%{
static void *__embedfunc(void *a) { return a};
%}
void *__embedfunc(void *);
%include tclsh.i
</pre></blockquote>
<p>
Now, run SWIG and compile as follows:<p>
<p>
<blockquote><pre>
% <b>swig -c -tcl mytclsh.i</b>
% <b>gcc mytclsh_wrap.c -I/usr/local/include -L/usr/local/lib -ltcl -lswigtcl -ldl -lm \
-o tclsh</b>
</pre></blockquote>
This produces a new executable "<tt>tclsh</tt>" that contains a copy of the SWIG runtime library. The weird <tt>__embedfunc()</tt> function is needed to force the functions in the runtime library to be included in the final executable.<p>
<p>
To make new dynamically loadable SWIG modules, simply compile as follows :<p>
<p>
<blockquote><pre>
% <b>swig -c -tcl example.i</b>
% <b>gcc -c example_wrap.c -I/usr/local/include</b>
% <b>ld -shared example_wrap.o -o example.so</b>
</pre></blockquote>
Linking against the <tt>swigtcl</tt> library is no longer necessary as all of the functions are now included in the <tt>tclsh</tt> executable and will be resolved when your module is loaded.<p>
<p>
2. Using shared library versions of the runtime library<p>
<p>
If supported on your machine, the runtime libraries will be built as shared libraries (indicated by a <tt>.so</tt>, <tt>.sl</tt>, or .<tt>dll</tt> suffix). To compile using the runtime libraries, you link process should look something like this:<p>
<blockquote><pre>
% <b>ld -shared swigtcl_wrap.o -o libswigtcl.so</b> # Irix
% <b>gcc -shared swigtcl_wrap.o -o libswigtcl.so</b> # Linux
% <b>ld -G swigtcl_wrap.o -o libswigtcl.so</b> # Solaris
</pre></blockquote>
In order for the <tt>libswigtcl.so</tt> library to work, it needs to be placed in a location where the dynamic loader can find it. Typically this is a system library directory (ie. <tt>/usr/local/lib</tt> or <tt>/usr/lib</tt>).<p>
<p>
When running with the shared libary version, you may get error messages such as the following:<p>
<p>
<blockquote><pre>Unable to locate libswigtcl.so</pre></blockquote>
This indicates that the loader was unable to find the shared libary at run-time. To find shared libaries, the loader looks through a collection of predetermined paths. If the <tt>libswigtcl.so</tt> file is not in any of these directories, it results in an error. On most machines, you can change the loader search path by changing the Unix environment variable <tt>LD_LIBRARY_PATH</tt>, e.g.<p>
<p>
<blockquote><pre>% <b>setenv LD_LIBRARY_PATH .:/home/beazley/packages/lib</b></pre></blockquote>
A somewhat better approach is to link your module with the proper path encoded. This is typically done using the `<tt>-rpath</tt>' or `<tt>-R</tt>' option to your linker (see the man page). For example:<p>
<p>
<blockquote><pre>% <b>ld -shared example_wrap.o example.o -rpath /home/beazley/packages/lib \
-L/home/beazley/packages/lib -lswigtcl.so -o example.so</b>
</pre></blockquote>
The <tt>-rpath</tt> option encodes the location of shared libraries into your modules and gets around having to set the <tt>LD_LIBRARY_PATH</tt> variable.<p>
<p>
If all else fails, pull up the man pages for your linker and start playing around.<p>
<a name="n7"></a><H2>13.2 Dynamic Loading of C++ modules</H2>
Dynamic loading of C++ modules presents a special problem for many systems. This is because C++ modules often need additional supporting code for proper initialization and operation. Static constructors are also a bit of a problem.<p>
<p>
While the process of building C++ modules is, by no means, and exact science, here are a few rules of thumb to follow :<p>
<p>
<ul>
<li>Don't use static constructors if at all possible (not always avoidable).
<li>Try linking your module with the C++ compiler using a command like `c++ -shared'. This often solves alot of problems.
<li>Sometimes it is necessary to link against special libraries. For example, modules compiled with g++ often need to be linked against the <tt>libgcc.a</tt>, <tt>libg++.a</tt>, and <tt>libstdc++.a</tt> libraries.
<li>Read the compiler and linker man pages over and over until you have them memorized (this may not help in some cases however).
<li>Search articles on Usenet, particularly in <tt>comp.lang.tcl</tt>, <tt>comp.lang.perl</tt>, <tt>comp.lang.python</tt> and <tt>comp.lang.ruby</tt>. Building C++ modules is a common problem.
</ul>
<p>
The SWIG distribution contains some additional documentation about C++ modules in the Doc directory as well.<p>
<a name="n8"></a><H2>13.3 Inside the SWIG type-checker</H2>
The SWIG runtime type-checker plays a critical role in the correct operation of SWIG modules. It not only checks the validity of pointer types, but also manages C++ inheritance, and performs proper type-casting of pointers when necessary. This section provides some insight into what it does, how it works, and why it is the way it is.<p>
<a name="n9"></a><H3>13.3.1 Type equivalence</H3>
SWIG uses a name-based approach to managing pointer datatypes. For example, if you are using a pointer like "<tt>double *</tt>", the type-checker will look for a particular string representation of that datatype such as "<tt>_double_p</tt>". If no match is found, a type-error is reported.<p>
<p>
However, the matching process is complicated by the fact that datatypes may use a variety of different names. For example, the following declarations<p>
<p>
<blockquote><pre>typedef double Real;
typedef Real * RealPtr;
typedef double Float;
</pre></blockquote>
define two sets of equivalent types :<p>
<p>
<blockquote><pre>{double, Real, Float}
{RealPtr, Real *}
</pre></blockquote>
All of the types in each set are freely interchangable and the type-checker knows about the relationships by managing a table of equivalences such as the following :<p>
<blockquote><pre>
double =&gt; { Real, Float }
Real =&gt; { double, Float }
Float =&gt; { double, Real }
RealPtr =&gt; { Real * }
Real * =&gt; { RealPtr }
</pre></blockquote>
<p>
When you declare a function such as the following :<p>
<p>
<blockquote><pre>void foo(Real *a);
</pre></blockquote>
SWIG first checks to see if the argument passed is a "<tt>Real *</tt>". If not, it checks to see if it is any of the other equivalent types (<tt>double *</tt>, <tt>RealPtr</tt>, <tt>Float *</tt>). If so, the value is accepted and no error occurs.<p>
<p>
Derived versions of the various datatypes are also legal. For example, if you had a function like this,<p>
<p>
<blockquote><pre>void bar(Float ***a);
</pre></blockquote>
The type-checker will accept pointers of type <tt>double ***</tt> and <tt>Real ***.</tt> However, the type-checker does not always capture the full-range of possibilities. For example, a datatype of `<tt>RealPtr **</tt>' is equivalent to a `<tt>Float ***</tt>' but would be flagged as a type error. If you encounter this kind of problem, you can manually force SWIG to make an equivalence as follows:<p>
<p>
<blockquote><pre>// Tell the type checker that `Float_ppp' and `RealPtr_pp' are equivalent.
%init %{
SWIG_RegisterMapping("Float_ppp","RealPtr_pp",0);
%}
</pre></blockquote>
Doing this should hardly ever be necessary (I have never encountered a case where this was necessary), but if all else fails, you can force the run-time type checker into doing what you want.<p>
<p>
Type-equivalence of C++ classes is handled in a similar manner, but is encoded in a manner to support inheritance. For example, consider the following classes hierarchy :<p>
<p>
<blockquote><pre>class A { };
class B : public A { };
class C : public B { };
class D {};
class E : public C, public D {};
</pre></blockquote>
The type-checker encodes this into the following sets :<p>
<p>
<blockquote><pre>A =&gt; { B, C, E } "B isa A, C isa A, E isa A"
B =&gt; { C, E } "C isa B, E isa B"
C =&gt; { E } "E isa C"
D =&gt; { E } "E isa D"
E =&gt; { }
</pre></blockquote>
The encoding reflects the class hierarchy. For example, any object of type "A" will also accept objects of type B,C, and E because these are all derived from A. However, it is not legal to go the other way. For example, a function operating on a object from class E will not accept an object from class A.<p>
<a name="n10"></a><H3>13.3.2 Type casting</H3>
When working with C++ classes, SWIG needs to perform proper typecasting between derived and base classes. This is particularly important when working with multiple inheritance. To do this, conversion functions are created such as the following :<p>
<p>
<blockquote><pre>void *EtoA(void *ptr) {
E *in = (E *) ptr;
A *out = (A *) in; // Cast using C++
return (void *) out;
}
</pre></blockquote>
All pointers are internally represented as void *, but conversion functions are always invoked when pointer values are converted between base and derived classes in a C++ class hierarchy.<p>
<a name="n11"></a><H3>13.3.3 Why a name based approach?</H3>
SWIG uses a name-based approach to type-checking for a number of reasons :<p>
<p>
<ul>
<li>One of SWIG's main uses is code development and debugging. In this environment, the type name of an object turns out to be a useful piece of information in tracking down problems.
<li>In languages like Perl, the name of a datatype is used to determine things like packages and classes. By using datatype names we get a natural mapping between C and Perl.
<li>I believe using the original names of datatypes is more intuitive than munging them into something completely different.
</ul>
<p>
An alternative to a name based scheme would be to generate type-signatures based on the structure of a datatype. Such a scheme would result in perfect type-checking, but I think it would also result in a very confusing scripting language module. For this reason, I see SWIG sticking with the name-based approach--at least for the foreseeable future. <p>
<a name="n12"></a><H3>13.3.4 Performance of the type-checker</H3>
The type-checker performs the following steps when matching a datatype :<p>
<p>
<dl>
<dt>1. Check a pointer against the type supplied in the original C declaration. If there is a perfect match, we're done.
<dt>2. Check the supplied pointer against a cache of recently used datatypes.
<dt>3. Search for a match against the full list of equivalent datatypes.
<dt>4. If not found, report an error.
</dl>
<p>
Most well-structured C codes will find an exact match on the first attempt, providing the best possible performance. For C++ codes, it is quite common to be passing various objects of a common base-class around between functions. When base-class functions are invoked, it almost always results in a miscompare (because the type-checker is looking for the base-type). In this case, we drop down to a small cache of recently used datatypes. If we've used a pointer of the same type recently, it will be in the cache and we can match against it. For tight loops, this results in about 10-15% overhead over finding a match on the first try. Finally, as a last resort, we need to search the internal pointer tables for a match. This involves a combination of hash table lookup and linear search. If a match is found, it is placed into the cache and the result returned. If not, we finally report a type-mismatch.<p>
<p>
As a rule of thumb, C++ programs require somewhat more processing than C programs, but this seems to be avoidable. Also, keep in mind that performance penalties in the type-checker don't necessarily translate into big penalties in the overall application. Performance is most greatly affected by the efficiency of the target scripting language and the types of operations your C code is performing.<p>
<p>
<p>
<p><hr>
<address>SWIG 1.1 - Last Modified : Mon Aug 4 10:47:13 1997</address>
</body>
</html>

View file

@ -0,0 +1,427 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Argument Handling</title>
</head>
<body bgcolor="#ffffff">
<a name="n1"></a><H1>7 Argument Handling</H1>
<!-- INDEX -->
<ul>
<li><a href="#n2">The typemaps.i library</a>
<ul>
<li><a href="#n3">Introduction</a>
<li><a href="#n4">Input parameters</a>
<li><a href="#n5">Output parameters</a>
<li><a href="#n6">Input/Output parameters</a>
<li><a href="#n7">Using different names</a>
</ul>
<li><a href="#n8">Applying constraints to input values</a>
<ul>
<li><a href="#n9">Simple constraint example</a>
<li><a href="#n10">Constraint methods</a>
<li><a href="#n11">Applying constraints to new datatypes</a>
</ul>
</ul>
<!-- INDEX -->
<b>Disclaimer: This chapter is under construction.</b>
<p>
In Chapter 3, SWIG's treatment of basic datatypes and pointers was
described. In particular, primitive types such as <tt>int</tt> and
<tt>double</tt> are mapped to corresponding types in the target
language. For everything else, pointers are used to refer to
structures, classes, arrays, and other user-defined datatypes.
However, in certain applications it is desirable to change SWIG's
handling of a specific datatype. For example, you might want to
return multiple values through the arguments of a function. This chapter
describes some of the techniques for doing this.
<a name="n2"></a><H2>7.1 The typemaps.i library</H2>
This section describes the <tt>typemaps.i</tt> library file--commonly used to
change certain properties of argument conversion.
<a name="n3"></a><H3>7.1.1 Introduction</H3>
Suppose you had a C function like this:
<p>
<blockquote><pre>void add(double a, double b, double *result) {
*result = a + b;
}
</pre></blockquote>
<p>
From reading the source code, it is clear that the function is storing
a value in the <tt>double *result</tt> parameter. However, since SWIG
does not examine function bodies, it has no way to know that this is
the underlying behavior.
<p>
One way to deal with this is to use the
<tt>typemaps.i</tt> library file and write interface code like this:
<p>
<blockquote><pre>// Simple example using typemaps
%module example
%include "typemaps.i"
%apply double *OUTPUT { double *result };
extern void add(double a, double b, double *result);
</pre></blockquote>
The <tt>%apply</tt> directive tells SWIG that you are going to apply
a special type handling rule to a type. The "<tt>double *OUTPUT</tt>" specification is the
name of a rule that defines how to return an output value from an argument of type
<tt>double *</tt>. This rule gets applied to all of the datatypes
listed in curly braces-- in this case "<tt>double *result</tt>".<p>
<p>
When the resulting module is created, you can now use the function
like this (shown for Python):
<p>
<blockquote><pre>
>>> a = add(3,4)
>>> print a
7
>>>
</pre></blockquote>
In this case, you can see how the output value normally returned in
the third argument has magically been transformed into a function
return value. Clearly this makes the function much easier to use
since it is no longer necessary to manufacture a special <tt>double
*</tt> object and pass it to the function somehow.
<p>
Once a typemap has been applied to a type, it stays in effect for all future occurrences
of the type and name. For example, you could write the following:
<p>
<blockquote><pre>
%module example
%include "typemaps.i"
%apply double *OUTPUT { double *result };
extern void add(double a, double b, double *result);
extern void sub(double a, double b, double *result);
extern void mul(double a, double b, double *result);
extern void div(double a, double b, double *result);
...
</pre></blockquote>
In this case, the <tt>double *OUTPUT</tt> rule is applied to all of the functions that follow.
<p>
Typemap transformations can even be extended to multiple return values.
For example, consider this code:
<blockquote>
<pre>
%include "typemaps.i"
%apply int *OUTPUT { int *width, int *height };
// Returns a pair (width,height)
void getwinsize(int winid, int *width, int *height);
</pre>
</blockquote>
In this case, the function returns multiple values, allowing it to be used like this:
<blockquote><pre>
>>> w,h = genwinsize(wid)
>>> print w
400
>>> print h
300
>>>
</pre>
</blockquote>
<p>
It should also be noted that although the <tt>%apply</tt> directive is
used to associate typemap rules to datatypes, you can also use the
rule names directly in arguments. For example, you could write this:
<blockquote><pre>// Simple example using typemaps
%module example
%include "typemaps.i"
extern void add(double a, double b, double *OUTPUT);
</pre></blockquote>
Typemaps stay in effect until they are explicitly deleted or redefined to something
else. To clear a typemap, the <tt>%clear</tt> directive should be used. For example:
<blockquote>
<pre>
%clear double *result; // Remove all typemaps for double *result
</pre>
</blockquote>
<a name="n4"></a><H3>7.1.2 Input parameters</H3>
<p>
The following typemaps instruct SWIG that a pointer really only holds a single
input value:
<blockquote><pre>
int *INPUT
short *INPUT
long *INPUT
unsigned int *INPUT
unsigned short *INPUT
unsigned long *INPUT
double *INPUT
float *INPUT
</pre></blockquote>
When used, it allows values to be passed instead of pointers. For example, consider this
function:
<blockquote><pre>
double add(double *a, double *b) {
return *a+*b;
}
</pre></blockquote>
Now, consider this SWIG interface:
<p>
<blockquote><pre>%module example
%include "typemaps.i"
...
extern double add(double *INPUT, double *INPUT);
</pre></blockquote>
When the function is used in the scripting language interpreter, it will work like this:
<p>
<blockquote><pre>
result = add(3,4)
</pre></blockquote>
<a name="n5"></a><H3>7.1.3 Output parameters</H3>
The following typemap rules tell SWIG that pointer is the output value of a
function. When used, you do not need to supply the argument when
calling the function. Instead, one or more output values are returned.
<p>
<blockquote><pre>int *OUTPUT
short *OUTPUT
long *OUTPUT
unsigned int *OUTPUT
unsigned short *OUTPUT
unsigned long *OUTPUT
double *OUTPUT
float *OUTPUT
</pre></blockquote>
These methods can be used as shown in an earlier example. For example, if you have this C function :<p>
<p>
<blockquote><pre>void add(double a, double b, double *c) {
*c = a+b;
}
</pre></blockquote>
<p>
A SWIG interface file might look like this :<p>
<p>
<blockquote><pre>%module example
%include "typemaps.i"
...
extern void add(double a, double b, double *OUTPUT);
</pre></blockquote>
In this case, only a single output value is returned, but this is not
a restriction. An arbitrary number of output values can be returned by applying
the output rules to more than one argument (as shown previously).
<p>
If the function also returns a value, it is returned along with the argument. For example,
if you had this:
<blockquote><pre>
extern int foo(double a, double b, double *OUTPUT);
</pre></blockquote>
The function will return two values like this:
<blockquote>
<pre>
iresult, dresult = foo(3.5, 2)
</pre>
</blockquote>
<a name="n6"></a><H3>7.1.4 Input/Output parameters</H3>
When a pointer serves as both an input and output value you can use
the following typemaps :<p>
<blockquote><pre>
int *INOUT
short *INOUT
long *INOUT
unsigned int *INOUT
unsigned short *INOUT
unsigned long *INOUT
double *INOUT
float *INOUT
</pre></blockquote>
A C function that uses this might be something like this:<p>
<p>
<blockquote><pre>void negate(double *x) {
*x = -(*x);
}
</pre></blockquote>
To make x function as both and input and output value, declare the
function like this in an interface file :<p>
<p>
<blockquote><pre>%module example
%include typemaps.i
...
extern void negate(double *INOUT);
</pre></blockquote>
Now within a script, you can simply call the function normally :<p>
<p>
<blockquote><pre>a = negate(3); # a = -3 after calling this
</pre></blockquote>
One subtle point of the <tt>INOUT</tt> rule is that many scripting languages
enforce mutability constraints on primitive objects (meaning that simple objects
like integers and strings aren't supposed to change). Because of this, you can't
just modify the object's value in place as the underlying C function does in this example.
Therefore, the <tt>INOUT</tt> rule returns the modified value as a new object
rather than directly overwriting the value of the original input object.
<p>
<b>Compatibility note :</b> The <tt>INOUT</tt> rule used to be known as <tt>BOTH</tt> in earlier versions of
SWIG. Backwards compatibility is preserved, but deprecated.
<a name="n7"></a><H3>7.1.5 Using different names</H3>
As previously shown, the <tt>%apply</tt> directive can be used to apply the <tt>INPUT</tt>, <tt>OUTPUT</tt>, and
<tt>INOUT</tt> typemaps to different argument names. For example:
<p>
<blockquote><pre>// Make double *result an output value
%apply double *OUTPUT { double *result };
// Make Int32 *in an input value
%apply int *INPUT { Int32 *in };
// Make long *x inout
%apply long *INOUT {long *x};
</pre></blockquote>
To clear a rule, the <tt>%clear</tt> directive is used:
<p>
<blockquote><pre>%clear double *result;
%clear Int32 *in, long *x;
</pre></blockquote>
Typemap declarations are lexically scoped so a typemap takes effect from the point of definition to the end of the
file or a matching <tt>%clear</tt> declaration.
<a name="n8"></a><H2>7.2 Applying constraints to input values</H2>
In addition to changing the handling of various input values, it is
also possible to use typemaps to apply constraints. For example, maybe you want to
insure that a value is positive, or that a pointer is non-NULL. This
can be accomplished including the <tt>constraints.i</tt> library file.
<a name="n9"></a><H3>7.2.1 Simple constraint example</H3>
The constraints library is best illustrated by the following interface
file :<p>
<p>
<blockquote><pre>// Interface file with constraints
%module example
%include "constraints.i"
double exp(double x);
double log(double POSITIVE); // Allow only positive values
double sqrt(double NONNEGATIVE); // Non-negative values only
double inv(double NONZERO); // Non-zero values
void free(void *NONNULL); // Non-NULL pointers only
</pre></blockquote>
The behavior of this file is exactly as you would expect. If any of
the arguments violate the constraint condition, a scripting language
exception will be raised. As a result, it is possible to catch bad
values, prevent mysterious program crashes and so on.<p>
<a name="n10"></a><H3>7.2.2 Constraint methods</H3>
The following constraints are currently available<p>
<blockquote><pre>
POSITIVE Any number &gt; 0 (not zero)
NEGATIVE Any number &lt; 0 (not zero)
NONNEGATIVE Any number &gt;= 0
NONPOSITIVE Any number &lt;= 0
NONZERO Nonzero number
NONNULL Non-NULL pointer (pointers only).
</pre></blockquote>
<a name="n11"></a><H3>7.2.3 Applying constraints to new datatypes</H3>
The constraints library only supports the primitive C datatypes, but it
is easy to apply it to new datatypes using <tt>%apply</tt>. For
example :<p>
<p>
<blockquote><pre>// Apply a constraint to a Real variable
%apply Number POSITIVE { Real in };
// Apply a constraint to a pointer type
%apply Pointer NONNULL { Vector * };
</pre></blockquote>
The special types of "Number" and "Pointer" can be applied to any
numeric and pointer variable type respectively. To later remove a
constraint, the <tt>%clear</tt> directive can be used :<p>
<p>
<blockquote><pre>%clear Real in;
%clear Vector *;
</pre></blockquote>
<p><hr>
<address>SWIG 1.3 - Last Modified : October 13, 2002</address>
</body>
</html>

View file

@ -0,0 +1,946 @@
<HTML>
<HEAD>
<TITLE>SWIG Users Manual</TITLE>
</HEAD>
<BODY BGCOLOR="#ffffff">
<H1>SWIG Users Manual</H1>
<p>
<h3><a href="Preface.html">0 Preface</a></h3>
<!-- INDEX -->
<ul>
<li><a href="Preface.html#n2">Introduction</a>
<li><a href="Preface.html#n3">Special Introduction for Version 1.3</a>
<li><a href="Preface.html#n4">SWIG Versions</a>
<li><a href="Preface.html#n5">SWIG resources</a>
<li><a href="Preface.html#n6">Prerequisites</a>
<li><a href="Preface.html#n7">Organization of this manual</a>
<li><a href="Preface.html#n8">How to avoid reading the manual</a>
<li><a href="Preface.html#n9">Backwards Compatibility</a>
<li><a href="Preface.html#n10">Credits</a>
<li><a href="Preface.html#n11">Bug reports</a>
</ul>
<!-- INDEX -->
<h3><a href="Introduction.html">1 Introduction</a></h3>
<!-- INDEX -->
<ul>
<li><a href="Introduction.html#n2">What is SWIG?</a>
<li><a href="Introduction.html#n3">Why use SWIG?</a>
<li><a href="Introduction.html#n4">A SWIG example</a>
<ul>
<li><a href="Introduction.html#n5">SWIG interface file</a>
<li><a href="Introduction.html#n6">The swig command</a>
<li><a href="Introduction.html#n7">Building a Perl5 module</a>
<li><a href="Introduction.html#n8">Building a Python module</a>
<li><a href="Introduction.html#n9">Shortcuts</a>
<li><a href="Introduction.html#n10">Building libraries and modules</a>
</ul>
<li><a href="Introduction.html#n11">Supported C/C++ language features</a>
<li><a href="Introduction.html#n12">Non-intrusive interface building</a>
<li><a href="Introduction.html#n13">Hands off code generation</a>
</ul>
<!-- INDEX -->
<h3><a href="Windows.html">2 Getting started on Windows </a></h3>
<!-- INDEX -->
<ul>
<li><a href="Windows.html#n2">Installation on Windows</a>
<ul>
<li><a href="Windows.html#n3">Windows Executable</a>
</ul>
<li><a href="Windows.html#n4">SWIG Windows Examples</a>
<ul>
<li><a href="Windows.html#n5">Instructions for using the Examples with Visual C++</a>
<ul>
<li><a href="Windows.html#n6">Python</a>
<li><a href="Windows.html#n7">TCL</a>
<li><a href="Windows.html#n8">Perl</a>
<li><a href="Windows.html#n9">Java</a>
<li><a href="Windows.html#n10">Ruby</a>
</ul>
<li><a href="Windows.html#n11">Instructions for using the Examples with other compilers</a>
</ul>
<li><a href="Windows.html#n12">SWIG on Cygwin and Mingw</a>
<ul>
<li><a href="Windows.html#n13">Building swig.exe on Windows</a>
<ul>
<li><a href="Windows.html#n14">Building swig.exe using Cygwin and Mingw</a>
<li><a href="Windows.html#n15">Building swig.exe alternatives</a>
</ul>
<li><a href="Windows.html#n16">Running the examples on Windows using Cygwin</a>
</ul>
</ul>
<!-- INDEX -->
<h3><a href="Scripting.html">3 Scripting Languages</a></h3>
<!-- INDEX -->
<ul>
<li><a href="Scripting.html#n2">The two language view of the world</a>
<li><a href="Scripting.html#n3">How does a scripting language talk to C?</a>
<ul>
<li><a href="Scripting.html#n4">Wrapper functions</a>
<li><a href="Scripting.html#n5">Variable linking</a>
<li><a href="Scripting.html#n6">Constants</a>
<li><a href="Scripting.html#n7">Structures and classes</a>
<li><a href="Scripting.html#n8">Shadow classes</a>
</ul>
<li><a href="Scripting.html#n9">Building scripting language extensions</a>
<ul>
<li><a href="Scripting.html#n10">Shared libraries and dynamic loading</a>
<li><a href="Scripting.html#n11">Linking with shared libraries</a>
<li><a href="Scripting.html#n12">Static linking</a>
</ul>
</ul>
<!-- INDEX -->
<h3><a href="SWIG.html">4 SWIG Basics</a></h3>
<!-- INDEX -->
<ul>
<li><a href="SWIG.html#n2">Running SWIG</a>
<ul>
<li><a href="SWIG.html#n3">Input format</a>
<li><a href="SWIG.html#n4">SWIG Output</a>
<li><a href="SWIG.html#n5">Comments</a>
<li><a href="SWIG.html#n6">C Preprocessor</a>
<li><a href="SWIG.html#n7">SWIG Directives</a>
<li><a href="SWIG.html#n8">Parser Limitations</a>
</ul>
<li><a href="SWIG.html#n9">Wrapping Simple C Declarations</a>
<ul>
<li><a href="SWIG.html#n10">Basic Type Handling</a>
<li><a href="SWIG.html#n11">Global Variables</a>
<li><a href="SWIG.html#n12">Constants</a>
<li><a href="SWIG.html#n13">A brief word about <tt>const</tt></a>
<li><a href="SWIG.html#n14">A cautionary tale of <tt>char *</tt></a>
</ul>
<li><a href="SWIG.html#n15">Pointers and complex objects</a>
<ul>
<li><a href="SWIG.html#n16">Simple pointers</a>
<li><a href="SWIG.html#n17">Run time pointer type checking</a>
<li><a href="SWIG.html#n18">Derived types, structs, and classes</a>
<li><a href="SWIG.html#n19">Undefined datatypes</a>
<li><a href="SWIG.html#n20">Typedef</a>
</ul>
<li><a href="SWIG.html#n21">Other Practicalities</a>
<ul>
<li><a href="SWIG.html#n22">Passing structures by value</a>
<li><a href="SWIG.html#n23">Return by value</a>
<li><a href="SWIG.html#n24">Linking to structure variables</a>
<li><a href="SWIG.html#n25">Linking to <tt>char *</tt></a>
<li><a href="SWIG.html#n26">Arrays</a>
<li><a href="SWIG.html#n27">Creating read-only variables</a>
<li><a href="SWIG.html#n28">Renaming and ignoring declarations</a>
<li><a href="SWIG.html#n29">Default/optional arguments</a>
<li><a href="SWIG.html#n30">Pointers to functions and callbacks</a>
</ul>
<li><a href="SWIG.html#n31">Structures and unions</a>
<ul>
<li><a href="SWIG.html#n32">Typedef and structures</a>
<li><a href="SWIG.html#n33">Character strings and structures</a>
<li><a href="SWIG.html#n34">Array members</a>
<li><a href="SWIG.html#n35">Structure data members</a>
<li><a href="SWIG.html#n36">C constructors and destructors </a>
<li><a href="SWIG.html#n37">Adding member functions to C structures</a>
<li><a href="SWIG.html#n38">Nested structures</a>
<li><a href="SWIG.html#n39">Other things to note about structure wrapping</a>
</ul>
<li><a href="SWIG.html#n40">Code Insertion</a>
<ul>
<li><a href="SWIG.html#n41">The output of SWIG</a>
<li><a href="SWIG.html#n42">Code insertion blocks</a>
<li><a href="SWIG.html#n43">Inlined code blocks</a>
<li><a href="SWIG.html#n44">Initialization blocks</a>
</ul>
<li><a href="SWIG.html#n45">An Interface Building Strategy</a>
<ul>
<li><a href="SWIG.html#n46">Preparing a C program for SWIG</a>
<li><a href="SWIG.html#n47">The SWIG interface file</a>
<li><a href="SWIG.html#n48">Why use separate interface files?</a>
<li><a href="SWIG.html#n49">Getting the right header files</a>
<li><a href="SWIG.html#n50">What to do with main()</a>
</ul>
</ul>
<!-- INDEX -->
<h3><a href="SWIGPlus.html">5 SWIG and C++</a></h3>
<!-- INDEX -->
<ul>
<li><a href="SWIGPlus.html#n2">Comments on C++ Wrapping</a>
<li><a href="SWIGPlus.html#n3">Approach</a>
<li><a href="SWIGPlus.html#n4">Supported C++ features</a>
<li><a href="SWIGPlus.html#n5">Command line options and compilation</a>
<li><a href="SWIGPlus.html#n6">Simple C++ wrapping</a>
<ul>
<li><a href="SWIGPlus.html#n7">Constructors and destructors</a>
<li><a href="SWIGPlus.html#n8">Copy constructors</a>
<li><a href="SWIGPlus.html#n9">Member functions</a>
<li><a href="SWIGPlus.html#n10">Static members</a>
<li><a href="SWIGPlus.html#n11">Member functions and default arguments</a>
<li><a href="SWIGPlus.html#n12">Member data</a>
</ul>
<li><a href="SWIGPlus.html#n13">Protection</a>
<li><a href="SWIGPlus.html#n14">Enums and constants</a>
<li><a href="SWIGPlus.html#n15">Friends</a>
<li><a href="SWIGPlus.html#n16">References and pointers</a>
<li><a href="SWIGPlus.html#n17">Pass and return by value</a>
<li><a href="SWIGPlus.html#n18">Inheritance</a>
<li><a href="SWIGPlus.html#n19">A brief discussion of multiple inheritance, pointers, and type checking</a>
<li><a href="SWIGPlus.html#n20">Renaming</a>
<li><a href="SWIGPlus.html#n21">Wrapping Overloaded Functions and Methods</a>
<ul>
<li><a href="SWIGPlus.html#n22">Dispatch function generation</a>
<li><a href="SWIGPlus.html#n23">Ambiguity in Overloading</a>
<li><a href="SWIGPlus.html#n24">Ambiguity resolution and renaming</a>
<li><a href="SWIGPlus.html#n25">Comments on overloading</a>
</ul>
<li><a href="SWIGPlus.html#n26">Wrapping overloaded operators</a>
<li><a href="SWIGPlus.html#n27">Class extension</a>
<li><a href="SWIGPlus.html#n28">Templates</a>
<li><a href="SWIGPlus.html#n29">Namespaces</a>
<li><a href="SWIGPlus.html#n30">Exception specifiers</a>
<li><a href="SWIGPlus.html#n31">Pointers to Members</a>
<li><a href="SWIGPlus.html#n32">Smart pointers and operator-&gt;()</a>
<li><a href="SWIGPlus.html#n33">Using declarations and inheritance</a>
<li><a href="SWIGPlus.html#n34">Partial class definitions</a>
<li><a href="SWIGPlus.html#n35">A brief rant about const-correctness</a>
<li><a href="SWIGPlus.html#n36">Proxy classes</a>
<li><a href="SWIGPlus.html#n37">Where to go for more information</a>
</ul>
<!-- INDEX -->
<h3><a href="Preprocessor.html">6 Preprocessing</a></h3>
<!-- INDEX -->
<ul>
<li><a href="Preprocessor.html#n2">File inclusion</a>
<li><a href="Preprocessor.html#n3">File imports</a>
<li><a href="Preprocessor.html#n4">Conditional Compilation</a>
<li><a href="Preprocessor.html#n5">Macro Expansion</a>
<li><a href="Preprocessor.html#n6">SWIG Macros</a>
<li><a href="Preprocessor.html#n7">C99 Extensions</a>
<li><a href="Preprocessor.html#n8">Preprocessing and %{ ... %} blocks</a>
<li><a href="Preprocessor.html#n9">Preprocessing and { ... }</a>
</ul>
<!-- INDEX -->
<h3><a href="Arguments.html">7 Argument Handling</a></h3>
<!-- INDEX -->
<ul>
<li><a href="Arguments.html#n2">The typemaps.i library</a>
<ul>
<li><a href="Arguments.html#n3">Introduction</a>
<li><a href="Arguments.html#n4">Input parameters</a>
<li><a href="Arguments.html#n5">Output parameters</a>
<li><a href="Arguments.html#n6">Input/Output parameters</a>
<li><a href="Arguments.html#n7">Using different names</a>
</ul>
<li><a href="Arguments.html#n8">Applying constraints to input values</a>
<ul>
<li><a href="Arguments.html#n9">Simple constraint example</a>
<li><a href="Arguments.html#n10">Constraint methods</a>
<li><a href="Arguments.html#n11">Applying constraints to new datatypes</a>
</ul>
</ul>
<!-- INDEX -->
<h3><a href="Typemaps.html">8 Typemaps</a></h3>
<!-- INDEX -->
<ul>
<li><a href="Typemaps.html#n2">Introduction</a>
<ul>
<li><a href="Typemaps.html#n3">Type conversion</a>
<li><a href="Typemaps.html#n4">Typemaps</a>
<li><a href="Typemaps.html#n5">Pattern matching</a>
<li><a href="Typemaps.html#n6">Reusing typemaps</a>
<li><a href="Typemaps.html#n7">What can be done with typemaps?</a>
<li><a href="Typemaps.html#n8">What can't be done with typemaps?</a>
<li><a href="Typemaps.html#n9">The rest of this chapter</a>
</ul>
<li><a href="Typemaps.html#n10">Typemap specifications</a>
<ul>
<li><a href="Typemaps.html#n11">Defining a typemap</a>
<li><a href="Typemaps.html#n12">Typemap scope</a>
<li><a href="Typemaps.html#n13">Copying a typemap</a>
<li><a href="Typemaps.html#n14">Deleting a typemap</a>
<li><a href="Typemaps.html#n15">Placement of typemaps</a>
</ul>
<li><a href="Typemaps.html#n16">Pattern matching rules</a>
<ul>
<li><a href="Typemaps.html#n17">Basic matching rules</a>
<li><a href="Typemaps.html#n18">Typedef reductions</a>
<li><a href="Typemaps.html#n19">Default typemaps</a>
<li><a href="Typemaps.html#n20">Multi-arguments typemaps</a>
</ul>
<li><a href="Typemaps.html#n21">Code generation rules</a>
<ul>
<li><a href="Typemaps.html#n22">Scope</a>
<li><a href="Typemaps.html#n23">Declaring new local variables</a>
<li><a href="Typemaps.html#n24">Special variables</a>
</ul>
<li><a href="Typemaps.html#n25">Common typemap methods</a>
<ul>
<li><a href="Typemaps.html#n26">"in" typemap</a>
<li><a href="Typemaps.html#n27">"out" typemap</a>
<li><a href="Typemaps.html#n28">"arginit" typemap</a>
<li><a href="Typemaps.html#n29">"default" typemap</a>
<li><a href="Typemaps.html#n30">"check" typemap</a>
<li><a href="Typemaps.html#n31">"argout" typemap</a>
<li><a href="Typemaps.html#n32">"freearg" typemap</a>
<li><a href="Typemaps.html#n33">"newfree" typemap</a>
<li><a href="Typemaps.html#n34">"memberin" typemap</a>
<li><a href="Typemaps.html#n35">"varin" typemap</a>
<li><a href="Typemaps.html#n36">"varout" typemap</a>
</ul>
<li><a href="Typemaps.html#n37">Some typemap examples</a>
<ul>
<li><a href="Typemaps.html#n38">Typemaps for arrays</a>
<li><a href="Typemaps.html#n39">Implementing constraints with typemaps</a>
</ul>
<li><a href="Typemaps.html#n40">Multi-argument typemaps</a>
<li><a href="Typemaps.html#n41">The run-time type checker</a>
<li><a href="Typemaps.html#n42">More about <tt>%apply</tt> and <tt>%clear</tt></a>
<li><a href="Typemaps.html#n43">Reducing wrapper code size</a>
<ul>
<li><a href="Typemaps.html#n44">Passing data between typemaps</a>
</ul>
<li><a href="Typemaps.html#n45">Where to go for more information?</a>
</ul>
<!-- INDEX -->
<h3><a href="Customization.html">9 Customization Features</a></h3>
<!-- INDEX -->
<ul>
<li><a href="Customization.html#n2">Exception handling with %exception</a>
<ul>
<li><a href="Customization.html#n3">Handling exceptions in C code</a>
<li><a href="Customization.html#n4">Exception handling with longjmp()</a>
<li><a href="Customization.html#n5">Handling C++ exceptions</a>
<li><a href="Customization.html#n6">Defining different exception handlers</a>
<li><a href="Customization.html#n7">Applying exception handlers to specific datatypes.</a>
<li><a href="Customization.html#n8">Using The SWIG exception library</a>
</ul>
<li><a href="Customization.html#n9">Object ownership and %newobject</a>
<li><a href="Customization.html#n10">Features and the %feature directive</a>
</ul>
<!-- INDEX -->
<h3><a href="Varargs.html">10 Variable Length Arguments</a></h3>
<!-- INDEX -->
<ul>
<li><a href="Varargs.html#n2">Introduction</a>
<li><a href="Varargs.html#n3">The Problem</a>
<li><a href="Varargs.html#n4">Default varargs support</a>
<li><a href="Varargs.html#n5">Argument replacement using %varargs</a>
<li><a href="Varargs.html#n6">Varargs and typemaps</a>
<li><a href="Varargs.html#n7">Varargs wrapping with libffi</a>
<li><a href="Varargs.html#n8">Wrapping of va_list</a>
<li><a href="Varargs.html#n9">C++ Issues</a>
<li><a href="Varargs.html#n10">Discussion</a>
</ul>
<!-- INDEX -->
<h3><a href="Warnings.html">11 Warning Messages</a></h3>
<!-- INDEX -->
<ul>
<li><a href="Warnings.html#n2">Introduction</a>
<li><a href="Warnings.html#n3">Warning message suppression</a>
<li><a href="Warnings.html#n4">Enabling additional warnings</a>
<li><a href="Warnings.html#n5">Issuing a warning message</a>
<li><a href="Warnings.html#n6">Commentary</a>
<li><a href="Warnings.html#n7">Warning number reference</a>
<ul>
<li><a href="Warnings.html#n8">Deprecated features (100-199)</a>
<li><a href="Warnings.html#n9">Preprocessor (200-299)</a>
<li><a href="Warnings.html#n10">C/C++ Parser (300-399)</a>
<li><a href="Warnings.html#n11">Types and typemaps (400-499) </a>
<li><a href="Warnings.html#n12">Code generation (500-599)</a>
<li><a href="Warnings.html#n13">Language module specific (800-899) </a>
<li><a href="Warnings.html#n14">User defined (900-999)</a>
</ul>
<li><a href="Warnings.html#n15">History</a>
</ul>
<!-- INDEX -->
<h3><a href="Library.html">12 SWIG library</a></h3>
<!-- INDEX -->
<ul>
<li><a href="Library.html#n2">The %include directive and library search path</a>
<li><a href="Library.html#n3">C Arrays and Pointers</a>
<ul>
<li><a href="Library.html#n4">cpointer.i</a>
<li><a href="Library.html#n5">carrays.i</a>
<li><a href="Library.html#n6">cmalloc.i</a>
<li><a href="Library.html#n7">cdata.i</a>
</ul>
<li><a href="Library.html#n8">C String Handling</a>
<ul>
<li><a href="Library.html#n9">Default string handling</a>
<li><a href="Library.html#n10">Passing binary data</a>
<li><a href="Library.html#n11">Using %newobject to release memory</a>
<li><a href="Library.html#n12">cstring.i</a>
</ul>
<li><a href="Library.html#n13">C++ Library</a>
<ul>
<li><a href="Library.html#n14">std_string.i</a>
<li><a href="Library.html#n15">std_vector.i</a>
</ul>
<li><a href="Library.html#n16">Utility Libraries</a>
<ul>
<li><a href="Library.html#n17">exception.i</a>
</ul>
</ul>
<!-- INDEX -->
<h3><a href="Advanced.html">13 Advanced Topics</a></h3>
<!-- INDEX -->
<ul>
<li><a href="Advanced.html#n2">Creating multi-module packages</a>
<ul>
<li><a href="Advanced.html#n3">Runtime support (and potential problems)</a>
<li><a href="Advanced.html#n4">Why doesn't C++ inheritance work between modules?</a>
<li><a href="Advanced.html#n5">The SWIG runtime library</a>
<li><a href="Advanced.html#n6">A few dynamic loading gotchas</a>
</ul>
<li><a href="Advanced.html#n7">Dynamic Loading of C++ modules</a>
<li><a href="Advanced.html#n8">Inside the SWIG type-checker</a>
<ul>
<li><a href="Advanced.html#n9">Type equivalence</a>
<li><a href="Advanced.html#n10">Type casting</a>
<li><a href="Advanced.html#n11">Why a name based approach?</a>
<li><a href="Advanced.html#n12">Performance of the type-checker</a>
</ul>
</ul>
<!-- INDEX -->
<h3><a href="Guile.html">14 SWIG and Guile</a></h3>
<!-- INDEX -->
<ul>
<li><a href="Guile.html#n2">Meaning of "Module"</a>
<li><a href="Guile.html#n3">Linkage</a>
<ul>
<li><a href="Guile.html#n4">Simple Linkage</a>
<li><a href="Guile.html#n5">Passive Linkage</a>
<li><a href="Guile.html#n6">Native Guile Module Linkage</a>
<li><a href="Guile.html#n7">Old Auto-Loading Guile Module Linkage</a>
<li><a href="Guile.html#n8">Hobbit4D Linkage</a>
<li><a href="Guile.html#n9">General Remarks on Multiple SWIG Modules</a>
</ul>
<li><a href="Guile.html#n10">Underscore Folding</a>
<li><a href="Guile.html#n11">Typemaps</a>
<li><a href="Guile.html#n12">Smobs</a>
<li><a href="Guile.html#n13">Exception Handling</a>
<li><a href="Guile.html#n14">Procedure documentation</a>
<li><a href="Guile.html#n15">Procedures with setters</a>
</ul>
<!-- INDEX -->
<h3><a href="Java.html">15 SWIG and Java</a></h3>
<!-- INDEX -->
<ul>
<li><a href="Java.html#n2">Preliminaries</a>
<ul>
<li><a href="Java.html#n3">Running SWIG</a>
<li><a href="Java.html#n4">Additional Commandline Options</a>
<li><a href="Java.html#n5">Getting the right header files</a>
<li><a href="Java.html#n6">Compiling a dynamic module</a>
<li><a href="Java.html#n7">Using your module</a>
<li><a href="Java.html#n8">Compilation problems and compiling with C++</a>
</ul>
<li><a href="Java.html#n9">Building Java Extensions under Windows</a>
<ul>
<li><a href="Java.html#n10">Running SWIG from Developer Studio</a>
<li><a href="Java.html#n11">Using NMAKE</a>
</ul>
<li><a href="Java.html#n12">A tour of basic C/C++ wrapping</a>
<ul>
<li><a href="Java.html#n13">Modules, packages and generated Java classes</a>
<li><a href="Java.html#n14">Functions</a>
<li><a href="Java.html#n15">Global variables</a>
<li><a href="Java.html#n16">Constants</a>
<li><a href="Java.html#n17">Enumerations</a>
<li><a href="Java.html#n18">Pointers</a>
<li><a href="Java.html#n19">Structures</a>
<li><a href="Java.html#n20">C++ classes</a>
<li><a href="Java.html#n21">C++ inheritance</a>
<li><a href="Java.html#n22">Pointers, references, arrays and pass by value</a>
<ul>
<li><a href="Java.html#n23">Null pointers</a>
</ul>
<li><a href="Java.html#n24">C++ overloaded functions</a>
<li><a href="Java.html#n25">C++ namespaces</a>
<li><a href="Java.html#n26">C++ templates</a>
<li><a href="Java.html#n27">C++ Smart Pointers</a>
</ul>
<li><a href="Java.html#n28">Further details on the generated Java classes</a>
<ul>
<li><a href="Java.html#n29">The JNI class</a>
<ul>
<li><a href="Java.html#n30">The JNI class pragmas</a>
</ul>
<li><a href="Java.html#n31">The Java module class</a>
<ul>
<li><a href="Java.html#n32">The Java module class pragmas</a>
</ul>
<li><a href="Java.html#n33">Java proxy classes</a>
<ul>
<li><a href="Java.html#n34">Memory management</a>
<li><a href="Java.html#n35">Inheritance</a>
<li><a href="Java.html#n36">Proxy classes and garbage collection</a>
</ul>
<li><a href="Java.html#n37">Type wrapper classes</a>
</ul>
<li><a href="Java.html#n38">Common customization features</a>
<ul>
<li><a href="Java.html#n39">C/C++ helper functions</a>
<li><a href="Java.html#n40">Class extension with %extend</a>
<li><a href="Java.html#n41">Exception handling with %exception</a>
<li><a href="Java.html#n42">Method access with %javamethodmodifiers</a>
</ul>
<li><a href="Java.html#n43">Tips and techniques</a>
<ul>
<li><a href="Java.html#n44">Input and output parameters using primitive pointers and references</a>
<li><a href="Java.html#n45">Simple pointers</a>
<li><a href="Java.html#n46">Wrapping C arrays with Java arrays</a>
<li><a href="Java.html#n47">Unbounded C Arrays</a>
</ul>
<li><a href="Java.html#n48">Java typemaps</a>
<ul>
<li><a href="Java.html#n49">Default primitive type mappings</a>
<li><a href="Java.html#n50">Sixty four bit JVMs</a>
<li><a href="Java.html#n51">What is a typemap?</a>
<li><a href="Java.html#n52">Typemaps for mapping C/C++ types to Java types</a>
<li><a href="Java.html#n53">Java special variables</a>
<li><a href="Java.html#n54">Typemaps for both C and C++ compilation</a>
<li><a href="Java.html#n55">Java code typemaps</a>
</ul>
<li><a href="Java.html#n56">Typemap Examples</a>
<ul>
<li><a href="Java.html#n57">Converting Java String arrays to char ** </a>
<li><a href="Java.html#n58">Expanding a Java object to multiple arguments</a>
<li><a href="Java.html#n59">Using typemaps to return arguments</a>
<li><a href="Java.html#n60">Adding Java downcasts to polymorphic return types</a>
<li><a href="Java.html#n61">Adding an equals method to the Java classes</a>
<li><a href="Java.html#n62">Void pointers and a common Java base class</a>
</ul>
<li><a href="Java.html#n63">Odds and ends</a>
<ul>
<li><a href="Java.html#n64">JavaDoc comments</a>
<li><a href="Java.html#n65">Functional interface without proxy classes</a>
<li><a href="Java.html#n66">Dynamic linking problems</a>
<li><a href="Java.html#n67">Using your own JNI functions</a>
<li><a href="Java.html#n68">Performance concerns and hints</a>
</ul>
<li><a href="Java.html#n69">Examples</a>
</ul>
<!-- INDEX -->
<h3><a href="Ocaml.html">16 SWIG and Ocaml</a></h3>
<!-- INDEX -->
<ul>
<li><a href="Ocaml.html#n2">Preliminaries</a>
<ul>
<li><a href="Ocaml.html#n3">Running SWIG</a>
<li><a href="Ocaml.html#n4">Getting the right header files</a>
<li><a href="Ocaml.html#n5">Compiling the code</a>
<li><a href="Ocaml.html#n6">The camlp4 module</a>
<li><a href="Ocaml.html#n7">Current thoughts on best practice for Ocaml</a>
<li><a href="Ocaml.html#n8">Using your module</a>
<li><a href="Ocaml.html#n9">Compilation problems and compiling with C++</a>
</ul>
<li><a href="Ocaml.html#n10">The low-level Ocaml/C interface</a>
<ul>
<li><a href="Ocaml.html#n11">The generated module</a>
<li><a href="Ocaml.html#n12">Enums</a>
<li><a href="Ocaml.html#n13">C++ Classes</a>
<ul>
<li><a href="Ocaml.html#n14">C++ Class Example</a>
<li><a href="Ocaml.html#n15">Compiling the example</a>
<li><a href="Ocaml.html#n16">Sample Session</a>
</ul>
<li><a href="Ocaml.html#n17">Exceptions</a>
</ul>
</ul>
<!-- INDEX -->
<h3><a href="Perl5.html">17 SWIG and Perl5</a></h3>
<!-- INDEX -->
<ul>
<li><a href="Perl5.html#n2">Overview</a>
<li><a href="Perl5.html#n3">Preliminaries</a>
<ul>
<li><a href="Perl5.html#n4">Getting the right header files</a>
<li><a href="Perl5.html#n5">Compiling a dynamic module</a>
<li><a href="Perl5.html#n6">Building a dynamic module with MakeMaker</a>
<li><a href="Perl5.html#n7">Building a static version of Perl</a>
<li><a href="Perl5.html#n8">Using the module</a>
<li><a href="Perl5.html#n9">Compilation problems and compiling with C++</a>
<li><a href="Perl5.html#n10">Compiling for 64-bit platforms</a>
</ul>
<li><a href="Perl5.html#n11">Building Perl Extensions under Windows</a>
<ul>
<li><a href="Perl5.html#n12">Running SWIG from Developer Studio</a>
<li><a href="Perl5.html#n13">Using other compilers</a>
</ul>
<li><a href="Perl5.html#n14">The low-level interface</a>
<ul>
<li><a href="Perl5.html#n15">Functions</a>
<li><a href="Perl5.html#n16">Global variables</a>
<li><a href="Perl5.html#n17">Constants</a>
<li><a href="Perl5.html#n18">Pointers</a>
<li><a href="Perl5.html#n19">Structures</a>
<li><a href="Perl5.html#n20">C++ classes</a>
<li><a href="Perl5.html#n21">C++ classes and type-checking</a>
<li><a href="Perl5.html#n22">C++ overloaded functions</a>
<li><a href="Perl5.html#n23">Operators</a>
<li><a href="Perl5.html#n24">Modules and packages</a>
</ul>
<li><a href="Perl5.html#n25">Input and output parameters</a>
<li><a href="Perl5.html#n26">Exception handling </a>
<li><a href="Perl5.html#n27">Remapping datatypes with typemaps</a>
<ul>
<li><a href="Perl5.html#n28">A simple typemap example</a>
<li><a href="Perl5.html#n29">Perl5 typemaps</a>
<li><a href="Perl5.html#n30">Typemap variables</a>
<li><a href="Perl5.html#n31">Useful functions</a>
</ul>
<li><a href="Perl5.html#n32">Typemap Examples</a>
<ul>
<li><a href="Perl5.html#n33">Converting a Perl5 array to a char ** </a>
<li><a href="Perl5.html#n34">Return values </a>
<li><a href="Perl5.html#n35">Returning values from arguments</a>
<li><a href="Perl5.html#n36">Accessing array structure members</a>
<li><a href="Perl5.html#n37">Turning Perl references into C pointers</a>
<li><a href="Perl5.html#n38">Pointer handling</a>
</ul>
<li><a href="Perl5.html#n39">Proxy classes</a>
<ul>
<li><a href="Perl5.html#n40">Preliminaries</a>
<li><a href="Perl5.html#n41">Object Ownership</a>
<li><a href="Perl5.html#n42">Nested Objects</a>
<li><a href="Perl5.html#n43">Shadow Functions</a>
<li><a href="Perl5.html#n44">Inheritance</a>
</ul>
</ul>
<!-- INDEX -->
<h3><a href="Php.html">18 SWIG and PHP4</a></h3>
<!-- INDEX -->
<ul>
<li><a href="Php.html#n2">Preliminaries</a>
<li><a href="Php.html#n3">Building PHP4 Extensions</a>
<ul>
<li><a href="Php.html#n4">Building a loadable extension</a>
<li><a href="Php.html#n5">Basic PHP4 interface</a>
<li><a href="Php.html#n6">Functions</a>
<li><a href="Php.html#n7">Global Variables</a>
<li><a href="Php.html#n8">Pointers </a>
<li><a href="Php.html#n9">Structures and C++ classes</a>
<li><a href="Php.html#n10">Constants</a>
<li><a href="Php.html#n11">Shadow classes</a>
<li><a href="Php.html#n12">Constructors and Destructers</a>
<li><a href="Php.html#n13">Static Member Variables</a>
<li><a href="Php.html#n14">PHP4 Pragmas</a>
<li><a href="Php.html#n15">Building extensions into php</a>
<li><a href="Php.html#n16">To be furthered...</a>
</ul>
</ul>
<!-- INDEX -->
<h3><a href="Python.html">19 SWIG and Python</a></h3>
<!-- INDEX -->
<ul>
<li><a href="Python.html#n2">Overview</a>
<li><a href="Python.html#n3">Preliminaries</a>
<ul>
<li><a href="Python.html#n4">Running SWIG</a>
<li><a href="Python.html#n5">Getting the right header files</a>
<li><a href="Python.html#n6">Compiling a dynamic module</a>
<li><a href="Python.html#n7">Using distutils</a>
<li><a href="Python.html#n8">Static linking</a>
<li><a href="Python.html#n9">Using your module</a>
<li><a href="Python.html#n10">Compilation of C++ extensions</a>
<li><a href="Python.html#n11">Compiling for 64-bit platforms</a>
<li><a href="Python.html#n12">Building Python Extensions under Windows</a>
</ul>
<li><a href="Python.html#n13">A tour of basic C/C++ wrapping</a>
<ul>
<li><a href="Python.html#n14">Modules</a>
<li><a href="Python.html#n15">Functions</a>
<li><a href="Python.html#n16">Global variables</a>
<li><a href="Python.html#n17">Constants and enums</a>
<li><a href="Python.html#n18">Pointers</a>
<li><a href="Python.html#n19">Structures</a>
<li><a href="Python.html#n20">C++ classes</a>
<li><a href="Python.html#n21">C++ inheritance</a>
<li><a href="Python.html#n22">Pointers, references, values, and arrays</a>
<li><a href="Python.html#n23">C++ overloaded functions</a>
<li><a href="Python.html#n24">C++ operators</a>
<li><a href="Python.html#n25">C++ namespaces</a>
<li><a href="Python.html#n26">C++ templates</a>
<li><a href="Python.html#n27">C++ Smart Pointers</a>
</ul>
<li><a href="Python.html#n28">Further details on the Python class interface</a>
<ul>
<li><a href="Python.html#n29">Proxy classes</a>
<li><a href="Python.html#n30">Memory management</a>
<li><a href="Python.html#n31">Python 2.2 and classic classes</a>
</ul>
<li><a href="Python.html#n32">Common customization features</a>
<ul>
<li><a href="Python.html#n33">C/C++ helper functions</a>
<li><a href="Python.html#n34">Adding additional Python code</a>
<li><a href="Python.html#n35">Class extension with %extend</a>
<li><a href="Python.html#n36">Exception handling with %exception</a>
</ul>
<li><a href="Python.html#n37">Tips and techniques</a>
<ul>
<li><a href="Python.html#n38">Input and output parameters</a>
<li><a href="Python.html#n39">Simple pointers</a>
<li><a href="Python.html#n40">Unbounded C Arrays</a>
<li><a href="Python.html#n41">String handling</a>
<li><a href="Python.html#n42">Arrays</a>
<li><a href="Python.html#n43">String arrays</a>
<li><a href="Python.html#n44">STL wrappers</a>
</ul>
<li><a href="Python.html#n45">Typemaps</a>
<ul>
<li><a href="Python.html#n46">What is a typemap?</a>
<li><a href="Python.html#n47">Python typemaps</a>
<li><a href="Python.html#n48">Typemap variables</a>
<li><a href="Python.html#n49">Useful Python Functions</a>
</ul>
<li><a href="Python.html#n50">Typemap Examples</a>
<ul>
<li><a href="Python.html#n51">Converting Python list to a char ** </a>
<li><a href="Python.html#n52">Expanding a Python object into multiple arguments</a>
<li><a href="Python.html#n53">Using typemaps to return arguments</a>
<li><a href="Python.html#n54">Mapping Python tuples into small arrays</a>
<li><a href="Python.html#n55">Mapping sequences to C arrays</a>
<li><a href="Python.html#n56">Pointer handling</a>
</ul>
</ul>
<!-- INDEX -->
<h3><a href="Ruby.html">20 SWIG and Ruby</a></h3>
<!-- INDEX -->
<ul>
<li><a href="Ruby.html#n2">Preliminaries</a>
<ul>
<li><a href="Ruby.html#n3">Running SWIG</a>
<li><a href="Ruby.html#n4">Getting the right header files</a>
<li><a href="Ruby.html#n5">Compiling a dynamic module</a>
<li><a href="Ruby.html#n6">Using your module</a>
<li><a href="Ruby.html#n7">Static linking</a>
<li><a href="Ruby.html#n8">Compilation of C++ extensions</a>
</ul>
<li><a href="Ruby.html#n9">Building Ruby Extensions under Windows 95/NT</a>
<ul>
<li><a href="Ruby.html#n10">Running SWIG from Developer Studio</a>
</ul>
<li><a href="Ruby.html#n11">The Ruby-to-C/C++ Mapping</a>
<ul>
<li><a href="Ruby.html#n12">Modules</a>
<li><a href="Ruby.html#n13">Functions</a>
<li><a href="Ruby.html#n14">Variable Linking</a>
<li><a href="Ruby.html#n15">Constants</a>
<li><a href="Ruby.html#n16">Pointers</a>
<li><a href="Ruby.html#n17">Structures</a>
<li><a href="Ruby.html#n18">C++ classes</a>
<li><a href="Ruby.html#n19">C++ inheritance</a>
<li><a href="Ruby.html#n20">C++ overloaded functions</a>
<li><a href="Ruby.html#n21">C++ Operators</a>
<li><a href="Ruby.html#n22">C++ namespaces</a>
<li><a href="Ruby.html#n23">C++ templates</a>
<li><a href="Ruby.html#n24">C++ Smart Pointers</a>
</ul>
<li><a href="Ruby.html#n25">Input and output parameters</a>
<li><a href="Ruby.html#n26">Simple exception handling </a>
<li><a href="Ruby.html#n27">Typemaps</a>
<ul>
<li><a href="Ruby.html#n28">What is a typemap?</a>
<li><a href="Ruby.html#n29">Ruby typemaps</a>
<li><a href="Ruby.html#n30">Typemap variables</a>
<li><a href="Ruby.html#n31">Useful Functions</a>
<ul>
<li><a href="Ruby.html#n32">C Datatypes to Ruby Objects</a>
<li><a href="Ruby.html#n33">Ruby Objects to C Datatypes</a>
<li><a href="Ruby.html#n34">Macros for VALUE</a>
<li><a href="Ruby.html#n35">Exceptions</a>
<li><a href="Ruby.html#n36">Iterators</a>
</ul>
<li><a href="Ruby.html#n37">Typemap Examples</a>
<li><a href="Ruby.html#n38">Converting a Ruby array to a char **</a>
<li><a href="Ruby.html#n39">Collecting arguments in a hash</a>
<li><a href="Ruby.html#n40">Pointer handling</a>
<ul>
<li><a href="Ruby.html#n41">Ruby Datatype Wrapping</a>
</ul>
</ul>
<li><a href="Ruby.html#n42">Operator overloading</a>
<ul>
<li><a href="Ruby.html#n43">An example (putting everything together)</a>
<li><a href="Ruby.html#n44">Expanding the example</a>
<li><a href="Ruby.html#n45">STL Vector to Ruby Array</a>
</ul>
<li><a href="Ruby.html#n46">Advanced Topics</a>
<ul>
<li><a href="Ruby.html#n47">Creating Multi-Module Packages</a>
<li><a href="Ruby.html#n48">Defining Aliases</a>
<li><a href="Ruby.html#n49">Predicate Methods</a>
<li><a href="Ruby.html#n50">Specifying Mixin Modules</a>
<li><a href="Ruby.html#n51">Interacting with Ruby's Garbage Collector</a>
</ul>
</ul>
<!-- INDEX -->
<h3><a href="Tcl.html">21 SWIG and Tcl</a></h3>
<!-- INDEX -->
<ul>
<li><a href="Tcl.html#n2">Preliminaries</a>
<ul>
<li><a href="Tcl.html#n3">Getting the right header files</a>
<li><a href="Tcl.html#n4">Compiling a dynamic module</a>
<li><a href="Tcl.html#n5">Static linking</a>
<li><a href="Tcl.html#n6">Using your module</a>
<li><a href="Tcl.html#n7">Compilation of C++ extensions</a>
<li><a href="Tcl.html#n8">Compiling for 64-bit platforms</a>
<li><a href="Tcl.html#n9">Setting a package prefix</a>
<li><a href="Tcl.html#n10">Using namespaces</a>
</ul>
<li><a href="Tcl.html#n11">Building Tcl/Tk Extensions under Windows 95/NT</a>
<ul>
<li><a href="Tcl.html#n12">Running SWIG from Developer Studio</a>
<li><a href="Tcl.html#n13">Using NMAKE</a>
</ul>
<li><a href="Tcl.html#n14">A tour of basic C/C++ wrapping</a>
<ul>
<li><a href="Tcl.html#n15">Modules</a>
<li><a href="Tcl.html#n16">Functions</a>
<li><a href="Tcl.html#n17">Global variables</a>
<li><a href="Tcl.html#n18">Constants and enums</a>
<li><a href="Tcl.html#n19">Pointers</a>
<li><a href="Tcl.html#n20">Structures</a>
<li><a href="Tcl.html#n21">C++ classes</a>
<li><a href="Tcl.html#n22">C++ inheritance</a>
<li><a href="Tcl.html#n23">Pointers, references, values, and arrays</a>
<li><a href="Tcl.html#n24">C++ overloaded functions</a>
<li><a href="Tcl.html#n25">C++ operators</a>
<li><a href="Tcl.html#n26">C++ namespaces</a>
<li><a href="Tcl.html#n27">C++ templates</a>
<li><a href="Tcl.html#n28">C++ Smart Pointers</a>
</ul>
<li><a href="Tcl.html#n29">Further details on the Tcl class interface</a>
<ul>
<li><a href="Tcl.html#n30">Proxy classes</a>
<li><a href="Tcl.html#n31">Memory management</a>
</ul>
<li><a href="Tcl.html#n32">Input and output parameters</a>
<li><a href="Tcl.html#n33">Exception handling </a>
<li><a href="Tcl.html#n34">Typemaps</a>
<ul>
<li><a href="Tcl.html#n35">What is a typemap?</a>
<li><a href="Tcl.html#n36">Tcl typemaps</a>
<li><a href="Tcl.html#n37">Typemap variables</a>
<li><a href="Tcl.html#n38">Converting a Tcl list to a char ** </a>
<li><a href="Tcl.html#n39">Returning values in arguments</a>
<li><a href="Tcl.html#n40">Useful functions</a>
<li><a href="Tcl.html#n41">Standard typemaps</a>
<li><a href="Tcl.html#n42">Pointer handling</a>
</ul>
<li><a href="Tcl.html#n43">Turning a SWIG module into a Tcl Package.</a>
<li><a href="Tcl.html#n44">Building new kinds of Tcl interfaces (in Tcl)</a>
<ul>
<li><a href="Tcl.html#n45">Shadow classes</a>
</ul>
</ul>
<!-- INDEX -->
<h3><a href="Extending.html">22 Extending SWIG</a></h3>
<!-- INDEX -->
<ul>
<li><a href="Extending.html#n2">Introduction</a>
<li><a href="Extending.html#n3">Prerequisites</a>
<li><a href="Extending.html#n4">The Big Picture</a>
<li><a href="Extending.html#n5">Execution Model</a>
<ul>
<li><a href="Extending.html#n6">Preprocessing</a>
<li><a href="Extending.html#n7">Parsing</a>
<li><a href="Extending.html#n8">Parse Trees</a>
<li><a href="Extending.html#n9">Attribute namespaces</a>
<li><a href="Extending.html#n10">Symbol Tables</a>
<li><a href="Extending.html#n11">The %feature directive</a>
<li><a href="Extending.html#n12">Code Generation</a>
<li><a href="Extending.html#n13">SWIG and XML</a>
</ul>
<li><a href="Extending.html#n14">Primitive Data Structures</a>
<ul>
<li><a href="Extending.html#n15">Strings</a>
<li><a href="Extending.html#n16">Hashes</a>
<li><a href="Extending.html#n17">Lists</a>
<li><a href="Extending.html#n18">Common operations</a>
<li><a href="Extending.html#n19">I/O</a>
</ul>
<li><a href="Extending.html#n20">Navigating and manipulating parse trees</a>
<li><a href="Extending.html#n21">Working with attributes</a>
<li><a href="Extending.html#n22">Type system</a>
<ul>
<li><a href="Extending.html#n23">String encoding of types</a>
<li><a href="Extending.html#n24">Type construction</a>
<li><a href="Extending.html#n25">Type tests</a>
<li><a href="Extending.html#n26">Typedef and inheritance</a>
<li><a href="Extending.html#n27">Lvalues</a>
<li><a href="Extending.html#n28">Output functions</a>
</ul>
<li><a href="Extending.html#n29">Parameters</a>
<li><a href="Extending.html#n30">Writing a Language Module</a>
<ul>
<li><a href="Extending.html#n31">Execution model</a>
<li><a href="Extending.html#n32">Starting out</a>
<li><a href="Extending.html#n33">Command line options</a>
<li><a href="Extending.html#n34">Configuration and preprocessing</a>
<li><a href="Extending.html#n35">Entry point to code generation</a>
<li><a href="Extending.html#n36">Module I/O and wrapper skeleton</a>
<li><a href="Extending.html#n37">Low-level code generators</a>
<li><a href="Extending.html#n38">Configuration files</a>
<li><a href="Extending.html#n39">Runtime support</a>
<li><a href="Extending.html#n40">Standard library files</a>
<li><a href="Extending.html#n41">Examples and test cases</a>
<li><a href="Extending.html#n42">Documentation</a>
</ul>
<li><a href="Extending.html#n43">Typemaps</a>
<ul>
<li><a href="Extending.html#n44">Proxy classes</a>
</ul>
<li><a href="Extending.html#n45">Guide to parse tree nodes</a>
</ul>
<!-- INDEX -->
</BODY>
</HTML>

View file

@ -0,0 +1,71 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<HTML>
<HEAD>
<title> SWIG Documentation Copyright</title>
</head>
<body BGCOLOR="#FFFFFF">
<h2> SWIG Users Manual </h2>
<b>
Version 1.1<br>
June, 1997 <br>
</b>
<p>
Copyright(C) 1996, 1997<br>
All Rights Reserved<br>
<br>
David M. Beazley<br>
Department of Computer Science <br>
University of Utah <br>
Salt Lake City, Utah 84112 </br>
<tt>beazley@cs.utah.edu</tt>
<p>
This document may be freely distributed in whole or part provided this
copyright notice is retained. Commercial distribution of this document
is prohibited without the express written consent of the author.
<hr>
SWIG 1.1 is Copyright (C) 1995-1997 by the University of Utah and the
Univerity of California and distributed under the following license.
<p>
This software is copyrighted by the University of Utah and the Regents
of the University of California. The following terms apply to all
files associated with the software unless explicitly disclaimed
in individual files.
<p>
Permission is hereby granted, without written agreement and without
license or royalty fees, to use, copy, modify, and distribute this
software and its documentation for any purpose, provided that
(1) The above copyright notice and the following two paragraphs
appear in all copies of the source code and (2) redistributions
including binaries reproduces these notices in the supporting
documentation. Substantial modifications to this software may be
copyrighted by their authors and need not follow the licensing terms
described here, provided that the new terms are clearly indicated in
all files where they apply.
<p>
IN NO EVENT SHALL THE AUTHOR, THE UNIVERSITY OF CALIFORNIA, THE
UNIVERSITY OF UTAH OR DISTRIBUTORS OF THIS SOFTWARE BE LIABLE TO ANY
PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION,
EVEN IF THE AUTHORS OR ANY OF THE ABOVE PARTIES HAVE BEEN ADVISED OF
THE POSSIBILITY OF SUCH DAMAGE.
<p>
THE AUTHOR, THE UNIVERSITY OF CALIFORNIA, AND THE UNIVERSITY OF UTAH
SPECIFICALLY DISCLAIM ANY WARRANTIES,INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND
THE AUTHORS AND DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE,
SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
<hr>
<address><a href="http://www.cs.utah.edu/~beazley"> beazley@cs.utah.edu </a> <br>
Last Modified, August 3, 1997</address>
</body>
</html>

View file

@ -0,0 +1,643 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Customization Features</title>
</head>
<body bgcolor="#ffffff">
<a name="n1"></a><H1>9 Customization Features</H1>
<!-- INDEX -->
<ul>
<li><a href="#n2">Exception handling with %exception</a>
<ul>
<li><a href="#n3">Handling exceptions in C code</a>
<li><a href="#n4">Exception handling with longjmp()</a>
<li><a href="#n5">Handling C++ exceptions</a>
<li><a href="#n6">Defining different exception handlers</a>
<li><a href="#n7">Applying exception handlers to specific datatypes.</a>
<li><a href="#n8">Using The SWIG exception library</a>
</ul>
<li><a href="#n9">Object ownership and %newobject</a>
<li><a href="#n10">Features and the %feature directive</a>
</ul>
<!-- INDEX -->
In many cases, it is desirable to change the default wrapping of
particular declarations in an interface. For example, you might want
to provide hooks for catching C++ exceptions, add assertions, or
provide hints to the underlying code generator. This chapter
describes some of these customization techniques. First, a discussion
of exception handling is presented. Then, a more general-purpose
customization mechanism known as "features" is described.
<a name="n2"></a><H2>9.1 Exception handling with %exception</H2>
The <tt>%exception</tt> directive allows you to define a general purpose exception
handler. For example, you can specify the following:
<p>
<blockquote><pre>%exception {
try {
$action
}
catch (RangeError) {
PyErr_SetString(PyExc_IndexError,"index out-of-bounds");
return NULL;
}
}
</pre></blockquote>
<p>
When defined, the code enclosed in braces is inserted directly into the low-level wrapper
functions. The special symbol <tt>$action</tt> gets replaced with the actual operation
to be performed (a function call, method invocation, attribute access, etc.). An exception handler
remains in effect until it is explicitly deleted. This is done by using <tt>%except</tt> with
no code. For example:
<p>
<blockquote><pre>%exception; // Deletes any previously defined handler
</pre></blockquote>
<p>
<b>Compatibility note:</b> Previous versions of SWIG used a special directive <tt>%except</tt>
for exception handling. That directive is still supported but is deprecated--<tt>%exception</tt>
provides the same functionality, but is substantially more flexible.
<a name="n3"></a><H3>9.1.1 Handling exceptions in C code</H3>
C has no formal exception handling mechanism so there are several approaches that might be
used. A somewhat common technique is to simply set a special error code. For example:
<p>
<blockquote><pre>
/* File : except.c */
static char error_message[256];
static int error_status = 0;
void throw_exception(char *msg) {
strncpy(error_message,msg,256);
error_status = 1;
}
void clear_exception() {
error_status = 0;
}
char *check_exception() {
if (error_status) return error_message;
else return NULL;
}
</pre></blockquote>
To use these functions, functions simply call
<tt>throw_exception()</tt> to indicate an error occurred. For example
:<p>
<p>
<blockquote><pre>double inv(double x) {
if (x != 0) return 1.0/x;
else {
throw_exception("Division by zero");
return 0;
}
}
</pre></blockquote>
To catch the exception, you can write a simple exception handler such
as the following (shown for Perl5) :<p>
<p>
<blockquote><pre>%exception {
char *err;
clear_exception();
$action
if ((err = check_exception())) {
croak(err);
}
}
</pre></blockquote>
<p>
In this case, when an error occurs, it is translated into a Perl error.
<a name="n4"></a><H3>9.1.2 Exception handling with longjmp()</H3>
Exception handling can also be added to C code using the
<tt>&lt;setjmp.h&gt;</tt> library. Here is a minimalistic implementation that
relies on the C preprocessor :
<blockquote><pre>
/* File : except.c
Just the declaration of a few global variables we're going to use */
#include &lt;setjmp.h&gt;
jmp_buf exception_buffer;
int exception_status;
/* File : except.h */
#include &lt;setjmp.h&gt;
extern jmp_buf exception_buffer;
extern int exception_status;
#define try if ((exception_status = setjmp(exception_buffer)) == 0)
#define catch(val) else if (exception_status == val)
#define throw(val) longjmp(exception_buffer,val)
#define finally else
/* Exception codes */
#define RangeError 1
#define DivisionByZero 2
#define OutOfMemory 3
</pre></blockquote>
Now, within a C program, you can do the following :<p>
<p>
<blockquote><pre>double inv(double x) {
if (x) return 1.0/x;
else throw(DivisionByZero);
}
</pre></blockquote>
Finally, to create a SWIG exception handler, write the following :<p>
<p>
<blockquote><pre>%{
#include "except.h"
%}
%exception {
try {
$action
} catch(RangeError) {
croak("Range Error");
} catch(DivisionByZero) {
croak("Division by zero");
} catch(OutOfMemory) {
croak("Out of memory");
} finally {
croak("Unknown exception");
}
}
</pre></blockquote>
Note: This implementation is only intended to illustrate the general idea. To make it work better, you'll need to
modify it to handle nested <tt>try</tt> declarations.
<a name="n5"></a><H3>9.1.3 Handling C++ exceptions</H3>
Handling C++ exceptions is also straightforward. For example:
<p>
<blockquote><pre>%exception {
try {
$action
} catch(RangeError) {
croak("Range Error");
} catch(DivisionByZero) {
croak("Division by zero");
} catch(OutOfMemory) {
croak("Out of memory");
} catch(...) {
croak("Unknown exception");
}
}
</pre></blockquote>
The exception types need to be declared as classes elsewhere, possibly
in a header file :<p>
<p>
<blockquote><pre>class RangeError {};
class DivisionByZero {};
class OutOfMemory {};
</pre>
</blockquote>
<a name="n6"></a><H3>9.1.4 Defining different exception handlers</H3>
By default, the <tt>%exception</tt> directive creates an exception
handler that is used for all wrapper functions that follow it. Unless
there is a well-defined (and simple) error handling mechanism in place,
defining one universal exception handler may be unwieldy and result
in excessive code bloat since the handler is inlined into each wrapper function.
<p>
To fix this, you can be more selective about how you use the
<tt>%exception</tt> directive. One approach is to only place it around
critical pieces of code. For example:
<p>
<blockquote><pre>%exception {
... your exception handler ...
}
/* Define critical operations that can throw exceptions here */
%exception;
/* Define non-critical operations that don't throw exceptions */
</pre></blockquote>
More precise control over exception handling can be obtained by attaching an exception handler
to specific declaration name. For example:
<blockquote>
<pre>
%exception allocate {
try {
$action
}
catch (MemoryError) {
croak("Out of memory");
}
}
</pre>
</blockquote>
In this case, the exception handler is only attached to declarations
named "allocate". This would include both global and member
functions. The names supplied to <tt>%exception</tt> follow the same
rules as for <tt>%rename</tt>. For example, if you wanted to define
an exception handler for a specific class, you might write this:
<blockquote>
<pre>
%exception Object::allocate {
try {
$action
}
catch (MemoryError) {
croak("Out of memory");
}
}
</pre>
</blockquote>
When a class prefix is supplied, the exception handler is applied to the corresponding declaration
in the specified class as well as for identically named functions appearing in derived classes.
<p>
<tt>%exception</tt> can even be used to pinpoint a precise declaration when overloading is used. For example:
<blockquote>
<pre>
%exception Object::allocate(int) {
try {
$action
}
catch (MemoryError) {
croak("Out of memory");
}
}
</pre>
</blockquote>
Attaching exceptions to specific declarations is a good way to reduce code bloat. It can also be a useful way
to attach exceptions to specific parts of a header file. For example:
<blockquote>
<pre>
%module example
%{
#include "someheader.h"
%}
// Define a few exception handlers for specific declarations
%exception Object::allocate(int) {
try {
$action
}
catch (MemoryError) {
croak("Out of memory");
}
}
%exception Object::getitem {
try {
$action
}
catch (RangeError) {
croak("Index out of range");
}
}
...
// Read a raw header file
%include "someheader.h"
</pre>
</blockquote>
<a name="n7"></a><H3>9.1.5 Applying exception handlers to specific datatypes.</H3>
An alternative approach to using the <tt>%exception</tt> directive is to
use the "except" typemap. This allows you to attach an error handler
to specific datatypes and function name. The typemap is applied to
the return value of a function. For example :<p>
<p>
<blockquote><pre>%typemap(except) void *malloc {
$action
if (!$1) {
PyExc_SetString(PyExc_MemoryError,"Out of memory in $symname");
return NULL;
}
}
void *malloc(int size);
</pre></blockquote>
When applied, this automatically checks the return value of
<tt>malloc()</tt> and raises an exception if it's invalid. For example
:<p>
<p>
<blockquote><pre>
&gt;&gt;&gt; from example import *
&gt;&gt;&gt; a = malloc(2048)
&gt;&gt;&gt; b = malloc(1500000000)
Traceback (innermost last):
File "&lt;stdin&gt;", line 1, in ?
MemoryError: Out of memory in malloc
&gt;&gt;&gt;
</pre></blockquote>
When "except" typemaps are used, they override any exception handler defined with
<tt>%exception</tt>.<p>
<p>
<b>Compatibility note:</b> The except typemap dates to earlier SWIG
releases and was intended to be a mechanism for pinpointing specific
declarations. However, it never really worked that well and the new
%exception directive is much better. The except typemap is preserved for now, but
may be deprecated in future versions.
<a name="n8"></a><H3>9.1.6 Using The SWIG exception library</H3>
The <tt>exception.i</tt> library file provides support for creating
language independent exceptions in your interfaces. To use it, simply
put an "<tt>%include exception.i</tt>" in your interface file. This
creates a function<tt> SWIG_exception()</tt> that can be used to raise
common scripting language exceptions in a portable manner. For example :<p>
<p>
<blockquote><pre>// Language independent exception handler
%include exception.i
%exception {
try {
$action
} catch(RangeError) {
SWIG_exception(SWIG_ValueError, "Range Error");
} catch(DivisionByZero) {
SWIG_exception(SWIG_DivisionByZero, "Division by zero");
} catch(OutOfMemory) {
SWIG_exception(SWIG_MemoryError, "Out of memory");
} catch(...) {
SWIG_exception(SWIG_RuntimeError,"Unknown exception");
}
}
</pre></blockquote>
As arguments, <tt>SWIG_exception()</tt> takes an error type code (an
integer) and an error message string. The currently supported error
types are :<p>
<p>
<blockquote><pre>SWIG_MemoryError
SWIG_IOError
SWIG_RuntimeError
SWIG_IndexError
SWIG_TypeError
SWIG_DivisionByZero
SWIG_OverflowError
SWIG_SyntaxError
SWIG_ValueError
SWIG_SystemError
SWIG_UnknownError
</pre></blockquote>
<p>
Since the <tt>SWIG_exception()</tt> function is defined at the C-level
it can be used elsewhere in SWIG. This includes typemaps and helper
functions.
<a name="n9"></a><H2>9.2 Object ownership and %newobject</H2>
A common problem in some applications is managing proper ownership of objects. For
example, consider a function like this:
<blockquote>
<pre>
Foo *blah() {
Foo *f = new Foo();
return f;
}
</pre>
</blockquote>
If you wrap the function <tt>blah()</tt>, SWIG has no idea that the
return value is a newly allocated object. As a result, the resulting
extension module may produce a memory leak (SWIG is conservative and
will never delete objects unless it knows for certain that the
returned object was newly created).
<p>
To fix this, you can provide an extra hint to the code generator using
the <tt>%newobject</tt> directive. For example:
<blockquote>
<pre>
%newobject blah;
Foo *blah();
</pre>
</blockquote>
<tt>%newobject</tt> works exactly like <tt>%rename</tt> and <tt>%exception</tt>. In other words,
you can attach it to class members and parameterized declarations as before. For example:
<blockquote>
<pre>
%newobject ::blah(); // Only applies to global blah
%newobject Object::blah(int,double); // Only blah(int,double) in Object
%newobject *::copy; // Copy method in all classes
...
</pre>
</blockquote>
When <tt>%newobject</tt> is supplied, many language modules will
arrange to take ownership of the return value. This allows the value
to be automatically garbage-collected when it is no longer in use. However,
this depends entirely on the target language (a language module may choose to ignore
the <tt>%newobject</tt> directive).
<p>
Closely related to <tt>%newobject</tt> is a special typemap. The "newfree" typemap
can be used to deallocate a newly allocated return value. It is only available on
methods for which <tt>%newobject</tt> has been applied and is commonly used to clean-up string
results. For example:
<blockquote>
<pre>
%typemap(newfree) char * "free($1);";
...
%newobject strdup;
...
char *strdup(const char *s);
</pre>
</blockquote>
In this case, the result of the function is a string in the target language. Since this string
is a copy of the original result, the data returned by <tt>strdup()</tt> is no longer needed.
The "newfree" typemap in the example simply releases this memory.
<p>
<b>Compatibility note:</b> Previous versions of SWIG had a special <tt>%new</tt> directive. However, unlike <tt>%newobject</tt>,
it only applied to the next declaration. For example:
<blockquote>
<pre>
%new char *strdup(const char *s);
</pre>
</blockquote>
For now this is still supported but is deprecated.
<p>
<b>How to shoot yourself in the foot:</b> The <tt>%newobject</tt> directive is not a declaration modifier like the old
<tt>%new</tt> directive. Don't write code like this:
<blockquote>
<pre>
%newobject
char *strdup(const char *s);
</pre>
</blockquote>
The results might not be what you expect.
<a name="n10"></a><H2>9.3 Features and the %feature directive</H2>
Both <tt>%exception</tt> and <tt>%newobject</tt> are examples of a
more general purpose customization mechanism known as "features." A
feature is simply a user-definable property that is attached to
specific declarations in an interface file. Features are attached
using the <tt>%feature</tt> directive. For example:
<blockquote>
<pre>
%feature("except") Object::allocate {
try {
$action
}
catch (MemoryError) {
croak("Out of memory");
}
}
%feature("new","1") *::copy;
</pre>
</blockquote>
In fact, the <tt>%exception</tt> and <tt>%newobject</tt> directives are really nothing more than macros
involving <tt>%feature</tt>:
<blockquote>
<pre>
#define %exception %feature("except")
#define %newobject %feature("new","1")
</pre>
</blockquote>
The <tt>%feature</tt> directive follows the same name matching rules
as the <tt>%rename</tt> directive (which is in fact just a special
form of <tt>%feature</tt>). This means that features can be applied with
pinpoint accuracy to specific declarations if needed.
<p>
When a feature is defined, it is given a name and a value. Most commonly, the
value is supplied after the declaration name as shown for the <tt>"except"</tt>
example above. However, if the feature is simple, a value might be supplied
as an extra argument as shown for the <tt>"new"</tt> feature.
<p>
A feature stays in effect until it is explicitly disabled. A feature is disabled by
supplying a <tt>%feature</tt> directive with no value. For example:
<blockquote>
<pre>
%feature("except") Object::allocate; // Removes any previously defined feature
</pre>
</blockquote>
<p>
If no declaration name is given, a global feature is defined. This feature is then
attached to <em>every</em> declaration that follows. This is how global exception handlers
are defined. For example:
<blockquote>
<pre>
/* Define a global exception handler */
%feature("except") {
try {
$action
}
...
}
... bunch of declarations ...
/* Disable the exception handler */
%feature("except");
</pre>
</blockquote>
<tt>%feature</tt> is a relatively new addition to SWIG that was not added until version 1.3.10.
Its intended use is as a highly flexible customization mechanism that can be used to annotate
declarations with additional information for use by specific target language modules. For example,
in the Python module, you might use <tt>%feature</tt> to rewrite shadow class code as follows:
<blockquote>
<pre>
%module example
%rename(bar_id) bar(int,double);
// Rewrite bar() to allow some nice overloading
%feature("shadow") Foo::bar(int) %{
def bar(*args):
if len(args) == 3:
return apply(examplec.Foo_bar_id,args)
return apply(examplec.Foo_bar,args)
%}
class Foo {
public:
int bar(int x);
int bar(int x, double y);
}
</pre>
</blockquote>
As of this writing, <tt>%feature</tt> is still experimental. Further details of its
use will be described in the documentation for specific language modules.
<p><hr>
<address>SWIG 1.3 - Last Modified : December 9, 2001</address>
</body>
</html>

View file

@ -0,0 +1,17 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Documentation System</title>
</head>
<body bgcolor="#ffffff">
<h1>5 Documentation System</h1>
The documentation system is under repair and disabled in SWIG1.3. It will
return in a later release.
<p><hr>
<address>SWIG 1.3 - Last Modified : August 18, 2001</address>
</body>
</html>

File diff suppressed because it is too large Load diff

456
SWIG/Doc/Manual/Guile.html Normal file
View file

@ -0,0 +1,456 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<!-- Hand-written HTML -->
<html>
<head>
<title>SWIG and Guile</title>
</head>
<body bgcolor="#ffffff">
<a name="n1"></a><H1>14 SWIG and Guile</H1>
<!-- INDEX -->
<ul>
<li><a href="#n2">Meaning of "Module"</a>
<li><a href="#n3">Linkage</a>
<ul>
<li><a href="#n4">Simple Linkage</a>
<li><a href="#n5">Passive Linkage</a>
<li><a href="#n6">Native Guile Module Linkage</a>
<li><a href="#n7">Old Auto-Loading Guile Module Linkage</a>
<li><a href="#n8">Hobbit4D Linkage</a>
<li><a href="#n9">General Remarks on Multiple SWIG Modules</a>
</ul>
<li><a href="#n10">Underscore Folding</a>
<li><a href="#n11">Typemaps</a>
<li><a href="#n12">Smobs</a>
<li><a href="#n13">Exception Handling</a>
<li><a href="#n14">Procedure documentation</a>
<li><a href="#n15">Procedures with setters</a>
</ul>
<!-- INDEX -->
<p>
This section details guile-specific support in SWIG.
<a name="n2"></a><H2>14.1 Meaning of "Module"</H2>
</a>
<p>
There are three different concepts of "module" involved, defined
separately for SWIG, Guile, and Libtool. To avoid horrible confusion,
we explicitly prefix the context, e.g., "guile-module".
<a name="n3"></a><H2>14.2 Linkage</H2>
</a>
<p>
Guile support is complicated by a lack of user community cohesiveness,
which manifests in multiple shared-library usage conventions. A set of
policies implementing a usage convention is called a <b>linkage</b>.
<a name="n4"></a><H3>14.2.1 Simple Linkage</H3>
The default linkage is the simplest; nothing special is done. In this
case the function <code>SWIG_init()</code> is exported. Simple linkage
can be used in several ways:
<ul>
<li><b>Embedded Guile, no modules.</b> You want to embed a Guile
interpreter into your program; all bindings made by SWIG shall show up
in the root module. Then call <code>SWIG_init()</code> in the
<code>inner_main()</code> function. See the "simple" and "matrix" examples under
<code>Examples/guile</code>.
<li><b>Dynamic module mix-in.</b> You want to create a Guile module
using <code>define-module</code>, containing both Scheme code and
bindings made by SWIG; you want to load the SWIG modules as shared
libraries into Guile.
<blockquote>
<pre>
(define-module (my module))
(define my-so (dynamic-link "./example.so"))
(dynamic-call "SWIG_init" my-so) ; make SWIG bindings
;; Scheme definitions can go here
</pre>
</blockquote>
Newer Guile versions provide a shorthand for <code>dynamic-link</code>
and <code>dynamic-call</code>:
<blockquote>
<pre>
(load-extension "./example.so" "SWIG_init")
</pre>
</blockquote>
You need to explicitly export those bindings made by SWIG that you
want to import into other modules:
<blockquote>
<pre>
(export foo bar)
</pre>
</blockquote>
In this example, the procedures <code>foo</code> and <code>bar</code>
would be exported. Alternatively, you can export all bindings with the
following module-system hack:
<blockquote>
<pre>
(module-map (lambda (sym var)
(module-export! (current-module) (list sym)))
(current-module))
</pre>
</blockquote>
<p>SWIG can also generate this Scheme stub (from
<code>define-module</code> up to <code>export</code>)
semi-automagically if you pass it the command-line argument
<code>-scmstub <var>foo.scm</var></code>. Since SWIG doesn't know how
to load your extension module (with <code>dynamic-link</code> or
<code>load-extension</code>), you need to supply this
information by including a directive like this in the interface file:
<blockquote>
<pre>
%scheme %{ (load-extension "./example.so" "SWIG_init") %}
</pre>
</blockquote>
(The <code>%scheme</code> directive allows to insert arbitrary Scheme
code into the generated file <code><var>foo.scm</var></code>; it is
placed between the <code>define-module</code> form and the
<code>export</code> form.)
</ul>
<p>If you want to include several SWIG modules, you would need to rename
<code>SWIG_init</code> via a preprocessor define to avoid symbol
clashes. For this case, however, passive linkage is available.
<a name="n5"></a><H3>14.2.2 Passive Linkage</H3>
<p>Passive linkage is just like simple linkage, but it generates an
initialization function whose name is derived from the module and
package name (see below).
<p>You should use passive linkage rather than simple linkage when you
are using multiple modules.
<a name="n6"></a><H3>14.2.3 Native Guile Module Linkage</H3>
<p>SWIG can also generate wrapper code that does all the Guile module
declarations on its own if you pass it the <code>-Linkage
module</code> command-line option. This requires Guile 1.5.0 or later.
<p>The module name is set with the <code>-package</code> and
<code>-module</code> command-line options. Suppose you want to define
a module with name <code>(my lib foo)</code>; then you would have to
pass the options <code>-package <var>my</var>/<var>lib</var> -module
<var>foo</var></code>. Note that the last part of the name can also be set
via the SWIG directive <code>%module</code>.
<p>You can use this linkage in several ways:
<ul>
<li><b>Embedded Guile with SWIG modules.</b> You want to embed a Guile
interpreter into your program; the SWIG bindings shall be put into
different modules. Simply call the function
<code>scm_init_<var>my</var>_<var>modules</var>_<var>foo</var>_module</code>
in the <code>inner_main()</code> function.
<li><b>Dynamic Guile modules.</b> You want to load the SWIG modules as
shared libraries into Guile; all bindings are automatically put in
newly created Guile modules.
<blockquote>
<pre>
(define my-so (dynamic-link "./foo.so"))
;; create new module and put bindings there:
(dynamic-call "scm_init_my_modules_foo_module" my-so)
</pre>
</blockquote>
Newer Guile versions have a shorthand procedure for this:
<blockquote>
<pre>
(load-extension "./foo.so" "scm_init_my_modules_foo_module")
</pre>
</blockquote>
</ul>
<a name="n7"></a><H3>14.2.4 Old Auto-Loading Guile Module Linkage</H3>
<p>Guile used to support an autoloading facility for object-code
modules. This support has been marked deprecated in version 1.4.1 and
is going to disappear sooner or later. SWIG still supports building
auto-loading modules if you pass it the <code>-Linkage ltdlmod</code>
command-line option.
<p>Auto-loading worked like this: Suppose a module with name <code>(my
lib foo)</code> is required and not loaded yet. Guile will then search
all directories in its search path
for a Scheme file <code>my/modules/foo.scm</code> or a shared library
<code><var>my</var>/<var>modules</var>/lib<var>foo</var>.so</code> (or
<code><var>my</var>/<var>modules</var>/lib<var>foo</var>.la</code>;
see the GNU libtool documentation). If a
shared library is found that contains the symbol
<code>scm_init_<var>my</var>_<var>modules</var>_<var>foo</var>_module</code>,
the library is loaded, and the function at that symbol is called with
no arguments in order to initialize the module.
<p>When invoked with the <code>-Linkage ltdlmod</code> command-line
option, SWIG generates an exported module initialization function with
an apropriate name.
<a name="n8"></a><H3>14.2.5 Hobbit4D Linkage</H3>
<p>
The only other linkage supported at this time creates shared object
libraries suitable for use by hobbit's <code>(hobbit4d link)</code>
guile module. This is called the "hobbit" linkage, and requires also
using the "-package" command line option to set the part of the module
name before the last symbol. For example, both command lines:
<blockquote>
<pre>
swig -guile -package my/lib foo.i
swig -guile -package my/lib -module foo foo.i
</pre>
</blockquote>
would create module <code>(my lib foo)</code> (assuming in the first
case foo.i declares the module to be "foo"). The installed files are
my/lib/libfoo.so.X.Y.Z and friends. This scheme is still very
experimental; the (hobbit4d link) conventions are not well understood.
<a name="n9"></a><H3>14.2.6 General Remarks on Multiple SWIG Modules</H3>
If you want to use multiple SWIG modules, they have to share some
run-time data for the typing system. You have two options:
<ul>
<li>Either generate all but one wrapper module with
the <code>-c</code> command-line argument. Compile all wrapper files
with the C compiler switch <code>-DSWIG_GLOBAL</code>.
<li>Or generate all wrapper modules with the <code>-c</code>
command-line argument and compile all wrapper files with the C
compiler switch <code>-DSWIG_GLOBAL</code>. Then link against the
runtime library <code>libswigguile</code>, which is built by
<code>make runtime</code>. The needed linker flags are reported by
SWIG if you invoke it with the <code>-guile -ldflags</code>
command-line arguments.
</ul>
<a name="n10"></a><H2>14.3 Underscore Folding</H2>
</a>
<p>
Underscores are converted to dashes in identifiers. Guile support may
grow an option to inhibit this folding in the future, but no one has
complained so far.
<p>You can use the SWIG directives <code>%name</code> and
<code>%rename</code> to specify the Guile name of the wrapped
functions and variables (see CHANGES).
<a name="n11"></a><H2>14.4 Typemaps</H2>
</a>
<p>
The Guile module handles all types via typemaps. This
information is read from <code>Lib/guile/typemaps.i</code>.
Some non-standard typemap substitutions are supported:
<ul>
<li><code>$descriptor</code> expands to a type descriptor for use with
the <code>SWIG_Guile_MakePtr()</code> and
<code>SWIG_Guile_GetPtr</code> functions.
<li>For pointer types, <code>$*descriptor</code> expands to a
descriptor for the direct base type (i.e., one pointer is stripped),
whereas <code>$basedescriptor</code> expands to a
descriptor for the base type (i.e., all pointers are stripped).
</ul>
<p>A function returning <code>void</code> (more precisely, a function
whose <code>out</code> typemap returns <code>GH_UNSPECIFIED</code>) is
treated as returning no values. In <code>argout</code> typemaps, one
can use the macro <code>GUILE_APPEND_RESULT</code> in order to append
a value to the list of function return values.
<p>Multiple values can be passed up to Scheme in one of three ways:
<ul>
<li><em>Multiple values as lists.</em>
By default, if more than one value is to
be returned, a list of the values is created and returned; to switch
back to this behavior, use
<blockquote>
<pre>%values_as_list;</pre>
</blockquote>
<li><em>Multiple values as vectors.</em>
By issueing
<blockquote>
<pre>%values_as_vector;</pre>
</blockquote>
vectors instead of lists will be used.
<li><em>Multiple values for multiple-value continuations.</em>
<strong>This is the most elegant way.</strong> By issueing
<blockquote>
<pre>%multiple_values;</pre>
</blockquote>
multiple values are passed to the multiple-value
continuation, as created by <code>call-with-values</code> or the
convenience macro <code>receive</code>. The latter is available if you
issue <code>(use-modules (srfi srfi-8))</code>. Assuming that your
<code>divide</code> function
wants to return two values, a quotient and a remainder, you can write:
<blockquote>
<pre>
(receive (quotient remainder)
(divide 35 17)
<var>body</var>...)
</pre>
</blockquote>
In <code><var>body</var></code>, the first result of
<code>divide</code> will be bound to the variable
<code>quotient</code>, and the second result to <code>remainder</code>.
</ul>
See also the "multivalue" example.
<a name="n12"></a><H2>14.5 Smobs</H2>
</a>
<p>
For pointer types, SWIG uses Guile smobs.
<p>
In earlier versions of SWIG, C pointers were represented as Scheme
strings containing a hexadecimal rendering of the pointer value and a
mangled type name. As Guile allows registering user types, so-called
"smobs" (small objects), a much cleaner representation has been
implemented now. The details will be discussed in the following.
<p>
A smob is a cons cell where the lower half of the CAR contains the
smob type tag, while the upper half of the CAR and the whole CDR are
available. <code>SWIG_Guile_Init()</code> registers a smob type named
"swig" with Guile; its type tag is stored in the variable
<code>swig_tag</code>. The upper half of the CAR store an index into
a table of all C pointer types seen so far, to which new types seen
are appended. The CDR stores the pointer value. SWIG smobs print
like this: <code>#&lt;swig struct xyzzy * 0x1234affe&gt;</code> Two of
them are <code>equal?</code> if and only if they have the same type
and value.
<p>
To construct a Scheme object from a C pointer, the wrapper code calls
the function <code>SWIG_Guile_MakePtr()</code>, passing a pointer to a
struct representing the pointer type. The type index to store in the
upper half of the CAR is read from this struct.
<p>
To get the pointer represented by a smob, the wrapper code calls the
function <code>SWIG_Guile_GetPtr</code>, passing a pointer to a struct
representing the expected pointer type. If the
Scheme object passed was not a SWIG smob representing a compatible
pointer, a <code>wrong-type-arg</code> exception is raised.
<a name="n13"></a><H2>14.6 Exception Handling</H2>
</a>
<p>
SWIG code calls <code>scm_error</code> on exception, using the following
mapping:
<pre>
MAP(SWIG_MemoryError, "swig-memory-error");
MAP(SWIG_IOError, "swig-io-error");
MAP(SWIG_RuntimeError, "swig-runtime-error");
MAP(SWIG_IndexError, "swig-index-error");
MAP(SWIG_TypeError, "swig-type-error");
MAP(SWIG_DivisionByZero, "swig-division-by-zero");
MAP(SWIG_OverflowError, "swig-overflow-error");
MAP(SWIG_SyntaxError, "swig-syntax-error");
MAP(SWIG_ValueError, "swig-value-error");
MAP(SWIG_SystemError, "swig-system-error");
</pre>
<p>
The default when not specified here is to use "swig-error".
See Lib/exception.i for details.
<a name="n14"></a><H2>14.7 Procedure documentation</H2>
</a>
<p>If invoked with the command-line option <code>-procdoc
<var>file</var></code>, SWIG creates documentation strings for the
generated wrapper functions, describing the procedure signature and
return value, and writes them to <var>file</var>. You need Guile 1.4
or later to make use of the documentation files.
<p>SWIG can generate documentation strings in three formats, which are
selected via the command-line option <code>-procdocformat
<var>format</var></code>:
<ul>
<li><code>guile-1.4</code> (default): Generates a format suitable for Guile 1.4.
<li><code>plain</code>: Generates a format suitable for Guile 1.4.1 and
later.
<li><code>texinfo</code>: Generates texinfo source, which must be run
through texinfo in order to get a format suitable for Guile 1.4.1 and
later.
</ul>
<p>You need to register the generated documentation file with Guile
like this:
<pre>
(use-modules (ice-9 documentation))
(set! documentation-files
(cons "<var>file</var>" documentation-files))
</pre>
<p>Documentation strings can be configured using the Guile-specific
typemaps <code>indoc</code>, <code>outdoc</code>,
<code>argoutdoc</code>, <code>varindoc</code>, and
<code>varoutdoc</code>. See <code>Lib/guile/typemaps.i</code> for
details.
<a name="n15"></a><H2>14.8 Procedures with setters</H2>
</a>
<p>For global variables, SWIG creates a single wrapper procedure
<code>(<var>variable</var> :optional value)</code>, which is used for
both getting and setting the value. For struct members, SWIG creates
two wrapper procedures <code>(<var>struct</var>-<var>member</var>-get
pointer)</code> and <code>(<var>struct-member</var>-set pointer value)</code>.
<p>If invoked with the command-line option <code>-emit-setters</code>,
SWIG will additionally create procedures with setters. For global
variables, the procedure-with-setter <code><var>variable</var></code>
is created, so you can use <code>(<var>variable</var>)</code> to get
the value and <code>(set! (<var>variable</var>)
<var>value</var>)</code> to set it. For struct members, the
procedure-with-setter <code><var>struct</var>-<var>member</var></code>
is created, so you can use <code>(<var>struct</var>-<var>member</var>
<var>pointer</var>)</code> to get the value and <code>(set!
(<var>struct</var>-<var>member</var> <var>pointer</var>)
<var>value</var>)</code> to set it.
</body>
</html>

View file

@ -0,0 +1,392 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Introduction</title>
</head>
<body bgcolor="#ffffff">
<a name="n1"></a><H1>1 Introduction</H1>
<!-- INDEX -->
<ul>
<li><a href="#n2">What is SWIG?</a>
<li><a href="#n3">Why use SWIG?</a>
<li><a href="#n4">A SWIG example</a>
<ul>
<li><a href="#n5">SWIG interface file</a>
<li><a href="#n6">The swig command</a>
<li><a href="#n7">Building a Perl5 module</a>
<li><a href="#n8">Building a Python module</a>
<li><a href="#n9">Shortcuts</a>
<li><a href="#n10">Building libraries and modules</a>
</ul>
<li><a href="#n11">Supported C/C++ language features</a>
<li><a href="#n12">Non-intrusive interface building</a>
<li><a href="#n13">Hands off code generation</a>
</ul>
<!-- INDEX -->
<a name="n2"></a><H2>1.1 What is SWIG?</H2>
SWIG is a software development tool that simplifies the task of
interfacing different languages to C and C++ programs. In a
nutshell, SWIG is a compiler that takes C declarations and creates
the wrappers needed to access those declarations from other languages including
including Perl, Python, Tcl, Ruby, Guile, and Java. SWIG normally
requires no modifications to existing code and can often be used to
build a usable interface in only a few minutes. Possible applications
of SWIG include:
<p>
<ul>
<li>Building interpreted interfaces to existing C programs.
<li>Rapid prototyping and application development.
<li>Interactive debugging.
<li>Reengineering or refactoring of legacy software into a scripting language components.
<li>Making a graphical user interface (using Tk for example).
<li>Testing of C libraries and programs (using scripts).
<li>Building high performance C modules for scripting languages.
<li>Making C programming more enjoyable (or tolerable depending on your point of view)
<li>Impressing your friends.
<li>Obtaining vast sums of research funding (although obviously not applicable to the author).
</ul>
<p>
SWIG was originally designed to make it extremely easy for scientists
and engineers to build extensible scientific software without having to get a
degree in software engineering. Because of this, the use of
SWIG tends to be somewhat informal and ad-hoc (e.g., SWIG does not
require users to provide formal interface specifications as you would find in
a dedicated IDL compiler). Although
this style of development isn't appropriate for every
project, it is particularly well suited to software development in the
small; especially the research and development work that is commonly found
in scientific and engineering projects.
<a name="n3"></a><H2>1.2 Why use SWIG?</H2>
Although C is great for high-performance number crunching and systems
programming, trying to make an interactive and highly flexible C
program is a pain. Even though it is possible to build a user
interface using command line options, a home grown command
interpreter, or a graphical user interface, this often results in a
program that is hard to extend, hard to modify, hard to port between
platforms, and hard to use. Furthermore, this sort of activity wastes
a lot of development time because it usually diverts everyone's attention away
from the real problem that they're trying to solve.
<p>
Many of the problems with C are due to the way in which
many programs are organized. For example, a lot of programs
are structured as follows:
<p>
<ul>
<li>A collection of functions and variables that do something useful.
<li>A <tt>main()</tt> program that starts everything.
<li>A horrible collection of hacks that form some kind of user interface (but
which no-one really wants to touch).
</ul>
<p>
In this case, the <tt>main()</tt> program may read command line
options or simple commands from <tt>stdin</tt>. However, modifying or
extending the program to do something new requires changing the C
code, recompiling, and testing. If you make a mistake, you need to
repeat this cycle until things work. Of course, as more and more
features are added, the program usually turns into a horrible mess
that is even more difficult to modify than before (although this
undoubtedly increases the job security of the programmer).
<p>
A common mistake is to assume that all of the problems with C can somehow be
fixed by using a better C---perhaps an undebuggable
language with unreadable syntax, complicated semantics, and nearly
infinite compilation time. This is an unfortunate.
<P>
Perhaps a better approach is to place your application under the control
of a very high-level language such as a common scripting language
interpreter. High level languages excel at turning hard problems into
easy tasks. They also provide a nice framework for managing software components
and gluing different systems together. Not only that, they make it easy
for users to configure the software to their liking and to program it to perform
new tasks without ever having to touch a C/C++ compiler.
<p>
SWIG simplifies the task of incorporating C++ code into a high-level
programming environment. Specifically, rather than creating a huge
monolithic package, SWIG allows you to restructure your application as
a collection of functions and variables that can be accessed from the
convenience of a high-level language. With this model, all of the
functionality of your C program is retained. The only difference is
that the high-level program logic and control is now driven by the
high-level language instead of a low level
<tt>main()</tt> function.
<p>
SWIG tries to make the integration between scripting languages and C
as painless as possible. This allows you to focus on the underlying C
program and using the high-level scripting language interface, but not
the tedious and complex chore of making the two languages talk to each
other.<p>
<p>
<a name="n4"></a><H2>1.3 A SWIG example</H2>
The best way to illustrate SWIG is with a simple example. Consider the
following C code: <p>
<p>
<blockquote><pre>/* File : example.c */
double My_variable = 3.0;
/* Compute factorial of n */
int fact(int n) {
if (n &lt;= 1) return 1;
else return n*fact(n-1);
}
/* Compute n mod m */
int my_mod(int n, int m) {
return(n % m);
}
</pre></blockquote>
<p>
Suppose that you wanted to access these functions and the global
variable <tt>My_variable</tt> from Tcl. You start by making a SWIG
interface file as shown below (by convention, these files carry a .i
suffix) : <p>
<a name="n5"></a><H3>1.3.1 SWIG interface file</H3>
<blockquote><pre>
/* File : example.i */
%module example
%{
/* Put headers and other declarations here */
%}
extern double My_variable;
extern int fact(int);
extern int my_mod(int n, int m);
</pre></blockquote>
<p>
The interface file contains ANSI C function prototypes and variable
declarations. The <tt>%module</tt> directive defines the name of the
module that will be created by SWIG. The <tt>%{,%}</tt> block
provides a location for inserting additional code such as C header
files or additional C declarations. <p>
<a name="n6"></a><H3>1.3.2 The swig command</H3>
SWIG is invoked using the <tt>swig</tt> command. We can use this to
build a Tcl module (under Linux) as follows :<p>
<p>
<blockquote><pre>unix &gt; <b>swig -tcl example.i</b>
unix &gt; <b>gcc -c -fpic example.c example_wrap.c -I/usr/local/include</b>
unix &gt; <b>gcc -shared example.o example_wrap.o -o example.so</b>
unix &gt; <b>tclsh</b>
% <b>load ./example.so</b>
% <b>fact 4</b>
24
% <b>my_mod 23 7</b>
2
% <b>expr $My_variable + 4.5</b>
7.5
%
</pre></blockquote>
<p>
The <tt>swig</tt> command produced a new file called
<tt>example_wrap.c</tt> that should be compiled along with the
<tt>example.c</tt> file. Most operating systems and scripting
languages now support dynamic loading of modules. In our example, our
Tcl module has been compiled into a shared library that can be loaded
into Tcl. When loaded, Tcl can now access the functions
and variables declared in the SWIG interface. A look at the file
<tt>example_wrap.c</tt> reveals a hideous mess. However, you
almost never need to worry about it.<p>
<a name="n7"></a><H3>1.3.3 Building a Perl5 module</H3>
Now, let's turn these functions into a Perl5 module. Without making
any changes type the following (shown for Solaris):<p>
<p>
<p>
<blockquote><pre>unix &gt; <b>swig -perl5 example.i</b>
unix &gt; <b>gcc -c example.c example_wrap.c \
-I/usr/local/lib/perl5/sun4-solaris/5.003/CORE</b>
unix&gt; <b>ld -G example.o example_wrap.o -o example.so</b> # This is for Solaris
unix &gt; <b>perl5.003
use example;
print example::fact(4), "\n";
print example::my_mod(23,7), "\n";
print $example::My_variable + 4.5, "\n";
&lt;ctrl-d&gt;</b>
24
2
7.5
unix &gt;
</pre></blockquote>
<a name="n8"></a><H3>1.3.4 Building a Python module</H3>
Finally, let's build a module for Python (shown for Irix).<p>
<p>
<blockquote><pre>unix &gt; <b>swig -python example.i</b>
unix &gt; <b>gcc -c -fpic example.c example_wrap.c -I/usr/local/include/python2.0</b>
unix &gt; <b>gcc -shared example.o example_wrap.o -o _example.so</b>
unix &gt; <b>python</b>
Python 2.0 (#6, Feb 21 2001, 13:29:45)
[GCC egcs-2.91.66 19990314/Linux (egcs-1.1.2 release)] on linux2
Type "copyright", "credits" or "license" for more information.
&gt;&gt;&gt; <b>import example</b>
&gt;&gt;&gt; <b>example.fact(4)</b>
24
&gt;&gt;&gt; <b>example.my_mod(23,7)</b>
2
&gt;&gt;&gt; <b>example.cvar.My_variable + 4.5</b>
7.5
</pre></blockquote>
<a name="n9"></a><H3>1.3.5 Shortcuts</H3>
To the truly lazy programmer, one may wonder why we needed the extra
interface file at all. As it turns out, you can often do without
it. For example, you could also build a Perl5 module by just running
SWIG on the C header file and specifying a module name as follows<p>
<p>
<blockquote><pre>unix&gt; <b>swig -perl5 -module example example.h</b>
unix &gt; <b>gcc -c example.c example_wrap.c \
-I/usr/local/lib/perl5/sun4-solaris/5.003/CORE</b>
unix&gt; <b>ld -G example.o example_wrap.o -o example.so</b>
unix &gt; <b>perl5.003
use example;
print example::fact(4), "\n";
print example::my_mod(23,7), "\n";
print $example::My_variable + 4.5, "\n";
&lt;ctrl-d&gt;</b>
24
2
7.5
</pre></blockquote>
<a name="n10"></a><H3>1.3.6 Building libraries and modules</H3>
In addition to generating wrapper code, SWIG provides extensive
support for handling multiple files and building interface
libraries. For example, our <tt>example.i</tt> file, could be used in
another interface as follows :<p>
<p>
<blockquote><pre>%module foo
%include example.i // Get definitions from example.i
... Now more declarations ...
</pre></blockquote>
In a large system, an interface might be built from a variety of pieces like this :<p>
<p>
<blockquote><pre>%module package
%include network.i
%include file.i
%include graphics.i
%include objects.i
%include simulation.i
</pre></blockquote>
SWIG comes with a library of existing functions known as the SWIG
library. The library contains a mix of language independent and
language dependent functionality. For example, the file
`<tt>array.i</tt>' provides access to C arrays while the file
`<tt>wish.i</tt>' includes specialized code for rebuilding the Tcl
wish interpreter. Using the library, you can use existing modules to
build up your own personalized environment for building interfaces.
If changes are made to any of the components, they will appear
automatically the next time SWIG is run. <p>
<a name="n11"></a><H2>1.4 Supported C/C++ language features</H2>
A primary goal of the SWIG project is to make the language binding
process extremely easy. Although a few simple examples have been shown,
SWIG is quite capable in supporting most of C++. Some of the
major features include:
<ul>
<li>Full C99 preprocessing.
<li>All ANSI C and C++ datatypes.
<li>Functions, variables, and constants.
<li>Classes.
<li>Single and multiple inheritance.
<li>Overloaded functions and methods.
<li>Overloaded operators.
<li>C++ templates (including member templates, specialization, and partial specialization).
<li>Namespaces.
<li>Variable length arguments.
<li>C++ smart pointers.
</ul>
Currently, the only C++ feature not supported is nested classes--a limitation
that will be removed in a future release.
<p>
It is important to stress that SWIG is not a simplistic C++ lexing
tool like several apparently similar wrapper generation tools. SWIG
not only parses C++, it implements the full C++ type system and it is
able to understand C++ semantics. SWIG generates its wrappers with
full knowledge of this information. As a result, you will find SWIG
to be just as capable of dealing with nasty corner cases as it is in
wrapping simple C++ code. In fact, SWIG is able handle C++ code that
stresses the very limits of many C++ compilers.
<a name="n12"></a><H2>1.5 Non-intrusive interface building</H2>
When used as intended, SWIG requires minimal modification to
existing C code. This makes SWIG extremely easy to use with existing
packages and promotes software reuse and modularity. By making
the C code independent of the high level interface, you can change the
interface and reuse the code in other applications. It is also
possible to support different types of interfaces depending on the application.
<a name="n13"></a><H2>1.6 Hands off code generation</H2>
SWIG is designed to produce working code that needs no
hand-modification (in fact, if you look at the output, you probably
won't want to modify it). Ideally, SWIG should be invoked
automatically inside a Makefile just as one would call the C
compiler. You should think of your scripting language interface being
defined entirely by the input to SWIG, not the resulting output
file. While this approach may limit flexibility for hard-core hackers,
it allows others to forget about the low-level implementation
details.
<p><hr>
<address>SWIG 1.3 - Last Modified : August 10, 2002</address>
</body>
</html>

3990
SWIG/Doc/Manual/Java.html Normal file

File diff suppressed because it is too large Load diff

1346
SWIG/Doc/Manual/Library.html Normal file

File diff suppressed because it is too large Load diff

522
SWIG/Doc/Manual/Ocaml.html Normal file
View file

@ -0,0 +1,522 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>SWIG and Ocaml</title>
</head>
<body bgcolor="#ffffff">
<a name="n1"></a>
<a name="n1"></a><H1>16 SWIG and Ocaml</H1>
<!-- INDEX -->
<ul>
<li><a href="#n2">Preliminaries</a>
<ul>
<li><a href="#n3">Running SWIG</a>
<li><a href="#n4">Getting the right header files</a>
<li><a href="#n5">Compiling the code</a>
<li><a href="#n6">The camlp4 module</a>
<li><a href="#n7">Current thoughts on best practice for Ocaml</a>
<li><a href="#n8">Using your module</a>
<li><a href="#n9">Compilation problems and compiling with C++</a>
</ul>
<li><a href="#n10">The low-level Ocaml/C interface</a>
<ul>
<li><a href="#n11">The generated module</a>
<li><a href="#n12">Enums</a>
<li><a href="#n13">C++ Classes</a>
<ul>
<li><a href="#n14">C++ Class Example</a>
<li><a href="#n15">Compiling the example</a>
<li><a href="#n16">Sample Session</a>
</ul>
<li><a href="#n17">Exceptions</a>
</ul>
</ul>
<!-- INDEX -->
This chapter describes SWIG's
support of Ocaml. Ocaml is a relatively recent addition to the ML family,
and is a recent addition to SWIG. It's the second compiled, typed
language to be added. Ocaml has widely acknowledged benefits for engineers,
mostly derived from a sophistocated type system, compile-time checking
which eliminates several classes of common programming errors, and good
native performance. While all of this is wonderful, there are well-written
C and C++ libraries that Ocaml users will want to take advantage of as
part of their arsenal (such as SSL and gdbm), as well as their own mature
C and C++ code. SWIG allows this code to be used in a natural, type-safe
way with Ocaml, by providing the necessary, but repetetive glue code
which creates and uses Ocaml values to communicate with C and C++ code.
In addition, SWIG also produces the needed Ocaml source that binds
variants, functions, classes, etc.
<a name="n2"></a><H2>16.1 Preliminaries</H2>
SWIG 1.3 works with Ocaml 3.04 and above. Given the choice,
you should use the latest stable release. The SWIG Ocaml module has
been tested on Linux (m68k,MIPS,Intel) and Cygwin on Windows. The
best way to determine whether your system will work is to compile the
examples and test-suite which come with SWIG. You can do this by running
<tt>make check</tt> from the SWIG root directory after installing SWIG.
The Ocaml module has been tested using the system's dynamic linking (the
usual -lxxx against libxxx.so, but not using the explicit dynamic linking
provided by the Dl package <a
href="http://www.ocaml-programming.de/packages/documentation/dl/"> http://www.ocaml-programming.de/packages/documentation/dl/
</a>, although I suspect that it will work without a problem. If anyone
would like to evaluate this support, I will share the results here.
<a name="n3"></a><H3>16.1.1 Running SWIG</H3>
The basics of getting a SWIG Ocaml module up and running
can be seen from one of SWIG's example Makefiles, but is also described
here. To build an Ocaml module, run SWIG using the <tt>-ocaml</tt>
option.
<blockquote>
<pre>%swig -ocaml example.i</pre>
</blockquote>
<p> This will produce 3 files. The file <tt>example_wrap.c</tt> contains
all of the C code needed to build an Ocaml module. To build the module,
you will compile the file <tt>example_wrap.c</tt> with <tt>ocamlc</tt> or
<tt>ocamlopt</tt> to create the needed .o file. You will need to compile
the resulting .ml and .mli files as well, and do the final link with -custom
(not needed for native link). </p>
<a name="n4"></a><H3>16.1.2 Getting the right header files</H3>
You may need the libswigocaml.h file that comes with the
distribution to be included. It provides several useful functions
that almost all programs that use SWIG will need. It is located in
$(prefix)/include/libswigocaml.h where $(prefix) is usually /usr/local,
but could be /usr. This is set at configure time. The functions most
frequently used in here are isnull and nullptr for creating and checking
null pointers.
<a name="n5"></a><H3>16.1.3 Compiling the code</H3>
Use <tt>ocamlc</tt> or <tt>ocamlopt</tt> to compile your
SWIG interface like:
<p> </p>
<blockquote>
<pre>% ocamlc -c -ccopt "-I/usr/include/foo -I/usr/local/include" example_wrap.c<br>% ocamlc -c example.mli<br>% ocamlc -c example.ml<br></pre>
</blockquote>
<p> <tt>ocamlc</tt> is aware of .c files and knows how to handle them. Unfortunately,
it does not know about .cxx, .cc, or .cpp files, so when SWIG is invoked
in C++ mode, you must: </p>
<blockquote>
<pre>% cp example_wrap.cxx example_wrap.cxx.c<br>% ocamlc -c ... -ccopt -xc++ example_wrap.cxx.c<br>% ...<br></pre>
</blockquote>
<a name="n6"></a><H3>16.1.4 The camlp4 module</H3>
The camlp4 module (swig.ml -&gt; swig.cmo) contains a simple rewriter which
makes C++ code blend more seamlessly with objective caml code. It's use is
optional. The source file is included in the Lib/ocaml directory of the
SWIG source distribution.
<p>
The basic principle of the module is to recognize certain non-caml expressions
and convert them for use with C++ code as interfaced by SWIG. The camlp4
module is written to work with generated SWIG interfaces, and probably isn't
great to use with anything else.
<p>
Here are the main rewriting rules:
<p>
<table border="1">
<tr><th>Input</th><th>Rewritten to</th></tr>
<tr><td>f'( ... ) as in<br> atoi'("0") or<br> _exit'(0)</td>
<td>f(C_list [ ... ]) as in<br> atoi (C_list [ C_string "0" ]) or<br> _exit (C_list [ C_int 0 ])</td></tr>
<tr><td>object -> "method" ( ... )</td><td>(invoke object) "method" (C_list [ ... ])</td></tr>
<tr><td>
object <i>'binop</i> argument as in<br>
a '+= b</td>
<td>
(invoke object) "+=" argument as in<br>
(invoke a) "+=" b<td></tr>
<tr><th colspan=2>Note that because camlp4 always recognizes &lt;&lt;
and &gt;&gt;, they are replaced by lsl and lsr in operator names.
<tr><td>
<i>'unop</i> object as in</br>
'! a
</td><td>
(invoke a) "!" C_void</td></tr>
<tr><td>
<b>Smart pointer access like this</b>
object '-> "method" ( args )
</td><td>
(invoke (invoke object "->" C_void))
</td></tr>
<tr><td>
<b>Invoke syntax</b>
object . '( ... )
</td><td>
(invoke object) "()" (C_list [ ... ])
</td></tr>
<tr><td>
<b>Array syntax</b>
object '[ 10 ]
</td><td>
(invoke object) "[]" (C_int 10)
</td></tr>
</table>
<a name="n7"></a><H3>16.1.5 Current thoughts on best practice for Ocaml</H3>
Because the VC compiler (cl) needs link options specified
after all compiler options, and ocamlc doesn't really understand
that, I think that this is the best way to link ocaml code with C++
code. I formulated this method to make it easy for co-workers who
rely on MSDev to create GUIs, etc.. to live in harmony with the
ocaml parts of the application.
<p> Let's say you have ocaml sources foo.ml and bar.ml and interface frob.i;
</p>
<blockquote><pre>
swig -ocaml -c++ frob.i
ocamlc -custom -c frob.mli
ocamlc -custom -c frob.ml
cp frob_wrap.cxx frob_wrap.c
ocamlc -custom -c -I$(FROBLIB)/include frob_wrap.c
ocamlc -custom -c foo.ml
ocamlc -custom -c bar.ml
ocamlc -pack -o foobar.cmo foo.cmo bar.cmo frob.cmo
ocamlc -custom -output-obj -o foobar.obj foobar.cmo
</pre></blockquote>
<p> At this point, foobar.obj can be included in your MSVC project and
linked against other code. This is how you link it: </p>
<blockquote><pre>
link /OUT:big_program.exe \
other1.obj other2.obj foobar.obj frob_wrap.obj \
$(OCAMLLIB)/ocamlrun.lib $(FROBLIB)/lib/frob.lib
</pre></blockquote>
<a name="n8"></a><H3>16.1.6 Using your module</H3>
You can test-drive your module by building a
toplevel ocaml interpreter. Consult the ocaml manual for details.
<p>When linking any ocaml bytecode with your module, use the -custom
option to build your functions into the primitive list. This
option is not needed when you build native code.
<a name="n9"></a><H3>16.1.7 Compilation problems and compiling with C++</H3>
As mentioned above, .cxx files need special
handling to be compiled with <tt>ocamlc</tt>. Other than that, C code
that uses <tt>class</tt> as a non-keyword, and C code that is too
liberal with pointer types may not compile under the C++ compiler.
Most code meant to be compiled as C++ will not have problems.
<a name="n10"></a><H2>16.2 The low-level Ocaml/C interface</H2>
In order to provide access to overloaded functions, and
provide sensible outputs from them, all C entites are represented as
members of the c_obj type:
<p>
In the code as seen by the typemap
writer, there is a value, swig_result, that always contains the
current return data. It is a list, and must be appended with the
caml_list_append function, or with functions and macros provided by
objective caml.<br>
<blockquote><pre>
type c_obj =
C_void
| C_bool of bool
| C_char of char
| C_uchar of char
| C_short of int
| C_ushort of int
| C_int of int
| C_uint of int32
| C_int32 of int32
| C_int64 of int64
| C_float of float
| C_double of float
| C_ptr of int64 * int64
| C_array of c_obj array
| C_list of c_obj list
| C_obj of (string -&gt; c_obj -&gt; c_obj)
| C_string of string
| C_enum of c_enum_t
</pre></blockquote>
A few functions exist which generate and return these:<br>
<ul>
<li>caml_ptr_val receives a c_obj and returns a void *. &nbsp;This
should be used for all pointer purposes.</li>
<li>caml_long_val receives a c_obj and returns a long. &nbsp;This
should be used for most integral purposes.<br>
</li>
<li>caml_val_ptr receives a void * and returns a c_obj.</li>
<li>caml_val_bool receives a C int and returns a c_obj representing
it's bool value.</li>
<li>caml_val_(u)?(char|short|int|long|float|double) receives an
appropriate C value and returns a c_obj representing it.</li>
<li>caml_val_string receives a char * and returns a string value.</li>
<li>caml_val_string_len receives a char * and a length and returns
a string value.</li>
<li>caml_val_obj receives a void * and an object type and returns
a C_obj, which contains a closure giving method access.</li>
</ul>
Because of this style, a typemap can return any kind of value it
wants from a function. &nbsp;This enables out typemaps and inout typemaps
to work well. &nbsp;The one thing to remember about outputting values
is that you must append them to the return list with swig_result = caml_list_append(swig_result,v).<p>
&nbsp;This function will return a new list that has your element
appended. Upon return to caml space, the fnhelper function
beautifies the result. A list containing a single item degrades to
only that item (i.e. [ C_int 3 ] -&gt; C_int 3), and a list
containing more than one item is wrapped in C_list (i.e. [ C_char
'a' ; C_char 'b' -&gt; C_list [ C_char 'a' ; C_char b
]). &nbsp;This is in order to make return values easier to handle
when functions have only one return value, such as constructors,
and operators. &nbsp;In addition, string, pointer, and object
values are interchangable with respect to caml_ptr_val, so you can
allocate memory as caml strings and still use the resulting
pointers for C purposes, even using them to construct simple objects
on. Note, though, that foreign C++ code does not respect the garbage
collector, although the SWIG interface does.<p>
The wild card type that you can use in lots of different ways is
C_obj. It allows you to wrap any type of thing you like as an
object using the same mechanism that the ocaml module
does. &nbsp;When evaluated in caml_ptr_val, the returned value is
the result of a call to the object's "&" operator, taken as a pointer.
<p>
You should only construct values using objective caml, or using the
functions caml_val_* functions provided as static functions to a SWIG
ocaml module, as well as the caml_list_* functions. These functions
provide everything a typemap needs to produce values. In addition,
value items pass through directly, but you must make your own type
signature for a function that uses value in this way.
<a name="n11"></a><H3>16.2.1 The generated module</H3>
The SWIG <tt>%module</tt> directive specifies the name of the Ocaml
module to be generated. If you specified `<tt>%module example</tt>',
then your Ocaml code will be accessible in the module Example. The
module name is always capitalized as is the ocaml convention. Note
that you must not use any Ocaml keyword to name your module. Remember
that the keywords are not the same as the C++ ones. <p>
You can introduce extra code into the output wherever you like with SWIG.
These are the places you can introduce code:
<table border="1">
<tr><td>"header"</td><td>This code is inserted near the beginning of the
C wrapper file, before any function definitions.</td></tr>
<tr><td>"wrapper"</td><td>This code is inserted in the function definition
section.</td></tr>
<tr><td>"runtime"</td><td>This code is inserted near the end of the C wrapper
file.</td></tr>
<tr><td>"mli"</td><td>This code is inserted into the caml interface file.
Special signatures should be inserted here.
</td></tr>
<tr><td>"ml"</td><td>This code is inserted in the caml code defining the
interface to your C code. Special caml code, as well as any initialization
which should run when the module is loaded may be inserted here.
</td></tr>
</table>
<a name="n12"></a><H3>16.2.2 Enums</H3>
SWIG will wrap enumerations as polymorphic variants in the output
Ocaml code, as above in C_enum.&nbsp; In order to support all
C++-style uses of enums, the function int_to_enum and enum_to_int are
provided for ocaml code to produce and consume these values as
integers. &nbsp;Other than that, correct uses of enums will not have
a problem. &nbsp;Since enum labels may overlap between enums, the
enum_to_int and int_to_enum functions take an enum type label as an
argument. Example:
<p>
<blockquote><pre>
%module enum_test
%{
enum c_enum_type { a = 1, b, c = 4, d = 8 };
%}
enum c_enum_type { a = 1, b, c = 4, d = 8 };
</pre></blockquote>
<p>
The output mli contains:
<p>
<blockquote><pre>
type c_enum_type = [
`unknown
| `c_enum_type
]
type c_enum_tag = [
`int of int
| `a
| `b
| `c
| `d
]
val int_to_enum c_enum_type -&gt; int -&gt; c_obj
val enum_to_int c_enum_type -&gt; c_obj -&gt; c_obj
</pre>
</blockquote>
So it's possible to do this:
<blockquote>
<pre>bash-2.05a$ ocamlmktop -custom enum_test_wrap.o enum_test.cmo -o enum_test_top
bash-2.05a$ ./enum_test_top
Objective Caml version 3.04
# open Enum_test ;;
# let x = C_enum `a ;;
val x : Enum_test.c_obj = C_enum `a
# enum_to_int `c_enum_type x ;;
- : Enum_test.c_obj = C_int 1
# int_to_enum `c_enum_type 4 ;;
- : Enum_test.c_obj = C_enum `c
</pre>
</blockquote>
<p> </p>
<a name="n13"></a><H3>16.2.3 C++ Classes</H3>
C++ classes, along with structs and unions are represented by C_obj
(string -&gt; c_obj -&gt; c_obj) wrapped closures. &nbsp;These objects
contain a method list, and a type, which allow them to be used like
C++ objects. When passed into typemaps that use pointers, they
degrade to pointers through their "&amp;" method. &nbsp;Every method
an object has is represented as a string in the object's method table,
and each method table exists in memory only once. &nbsp;In addition
to any other operators an object might have, certain builtin ones are
provided by SWIG: (all of these take no arguments (C_void))
<table>
<tr><td>"~"</td><td>Delete this object</td></tr>
<tr><td>"&amp;"</td><td>Return an ordinary C_ptr value representing this
object's address</td></tr>
<tr><td>":methods"</td><td>Returns a list of strings containing the names of
the methods this object contains</td></tr>
<tr><td>":classof"</td><td>Returns the name of the class this object belongs
to.</td></tr>
<tr><td>":parents"</td><td>Returns a list of all direct parent classes which
have been wrapped by SWIG.</td></tr>
<tr><td>"::[parent-class]"</td><td>Returns a view of the object as the
indicated parent class. This is mainly used internally by the SWIG module,
but may be useful to client programs.</td></tr>
<tr><td>"[member-variable]"</td><td>Each member variable is wrapped as a
method with an optional parameter.
Called with one argument, the member variable is set to the value of the
argument. With zero arguments, the value is returned.
</td></tr>
</table>
Note that this string belongs to the wrapper object, and not
the underlying pointer, so using create_[x]_from_ptr alters the
returned value for the same object.
<p>
<a name="n14"></a><H4>16.2.3.1 C++ Class Example</H4>
Here's a simple example using Trolltech's Qt Library:
<table border="1" bgcolor="#dddddd"><tr><th><center>qt.i</center></th></tr>
<tr><td><pre>
%module qt
%{
#include &lt;qapplication.h&gt;
#include &lt;qpushbutton.h&gt;
%}
class QApplication {
public:
QApplication( int argc, char **argv );
void setMainWidget( QWidget *widget );
void exec();
};
class QPushButton {
public:
QPushButton( char *str, QWidget *w );
void resize( int x, int y );
void show();
};
</pre></td></tr></table><p>
<a name="n15"></a><H4>16.2.3.2 Compiling the example</H4>
<blockquote><pre>
bash-2.05a$ QTPATH=/your/qt/path
bash-2.05a$ swig -ocaml -c++ -I$QTPATH/include qt.i
bash-2.05a$ mv qt_wrap.cxx qt_wrap.c
bash-2.05a$ ocamlc -c -ccopt -xc++ -ccopt -g -g -ccopt -I$QTPATH/include qt_wrap.c
bash-2.05a$ ocamlc -c qt.mli
bash-2.05a$ ocamlc -c qt.ml
bash-2.05a$ ocamlmktop -custom qt_wrap.o qt.cmo -o qt_top -cclib -L$QTPATH/lib -cclib -lqt
</pre></blockquote>
<a name="n16"></a><H4>16.2.3.3 Sample Session</H4>
<blockquote><pre>
bash-2.05a$ ./qt_top
Objective Caml version 3.06
# open Qt ;;
# let a = new_QApplication (C_list [ C_int 0; C_int 0 ]) ;;
val a : Qt.c_obj = C_obj <fun>
# let hello = new_QPushButton (C_list [ C_string "hi" ; C_int 0 ]) ;;
val hello : Qt.c_obj = C_obj <fun>
# (invoke hello) "resize" (C_list [ C_int 100 ; C_int 30 ]) ;;
- : Qt.c_obj = C_void
# (invoke hello) "show" C_void ;;
- : Qt.c_obj = C_void
# (invoke a) "exec" C_void ;;
</pre></blockquote><p>
Or with the camlp4 module:
<blockquote><pre>
bash-2.05a$ ./qt_top
Objective Caml version 3.06
# #load "camlp4o.cma" ;;
Camlp4 Parsing version 3.06
# #load "./swig.cmo" ;;
# open Qt ;;
# let a = new_QApplication '(0,0) ;;
val a : Qt.c_obj = C_obj <fun>
# let hello = new_QPushButton '("hi",0) ;;
val hello : Qt.c_obj = C_obj <fun>
# hello -> "resize" (100,30) ;;
- : Qt.c_obj = C_void
# hello -> "show" () ;;
- : Qt.c_obj = C_void
# a -> "exec" () ;;
</pre></blockquote><p>
In either case, assuming you have a working installation of QT, you will
see a window containing the string "hi" in a button.
<a name="n17"></a><H3>16.2.4 Exceptions</H3>
Catching exceptions is now supported using SWIG's %exception feature. A simple
but not too useful example is provided by the throw_exception testcase in
Examples/test-suite. You can provide your own exceptions, too.
</body>
</html>

Some files were not shown because too many files have changed in this diff Show more