- •Preface
- •Introduction
- •SWIG resources
- •About this manual
- •Prerequisites
- •Organization of this manual
- •How to avoid reading the manual
- •Credits
- •What’s new?
- •Bug reports
- •SWIG is free
- •Introduction
- •What is SWIG?
- •Life before SWIG
- •Life after SWIG
- •The SWIG package
- •A SWIG example
- •The swig command
- •Building a Perl5 module
- •Building a Python module
- •Shortcuts
- •Documentation generation
- •Building libraries and modules
- •C syntax, but not a C compiler
- •Non-intrusive interface building
- •Hands off code generation
- •Event driven C programming
- •Automatic documentation generation
- •Summary
- •SWIG for Windows and Macintosh
- •SWIG on Windows 95/NT
- •SWIG on the Power Macintosh
- •Cross platform woes
- •How to survive this manual
- •Scripting Languages
- •The two language view of the world
- •How does a scripting language talk to C?
- •Wrapper functions
- •Variable linking
- •Constants
- •Structures and classes
- •Shadow classes
- •Building scripting language extensions
- •Static linking
- •Shared libraries and dynamic loading
- •Linking with shared libraries
- •SWIG Basics
- •Running SWIG
- •Input format
- •SWIG Output
- •Comments
- •C Preprocessor directives
- •SWIG Directives
- •Simple C functions, variables, and constants
- •Integers
- •Floating Point
- •Character Strings
- •Variables
- •Constants
- •Pointers and complex objects
- •Simple pointers
- •Run time pointer type checking
- •Derived types, structs, and classes
- •Typedef
- •Getting down to business
- •Passing complex datatypes by value
- •Return by value
- •Linking to complex variables
- •Arrays
- •Creating read-only variables
- •Renaming declarations
- •Overriding call by reference
- •Default/optional arguments
- •Pointers to functions
- •Typedef and structures
- •Character strings and structures
- •Array members
- •C constructors and destructors
- •Adding member functions to C structures
- •Nested structures
- •Other things to note about structures
- •C++ support
- •Supported C++ features
- •C++ example
- •Constructors and destructors
- •Member functions
- •Static members
- •Member data
- •Protection
- •Enums and constants
- •References
- •Inheritance
- •Templates
- •Renaming
- •Adding new methods
- •SWIG, C++, and the Legislation of Morality
- •The future of C++ and SWIG
- •Objective-C
- •Objective-C Example
- •Constructors and destructors
- •Instance methods
- •Class methods
- •Member data
- •Protection
- •Inheritance
- •Referring to other classes
- •Categories
- •Implementations and Protocols
- •Renaming
- •Adding new methods
- •Other issues
- •Conditional compilation
- •The #if directive
- •Code Insertion
- •The output of SWIG
- •Code blocks
- •Inlined code blocks
- •Initialization blocks
- •Wrapper code blocks
- •A general interface building strategy
- •Preparing a C program for SWIG
- •What to do with main()
- •Working with the C preprocessor
- •How to cope with C++
- •How to avoid creating the interface from hell
- •Multiple files and the SWIG library
- •The %include directive
- •The %extern directive
- •The %import directive
- •The SWIG library
- •Library example
- •Creating Library Files
- •tclsh.i
- •malloc.i
- •Static initialization of multiple modules
- •More about the SWIG library
- •Documentation System
- •Introduction
- •How it works
- •Choosing a documentation format
- •Function usage and argument names
- •Titles, sections, and subsections
- •Formatting
- •Default Formatting
- •Comment Formatting variables
- •Sorting
- •Comment placement and formatting
- •Tabs and other annoyances
- •Ignoring comments
- •C Information
- •Adding Additional Text
- •Disabling all documentation
- •An Example
- •ASCII Documentation
- •HTML Documentation
- •LaTeX Documentation
- •C++ Support
- •The Final Word?
- •Pointers, Constraints, and Typemaps
- •Introduction
- •The SWIG Pointer Library
- •Pointer Library Functions
- •A simple example
- •Creating arrays
- •Packing a data structure
- •Introduction to typemaps
- •The idea (in a nutshell)
- •Using some typemaps
- •Managing input and output parameters
- •Input Methods
- •Output Methods
- •Input/Output Methods
- •Using different names
- •Applying constraints to input values
- •Simple constraint example
- •Constraint methods
- •Applying constraints to new datatypes
- •Writing new typemaps
- •Motivations for using typemaps
- •Managing special data-types with helper functions
- •A Typemap Implementation
- •What is a typemap?
- •Creating a new typemap
- •Deleting a typemap
- •Copying a typemap
- •Typemap matching rules
- •Common typemap methods
- •Writing typemap code
- •Scope
- •Creating local variables
- •Special variables
- •Typemaps for handling arrays
- •Typemaps and the SWIG Library
- •Implementing constraints with typemaps
- •Typemap examples
- •How to break everything with a typemap
- •Typemaps and the future
- •Exception Handling
- •The %except directive
- •Handling exceptions in C code
- •Exception handling with longjmp()
- •Handling C++ exceptions
- •Using The SWIG exception library
- •Debugging and other interesting uses for %except
- •More Examples
- •SWIG and Perl5
- •Preliminaries
- •Running SWIG
- •Compiling a dynamic module
- •Building a dynamic module with MakeMaker
- •Building a static version of Perl
- •Compilation problems and compiling with C++
- •Building Perl Extensions under Windows 95/NT
- •Running SWIG from Developer Studio
- •Using NMAKE
- •Modules, packages, and classes
- •Basic Perl interface
- •Functions
- •Global variables
- •Constants
- •Pointers
- •Structures and C++ classes
- •A simple Perl example
- •Graphs
- •Sample Perl Script
- •Accessing arrays and other strange objects
- •Implementing methods in Perl
- •Shadow classes
- •Getting serious
- •Wrapping C libraries and other packages
- •Building a Perl5 interface to MATLAB
- •The MATLAB engine interface
- •Wrapping the MATLAB matrix functions
- •Putting it all together
- •Graphical Web-Statistics in Perl5
- •Handling output values (the easy way)
- •Exception handling
- •Remapping datatypes with typemaps
- •A simple typemap example
- •Perl5 typemaps
- •Typemap variables
- •Name based type conversion
- •Converting a Perl5 array to a char **
- •Using typemaps to return values
- •Accessing array structure members
- •Turning Perl references into C pointers
- •Useful functions
- •Standard typemaps
- •Pointer handling
- •Return values
- •The gory details on shadow classes
- •Module and package names
- •What gets created?
- •Object Ownership
- •Nested Objects
- •Shadow Functions
- •Inheritance
- •Iterators
- •Where to go from here?
- •SWIG and Python
- •Preliminaries
- •Running SWIG
- •Compiling a dynamic module
- •Using your module
- •Compilation problems and compiling with C++
- •Building Python Extensions under Windows 95/NT
- •Running SWIG from Developer Studio
- •Using NMAKE
- •The low-level Python/C interface
- •Modules
- •Functions
- •Variable Linking
- •Constants
- •Pointers
- •Structures
- •C++ Classes
- •Python shadow classes
- •A simple example
- •Why write shadow classes in Python?
- •Automated shadow class generation
- •Compiling modules with shadow classes
- •Where to go for more information
- •About the Examples
- •Solving a simple heat-equation
- •The C++ code
- •Making a quick and dirty Python module
- •Using our new module
- •Accessing array data
- •Use Python for control, C for performance
- •Getting even more serious about array access
- •Implementing special Python methods in C
- •Summary (so far)
- •Wrapping a C library
- •Preparing a module
- •Using the gd module
- •Building a simple 2D imaging class
- •A mathematical function plotter
- •Plotting an unstructured mesh
- •From C to SWIG to Python
- •Putting it all together
- •Merging modules
- •Using dynamic loading
- •Use static linking
- •Building large multi-module systems
- •A complete application
- •Exception handling
- •Remapping C datatypes with typemaps
- •What is a typemap?
- •Python typemaps
- •Typemap variables
- •Name based type conversion
- •Converting Python list to a char **
- •Using typemaps to return arguments
- •Mapping Python tuples into small arrays
- •Accessing array structure members
- •Useful Functions
- •Standard typemaps
- •Pointer handling
- •Implementing C callback functions in Python
- •Other odds and ends
- •Adding native Python functions to a SWIG module
- •The gory details of shadow classes
- •A simple shadow class
- •Module names
- •Two classes
- •The this pointer
- •Object ownership
- •Constructors and Destructors
- •Member data
- •Printing
- •Shadow Functions
- •Nested objects
- •Inheritance and shadow classes
- •Methods that return new objects
- •Performance concerns and hints
- •SWIG and Tcl
- •Preliminaries
- •Running SWIG
- •Additional SWIG options
- •Compiling a dynamic module (Unix)
- •Using a dynamic module
- •Static linking
- •Compilation problems
- •Using [incr Tcl] namespaces
- •Building Tcl/Tk Extensions under Windows 95/NT
- •Running SWIG from Developer Studio
- •Using NMAKE
- •Basic Tcl Interface
- •Functions
- •Global variables
- •Constants
- •Pointers
- •Structures
- •C++ Classes
- •The object oriented interface
- •Creating new objects
- •Invoking member functions
- •Deleting objects
- •Accessing member data
- •Changing member data
- •Relationship with pointers
- •About the examples
- •Binary trees in Tcl
- •Making a quick a dirty Tcl module
- •Building a C data structure in Tcl
- •Implementing methods in C
- •Building an object oriented C interface
- •Building C/C++ data structures with Tk
- •Accessing arrays
- •Building a simple OpenGL module
- •Wrapping gl.h
- •Wrapping glu.h
- •Wrapping the aux library
- •A few helper functions
- •An OpenGL package
- •Using the OpenGL module
- •Problems with the OpenGL interface
- •Exception handling
- •Typemaps
- •What is a typemap?
- •Tcl typemaps
- •Typemap variables
- •Name based type conversion
- •Converting a Tcl list to a char **
- •Remapping constants
- •Returning values in arguments
- •Mapping C structures into Tcl Lists
- •Useful functions
- •Standard typemaps
- •Pointer handling
- •Writing a main program and Tcl_AppInit()
- •Creating a new package initialization library
- •Combining Tcl/Tk Extensions
- •Limitations to this approach
- •Dynamic loading
- •Turning a SWIG module into a Tcl Package.
- •Building new kinds of Tcl interfaces (in Tcl)
- •Shadow classes
- •Extending the Tcl Netscape Plugin
- •Using the plugin
- •Tcl8.0 features
- •Advanced Topics
- •Creating multi-module packages
- •Runtime support (and potential problems)
- •Why doesn’t C++ inheritance work between modules?
- •The SWIG runtime library
- •A few dynamic loading gotchas
- •Dynamic Loading of C++ modules
- •Inside the SWIG type-checker
- •Type equivalence
- •Type casting
- •Why a name based approach?
- •Performance of the type-checker
- •Extending SWIG
- •Introduction
- •Prerequisites
- •SWIG Organization
- •The organization of this chapter
- •Compiling a SWIG extension
- •Required C++ compiler
- •Writing a main program
- •Compiling
- •SWIG output
- •The Language class (simple version)
- •A tour of SWIG datatypes
- •The DataType class
- •Function Parameters
- •The String Class
- •Hash Tables
- •The WrapperFunction class
- •Typemaps (from C)
- •The typemap C API.
- •What happens on typemap lookup?
- •How many typemaps are there?
- •File management
- •Naming Services
- •Code Generation Functions
- •Writing a Real Language Module
- •Command Line Options and Basic Initialization
- •Starting the parser
- •Emitting headers and support code
- •Setting a module name
- •Final Initialization
- •Cleanup
- •Creating Commands
- •Creating a Wrapper Function
- •Manipulating Global Variables
- •Constants
- •A Quick Intermission
- •Writing the default typemaps
- •The SWIG library and installation issues
- •C++ Processing
- •How C++ processing works
- •Language extensions
- •Hints
- •Documentation Processing
- •Documentation entries
- •Creating a usage string
- •Writing a new documentation module
- •Using a new documentation module
- •Where to go for more information
- •The Future of SWIG
- •Index
SWIG Users Guide |
Documentation System |
79 |
|
|
|
The chopping parameters can be used to strip out the text of block comments. For example, using chop_left=3, chop_top=1, chop_bottom=1 on the above comment produces the following output :
Plot2D_line x1 y1 x2 y2 color [ returns void ]
void Plot2D_line(int x1, int y1, int x2, int y2, Pixel color)
Draws a line between the points (x1,y1) and (x2,y2) using the the given color. The line is cropped to fit in the current bounding box.
Uses the Bresenham line drawing algorithm.
The chopping parameters only apply if a comment is sufficiently large (i.e.. if the number of lines exceed chop_top+chop_bottom). Thus, in our example, a one line comment will be unaltered even though chopping has been set. By default, SWIG sets chop_left=3 and all others to zero. This setting removes the ‘/* ‘ or ‘// ‘ preceeding a comment.
Tabs and other annoyances
When using the preformatted mode, SWIG will automatically convert tabs to white space. This is done assuming that tabs are placed every 8 characters. The tabification mode can be selected using the ‘tabify’ and ‘untabify’ parameters :
%section “Untabified Section”,untabify %section “Leave those tabs alone”, tabify
Tabs are simply ignored when comments are reformatted (well, actually, they’re just copied into the output, but the target documentation method will ignore them).
Ignoring comments
To ignore the comments in a particular section, you can use the ‘ignore’ parameter. For example :
%section “No Comments”, ignore %section “Keep Comments”, keep
The ‘keep’ parameter is used to disable the effect of an ignore parameter (if set by a section’s parent).
C Information
Normally, each declaration in a file will have a C information tag attached to it. This is usually enclosed in [ ] and contains the return type of a function along with other information. This text can disabled using the ‘noinfo’ parameters and reenabled using the ‘info’ parameter.
%section “No C Information”, noinfo %section “Print C Information”, info
Adding Additional Text
Additional documentation text can be added using the %text directive as shown :
Version 1.1, June 24, 1997
SWIG Users Guide |
Documentation System |
80 |
|
|
|
%text %{
This is some additional documentation text.
%}
The %text directive is primarily used to add text that is not associated with any particular declaration. For example, you may want to provide a general description of a module before defining all of the functions. Any text can be placed inside the %{,%} block except for a ‘%}’ that ends the block. For the purposes of sorting, text segments will always appear immediately after the previous declaration.
Disabling all documentation
All documentation can be suppressed for a portion of an interface file by using the %disabledoc and %enabledoc directives. These would be used as follows:
%disabledoc
... A a bunch of declarations with no documentation ...
%enabledoc
... Now declarations are documented again ...
These directives can be safely nested. Thus, the occurrence of these directives inside a %disabledoc section has no effect (only the outer-most occurrence is important).
The primary use of these directives is for disabling the documentation on commonly used modules that you might use repeatedly (but don’t want any documentation for). For example :
%disabledoc %include wish.i %include array.i %include timer.i %enabledoc
An Example
To illustrate the documentation system in action, here is some code from the SWIG library file ‘array.i’.
//
//array.i
//This SWIG library file provides access to C arrays.
%module carray
%section "SWIG C Array Module",info,after,pre,nosort,skip=1,chop_left=3, chop_right=0,chop_top=0,chop_bottom=0
%text %{ %include array.i
Version 1.1, June 24, 1997
SWIG Users Guide |
Documentation System |
81 |
|
|
|
This module provides scripting language access to various kinds of C/C++ arrays. For each datatype, a collection of four functions are created :
<type>_array(size) |
: |
Create a new array of given size |
<type>_get(array, index) |
: |
Get an element from the array |
<type>_set(array, index, value) : |
Set an element in the array |
|
<type>_destroy(array) |
: |
Destroy an array |
The functions in this library are only low-level accessor functions designed to directly access C arrays. Like C, no bounds checking is performed so use at your own peril.
%}
// -----------------------------------------------------------------------
// Integer array support
// -----------------------------------------------------------------------
%subsection "Integer Arrays"
/* The following functions provide access to integer arrays (mapped onto the C 'int' datatype. */
%{
... Supporting C code ...
%}
int *int_array(int nitems);
/* Creates a new array of integers. nitems specifies the number of elements. The array is created using malloc() in C and new() in C++. */
void int_destroy(int *array); /* Destroys the given array. */
int int_get(int *array, int index);
/* Returns the value of array[index]. */
int int_set(int *array, int index, int value); /* Sets array[index] = value. Returns value. */
// -----------------------------------------------------------------------
// Floating point
// -----------------------------------------------------------------------
%subsection "Floating Point Arrays"
/* The following functions provide access to arrays of floats and doubles. */
%{
.. Supporting C code ...
%}
double *double_array(int nitems);
/* Creates a new array of doubles. nitems specifies the number of elements. The array is created using malloc() in C and new() in C++. */
void double_destroy(double *array); /* Destroys the given array. */
double double_get(double *array, int index); /* Returns the value of array[index]. */
double double_set(double *array, int index, double value);
Version 1.1, June 24, 1997
SWIG Users Guide |
Documentation System |
82 |
|
|
|
/* Sets array[index] = value. Returns value. */
float *float_array(int nitems);
/* Creates a new array of floats. nitems specifies the number of elements. The array is created using malloc() in C and new() in C++. */
void float_destroy(float *array); /* Destroys the given array. */
float float_get(float *array, int index); /* Returns the value of array[index]. */
float float_set(float *array, int index, float value); /* Sets array[index] = value. Returns value. */
//-----------------------------------------------------------------------
//Character strings
//-----------------------------------------------------------------------
%subsection "String Arrays"
%text %{
The following functions provide support for the 'char **' datatype. This is primarily used to handle argument lists and other similar structures that need to be passed to a C/C++ function.
%}
#if defined(SWIGTCL) %text %{
To convert from a Tcl list into a 'char **', the following code can be used :
# $list is a list
set args [string_array expr {[llength $list] + 1}] set i 0
foreach a $list { string_set $args $i $a incr i 1
}
string_set $i ""
# $args is now a char ** type
%}
#elif defined(SWIGPERL)
%text %{
To convert from a Perl list into a 'char **', code similar to the following can be used :
# @list is a list
my $l = scalar(@list);
my $args = string_array($l+1); my $i = 0;
foreach $arg (@list) { string_set($args,$i,$arg); $i++;
}
string_set($args,$i,"");
(of course, there is always more than one way to do it) %}
Version 1.1, June 24, 1997
SWIG Users Guide |
Documentation System |
83 |
|
|
|
#elif defined(SWIGPYTHON)
%text %{
To convert from a Python list to a 'char **', code similar to the following can be used :
# 'list' is a list
args = string_array(len(list)+1) for i in range(0,len(list)):
string_set(args,i,list[i]) string_set(args,len(list),"")
%}
#endif
%{
... Supporting C code ...
%}
char **string_array(int nitems);
/* Creates a new array of strings. nitems specifies the number of elements. The array is created using malloc() in C and new() in C++. Each element of the array is set to NULL upon initialization. */
void string_destroy(char *array);
/* Destroys the given array. Each element of the array is assumed to be a NULL-terminated string allocated with malloc() or new(). All of these strings will be destroyed as well. (It is probably only safe to use this function on an array created by string_array) */
char *string_get(char **array, int index);
/* Returns the value of array[index]. Returns a string of zero length if the corresponding element is NULL. */
char *string_set(char **array, int index, char *value);
/* Sets array[index] = value. value is assumed to be a NULL-terminated string. A string of zero length is mapped into a NULL value. When setting the value, the value will be copied into a new string allocated with malloc() or new(). Any previous value in the array will be destroyed. */
In this file, all of the declarations are placed into a new section. We specify formatting information for our section. Since this is a general purpose library file, we have no idea what formatting our parent might be using so an explicit declaration makes sure we get it right. Each comment contains preformatted text describing each function. Finally, in the case of the string functions, we are using a combination of conditional compilation and documentation system directives to produce language-specific documentation. In this case, the documentation contains a usage example in the target scripting language.
When processed through the ASCII module, this file will produce documentation similar to the following :
7. SWIG C Array Module
=======================
%include array.i
Version 1.1, June 24, 1997
SWIG Users Guide |
Documentation System |
84 |
|
|
|
This module provides scripting language access to various kinds of C/C++ arrays. For each datatype, a collection of four functions are created :
<type>_array(size) |
: |
Create a new array of given size |
<type>_get(array, index) |
: |
Get an element from the array |
<type>_set(array, index, value) : |
Set an element in the array |
|
<type>_destroy(array) |
: |
Destroy an array |
The functions in this library are only low-level accessor functions designed to directly access C arrays. Like C, no bounds checking is performed so use at your own peril.
7.1. Integer Arrays
--------------------
The following functions provide access to integer arrays (mapped onto the C 'int' datatype.
int_array(nitems)
[ returns int * ]
Creates a new array of integers. nitems specifies the number of elements. The array is created using malloc() in C and new() in C++.
int_destroy(array)
[ returns void ] Destroys the given array.
int_get(array,index)
[ returns int ]
Returns the value of array[index].
int_set(array,index,value) [ returns int ]
Sets array[index] = value. Returns value.
7.2. Floating Point Arrays
---------------------------
The following functions provide access to arrays of floats and doubles.
double_array(nitems)
[ returns double * ]
Creates a new array of doubles. nitems specifies the number of elements. The array is created using malloc() in C and new() in C++.
double_destroy(array)
[ returns void ] Destroys the given array.
double_get(array,index)
[ returns double ]
Returns the value of array[index].
double_set(array,index,value) [ returns double ]
Sets array[index] = value. Returns value.
float_array(nitems)
[ returns float * ]
Version 1.1, June 24, 1997
SWIG Users Guide |
Documentation System |
85 |
|
|
|
Creates a new array of floats. nitems specifies the number of elements.
The array is created using malloc() in C and new() in C++.
float_destroy(array)
[ returns void ] Destroys the given array.
float_get(array,index)
[ returns float ]
Returns the value of array[index].
float_set(array,index,value) [ returns float ]
Sets array[index] = value. Returns value.
7.3. String Arrays
-------------------
The following functions provide support for the 'char **' datatype. This is primarily used to handle argument lists and other similar structures that need to be passed to a C/C++ function.
To convert from a Python list to a 'char **', code similar to the following can be used :
# 'list' is a list
args = string_array(len(list)+1) for i in range(0,len(list)):
string_set(args,i,list[i]) string_set(args,len(list),"")
string_array(nitems)
[ returns char ** ]
Creates a new array of strings. nitems specifies the number of elements. The array is created using malloc() in C and new() in C++. Each element of the array is set to NULL upon initialization.
string_destroy(array)
[ returns void ]
Destroys the given array. Each element of the array is assumed to be a NULL-terminated string allocated with malloc() or new(). All of these strings will be destroyed as well. (It is probably only safe to use this function on an array created by string_array)
string_get(array,index)
[ returns char * ]
Returns the value of array[index]. Returns a string of zero length if the corresponding element is NULL.
string_set(array,index,value) [ returns char * ]
Sets array[index] = value. value is assumed to be a NULL-terminated string. A string of zero length is mapped into a NULL value. When setting the value, the value will be copied into a new string allocated with malloc() or new(). Any previous value in the array will be destroyed.
Version 1.1, June 24, 1997