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
C#
Java
Perl
Python
TCL
R
Ruby
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
Renaming templated types in 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 %{ ... %} & " ... " delimiters
Preprocessing and { ... } delimiters
Preprocessor and Typemaps
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
Special variable macros
$descriptor(type)
$typemap(method, typepattern)
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
Optimal code generation when returning by value
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
C++ "this" pointer
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
Special variables for %exception
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 extra warnings
Issuing a warning message
Symbolic symbols
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
Modules Introduction
Basics
The SWIG runtime code
External access to the runtime
A word of caution about static libraries
References
Reducing the wrapper file size
16 Using SWIG with ccache - ccache-swig(1) manpage
NAME
SYNOPSIS
DESCRIPTION
OPTIONS SUMMARY
OPTIONS
INSTALLATION
EXTRA OPTIONS
ENVIRONMENT VARIABLES
CACHE SIZE MANAGEMENT
CACHE COMPRESSION
HOW IT WORKS
USING CCACHE WITH DISTCC
SHARING A CACHE
HISTORY
DIFFERENCES FROM COMPILERCACHE
CREDITS
AUTHOR
17 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
18 SWIG and C#
Introduction
Differences to the Java module
C# Arrays
The SWIG C arrays library
Managed arrays using P/Invoke default array marshalling
Managed arrays using pinning
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
Date marshalling using the csin typemap and associated attributes
A date example demonstrating marshalling of C# properties
Turning wrapped classes into partial classes
Extending proxy classes with additional C# code
19 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
20 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
21 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
Single threaded applications and thread safety
Type wrapper classes
Enum classes
Typesafe enum classes
Proper Java enum classes
Type unsafe enum classes
Cross language polymorphism using directors
Enabling directors
Director classes
Overhead and code bloat
Simple directors example
Director threading issues
Accessing protected members
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
Overriding new and delete to allocate from Java heap
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
Date marshalling using the javain typemap and associated attributes
Living with Java Directors
Odds and ends
JavaDoc comments
Functional interface without proxy classes
Using your own JNI functions
Performance concerns and hints
Debugging
Examples
22 SWIG and Common Lisp
Allegro Common Lisp
Common Foreign Function Interface(CFFI)
Additional Commandline Options
Generating CFFI bindings
Generating CFFI bindings for C++ code
Inserting user code into generated files
CLISP
Additional Commandline Options
Details on CLISP bindings
UFFI
23 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
C++ Exceptions
Typemaps
What is a typemap?
Using typemaps
Typemaps and arrays
Typemaps and pointer-pointer functions
Writing typemaps
Typemaps you can write
SWIG's Lua-C API
Customization of your Bindings
Writing your own custom wrappers
Adding additional Lua code
Details on the Lua binding
Binding global data into the module.
Userdata and Metatables
Memory management
24 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
25 SWIG and MzScheme
Creating native MzScheme structures
26 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
27 SWIG and Octave
Preliminaries
Running SWIG
Compiling a dynamic module
Using your module
A tour of basic C/C++ wrapping
Modules
Functions
Global variables
Constants and enums
Pointers
Structures and C++ classes
C++ inheritance
C++ overloaded functions
C++ operators
Class extension with %extend
C++ templates
C++ Smart Pointers
Directors (calling Octave from C++ code)
Threads
Memory management
STL support
Matrix typemaps
28 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
29 SWIG and PHP
Generating PHP Extensions
Building a loadable extension
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
Cross language polymorphism
Enabling directors
Director classes
Ownership and object destruction
Exception unrolling
Overhead and code bloat
Typemaps
Miscellaneous
30 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
31 SWIG and Python
Overview
Preliminaries
Running SWIG
Using distutils
Hand compiling a dynamic module
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
Python 3 Support
Function annotation
Buffer interface
Abstract base classes
32 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++ Standard Template Library (STL)
C++ STL Functors
C++ STL Iterators
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
Handling Ruby Blocks
Raising exceptions
Exception classes
Typemaps
What is a typemap?
Typemap scope
Copying a typemap
Deleting a typemap
Placement of typemaps
Ruby typemaps
"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
directorin typemap
directorout typemap
directorargout typemap
ret typemap
globalin typemap
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
Docstring Features
Module docstring
%feature("autodoc")
%feature("autodoc", "0")
%feature("autodoc", "1")
%feature("autodoc", "2")
%feature("autodoc", "3")
%feature("autodoc", "docstring")
%feature("docstring")
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
Embedded Ruby and the C++ Stack
33 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
Tcl/Tk Stubs
34 SWIG and R
Bugs
Using R and SWIG
Precompiling large R files
General policy
Language conventions
C++ classes
Enumerations
35 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
Coding style guidelines
Typemaps
Proxy classes
Guide to parse tree nodes