SWIG Users Manual
1 Preface
Introduction
Special Introduction for Version 1.3
SWIG Versions
SWIG resources
Prerequisites
Organization of this manual
How to avoid reading the manual
Backwards Compatibility
Credits
Bug reports
2 Introduction
What is SWIG?
Why use SWIG?
A SWIG example
SWIG interface file
The swig command
Building a Perl5 module
Building a Python module
Shortcuts
Supported C/C++ language features
Non-intrusive interface building
Incorporating SWIG into a build system
Hands off code generation
SWIG and freedom
3 Getting started on Windows
Installation on Windows
Windows Executable
SWIG Windows Examples
Instructions for using the Examples with Visual Studio
Python
TCL
Perl
Java
Ruby
C#
Instructions for using the Examples with other compilers
SWIG on Cygwin and MinGW
Building swig.exe on Windows
Building swig.exe using MinGW and MSYS
Building swig.exe using Cygwin
Building swig.exe alternatives
Running the examples on Windows using Cygwin
Microsoft extensions and other Windows quirks
4 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
Proxy classes
Building scripting language extensions
Shared libraries and dynamic loading
Linking with shared libraries
Static linking
5 SWIG Basics
Running SWIG
Input format
SWIG Output
Comments
C Preprocessor
SWIG Directives
Parser Limitations
Wrapping Simple C Declarations
Basic Type Handling
Global Variables
Constants
A brief word about
const
A cautionary tale of
char *
Pointers and complex objects
Simple pointers
Run time pointer type checking
Derived types, structs, and classes
Undefined datatypes
Typedef
Other Practicalities
Passing structures by value
Return by value
Linking to structure variables
Linking to
char *
Arrays
Creating read-only variables
Renaming and ignoring declarations
Default/optional arguments
Pointers to functions and callbacks
Structures and unions
Typedef and structures
Character strings and structures
Array members
Structure data members
C constructors and destructors
Adding member functions to C structures
Nested structures
Other things to note about structure wrapping
Code Insertion
The output of SWIG
Code insertion blocks
Inlined code blocks
Initialization blocks
An Interface Building Strategy
Preparing a C program for SWIG
The SWIG interface file
Why use separate interface files?
Getting the right header files
What to do with main()
6 SWIG and C++
Comments on C++ Wrapping
Approach
Supported C++ features
Command line options and compilation
Proxy classes
Construction of proxy classes
Resource management in proxies
Language specific details
Simple C++ wrapping
Constructors and destructors
Default constructors, copy constructors and implicit destructors
When constructor wrappers aren't created
Copy constructors
Member functions
Static members
Member data
Default arguments
Protection
Enums and constants
Friends
References and pointers
Pass and return by value
Inheritance
A brief discussion of multiple inheritance, pointers, and type checking
Wrapping Overloaded Functions and Methods
Dispatch function generation
Ambiguity in Overloading
Ambiguity resolution and renaming
Comments on overloading
Wrapping overloaded operators
Class extension
Templates
Namespaces
Exception specifications
Exception handling with %catches
Pointers to Members
Smart pointers and operator->()
Using declarations and inheritance
Nested classes
A brief rant about const-correctness
Where to go for more information
7 Preprocessing
File inclusion
File imports
Conditional Compilation
Macro Expansion
SWIG Macros
C99 and GNU Extensions
Preprocessing and %{ ... %} blocks
Preprocessing and { ... }
Viewing preprocessor output
The #error and #warning directives
8 SWIG library
The %include directive and library search path
C Arrays and Pointers
cpointer.i
carrays.i
cmalloc.i
cdata.i
C String Handling
Default string handling
Passing binary data
Using %newobject to release memory
cstring.i
STL/C++ Library
std_string.i
std_vector.i
STL exceptions
Utility Libraries
exception.i
9 Argument Handling
The typemaps.i library
Introduction
Input parameters
Output parameters
Input/Output parameters
Using different names
Applying constraints to input values
Simple constraint example
Constraint methods
Applying constraints to new datatypes
10 Typemaps
Introduction
Type conversion
Typemaps
Pattern matching
Reusing typemaps
What can be done with typemaps?
What can't be done with typemaps?
The rest of this chapter
Typemap specifications
Defining a typemap
Typemap scope
Copying a typemap
Deleting a typemap
Placement of typemaps
Pattern matching rules
Basic matching rules
Typedef reductions
Default typemaps
Mixed default typemaps
Multi-arguments typemaps
Code generation rules
Scope
Declaring new local variables
Special variables
Common typemap methods
"in" typemap
"typecheck" typemap
"out" typemap
"arginit" typemap
"default" typemap
"check" typemap
"argout" typemap
"freearg" typemap
"newfree" typemap
"memberin" typemap
"varin" typemap
"varout" typemap
"throws" typemap
Some typemap examples
Typemaps for arrays
Implementing constraints with typemaps
Typemaps for multiple languages
Multi-argument typemaps
The run-time type checker
Implementation
Usage
Typemaps and overloading
More about
%apply
and
%clear
Reducing wrapper code size
Passing data between typemaps
Where to go for more information?
11 Customization Features
Exception handling with %exception
Handling exceptions in C code
Exception handling with longjmp()
Handling C++ exceptions
Exception handlers for variables
Defining different exception handlers
Using The SWIG exception library
Object ownership and %newobject
Features and the %feature directive
Feature attributes
Feature flags
Clearing features
Features and default arguments
Feature example
12 Contracts
The %contract directive
%contract and classes
Constant aggregation and %aggregate_check
Notes
13 Variable Length Arguments
Introduction
The Problem
Default varargs support
Argument replacement using %varargs
Varargs and typemaps
Varargs wrapping with libffi
Wrapping of va_list
C++ Issues
Discussion
14 Warning Messages
Introduction
Warning message suppression
Enabling additional warnings
Issuing a warning message
Commentary
Warnings as errors
Message output format
Warning number reference
Deprecated features (100-199)
Preprocessor (200-299)
C/C++ Parser (300-399)
Types and typemaps (400-499)
Code generation (500-599)
Language module specific (800-899)
User defined (900-999)
History
15 Working with Modules
The SWIG runtime code
External access to the runtime
A word of caution about static libraries
References
Reducing the wrapper file size
16 SWIG and Allegro Common Lisp
Basics
Running Swig
Command Line Options
Inserting user code into generated files
Wrapping Overview
Function Wrapping
Foreign Wrappers
FFI Wrappers
Non-overloaded Defuns
Overloaded Defuns
What about constant and variable access?
Object Wrapping
Wrapping Details
Namespaces
Constants
Variables
Enumerations
Arrays
Classes and Structs and Unions (oh my!)
CLOS wrapping of
CLOS Inheritance
Member fields and functions
Why not directly access C++ classes using foreign types?
Templates
Generating wrapper code for templates
Implicit Template instantiation
Typedef, Templates, and Synonym Types
Choosing a primary type
Function overloading/Parameter defaulting
Operator wrapping and Operator overloading
Varargs
C++ Exceptions
Pass by value, pass by reference
Typemaps
Code Generation in the C++ Wrapper
IN Typemap
OUT Typemap
CTYPE Typemap
Code generation in Lisp wrappers
LIN Typemap
LOUT Typemap
FFITYPE Typemap
LISPTYPE Typemap
LISPCLASS Typemap
Modifying SWIG behavior using typemaps
Identifier Converter functions
Creating symbols in the lisp environment
Existing identifier-converter functions
identifier-convert-null
identifier-convert-lispify
Default identifier to symbol conversions
Defining your own identifier-converter
Instructing SWIG to use a particular identifier-converter
17 SWIG and C#
Introduction
Differences to the Java module
C# Exceptions
C# exception example using "check" typemap
C# exception example using %exception
C# exception example using exception specifications
Custom C# ApplicationException example
C# Directors
Directors example
Directors implementation
Director caveats
C# Typemap examples
Memory management when returning references to member variables
Memory management for objects passed to the C++ layer
18 SWIG and Chicken
Preliminaries
Running SWIG in C mode
Running SWIG in C++ mode
Code Generation
Naming Conventions
Modules
Constants and Variables
Functions
Exceptions
TinyCLOS
Linkage
Static binary or shared library linked at compile time
Building chicken extension libraries
Linking multiple SWIG modules with TinyCLOS
Typemaps
Pointers
Garbage collection
Unsupported features and known problems
TinyCLOS problems with Chicken version <= 1.92
19 SWIG and Guile
Meaning of "Module"
Using the SCM or GH Guile API
Linkage
Simple Linkage
Passive Linkage
Native Guile Module Linkage
Old Auto-Loading Guile Module Linkage
Hobbit4D Linkage
Underscore Folding
Typemaps
Representation of pointers as smobs
GH Smobs
SCM Smobs
Garbage Collection
Exception Handling
Procedure documentation
Procedures with setters
GOOPS Proxy Classes
Naming Issues
Linking
20 SWIG and Java
Overview
Preliminaries
Running SWIG
Additional Commandline Options
Getting the right header files
Compiling a dynamic module
Using your module
Dynamic linking problems
Compilation problems and compiling with C++
Building on Windows
Running SWIG from Visual Studio
Using NMAKE
A tour of basic C/C++ wrapping
Modules, packages and generated Java classes
Functions
Global variables
Constants
Enumerations
Anonymous enums
Typesafe enums
Proper Java enums
Type unsafe enums
Simple enums
Pointers
Structures
C++ classes
C++ inheritance
Pointers, references, arrays and pass by value
Null pointers
C++ overloaded functions
C++ default arguments
C++ namespaces
C++ templates
C++ Smart Pointers
Further details on the generated Java classes
The intermediary JNI class
The intermediary JNI class pragmas
The Java module class
The Java module class pragmas
Java proxy classes
Memory management
Inheritance
Proxy classes and garbage collection
The premature garbage collection prevention parameter for proxy class marshalling
Type wrapper classes
Enum classes
Typesafe enum classes
Proper Java enum classes
Type unsafe enum classes
Cross language polymorphism using directors (experimental)
Enabling directors
Director classes
Overhead and code bloat
Simple directors example
Common customization features
C/C++ helper functions
Class extension with %extend
Exception handling with %exception and %javaexception
Method access with %javamethodmodifiers
Tips and techniques
Input and output parameters using primitive pointers and references
Simple pointers
Wrapping C arrays with Java arrays
Unbounded C Arrays
Java typemaps
Default primitive type mappings
Default typemaps for non-primitive types
Sixty four bit JVMs
What is a typemap?
Typemaps for mapping C/C++ types to Java types
Java typemap attributes
Java special variables
Typemaps for both C and C++ compilation
Java code typemaps
Director specific typemaps
Typemap Examples
Simpler Java enums for enums without initializers
Handling C++ exception specifications as Java exceptions
NaN Exception - exception handling for a particular type
Converting Java String arrays to char **
Expanding a Java object to multiple arguments
Using typemaps to return arguments
Adding Java downcasts to polymorphic return types
Adding an equals method to the Java classes
Void pointers and a common Java base class
Struct pointer to pointer
Memory management when returning references to member variables
Memory management for objects passed to the C++ layer
Living with Java Directors
Odds and ends
JavaDoc comments
Functional interface without proxy classes
Using your own JNI functions
Performance concerns and hints
Examples
21 SWIG and Common Lisp
Allegro Common Lisp
Common Foreign Function Interface(CFFI)
Additional Commandline Options
Generating CFFI bindings
Generating CFFI bindings for C++ code
CLISP
Additional Commandline Options
Details on CLISP bindings
UFFI
22 SWIG and Lua
Preliminaries
Running SWIG
Compiling and Linking and Interpreter
Compiling a dynamic module
Using your module
A tour of basic C/C++ wrapping
Modules
Functions
Global variables
Constants and enums
Pointers
Structures
C++ classes
C++ inheritance
Pointers, references, values, and arrays
C++ overloaded functions
C++ operators
Class extension with %extend
C++ templates
C++ Smart Pointers
Details on the Lua binding
Binding global data into the module.
Userdata and Metatables
Memory management
23 SWIG and Modula-3
Overview
Why not scripting ?
Why Modula-3 ?
Why C / C++ ?
Why SWIG ?
Conception
Interfaces to C libraries
Interfaces to C++ libraries
Preliminaries
Compilers
Additional Commandline Options
Modula-3 typemaps
Inputs and outputs
Subranges, Enumerations, Sets
Objects
Imports
Exceptions
Example
More hints to the generator
Features
Pragmas
Remarks
24 SWIG and MzScheme
Creating native MzScheme structures
25 SWIG and Ocaml
Preliminaries
Running SWIG
Compiling the code
The camlp4 module
Using your module
Compilation problems and compiling with C++
The low-level Ocaml/C interface
The generated module
Enums
Enum typing in Ocaml
Arrays
Simple types of bounded arrays
Complex and unbounded arrays
Using an object
Example typemap for a function taking float * and int
C++ Classes
STL vector and string Example
C++ Class Example
Compiling the example
Sample Session
Director Classes
Director Introduction
Overriding Methods in Ocaml
Director Usage Example
Creating director objects
Typemaps for directors,
directorin, directorout, directorargout
directorin
typemap
directorout
typemap
directorargout
typemap
Exceptions
26 SWIG and Perl5
Overview
Preliminaries
Getting the right header files
Compiling a dynamic module
Building a dynamic module with MakeMaker
Building a static version of Perl
Using the module
Compilation problems and compiling with C++
Compiling for 64-bit platforms
Building Perl Extensions under Windows
Running SWIG from Developer Studio
Using other compilers
The low-level interface
Functions
Global variables
Constants
Pointers
Structures
C++ classes
C++ classes and type-checking
C++ overloaded functions
Operators
Modules and packages
Input and output parameters
Exception handling
Remapping datatypes with typemaps
A simple typemap example
Perl5 typemaps
Typemap variables
Useful functions
Typemap Examples
Converting a Perl5 array to a char **
Return values
Returning values from arguments
Accessing array structure members
Turning Perl references into C pointers
Pointer handling
Proxy classes
Preliminaries
Structure and class wrappers
Object Ownership
Nested Objects
Proxy Functions
Inheritance
Modifying the proxy methods
Adding additional Perl code
27 SWIG and PHP
Generating PHP Extensions
Building a loadable extension
Building extensions into PHP
Using PHP Extensions
Basic PHP interface
Constants
Global Variables
Functions
Overloading
Pointers and References
Structures and C++ classes
Using
-noproxy
Constructors and Destructors
Static Member Variables
Static Member Functions
PHP Pragmas, Startup and Shutdown code
28 SWIG and Pike
Preliminaries
Running SWIG
Getting the right header files
Using your module
Basic C/C++ Mapping
Modules
Functions
Global variables
Constants and enumerated types
Constructors and Destructors
Static Members
29 SWIG and Python
Overview
Preliminaries
Running SWIG
Compiling a dynamic module
Using distutils
Static linking
Using your module
Compilation of C++ extensions
Compiling for 64-bit platforms
Building Python Extensions under Windows
A tour of basic C/C++ wrapping
Modules
Functions
Global variables
Constants and enums
Pointers
Structures
C++ classes
C++ inheritance
Pointers, references, values, and arrays
C++ overloaded functions
C++ operators
C++ namespaces
C++ templates
C++ Smart Pointers
C++ Reference Counted Objects (ref/unref)
Further details on the Python class interface
Proxy classes
Memory management
Python 2.2 and classic classes
Cross language polymorphism
Enabling directors
Director classes
Ownership and object destruction
Exception unrolling
Overhead and code bloat
Typemaps
Miscellaneous
Common customization features
C/C++ helper functions
Adding additional Python code
Class extension with %extend
Exception handling with %exception
Tips and techniques
Input and output parameters
Simple pointers
Unbounded C Arrays
String handling
Arrays
String arrays
STL wrappers
Typemaps
What is a typemap?
Python typemaps
Typemap variables
Useful Python Functions
Typemap Examples
Converting Python list to a char **
Expanding a Python object into multiple arguments
Using typemaps to return arguments
Mapping Python tuples into small arrays
Mapping sequences to C arrays
Pointer handling
Docstring Features
Module docstring
%feature("autodoc")
%feature("autodoc", "0")
%feature("autodoc", "1")
%feature("autodoc", "docstring")
%feature("docstring")
Python Packages
30 SWIG and Ruby
Preliminaries
Running SWIG
Getting the right header files
Compiling a dynamic module
Using your module
Static linking
Compilation of C++ extensions
Building Ruby Extensions under Windows 95/NT
Running SWIG from Developer Studio
The Ruby-to-C/C++ Mapping
Modules
Functions
Variable Linking
Constants
Pointers
Structures
C++ classes
C++ Inheritance
C++ Overloaded Functions
C++ Operators
C++ namespaces
C++ templates
C++ Smart Pointers
Cross-Language Polymorphism
Exception Unrolling
Naming
Defining Aliases
Predicate Methods
Bang Methods
Getters and Setters
Input and output parameters
Exception handling
Using the %exception directive
Raising exceptions
Exception classes
Typemaps
What is a typemap?
Ruby typemaps
Typemap variables
Useful Functions
C Datatypes to Ruby Objects
Ruby Objects to C Datatypes
Macros for VALUE
Exceptions
Iterators
Typemap Examples
Converting a Ruby array to a char **
Collecting arguments in a hash
Pointer handling
Ruby Datatype Wrapping
Example: STL Vector to Ruby Array
Advanced Topics
Operator overloading
Creating Multi-Module Packages
Specifying Mixin Modules
Memory Management
Mark and Sweep Garbage Collector
Object Ownership
Object Tracking
Mark Functions
Free Functions
31 SWIG and Tcl
Preliminaries
Getting the right header files
Compiling a dynamic module
Static linking
Using your module
Compilation of C++ extensions
Compiling for 64-bit platforms
Setting a package prefix
Using namespaces
Building Tcl/Tk Extensions under Windows 95/NT
Running SWIG from Developer Studio
Using NMAKE
A tour of basic C/C++ wrapping
Modules
Functions
Global variables
Constants and enums
Pointers
Structures
C++ classes
C++ inheritance
Pointers, references, values, and arrays
C++ overloaded functions
C++ operators
C++ namespaces
C++ templates
C++ Smart Pointers
Further details on the Tcl class interface
Proxy classes
Memory management
Input and output parameters
Exception handling
Typemaps
What is a typemap?
Tcl typemaps
Typemap variables
Converting a Tcl list to a char **
Returning values in arguments
Useful functions
Standard typemaps
Pointer handling
Turning a SWIG module into a Tcl Package.
Building new kinds of Tcl interfaces (in Tcl)
Proxy classes
32 SWIG and R
Bugs
Using R and SWIG
General policy
Language conventions
C++ classes
Enumerations
33 Extending SWIG to support new languages
Introduction
Prerequisites
The Big Picture
Execution Model
Preprocessing
Parsing
Parse Trees
Attribute namespaces
Symbol Tables
The %feature directive
Code Generation
SWIG and XML
Primitive Data Structures
Strings
Hashes
Lists
Common operations
Iterating over Lists and Hashes
I/O
Navigating and manipulating parse trees
Working with attributes
Type system
String encoding of types
Type construction
Type tests
Typedef and inheritance
Lvalues
Output functions
Parameters
Writing a Language Module
Execution model
Starting out
Command line options
Configuration and preprocessing
Entry point to code generation
Module I/O and wrapper skeleton
Low-level code generators
Configuration files
Runtime support
Standard library files
Examples and test cases
Documentation
Prerequisites for adding a new language module to the SWIG distribution
Typemaps
Proxy classes
Guide to parse tree nodes