- •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 Perl5 |
123 |
|
|
|
A simple Perl example
In the next few sections, use of the Perl5 module will be illustrated through a series of increasingly complex examples. In the example, we will write some simple graph algorithms to illustrate how C and Perl can interact with each other.
Graphs
A directed graph is simply a collection of nodes (or vertices) that are connected to each other by a collection of edges :
A graph
To represent simple graphs, we can use the following C data structures :
/* File : graph.h */
/* Simple data structures for directed graph of Nodes and Edges */
struct Edge; |
|
|
|
typedef struct Node { |
|
|
|
int |
v; |
/* Vertex number |
*/ |
struct Edge |
*adj; |
/* Adjacency List |
*/ |
} Node; |
|
|
|
typedef struct Edge { |
|
|
|
Node |
*node; |
/* Connecting Node |
*/ |
double |
w; |
/* Weight (optional) |
*/ |
struct Edge |
*next; |
/* Next edge |
*/ |
} Edge; |
|
|
|
Each node contains a unique number v for identifying it, and a linked list of other nodes that are nearby. This linked list is managed by the Edge structure. Associated with each edge is an optional weighting factor. This could be something like miles between cities, bandwidth, or some other numerical property about a particular link. Okay, enough talk about data structures for now.
To construct nodes and add edges, we can use the following C code :
/* File : graph.c |
*/ |
/* Directed graph functions */ |
|
#include "graph.h" |
|
static int node_count = 0; |
/* Number of nodes created */ |
Version 1.1, June 24, 1997
SWIG Users Guide |
SWIG and Perl5 |
124 |
|
|
|
/* Create a new Node */ Node *new_Node() {
Node *node;
node = (Node *) malloc(sizeof(Node));
node->v = node_count++; /* Bump up the count */ node->adj = (Edge *) 0;
return node;
}
/* Add an "edge" to another node. */
Edge *Node_addedge(Node *mynode, Node *othernode, double w) { Edge *edge;
edge = (Edge *) malloc(sizeof(Edge)); edge->node = othernode;
edge->w = w;
edge->next = mynode->adj; /* add to my adjacency list */ mynode->adj = edge;
return edge;
}
A simple SWIG interface file
So far, the code doesn’t do much, but it’s enough to wrap into Perl5 module. Since the C code is fairly simple right now, we can do this by creating the following interface file :
%module graph |
|
%{ |
|
#include “graph.h” |
|
%} |
|
%include graph.h |
// Get structure definition |
%include graph.c |
// Get support functions |
We’ll call our module “graph” and simply read in both the files graph.h and graph.c to build an interface.
Sample Perl Script
Once compiled, we can now start using our new module. All of the C functions found in graph.h and graph.c can be called normally . Even though we are using pointers, this is not a problem. Here is a very simple script :
# Perl code to use our graph code |
0 |
use graph; package graph;
1
# Create some nodes
2
$n0 = new_Node(); $n1 = new_Node(); $n2 = new_Node();
# Make some edges |
|
|
|
|
Node_addedge($n0,$n1,0); |
# |
0 |
-> |
1 |
Node_addedge($n0,$n2,0); |
# |
0 |
-> |
2 |
Version 1.1, June 24, 1997
SWIG Users Guide |
SWIG and Perl5 |
|
|
|
125 |
|
|
|
|
|
|
Node_addedge($n1,$n2,0); |
# |
1 |
-> |
2 |
|
Node_addedge($n2,$n0,0); |
# |
2 |
-> |
0 |
|
# A procedure to print out a node and its adjacency list sub print_node {
my $node = shift;
print "Node : ", Node_v_get($node), ", Adj : ";
my $adj = Node_adj_get($node); |
|
while (defined($adj)) { |
# This checks for a NULL pointer |
my $anode = Edge_node_get($adj); |
|
my $v = Node_v_get($anode); |
|
print "$v "; |
|
$adj = Edge_next_get($adj); |
# Move to next node |
} |
|
print "\n"; |
|
}
# Print out node information print_node($n0); print_node($n1); print_node($n2);
When executed, this script produces the following output :
Node : 0, Adj : 2 1
Node : 1, Adj : 2
Node : 2, Adj : 0
While our two C functions are used in the script, SWIG also created a collection of accessor functions for managing the two C data structures. The functions Node_v_get(),
Node_adj_get(), Edge_node_get(), and Edge_next_get() are used to access the corresponding members of our Node and Edge structures. As arguments, these functions simply take a pointer to the corresponding structure.
There are a few other things to notice about the code.
•Pointers to complex objects are manipulated like ordinary scalar values, but in reality they are blessed references. For all practical purposes, you should think of them as funny opaque objects (in other words, don’t worry about it).
•To check for a NULL pointer, use the expression defined($ptr). This will return true if a pointer is non-NULL, false if it isn’t. In our example, we use this to walk down a linked list of pointers until we reach a NULL value.
Even though the original C code was rather useless by itself, we have used it to build a simple graph in Perl along with a debugging function for printing out node information. In fact, without making any modifications to the C code, we can use this to build up something more complex such as a database of cities and mileages.
Version 1.1, June 24, 1997
SWIG Users Guide |
SWIG and Perl5 |
126 |
|
|
|
Denver, Cheyenne, |
100 |
Denver, Santa Fe, |
362 |
Denver, Kansas City, |
600 |
Santa Fe, Albuquerque, |
55 |
Santa Fe, Durango, |
214 |
... |
|
Durango, Moab, |
160 |
Moab, Salt Lake City, |
237 |
Moab, Denver, |
310 |
Cheyenne, Salt Lake City, |
436 |
Some cities and mileages
Here’s a slightly more complicated Perl script to read in the above mileage table and turn it into
agraph:
#Read a file with cities into a graph
use graph; package graph;
%Cities = (); |
# Hash table mapping cities to nodes |
%Nodes = (); |
# Mapping of Node indicies to cities |
sub read_cities { |
|
my $filename = shift; open(CITIES,$filename); while (<CITIES>) {
chop;
my @a = split(/, +/); my $node1;
my $node2;
#Check to see if a given city is already a node if (!exists $Cities{$a[0]}) {
$node1 = new_Node(); $Cities{$a[0]} = $node1;
my $node_num = Node_v_get($node1); $Nodes{$node_num} = $a[0];
} else {
$node1 = $Cities{$a[0]};
}
if (!exists $Cities{$a[1]}) { $node2 = new_Node(); $Cities{$a[1]} = $node2;
my $node_num = Node_v_get($node2); $Nodes{$node_num} = $a[1];
} else {
$node2 = $Cities{$a[1]};
}
#Add edges
Node_addedge($node1,$node2,$a[2]);
Node_addedge($node2,$node1,$a[2]);
}
}
Version 1.1, June 24, 1997
