
- •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 |
138 |
|
|
|
Wrapping C libraries and other packages
SWIG can be used to build Perl interfaces to existing C libraries and packages. The general strategy for doing this is as follows :
•Locate important header files for the package.
•Copy them into a SWIG interface file.
•Edit the interface file by removing problematic declarations, unneeded functions, and other clutter (this can often be found by just running SWIG).
•Add support functions to improve the interface.
While SWIG can sometimes be used to simply process a raw header file, the results aren’t always what you would expect. By working with a separate interface file, you get an opportunity to clean things up. If you’re using a stable package, chances are that it’s not going to change suddenly so there is really little problem in doing this. To illustrate the process, we will build a Perl5 interface to MATLAB in the next example.
Building a Perl5 interface to MATLAB
To illustrate the process, we can build a Perl5 interface to MATLAB by wrapping its C API. The MATLAB system consists of the MATLAB engine, and library of functions for creating and manipulating matrices, and a collection of utility function. A full description can be found in the “External Interface Guide” provided with MATLAB. Even if you don’t have MATLAB, this section can provide some ideas on how to handle other libraries.
The MATLAB engine interface
The first step in building an interface will be to provide access to the MATLAB engine. This is a separate process that runs in the background, but we need to have some mechanism for starting it and issuing commands. The following functions are defined in the MATLAB interface.,
int |
engClose(Engine *ep); |
int |
engEvalString(Engine *ep, char *string); |
Matrix |
*engGetMatrix(Engine *ep, char *name); |
int |
engPutMatrix(Engine *ep, Matrix *mp); |
Engine |
*engOpen(char *startcommand); |
void |
engOutputBuffer(Engine *ep, char *p, int size); |
While we could wrap these directly, each function requires an object “Engine”. They could be a little annoying to use in Perl since we would have to pass a pointer to the engine with every command. This probably isn’t necessary or desired. Thus, we could write some wrappers around these to produce a better interface as follows :
// engine.i : SWIG file for MATLAB engine %{
#define BUFFER_SIZE 32768
static Engine |
*eng = 0; |
static char |
ml_output[BUFFER_SIZE]; /* Result Buffer */ |
%} |
|
%inline %{ |
|
Version 1.1, June 24, 1997
SWIG Users Guide |
SWIG and Perl5 |
139 |
|
|
|
/* Initialize the MATLAB engine */ int init(void) {
if (eng) return -1; /* Already open */ if (!(eng = engOpen(“matlab42”))) {
fprintf(stderr,"Unable to open matlab.\n"); return -1;
}
engOutputBuffer(eng,ml_output,BUFFER_SIZE); return 0;
}
/* Execute a MATLAB command */ char *matlab(char *c) {
if (!eng) return “not initialized!”; engEvalString(eng, c);
return &ml_output[0];
}
/* Get a matrix from MATLAB */ Matrix *GetMatrix(char *name) {
if (!eng) return (Matrix *) 0; return(engGetMatrix(eng,name));
}
/* Send a matrix to MATLAB */ int PutMatrix(Matrix *m) {
if (!eng) return -1; return(engPutMatrix(eng,m));
}
%}
Wrapping the MATLAB matrix functions
Next, we need to build an interface to the MATLAB matrix manipulation library. This library contains about 30 functions to manipulate both real and complex valued matrices. Here we will only consider real-valued matrices. To provide access to the matrices, we’ll write a different interface file with a list of the functions along with a few helper functions.
//
// mx.i : SWIG file for MATLAB matrix manipulation %inline %{
/* Get an element from a matrix */ double getr(Matrix *mat, int i, int j) {
double *pr; int m;
pr = mxGetPr(mat); m = mxGetM(mat); return pr[m*j + i];
}
/* Set an element of a matrix */
void setr(Matrix *mat, int i, int j, double val) { double *pr;
int m;
pr = mxGetPr(mat); m = mxGetM(mat);
pr[m*j + i] = val;
}
Version 1.1, June 24, 1997
SWIG Users Guide |
SWIG and Perl5 |
140 |
|
|
|
%}
/* Now some MATLAB command */
Matrix *mxCreateFull(int m, int n, int ComplexFlag); int mxGetM(Matrix *mat);
int mxGetN(Matrix *mat); char *mxGetName(Matrix *mat);
void mxSetName(Matrix *mat, char *name); double *mxGetPr(Matrix *mat);
void mxSetPr(Matrix *mat, double *pr); double mxGetScalar(Matrix *mat);
void mxFreeMatrix(Matrix *pm);
Putting it all together
Finally we are ready to put our interface together. There is no need to build a big monolithic interface file--we can simply build it up in pieces :
//matlab.i
//Simple SWIG interface to MATLAB %module matlab
%{
#include “engine.h” %}
%include engine.i %include mx.i
Our module can be compiled as follows :
unix > swig -perl5 matlab.i
unix > gcc -c matlab_wrap.c -I/usr/local/lib/perl5/arch-osname/5.003/CORE -Dbool=char -I$(MATLAB)/extern/include
unix > ld -shared matlab_wrap.o -L$(MATLAB)/extern/lib -lmat -o matlab.so
Where $(MATLAB) is the location of the MATLAB installation (you may have to dig for this).
With our new MATLAB module, we can now write Perl scripts that issue MATLAB commands. For example :
use matlab; matlab::init();
matlab::matlab(“x = -8:.25:8; \ y = x; \
[X,Y] = meshgrid(x,y); \
R = sqrt(X.^2 + Y.^2)+eps; \ Z = sin(R)./R; \
mesh(Z); “);
Creates a simple 3D surface plot.
Graphical Web-Statistics in Perl5
Now, lets use our MATLAB module to generate plots of web-server hits for a given month. To do this, we’ll use our MATLAB module, and create a special purpose function for processing days and hours.
Version 1.1, June 24, 1997
SWIG Users Guide |
SWIG and Perl5 |
141 |
|
|
|
// Simple C function for recording a hit %module webgraph
%inline %
void hit(double *m, int day, int hour) { if ((day >= 0) && (day <= 31)) {
*(m+24*(day-1)+hour) += 1.0;
}
}
%}
While we could write this function in Perl, it will be much faster in C. If we’re processing a huge file, then the extra bit of performance will help us out. Once compiled, we can now write a Perl5 script like the following :
use matlab; use webgraph;
# Initialize matlab engine |
|
matlab::init(); |
|
# Make a matrix for all hits |
|
$m_all = matlab::mxCreateFull(24,31,0); |
|
matlab::mxSetName($m_all,"all"); |
|
$all = matlab::mxGetPr($m_all); |
# Get double * of Matrix |
foreach $file (@ARGV) { open(FILE,$file);
print "Processing ",$file,"\n"; while (<FILE>) {
@fields = split(/\s+/, $_); next if ($fields[8] != 200);
@datetime = split(/\[|\/|:/, $fields[3]); if ($datetime[2] =~ /Apr/) {
webgraph::hit($all, $datetime[1],$datetime[4]);
}
}
#Dump temporary results
}#foreach matlab::PutMatrix($m_all); matlab::matlab("figure(1); \
surf(all); \ view(40,40); \ shading interp; \ title('All hits'); \
set(gca,'xlabel',text(0,0,'Day')); \ set(gca,'ylabel',text(0,0,'Hour')); \ print -dgif8 stats_all.gif");
When run on the web-server logs for the University of Utah, this script produces the following GIF file (showing hits per hour) :
Version 1.1, June 24, 1997