- •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 |
SWIG and Tcl |
226 |
|
|
|
$l insert Part |
|
|
List_print $l |
|
# Call static method (uses pointer value as before). |
Performance concerns and disabling the object oriented interface
The object oriented interface is mainly provided for ease of programming at the expense of introducing more overhead and increased code size (C code that is). If you are concerned about these issues use the basic SWIG interface instead. It provides direct access and is much faster. As it turns out, it is possible to build an object oriented interface directly in Tcl as well--an example we’ll return to a little later.
To disable the object oriented interface, run SWIG with the -noobject option. This will strip out all of the extra code and produce only the low-level interface.
About the examples
The next few sections cover Tcl examples of varying complexity. These are primarily designed to illustrate how SWIG can be used to integrate C/C++ and Tcl in a variety of ways. Some of the things that will be covered are :
•Controlling C programs with Tcl
•Building C data structures in Tcl.
•Use of C objects with Tk
•Wrapping a C library (OpenGL in this case)
•Accessing arrays and other common data structures
•Using Tcl to build new Tcl interfaces to C programs.
•Modifying SWIG’s handling of datatypes.
•And a bunch of other cool stuff.
Binary trees in Tcl
In this example, we show Tcl can be used to manipulate binary trees implemented in C. This will involve accessing C data structures and functions.
C files
We will build trees using the following C header file :
/* tree.h */ |
|
|
typedef struct Node Node; |
|
|
struct Node { |
|
|
char |
*key; |
|
char |
*value; |
|
Node |
*left; |
|
Node |
*right; |
|
}; |
|
|
typedef struct Tree { |
|
|
Node |
*head; |
/* Starting node */ |
Node |
*z; |
/* Ending node (at leaves) */ |
} Tree; |
|
|
Version 1.1, June 24, 1997
SWIG Users Guide |
SWIG and Tcl |
227 |
|
|
|
extern Node *new_Node(char *key, char *value); extern Tree *new_Tree();
The C functions to create new nodes and trees are as follows :
/* File : tree.c */ #include <string.h> #include “tree.h”
Node *new_Node(char *key, char *value) { Node *n;
n = (Node *) malloc(sizeof(Node)); n->key = (char *) malloc(strlen(key)+1);
n->value = (char *) malloc(strlen(value)+1); strcpy(n->key,key);
strcpy(n->value,value); n->left = 0;
n->right = 0; return n;
};
Tree *new_Tree() { Tree *t;
t = (Tree *) malloc(sizeof(Tree)); t->head = new_Node(““,”__head__”); t->z = new_Node(“__end__”,”__end__”); t->head->right = t->z;
t->z->left = t->z; t->z->right = t->z; return t;
}
Making a quick a dirty Tcl module
To make a quick Tcl module with these functions, we can do the following :
// file : tree.i |
|
%module tree |
|
%{ |
|
#include “tree.h” |
|
%} |
|
%include tree.h |
// Just grab header file since it’s fairly simple |
To build the module, run SWIG as follows and compile the resulting output :
%swig -tcl -ltclsh.i tree.i
%gcc tree.c tree_wrap.c -I/usr/local/include -L/usr/local/lib -ltcl -lm -o my_tclsh
We can now try out the module interactively by just running the new ‘my_tclsh’ executable.
unix > my_tclsh |
|
% set t [new_Tree] |
# Create a new tree |
_8053198_Tree_p |
|
% set n [Tree_head_get $t] |
# Get first node |
_80531a8_Node_p |
|
% puts [Node_value_get $n] |
# Get its value |
__head__ |
|
% Node -this $n |
|
Version 1.1, June 24, 1997
SWIG Users Guide |
SWIG and Tcl |
228 |
|
|
|
% $n cget -value |
# Altenative method for getting value |
|
__head__ |
|
|
Building a C data structure in Tcl
Given our simple Tcl interface, it is easy to write Tcl functions for building up a C binary tree. For example :
# Insert an item into a tree
proc insert_tree {tree key value} { set tree_head [Tree_head_get $tree] set tree_z [Tree_z_get $tree]
set p $tree_head
set x [Node_right_get $tree_head]
while {[Node_key_get $x] != “__end__”} { set p $x
if {$key < [Node_key_get $x]} { set x [Node_left_get $x]
} {
set x [Node_right_get $x]
}
}
set x [new_Node $key $value] if {$key < [Node_key_get $p]} {
Node_left_set $p $x
} {
Node_right_set $p $x
}
Node_left_set $x $tree_z
Node_right_set $x $tree_z
}
# Search tree and return all matches proc search_tree {tree key} {
set tree_head [Tree_head_get $tree] set tree_z [Tree_z_get $tree]
set found {}
set x [Node_right_get $tree_head]
while {[Node_key_get $x] != "__end__"} { if {[Node_key_get $x] == $key} {
lappend found [Node_value_get $x]
}
if {$key < [Node_key_get $x]} { set x [Node_left_get $x]
} {
set x [Node_right_get $x]
}
}
return $found
}
While written in Tcl, these functions are building up a real C binary tree data structure that could be passed into other C function. For example, we could write a function that globs an entire directory and builds a tree structure as follows :
# Insert all of the files in pathname into a binary tree
Version 1.1, June 24, 1997
SWIG Users Guide |
SWIG and Tcl |
229 |
|
|
|
proc build_dir_tree {tree pathname} {
set error [catch {set filelist [glob -nocomplain $pathname/*]}] if {$error == 0} {
foreach f $filelist {
if {[file isdirectory $f] == 1} { insert_tree $tree [file tail $f] $f
if {[file type $f] != "link"} {build_dir_tree $tree $f}
} {
insert_tree $tree [file tail $f] $f
}
}
}
}
We can test out our function interactively as follows :
% source tree.tcl
% set t [new_Tree] # Create a new tree _80533c8_Tree_p
%build_dir_tree $t /home/beazley/SWIG/SWIG1.1
%search_tree $t tcl
/home/beazley/SWIG/SWIG1.1/Examples/tcl /home/beazley/SWIG/SWIG1.1/swig_lib/tcl
%
Implementing methods in C
While our Tcl methods may be fine for small problems, it may be faster to reimplement the insert and search methods in C :
void insert_tree(Tree *t, char *key, char *value) { Node *p;
Node *x;
p = t->head;
x = t->head->right; while (x != t->z) { p = x;
if (strcmp(key,x->key) < 0) x = x->left;
else
x = x->right;
}
x = new_Node(key,value); if (strcmp(key,p->key) < 0)
p->left = x;
else
p->right = x; x->left = t->z; x->right = t->z;
}
To use this function in Tcl, simply put a declaration into the file tree.h or tree.i.
When reimplemented in C, the underlying Tcl script may not notice the difference. For example, our directory subroutine would not care if insert_tree had been written in Tcl or C. Of course, by writing this function C, we will get significantly better performance.
Version 1.1, June 24, 1997