SWIG-1.3 Documentation

SWIG-1.3 Documentation



Table of Contents



SWIG-1.3 Development Documentation 1 Preface 2 Introduction 3 Getting started on Windows 4 Scripting Languages 5 SWIG Basics 6 SWIG and C++ 7 Preprocessing 8 SWIG library 9 Argument Handling 10 Typemaps 11 Customization Features 12 Contracts 13 Variable Length Arguments 14 Warning Messages 15 Working with Modules 16 SWIG and Allegro Common Lisp 17 SWIG and C# 18 SWIG and Chicken 19 SWIG and Guile 20 SWIG and Java 21 SWIG and Common Lisp 22 SWIG and Lua 23 SWIG and Modula-3 24 SWIG and MzScheme 25 SWIG and Ocaml 26 SWIG and Perl5 27 SWIG and PHP 28 SWIG and Pike 29 SWIG and Python 30 SWIG and Ruby 31 SWIG and Tcl 32 SWIG and R 33 Extending SWIG to support new languages

SWIG-1.3 Development Documentation

Last update : SWIG-1.3.31 (November 20, 2006)

Sections

The SWIG documentation is being updated to reflect new SWIG features and enhancements. However, this update process is not quite finished--there is a lot of old SWIG-1.1 documentation and it is taking some time to update all of it. Please pardon our dust (or volunteer to help!).

SWIG Core Documentation

Language Module Documentation

Developer Documentation

Documentation that has not yet been updated

This documentation has not been completely updated from SWIG-1.1, but most of the topics still apply to the current release. Make sure you read the SWIG Basics chapter before reading any of these chapters. Also, SWIG-1.3.10 features extensive changes to the implementation of typemaps. Make sure you read the Typemaps chapter above if you are using this feature.


1 Preface

1.1 Introduction

SWIG (Simplified Wrapper and Interface Generator) is a software development tool for building scripting language interfaces to C and C++ programs. Originally developed in 1995, SWIG was first used by scientists in the Theoretical Physics Division at Los Alamos National Laboratory for building user interfaces to simulation codes running on the Connection Machine 5 supercomputer. In this environment, scientists needed to work with huge amounts of simulation data, complex hardware, and a constantly changing code base. The use of a scripting language interface provided a simple yet highly flexible foundation for solving these types of problems. SWIG simplifies development by largely automating the task of scripting language integration--allowing developers and users to focus on more important problems.

Although SWIG was originally developed for scientific applications, it has since evolved into a general purpose tool that is used in a wide variety of applications--in fact almost anything where C/C++ programming is involved.

1.2 Special Introduction for Version 1.3

Since SWIG was released in 1996, its user base and applicability has continued to grow. Although its rate of development has varied, an active development effort has continued to make improvements to the system. Today, nearly a dozen developers are working to create SWIG-2.0---a system that aims to provide wrapping support for nearly all of the ANSI C++ standard and approximately ten target languages including Guile, Java, Mzscheme, Ocaml, Perl, Pike, PHP, Python, Ruby, and Tcl.

1.3 SWIG Versions

For several years, the most stable version of SWIG has been release 1.1p5. Starting with version 1.3, a new version numbering scheme has been adopted. Odd version numbers (1.3, 1.5, etc.) represent development versions of SWIG. Even version numbers (1.4, 1.6, etc.) represent stable releases. Currently, developers are working to create a stable SWIG-2.0 release. Don't let the development status of SWIG-1.3 scare you---it is much more stable (and capable) than SWIG-1.1p5.

1.4 SWIG resources

The official location of SWIG related material is

http://www.swig.org

This site contains the latest version of the software, users guide, and information regarding bugs, installation problems, and implementation tricks.

You can also subscribe to the swig-user mailing list by visiting the page

http://www.swig.org/mail.html

The mailing list often discusses some of the more technical aspects of SWIG along with information about beta releases and future work.

CVS access to the latest version of SWIG is also available. More information about this can be obtained at:

http://www.swig.org/cvs.html

1.5 Prerequisites

This manual assumes that you know how to write C/C++ programs and that you have at least heard of scripting languages such as Tcl, Python, and Perl. A detailed knowledge of these scripting languages is not required although some familiarity won't hurt. No prior experience with building C extensions to these languages is required---after all, this is what SWIG does automatically. However, you should be reasonably familiar with the use of compilers, linkers, and makefiles since making scripting language extensions is somewhat more complicated than writing a normal C program.

Recent SWIG releases have become significantly more capable in their C++ handling--especially support for advanced features like namespaces, overloaded operators, and templates. Whenever possible, this manual tries to cover the technicalities of this interface. However, this isn't meant to be a tutorial on C++ programming. For many of the gory details, you will almost certainly want to consult a good C++ reference. If you don't program in C++, you may just want to skip those parts of the manual.

1.6 Organization of this manual

The first few chapters of this manual describe SWIG in general and provide an overview of its capabilities. The remaining chapters are devoted to specific SWIG language modules and are self contained. Thus, if you are using SWIG to build Python interfaces, you can probably skip to that chapter and find almost everything you need to know. Caveat: we are currently working on a documentation rewrite and many of the older language module chapters are still somewhat out of date.

1.7 How to avoid reading the manual

If you hate reading manuals, glance at the "Introduction" which contains a few simple examples. These examples contain about 95% of everything you need to know to use SWIG. After that, simply use the language-specific chapters as a reference. The SWIG distribution also comes with a large directory of examples that illustrate different topics.

1.8 Backwards Compatibility

If you are a previous user of SWIG, don't expect recent versions of SWIG to provide backwards compatibility. In fact, backwards compatibility issues may arise even between successive 1.3.x releases. Although these incompatibilities are regrettable, SWIG-1.3 is an active development project. The primary goal of this effort is to make SWIG better---a process that would simply be impossible if the developers are constantly bogged down with backwards compatibility issues.

On a positive note, a few incompatibilities are a small price to pay for the large number of new features that have been added---namespaces, templates, smart pointers, overloaded methods, operators, and more.

If you need to work with different versions of SWIG and backwards compatibility is an issue, you can use the SWIG_VERSION preprocessor symbol which holds the version of SWIG being executed. SWIG_VERSION is a hexadecimal integer such as 0x010311 (corresponding to SWIG-1.3.11). This can be used in an interface file to define different typemaps, take advantage of different features etc:

#if SWIG_VERSION >= 0x010311
/* Use some fancy new feature */
#endif

Note: The version symbol is not defined in the generated SWIG wrapper file. The SWIG preprocessor has defined SWIG_VERSION since SWIG-1.3.11.

1.9 Credits

SWIG is an unfunded project that would not be possible without the contributions of many people. Most recent SWIG development has been supported by Matthias Köppe, William Fulton, Lyle Johnson, Richard Palmer, Thien-Thi Nguyen, Jason Stewart, Loic Dachary, Masaki Fukushima, Luigi Ballabio, Sam Liddicott, Art Yerkes, Marcelo Matus, Harco de Hilster, John Lenz, and Surendra Singhi.

Historically, the following people contributed to early versions of SWIG. Peter Lomdahl, Brad Holian, Shujia Zhou, Niels Jensen, and Tim Germann at Los Alamos National Laboratory were the first users. Patrick Tullmann at the University of Utah suggested the idea of automatic documentation generation. John Schmidt and Kurtis Bleeker at the University of Utah tested out the early versions. Chris Johnson supported SWIG's developed at the University of Utah. John Buckman, Larry Virden, and Tom Schwaller provided valuable input on the first releases and improving the portability of SWIG. David Fletcher and Gary Holt have provided a great deal of input on improving SWIG's Perl5 implementation. Kevin Butler contributed the first Windows NT port.

1.10 Bug reports

Although every attempt has been made to make SWIG bug-free, we are also trying to make feature improvements that may introduce bugs. To report a bug, either send mail to the SWIG developer list at the swig-devel mailing list or report a bug at the SWIG bug tracker. In your report, be as specific as possible, including (if applicable), error messages, tracebacks (if a core dump occurred), corresponding portions of the SWIG interface file used, and any important pieces of the SWIG generated wrapper code. We can only fix bugs if we know about them.


2 Introduction

2.1 What is SWIG?

SWIG is a software development tool that simplifies the task of interfacing different languages to C and C++ programs. In a nutshell, SWIG is a compiler that takes C declarations and creates the wrappers needed to access those declarations from other languages including including Perl, Python, Tcl, Ruby, Guile, and Java. SWIG normally requires no modifications to existing code and can often be used to build a usable interface in only a few minutes. Possible applications of SWIG include:

SWIG was originally designed to make it extremely easy for scientists and engineers to build extensible scientific software without having to get a degree in software engineering. Because of this, the use of SWIG tends to be somewhat informal and ad-hoc (e.g., SWIG does not require users to provide formal interface specifications as you would find in a dedicated IDL compiler). Although this style of development isn't appropriate for every project, it is particularly well suited to software development in the small; especially the research and development work that is commonly found in scientific and engineering projects.

2.2 Why use SWIG?

As stated in the previous section, the primary purpose of SWIG is to simplify the task of integrating C/C++ with other programming languages. However, why would anyone want to do that? To answer that question, it is useful to list a few strengths of C/C++ programming:

Next, let's list a few problems with C/C++ programming

To address these limitations, many programmers have arrived at the conclusion that it is much easier to use different programming languages for different tasks. For instance, writing a graphical user interface may be significantly easier in a scripting language like Python or Tcl (consider the reasons why millions of programmers have used languages like Visual Basic if you need more proof). An interactive interpreter might also serve as a useful debugging and testing tool. Other languages like Java might greatly simplify the task of writing distributed computing software. The key point is that different programming languages offer different strengths and weaknesses. Moreover, it is extremely unlikely that any programming is ever going to be perfect. Therefore, by combining languages together, you can utilize the best features of each language and greatly simplify certain aspects of software development.

From the standpoint of C/C++, a lot of people use SWIG because they want to break out of the traditional monolithic C programming model which usually results in programs that resemble this:

Instead of going down that route, incorporating C/C++ into a higher level language often results in a more modular design, less code, better flexibility, and increased programmer productivity.

SWIG tries to make the problem of C/C++ integration as painless as possible. This allows you to focus on the underlying C program and using the high-level language interface, but not the tedious and complex chore of making the two languages talk to each other. At the same time, SWIG recognizes that all applications are different. Therefore, it provides a wide variety of customization features that let you change almost every aspect of the language bindings. This is the main reason why SWIG has such a large user manual ;-).

2.3 A SWIG example

The best way to illustrate SWIG is with a simple example. Consider the following C code:

/* File : example.c */

double  My_variable  = 3.0;

/* Compute factorial of n */
int  fact(int n) {
	if (n <= 1) return 1;
	else return n*fact(n-1);
}

/* Compute n mod m */
int my_mod(int n, int m) {
	return(n % m);
}

Suppose that you wanted to access these functions and the global variable My_variable from Tcl. You start by making a SWIG interface file as shown below (by convention, these files carry a .i suffix) :

2.3.1 SWIG interface file

/* File : example.i */
%module example
%{
/* Put headers and other declarations here */
extern double My_variable;
extern int    fact(int);
extern int    my_mod(int n, int m);
%}

extern double My_variable;
extern int    fact(int);
extern int    my_mod(int n, int m);

The interface file contains ANSI C function prototypes and variable declarations. The %module directive defines the name of the module that will be created by SWIG. The %{,%} block provides a location for inserting additional code such as C header files or additional C declarations.

2.3.2 The swig command

SWIG is invoked using the swig command. We can use this to build a Tcl module (under Linux) as follows :

unix > swig -tcl example.i
unix > gcc -c -fpic example.c example_wrap.c -I/usr/local/include
unix > gcc -shared example.o example_wrap.o -o example.so
unix > tclsh
% load ./example.so
% fact 4
24
% my_mod 23 7
2
% expr $My_variable + 4.5
7.5
%

The swig command produced a new file called example_wrap.c that should be compiled along with the example.c file. Most operating systems and scripting languages now support dynamic loading of modules. In our example, our Tcl module has been compiled into a shared library that can be loaded into Tcl. When loaded, Tcl can now access the functions and variables declared in the SWIG interface. A look at the file example_wrap.c reveals a hideous mess. However, you almost never need to worry about it.

2.3.3 Building a Perl5 module

Now, let's turn these functions into a Perl5 module. Without making any changes type the following (shown for Solaris):

unix > swig -perl5 example.i
unix > gcc -c example.c example_wrap.c \
	-I/usr/local/lib/perl5/sun4-solaris/5.003/CORE
unix > ld -G example.o example_wrap.o -o example.so		# This is for Solaris
unix > perl5.003
use example;
print example::fact(4), "\n";
print example::my_mod(23,7), "\n";
print $example::My_variable + 4.5, "\n";
<ctrl-d>
24
2
7.5
unix >

2.3.4 Building a Python module

Finally, let's build a module for Python (shown for Irix).

unix > swig -python example.i
unix > gcc -c -fpic example.c example_wrap.c -I/usr/local/include/python2.0
unix > gcc -shared example.o example_wrap.o -o _example.so
unix > python
Python 2.0 (#6, Feb 21 2001, 13:29:45)
[GCC egcs-2.91.66 19990314/Linux (egcs-1.1.2 release)] on linux2
Type "copyright", "credits" or "license" for more information.     
>>> import example
>>> example.fact(4)
24
>>> example.my_mod(23,7)
2
>>> example.cvar.My_variable + 4.5
7.5

2.3.5 Shortcuts

To the truly lazy programmer, one may wonder why we needed the extra interface file at all. As it turns out, you can often do without it. For example, you could also build a Perl5 module by just running SWIG on the C header file and specifying a module name as follows

unix > swig -perl5 -module example example.h
unix > gcc -c example.c example_wrap.c \
	-I/usr/local/lib/perl5/sun4-solaris/5.003/CORE
unix > ld -G example.o example_wrap.o -o example.so
unix > perl5.003
use example;
print example::fact(4), "\n";
print example::my_mod(23,7), "\n";
print $example::My_variable + 4.5, "\n";
<ctrl-d>
24
2
7.5

2.4 Supported C/C++ language features

A primary goal of the SWIG project is to make the language binding process extremely easy. Although a few simple examples have been shown, SWIG is quite capable in supporting most of C++. Some of the major features include:

Currently, the only major C++ feature not supported is nested classes--a limitation that will be removed in a future release.

It is important to stress that SWIG is not a simplistic C++ lexing tool like several apparently similar wrapper generation tools. SWIG not only parses C++, it implements the full C++ type system and it is able to understand C++ semantics. SWIG generates its wrappers with full knowledge of this information. As a result, you will find SWIG to be just as capable of dealing with nasty corner cases as it is in wrapping simple C++ code. In fact, SWIG is able handle C++ code that stresses the very limits of many C++ compilers.

2.5 Non-intrusive interface building

When used as intended, SWIG requires minimal (if any) modification to existing C or C++ code. This makes SWIG extremely easy to use with existing packages and promotes software reuse and modularity. By making the C/C++ code independent of the high level interface, you can change the interface and reuse the code in other applications. It is also possible to support different types of interfaces depending on the application.

2.6 Incorporating SWIG into a build system

SWIG is a command line tool and as such can be incorporated into any build system that supports invoking external tools/compilers. SWIG is most commonly invoked from within a Makefile, but is also known to be invoked from from popular IDEs such as Microsoft Visual Studio.

If you are using the GNU Autotools ( Autoconf/ Automake / Libtool) to configure SWIG use in your project, the SWIG Autoconf macros can be used. The primary macro is ac_pkg_swig, see http://www.gnu.org/software/ac-archive/htmldoc/ac_pkg_swig.html. The ac_python_devel macro is also helpful for generating Python extensions. See the Autoconf Macro Archive for further information on this and other Autoconf macros.

There is growing support for SWIG in some build tools, for example CMake is a cross-platform, open-source build manager with built in support for SWIG. CMake can detect the SWIG executable and many of the target language libraries for linking against. CMake knows how to build shared libraries and loadable modules on many different operating systems. This allows easy cross platform SWIG development. It also can generate the custom commands necessary for driving SWIG from IDE's and makefiles. All of this can be done from a single cross platform input file. The following example is a CMake input file for creating a python wrapper for the SWIG interface file, example.i:


# This is a CMake example for Python

FIND_PACKAGE(SWIG REQUIRED)
INCLUDE(${SWIG_USE_FILE})

FIND_PACKAGE(PythonLibs)
INCLUDE_DIRECTORIES(${PYTHON_INCLUDE_PATH})

INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR})

SET(CMAKE_SWIG_FLAGS "")

SET_SOURCE_FILES_PROPERTIES(example.i PROPERTIES CPLUSPLUS ON)
SET_SOURCE_FILES_PROPERTIES(example.i PROPERTIES SWIG_FLAGS "-includeall")
SWIG_ADD_MODULE(example python example.i example.cxx)
SWIG_LINK_LIBRARIES(example ${PYTHON_LIBRARIES})

The above example will generate native build files such as makefiles, nmake files and Visual Studio projects which will invoke SWIG and compile the generated C++ files into _example.so (UNIX) or _example.dll (Windows).

2.7 Hands off code generation

SWIG is designed to produce working code that needs no hand-modification (in fact, if you look at the output, you probably won't want to modify it). You should think of your target language interface being defined entirely by the input to SWIG, not the resulting output file. While this approach may limit flexibility for hard-core hackers, it allows others to forget about the low-level implementation details.

2.8 SWIG and freedom

No, this isn't a special section on the sorry state of world politics. However, it may be useful to know that SWIG was written with a certain "philosophy" about programming---namely that programmers are smart and that tools should just stay out of their way. Because of that, you will find that SWIG is extremely permissive in what it lets you get away with. In fact, you can use SWIG to go well beyond "shooting yourself in the foot" if dangerous programming is your goal. On the other hand, this kind of freedom may be exactly what is needed to work with complicated and unusual C/C++ applications.

Ironically, the freedom that SWIG provides is countered by an extremely conservative approach to code generation. At it's core, SWIG tries to distill even the most advanced C++ code down to a small well-defined set of interface building techniques based on ANSI C programming. Because of this, you will find that SWIG interfaces can be easily compiled by virtually every C/C++ compiler and that they can be used on any platform. Again, this is an important part of staying out of the programmer's way----the last thing any developer wants to do is to spend their time debugging the output of a tool that relies on non-portable or unreliable programming features.


3 Getting started on Windows

This chapter describes SWIG usage on Microsoft Windows. Installing SWIG and running the examples is covered as well as building the SWIG executable. Usage within the Unix like environments MinGW and Cygwin is also detailed.

3.1 Installation on Windows

SWIG does not come with the usual Windows type installation program, however it is quite easy to get started. The main steps are:

3.1.1 Windows Executable

The swigwin distribution contains the SWIG Windows executable, swig.exe, which will run on 32 bit versions of Windows, ie Windows 95/98/ME/NT/2000/XP. If you want to build your own swig.exe have a look at Building swig.exe on Windows.

3.2 SWIG Windows Examples

Using Microsoft Visual C++ is the most common approach to compiling and linking SWIG's output. The Examples directory has a few Visual C++ project files (.dsp files). These were produced by Visual C++ 6, although they should also work in Visual C++ 5. Later versions of Visual Studio should also be able to open and convert these project files. The C# examples come with .NET 2003 solution (.sln) and project files instead of Visual C++ 6 project files. The project files have been set up to execute SWIG in a custom build rule for the SWIG interface (.i) file. Alternatively run the examples using Cygwin.

More information on each of the examples is available with the examples distributed with SWIG (Examples/index.html).

3.2.1 Instructions for using the Examples with Visual Studio

Ensure the SWIG executable is as supplied in the SWIG root directory in order for the examples to work. Most languages require some environment variables to be set before running Visual C++. Note that Visual C++ must be re-started to pick up any changes in environment variables. Open up an example .dsp file, Visual C++ will create a workspace for you (.dsw file). Ensure the Release build is selected then do a Rebuild All from the Build menu. The required environment variables are displayed with their current values.

The list of required environment variables for each module language is also listed below. They are usually set from the Control Panel and System properties, but this depends on which flavour of Windows you are running. If you don't want to use environment variables then change all occurrences of the environment variables in the .dsp files with hard coded values. If you are interested in how the project files are set up there is explanatory information in some of the language module's documentation.

3.2.1.1 Python

PYTHON_INCLUDE : Set this to the directory that contains python.h
PYTHON_LIB : Set this to the python library including path for linking

Example using Python 2.1.1:
PYTHON_INCLUDE: d:\python21\include
PYTHON_LIB: d:\python21\libs\python21.lib

3.2.1.2 TCL

TCL_INCLUDE : Set this to the directory containing tcl.h
TCL_LIB : Set this to the TCL library including path for linking

Example using ActiveTcl 8.3.3.3
TCL_INCLUDE: d:\tcl\include
TCL_LIB: d:\tcl\lib\tcl83.lib

3.2.1.3 Perl

PERL5_INCLUDE : Set this to the directory containing perl.h
PERL5_LIB : Set this to the Perl library including path for linking

Example using nsPerl 5.004_04:

PERL5_INCLUDE: D:\nsPerl5.004_04\lib\CORE
PERL5_LIB: D:\nsPerl5.004_04\lib\CORE\perl.lib

3.2.1.4 Java

JAVA_INCLUDE : Set this to the directory containing jni.h
JAVA_BIN : Set this to the bin directory containing javac.exe

Example using JDK1.3:
JAVA_INCLUDE: d:\jdk1.3\include
JAVA_BIN: d:\jdk1.3\bin

3.2.1.5 Ruby

RUBY_INCLUDE : Set this to the directory containing ruby.h
RUBY_LIB : Set this to the ruby library including path for linking

Example using Ruby 1.6.4:
RUBY_INCLUDE: D:\ruby\lib\ruby\1.6\i586-mswin32
RUBY_LIB: D:\ruby\lib\mswin32-ruby16.lib

3.2.1.6 C#

The C# examples do not require any environment variables to be set as a C# project file is included. Just open up the .sln solution file in Visual Studio .NET 2003 and do a Rebuild All from the Build menu. The accompanying C# and C++ project file are automatically used by the solution file.

3.2.2 Instructions for using the Examples with other compilers

If you do not have access to Visual C++ you will have to set up project files / Makefiles for your chosen compiler. There is a section in each of the language modules detailing what needs setting up using Visual C++ which may be of some guidance. Alternatively you may want to use Cygwin as described in the following section.

3.3 SWIG on Cygwin and MinGW

SWIG can also be compiled and run using Cygwin or MinGW which provides a Unix like front end to Windows and comes free with gcc, an ANSI C/C++ compiler. However, this is not a recommended approach as the prebuilt executable is supplied.

3.3.1 Building swig.exe on Windows

If you want to replicate the build of swig.exe that comes with the download, follow the MinGW instructions below. This is not necessary to use the supplied swig.exe. This information is provided for those that want to modify the SWIG source code in a Windows environment. Normally this is not needed, so most people will want to ignore this section.

3.3.1.1 Building swig.exe using MinGW and MSYS

The short abbreviated instructions follow...

The step by step instructions to download and install MinGW and MSYS, then download and build the latest version of SWIG from cvs follow... Note that the instructions for obtaining SWIG from CVS are also online at SWIG CVS.

Pitfall note: Execute the steps in the order shown and don't use spaces in path names. In fact it is best to use the default installation directories.

  1. Download the following packages from the MinGW download page or MinGW SourceForge download page. Note that at the time of writing, the majority of these are in the Current release list and some are in the Snapshot or Previous release list.
  2. Install MinGW-3.1.0-1.exe (C:\MinGW is default location.)
  3. Install MSYS-1.0.11-2004.04.30-1.exe. Make sure you install it on the same windows drive letter as MinGW (C:\msys\1.0 is default). In the post install script,
  4. Install msysDTK-1.0.1.exe to the same folder that you installed MSYS (C:\msys\1.0 is default).
  5. Copy the followig to the MSYS install folder (C:\msys\1.0 is default):
  6. Start the MSYS command prompt and execute:
    cd /
    tar -jxf msys-automake-1.8.2.tar.bz2 
    tar -jxf msys-autoconf-2.59.tar.bz2
    tar -zxf bison-2.0-MSYS.tar.gz   
    
  7. To get the latest SWIG CVS, type in the following:
    mkdir /usr/src
    cd /usr/src
    export CVSROOT=:pserver:anonymous@swig.cvs.sourceforge.net:/cvsroot/swig
    cvs login
     (Logging in to anonymous@swig.cvs.sourceforge.net)
     CVS password: <Just Press Return Here>
    cvs -z3 checkout SWIG
    
    Pitfall note: If you want to check out SWIG to a different folder to the proposed /usr/src/SWIG, do not use MSYS emulated windows drive letters, because the autotools will fail miserably on those.
  8. You are now ready to build SWIG. Execute the following commands to build swig.exe:
    cd /usr/src/SWIG
    ./autogen.sh
    ./configure
    make
    

3.3.1.2 Building swig.exe using Cygwin

Note that SWIG can also be built using Cygwin. However, SWIG will then require the Cygwin DLL when executing. Follow the Unix instructions in the README file in the SWIG root directory. Note that the Cygwin environment will also allow one to regenerate the autotool generated files which are supplied with the release distribution. These files are generated using the autogen.sh script and will only need regenerating in circumstances such as changing the build system.

3.3.1.3 Building swig.exe alternatives

If you don't want to install Cygwin or MinGW, use a different compiler to build SWIG. For example, all the source code files can be added to a Visual C++ project file in order to build swig.exe from the Visual C++ IDE.

3.3.2 Running the examples on Windows using Cygwin

The examples and test-suite work as successfully on Cygwin as on any other Unix operating system. The modules which are known to work are Python, Tcl, Perl, Ruby, Java and C#. Follow the Unix instructions in the README file in the SWIG root directory to build the examples.

3.4 Microsoft extensions and other Windows quirks

A common problem when using SWIG on Windows are the Microsoft function calling conventions which are not in the C++ standard. SWIG parses ISO C/C++ so cannot deal with proprietary conventions such as __declspec(dllimport), __stdcall etc. There is a Windows interface file, windows.i, to deal with these calling conventions though. The file also contains typemaps for handling commonly used Windows specific types such as __int64, BOOL , DWORD etc. Include it like you would any other interface file, for example:

%include <windows.i>

__declspec(dllexport) ULONG __stdcall foo(DWORD, __int32);

4 Scripting Languages

This chapter provides a brief overview of scripting language extension programming and the mechanisms by which scripting language interpreters access C and C++ code.

4.1 The two language view of the world

When a scripting language is used to control a C program, the resulting system tends to look as follows:

Scripting language input - C/C++ functions output

In this programming model, the scripting language interpreter is used for high level control whereas the underlying functionality of the C/C++ program is accessed through special scripting language "commands." If you have ever tried to write your own simple command interpreter, you might view the scripting language approach to be a highly advanced implementation of that. Likewise, If you have ever used a package such as MATLAB or IDL, it is a very similar model--the interpreter executes user commands and scripts. However, most of the underlying functionality is written in a low-level language like C or Fortran.

The two-language model of computing is extremely powerful because it exploits the strengths of each language. C/C++ can be used for maximal performance and complicated systems programming tasks. Scripting languages can be used for rapid prototyping, interactive debugging, scripting, and access to high-level data structures such associative arrays.

4.2 How does a scripting language talk to C?

Scripting languages are built around a parser that knows how to execute commands and scripts. Within this parser, there is a mechanism for executing commands and accessing variables. Normally, this is used to implement the builtin features of the language. However, by extending the interpreter, it is usually possible to add new commands and variables. To do this, most languages define a special API for adding new commands. Furthermore, a special foreign function interface defines how these new commands are supposed to hook into the interpreter.

Typically, when you add a new command to a scripting interpreter you need to do two things; first you need to write a special "wrapper" function that serves as the glue between the interpreter and the underlying C function. Then you need to give the interpreter information about the wrapper by providing details about the name of the function, arguments, and so forth. The next few sections illustrate the process.

4.2.1 Wrapper functions

Suppose you have an ordinary C function like this :

int fact(int n) {
	if (n <= 1) return 1;
	else return n*fact(n-1);
}

In order to access this function from a scripting language, it is necessary to write a special "wrapper" function that serves as the glue between the scripting language and the underlying C function. A wrapper function must do three things :

As an example, the Tcl wrapper function for the fact() function above example might look like the following :

int wrap_fact(ClientData clientData, Tcl_Interp *interp,
		int argc, char *argv[]) {
	int result;
	int arg0;
	if (argc != 2) {
		interp->result = "wrong # args";
		return TCL_ERROR;
	}
	arg0 = atoi(argv[1]);
	result = fact(arg0);
	sprintf(interp->result,"%d", result);
	return TCL_OK;
}

Once you have created a wrapper function, the final step is to tell the scripting language about the new function. This is usually done in an initialization function called by the language when the module is loaded. For example, adding the above function to the Tcl interpreter requires code like the following :

int Wrap_Init(Tcl_Interp *interp) {
	Tcl_CreateCommand(interp, "fact", wrap_fact, (ClientData) NULL,
				(Tcl_CmdDeleteProc *) NULL);
	return TCL_OK;
}

When executed, Tcl will now have a new command called "fact " that you can use like any other Tcl command.

Although the process of adding a new function to Tcl has been illustrated, the procedure is almost identical for Perl and Python. Both require special wrappers to be written and both need additional initialization code. Only the specific details are different.

4.2.2 Variable linking

Variable linking refers to the problem of mapping a C/C++ global variable to a variable in the scripting language interpreter. For example, suppose you had the following variable:

double Foo = 3.5;

It might be nice to access it from a script as follows (shown for Perl):

$a = $Foo * 2.3;   # Evaluation
$Foo = $a + 2.0;   # Assignment

To provide such access, variables are commonly manipulated using a pair of get/set functions. For example, whenever the value of a variable is read, a "get" function is invoked. Similarly, whenever the value of a variable is changed, a "set" function is called.

In many languages, calls to the get/set functions can be attached to evaluation and assignment operators. Therefore, evaluating a variable such as $Foo might implicitly call the get function. Similarly, typing $Foo = 4 would call the underlying set function to change the value.

4.2.3 Constants

In many cases, a C program or library may define a large collection of constants. For example:

#define RED   0xff0000
#define BLUE  0x0000ff
#define GREEN 0x00ff00

To make constants available, their values can be stored in scripting language variables such as $RED, $BLUE, and $GREEN. Virtually all scripting languages provide C functions for creating variables so installing constants is usually a trivial exercise.

4.2.4 Structures and classes

Although scripting languages have no trouble accessing simple functions and variables, accessing C/C++ structures and classes present a different problem. This is because the implementation of structures is largely related to the problem of data representation and layout. Furthermore, certain language features are difficult to map to an interpreter. For instance, what does C++ inheritance mean in a Perl interface?

The most straightforward technique for handling structures is to implement a collection of accessor functions that hide the underlying representation of a structure. For example,

struct Vector {
	Vector();
	~Vector();
	double x,y,z;
};

can be transformed into the following set of functions :

Vector *new_Vector();
void delete_Vector(Vector *v);
double Vector_x_get(Vector *v);
double Vector_y_get(Vector *v);
double Vector_z_get(Vector *v);
void Vector_x_set(Vector *v, double x);
void Vector_y_set(Vector *v, double y);
void Vector_z_set(Vector *v, double z);

Now, from an interpreter these function might be used as follows:

% set v [new_Vector]
% Vector_x_set $v 3.5
% Vector_y_get $v
% delete_Vector $v
% ...

Since accessor functions provide a mechanism for accessing the internals of an object, the interpreter does not need to know anything about the actual representation of a Vector.

4.2.5 Proxy classes

In certain cases, it is possible to use the low-level accessor functions to create a proxy class, also known as a shadow class. A proxy class is a special kind of object that gets created in a scripting language to access a C/C++ class (or struct) in a way that looks like the original structure (that is, it proxies the real C++ class). For example, if you have the following C definition :

class Vector {
public:
	Vector();
	~Vector();
	double x,y,z;
};

A proxy classing mechanism would allow you to access the structure in a more natural manner from the interpreter. For example, in Python, you might want to do this:

>>> v = Vector()
>>> v.x = 3
>>> v.y = 4
>>> v.z = -13
>>> ...
>>> del v

Similarly, in Perl5 you may want the interface to work like this:

$v = new Vector;
$v->{x} = 3;
$v->{y} = 4;
$v->{z} = -13;

Finally, in Tcl :

Vector v
v configure -x 3 -y 4 -z 13

When proxy classes are used, two objects are at really work--one in the scripting language, and an underlying C/C++ object. Operations affect both objects equally and for all practical purposes, it appears as if you are simply manipulating a C/C++ object.

4.3 Building scripting language extensions

The final step in using a scripting language with your C/C++ application is adding your extensions to the scripting language itself. There are two primary approaches for doing this. The preferred technique is to build a dynamically loadable extension in the form a shared library. Alternatively, you can recompile the scripting language interpreter with your extensions added to it.

4.3.1 Shared libraries and dynamic loading

To create a shared library or DLL, you often need to look at the manual pages for your compiler and linker. However, the procedure for a few common machines is shown below:

# Build a shared library for Solaris
gcc -c example.c example_wrap.c -I/usr/local/include
ld -G example.o example_wrap.o -o example.so

# Build a shared library for Linux
gcc -fpic -c example.c example_wrap.c -I/usr/local/include
gcc -shared example.o example_wrap.o -o example.so

# Build a shared library for Irix
gcc -c example.c example_wrap.c -I/usr/local/include
ld -shared example.o example_wrap.o -o example.so

To use your shared library, you simply use the corresponding command in the scripting language (load, import, use, etc...). This will import your module and allow you to start using it. For example:

% load ./example.so
% fact 4
24
%

When working with C++ codes, the process of building shared libraries may be more complicated--primarily due to the fact that C++ modules may need additional code in order to operate correctly. On many machines, you can build a shared C++ module by following the above procedures, but changing the link line to the following :

c++ -shared example.o example_wrap.o -o example.so

4.3.2 Linking with shared libraries

When building extensions as shared libraries, it is not uncommon for your extension to rely upon other shared libraries on your machine. In order for the extension to work, it needs to be able to find all of these libraries at run-time. Otherwise, you may get an error such as the following :

>>> import graph
Traceback (innermost last):
  File "<stdin>", line 1, in ?
  File "/home/sci/data1/beazley/graph/graph.py", line 2, in ?
    import graphc
ImportError:  1101:/home/sci/data1/beazley/bin/python: rld: Fatal Error: cannot 
successfully map soname 'libgraph.so' under any of the filenames /usr/lib/libgraph.so:/
lib/libgraph.so:/lib/cmplrs/cc/libgraph.so:/usr/lib/cmplrs/cc/libgraph.so:
>>>

What this error means is that the extension module created by SWIG depends upon a shared library called "libgraph.so" that the system was unable to locate. To fix this problem, there are a few approaches you can take.

4.3.3 Static linking

With static linking, you rebuild the scripting language interpreter with extensions. The process usually involves compiling a short main program that adds your customized commands to the language and starts the interpreter. You then link your program with a library to produce a new scripting language executable.

Although static linking is supported on all platforms, this is not the preferred technique for building scripting language extensions. In fact, there are very few practical reasons for doing this--consider using shared libraries instead.


5 SWIG Basics

This chapter describes the basic operation of SWIG, the structure of its input files, and how it handles standard ANSI C declarations. C++ support is described in the next chapter. However, C++ programmers should still read this chapter to understand the basics. Specific details about each target language are described in later chapters.

5.1 Running SWIG

To run SWIG, use the swig command with options options and a filename like this:

swig [ options ] filename

where filename is a SWIG interface file or a C/C++ header file. Below is a subset of options that can be used. Additional options are also defined for each target language. A full list can be obtained by typing swig -help or swig - lang -help.

-allegrocl            Generate ALLEGROCL wrappers
-chicken              Generate CHICKEN wrappers
-clisp                Generate CLISP wrappers
-cffi                 Generate CFFI wrappers
-csharp               Generate C# wrappers
-guile                Generate Guile wrappers
-java                 Generate Java wrappers
-lua                  Generate Lua wrappers
-modula3              Generate Modula 3 wrappers
-mzscheme             Generate Mzscheme wrappers
-ocaml                Generate Ocaml wrappers
-perl                 Generate Perl wrappers
-php                  Generate PHP wrappers
-pike                 Generate Pike wrappers
-python               Generate Python wrappers
-ruby                 Generate Ruby wrappers
-sexp                 Generate Lisp S-Expressions wrappers
-tcl                  Generate Tcl wrappers
-uffi                 Generate Common Lisp / UFFI wrappers
-xml                  Generate XML wrappers

-c++                  Enable C++ parsing
-Dsymbol              Define a preprocessor symbol
-Fstandard            Display error/warning messages in commonly used format
-Fmicrosoft           Display error/warning messages in Microsoft format
-help                 Display all options
-Idir                 Add a directory to the file include path
-lfile                Include a SWIG library file.
-module name          Set the name of the SWIG module
-o outfile            Name of output file
-outdir dir           Set language specific files output directory
-swiglib              Show location of SWIG library
-version              Show SWIG version number

5.1.1 Input format

As input, SWIG expects a file containing ANSI C/C++ declarations and special SWIG directives. More often than not, this is a special SWIG interface file which is usually denoted with a special .i or .swg suffix. In certain cases, SWIG can be used directly on raw header files or source files. However, this is not the most typical case and there are several reasons why you might not want to do this (described later).

The most common format of a SWIG interface is as follows:

%module mymodule 
%{
#include "myheader.h"
%}
// Now list ANSI C/C++ declarations
int foo;
int bar(int x);
...

The name of the module is supplied using the special %module directive (or the -module command line option). This directive must appear at the beginning of the file and is used to name the resulting extension module (in addition, this name often defines a namespace in the target language). If the module name is supplied on the command line, it overrides the name specified with the %module directive.

Everything in the %{ ... %} block is simply copied verbatim to the resulting wrapper file created by SWIG. This section is almost always used to include header files and other declarations that are required to make the generated wrapper code compile. It is important to emphasize that just because you include a declaration in a SWIG input file, that declaration does not automatically appear in the generated wrapper code---therefore you need to make sure you include the proper header files in the %{ ... %} section. It should be noted that the text enclosed in %{ ... %} is not parsed or interpreted by SWIG. The %{...%} syntax and semantics in SWIG is analogous to that of the declarations section used in input files to parser generation tools such as yacc or bison.

5.1.2 SWIG Output

The output of SWIG is a C/C++ file that contains all of the wrapper code needed to build an extension module. SWIG may generate some additional files depending on the target language. By default, an input file with the name file.i is transformed into a file file_wrap.c or file_wrap.cxx (depending on whether or not the -c++ option has been used). The name of the output file can be changed using the -o option. In certain cases, file suffixes are used by the compiler to determine the source language (C, C++, etc.). Therefore, you have to use the -o option to change the suffix of the SWIG-generated wrapper file if you want something different than the default. For example:

$ swig -c++ -python -o example_wrap.cpp example.i

The C/C++ output file created by SWIG often contains everything that is needed to construct a extension module for the target scripting language. SWIG is not a stub compiler nor is it usually necessary to edit the output file (and if you look at the output, you probably won't want to). To build the final extension module, the SWIG output file is compiled and linked with the rest of your C/C++ program to create a shared library.

Many target languages will also generate proxy class files in the target language. The default output directory for these language specific files is the same directory as the generated C/C++ file. This can can be modified using the -outdir option. For example:

$ swig -c++ -python -outdir pyfiles -o cppfiles/example_wrap.cpp example.i

If the directories cppfiles and pyfiles exist, the following will be generated:

cppfiles/example_wrap.cpp
pyfiles/example.py

5.1.3 Comments

C and C++ style comments may appear anywhere in interface files. In previous versions of SWIG, comments were used to generate documentation files. However, this feature is currently under repair and will reappear in a later SWIG release.

5.1.4 C Preprocessor

Like C, SWIG preprocesses all input files through an enhanced version of the C preprocessor. All standard preprocessor features are supported including file inclusion, conditional compilation and macros. However, #include statements are ignored unless the -includeall command line option has been supplied. The reason for disabling includes is that SWIG is sometimes used to process raw C header files. In this case, you usually only want the extension module to include functions in the supplied header file rather than everything that might be included by that header file (i.e., system headers, C library functions, etc.).

It should also be noted that the SWIG preprocessor skips all text enclosed inside a %{...%} block. In addition, the preprocessor includes a number of macro handling enhancements that make it more powerful than the normal C preprocessor. These extensions are described in the "Preprocessor" chapter.

5.1.5 SWIG Directives

Most of SWIG's operation is controlled by special directives that are always preceded by a "%" to distinguish them from normal C declarations. These directives are used to give SWIG hints or to alter SWIG's parsing behavior in some manner.

Since SWIG directives are not legal C syntax, it is generally not possible to include them in header files. However, SWIG directives can be included in C header files using conditional compilation like this:

/* header.h  --- Some header file */

/* SWIG directives -- only seen if SWIG is running */ 
#ifdef SWIG
%module foo
#endif

SWIG is a special preprocessing symbol defined by SWIG when it is parsing an input file.

5.1.6 Parser Limitations

Although SWIG can parse most C/C++ declarations, it does not provide a complete C/C++ parser implementation. Most of these limitations pertain to very complicated type declarations and certain advanced C++ features. Specifically, the following features are not currently supported:

In the event of a parsing error, conditional compilation can be used to skip offending code. For example:

#ifndef SWIG
... some bad declarations ...
#endif

Alternatively, you can just delete the offending code from the interface file.

One of the reasons why SWIG does not provide a full C++ parser implementation is that it has been designed to work with incomplete specifications and to be very permissive in its handling of C/C++ datatypes (e.g., SWIG can generate interfaces even when there are missing class declarations or opaque datatypes). Unfortunately, this approach makes it extremely difficult to implement certain parts of a C/C++ parser as most compilers use type information to assist in the parsing of more complex declarations (for the truly curious, the primary complication in the implementation is that the SWIG parser does not utilize a separate typedef-name terminal symbol as described on p. 234 of K&R).

5.2 Wrapping Simple C Declarations

SWIG wraps simple C declarations by creating an interface that closely matches the way in which the declarations would be used in a C program. For example, consider the following interface file:

%module example

%inline %{
extern double sin(double x);
extern int strcmp(const char *, const char *);
extern int Foo;
%}
#define STATUS 50
#define VERSION "1.1"

In this file, there are two functions sin() and strcmp(), a global variable Foo, and two constants STATUS and VERSION. When SWIG creates an extension module, these declarations are accessible as scripting language functions, variables, and constants respectively. For example, in Tcl:

% sin 3
5.2335956
% strcmp Dave Mike
-1
% puts $Foo
42
% puts $STATUS
50
% puts $VERSION
1.1

Or in Python:

>>> example.sin(3)
5.2335956
>>> example.strcmp('Dave','Mike')
-1
>>> print example.cvar.Foo
42
>>> print example.STATUS
50
>>> print example.VERSION
1.1

Whenever possible, SWIG creates an interface that closely matches the underlying C/C++ code. However, due to subtle differences between languages, run-time environments, and semantics, it is not always possible to do so. The next few sections describes various aspects of this mapping.

5.2.1 Basic Type Handling

In order to build an interface, SWIG has to convert C/C++ datatypes to equivalent types in the target language. Generally, scripting languages provide a more limited set of primitive types than C. Therefore, this conversion process involves a certain amount of type coercion.

Most scripting languages provide a single integer type that is implemented using the int or long datatype in C. The following list shows all of the C datatypes that SWIG will convert to and from integers in the target language:

int
short
long
unsigned
signed
unsigned short
unsigned long
unsigned char
signed char
bool

When an integral value is converted from C, a cast is used to convert it to the representation in the target language. Thus, a 16 bit short in C may be promoted to a 32 bit integer. When integers are converted in the other direction, the value is cast back into the original C type. If the value is too large to fit, it is silently truncated.

unsigned char and signed char are special cases that are handled as small 8-bit integers. Normally, the char datatype is mapped as a one-character ASCII string.

The bool datatype is cast to and from an integer value of 0 and 1 unless the target language provides a special boolean type.

Some care is required when working with large integer values. Most scripting languages use 32-bit integers so mapping a 64-bit long integer may lead to truncation errors. Similar problems may arise with 32 bit unsigned integers (which may appear as large negative numbers). As a rule of thumb, the int datatype and all variations of char and short datatypes are safe to use. For unsigned int and long datatypes, you will need to carefully check the correct operation of your program after it has been wrapped with SWIG.

Although the SWIG parser supports the long long datatype, not all language modules support it. This is because long long usually exceeds the integer precision available in the target language. In certain modules such as Tcl and Perl5, long long integers are encoded as strings. This allows the full range of these numbers to be represented. However, it does not allow long long values to be used in arithmetic expressions. It should also be noted that although long long is part of the ISO C99 standard, it is not universally supported by all C compilers. Make sure you are using a compiler that supports long long before trying to use this type with SWIG.

SWIG recognizes the following floating point types :

float
double

Floating point numbers are mapped to and from the natural representation of floats in the target language. This is almost always a C double. The rarely used datatype of long double is not supported by SWIG.

The char datatype is mapped into a NULL terminated ASCII string with a single character. When used in a scripting language it shows up as a tiny string containing the character value. When converting the value back into C, SWIG takes a character string from the scripting language and strips off the first character as the char value. Thus if the value "foo" is assigned to a char datatype, it gets the value `f'.

The char * datatype is handled as a NULL-terminated ASCII string. SWIG maps this into a 8-bit character string in the target scripting language. SWIG converts character strings in the target language to NULL terminated strings before passing them into C/C++. The default handling of these strings does not allow them to have embedded NULL bytes. Therefore, the char * datatype is not generally suitable for passing binary data. However, it is possible to change this behavior by defining a SWIG typemap. See the chapter on Typemaps for details about this.

At this time, SWIG does not provide any special support for Unicode or wide-character strings (the C wchar_t type). This is a delicate topic that is poorly understood by many programmers and not implemented in a consistent manner across languages. For those scripting languages that provide Unicode support, Unicode strings are often available in an 8-bit representation such as UTF-8 that can be mapped to the char * type (in which case the SWIG interface will probably work). If the program you are wrapping uses Unicode, there is no guarantee that Unicode characters in the target language will use the same internal representation (e.g., UCS-2 vs. UCS-4). You may need to write some special conversion functions.

5.2.2 Global Variables

Whenever possible, SWIG maps C/C++ global variables into scripting language variables. For example,

%module example
double foo;

results in a scripting language variable like this:

# Tcl
set foo [3.5]                   ;# Set foo to 3.5
puts $foo                       ;# Print the value of foo

# Python
cvar.foo = 3.5                  # Set foo to 3.5
print cvar.foo                  # Print value of foo

# Perl
$foo = 3.5;                     # Set foo to 3.5
print $foo,"\n";                # Print value of foo

# Ruby
Module.foo = 3.5               # Set foo to 3.5
print Module.foo, "\n"         # Print value of foo

Whenever the scripting language variable is used, the underlying C global variable is accessed. Although SWIG makes every attempt to make global variables work like scripting language variables, it is not always possible to do so. For instance, in Python, all global variables must be accessed through a special variable object known as cvar (shown above). In Ruby, variables are accessed as attributes of the module. Other languages may convert variables to a pair of accessor functions. For example, the Java module generates a pair of functions double get_foo() and set_foo(double val) that are used to manipulate the value.

Finally, if a global variable has been declared as const, it only supports read-only access. Note: this behavior is new to SWIG-1.3. Earlier versions of SWIG incorrectly handled const and created constants instead.

5.2.3 Constants

Constants can be created using #define, enumerations, or a special %constant directive. The following interface file shows a few valid constant declarations :

#define I_CONST       5               // An integer constant
#define PI            3.14159         // A Floating point constant
#define S_CONST       "hello world"   // A string constant
#define NEWLINE       '\n'            // Character constant

enum boolean {NO=0, YES=1};
enum months {JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG,
             SEP, OCT, NOV, DEC};
%constant double BLAH = 42.37;
#define F_CONST (double) 5            // A floating pointer constant with cast
#define PI_4 PI/4
#define FLAGS 0x04 | 0x08 | 0x40

In #define declarations, the type of a constant is inferred by syntax. For example, a number with a decimal point is assumed to be floating point. In addition, SWIG must be able to fully resolve all of the symbols used in a #define in order for a constant to actually be created. This restriction is necessary because #define is also used to define preprocessor macros that are definitely not meant to be part of the scripting language interface. For example:

#define EXTERN extern

EXTERN void foo();

In this case, you probably don't want to create a constant called EXTERN (what would the value be?). In general, SWIG will not create constants for macros unless the value can be completely determined by the preprocessor. For instance, in the above example, the declaration

#define PI_4  PI/4

defines a constant because PI was already defined as a constant and the value is known.

The use of constant expressions is allowed, but SWIG does not evaluate them. Rather, it passes them through to the output file and lets the C compiler perform the final evaluation (SWIG does perform a limited form of type-checking however).

For enumerations, it is critical that the original enum definition be included somewhere in the interface file (either in a header file or in the %{,%} block). SWIG only translates the enumeration into code needed to add the constants to a scripting language. It needs the original enumeration declaration in order to get the correct enum values as assigned by the C compiler.

The %constant directive is used to more precisely create constants corresponding to different C datatypes. Although it is not usually not needed for simple values, it is more useful when working with pointers and other more complex datatypes. Typically, %constant is only used when you want to add constants to the scripting language interface that are not defined in the original header file.

5.2.4 A brief word about const

A common confusion with C programming is the semantic meaning of the const qualifier in declarations--especially when it is mixed with pointers and other type modifiers. In fact, previous versions of SWIG handled const incorrectly--a situation that SWIG-1.3.7 and newer releases have fixed.

Starting with SWIG-1.3, all variable declarations, regardless of any use of const, are wrapped as global variables. If a declaration happens to be declared as const, it is wrapped as a read-only variable. To tell if a variable is const or not, you need to look at the right-most occurrence of the const qualifier (that appears before the variable name). If the right-most const occurs after all other type modifiers (such as pointers), then the variable is const. Otherwise, it is not.

Here are some examples of const declarations.

const char a;           // A constant character
char const b;           // A constant character (the same)
char *const c;          // A constant pointer to a character
const char *const d;    // A constant pointer to a constant character

Here is an example of a declaration that is not const:

const char *e;          // A pointer to a constant character.  The pointer
                        // may be modified.

In this case, the pointer e can change---it's only the value being pointed to that is read-only.

Compatibility Note: One reason for changing SWIG to handle const declarations as read-only variables is that there are many situations where the value of a const variable might change. For example, a library might export a symbol as const in its public API to discourage modification, but still allow the value to change through some other kind of internal mechanism. Furthermore, programmers often overlook the fact that with a constant declaration like char *const, the underlying data being pointed to can be modified--it's only the pointer itself that is constant. In an embedded system, a const declaration might refer to a read-only memory address such as the location of a memory-mapped I/O device port (where the value changes, but writing to the port is not supported by the hardware). Rather than trying to build a bunch of special cases into the const qualifier, the new interpretation of const as "read-only" is simple and exactly matches the actual semantics of const in C/C++. If you really want to create a constant as in older versions of SWIG, use the %constant directive instead. For example:

%constant double PI = 3.14159;

or

#ifdef SWIG
#define const %constant
#endif
const double foo = 3.4;
const double bar = 23.4;
const int    spam = 42;
#ifdef SWIG
#undef const
#endif
...

5.2.5 A cautionary tale of char *

Before going any further, there is one bit of caution involving char * that must now be mentioned. When strings are passed from a scripting language to a C char *, the pointer usually points to string data stored inside the interpreter. It is almost always a really bad idea to modify this data. Furthermore, some languages may explicitly disallow it. For instance, in Python, strings are supposed be immutable. If you violate this, you will probably receive a vast amount of wrath when you unleash your module on the world.

The primary source of problems are functions that might modify string data in place. A classic example would be a function like this:

char *strcat(char *s, const char *t)

Although SWIG will certainly generate a wrapper for this, its behavior will be undefined. In fact, it will probably cause your application to crash with a segmentation fault or other memory related problem. This is because s refers to some internal data in the target language---data that you shouldn't be touching.

The bottom line: don't rely on char * for anything other than read-only input values. However, it must be noted that you could change the behavior of SWIG using typemaps.

5.3 Pointers and complex objects

Most C programs manipulate arrays, structures, and other types of objects. This section discusses the handling of these datatypes.

5.3.1 Simple pointers

Pointers to primitive C datatypes such as

int *
double ***
char **

are fully supported by SWIG. Rather than trying to convert the data being pointed to into a scripting representation, SWIG simply encodes the pointer itself into a representation that contains the actual value of the pointer and a type-tag. Thus, the SWIG representation of the above pointers (in Tcl), might look like this:

_10081012_p_int
_1008e124_ppp_double
_f8ac_pp_char

A NULL pointer is represented by the string "NULL" or the value 0 encoded with type information.

All pointers are treated as opaque objects by SWIG. Thus, a pointer may be returned by a function and passed around to other C functions as needed. For all practical purposes, the scripting language interface works in exactly the same way as you would use the pointer in a C program. The only difference is that there is no mechanism for dereferencing the pointer since this would require the target language to understand the memory layout of the underlying object.

The scripting language representation of a pointer value should never be manipulated directly. Even though the values shown look like hexadecimal addresses, the numbers used may differ from the actual machine address (e.g., on little-endian machines, the digits may appear in reverse order). Furthermore, SWIG does not normally map pointers into high-level objects such as associative arrays or lists (for example, converting an int * into an list of integers). There are several reasons why SWIG does not do this:

5.3.2 Run time pointer type checking

By allowing pointers to be manipulated from a scripting language, extension modules effectively bypass compile-time type checking in the C/C++ compiler. To prevent errors, a type signature is encoded into all pointer values and is used to perform run-time type checking. This type-checking process is an integral part of SWIG and can not be disabled or modified without using typemaps (described in later chapters).

Like C, void * matches any kind of pointer. Furthermore, NULL pointers can be passed to any function that expects to receive a pointer. Although this has the potential to cause a crash, NULL pointers are also sometimes used as sentinel values or to denote a missing/empty value. Therefore, SWIG leaves NULL pointer checking up to the application.

5.3.3 Derived types, structs, and classes

For everything else (structs, classes, arrays, etc...) SWIG applies a very simple rule :

Everything else is a pointer

In other words, SWIG manipulates everything else by reference. This model makes sense because most C/C++ programs make heavy use of pointers and SWIG can use the type-checked pointer mechanism already present for handling pointers to basic datatypes.

Although this probably sounds complicated, it's really quite simple. Suppose you have an interface file like this :

%module fileio
FILE *fopen(char *, char *);
int fclose(FILE *);
unsigned fread(void *ptr, unsigned size, unsigned nobj, FILE *);
unsigned fwrite(void *ptr, unsigned size, unsigned nobj, FILE *);
void *malloc(int nbytes);
void free(void *);

In this file, SWIG doesn't know what a FILE is, but since it's used as a pointer, so it doesn't really matter what it is. If you wrapped this module into Python, you can use the functions just like you expect :

# Copy a file 
def filecopy(source,target):
	f1 = fopen(source,"r")
	f2 = fopen(target,"w")
	buffer = malloc(8192)
	nbytes = fread(buffer,8192,1,f1)
	while (nbytes > 0):
		fwrite(buffer,8192,1,f2)
		nbytes = fread(buffer,8192,1,f1)
	free(buffer)

In this case f1, f2, and buffer are all opaque objects containing C pointers. It doesn't matter what value they contain--our program works just fine without this knowledge.

5.3.4 Undefined datatypes

When SWIG encounters an undeclared datatype, it automatically assumes that it is a structure or class. For example, suppose the following function appeared in a SWIG input file:

void matrix_multiply(Matrix *a, Matrix *b, Matrix *c);

SWIG has no idea what a "Matrix" is. However, it is obviously a pointer to something so SWIG generates a wrapper using its generic pointer handling code.

Unlike C or C++, SWIG does not actually care whether Matrix has been previously defined in the interface file or not. This allows SWIG to generate interfaces from only partial or limited information. In some cases, you may not care what a Matrix really is as long as you can pass an opaque reference to one around in the scripting language interface.

An important detail to mention is that SWIG will gladly generate wrappers for an interface when there are unspecified type names. However, all unspecified types are internally handled as pointers to structures or classes! For example, consider the following declaration:

void foo(size_t num);

If size_t is undeclared, SWIG generates wrappers that expect to receive a type of size_t * (this mapping is described shortly). As a result, the scripting interface might behave strangely. For example:

foo(40);
TypeError: expected a _p_size_t.

The only way to fix this problem is to make sure you properly declare type names using typedef.

5.3.5 Typedef

Like C, typedef can be used to define new type names in SWIG. For example:

typedef unsigned int size_t;

typedef definitions appearing in a SWIG interface are not propagated to the generated wrapper code. Therefore, they either need to be defined in an included header file or placed in the declarations section like this:

%{
/* Include in the generated wrapper file */
typedef unsigned int size_t;
%}
/* Tell SWIG about it */
typedef unsigned int size_t;

or

%inline %{
typedef unsigned int size_t;
%}

In certain cases, you might be able to include other header files to collect type information. For example:

%module example
%import "sys/types.h"

In this case, you might run SWIG as follows:

$ swig -I/usr/include -includeall example.i

It should be noted that your mileage will vary greatly here. System headers are notoriously complicated and may rely upon a variety of non-standard C coding extensions (e.g., such as special directives to GCC). Unless you exactly specify the right include directories and preprocessor symbols, this may not work correctly (you will have to experiment).

SWIG tracks typedef declarations and uses this information for run-time type checking. For instance, if you use the above typedef and had the following function declaration:

void foo(unsigned int *ptr);

The corresponding wrapper function will accept arguments of type unsigned int * or size_t *.

5.4 Other Practicalities

So far, this chapter has presented almost everything you need to know to use SWIG for simple interfaces. However, some C programs use idioms that are somewhat more difficult to map to a scripting language interface. This section describes some of these issues.

5.4.1 Passing structures by value

Sometimes a C function takes structure parameters that are passed by value. For example, consider the following function:

double dot_product(Vector a, Vector b);

To deal with this, SWIG transforms the function to use pointers by creating a wrapper equivalent to the following:

double wrap_dot_product(Vector *a, Vector *b) {
    Vector x = *a;
    Vector y = *b;
    return dot_product(x,y);
}

In the target language, the dot_product() function now accepts pointers to Vectors instead of Vectors. For the most part, this transformation is transparent so you might not notice.

5.4.2 Return by value

C functions that return structures or classes datatypes by value are more difficult to handle. Consider the following function:

Vector cross_product(Vector v1, Vector v2);

This function wants to return Vector, but SWIG only really supports pointers. As a result, SWIG creates a wrapper like this:

Vector *wrap_cross_product(Vector *v1, Vector *v2) {
        Vector x = *v1;
        Vector y = *v2;
        Vector *result;
        result = (Vector *) malloc(sizeof(Vector));
        *(result) = cross(x,y);
        return result;
}

or if SWIG was run with the -c++ option:

Vector *wrap_cross(Vector *v1, Vector *v2) {
        Vector x = *v1;
        Vector y = *v2;
        Vector *result = new Vector(cross(x,y)); // Uses default copy constructor
        return result;
}

In both cases, SWIG allocates a new object and returns a reference to it. It is up to the user to delete the returned object when it is no longer in use. Clearly, this will leak memory if you are unaware of the implicit memory allocation and don't take steps to free the result. That said, it should be noted that some language modules can now automatically track newly created objects and reclaim memory for you. Consult the documentation for each language module for more details.

It should also be noted that the handling of pass/return by value in C++ has some special cases. For example, the above code fragments don't work correctly if Vector doesn't define a default constructor. The section on SWIG and C++ has more information about this case.

5.4.3 Linking to structure variables

When global variables or class members involving structures are encountered, SWIG handles them as pointers. For example, a global variable like this

Vector unit_i;

gets mapped to an underlying pair of set/get functions like this :

Vector *unit_i_get() {
	return &unit_i;
}
void unit_i_set(Vector *value) {
	unit_i = *value;
}

Again some caution is in order. A global variable created in this manner will show up as a pointer in the target scripting language. It would be an extremely bad idea to free or destroy such a pointer. Also, C++ classes must supply a properly defined copy constructor in order for assignment to work correctly.

5.4.4 Linking to char *

When a global variable of type char * appears, SWIG uses malloc() or new to allocate memory for the new value. Specifically, if you have a variable like this

char *foo;

SWIG generates the following code:

/* C mode */
void foo_set(char *value) {
   if (foo) free(foo);
   foo = (char *) malloc(strlen(value)+1);
   strcpy(foo,value);
}

/* C++ mode.  When -c++ option is used */
void foo_set(char *value) {
   if (foo) delete [] foo;
   foo = new char[strlen(value)+1];
   strcpy(foo,value);
}

If this is not the behavior that you want, consider making the variable read-only using the %immutable directive. Alternatively, you might write a short assist-function to set the value exactly like you want. For example:

%inline %{
  void set_foo(char *value) {
       strncpy(foo,value, 50);
   }
%}

Note: If you write an assist function like this, you will have to call it as a function from the target scripting language (it does not work like a variable). For example, in Python you will have to write:

>>> set_foo("Hello World")

A common mistake with char * variables is to link to a variable declared like this:

char *VERSION = "1.0";

In this case, the variable will be readable, but any attempt to change the value results in a segmentation or general protection fault. This is due to the fact that SWIG is trying to release the old value using free or delete when the string literal value currently assigned to the variable wasn't allocated using malloc() or new. To fix this behavior, you can either mark the variable as read-only, write a typemap (as described in Chapter 6), or write a special set function as shown. Another alternative is to declare the variable as an array:

char VERSION[64] = "1.0";

When variables of type const char * are declared, SWIG still generates functions for setting and getting the value. However, the default behavior does not release the previous contents (resulting in a possible memory leak). In fact, you may get a warning message such as this when wrapping such a variable:

example.i:20. Typemap warning. Setting const char * variable may leak memory

The reason for this behavior is that const char * variables are often used to point to string literals. For example:

const char *foo = "Hello World\n";

Therefore, it's a really bad idea to call free() on such a pointer. On the other hand, it is legal to change the pointer to point to some other value. When setting a variable of this type, SWIG allocates a new string (using malloc or new) and changes the pointer to point to the new value. However, repeated modifications of the value will result in a memory leak since the old value is not released.

5.4.5 Arrays

Arrays are fully supported by SWIG, but they are always handled as pointers instead of mapping them to a special array object or list in the target language. Thus, the following declarations :

int foobar(int a[40]);
void grok(char *argv[]);
void transpose(double a[20][20]);

are processed as if they were really declared like this:

int foobar(int *a);
void grok(char **argv);
void transpose(double (*a)[20]);

Like C, SWIG does not perform array bounds checking. It is up to the user to make sure the pointer points a suitably allocated region of memory.

Multi-dimensional arrays are transformed into a pointer to an array of one less dimension. For example:

int [10];         // Maps to int *
int [10][20];     // Maps to int (*)[20]
int [10][20][30]; // Maps to int (*)[20][30]

It is important to note that in the C type system, a multidimensional array a[][] is NOT equivalent to a single pointer *a or a double pointer such as **a. Instead, a pointer to an array is used (as shown above) where the actual value of the pointer is the starting memory location of the array. The reader is strongly advised to dust off their C book and re-read the section on arrays before using them with SWIG.

Array variables are supported, but are read-only by default. For example:

int   a[100][200];

In this case, reading the variable 'a' returns a pointer of type int (*)[200] that points to the first element of the array &a[0][0]. Trying to modify 'a' results in an error. This is because SWIG does not know how to copy data from the target language into the array. To work around this limitation, you may want to write a few simple assist functions like this:

%inline %{
void a_set(int i, int j, int val) {
   a[i][j] = val;
}
int a_get(int i, int j) {
   return a[i][j];
}
%}

To dynamically create arrays of various sizes and shapes, it may be useful to write some helper functions in your interface. For example:

// Some array helpers
%inline %{
  /* Create any sort of [size] array */
  int *int_array(int size) {
     return (int *) malloc(size*sizeof(int));
  }
  /* Create a two-dimension array [size][10] */
  int (*int_array_10(int size))[10] {
     return (int (*)[10]) malloc(size*10*sizeof(int));
  }
%}

Arrays of char are handled as a special case by SWIG. In this case, strings in the target language can be stored in the array. For example, if you have a declaration like this,

char pathname[256];

SWIG generates functions for both getting and setting the value that are equivalent to the following code:

char *pathname_get() {
   return pathname;
}
void pathname_set(char *value) {
   strncpy(pathname,value,256);
}

In the target language, the value can be set like a normal variable.

5.4.6 Creating read-only variables

A read-only variable can be created by using the %immutable directive as shown :

// File : interface.i

int 	a; 			// Can read/write
%immutable;
int	b,c,d			// Read only variables
%mutable;
double	x,y			// read/write

The %immutable directive enables read-only mode until it is explicitly disabled using the %mutable directive. As an alternative to turning read-only mode off and on like this, individual declarations can also be tagged as immutable. For example:

%immutable x;                   // Make x read-only
...
double x;                       // Read-only (from earlier %immutable directive)
double y;                       // Read-write
...

The %mutable and %immutable directives are actually %feature directives defined like this:

#define %immutable   %feature("immutable")
#define %mutable     %feature("immutable","")

If you wanted to make all wrapped variables read-only, barring one or two, it might be easier to take this approach:

%immutable;                     // Make all variables read-only
%feature("immutable","0") x;    // except, make x read/write
...
double x;
double y;
double z;
...

Read-only variables are also created when declarations are declared as const. For example:

const int foo;               /* Read only variable */
char * const version="1.0";  /* Read only variable */

Compatibility note: Read-only access used to be controlled by a pair of directives %readonly and %readwrite. Although these directives still work, they generate a warning message. Simply change the directives to %immutable; and %mutable; to silence the warning. Don't forget the extra semicolon!

5.4.7 Renaming and ignoring declarations

Normally, the name of a C declaration is used when that declaration is wrapped into the target language. However, this may generate a conflict with a keyword or already existing function in the scripting language. To resolve a name conflict, you can use the %rename directive as shown :

// interface.i

%rename(my_print) print;
extern void print(char *);

%rename(foo) a_really_long_and_annoying_name;
extern int a_really_long_and_annoying_name;

SWIG still calls the correct C function, but in this case the function print() will really be called "my_print()" in the target language.

The placement of the %rename directive is arbitrary as long as it appears before the declarations to be renamed. A common technique is to write code for wrapping a header file like this:

// interface.i

%rename(my_print) print;
%rename(foo) a_really_long_and_annoying_name;

%include "header.h"

%rename applies a renaming operation to all future occurrences of a name. The renaming applies to functions, variables, class and structure names, member functions, and member data. For example, if you had two-dozen C++ classes, all with a member function named `print' (which is a keyword in Python), you could rename them all to `output' by specifying :

%rename(output) print; // Rename all `print' functions to `output'

SWIG does not normally perform any checks to see if the functions it wraps are already defined in the target scripting language. However, if you are careful about namespaces and your use of modules, you can usually avoid these problems.

Closely related to %rename is the %ignore directive. %ignore instructs SWIG to ignore declarations that match a given identifier. For example:

%ignore print;         // Ignore all declarations named print
%ignore _HAVE_FOO_H;   // Ignore an include guard constant
...
%include "foo.h"       // Grab a header file
...

Any function, variable etc which matches %ignore will not be wrapped and therefore will not be available from the target language. A common usage of %ignore is to selectively remove certain declarations from a header file without having to add conditional compilation to the header. However, it should be stressed that this only works for simple declarations. If you need to remove a whole section of problematic code, the SWIG preprocessor should be used instead.

More powerful variants of %rename and %ignore directives can be used to help wrap C++ overloaded functions and methods or C++ methods which use default arguments. This is described in the Ambiguity resolution and renaming section in the C++ chapter.

Compatibility note: Older versions of SWIG provided a special %name directive for renaming declarations. For example:

%name(output) extern void print(char *);

This directive is still supported, but it is deprecated and should probably be avoided. The %rename directive is more powerful and better supports wrapping of raw header file information.

5.4.8 Default/optional arguments

SWIG supports default arguments in both C and C++ code. For example:

int plot(double x, double y, int color=WHITE);

In this case, SWIG generates wrapper code where the default arguments are optional in the target language. For example, this function could be used in Tcl as follows :

% plot -3.4 7.5 				# Use default value
% plot -3.4 7.5 10				# set color to 10 instead

Although the ANSI C standard does not allow default arguments, default arguments specified in a SWIG interface work with both C and C++.

Note: There is a subtle semantic issue concerning the use of default arguments and the SWIG generated wrapper code. When default arguments are used in C code, the default values are emitted into the wrappers and the function is invoked with a full set of arguments. This is different to when wrapping C++ where an overloaded wrapper method is generated for each defaulted argument. Please refer to the section on default arguments in the C++ chapter for further details.

5.4.9 Pointers to functions and callbacks

Occasionally, a C library may include functions that expect to receive pointers to functions--possibly to serve as callbacks. SWIG provides full support for function pointers provided that the callback functions are defined in C and not in the target language. For example, consider a function like this:

int binary_op(int a, int b, int (*op)(int,int));

When you first wrap something like this into an extension module, you may find the function to be impossible to use. For instance, in Python:

>>> def add(x,y):
...     return x+y
...
>>> binary_op(3,4,add)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: Type error. Expected _p_f_int_int__int
>>>

The reason for this error is that SWIG doesn't know how to map a scripting language function into a C callback. However, existing C functions can be used as arguments provided you install them as constants. One way to do this is to use the %constant directive like this:

/* Function with a callback */
int binary_op(int a, int b, int (*op)(int,int));

/* Some callback functions */
%constant int add(int,int);
%constant int sub(int,int);
%constant int mul(int,int);

In this case, add, sub, and mul become function pointer constants in the target scripting language. This allows you to use them as follows:

>>> binary_op(3,4,add)
7
>>> binary_op(3,4,mul)
12
>>>

Unfortunately, by declaring the callback functions as constants, they are no longer accessible as functions. For example:

>>> add(3,4)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: object is not callable: '_ff020efc_p_f_int_int__int'
>>>

If you want to make a function available as both a callback function and a function, you can use the %callback and %nocallback directives like this:

/* Function with a callback */
int binary_op(int a, int b, int (*op)(int,int));

/* Some callback functions */
%callback("%s_cb")
int add(int,int);
int sub(int,int);
int mul(int,int);
%nocallback

The argument to %callback is a printf-style format string that specifies the naming convention for the callback constants (%s gets replaced by the function name). The callback mode remains in effect until it is explicitly disabled using %nocallback. When you do this, the interface now works as follows:

>>> binary_op(3,4,add_cb)
7
>>> binary_op(3,4,mul_cb)
12
>>> add(3,4)
7
>>> mul(3,4)
12

Notice that when the function is used as a callback, special names such as add_cb is used instead. To call the function normally, just use the original function name such as add().

SWIG provides a number of extensions to standard C printf formatting that may be useful in this context. For instance, the following variation installs the callbacks as all upper-case constants such as ADD, SUB, and MUL:

/* Some callback functions */
%callback("%(upper)s")
int add(int,int);
int sub(int,int);
int mul(int,int);
%nocallback

A format string of "%(lower)s" converts all characters to lower-case. A string of "%(title)s" capitalizes the first character and converts the rest to lower case.

And now, a final note about function pointer support. Although SWIG does not normally allow callback functions to be written in the target language, this can be accomplished with the use of typemaps and other advanced SWIG features. This is described in a later chapter.

5.5 Structures and unions

This section describes the behavior of SWIG when processing ANSI C structures and union declarations. Extensions to handle C++ are described in the next section.

If SWIG encounters the definition of a structure or union, it creates a set of accessor functions. Although SWIG does not need structure definitions to build an interface, providing definitions make it possible to access structure members. The accessor functions generated by SWIG simply take a pointer to an object and allow access to an individual member. For example, the declaration :

struct Vector {
	double x,y,z;
}

gets transformed into the following set of accessor functions :

double Vector_x_get(struct Vector *obj) {
	return obj->x;
}
double Vector_y_get(struct Vector *obj) { 
	return obj->y;
}
double Vector_z_get(struct Vector *obj) { 
	return obj->z;
}
void Vector_x_set(struct Vector *obj, double value) {
	obj->x = value;
}
void Vector_y_set(struct Vector *obj, double value) {
	obj->y = value;
}
void Vector_z_set(struct Vector *obj, double value) {
	obj->z = value;
}

In addition, SWIG creates default constructor and destructor functions if none are defined in the interface. For example:

struct Vector *new_Vector() {
    return (Vector *) calloc(1,sizeof(struct Vector));
}
void delete_Vector(struct Vector *obj) {
    free(obj);
}

Using these low-level accessor functions, an object can be minimally manipulated from the target language using code like this:

v = new_Vector()
Vector_x_set(v,2)
Vector_y_set(v,10)
Vector_z_set(v,-5)
...
delete_Vector(v)

However, most of SWIG's language modules also provide a high-level interface that is more convenient. Keep reading.

5.5.1 Typedef and structures

SWIG supports the following construct which is quite common in C programs :

typedef struct {
	double x,y,z;
} Vector;

When encountered, SWIG assumes that the name of the object is `Vector' and creates accessor functions like before. The only difference is that the use of typedef allows SWIG to drop the struct keyword on its generated code. For example:

double Vector_x_get(Vector *obj) {
	return obj->x;
}

If two different names are used like this :

typedef struct vector_struct {
	double x,y,z;
} Vector;

the name Vector is used instead of vector_struct since this is more typical C programming style. If declarations defined later in the interface use the type struct vector_struct, SWIG knows that this is the same as Vector and it generates the appropriate type-checking code.

5.5.2 Character strings and structures

Structures involving character strings require some care. SWIG assumes that all members of type char * have been dynamically allocated using malloc() and that they are NULL-terminated ASCII strings. When such a member is modified, the previously contents will be released, and the new contents allocated. For example :

%module mymodule
...
struct Foo {
	char *name;
	...
}

This results in the following accessor functions :

char *Foo_name_get(Foo *obj) {
	return Foo->name;
}

char *Foo_name_set(Foo *obj, char *c) {
	if (obj->name) free(obj->name);
	obj->name = (char *) malloc(strlen(c)+1);
	strcpy(obj->name,c);
	return obj->name;
}

If this behavior differs from what you need in your applications, the SWIG "memberin" typemap can be used to change it. See the typemaps chapter for further details.

Note: If the -c++ option is used, new and delete are used to perform memory allocation.

5.5.3 Array members

Arrays may appear as the members of structures, but they will be read-only. SWIG will write an accessor function that returns the pointer to the first element of the array, but will not write a function to change the contents of the array itself. When this situation is detected, SWIG may generate a warning message such as the following :

interface.i:116. Warning. Array member will be read-only

To eliminate the warning message, typemaps can be used, but this is discussed in a later chapter. In many cases, the warning message is harmless.

5.5.4 Structure data members

Occasionally, a structure will contain data members that are themselves structures. For example:

typedef struct Foo {
   int x;
} Foo;

typedef struct Bar {
   int y;
   Foo f;           /* struct member */
} Bar;

When a structure member is wrapped, it is handled as a pointer, unless the %naturalvar directive is used where it is handled more like a C++ reference (see C++ Member data). The accessors to the member variable as a pointer is effectively wrapped as follows:

Foo *Bar_f_get(Bar *b) {
   return &b->f;
}
void Bar_f_set(Bar *b, Foo *value) {
   b->f = *value;
}

The reasons for this are somewhat subtle but have to do with the problem of modifying and accessing data inside the data member. For example, suppose you wanted to modify the value of f.x of a Bar object like this:

Bar *b;
b->f.x = 37;

Translating this assignment to function calls (as would be used inside the scripting language interface) results in the following code:

Bar *b;
Foo_x_set(Bar_f_get(b),37);

In this code, if the Bar_f_get() function were to return a Foo instead of a Foo *, then the resulting modification would be applied to a copy of f and not the data member f itself. Clearly that's not what you want!

It should be noted that this transformation to pointers only occurs if SWIG knows that a data member is a structure or class. For instance, if you had a structure like this,

struct Foo {
   WORD   w;
};

and nothing was known about WORD, then SWIG will generate more normal accessor functions like this:

WORD Foo_w_get(Foo *f) {
    return f->w;
}
void Foo_w_set(FOO *f, WORD value) {
    f->w = value;
}

Compatibility Note: SWIG-1.3.11 and earlier releases transformed all non-primitive member datatypes to pointers. Starting in SWIG-1.3.12, this transformation only occurs if a datatype is known to be a structure, class, or union. This is unlikely to break existing code. However, if you need to tell SWIG that an undeclared datatype is really a struct, simply use a forward struct declaration such as "struct Foo;".

5.5.5 C constructors and destructors

When wrapping structures, it is generally useful to have a mechanism for creating and destroying objects. If you don't do anything, SWIG will automatically generate functions for creating and destroying objects using malloc() and free(). Note: the use of malloc() only applies when SWIG is used on C code (i.e., when the -c++ option is not supplied on the command line). C++ is handled differently.

If you don't want SWIG to generate default constructors for your interfaces, you can use the %nodefaultctor directive or the -nodefaultctor command line option. For example:

swig -nodefaultctor example.i 

or

%module foo
...
%nodefaultctor;        // Don't create default constructors
... declarations ...
%clearnodefaultctor;   // Re-enable default constructors

If you need more precise control, %nodefaultctor can selectively target individual structure definitions. For example:

%nodefaultctor Foo;      // No default constructor for Foo
...
struct Foo {             // No default constructor generated.
};

struct Bar {             // Default constructor generated.
};

Since ignoring the implicit or default destructors most of the times produce memory leaks, SWIG will always try to generate them. If needed, however, you can selectively disable the generation of the default/implicit destructor by using %nodefaultdtor

%nodefaultdtor Foo; // No default/implicit destructor for Foo
...
struct Foo {              // No default destructor is generated.
};

struct Bar {              // Default destructor generated.
};

Compatibility note: Prior to SWIG-1.3.7, SWIG did not generate default constructors or destructors unless you explicitly turned them on using -make_default. However, it appears that most users want to have constructor and destructor functions so it has now been enabled as the default behavior.

Note: There are also the -nodefault option and %nodefault directive, which disable both the default or implicit destructor generation. This could lead to memory leaks across the target languages, and is highly recommended you don't use them.

5.5.6 Adding member functions to C structures

Most languages provide a mechanism for creating classes and supporting object oriented programming. From a C standpoint, object oriented programming really just boils down to the process of attaching functions to structures. These functions normally operate on an instance of the structure (or object). Although there is a natural mapping of C++ to such a scheme, there is no direct mechanism for utilizing it with C code. However, SWIG provides a special %extend directive that makes it possible to attach methods to C structures for purposes of building an object oriented interface. Suppose you have a C header file with the following declaration :

/* file : vector.h */
...
typedef struct {
	double x,y,z;
} Vector;

You can make a Vector look a lot like a class by writing a SWIG interface like this:

// file : vector.i
%module mymodule
%{
#include "vector.h"
%}

%include vector.h            // Just grab original C header file
%extend Vector {             // Attach these functions to struct Vector
	Vector(double x, double y, double z) {
		Vector *v;
		v = (Vector *) malloc(sizeof(Vector));
		v->x = x;
		v->y = y;
		v->z = z;
		return v;
	}
	~Vector() {
		free($self);
	}
	double magnitude() {
		return sqrt($self->x*$self->x+$self->y*$self->y+$self->z*$self->z);
	}
	void print() {
		printf("Vector [%g, %g, %g]\n", $self->x,$self->y,$self->z);
	}
};

Note the usage of the $self special variable. Its usage is identical to a C++ 'this' pointer and should be used whenever access to the struct instance is required.

Now, when used with proxy classes in Python, you can do things like this :

>>> v = Vector(3,4,0)                 # Create a new vector
>>> print v.magnitude()                # Print magnitude
5.0
>>> v.print()                  # Print it out
[ 3, 4, 0 ]
>>> del v                      # Destroy it

The %extend directive can also be used inside the definition of the Vector structure. For example:

// file : vector.i
%module mymodule
%{
#include "vector.h"
%}

typedef struct {
	double x,y,z;
	%extend {
		Vector(double x, double y, double z) { ... }
		~Vector() { ... }
		...
	}
} Vector;

Finally, %extend can be used to access externally written functions provided they follow the naming convention used in this example :

/* File : vector.c */
/* Vector methods */
#include "vector.h"
Vector *new_Vector(double x, double y, double z) {
	Vector *v;
	v = (Vector *) malloc(sizeof(Vector));
	v->x = x;
	v->y = y;
	v->z = z;
	return v;
}
void delete_Vector(Vector *v) {
	free(v);
}

double Vector_magnitude(Vector *v) {
	return sqrt(v->x*v->x+v->y*v->y+v->z*v->z);
}

// File : vector.i
// Interface file
%module mymodule
%{
#include "vector.h"
%}

typedef struct {
	double x,y,z;
	%extend {
                Vector(int,int,int); // This calls new_Vector()
               ~Vector();            // This calls delete_Vector()
		double magnitude();  // This will call Vector_magnitude()
		...
	}
} Vector;

A little known feature of the %extend directive is that it can also be used to add synthesized attributes or to modify the behavior of existing data attributes. For example, suppose you wanted to make magnitude a read-only attribute of Vector instead of a method. To do this, you might write some code like this:

// Add a new attribute to Vector
%extend Vector {
    const double magnitude;
}
// Now supply the implementation of the Vector_magnitude_get function
%{
const double Vector_magnitude_get(Vector *v) {
  return (const double) return sqrt(v->x*v->x+v->y*v->y+v->z*v->z);
}
%}

Now, for all practical purposes, magnitude will appear like an attribute of the object.

A similar technique can also be used to work with problematic data members. For example, consider this interface:

struct Person {
   char name[50];
   ...
}

By default, the name attribute is read-only because SWIG does not normally know how to modify arrays. However, you can rewrite the interface as follows to change this:

struct Person {
    %extend {
       char *name;
    }
...
}

// Specific implementation of set/get functions
%{
char *Person_name_get(Person *p) {
   return p->name;
}
void Person_name_set(Person *p, char *val) {
   strncpy(p->name,val,50);
}
%}

Finally, it should be stressed that even though %extend can be used to add new data members, these new members can not require the allocation of additional storage in the object (e.g., their values must be entirely synthesized from existing attributes of the structure).

Compatibility note: The %extend directive is a new name for the %addmethods directive. Since %addmethods could be used to extend a structure with more than just methods, a more suitable directive name has been chosen.

5.5.7 Nested structures

Occasionally, a C program will involve structures like this :

typedef struct Object {
	int objtype;
	union {
		int 	ivalue;
		double	dvalue;
		char	*strvalue;
		void	*ptrvalue;
	} intRep;
} Object;

When SWIG encounters this, it performs a structure splitting operation that transforms the declaration into the equivalent of the following:

typedef union {
	int 		ivalue;
	double		dvalue;
	char		*strvalue;
	void		*ptrvalue;
} Object_intRep;

typedef struct Object {
	int objType;
	Object_intRep intRep;
} Object;

SWIG will then create an Object_intRep structure for use inside the interface file. Accessor functions will be created for both structures. In this case, functions like this would be created :

Object_intRep *Object_intRep_get(Object *o) {
	return (Object_intRep *) &o->intRep;
}
int Object_intRep_ivalue_get(Object_intRep *o) {
	return o->ivalue;
}
int Object_intRep_ivalue_set(Object_intRep *o, int value) {
	return (o->ivalue = value);
}
double Object_intRep_dvalue_get(Object_intRep *o) {
	return o->dvalue;
}
... etc ...

Although this process is a little hairy, it works like you would expect in the target scripting language--especially when proxy classes are used. For instance, in Perl:

# Perl5 script for accessing nested member
$o = CreateObject();                    # Create an object somehow
$o->{intRep}->{ivalue} = 7              # Change value of o.intRep.ivalue

If you have a lot nested structure declarations, it is advisable to double-check them after running SWIG. Although, there is a good chance that they will work, you may have to modify the interface file in certain cases.

5.5.8 Other things to note about structure wrapping

SWIG doesn't care if the declaration of a structure in a .i file exactly matches that used in the underlying C code (except in the case of nested structures). For this reason, there are no problems omitting problematic members or simply omitting the structure definition altogether. If you are happy passing pointers around, this can be done without ever giving SWIG a structure definition.

Starting with SWIG1.3, a number of improvements have been made to SWIG's code generator. Specifically, even though structure access has been described in terms of high-level accessor functions such as this,

double Vector_x_get(Vector *v) {
   return v->x;
}

most of the generated code is actually inlined directly into wrapper functions. Therefore, no function Vector_x_get() actually exists in the generated wrapper file. For example, when creating a Tcl module, the following function is generated instead:

static int
_wrap_Vector_x_get(ClientData clientData, Tcl_Interp *interp, 
                   int objc, Tcl_Obj *CONST objv[]) {
    struct Vector *arg1 ;
    double result ;
    
    if (SWIG_GetArgs(interp, objc, objv,"p:Vector_x_get self ",&arg0,
                     SWIGTYPE_p_Vector) == TCL_ERROR)
         return TCL_ERROR;
    result = (double ) (arg1->x);
    Tcl_SetObjResult(interp,Tcl_NewDoubleObj((double) result));
    return TCL_OK;
}

The only exception to this rule are methods defined with %extend . In this case, the added code is contained in a separate function.

Finally, it is important to note that most language modules may choose to build a more advanced interface. Although you may never use the low-level interface described here, most of SWIG's language modules use it in some way or another.

5.6 Code Insertion

Sometimes it is necessary to insert special code into the resulting wrapper file generated by SWIG. For example, you may want to include additional C code to perform initialization or other operations. There are four common ways to insert code, but it's useful to know how the output of SWIG is structured first.

5.6.1 The output of SWIG

When SWIG creates its output file, it is broken up into four sections corresponding to runtime code, headers, wrapper functions, and module initialization code (in that order).

5.6.2 Code insertion blocks

Code is inserted into the appropriate code section by using one of the following code insertion directives:

%runtime %{
   ... code in runtime section ...
%}

%header %{
   ... code in header section ...
%}

%wrapper %{
   ... code in wrapper section ...
%}

%init %{
   ... code in init section ...
%}

The bare %{ ... %} directive is a shortcut that is the same as %header %{ ... %}.

Everything in a code insertion block is copied verbatim into the output file and is not parsed by SWIG. Most SWIG input files have at least one such block to include header files and support C code. Additional code blocks may be placed anywhere in a SWIG file as needed.

%module mymodule
%{
#include "my_header.h"
%}
... Declare functions here
%{

void some_extra_function() {
  ...
}
%}

A common use for code blocks is to write "helper" functions. These are functions that are used specifically for the purpose of building an interface, but which are generally not visible to the normal C program. For example :

%{
/* Create a new vector */
static Vector *new_Vector() {
	return (Vector *) malloc(sizeof(Vector));
}

%}
// Now wrap it 
Vector *new_Vector();

5.6.3 Inlined code blocks

Since the process of writing helper functions is fairly common, there is a special inlined form of code block that is used as follows :

%inline %{
/* Create a new vector */
Vector *new_Vector() {
	return (Vector *) malloc(sizeof(Vector));
}
%}

The %inline directive inserts all of the code that follows verbatim into the header portion of an interface file. The code is then parsed by both the SWIG preprocessor and parser. Thus, the above example creates a new command new_Vector using only one declaration. Since the code inside an %inline %{ ... %} block is given to both the C compiler and SWIG, it is illegal to include any SWIG directives inside a %{ ... %} block.

5.6.4 Initialization blocks

When code is included in the %init section, it is copied directly into the module initialization function. For example, if you needed to perform some extra initialization on module loading, you could write this:

%init %{
	init_variables();
%}

5.7 An Interface Building Strategy

This section describes the general approach for building interface with SWIG. The specifics related to a particular scripting language are found in later chapters.

5.7.1 Preparing a C program for SWIG

SWIG doesn't require modifications to your C code, but if you feed it a collection of raw C header files or source code, the results might not be what you expect---in fact, they might be awful. Here's a series of steps you can follow to make an interface for a C program :

Although this may sound complicated, the process turns out to be fairly easy once you get the hang of it.

In the process of building an interface, SWIG may encounter syntax errors or other problems. The best way to deal with this is to simply copy the offending code into a separate interface file and edit it. However, the SWIG developers have worked very hard to improve the SWIG parser--you should report parsing errors to the swig-devel mailing list or to the SWIG bug tracker.

5.7.2 The SWIG interface file

The preferred method of using SWIG is to generate separate interface file. Suppose you have the following C header file :

/* File : header.h */

#include <stdio.h>
#include <math.h>

extern int foo(double);
extern double bar(int, int);
extern void dump(FILE *f);

A typical SWIG interface file for this header file would look like the following :

/* File : interface.i */
%module mymodule
%{
#include "header.h"
%}
extern int foo(double);
extern double bar(int, int);
extern void dump(FILE *f);

Of course, in this case, our header file is pretty simple so we could have made an interface file like this as well:

/* File : interface.i */
%module mymodule
%include header.h

Naturally, your mileage may vary.

5.7.3 Why use separate interface files?

Although SWIG can parse many header files, it is more common to write a special .i file defining the interface to a package. There are several reasons why you might want to do this:

5.7.4 Getting the right header files

Sometimes, it is necessary to use certain header files in order for the code generated by SWIG to compile properly. Make sure you include certain header files by using a %{,%} block like this:

%module graphics
%{
#include <GL/gl.h>
#include <GL/glu.h>
%}

// Put rest of declarations here
...

5.7.5 What to do with main()

If your program defines a main() function, you may need to get rid of it or rename it in order to use a scripting language. Most scripting languages define their own main() procedure that is called instead. main() also makes no sense when working with dynamic loading. There are a few approaches to solving the main() conflict :

Getting rid of main() may cause potential initialization problems of a program. To handle this problem, you may consider writing a special function called program_init() that initializes your program upon startup. This function could then be called either from the scripting language as the first operation, or when the SWIG generated module is loaded.

As a general note, many C programs only use the main() function to parse command line options and to set parameters. However, by using a scripting language, you are probably trying to create a program that is more interactive. In many cases, the old main() program can be completely replaced by a Perl, Python, or Tcl script.

Note: If some cases, you might be inclined to create a scripting language wrapper for main(). If you do this, the compilation will probably work and your module might even load correctly. The only trouble is that when you call your main() wrapper, you will find that it actually invokes the main() of the scripting language interpreter itself! This behavior is a side effect of the symbol binding mechanism used in the dynamic linker. The bottom line: don't do this.


6 SWIG and C++

This chapter describes SWIG's support for wrapping C++. As a prerequisite, you should first read the chapter SWIG Basics to see how SWIG wraps ANSI C. Support for C++ builds upon ANSI C wrapping and that material will be useful in understanding this chapter.

6.1 Comments on C++ Wrapping

Because of its complexity and the fact that C++ can be difficult to integrate with itself let alone other languages, SWIG only provides support for a subset of C++ features. Fortunately, this is now a rather large subset.

In part, the problem with C++ wrapping is that there is no semantically obvious (or automatic ) way to map many of its advanced features into other languages. As a simple example, consider the problem of wrapping C++ multiple inheritance to a target language with no such support. Similarly, the use of overloaded operators and overloaded functions can be problematic when no such capability exists in a target language.

A more subtle issue with C++ has to do with the way that some C++ programmers think about programming libraries. In the world of SWIG, you are really trying to create binary-level software components for use in other languages. In order for this to work, a "component" has to contain real executable instructions and there has to be some kind of binary linking mechanism for accessing its functionality. In contrast, C++ has increasingly relied upon generic programming and templates for much of its functionality. Although templates are a powerful feature, they are largely orthogonal to the whole notion of binary components and libraries. For example, an STL vector does not define any kind of binary object for which SWIG can just create a wrapper. To further complicate matters, these libraries often utilize a lot of behind the scenes magic in which the semantics of seemingly basic operations (e.g., pointer dereferencing, procedure call, etc.) can be changed in dramatic and sometimes non-obvious ways. Although this "magic" may present few problems in a C++-only universe, it greatly complicates the problem of crossing language boundaries and provides many opportunities to shoot yourself in the foot. You will just have to be careful.

6.2 Approach

To wrap C++, SWIG uses a layered approach to code generation. At the lowest level, SWIG generates a collection of procedural ANSI-C style wrappers. These wrappers take care of basic type conversion, type checking, error handling, and other low-level details of the C++ binding. These wrappers are also sufficient to bind C++ into any target language that supports built-in procedures. In some sense, you might view this layer of wrapping as providing a C library interface to C++. On top of the low-level procedural (flattened) interface, SWIG generates proxy classes that provide a natural object-oriented (OO) interface to the underlying code. The proxy classes are typically written in the target language itself. For instance, in Python, a real Python class is used to provide a wrapper around the underlying C++ object.

It is important to emphasize that SWIG takes a deliberately conservative and non-intrusive approach to C++ wrapping. SWIG does not encapsulate C++ classes inside a special C++ adaptor, it does not rely upon templates, nor does it add in additional C++ inheritance when generating wrappers. The last thing that most C++ programs need is even more compiler magic. Therefore, SWIG tries to maintain a very strict and clean separation between the implementation of your C++ application and the resulting wrapper code. You might say that SWIG has been written to follow the principle of least surprise--it does not play sneaky tricks with the C++ type system, it doesn't mess with your class hierarchies, and it doesn't introduce new semantics. Although this approach might not provide the most seamless integration with C++, it is safe, simple, portable, and debuggable.

Some of this chapter focuses on the low-level procedural interface to C++ that is used as the foundation for all language modules. Keep in mind that the target languages also provide the high-level OO interface via proxy classes. More detailed coverage can be found in the documentation for each target language.

6.3 Supported C++ features

SWIG currently supports most C++ features including the following:

The following C++ features are not currently supported:

As a rule of thumb, SWIG should not be used on raw C++ source files, use header files only.

SWIG's C++ support is an ongoing project so some of these limitations may be lifted in future releases. However, we make no promises. Also, submitting a bug report is a very good way to get problems fixed (wink).

6.4 Command line options and compilation

When wrapping C++ code, it is critical that SWIG be called with the `-c++' option. This changes the way a number of critical features such as memory management are handled. It also enables the recognition of C++ keywords. Without the -c++ flag, SWIG will either issue a warning or a large number of syntax errors if it encounters C++ code in an interface file.

When compiling and linking the resulting wrapper file, it is normal to use the C++ compiler. For example:

$ swig -c++ -tcl example.i
$ c++ -c example_wrap.cxx 
$ c++ example_wrap.o $(OBJS) -o example.so

Unfortunately, the process varies slightly on each platform. Make sure you refer to the documentation on each target language for further details. The SWIG Wiki also has further details.

Compatibility Note: Early versions of SWIG generated just a flattened low-level C style API to C++ classes by default. The -noproxy commandline option is recognised by many target languages and will generate just this interface as in earlier versions.

6.5 Proxy classes

In order to provide a natural mapping from C++ classes to the target language classes, SWIG's target languages mostly wrap C++ classes with special proxy classes. These proxy classes are typically implemented in the target language itself. For example, if you're building a Python module, each C++ class is wrapped by a Python proxy class. Or if you're building a Java module, each C++ class is wrapped by a Java proxy class.

6.5.1 Construction of proxy classes

Proxy classes are always constructed as an extra layer of wrapping that uses low-level accessor functions. To illustrate, suppose you had a C++ class like this:

class Foo {
public:
      Foo();
     ~Foo();
      int  bar(int x);
      int  x;
};

Using C++ as pseudocode, a proxy class looks something like this:

class FooProxy {
private:
      Foo    *self;
public:
      FooProxy() {
            self = new_Foo();
      }
     ~FooProxy() {
            delete_Foo(self);
      }
      int bar(int x) {
            return Foo_bar(self,x);
      }
      int x_get() {
            return Foo_x_get(self);
      }
      void x_set(int x) {
            Foo_x_set(self,x);
      }
};

Of course, always keep in mind that the real proxy class is written in the target language. For example, in Python, the proxy might look roughly like this:

class Foo:
    def __init__(self):
         self.this = new_Foo()
    def __del__(self):
         delete_Foo(self.this)
    def bar(self,x):
         return Foo_bar(self.this,x)
    def __getattr__(self,name):
         if name == 'x':
              return Foo_x_get(self.this)
         ...
    def __setattr__(self,name,value):
         if name == 'x':
              Foo_x_set(self.this,value)
         ...

Again, it's important to emphasize that the low-level accessor functions are always used by the proxy classes. Whenever possible, proxies try to take advantage of language features that are similar to C++. This might include operator overloading, exception handling, and other features.

6.5.2 Resource management in proxies

A major issue with proxies concerns the memory management of wrapped objects. Consider the following C++ code:

class Foo {
public:
      Foo();
     ~Foo();
      int bar(int x);
      int x;
};

class Spam {
public:
      Foo *value;
      ...
};

Consider some script code that uses these classes:

f = Foo()               # Creates a new Foo
s = Spam()              # Creates a new Spam
s.value = f             # Stores a reference to f inside s
g = s.value             # Returns stored reference
g = 4                   # Reassign g to some other value
del f                   # Destroy f 

Now, ponder the resulting memory management issues. When objects are created in the script, the objects are wrapped by newly created proxy classes. That is, there is both a new proxy class instance and a new instance of the underlying C++ class. In this example, both f and s are created in this way. However, the statement s.value is rather curious---when executed, a pointer to f is stored inside another object. This means that the scripting proxy class AND another C++ class share a reference to the same object. To make matters even more interesting, consider the statement g = s.value. When executed, this creates a new proxy class g that provides a wrapper around the C++ object stored in s.value . In general, there is no way to know where this object came from---it could have been created by the script, but it could also have been generated internally. In this particular example, the assignment of g results in a second proxy class for f. In other words, a reference to f is now shared by two proxy classes and a C++ class.

Finally, consider what happens when objects are destroyed. In the statement, g=4, the variable g is reassigned. In many languages, this makes the old value of g available for garbage collection. Therefore, this causes one of the proxy classes to be destroyed. Later on, the statement del f destroys the other proxy class. Of course, there is still a reference to the original object stored inside another C++ object. What happens to it? Is the object still valid?

To deal with memory management problems, proxy classes provide an API for controlling ownership. In C++ pseudocode, ownership control might look roughly like this:

class FooProxy {
public:
      Foo    *self;
      int     thisown;

      FooProxy() {
            self = new_Foo();
            thisown = 1;       // Newly created object
      }
     ~FooProxy() {
            if (thisown) delete_Foo(self);
      }
      ...
      // Ownership control API
      void disown() {
           thisown = 0;
      }
      void acquire() {
           thisown = 1;
      }
};

class FooPtrProxy: public FooProxy {
public:
      FooPtrProxy(Foo *s) {
          self = s;
          thisown = 0;
      }
};

class SpamProxy {
     ...
     FooProxy *value_get() {
          return FooPtrProxy(Spam_value_get(self));
     }
     void value_set(FooProxy *v) {
          Spam_value_set(self,v->self);
          v->disown();
     }
     ...
};

Looking at this code, there are a few central features:

Given the tricky nature of C++ memory management, it is impossible for proxy classes to automatically handle every possible memory management problem. However, proxies do provide a mechanism for manual control that can be used (if necessary) to address some of the more tricky memory management problems.

6.5.3 Language specific details

Language specific details on proxy classes are contained in the chapters describing each target language. This chapter has merely introduced the topic in a very general way.

6.6 Simple C++ wrapping

The following code shows a SWIG interface file for a simple C++ class.

%module list
%{
#include "list.h"
%}

// Very simple C++ example for linked list

class List {
public:
  List();
  ~List();
  int  search(char *value);
  void insert(char *);
  void remove(char *);
  char *get(int n);
  int  length;
static void print(List *l);
};

To generate wrappers for this class, SWIG first reduces the class to a collection of low-level C-style accessor functions which are then used by the proxy classes.

6.6.1 Constructors and destructors

C++ constructors and destructors are translated into accessor functions such as the following :

List * new_List(void) {
	return new List;
}
void delete_List(List *l) {
	delete l;
}

6.6.2 Default constructors, copy constructors and implicit destructors

Following the C++ rules for implicit constructor and destructors, SWIG will automatically assume there is one even when they are not explicitly declared in the class interface.

In general then:

And as in C++, a few rules that alters the previous behavior:

SWIG should never generate a default constructor, copy constructor or default destructor wrapper for a class in which it is illegal to do so. In some cases, however, it could be necessary (if the complete class declaration is not visible from SWIG, and one of the above rules is violated) or desired (to reduce the size of the final interface) by manually disabling the implicit constructor/destructor generation.

To manually disable these, the %nodefaultctor and %nodefaultdtor feature flag directives can be used. Note that these directives only affects the implicit generation, and they have no effect if the default/copy constructors or destructor are explicitly declared in the class interface.

For example:

%nodefaultctor Foo;  // Disable the default constructor for class Foo.
class Foo {          // No default constructor is generated, unless one is declared
...
};
class Bar {          // A default constructor is generated, if possible
...
};

The directive %nodefaultctor can also be applied "globally", as in:

%nodefaultctor; // Disable creation of default constructors
class Foo {     // No default constructor is generated, unless one is declared
...
};
class Bar {   
public:
  Bar();        // The default constructor is generated, since one is declared
};
%clearnodefaultctor; // Enable the creation of default constructors again

The corresponding %nodefaultdtor directive can be used to disable the generation of the default or implicit destructor, if needed. Be aware, however, that this could lead to memory leaks in the target language. Hence, it is recommended to use this directive only in well known cases. For example:

%nodefaultdtor Foo;   // Disable the implicit/default destructor for class Foo.
class Foo {           // No destructor is generated, unless one is declared
...
};

Compatibility Note: The generation of default constructors/implicit destructors was made the default behavior in SWIG 1.3.7. This may break certain older modules, but the old behavior can be easily restored using %nodefault or the -nodefault command line option. Furthermore, in order for SWIG to properly generate (or not generate) default constructors, it must be able to gather information from both the private and protected sections (specifically, it needs to know if a private or protected constructor/destructor is defined). In older versions of SWIG, it was fairly common to simply remove or comment out the private and protected sections of a class due to parser limitations. However, this removal may now cause SWIG to erroneously generate constructors for classes that define a constructor in those sections. Consider restoring those sections in the interface or using %nodefault to fix the problem.

Note: The %nodefault directive/-nodefault options described above, which disable both the default constructor and the implicit destructors, could lead to memory leaks, and so it is strongly recommended to not use them.

6.6.3 When constructor wrappers aren't created

If a class defines a constructor, SWIG normally tries to generate a wrapper for it. However, SWIG will not generate a constructor wrapper if it thinks that it will result in illegal wrapper code. There are really two cases where this might show up.

First, SWIG won't generate wrappers for protected or private constructors. For example:

class Foo {
protected:
     Foo();         // Not wrapped.
public:
      ...
};

Next, SWIG won't generate wrappers for a class if it appears to be abstract--that is, it has undefined pure virtual methods. Here are some examples:

class Bar {
public:
     Bar();               // Not wrapped.  Bar is abstract.
     virtual void spam(void) = 0; 
};

class Grok : public Bar {
public:
      Grok();            // Not wrapped. No implementation of abstract spam().
};

Some users are surprised (or confused) to find missing constructor wrappers in their interfaces. In almost all cases, this is caused when classes are determined to be abstract. To see if this is the case, run SWIG with all of its warnings turned on:

% swig -Wall -python module.i

In this mode, SWIG will issue a warning for all abstract classes. It is possible to force a class to be non-abstract using this:

%feature("notabstract") Foo;

class Foo : public Bar {
public:
     Foo();    // Generated no matter what---not abstract. 
     ...
};

More information about %feature can be found in the Customization features chapter.

6.6.4 Copy constructors

If a class defines more than one constructor, its behavior depends on the capabilities of the target language. If overloading is supported, the copy constructor is accessible using the normal constructor function. For example, if you have this:

class List {
public:
    List();    
    List(const List &);      // Copy constructor
    ...
};

then the copy constructor can be used as follows:

x = List()               # Create a list
y = List(x)              # Copy list x

If the target language does not support overloading, then the copy constructor is available through a special function like this:

List *copy_List(List *f) {
    return new List(*f);
}

Note: For a class X, SWIG only treats a constructor as a copy constructor if it can be applied to an object of type X or X *. If more than one copy constructor is defined, only the first definition that appears is used as the copy constructor--other definitions will result in a name-clash. Constructors such as X(const X &), X(X &), and X(X *) are handled as copy constructors in SWIG.

Note: SWIG does not generate a copy constructor wrapper unless one is explicitly declared in the class. This differs from the treatment of default constructors and destructors. However, copy constructor wrappers can be generated if using the copyctor feature flag. For example:

%copyctor List;

class List {
public:
    List();    
};

Will generate a copy constructor wrapper for List.

Compatibility note: Special support for copy constructors was not added until SWIG-1.3.12. In previous versions, copy constructors could be wrapped, but they had to be renamed. For example:

class Foo {
public:
    Foo();
  %name(CopyFoo) Foo(const Foo &);
    ...
};

For backwards compatibility, SWIG does not perform any special copy-constructor handling if the constructor has been manually renamed. For instance, in the above example, the name of the constructor is set to new_CopyFoo(). This is the same as in older versions.

6.6.5 Member functions

All member functions are roughly translated into accessor functions like this :

int List_search(List *obj, char *value) {
	return obj->search(value);
}

This translation is the same even if the member function has been declared as virtual.

It should be noted that SWIG does not actually create a C accessor function in the code it generates. Instead, member access such as obj->search(value) is directly inlined into the generated wrapper functions. However, the name and calling convention of the low-level procedural wrappers match the accessor function prototype described above.

6.6.6 Static members

Static member functions are called directly without making any special transformations. For example, the static member function print(List *l) directly invokes List::print(List *l) in the generated wrapper code.

6.6.7 Member data

Member data is handled in exactly the same manner as for C structures. A pair of accessor functions are effectively created. For example :

int List_length_get(List *obj) {
	return obj->length;
}
int List_length_set(List *obj, int value) {
	obj->length = value;
	return value;
}

A read-only member can be created using the %immutable and %mutable feature flag directive. For example, we probably wouldn't want the user to change the length of a list so we could do the following to make the value available, but read-only.

class List {
public:
...
%immutable;
	int length;
%mutable;
...
};

Alternatively, you can specify an immutable member in advance like this:

%immutable List::length;
...
class List {
   ...
   int length;         // Immutable by above directive
   ...
};

Similarly, all data attributes declared as const are wrapped as read-only members.

There are some subtle issues when wrapping data members that are themselves classes. For instance, if you had another class like this,

class Foo {
public:
    List items;
    ...

then the low-level accessor to the items member actually uses pointers. For example:

List *Foo_items_get(Foo *self) {
    return &self->items;
}
void Foo_items_set(Foo *self, List *value) {
    self->items = *value;
}

More information about this can be found in the SWIG Basics chapter, Structure data members section.

The wrapper code to generate the accessors for classes comes from the pointer typemaps. This can be somewhat unnatural for some types. For example, a user would expect the STL std::string class member variables to be wrapped as a string in the target language, rather than a pointer to this class. The const reference typemaps offer this type of marshalling, so there is a feature to tell SWIG to use the const reference typemaps rather than the pointer typemaps. It is the %naturalvar directive and is used as follows:

// All List variables will use const List& typemaps
%naturalvar List;

// Only Foo::myList will use const List& typemaps
%naturalvar Foo::myList;
struct Foo {
  List myList;
};

// All variables will use const reference typemaps
%naturalvar;

The observant reader will notice that %naturalvar works like any other feature flag directive, except it can also be attached to class types. The first of the example usages above show %naturalvar attaching to the List class. Effectively this feature changes the way accessors are generated to the following:

const List &Foo_items_get(Foo *self) {
    return self->items;
}
void Foo_items_set(Foo *self, const List &value) {
    self->items = value;
}

In fact it is generally a good idea to use this feature globally as the reference typemaps have extra NULL checking compared to the pointer typemaps. A pointer can be NULL, whereas a reference cannot, so the extra checking ensures that the target language user does not pass in a value that translates to a NULL pointer and thereby preventing any potential NULL pointer dereferences. The %naturalvar feature will apply to global variables in addition to member variables in some language modules, eg C# and Java.

Other alternatives for turning this feature on globally are to use the swig -naturalvar commandline option or the module mode option, %module(naturalvar=1)

Compatibility note: The %naturalvar feature was introduced in SWIG-1.3.28, prior to which it was necessary to manually apply the const reference typemaps, eg %apply const std::string & { std::string * }, but this example would also apply the typemaps to methods taking a std::string pointer.

Compatibility note: Read-only access used to be controlled by a pair of directives %readonly and %readwrite. Although these directives still work, they generate a warning message. Simply change the directives to %immutable; and %mutable; to silence the warning. Don't forget the extra semicolon!

Compatibility note: Prior to SWIG-1.3.12, all members of unknown type were wrapped into accessor functions using pointers. For example, if you had a structure like this

struct Foo {
   size_t  len;
};

and nothing was known about size_t, then accessors would be written to work with size_t *. Starting in SWIG-1.3.12, this behavior has been modified. Specifically, pointers will only be used if SWIG knows that a datatype corresponds to a structure or class. Therefore, the above code would be wrapped into accessors involving size_t. This change is subtle, but it smooths over a few problems related to structure wrapping and some of SWIG's customization features.

6.7 Default arguments

SWIG will wrap all types of functions that have default arguments. For example member functions:

class Foo {
public:
    void bar(int x, int y = 3, int z = 4);
};

SWIG handles default arguments by generating an extra overloaded method for each defaulted argument. SWIG is effectively handling methods with default arguments as if it was wrapping the equivalent overloaded methods. Thus for the example above, it is as if we had instead given the following to SWIG:

class Foo {
public:
    void bar(int x, int y, int z);
    void bar(int x, int y);
    void bar(int x);
};

The wrappers produced are exactly the same as if the above code was instead fed into SWIG. Details of this are covered later in the Wrapping Overloaded Functions and Methods section. This approach allows SWIG to wrap all possible default arguments, but can be verbose. For example if a method has ten default arguments, then eleven wrapper methods are generated.

Please see the Features and default arguments section for more information on using %feature with functions with default arguments. The Ambiguity resolution and renaming section also deals with using %rename and %ignore on methods with default arguments. If you are writing your own typemaps for types used in methods with default arguments, you may also need to write a typecheck typemap. See the Typemaps and overloading section for details or otherwise use the compactdefaultargs feature flag as mentioned below.

Compatibility note: Versions of SWIG prior to SWIG-1.3.23 wrapped default arguments slightly differently. Instead a single wrapper method was generated and the default values were copied into the C++ wrappers so that the method being wrapped was then called with all the arguments specified. If the size of the wrappers are a concern then this approach to wrapping methods with default arguments can be re-activated by using the compactdefaultargs feature flag.

%feature("compactdefaultargs") Foo::bar;
class Foo {
public:
    void bar(int x, int y = 3, int z = 4);
};

This is great for reducing the size of the wrappers, but the caveat is it does not work for the strongly typed languages which don't have optional arguments in the language, such as C# and Java. Another restriction of this feature is that it cannot handle default arguments that are not public. The following example illustrates this:

class Foo {
private:
   static const int spam;
public:
   void bar(int x, int y = spam);   // Won't work with %feature("compactdefaultargs") -
                                    // private default value
};

This produces uncompileable wrapper code because default values in C++ are evaluated in the same scope as the member function whereas SWIG evaluates them in the scope of a wrapper function (meaning that the values have to be public).

This feature is automatically turned on when wrapping C code with default arguments and whenever keyword arguments (kwargs) are specified for either C or C++ code. Keyword arguments are a language feature of some scripting languages, for example Ruby and Python. SWIG is unable to support kwargs when wrapping overloaded methods, so the default approach cannot be used.

6.8 Protection

SWIG wraps class members that are public following the C++ conventions, i.e., by explicit public declaration or by the use of the using directive. In general, anything specified in a private or protected section will be ignored, although the internal code generator sometimes looks at the contents of the private and protected sections so that it can properly generate code for default constructors and destructors. Directors could also modify the way non-public virtual protected members are treated.

By default, members of a class definition are assumed to be private until you explicitly give a `public:' declaration (This is the same convention used by C++).

6.9 Enums and constants

Enumerations and constants are handled differently by the different language modules and are described in detail in the appropriate language chapter. However, many languages map enums and constants in a class definition into constants with the classname as a prefix. For example :

class Swig {
public:
	enum {ALE, LAGER, PORTER, STOUT};
};

Generates the following set of constants in the target scripting language :

Swig_ALE = Swig::ALE
Swig_LAGER = Swig::LAGER
Swig_PORTER = Swig::PORTER
Swig_STOUT = Swig::STOUT

Members declared as const are wrapped as read-only members and do not create constants.

6.10 Friends

Friend declarations are recognised by SWIG. For example, if you have this code:

class Foo {
public:
     ...
     friend void blah(Foo *f);
     ...
};

then the friend declaration does result in a wrapper code equivalent to one generated for the following declaration

class Foo {
public:
    ...
};

void blah(Foo *f);    

A friend declaration, as in C++, is understood to be in the same scope where the class is declared, hence, you can have


%ignore bar::blah(Foo *f);

namespace bar {

  class Foo {
  public:
     ...
     friend void blah(Foo *f);
     ...
  };
}

and a wrapper for the method 'blah' will not be generated.

6.11 References and pointers

C++ references are supported, but SWIG transforms them back into pointers. For example, a declaration like this :

class Foo {
public:
	double bar(double &a);
}

has a low-level accessor

double Foo_bar(Foo *obj, double *a) {
	obj->bar(*a);
}

As a special case, most language modules pass const references to primitive datatypes (int, short, float, etc.) by value instead of pointers. For example, if you have a function like this,

void foo(const int &x);

it is called from a script as follows:

foo(3)              # Notice pass by value

Functions that return a reference are remapped to return a pointer instead. For example:

class Bar {
public:
     Foo &spam();
};

Generates an accessor like this:

Foo *Bar_spam(Bar *obj) {
   Foo &result = obj->spam();
   return &result;
}

However, functions that return const references to primitive datatypes (int, short, etc.) normally return the result as a value rather than a pointer. For example, a function like this,

const int &bar();

will return integers such as 37 or 42 in the target scripting language rather than a pointer to an integer.

Don't return references to objects allocated as local variables on the stack. SWIG doesn't make a copy of the objects so this will probably cause your program to crash.

Note: The special treatment for references to primitive datatypes is necessary to provide more seamless integration with more advanced C++ wrapping applications---especially related to templates and the STL. This was first added in SWIG-1.3.12.

6.12 Pass and return by value

Occasionally, a C++ program will pass and return class objects by value. For example, a function like this might appear:

Vector cross_product(Vector a, Vector b);

If no information is supplied about Vector, SWIG creates a wrapper function similar to the following:

Vector *wrap_cross_product(Vector *a, Vector *b) {
   Vector x = *a;
   Vector y = *b;
   Vector r = cross_product(x,y);
   return new Vector(r);
}

In order for the wrapper code to compile, Vector must define a copy constructor and a default constructor.

If Vector is defined as class in the interface, but it does not support a default constructor, SWIG changes the wrapper code by encapsulating the arguments inside a special C++ template wrapper class. This produces a wrapper that looks like this:

Vector cross_product(Vector *a, Vector *b) {
   SwigValueWrapper<Vector> x = *a;
   SwigValueWrapper<Vector> y = *b;
   SwigValueWrapper<Vector> r = cross_product(x,y);
   return new Vector(r);
}

This transformation is a little sneaky, but it provides support for pass-by-value even when a class does not provide a default constructor and it makes it possible to properly support a number of SWIG's customization options. The definition of SwigValueWrapper can be found by reading the SWIG wrapper code. This class is really nothing more than a thin wrapper around a pointer.

Note: this transformation has no effect on typemaps or any other part of SWIG---it should be transparent except that you may see this code when reading the SWIG output file.

Note: This template transformation is new in SWIG-1.3.11 and may be refined in future SWIG releases. In practice, it is only necessary to do this for classes that don't define a default constructor.

Note: The use of this template only occurs when objects are passed or returned by value. It is not used for C++ pointers or references.

Note: The performance of pass-by-value is especially bad for large objects and should be avoided if possible (consider using references instead).

6.13 Inheritance

SWIG supports C++ inheritance of classes and allows both single and multiple inheritance, as limited or allowed by the target language. The SWIG type-checker knows about the relationship between base and derived classes and allows pointers to any object of a derived class to be used in functions of a base class. The type-checker properly casts pointer values and is safe to use with multiple inheritance.

SWIG treats private or protected inheritance as close to the C++ spirit, and target language capabilities, as possible. In most of the cases, this means that SWIG will parse the non-public inheritance declarations, but that will have no effect in the generated code, besides the implicit policies derived for constructor and destructors.

The following example shows how SWIG handles inheritance. For clarity, the full C++ code has been omitted.

// shapes.i
%module shapes
%{
#include "shapes.h"
%}

class Shape {
public:
        double x,y;
	virtual double area() = 0;
	virtual double perimeter() = 0;
	void    set_location(double x, double y);
};
class Circle : public Shape {
public:
	Circle(double radius);
	~Circle();
	double area();
	double perimeter();
};
class Square : public Shape {
public:
	Square(double size);
	~Square();
	double area();
	double perimeter();
}

When wrapped into Python, we can perform the following operations (shown using the low level Python accessors):

$ python
>>> import shapes
>>> circle = shapes.new_Circle(7)
>>> square = shapes.new_Square(10)
>>> print shapes.Circle_area(circle)
153.93804004599999757
>>> print shapes.Shape_area(circle)
153.93804004599999757
>>> print shapes.Shape_area(square)
100.00000000000000000
>>> shapes.Shape_set_location(square,2,-3)
>>> print shapes.Shape_perimeter(square)
40.00000000000000000
>>>

In this example, Circle and Square objects have been created. Member functions can be invoked on each object by making calls to Circle_area, Square_area, and so on. However, the same results can be accomplished by simply using the Shape_area function on either object.

One important point concerning inheritance is that the low-level accessor functions are only generated for classes in which they are actually declared. For instance, in the above example, the method set_location() is only accessible as Shape_set_location() and not as Circle_set_location() or Square_set_location() . Of course, the Shape_set_location() function will accept any kind of object derived from Shape. Similarly, accessor functions for the attributes x and y are generated as Shape_x_get(), Shape_x_set(), Shape_y_get(), and Shape_y_set(). Functions such as Circle_x_get() are not available--instead you should use Shape_x_get().

Note that there is a one to one correlation between the low-level accessor functions and the proxy methods and therefore there is also a one to one correlation between the C++ class methods and the generated proxy class methods.

Note: For the best results, SWIG requires all base classes to be defined in an interface. Otherwise, you may get a warning message like this:

example.i:18: Warning(401): Nothing known about base class 'Foo'. Ignored.

If any base class is undefined, SWIG still generates correct type relationships. For instance, a function accepting a Foo * will accept any object derived from Foo regardless of whether or not SWIG actually wrapped the Foo class. If you really don't want to generate wrappers for the base class, but you want to silence the warning, you might consider using the %import directive to include the file that defines Foo. %import simply gathers type information, but doesn't generate wrappers. Alternatively, you could just define Foo as an empty class in the SWIG interface or use warning suppression .

Note: typedef-names can be used as base classes. For example:

class Foo {
...
};

typedef Foo FooObj;
class Bar : public FooObj {     // Ok.  Base class is Foo
...
};

Similarly, typedef allows unnamed structures to be used as base classes. For example:

typedef struct {
   ...
} Foo;

class Bar : public Foo {    // Ok. 
...
};

Compatibility Note: Starting in version 1.3.7, SWIG only generates low-level accessor wrappers for the declarations that are actually defined in each class. This differs from SWIG1.1 which used to inherit all of the declarations defined in base classes and regenerate specialized accessor functions such as Circle_x_get(), Square_x_get(), Circle_set_location(), and Square_set_location(). This behavior resulted in huge amounts of replicated code for large class hierarchies and made it awkward to build applications spread across multiple modules (since accessor functions are duplicated in every single module). It is also unnecessary to have such wrappers when advanced features like proxy classes are used. Note: Further optimizations are enabled when using the -fvirtual option, which avoids the regenerating of wrapper functions for virtual members that are already defined in a base class.

6.14 A brief discussion of multiple inheritance, pointers, and type checking

When a target scripting language refers to a C++ object, it normally uses a tagged pointer object that contains both the value of the pointer and a type string. For example, in Tcl, a C++ pointer might be encoded as a string like this:

_808fea88_p_Circle

A somewhat common question is whether or not the type-tag could be safely removed from the pointer. For instance, to get better performance, could you strip all type tags and just use simple integers instead?

In general, the answer to this question is no. In the wrappers, all pointers are converted into a common data representation in the target language. Typically this is the equivalent of casting a pointer to void *. This means that any C++ type information associated with the pointer is lost in the conversion.

The problem with losing type information is that it is needed to properly support many advanced C++ features--especially multiple inheritance. For example, suppose you had code like this:

class A {
public:
   int x;
};

class B {
public:
   int y;
};

class C : public A, public B {
};

int A_function(A *a) {
   return a->x;
}

int B_function(B *b) {
   return b->y;
}

Now, consider the following code that uses void *.

C *c = new C();
void *p = (void *) c;
...
int x = A_function((A *) p);
int y = B_function((B *) p);

In this code, both A_function() and B_function() may legally accept an object of type C * (via inheritance). However, one of the functions will always return the wrong result when used as shown. The reason for this is that even though p points to an object of type C, the casting operation doesn't work like you would expect. Internally, this has to do with the data representation of C. With multiple inheritance, the data from each base class is stacked together. For example:

             ------------    <--- (C *),  (A *)
            |     A      |
            |------------|   <--- (B *)
            |     B      |
             ------------   

Because of this stacking, a pointer of type C * may change value when it is converted to a A * or B *. However, this adjustment does not occur if you are converting from a void *.

The use of type tags marks all pointers with the real type of the underlying object. This extra information is then used by SWIG generated wrappers to correctly cast pointer values under inheritance (avoiding the above problem).

Some of the language modules are able to solve the problem by storing multiple instances of the pointer, for example, A *, in the A proxy class as well as C * in the C proxy class. The correct cast can then be made by choosing the correct void * pointer to use and is guaranteed to work as the cast to a void pointer and back to the same type does not lose any type information:

C *c = new C();
void *p = (void *) c;
void *pA = (void *) c;
void *pB = (void *) c;
...
int x = A_function((A *) pA);
int y = B_function((B *) pB);

In practice, the pointer is held as an integral number in the target language proxy class.

6.15 Wrapping Overloaded Functions and Methods

In many language modules, SWIG provides partial support for overloaded functions, methods, and constructors. For example, if you supply SWIG with overloaded functions like this:

void foo(int x) {
   printf("x is %d\n", x);
}
void foo(char *x) {
   printf("x is '%s'\n", x);
}

The function is used in a completely natural way. For example:

>>> foo(3)
x is 3
>>> foo("hello")
x is 'hello'
>>>

Overloading works in a similar manner for methods and constructors. For example if you have this code,

class Foo {
public:
     Foo();
     Foo(const Foo &);   // Copy constructor
     void bar(int x);
     void bar(char *s, int y);
};

it might be used like this

>>> f = Foo()          # Create a Foo
>>> f.bar(3)
>>> g = Foo(f)         # Copy Foo
>>> f.bar("hello",2)

6.15.1 Dispatch function generation

The implementation of overloaded functions and methods is somewhat complicated due to the dynamic nature of scripting languages. Unlike C++, which binds overloaded methods at compile time, SWIG must determine the proper function as a runtime check for scripting language targets. This check is further complicated by the typeless nature of certain scripting languages. For instance, in Tcl, all types are simply strings. Therefore, if you have two overloaded functions like this,

void foo(char *x);
void foo(int x);

the order in which the arguments are checked plays a rather critical role.

For statically typed languages, SWIG uses the language's method overloading mechanism. To implement overloading for the scripting languages, SWIG generates a dispatch function that checks the number of passed arguments and their types. To create this function, SWIG first examines all of the overloaded methods and ranks them according to the following rules:

  1. Number of required arguments. Methods are sorted by increasing number of required arguments.
  2. Argument type precedence. All C++ datatypes are assigned a numeric type precedence value (which is determined by the language module).

    Type              Precedence
    ----------------  ----------
    TYPE *            0     (High)
    void *            20
    Integers          40
    Floating point    60
    char              80
    Strings           100   (Low)
    

    Using these precedence values, overloaded methods with the same number of required arguments are sorted in increased order of precedence values.

This may sound very confusing, but an example will help. Consider the following collection of overloaded methods:

void foo(double);
void foo(int);
void foo(Bar *);
void foo();
void foo(int x, int y, int z, int w);
void foo(int x, int y, int z = 3);
void foo(double x, double y);
void foo(double x, Bar *z);

The first rule simply ranks the functions by required argument count. This would produce the following list:

rank
-----
[0]   foo()
[1]   foo(double);
[2]   foo(int);
[3]   foo(Bar *);
[4]   foo(int x, int y, int z = 3);
[5]   foo(double x, double y)
[6]   foo(double x, Bar *z)
[7]   foo(int x, int y, int z, int w);

The second rule, simply refines the ranking by looking at argument type precedence values.

rank
-----
[0]   foo()
[1]   foo(Bar *);
[2]   foo(int);
[3]   foo(double);
[4]   foo(int x, int y, int z = 3);
[5]   foo(double x, Bar *z)
[6]   foo(double x, double y)
[7]   foo(int x, int y, int z, int w);

Finally, to generate the dispatch function, the arguments passed to an overloaded method are simply checked in the same order as they appear in this ranking.

If you're still confused, don't worry about it---SWIG is probably doing the right thing.

6.15.2 Ambiguity in Overloading

Regrettably, SWIG is not able to support every possible use of valid C++ overloading. Consider the following example:

void foo(int x);
void foo(long x);

In C++, this is perfectly legal. However, in a scripting language, there is generally only one kind of integer object. Therefore, which one of these functions do you pick? Clearly, there is no way to truly make a distinction just by looking at the value of the integer itself ( int and long may even be the same precision). Therefore, when SWIG encounters this situation, it may generate a warning message like this for scripting languages:

example.i:4: Warning(509): Overloaded foo(long) is shadowed by foo(int) at example.i:3.

or for statically typed languages like Java:

example.i:4: Warning(516): Overloaded method foo(long) ignored. Method foo(int)
at example.i:3 used.

This means that the second overloaded function will be inaccessible from a scripting interface or the method won't be wrapped at all. This is done as SWIG does not know how to disambiguate it from an earlier method.

Ambiguity problems are known to arise in the following situations:

When an ambiguity arises, methods are checked in the same order as they appear in the interface file. Therefore, earlier methods will shadow methods that appear later.

When wrapping an overloaded function, there is a chance that you will get an error message like this:

example.i:3: Warning(467): Overloaded foo(int) not supported (no type checking
rule for 'int').

This error means that the target language module supports overloading, but for some reason there is no type-checking rule that can be used to generate a working dispatch function. The resulting behavior is then undefined. You should report this as a bug to the SWIG bug tracking database.

If you get an error message such as the following,

foo.i:6. Overloaded declaration ignored.  Spam::foo(double )
foo.i:5. Previous declaration is Spam::foo(int )
foo.i:7. Overloaded declaration ignored.  Spam::foo(Bar *,Spam *,int )
foo.i:5. Previous declaration is Spam::foo(int )

it means that the target language module has not yet implemented support for overloaded functions and methods. The only way to fix the problem is to read the next section.

6.15.3 Ambiguity resolution and renaming

If an ambiguity in overload resolution occurs or if a module doesn't allow overloading, there are a few strategies for dealing with the problem. First, you can tell SWIG to ignore one of the methods. This is easy---simply use the %ignore directive. For example:

%ignore foo(long);

void foo(int);
void foo(long);       // Ignored.  Oh well.

The other alternative is to rename one of the methods. This can be done using %rename. For example:

%rename("foo_short") foo(short);
%rename(foo_long) foo(long);

void foo(int);
void foo(short);      // Accessed as foo_short()
void foo(long);       // Accessed as foo_long()

Note that the quotes around the new name are optional, however, should the new name be a C/C++ keyword they would be essential in order to avoid a parsing error. The %ignore and %rename directives are both rather powerful in their ability to match declarations. When used in their simple form, they apply to both global functions and methods. For example:

/* Forward renaming declarations */
%rename(foo_i) foo(int); 
%rename(foo_d) foo(double);
...
void foo(int);           // Becomes 'foo_i'
void foo(char *c);       // Stays 'foo' (not renamed)

class Spam {
public:
   void foo(int);      // Becomes 'foo_i'
   void foo(double);   // Becomes 'foo_d'
   ...
};

If you only want the renaming to apply to a certain scope, the C++ scope resolution operator (::) can be used. For example:

%rename(foo_i) ::foo(int);      // Only rename foo(int) in the global scope.
                                // (will not rename class members)

%rename(foo_i) Spam::foo(int);  // Only rename foo(int) in class Spam

When a renaming operator is applied to a class as in Spam::foo(int), it is applied to that class and all derived classes. This can be used to apply a consistent renaming across an entire class hierarchy with only a few declarations. For example:

%rename(foo_i) Spam::foo(int);
%rename(foo_d) Spam::foo(double);

class Spam {
public:
   virtual void foo(int);      // Renamed to foo_i
   virtual void foo(double);   // Renamed to foo_d
   ...
};

class Bar : public Spam {
public:
   virtual void foo(int);      // Renamed to foo_i
   virtual void foo(double);   // Renamed to foo_d
...
};

class Grok : public Bar {
public:
   virtual void foo(int);      // Renamed to foo_i
   virtual void foo(double);   // Renamed to foo_d
...
};

It is also possible to include %rename specifications in the class definition itself. For example:

class Spam {
   %rename(foo_i) foo(int);
   %rename(foo_d) foo(double);
public:
   virtual void foo(int);      // Renamed to foo_i
   virtual void foo(double);   // Renamed to foo_d
   ...
};

class Bar : public Spam {
public:
   virtual void foo(int);      // Renamed to foo_i
   virtual void foo(double);   // Renamed to foo_d
...
};

In this case, the %rename directives still get applied across the entire inheritance hierarchy, but it's no longer necessary to explicitly specify the class prefix Spam::.

A special form of %rename can be used to apply a renaming just to class members (of all classes):

%rename(foo_i) *::foo(int);   // Only rename foo(int) if it appears in a class.

Note: the *:: syntax is non-standard C++, but the '*' is meant to be a wildcard that matches any class name (we couldn't think of a better alternative so if you have a better idea, send email to the swig-devel mailing list.

Although this discussion has primarily focused on %rename all of the same rules also apply to %ignore. For example:

%ignore foo(double);          // Ignore all foo(double)
%ignore Spam::foo;            // Ignore foo in class Spam
%ignore Spam::foo(double);    // Ignore foo(double) in class Spam
%ignore *::foo(double);       // Ignore foo(double) in all classes

When applied to a base class, %ignore forces all definitions in derived classes to disappear. For example, %ignore Spam::foo(double) will eliminate foo(double) in Spam and all classes derived from Spam.

Notes on %rename and %ignore:

6.15.4 Comments on overloading

Support for overloaded methods was first added in SWIG-1.3.14. The implementation is somewhat unusual when compared to similar tools. For instance, the order in which declarations appear is largely irrelevant in SWIG. Furthermore, SWIG does not rely upon trial execution or exception handling to figure out which method to invoke.

Internally, the overloading mechanism is completely configurable by the target language module. Therefore, the degree of overloading support may vary from language to language. As a general rule, statically typed languages like Java are able to provide more support than dynamically typed languages like Perl, Python, Ruby, and Tcl.

6.16 Wrapping overloaded operators

C++ overloaded operator declarations can be wrapped. For example, consider a class like this:

class Complex {
private:
  double rpart, ipart;
public:
  Complex(double r = 0, double i = 0) : rpart(r), ipart(i) { }
  Complex(const Complex &c) : rpart(c.rpart), ipart(c.ipart) { }
  Complex &operator=(const Complex &c) {
    rpart = c.rpart;
    ipart = c.ipart;
    return *this;
  }
  Complex operator+(const Complex &c) const {
    return Complex(rpart+c.rpart, ipart+c.ipart);
  }
  Complex operator-(const Complex &c) const {
    return Complex(rpart-c.rpart, ipart-c.ipart);
  }
  Complex operator*(const Complex &c) const {
    return Complex(rpart*c.rpart - ipart*c.ipart,
		   rpart*c.ipart + c.rpart*ipart);
  }
  Complex operator-() const {
    return Complex(-rpart, -ipart);
  }
  double re() const { return rpart; }
  double im() const { return ipart; }
};

When operator declarations appear, they are handled in exactly the same manner as regular methods. However, the names of these methods are set to strings like "operator +" or "operator -". The problem with these names is that they are illegal identifiers in most scripting languages. For instance, you can't just create a method called "operator +" in Python--there won't be any way to call it.

Some language modules already know how to automatically handle certain operators (mapping them into operators in the target language). However, the underlying implementation of this is really managed in a very general way using the %rename directive. For example, in Python a declaration similar to this is used:

%rename(__add__) Complex::operator+;

This binds the + operator to a method called __add__ (which is conveniently the same name used to implement the Python + operator). Internally, the generated wrapper code for a wrapped operator will look something like this pseudocode:

_wrap_Complex___add__(args) {
   ... get args ...
   obj->operator+(args);
   ...
}

When used in the target language, it may now be possible to use the overloaded operator normally. For example:

>>> a = Complex(3,4)
>>> b = Complex(5,2)
>>> c = a + b           # Invokes __add__ method

It is important to realize that there is nothing magical happening here. The %rename directive really only picks a valid method name. If you wrote this:

%rename(add) operator+;

The resulting scripting interface might work like this:

a = Complex(3,4)
b = Complex(5,2)
c = a.add(b)      # Call a.operator+(b)

All of the techniques described to deal with overloaded functions also apply to operators. For example:

%ignore Complex::operator=;             // Ignore = in class Complex
%ignore *::operator=;                   // Ignore = in all classes
%ignore operator=;                      // Ignore = everywhere.

%rename(__sub__) Complex::operator-; 
%rename(__neg__) Complex::operator-();  // Unary - 

The last part of this example illustrates how multiple definitions of the operator- method might be handled.

Handling operators in this manner is mostly straightforward. However, there are a few subtle issues to keep in mind:

6.17 Class extension

New methods can be added to a class using the %extend directive. This directive is primarily used in conjunction with proxy classes to add additional functionality to an existing class. For example :

%module vector
%{
#include "vector.h"
%}

class Vector {
public:
	double x,y,z;
	Vector();
	~Vector();
	... bunch of C++ methods ...
	%extend {
		char *__str__() {
			static char temp[256];
			sprintf(temp,"[ %g, %g, %g ]", $self->x,$self->y,$self->z);
			return &temp[0];
		}
	}
};

This code adds a __str__ method to our class for producing a string representation of the object. In Python, such a method would allow us to print the value of an object using the print command.

>>>
>>> v = Vector();
>>> v.x = 3
>>> v.y = 4
>>> v.z = 0
>>> print(v)
[ 3.0, 4.0, 0.0 ]
>>>

The C++ 'this' pointer is often needed to access member variables, methods etc. The $self special variable should be used wherever you could use 'this'. The example above demonstrates this for accessing member variables. The implicit 'this' pointer that is present in C++ methods is not present in %extend methods. In order to access anything in the extended class or its base class, an explicit 'this' is required. The following example shows how one could access base class members:

struct Base {
  virtual void method(int v) {
    ...
  }
  int value;
};
struct Derived : Base {
};
%extend Derived {
  virtual void method(int v) {
    $self->Base::method(v);
    $self->value = v;
    ...
  }
}

The %extend directive follows all of the same conventions as its use with C structures. Please refer to the Adding member functions to C structures section for further details.

Compatibility note: The %extend directive is a new name for the %addmethods directive in SWIG1.1. Since %addmethods could be used to extend a structure with more than just methods, a more suitable directive name has been chosen.

6.18 Templates

Template type names may appear anywhere a type is expected in an interface file. For example:

void foo(vector<int> *a, int n);
void bar(list<int,100> *x);

There are some restrictions on the use of non-type arguments. Specifically, they have to be simple literals and not expressions. For example:

void bar(list<int,100> *x);    // OK
void bar(list<int,2*50> *x);   // Illegal

The type system is smart enough to figure out clever games you might try to play with typedef. For instance, consider this code:

typedef int Integer;
void foo(vector<int> *x, vector<Integer> *y);

In this case, vector<Integer> is exactly the same type as vector<int>. The wrapper for foo() will accept either variant.

Starting with SWIG-1.3.7, simple C++ template declarations can also be wrapped. SWIG-1.3.12 greatly expands upon the earlier implementation. Before discussing this any further, there are a few things you need to know about template wrapping. First, a bare C++ template does not define any sort of runnable object-code for which SWIG can normally create a wrapper. Therefore, in order to wrap a template, you need to give SWIG information about a particular template instantiation (e.g., vector<int>, array<double>, etc.). Second, an instantiation name such as vector<int> is generally not a valid identifier name in most target languages. Thus, you will need to give the template instantiation a more suitable name such as intvector when creating a wrapper.

To illustrate, consider the following template definition:

template<class T> class List {
private:
    T *data;
    int nitems;
    int maxitems;
public:
    List(int max) {
      data = new T [max];
      nitems = 0;
      maxitems = max;
    }
    ~List() {
      delete [] data;
    };
    void append(T obj) {
      if (nitems < maxitems) {
        data[nitems++] = obj;
      }
    }
    int length() {
      return nitems;
    }
    T get(int n) {
      return data[n];
    }
};

By itself, this template declaration is useless--SWIG simply ignores it because it doesn't know how to generate any code until unless a definition of T is provided.

One way to create wrappers for a specific template instantiation is to simply provide an expanded version of the class directly like this:

%rename(intList) List<int>;       // Rename to a suitable identifier
class List<int> {
private:
    int *data;
    int nitems;
    int maxitems;
public:
    List(int max);
    ~List();
    void append(int obj);
    int length();
    int get(int n);
};

The %rename directive is needed to give the template class an appropriate identifier name in the target language (most languages would not recognize C++ template syntax as a valid class name). The rest of the code is the same as what would appear in a normal class definition.

Since manual expansion of templates gets old in a hurry, the %template directive can be used to create instantiations of a template class. Semantically, %template is simply a shortcut---it expands template code in exactly the same way as shown above. Here are some examples:

/* Instantiate a few different versions of the template */
%template(intList) List<int>;
%template(doubleList) List<double>;

The argument to %template() is the name of the instantiation in the target language. The name you choose should not conflict with any other declarations in the interface file with one exception---it is okay for the template name to match that of a typedef declaration. For example:

%template(intList) List<int>;
...
typedef List<int> intList;    // OK

SWIG can also generate wrappers for function templates using a similar technique. For example:

// Function template
template<class T> T max(T a, T b) { return a > b ? a : b; }

// Make some different versions of this function
%template(maxint) max<int>;
%template(maxdouble) max<double>;

In this case, maxint and maxdouble become unique names for specific instantiations of the function.

The number of arguments supplied to %template should match that in the original template definition. Template default arguments are supported. For example:

template vector<typename T, int max=100> class vector {
...
};

%template(intvec) vector<int>;           // OK
%template(vec1000) vector<int,1000>;     // OK

The %template directive should not be used to wrap the same template instantiation more than once in the same scope. This will generate an error. For example:

%template(intList) List<int>;
%template(Listint) List<int>;    // Error.   Template already wrapped.

This error is caused because the template expansion results in two identical classes with the same name. This generates a symbol table conflict. Besides, it probably more efficient to only wrap a specific instantiation only once in order to reduce the potential for code bloat.

Since the type system knows how to handle typedef, it is generally not necessary to instantiate different versions of a template for typenames that are equivalent. For instance, consider this code:

%template(intList) vector<int>;
typedef int Integer;
...
void foo(vector<Integer> *x);

In this case, vector<Integer> is exactly the same type as vector<int>. Any use of Vector<Integer> is mapped back to the instantiation of vector<int> created earlier. Therefore, it is not necessary to instantiate a new class for the type Integer (doing so is redundant and will simply result in code bloat).

When a template is instantiated using %template, information about that class is saved by SWIG and used elsewhere in the program. For example, if you wrote code like this,

...
%template(intList) List<int>;
...
class UltraList : public List<int> {
   ...
};

then SWIG knows that List<int> was already wrapped as a class called intList and arranges to handle the inheritance correctly. If, on the other hand, nothing is known about List<int> , you will get a warning message similar to this:

example.h:42. Nothing known about class 'List<int >' (ignored). 
example.h:42. Maybe you forgot to instantiate 'List<int >' using %template. 

If a template class inherits from another template class, you need to make sure that base classes are instantiated before derived classes. For example:

template<class T> class Foo {
...
};

template<class T> class Bar : public Foo<T> {
...
};

// Instantiate base classes first 
%template(intFoo) Foo<int>;
%template(doubleFoo) Foo<double>;

// Now instantiate derived classes
%template(intBar) Bar<int>;
%template(doubleBar) Bar<double>;

The order is important since SWIG uses the instantiation names to properly set up the inheritance hierarchy in the resulting wrapper code (and base classes need to be wrapped before derived classes). Don't worry--if you get the order wrong, SWIG should generate a warning message.

Occasionally, you may need to tell SWIG about base classes that are defined by templates, but which aren't supposed to be wrapped. Since SWIG is not able to automatically instantiate templates for this purpose, you must do it manually. To do this, simply use %template with no name. For example:

// Instantiate traits<double,double>, but don't wrap it.
%template() traits<double,double>;

If you have to instantiate a lot of different classes for many different types, you might consider writing a SWIG macro. For example:

%define TEMPLATE_WRAP(prefix, T...) 
%template(prefix ## Foo) Foo<T >;
%template(prefix ## Bar) Bar<T >;
...
%enddef

TEMPLATE_WRAP(int, int)
TEMPLATE_WRAP(double, double)
TEMPLATE_WRAP(String, char *)
TEMPLATE_WRAP(PairStringInt, std::pair<string, int>)
...

Note the use of a vararg macro for the type T. If this wasn't used, the comma in the templated type in last example would not be possible.

The SWIG template mechanism does support specialization. For instance, if you define a class like this,

template<> class List<int> {
private:
    int *data;
    int nitems;
    int maxitems;
public:
    List(int max);
    ~List();
    void append(int obj);
    int length();
    int get(int n);
};

then SWIG will use this code whenever the user expands List<int> . In practice, this may have very little effect on the underlying wrapper code since specialization is often used to provide slightly modified method bodies (which are ignored by SWIG). However, special SWIG directives such as %typemap, %extend, and so forth can be attached to a specialization to provide customization for specific types.

Partial template specialization is partially supported by SWIG. For example, this code defines a template that is applied when the template argument is a pointer.

template<class T> class List<T*> {
private:
    T *data;
    int nitems;
    int maxitems;
public:
    List(int max);
    ~List();
    void append(int obj);
    int length();
    T get(int n);
};

SWIG should be able to handle most simple uses of partial specialization. However, it may fail to match templates properly in more complicated cases. For example, if you have this code,

template<class T1, class T2> class Foo<T1, T2 *> { };

SWIG isn't able to match it properly for instantiations like Foo<int *, int *>. This problem is not due to parsing, but due to the fact that SWIG does not currently implement all of the C++ argument deduction rules.

Member function templates are supported. The underlying principle is the same as for normal templates--SWIG can't create a wrapper unless you provide more information about types. For example, a class with a member template might look like this:

class Foo {
public:
     template<class T> void bar(T x, T y) { ... };
     ...
};

To expand the template, simply use %template inside the class.

class Foo {
public:
     template<class T> void bar(T x, T y) { ... };
     ...
     %template(barint)    bar<int>;
     %template(bardouble) bar<double>;
};

Or, if you want to leave the original class definition alone, just do this:

class Foo {
public:
     template<class T> void bar(T x, T y) { ... };
     ...
};
...
%extend Foo {
     %template(barint)    bar<int>;
     %template(bardouble) bar<double>;
};

or simply

class Foo {
public:
     template<class T> void bar(T x, T y) { ... };
     ...
};
...

%template(bari) Foo::bar<int>;
%template(bard) Foo::bar<double>;

In this case, the %extend directive is not needed, and %template does the exactly same job, i.e., it adds two new methods to the Foo class.

Note: because of the way that templates are handled, the %template directive must always appear after the definition of the template to be expanded.

Now, if your target language supports overloading, you can even try

%template(bar) Foo::bar<int>;
%template(bar) Foo::bar<double>;

and since the two new wrapped methods have the same name 'bar', they will be overloaded, and when called, the correct method will be dispatched depending on the argument type.

When used with members, the %template directive may be placed in another template class. Here is a slightly perverse example:

// A template
template<class T> class Foo {
public:
     // A member template
     template<class S> T bar(S x, S y) { ... };
     ...
};

// Expand a few member templates
%extend Foo {
  %template(bari) bar<int>;
  %template(bard) bar<double>;
}

// Create some wrappers for the template
%template(Fooi) Foo<int>;
%template(Food) Foo<double>;

Miraculously, you will find that each expansion of Foo has member functions bari() and bard() added.

A common use of member templates is to define constructors for copies and conversions. For example:

template<class T1, class T2> struct pair {
   T1 first;
   T2 second;
   pair() : first(T1()), second(T2()) { }
   pair(const T1 &x, const T2 &y) : first(x), second(y) { }
   template<class U1, class U2> pair(const pair<U1,U2> &x) 
                                        : first(x.first),second(x.second) { }
};

This declaration is perfectly acceptable to SWIG, but the constructor template will be ignored unless you explicitly expand it. To do that, you could expand a few versions of the constructor in the template class itself. For example:

%extend pair {
   %template(pair) pair<T1,T2>;        // Generate default copy constructor
};

When using %extend in this manner, notice how you can still use the template parameters in the original template definition.

Alternatively, you could expand the constructor template in selected instantiations. For example:

// Instantiate a few versions
%template(pairii) pair<int,int>;
%template(pairdd) pair<double,double>;

// Create a default constructor only 
%extend pair<int,int> {
   %template(paird) pair<int,int>;         // Default constructor
};

// Create default and conversion constructors 
%extend pair<double,double> {
   %template(paird) pair<double,dobule>;   // Default constructor
   %template(pairc) pair<int,int>;         // Conversion constructor
};

And if your target language supports overloading, then you can try instead:

// Create default and conversion constructors 
%extend pair<double,double> {
   %template(pair) pair<double,dobule>;   // Default constructor
   %template(pair) pair<int,int>;         // Conversion constructor
};

In this case, the default and conversion constructors have the same name. Hence, Swig will overload them and define an unique visible constructor, that will dispatch the proper call depending on the argument type.

If all of this isn't quite enough and you really want to make someone's head explode, SWIG directives such as %rename, %extend, and %typemap can be included directly in template definitions. For example:

// File : list.h
template<class T> class List {
   ...
public:
    %rename(__getitem__) get(int);
    List(int max);
    ~List();
    ...
    T get(int index);
    %extend {
        char *__str__() {
            /* Make a string representation */
            ...
        }
    }
};

In this example, the extra SWIG directives are propagated to every template instantiation.

It is also possible to separate these declarations from the template class. For example:

%rename(__getitem__) List::get;
%extend List {
    char *__str__() {
        /* Make a string representation */
        ...
    }
    /* Make a copy */
    T *__copy__() {
       return new List<T>(*$self);
    }
};

...
template<class T> class List {
   ...
   public:
   List() { };
   ...
};

When %extend is decoupled from the class definition, it is legal to use the same template parameters as provided in the class definition. These are replaced when the template is expanded. In addition, the %extend directive can be used to add additional methods to a specific instantiation. For example:

%template(intList) List<int>;

%extend List<int> {
    void blah() {
          printf("Hey, I'm an List<int>!\n");
    }
};

SWIG even supports overloaded templated functions. As usual the %template directive is used to wrap templated functions. For example:

template<class T> void foo(T x) { };
template<class T> void foo(T x, T y) { };

%template(foo) foo<int>;

This will generate two overloaded wrapper methods, the first will take a single integer as an argument and the second will take two integer arguments.

Needless to say, SWIG's template support provides plenty of opportunities to break the universe. That said, an important final point is that SWIG does not perform extensive error checking of templates! Specifically, SWIG does not perform type checking nor does it check to see if the actual contents of the template declaration make any sense. Since the C++ compiler will hopefully check this when it compiles the resulting wrapper file, there is no practical reason for SWIG to duplicate this functionality (besides, none of the SWIG developers are masochistic enough to want to implement this right now).

Compatibility Note: The first implementation of template support relied heavily on macro expansion in the preprocessor. Templates have been more tightly integrated into the parser and type system in SWIG-1.3.12 and the preprocessor is no longer used. Code that relied on preprocessing features in template expansion will no longer work. However, SWIG still allows the # operator to be used to generate a string from a template argument.

Compatibility Note: In earlier versions of SWIG, the %template directive introduced a new class name. This name could then be used with other directives. For example:

%template(vectori) vector<int>;
%extend vectori {
    void somemethod() { }
};

This behavior is no longer supported. Instead, you should use the original template name as the class name. For example:

%template(vectori) vector<int>;
%extend vector<int> {
    void somemethod() { }
};

Similar changes apply to typemaps and other customization features.

6.19 Namespaces

Support for C++ namespaces is a relatively late addition to SWIG, first appearing in SWIG-1.3.12. Before describing the implementation, it is worth noting that the semantics of C++ namespaces is extremely non-trivial--especially with regard to the C++ type system and class machinery. At a most basic level, namespaces are sometimes used to encapsulate common functionality. For example:

namespace math {
   double sin(double);
   double cos(double);

   class Complex {
      double im,re;
   public:
      ...
   };
   ...
};

Members of the namespace are accessed in C++ by prepending the namespace prefix to names. For example:

double x = math::sin(1.0);
double magnitude(math::Complex *c);
math::Complex c;
...

At this level, namespaces are relatively easy to manage. However, things start to get very ugly when you throw in the other ways a namespace can be used. For example, selective symbols can be exported from a namespace with using.

using math::Complex;
double magnitude(Complex *c);       // Namespace prefix stripped

Similarly, the contents of an entire namespace can be made available like this:

using namespace math;
double x = sin(1.0);
double magnitude(Complex *c);

Alternatively, a namespace can be aliased:

namespace M = math;
double x = M::sin(1.0);
double magnitude(M::Complex *c);

Using combinations of these features, it is possible to write head-exploding code like this:

namespace A {
  class Foo {
  };
}

namespace B {
   namespace C {
      using namespace A;
   }
   typedef C::Foo FooClass;
}

namespace BIGB = B;

namespace D {
   using BIGB::FooClass;
   class Bar : public FooClass {
   }
};

class Spam : public D::Bar {
};

void evil(A::Foo *a, B::FooClass *b, B::C::Foo *c, BIGB::FooClass *d,
          BIGB::C::Foo *e, D::FooClass *f);

Given the possibility for such perversion, it's hard to imagine how every C++ programmer might want such code wrapped into the target language. Clearly this code defines three different classes. However, one of those classes is accessible under at least six different names!

SWIG fully supports C++ namespaces in its internal type system and class handling code. If you feed SWIG the above code, it will be parsed correctly, it will generate compilable wrapper code, and it will produce a working scripting language module. However, the default wrapping behavior is to flatten namespaces in the target language. This means that the contents of all namespaces are merged together in the resulting scripting language module. For example, if you have code like this,

%module foo
namespace foo {
   void bar(int);
   void spam();
}

namespace bar {
   void blah();
}

then SWIG simply creates three wrapper functions bar(), spam(), and blah() in the target language. SWIG does not prepend the names with a namespace prefix nor are the functions packaged in any kind of nested scope.

There is some rationale for taking this approach. Since C++ namespaces are often used to define modules in C++, there is a natural correlation between the likely contents of a SWIG module and the contents of a namespace. For instance, it would not be unreasonable to assume that a programmer might make a separate extension module for each C++ namespace. In this case, it would be redundant to prepend everything with an additional namespace prefix when the module itself already serves as a namespace in the target language. Or put another way, if you want SWIG to keep namespaces separate, simply wrap each namespace with its own SWIG interface.

Because namespaces are flattened, it is possible for symbols defined in different namespaces to generate a name conflict in the target language. For example:

namespace A {
   void foo(int);
}
namespace B {
   void foo(double);
}

When this conflict occurs, you will get an error message that resembles this:

example.i:26. Error. 'foo' is multiply defined in the generated module.
example.i:23. Previous declaration of 'foo'

To resolve this error, simply use %rename to disambiguate the declarations. For example:

%rename(B_foo) B::foo;
...
namespace A {
   void foo(int);
}
namespace B {
   void foo(double);     // Gets renamed to B_foo
}

Similarly, %ignore can be used to ignore declarations.

using declarations do not have any effect on the generated wrapper code. They are ignored by SWIG language modules and they do not result in any code. However, these declarations are used by the internal type system to track type-names. Therefore, if you have code like this:

namespace A {
   typedef int Integer;
}
using namespace A;
void foo(Integer x);

SWIG knows that Integer is the same as A::Integer which is the same as int.

Namespaces may be combined with templates. If necessary, the %template directive can be used to expand a template defined in a different namespace. For example:

namespace foo {
    template<typename T> T max(T a, T b) { return a > b ? a : b; }
}

using foo::max;

%template(maxint)   max<int>;           // Okay.
%template(maxfloat) foo::max<float>;    // Okay (qualified name).

namespace bar {
    using namespace foo;
    %template(maxdouble)  max<double>;    // Okay.
}

The combination of namespaces and other SWIG directives may introduce subtle scope-related problems. The key thing to keep in mind is that all SWIG generated wrappers are produced in the global namespace. Symbols from other namespaces are always accessed using fully qualified names---names are never imported into the global space unless the interface happens to do so with a using declaration. In almost all cases, SWIG adjusts typenames and symbols to be fully qualified. However, this is not done in code fragments such as function bodies, typemaps, exception handlers, and so forth. For example, consider the following:

namespace foo {
    typedef int Integer;
    class bar {
    public:
       ...
    };
}

%extend foo::bar {
   Integer add(Integer x, Integer y) {
       Integer r = x + y;        // Error. Integer not defined in this scope
       return r;
   }
};

In this case, SWIG correctly resolves the added method parameters and return type to foo::Integer. However, since function bodies aren't parsed and such code is emitted in the global namespace, this code produces a compiler error about Integer. To fix the problem, make sure you use fully qualified names. For example:

%extend foo::bar {
   Integer add(Integer x, Integer y) {
       foo::Integer r = x + y;        // Ok.
       return r;
   }
};

Note: SWIG does not propagate using declarations to the resulting wrapper code. If these declarations appear in an interface, they should also appear in any header files that might have been included in a %{ ... %} section. In other words, don't insert extra using declarations into a SWIG interface unless they also appear in the underlying C++ code.

Note: Code inclusion directives such as %{ ... %} or %inline %{ ... %} should not be placed inside a namespace declaration. The code emitted by these directives will not be enclosed in a namespace and you may get very strange results. If you need to use namespaces with these directives, consider the following:

// Good version
%inline %{
namespace foo {
     void bar(int) { ... }
     ...
}
%}

// Bad version.  Emitted code not placed in namespace.
namespace foo {
%inline %{
     void bar(int) { ... }   /* I'm bad */
     ...
%}
}

Note: When the %extend directive is used inside a namespace, the namespace name is included in the generated functions. For example, if you have code like this,

namespace foo {
   class bar {
   public:
        %extend {
           int blah(int x);
        };
   };
}

the added method blah() is mapped to a function int foo_bar_blah(foo::bar *self, int x). This function resides in the global namespace.

Note: Although namespaces are flattened in the target language, the SWIG generated wrapper code observes the same namespace conventions as used in the input file. Thus, if there are no symbol conflicts in the input, there will be no conflicts in the generated code.

Note: Namespaces have a subtle effect on the wrapping of conversion operators. For instance, suppose you had an interface like this:

namespace foo {
   class bar;
   class spam {
   public:
        ...
        operator bar();      // Conversion of spam -> bar
        ...
   };
}

To wrap the conversion function, you might be inclined to write this:

%rename(tofoo) foo::spam::operator bar();

The only problem is that it doesn't work. The reason it doesn't work is that bar is not defined in the global scope. Therefore, to make it work, do this instead:

%rename(tofoo) foo::spam::operator foo::bar();

Note: The flattening of namespaces is only intended to serve as a basic namespace implementation. Since namespaces are a new addition to SWIG, none of the target language modules are currently programmed with any namespace awareness. In the future, language modules may or may not provide more advanced namespace support.

6.20 Exception specifications

When C++ programs utilize exceptions, exceptional behavior is sometimes specified as part of a function or method declaration. For example:

class Error { };

class Foo {
public:
    ...
    void blah() throw(Error);
    ...
};

If an exception specification is used, SWIG automatically generates wrapper code for catching the indicated exception and, when possible, rethrowing it into the target language, or converting it into an error in the target language otherwise. For example, in Python, you can write code like this:

f = Foo()
try:
    f.blah()
except Error,e:
     # e is a wrapped instance of "Error"

Details of how to tailor code for handling the caught C++ exception and converting it into the target language's exception/error handling mechanism is outlined in the "throws" typemap section.

Since exception specifications are sometimes only used sparingly, this alone may not be enough to properly handle C++ exceptions. To do that, a different set of special SWIG directives are used. Consult the "Exception handling with %exception" section for details. The next section details a way of simulating an exception specification or replacing an existing one.

6.21 Exception handling with %catches

Exceptions are automatically handled for methods with an exception specification. Similar handling can be achieved for methods without exception specifications through the %catches feature. It is also possible to replace any declared exception specification using the %catches feature. In fact, %catches uses the same "throws" typemaps that SWIG uses for exception specifications in handling exceptions. The %catches feature must contain a list of possible types that can be thrown. For each type that is in the list, SWIG will generate a catch handler, in the same way that it would for types declared in the exception specification. Note that the list can also include the catch all specification "...". For example,

struct EBase { virtual ~EBase(); };
struct Error1 : EBase { };
struct Error2 : EBase { };
struct Error3 : EBase { };
struct Error4 : EBase { };

%catches(Error1,Error2,...) Foo::bar();
%catches(EBase) Foo::blah();

class Foo {
public:
    ...
    void bar();
    void blah() throw(Error1,Error2,Error3,Error4);
    ...
};

For the Foo::bar() method, which can throw anything, SWIG will generate catch handlers for Error1, Error2 as well as a catch all handler (...). Each catch handler will convert the caught exception and convert it into a target language error/exception. The catch all handler will convert the caught exception into an unknown error/exception.

Without the %catches feature being attached to Foo::blah(), SWIG will generate catch handlers for all of the types in the exception specification, that is, Error1, Error2, Error3, Error4. However, with the %catches feature above, just a single catch handler for the base class, EBase will be generated to convert the C++ exception into a target language error/exception.

6.22 Pointers to Members

Starting with SWIG-1.3.7, there is limited parsing support for pointers to C++ class members. For example:

double do_op(Object *o, double (Object::*callback)(double,double));
extern double (Object::*fooptr)(double,double);
%constant double (Object::*FOO)(double,double) = &Object::foo;

Although these kinds of pointers can be parsed and represented by the SWIG type system, few language modules know how to handle them due to implementation differences from standard C pointers. Readers are strongly advised to consult an advanced text such as the "The Annotated C++ Manual" for specific details.

When pointers to members are supported, the pointer value might appear as a special string like this:

>>> print example.FOO
_ff0d54a800000000_m_Object__f_double_double__double
>>>

In this case, the hexadecimal digits represent the entire value of the pointer which is usually the contents of a small C++ structure on most machines.

SWIG's type-checking mechanism is also more limited when working with member pointers. Normally SWIG tries to keep track of inheritance when checking types. However, no such support is currently provided for member pointers.

6.23 Smart pointers and operator->()

In some C++ programs, objects are often encapsulated by smart-pointers or proxy classes. This is sometimes done to implement automatic memory management (reference counting) or persistence. Typically a smart-pointer is defined by a template class where the -> operator has been overloaded. This class is then wrapped around some other class. For example:

// Smart-pointer class
template<class T> class SmartPtr {
    T *pointee;
public:
    ...
    T *operator->() {
        return pointee;
    }
    ...
};

// Ordinary class
class Foo_Impl {
public:
    int x;
    virtual void bar();
    ...
};

// Smart-pointer wrapper
typedef SmartPtr<Foo_Impl> Foo;

// Create smart pointer Foo
Foo make_Foo() {
    return SmartPtr(new Foo_Impl());
}

// Do something with smart pointer Foo
void do_something(Foo f) {
    printf("x = %d\n", f->x);
    f->bar();
}

A key feature of this approach is that by defining operator-> the methods and attributes of the object wrapped by a smart pointer are transparently accessible. For example, expressions such as these (from the previous example),

f->x
f->bar()

are transparently mapped to the following

(f.operator->())->x;
(f.operator->())->bar();

When generating wrappers, SWIG tries to emulate this functionality to the extent that it is possible. To do this, whenever operator->() is encountered in a class, SWIG looks at its returned type and uses it to generate wrappers for accessing attributes of the underlying object. For example, wrapping the above code produces wrappers like this:

int Foo_x_get(Foo *f) {
   return (*f)->x;
}
void Foo_x_set(Foo *f, int value) {
   (*f)->x = value;
}
void Foo_bar(Foo *f) {
   (*f)->bar();
}

These wrappers take a smart-pointer instance as an argument, but dereference it in a way to gain access to the object returned by operator->(). You should carefully compare these wrappers to those in the first part of this chapter (they are slightly different).

The end result is that access looks very similar to C++. For example, you could do this in Python:

>>> f = make_Foo()
>>> print f.x
0
>>> f.bar()
>>>

When generating wrappers through a smart-pointer, SWIG tries to generate wrappers for all methods and attributes that might be accessible through operator->(). This includes any methods that might be accessible through inheritance. However, there are a number of restrictions:

If your intent is to only expose the smart-pointer class in the interface, it is not necessary to wrap both the smart-pointer class and the class for the underlying object. However, you must still tell SWIG about both classes if you want the technique described in this section to work. To only generate wrappers for the smart-pointer class, you can use the %ignore directive. For example:

%ignore Foo;
class Foo {       // Ignored
};

class Bar {
public:
   Foo *operator->();
   ...
};

Alternatively, you can import the definition of Foo from a separate file using %import.

Note: When a class defines operator->(), the operator itself is wrapped as a method __deref__(). For example:

f = Foo()               # Smart-pointer
p = f.__deref__()       # Raw pointer from operator->

Note: To disable the smart-pointer behavior, use %ignore to ignore operator->(). For example:

%ignore Bar::operator->;

Note: Smart pointer support was first added in SWIG-1.3.14.

6.24 Using declarations and inheritance

using declarations are sometimes used to adjust access to members of base classes. For example:

class Foo {
public:
      int  blah(int x);
};

class Bar {
public:
      double blah(double x);
};

class FooBar : public Foo, public Bar {
public:
      using Foo::blah;  
      using Bar::blah;
      char *blah(const char *x);
};

In this example, the using declarations make different versions of the overloaded blah() method accessible from the derived class. For example:

FooBar *f;
f->blah(3);         // Ok. Invokes Foo::blah(int)
f->blah(3.5);       // Ok. Invokes Bar::blah(double)
f->blah("hello");   // Ok. Invokes FooBar::blah(const char *);

SWIG emulates the same functionality when creating wrappers. For example, if you wrap this code in Python, the module works just like you would expect:

>>> import example
>>> f = example.FooBar()
>>> f.blah(3)
>>> f.blah(3.5)
>>> f.blah("hello")

using declarations can also be used to change access when applicable. For example:

class Foo {
protected:
    int x;
    int blah(int x);
};

class Bar : public Foo {
public:
    using Foo::x;       // Make x public
    using Foo::blah;    // Make blah public
};

This also works in SWIG---the exposed declarations will be wrapped normally.

When using declarations are used as shown in these examples, declarations from the base classes are copied into the derived class and wrapped normally. When copied, the declarations retain any properties that might have been attached using %rename , %ignore, or %feature. Thus, if a method is ignored in a base class, it will also be ignored by a using declaration.

Because a using declaration does not provide fine-grained control over the declarations that get imported, it may be difficult to manage such declarations in applications that make heavy use of SWIG customization features. If you can't get using to work correctly, you can always change the interface to the following:


class FooBar : public Foo, public Bar {
public:
#ifndef SWIG
      using Foo::blah;  
      using Bar::blah;
#else
      int blah(int x);         // explicitly tell SWIG about other declarations
      double blah(double x);
#endif

      char *blah(const char *x);
};

Notes:

6.25 Nested classes

There is limited support for nested structs and unions when wrapping C code, see Nested structures for further details. However, there is no nested class/struct/union support when wrapping C++ code (using the -c++ commandline option). This may be added at a future date, however, until then some of the following workarounds can be applied.

It might be possible to use partial class information. Since SWIG does not need the entire class specification to work, conditional compilation can be used to comment out the problematic nested class definition, you might do this:

class Foo {
public:
#ifndef SWIG
   class Bar {
   public:
     ...
   };
#endif
   Foo();
  ~Foo();
   ...
};

The next workaround assumes you cannot modify the source code as was done above and it provides a solution for methods that use nested class types. Imagine we are wrapping the Outer class which contains a nested class Inner:

// File outer.h
class Outer {
public:
  class Inner {
    public:
      int var;
      Inner(int v = 0) : var(v) {}
  };
  void method(Inner inner);
};

The following interface file works around SWIG nested class limitations by redefining the nested class as a global class. A typedef for the compiler is also required in order for the generated wrappers to compile.

// File : example.i
%module example

// Suppress SWIG warning
#pragma SWIG nowarn=SWIGWARN_PARSE_NESTED_CLASS

// Redefine nested class in global scope in order for SWIG to generate
// a proxy class. Only SWIG parses this definition.
class Inner {
  public:
    int var;
    Inner(int v = 0) : var(v) {}
};

%{
#include "outer.h"
%}
%include "outer.h"

%{
// SWIG thinks that Inner is a global class, so we need to trick the C++
// compiler into understanding this so called global type.
typedef Outer::Inner Inner;
%}

The downside to this approach is having to maintain two definitions of Inner, the real one and the one in the interface file that SWIG parses.

6.26 A brief rant about const-correctness

A common issue when working with C++ programs is dealing with all possible ways in which the const qualifier (or lack thereof) will break your program, all programs linked against your program, and all programs linked against those programs.

Although SWIG knows how to correctly deal with const in its internal type system and it knows how to generate wrappers that are free of const-related warnings, SWIG does not make any attempt to preserve const-correctness in the target language. Thus, it is possible to pass const qualified objects to non-const methods and functions. For example, consider the following code in C++:

const Object * foo();
void bar(Object *);

...
// C++ code
void blah() {
   bar(foo());         // Error: bar discards const
};

Now, consider the behavior when wrapped into a Python module:

>>> bar(foo())         # Okay
>>> 

Although this is clearly a violation of the C++ type-system, fixing the problem doesn't seem to be worth the added implementation complexity that would be required to support it in the SWIG run-time type system. There are no plans to change this in future releases (although we'll never rule anything out entirely).

The bottom line is that this particular issue does not appear to be a problem for most SWIG projects. Of course, you might want to consider using another tool if maintaining constness is the most important part of your project.

6.27 Where to go for more information

If you're wrapping serious C++ code, you might want to pick up a copy of "The Annotated C++ Reference Manual" by Ellis and Stroustrup. This is the reference document we use to guide a lot of SWIG's C++ support.


7 Preprocessing

SWIG includes its own enhanced version of the C preprocessor. The preprocessor supports the standard preprocessor directives and macro expansion rules. However, a number of modifications and enhancements have been made. This chapter describes some of these modifications.

7.1 File inclusion

To include another file into a SWIG interface, use the %include directive like this:

%include "pointer.i"

Unlike, #include, %include includes each file once (and will not reload the file on subsequent %include declarations). Therefore, it is not necessary to use include-guards in SWIG interfaces.

By default, the #include is ignored unless you run SWIG with the -includeall option. The reason for ignoring traditional includes is that you often don't want SWIG to try and wrap everything included in standard header system headers and auxiliary files.

7.2 File imports

SWIG provides another file inclusion directive with the %import directive. For example:

%import "foo.i"

The purpose of %import is to collect certain information from another SWIG interface file or a header file without actually generating any wrapper code. Such information generally includes type declarations (e.g., typedef) as well as C++ classes that might be used as base-classes for class declarations in the interface. The use of %import is also important when SWIG is used to generate extensions as a collection of related modules. This is an advanced topic and is described in a later chapter.

The -importall directive tells SWIG to follow all #include statements as imports. This might be useful if you want to extract type definitions from system header files without generating any wrappers.

7.3 Conditional Compilation

SWIG fully supports the use of #if, #ifdef, #ifndef, #else, #endif to conditionally include parts of an interface. The following symbols are predefined by SWIG when it is parsing the interface:

SWIG                            Always defined when SWIG is processing a file
SWIGIMPORTED                    Defined when SWIG is importing a file with %import
SWIGMAC                         Defined when running SWIG on the Macintosh
SWIGWIN                         Defined when running SWIG under Windows
SWIG_VERSION                    Hexadecimal number containing SWIG version,
                                such as 0x010311 (corresponding to SWIG-1.3.11).

SWIGCHICKEN                     Defined when using CHICKEN
SWIGCSHARP                      Defined when using C#
SWIGGUILE                       Defined when using Guile
SWIGJAVA                        Defined when using Java
SWIGLUA                         Defined when using Lua
SWIGMODULA3                     Defined when using Modula-3
SWIGMZSCHEME                    Defined when using Mzscheme        
SWIGOCAML                       Defined when using Ocaml
SWIGPERL                        Defined when using Perl
SWIGPERL5                       Defined when using Perl5
SWIGPHP                         Defined when using PHP
SWIGPHP4                        Defined when using PHP4
SWIGPHP5                        Defined when using PHP5
SWIGPIKE                        Defined when using Pike
SWIGPYTHON                      Defined when using Python
SWIGRUBY                        Defined when using Ruby
SWIGSEXP                        Defined when using S-expressions
SWIGTCL                         Defined when using Tcl
SWIGTCL8                        Defined when using Tcl8.0
SWIGXML                         Defined when using XML

In addition, SWIG defines the following set of standard C/C++ macros:

__LINE__                        Current line number
__FILE__                        Current file name
__STDC__                        Defined to indicate ANSI C
__cplusplus                     Defined when -c++ option used

Interface files can look at these symbols as necessary to change the way in which an interface is generated or to mix SWIG directives with C code. These symbols are also defined within the C code generated by SWIG (except for the symbol `SWIG' which is only defined within the SWIG compiler).

7.4 Macro Expansion

Traditional preprocessor macros can be used in SWIG interfaces. Be aware that the #define statement is also used to try and detect constants. Therefore, if you have something like this in your file,

#ifndef _FOO_H 1
#define _FOO_H 1
...
#endif

you may get some extra constants such as _FOO_H showing up in the scripting interface.

More complex macros can be defined in the standard way. For example:

#define EXTERN extern
#ifdef __STDC__
#define _ANSI(args)   (args)
#else
#define _ANSI(args) ()
#endif

The following operators can appear in macro definitions:

7.5 SWIG Macros

SWIG provides an enhanced macro capability with the %define and %enddef directives. For example:

%define ARRAYHELPER(type,name)
%inline %{
type *new_ ## name (int nitems) {
   return (type *) malloc(sizeof(type)*nitems);
}
void delete_ ## name(type *t) {
   free(t);
}
type name ## _get(type *t, int index) {
   return t[index];
}
void name ## _set(type *t, int index, type val) {
   t[index] = val;
}
%}
%enddef

ARRAYHELPER(int, IntArray)
ARRAYHELPER(double, DoubleArray)

The primary purpose of %define is to define large macros of code. Unlike normal C preprocessor macros, it is not necessary to terminate each line with a continuation character (\)--the macro definition extends to the first occurrence of %enddef. Furthermore, when such macros are expanded, they are reparsed through the C preprocessor. Thus, SWIG macros can contain all other preprocessor directives except for nested %define statements.

The SWIG macro capability is a very quick and easy way to generate large amounts of code. In fact, many of SWIG's advanced features and libraries are built using this mechanism (such as C++ template support).

7.6 C99 and GNU Extensions

SWIG-1.3.12 and newer releases support variadic preprocessor macros. For example:

#define DEBUGF(fmt,...)   fprintf(stderr,fmt,__VA_ARGS__)

When used, any extra arguments to ... are placed into the special variable __VA_ARGS__. This also works with special SWIG macros defined using %define.

SWIG allows a variable number of arguments to be empty. However, this often results in an extra comma (,) and syntax error in the resulting expansion. For example:

DEBUGF("hello");   --> fprintf(stderr,"hello",);

To get rid of the extra comma, use ## like this:

#define DEBUGF(fmt,...)   fprintf(stderr,fmt, ##__VA_ARGS__)

SWIG also supports GNU-style variadic macros. For example:

#define DEBUGF(fmt, args...)  fprintf(stdout,fmt,args)

Comment: It's not entirely clear how variadic macros might be useful to interface building. However, they are used internally to implement a number of SWIG directives and are provided to make SWIG more compatible with C99 code.

7.7 Preprocessing and %{ ... %} blocks

The SWIG preprocessor does not process any text enclosed in a code block %{ ... %}. Therefore, if you write code like this,

%{
#ifdef NEED_BLAH
int blah() {
   ...
}
#endif
%}

the contents of the %{ ... %} block are copied without modification to the output (including all preprocessor directives).

7.8 Preprocessing and { ... }

SWIG always runs the preprocessor on text appearing inside { ... }. However, sometimes it is desirable to make a preprocessor directive pass through to the output file. For example:

%extend Foo {
   void bar() {
      #ifdef DEBUG
       printf("I'm in bar\n");
      #endif
   }
}

By default, SWIG will interpret the #ifdef DEBUG statement. However, if you really wanted that code to actually go into the wrapper file, prefix the preprocessor directives with % like this:

%extend Foo {
   void bar() {
      %#ifdef DEBUG
       printf("I'm in bar\n");
      %#endif
   }
}

SWIG will strip the extra % and leave the preprocessor directive in the code.

7.9 Viewing preprocessor output

Like many compilers, SWIG supports a -E command line option to display the output from the preprocessor. When the -E switch is used, SWIG will not generate any wrappers. Instead the results after the preprocessor has run are displayed. This might be useful as an aid to debugging and viewing the results of macro expansions.

7.10 The #error and #warning directives

SWIG supports the commonly used #warning and #error preprocessor directives. The #warning directive will cause SWIG to issue a warning then continue processing. The #error directive will cause SWIG to exit with a fatal error. Example usage:

#error "This is a fatal error message"
#warning "This is a warning message"

The #error behaviour can be made to work like #warning if the -cpperraswarn commandline option is used. Alternatively, the #pragma directive can be used to the same effect, for example:

  /* Modified behaviour: #error does not cause SWIG to exit with error */
  #pragma SWIG cpperraswarn=1
  /* Normal behaviour: #error does cause SWIG to exit with error */
  #pragma SWIG cpperraswarn=0

8 SWIG library

To help build extension modules, SWIG is packaged with a library of support files that you can include in your own interfaces. These files often define new SWIG directives or provide utility functions that can be used to access parts of the standard C and C++ libraries. This chapter provides a reference to the current set of supported library files.

Compatibility note: Older versions of SWIG included a number of library files for manipulating pointers, arrays, and other structures. Most these files are now deprecated and have been removed from the distribution. Alternative libraries provide similar functionality. Please read this chapter carefully if you used the old libraries.

8.1 The %include directive and library search path

Library files are included using the %include directive. When searching for files, directories are searched in the following order:

Within each directory, SWIG first looks for a subdirectory corresponding to a target language (e.g., python, tcl , etc.). If found, SWIG will search the language specific directory first. This allows for language-specific implementations of library files.

You can ignore the installed SWIG library by setting the SWIG_LIB environment variable. Set the environment variable to hold an alternative library directory.

The directories that are searched are displayed when using -verbose commandline option.

8.2 C Arrays and Pointers

This section describes library modules for manipulating low-level C arrays and pointers. The primary use of these modules is in supporting C declarations that manipulate bare pointers such as int *, double *, or void *. The modules can be used to allocate memory, manufacture pointers, dereference memory, and wrap pointers as class-like objects. Since these functions provide direct access to memory, their use is potentially unsafe and you should exercise caution.

8.2.1 cpointer.i

The cpointer.i module defines macros that can be used to used to generate wrappers around simple C pointers. The primary use of this module is in generating pointers to primitive datatypes such as int and double.

%pointer_functions(type,name)

Generates a collection of four functions for manipulating a pointer type *:

type *new_name()

Creates a new object of type type and returns a pointer to it. In C, the object is created using calloc(). In C++, new is used.

type *copy_name(type value)

Creates a new object of type type and returns a pointer to it. An initial value is set by copying it from value. In C, the object is created using calloc(). In C++, new is used.

type *delete_name(type *obj)

Deletes an object type type.

void name_assign(type *obj, type value)

Assigns *obj = value.

type name_value(type *obj)

Returns the value of *obj.

When using this macro, type may be any type and name must be a legal identifier in the target language. name should not correspond to any other name used in the interface file.

Here is a simple example of using %pointer_functions():

%module example
%include "cpointer.i"

/* Create some functions for working with "int *" */
%pointer_functions(int, intp);

/* A function that uses an "int *" */
void add(int x, int y, int *result);

Now, in Python:

>>> import example
>>> c = example.new_intp()     # Create an "int" for storing result
>>> example.add(3,4,c)         # Call function
>>> example.intp_value(c)      # Dereference
7
>>> example.delete_intp(c)     # Delete

%pointer_class(type,name)

Wraps a pointer of type * inside a class-based interface. This interface is as follows:

struct name {
   name();                            // Create pointer object
  ~name();                            // Delete pointer object
   void assign(type value);           // Assign value
   type value();                      // Get value
   type *cast();                      // Cast the pointer to original type
   static name *frompointer(type *);  // Create class wrapper from existing
                                      // pointer
};

When using this macro, type is restricted to a simple type name like int, float, or Foo. Pointers and other complicated types are not allowed. name must be a valid identifier not already in use. When a pointer is wrapped as a class, the "class" may be transparently passed to any function that expects the pointer.

If the target language does not support proxy classes, the use of this macro will produce the example same functions as %pointer_functions() macro.

It should be noted that the class interface does introduce a new object or wrap a pointer inside a special structure. Instead, the raw pointer is used directly.

Here is the same example using a class instead:

%module example
%include "cpointer.i"

/* Wrap a class interface around an "int *" */
%pointer_class(int, intp);

/* A function that uses an "int *" */
void add(int x, int y, int *result);

Now, in Python (using proxy classes)

>>> import example
>>> c = example.intp()         # Create an "int" for storing result
>>> example.add(3,4,c)         # Call function
>>> c.value()                  # Dereference
7

Of the two macros, %pointer_class is probably the most convenient when working with simple pointers. This is because the pointers are access like objects and they can be easily garbage collected (destruction of the pointer object destroys the underlying object).

%pointer_cast(type1, type2, name)

Creates a casting function that converts type1 to type2 . The name of the function is name. For example:

%pointer_cast(int *, unsigned int *, int_to_uint);

In this example, the function int_to_uint() would be used to cast types in the target language.

Note: None of these macros can be used to safely work with strings (char * or char **).

Note: When working with simple pointers, typemaps can often be used to provide more seamless operation.

8.2.2 carrays.i

This module defines macros that assist in wrapping ordinary C pointers as arrays. The module does not provide any safety or an extra layer of wrapping--it merely provides functionality for creating, destroying, and modifying the contents of raw C array data.

%array_functions(type,name)

Creates four functions.

type *new_name(int nelements)

Creates a new array of objects of type type. In C, the array is allocated using calloc(). In C++, new [] is used.

type *delete_name(type *ary)

Deletes an array. In C, free() is used. In C++, delete [] is used.

type name_getitem(type *ary, int index)

Returns the value ary[index].

void name_setitem(type *ary, int index, type value)

Assigns ary[index] = value.

When using this macro, type may be any type and name must be a legal identifier in the target language. name should not correspond to any other name used in the interface file.

Here is an example of %array_functions(). Suppose you had a function like this:

void print_array(double x[10]) {
   int i;
   for (i = 0; i < 10; i++) {
      printf("[%d] = %g\n", i, x[i]);
   }
}

To wrap it, you might write this:

%module example

%include "carrays.i"
%array_functions(double, doubleArray);

void print_array(double x[10]);

Now, in a scripting language, you might write this:

a = new_doubleArray(10)           # Create an array
for i in range(0,10):
    doubleArray_setitem(a,i,2*i)  # Set a value
print_array(a)                    # Pass to C
delete_doubleArray(a)             # Destroy array
%array_class(type,name)

Wraps a pointer of type * inside a class-based interface. This interface is as follows:

struct name {
   name(int nelements);                  // Create an array
  ~name();                               // Delete array
   type getitem(int index);              // Return item
   void setitem(int index, type value);  // Set item
   type *cast();                         // Cast to original type
   static name *frompointer(type *);     // Create class wrapper from
                                         // existing pointer
};

When using this macro, type is restricted to a simple type name like int or float. Pointers and other complicated types are not allowed. name must be a valid identifier not already in use. When a pointer is wrapped as a class, it can be transparently passed to any function that expects the pointer.

When combined with proxy classes, the %array_class() macro can be especially useful. For example:

%module example
%include "carrays.i"
%array_class(double, doubleArray);

void print_array(double x[10]);

Allows you to do this:

import example
c = example.doubleArray(10)  # Create double[10]
for i in range(0,10):
    c[i] = 2*i               # Assign values
example.print_array(c)       # Pass to C

Note: These macros do not encapsulate C arrays inside a special data structure or proxy. There is no bounds checking or safety of any kind. If you want this, you should consider using a special array object rather than a bare pointer.

Note: %array_functions() and %array_class() should not be used with types of char or char *.

8.2.3 cmalloc.i

This module defines macros for wrapping the low-level C memory allocation functions malloc(), calloc(), realloc(), and free().

%malloc(type [,name=type])

Creates a wrapper around malloc() with the following prototype:

type *malloc_name(int nbytes = sizeof(type));

If type is void, then the size parameter nbytes is required. The name parameter only needs to be specified when wrapping a type that is not a valid identifier (e.g., " int *", "double **", etc.).

%calloc(type [,name=type])

Creates a wrapper around calloc() with the following prototype:

type *calloc_name(int nobj =1, int sz = sizeof(type));

If type is void, then the size parameter sz is required.

%realloc(type [,name=type])

Creates a wrapper around realloc() with the following prototype:

type *realloc_name(type *ptr, int nitems);

Note: unlike the C realloc(), the wrapper generated by this macro implicitly includes the size of the corresponding type. For example, realloc_int(p, 100) reallocates p so that it holds 100 integers.

%free(type [,name=type])

Creates a wrapper around free() with the following prototype:

void free_name(type *ptr);

%sizeof(type [,name=type])

Creates the constant:

%constant int sizeof_name = sizeof(type);

%allocators(type [,name=type])

Generates wrappers for all five of the above operations.

Here is a simple example that illustrates the use of these macros:

// SWIG interface
%module example
%include "cmalloc.i"

%malloc(int);
%free(int);

%malloc(int *, intp);
%free(int *, intp);

%allocators(double);

Now, in a script:

>>> from example import *
>>> a = malloc_int()
>>> a
'_000efa70_p_int'
>>> free_int(a)
>>> b = malloc_intp()
>>> b
'_000efb20_p_p_int'
>>> free_intp(b)
>>> c = calloc_double(50)
>>> c
'_000fab98_p_double'
>>> c = realloc_double(100000)
>>> free_double(c)
>>> print sizeof_double
8
>>>

8.2.4 cdata.i

The cdata.i module defines functions for converting raw C data to and from strings in the target language. The primary applications of this module would be packing/unpacking of binary data structures---for instance, if you needed to extract data from a buffer. The target language must support strings with embedded binary data in order for this to work.

char *cdata(void *ptr, int nbytes)

Converts nbytes of data at ptr into a string. ptr can be any pointer.

void memmove(void *ptr, char *s)

Copies all of the string data in s into the memory pointed to by ptr. The string may contain embedded NULL bytes. The length of the string is implicitly determined in the underlying wrapper code.

One use of these functions is packing and unpacking data from memory. Here is a short example:

// SWIG interface
%module example
%include "carrays.i"
%include "cdata.i"

%array_class(int, intArray);

Python example:

>>> a = intArray(10)
>>> for i in range(0,10):
...    a[i] = i
>>> b = cdata(a,40)
>>> b
'\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04
\x00\x00\x00\x05\x00\x00\x00\x06\x00\x00\x00\x07\x00\x00\x00\x08\x00\x00\x00\t'
>>> c = intArray(10)
>>> memmove(c,b)
>>> print c[4]
4
>>>

Since the size of data is not always known, the following macro is also defined:

%cdata(type [,name=type])

Generates the following function for extracting C data for a given type.

char *cdata_name(type* ptr, int nitems)

nitems is the number of items of the given type to extract.

Note: These functions provide direct access to memory and can be used to overwrite data. Clearly they are unsafe.

8.3 C String Handling

A common problem when working with C programs is dealing with functions that manipulate raw character data using char *. In part, problems arise because there are different interpretations of char *---it could be a NULL-terminated string or it could point to binary data. Moreover, functions that manipulate raw strings may mutate data, perform implicit memory allocations, or utilize fixed-sized buffers.

The problems (and perils) of using char * are well-known. However, SWIG is not in the business of enforcing morality. The modules in this section provide basic functionality for manipulating raw C strings.

8.3.1 Default string handling

Suppose you have a C function with this prototype:

char *foo(char *s);

The default wrapping behavior for this function is to set s to a raw char * that refers to the internal string data in the target language. In other words, if you were using a language like Tcl, and you wrote this,

% foo Hello

then s would point to the representation of "Hello" inside the Tcl interpreter. When returning a char *, SWIG assumes that it is a NULL-terminated string and makes a copy of it. This gives the target language its own copy of the result.

There are obvious problems with the default behavior. First, since a char * argument points to data inside the target language, it is NOT safe for a function to modify this data (doing so may corrupt the interpreter and lead to a crash). Furthermore, the default behavior does not work well with binary data. Instead, strings are assumed to be NULL-terminated.

8.3.2 Passing binary data

If you have a function that expects binary data,

int parity(char *str, int len, int initial);

you can wrap the parameters (char *str, int len) as a single argument using a typemap. Just do this:

%apply (char *STRING, int LENGTH) { (char *str, int len) };
...
int parity(char *str, int len, int initial);

Now, in the target language, you can use binary string data like this:

>>> s = "H\x00\x15eg\x09\x20"
>>> parity(s,0)

In the wrapper function, the passed string will be expanded to a pointer and length parameter.

8.3.3 Using %newobject to release memory

If you have a function that allocates memory like this,

char *foo() {
   char *result = (char *) malloc(...);
   ...
   return result;
}

then the SWIG generated wrappers will have a memory leak--the returned data will be copied into a string object and the old contents ignored.

To fix the memory leak, use the %newobject directive.

%newobject foo;
...
char *foo();

This will release the result.

8.3.4 cstring.i

The cstring.i library file provides a collection of macros for dealing with functions that either mutate string arguments or which try to output string data through their arguments. An example of such a function might be this rather questionable implementation:

void get_path(char *s) {
    // Potential buffer overflow---uh, oh.
    sprintf(s,"%s/%s", base_directory, sub_directory);
}
...
// Somewhere else in the C program
{
    char path[1024];
    ...
    get_path(path);
    ...
}

(Off topic rant: If your program really has functions like this, you would be well-advised to replace them with safer alternatives involving bounds checking).

The macros defined in this module all expand to various combinations of typemaps. Therefore, the same pattern matching rules and ideas apply.

%cstring_bounded_output(parm, maxsize)

Turns parameter parm into an output value. The output string is assumed to be NULL-terminated and smaller than maxsize characters. Here is an example:

%cstring_bounded_output(char *path, 1024);
...
void get_path(char *path);

In the target language:

>>> get_path()
/home/beazley/packages/Foo/Bar
>>>

Internally, the wrapper function allocates a small buffer (on the stack) of the requested size and passes it as the pointer value. Data stored in the buffer is then returned as a function return value. If the function already returns a value, then the return value and the output string are returned together (multiple return values). If more than maxsize bytes are written, your program will crash with a buffer overflow!

%cstring_chunk_output(parm, chunksize)

Turns parameter parm into an output value. The output string is always chunksize and may contain binary data. Here is an example:

%cstring_chunk_output(char *packet, PACKETSIZE);
...
void get_packet(char *packet);

In the target language:

>>> get_packet()
'\xa9Y:\xf6\xd7\xe1\x87\xdbH;y\x97\x7f\xd3\x99\x14V\xec\x06\xea\xa2\x88'
>>>

This macro is essentially identical to %cstring_bounded_output . The only difference is that the result is always chunksize characters. Furthermore, the result can contain binary data. If more than maxsize bytes are written, your program will crash with a buffer overflow!

%cstring_bounded_mutable(parm, maxsize)

Turns parameter parm into a mutable string argument. The input string is assumed to be NULL-terminated and smaller than maxsize characters. The output string is also assumed to be NULL-terminated and less than maxsize characters.

%cstring_bounded_mutable(char *ustr, 1024);
...
void make_upper(char *ustr);

In the target language:

>>> make_upper("hello world")
'HELLO WORLD'
>>>

Internally, this macro is almost exactly the same as %cstring_bounded_output. The only difference is that the parameter accepts an input value that is used to initialize the internal buffer. It is important to emphasize that this function does not mutate the string value passed---instead it makes a copy of the input value, mutates it, and returns it as a result. If more than maxsize bytes are written, your program will crash with a buffer overflow!

%cstring_mutable(parm [, expansion])

Turns parameter parm into a mutable string argument. The input string is assumed to be NULL-terminated. An optional parameter expansion specifies the number of extra characters by which the string might grow when it is modified. The output string is assumed to be NULL-terminated and less than the size of the input string plus any expansion characters.

%cstring_mutable(char *ustr);
...
void make_upper(char *ustr);

%cstring_mutable(char *hstr, HEADER_SIZE);
...
void attach_header(char *hstr);

In the target language:

>>> make_upper("hello world")
'HELLO WORLD'
>>> attach_header("Hello world")
'header: Hello world'
>>>

This macro differs from %cstring_bounded_mutable() in that a buffer is dynamically allocated (on the heap using malloc/new ). This buffer is always large enough to store a copy of the input value plus any expansion bytes that might have been requested. It is important to emphasize that this function does not directly mutate the string value passed---instead it makes a copy of the input value, mutates it, and returns it as a result. If the function expands the result by more than expansion extra bytes, then the program will crash with a buffer overflow!

%cstring_output_maxsize(parm, maxparm)

This macro is used to handle bounded character output functions where both a char * and a maximum length parameter are provided. As input, a user simply supplies the maximum length. The return value is assumed to be a NULL-terminated string.

%cstring_output_maxsize(char *path, int maxpath);
...
void get_path(char *path, int maxpath);

In the target language:

>>> get_path(1024)
'/home/beazley/Packages/Foo/Bar'
>>>

This macro provides a safer alternative for functions that need to write string data into a buffer. User supplied buffer size is used to dynamically allocate memory on heap. Results are placed into that buffer and returned as a string object.

%cstring_output_withsize(parm, maxparm)

This macro is used to handle bounded character output functions where both a char * and a pointer int * are passed. Initially, the int * parameter points to a value containing the maximum size. On return, this value is assumed to contain the actual number of bytes. As input, a user simply supplies the maximum length. The output value is a string that may contain binary data.

%cstring_output_withsize(char *data, int *maxdata);
...
void get_data(char *data, int *maxdata);

In the target language:

>>> get_data(1024)
'x627388912'
>>> get_data(1024)
'xyzzy'
>>>

This macro is a somewhat more powerful version of %cstring_output_chunk(). Memory is dynamically allocated and can be arbitrary large. Furthermore, a function can control how much data is actually returned by changing the value of the maxparm argument.

%cstring_output_allocate(parm, release)

This macro is used to return strings that are allocated within the program and returned in a parameter of type char **. For example:

void foo(char **s) {
    *s = (char *) malloc(64);
    sprintf(*s, "Hello world\n");
}

The returned string is assumed to be NULL-terminated. release specifies how the allocated memory is to be released (if applicable). Here is an example:

%cstring_output_allocate(char **s, free(*$1));
...
void foo(char **s);

In the target language:

>>> foo()
'Hello world\n'
>>>

%cstring_output_allocate_size(parm, szparm, release)

This macro is used to return strings that are allocated within the program and returned in two parameters of type char ** and int *. For example:

void foo(char **s, int *sz) {
    *s = (char *) malloc(64);
    *sz = 64;
    // Write some binary data
    ...
}

The returned string may contain binary data. release specifies how the allocated memory is to be released (if applicable). Here is an example:

%cstring_output_allocate_size(char **s, int *slen, free(*$1));
...
void foo(char **s, int *slen);

In the target language:

>>> foo()
'\xa9Y:\xf6\xd7\xe1\x87\xdbH;y\x97\x7f\xd3\x99\x14V\xec\x06\xea\xa2\x88'
>>>

This is the safest and most reliable way to return binary string data in SWIG. If you have functions that conform to another prototype, you might consider wrapping them with a helper function. For example, if you had this:

char  *get_data(int *len);

You could wrap it with a function like this:

void my_get_data(char **result, int *len) {
   *result = get_data(len);
}

Comments:

8.4 STL/C++ Library

The library modules in this section provide access to parts of the standard C++ library including the STL. SWIG support for the STL is an ongoing effort. Support is quite comprehensive for some language modules but some of the lesser used modules do not have quite as much library code written.

The following table shows which C++ classes are supported and the equivalent SWIG interface library file for the C++ library.

C++ classC++ Library file SWIG Interface library file
std::dequedequestd_deque.i
std::listliststd_list.i
std::mapmapstd_map.i
std::pairutilitystd_pair.i
std::setsetstd_set.i
std::stringstringstd_string.i
std::vectorvectorstd_vector.i

The list is by no means complete; some language modules support a subset of the above and some support additional STL classes. Please look for the library files in the appropriate language library directory.

8.4.1 std_string.i

The std_string.i library provides typemaps for converting C++ std::string objects to and from strings in the target scripting language. For example:

%module example
%include "std_string.i"

std::string foo();
void        bar(const std::string &x);

In the target language:

x = foo();                # Returns a string object
bar("Hello World");       # Pass string as std::string

A common problem that people encounter is that of classes/structures containing a std::string. This can be overcome by defining a typemap. For example:

%module example
%include "std_string.i"

%apply const std::string& {std::string* foo};

struct my_struct
{
  std::string foo;
};

In the target language:

x = my_struct();
x.foo="Hello World";      # assign with string
print x.foo;              # print as string

This module only supports types std::string and const std::string &. Pointers and non-const references are left unmodified and returned as SWIG pointers.

This library file is fully aware of C++ namespaces. If you export std::string or rename it with a typedef, make sure you include those declarations in your interface. For example:

%module example
%include "std_string.i"

using namespace std;
typedef std::string String;
...
void foo(string s, const String &t);     // std_string typemaps still applied

Note: The std_string library is incompatible with Perl on some platforms. We're looking into it.

8.4.2 std_vector.i

The std_vector.i library provides support for the C++ vector class in the STL. Using this library involves the use of the %template directive. All you need to do is to instantiate different versions of vector for the types that you want to use. For example:

%module example
%include "std_vector.i"

namespace std {
   %template(vectori) vector<int>;
   %template(vectord) vector<double>;
};

When a template vector<X> is instantiated a number of things happen:

To illustrate the use of this library, consider the following functions:

/* File : example.h */

#include <vector>
#include <algorithm>
#include <functional>
#include <numeric>

double average(std::vector<int> v) {
    return std::accumulate(v.begin(),v.end(),0.0)/v.size();
}

std::vector<double> half(const std::vector<double>& v) {
    std::vector<double> w(v);
    for (unsigned int i=0; i<w.size(); i++)
        w[i] /= 2.0;
    return w;
}

void halve_in_place(std::vector<double>& v) {
    std::transform(v.begin(),v.end(),v.begin(),
                   std::bind2nd(std::divides<double>(),2.0));
}

To wrap with SWIG, you might write the following:

%module example
%{
#include "example.h"
%}

%include "std_vector.i"
// Instantiate templates used by example
namespace std {
   %template(IntVector) vector<int>;
   %template(DoubleVector) vector<double>;
}

// Include the header file with above prototypes
%include "example.h"

Now, to illustrate the behavior in the scripting interpreter, consider this Python example:

>>> from example import *
>>> iv = IntVector(4)         # Create an vector<int>
>>> for i in range(0,4):
...      iv[i] = i
>>> average(iv)               # Call method
1.5
>>> average([0,1,2,3])        # Call with list
1.5
>>> half([1,2,3])             # Half a list
(0.5,1.0,1.5)
>>> halve_in_place([1,2,3])   # Oops
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: Type error. Expected _p_std__vectorTdouble_t
>>> dv = DoubleVector(4)
>>> for i in range(0,4):
...       dv[i] = i
>>> halve_in_place(dv)       # Ok
>>> for i in dv:
...       print i
...
0.0
0.5
1.0
1.5
>>> dv[20] = 4.5
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "example.py", line 81, in __setitem__
    def __setitem__(*args): return apply(examplec.DoubleVector___setitem__,args)
IndexError: vector index out of range
>>>

This library module is fully aware of C++ namespaces. If you use vectors with other names, make sure you include the appropriate using or typedef directives. For example:

%include "std_vector.i"

namespace std {
    %template(IntVector) vector<int>;
}

using namespace std;
typedef std::vector Vector;

void foo(vector<int> *x, const Vector &x);

Note: This module makes use of several advanced SWIG features including templatized typemaps and template partial specialization. If you are trying to wrap other C++ code with templates, you might look at the code contained in std_vector.i. Alternatively, you can show them the code if you want to make their head explode.

Note: This module is defined for all SWIG target languages. However argument conversion details and the public API exposed to the interpreter vary.

Note: std_vector.i was written by Luigi "The Amazing" Ballabio.

8.4.3 STL exceptions

Many of the STL wrapper functions add parameter checking and will throw a language dependent error/exception should the values not be valid. The classic example is array bounds checking. The library wrappers are written to throw a C++ exception in the case of error. The C++ exception in turn gets converted into an appropriate error/exception for the target language. By and large this handling should not need customising, however, customisation can easily be achieved by supplying appropriate "throws" typemaps. For example:

%module example
%include "std_vector.i"
%typemap(throws) std::out_of_range {
  // custom exception handler
}
%template(VectInt) std::vector<int>;

The custom exception handler might, for example, log the exception then convert it into a specific error/exception for the target language.

When using the STL it is advisable to add in an exception handler to catch all STL exceptions. The %exception directive can be used by placing the following code before any other methods or libraries to be wrapped:

%include "exception.i"

%exception {
  try {
    $action
  } catch (const std::exception& e) {
    SWIG_exception(SWIG_RuntimeError, e.what());
  }
}

Any thrown STL exceptions will then be gracefully handled instead of causing a crash.

8.5 Utility Libraries

8.5.1 exception.i

The exception.i library provides a language-independent function for raising a run-time exception in the target language. This library is largely used by the SWIG library writers. If possible, use the error handling scheme available to your target language as there is greater flexibility in what errors/exceptions can be thrown.

SWIG_exception(int code, const char *message)

Raises an exception in the target language. code is one of the following symbolic constants:

SWIG_MemoryError
SWIG_IOError
SWIG_RuntimeError
SWIG_IndexError
SWIG_TypeError
SWIG_DivisionByZero
SWIG_OverflowError
SWIG_SyntaxError
SWIG_ValueError
SWIG_SystemError

message is a string indicating more information about the problem.

The primary use of this module is in writing language-independent exception handlers. For example:

%include "exception.i"
%exception std::vector::getitem {
    try {
        $action
    } catch (std::out_of_range& e) {
        SWIG_exception(SWIG_IndexError,const_cast<char*>(e.what()));
    }
}

9 Argument Handling

Disclaimer: This chapter is under construction.

In Chapter 3, SWIG's treatment of basic datatypes and pointers was described. In particular, primitive types such as int and double are mapped to corresponding types in the target language. For everything else, pointers are used to refer to structures, classes, arrays, and other user-defined datatypes. However, in certain applications it is desirable to change SWIG's handling of a specific datatype. For example, you might want to return multiple values through the arguments of a function. This chapter describes some of the techniques for doing this.

9.1 The typemaps.i library

This section describes the typemaps.i library file--commonly used to change certain properties of argument conversion.

9.1.1 Introduction

Suppose you had a C function like this:

void add(double a, double b, double *result) {
	*result = a + b;
}

From reading the source code, it is clear that the function is storing a value in the double *result parameter. However, since SWIG does not examine function bodies, it has no way to know that this is the underlying behavior.

One way to deal with this is to use the typemaps.i library file and write interface code like this:

// Simple example using typemaps
%module example
%include "typemaps.i"

%apply double *OUTPUT { double *result };
%inlne %{
extern void add(double a, double b, double *result);
%}

The %apply directive tells SWIG that you are going to apply a special type handling rule to a type. The "double *OUTPUT" specification is the name of a rule that defines how to return an output value from an argument of type double *. This rule gets applied to all of the datatypes listed in curly braces-- in this case " double *result".

When the resulting module is created, you can now use the function like this (shown for Python):

>>> a = add(3,4)
>>> print a
7
>>>

In this case, you can see how the output value normally returned in the third argument has magically been transformed into a function return value. Clearly this makes the function much easier to use since it is no longer necessary to manufacture a special double * object and pass it to the function somehow.

Once a typemap has been applied to a type, it stays in effect for all future occurrences of the type and name. For example, you could write the following:

%module example
%include "typemaps.i"

%apply double *OUTPUT { double *result };

%inline %{
extern void add(double a, double b, double *result);
extern void sub(double a, double b, double *result);
extern void mul(double a, double b, double *result);
extern void div(double a, double b, double *result);
%}
...

In this case, the double *OUTPUT rule is applied to all of the functions that follow.

Typemap transformations can even be extended to multiple return values. For example, consider this code:

%include "typemaps.i"
%apply int *OUTPUT { int *width, int *height };

// Returns a pair (width,height)
void getwinsize(int winid, int *width, int *height);

In this case, the function returns multiple values, allowing it to be used like this:

>>> w,h = genwinsize(wid)
>>> print w
400
>>> print h
300
>>>

It should also be noted that although the %apply directive is used to associate typemap rules to datatypes, you can also use the rule names directly in arguments. For example, you could write this:

// Simple example using typemaps
%module example
%include "typemaps.i"

%{
extern void add(double a, double b, double *OUTPUT);
%}
extern void add(double a, double b, double *OUTPUT);

Typemaps stay in effect until they are explicitly deleted or redefined to something else. To clear a typemap, the %clear directive should be used. For example:

%clear double *result;      // Remove all typemaps for double *result

9.1.2 Input parameters

The following typemaps instruct SWIG that a pointer really only holds a single input value:

int *INPUT		
short *INPUT
long *INPUT
unsigned int *INPUT
unsigned short *INPUT
unsigned long *INPUT
double *INPUT
float *INPUT

When used, it allows values to be passed instead of pointers. For example, consider this function:

double add(double *a, double *b) {
	return *a+*b;
}

Now, consider this SWIG interface:

%module example
%include "typemaps.i"
...
%{
extern double add(double *, double *);
%}
extern double add(double *INPUT, double *INPUT);

When the function is used in the scripting language interpreter, it will work like this:

result = add(3,4)

9.1.3 Output parameters

The following typemap rules tell SWIG that pointer is the output value of a function. When used, you do not need to supply the argument when calling the function. Instead, one or more output values are returned.

int *OUTPUT
short *OUTPUT
long *OUTPUT
unsigned int *OUTPUT
unsigned short *OUTPUT
unsigned long *OUTPUT
double *OUTPUT
float *OUTPUT

These methods can be used as shown in an earlier example. For example, if you have this C function :

void add(double a, double b, double *c) {
	*c = a+b;
}

A SWIG interface file might look like this :

%module example
%include "typemaps.i"
...
%inline %{
extern void add(double a, double b, double *OUTPUT);
%}

In this case, only a single output value is returned, but this is not a restriction. An arbitrary number of output values can be returned by applying the output rules to more than one argument (as shown previously).

If the function also returns a value, it is returned along with the argument. For example, if you had this:

extern int foo(double a, double b, double *OUTPUT);

The function will return two values like this:

iresult, dresult = foo(3.5, 2)

9.1.4 Input/Output parameters

When a pointer serves as both an input and output value you can use the following typemaps :

int *INOUT
short *INOUT
long *INOUT
unsigned int *INOUT
unsigned short *INOUT
unsigned long *INOUT
double *INOUT
float *INOUT

A C function that uses this might be something like this:

void negate(double *x) {
	*x = -(*x);
}

To make x function as both and input and output value, declare the function like this in an interface file :

%module example
%include typemaps.i
...
%{
extern void negate(double *);
%}
extern void negate(double *INOUT);

Now within a script, you can simply call the function normally :

a = negate(3);         # a = -3 after calling this

One subtle point of the INOUT rule is that many scripting languages enforce mutability constraints on primitive objects (meaning that simple objects like integers and strings aren't supposed to change). Because of this, you can't just modify the object's value in place as the underlying C function does in this example. Therefore, the INOUT rule returns the modified value as a new object rather than directly overwriting the value of the original input object.

Compatibility note : The INOUT rule used to be known as BOTH in earlier versions of SWIG. Backwards compatibility is preserved, but deprecated.

9.1.5 Using different names

As previously shown, the %apply directive can be used to apply the INPUT, OUTPUT, and INOUT typemaps to different argument names. For example:

// Make double *result an output value
%apply double *OUTPUT { double *result };

// Make Int32 *in an input value
%apply int *INPUT { Int32 *in };

// Make long *x inout
%apply long *INOUT {long *x};

To clear a rule, the %clear directive is used:

%clear double *result;
%clear Int32 *in, long *x;

Typemap declarations are lexically scoped so a typemap takes effect from the point of definition to the end of the file or a matching %clear declaration.

9.2 Applying constraints to input values

In addition to changing the handling of various input values, it is also possible to use typemaps to apply constraints. For example, maybe you want to insure that a value is positive, or that a pointer is non-NULL. This can be accomplished including the constraints.i library file.

9.2.1 Simple constraint example

The constraints library is best illustrated by the following interface file :

// Interface file with constraints
%module example
%include "constraints.i"

double exp(double x);
double log(double POSITIVE);         // Allow only positive values
double sqrt(double NONNEGATIVE);     // Non-negative values only
double inv(double NONZERO);          // Non-zero values
void   free(void *NONNULL);          // Non-NULL pointers only

The behavior of this file is exactly as you would expect. If any of the arguments violate the constraint condition, a scripting language exception will be raised. As a result, it is possible to catch bad values, prevent mysterious program crashes and so on.

9.2.2 Constraint methods

The following constraints are currently available

POSITIVE                     Any number > 0 (not zero)
NEGATIVE                     Any number < 0 (not zero)
NONNEGATIVE                  Any number >= 0
NONPOSITIVE                  Any number <= 0
NONZERO                      Nonzero number
NONNULL                      Non-NULL pointer (pointers only).

9.2.3 Applying constraints to new datatypes

The constraints library only supports the primitive C datatypes, but it is easy to apply it to new datatypes using %apply. For example :

// Apply a constraint to a Real variable
%apply Number POSITIVE { Real in };

// Apply a constraint to a pointer type
%apply Pointer NONNULL { Vector * };

The special types of "Number" and "Pointer" can be applied to any numeric and pointer variable type respectively. To later remove a constraint, the %clear directive can be used :

%clear Real in;
%clear Vector *;

10 Typemaps

Disclaimer: This chapter is under construction!

10.1 Introduction

Chances are, you are reading this chapter for one of two reasons; you either want to customize SWIG's behavior or you overheard someone mumbling some incomprehensible drivel about "typemaps" and you asked yourself "typemaps, what are those?" That said, let's start with a short disclaimer that "typemaps" are an advanced customization feature that provide direct access to SWIG's low-level code generator. Not only that, they are an integral part of the SWIG C++ type system (a non-trivial topic of its own). Typemaps are generally not a required part of using SWIG. Therefore, you might want to re-read the earlier chapters if you have found your way to this chapter with only a vague idea of what SWIG already does by default.

10.1.1 Type conversion

One of the most important problems in wrapper code generation is the conversion of datatypes between programming languages. Specifically, for every C/C++ declaration, SWIG must somehow generate wrapper code that allows values to be passed back and forth between languages. Since every programming language represents data differently, this is not a simple of matter of simply linking code together with the C linker. Instead, SWIG has to know something about how data is represented in each language and how it can be manipulated.

To illustrate, suppose you had a simple C function like this:

int factorial(int n);

To access this function from Python, a pair of Python API functions are used to convert integer values. For example:

long PyInt_AsLong(PyObject *obj);      /* Python --> C */
PyObject *PyInt_FromLong(long x);      /* C --> Python */

The first function is used to convert the input argument from a Python integer object to C long. The second function is used to convert a value from C back into a Python integer object.

Inside the wrapper function, you might see these functions used like this:

PyObject *wrap_factorial(PyObject *self, PyObject *args) {
    int       arg1;
    int       result;
    PyObject *obj1;
    PyObject *resultobj;

    if (!PyArg_ParseTuple("O:factorial", &obj1)) return NULL;
    arg1 = PyInt_AsLong(obj1);
    result = factorial(arg1);
    resultobj = PyInt_FromLong(result);
    return resultobj;
}

Every target language supported by SWIG has functions that work in a similar manner. For example, in Perl, the following functions are used:

IV SvIV(SV *sv);                     /* Perl --> C */
void sv_setiv(SV *sv, IV val);       /* C --> Perl */

In Tcl:

int Tcl_GetLongFromObj(Tcl_Interp *interp, Tcl_Obj *obj, long *value);
Tcl_Obj *Tcl_NewIntObj(long value);

The precise details are not so important. What is important is that all of the underlying type conversion is handled by collections of utility functions and short bits of C code like this---you simply have to read the extension documentation for your favorite language to know how it works (an exercise left to the reader).

10.1.2 Typemaps

Since type handling is so central to wrapper code generation, SWIG allows it to be completely defined (or redefined) by the user. To do this, a special %typemap directive is used. For example:

/* Convert from Python --> C */
%typemap(in) int {
    $1 = PyInt_AsLong($input);
}

/* Convert from C --> Python */
%typemap(out) int {
    $result = PyInt_FromLong($1);
}

At first glance, this code will look a little confusing. However, there is really not much to it. The first typemap (the "in" typemap) is used to convert a value from the target language to C. The second typemap (the "out" typemap) is used to convert in the other direction. The content of each typemap is a small fragment of C code that is inserted directly into the SWIG generated wrapper functions. Within this code, a number of special variables prefixed with a $ are expanded. These are really just placeholders for C variables that are generated in the course of creating the wrapper function. In this case, $input refers to an input object that needs to be converted to C and $result refers to an object that is going to be returned by a wrapper function. $1 refers to a C variable that has the same type as specified in the typemap declaration (an int in this example).

A short example might make this a little more clear. If you were wrapping a function like this:

int gcd(int x, int y);

A wrapper function would look approximately like this:

PyObject *wrap_gcd(PyObject *self, PyObject *args) {
   int arg1;
   int arg2;
   int result;
   PyObject *obj1;
   PyObject *obj2;
   PyObject *resultobj;

   if (!PyArg_ParseTuple("OO:gcd", &obj1, &obj2)) return NULL;

   /* "in" typemap, argument 1 */   
   {
      arg1 = PyInt_AsLong(obj1);
   }

   /* "in" typemap, argument 2 */
   {
      arg2 = PyInt_AsLong(obj2);
   }

   result = gcd(arg1,arg2);

   /* "out" typemap, return value */
   {
      resultobj = PyInt_FromLong(result);
   }

   return resultobj;
}

In this code, you can see how the typemap code has been inserted into the function. You can also see how the special $ variables have been expanded to match certain variable names inside the wrapper function. This is really the whole idea behind typemaps--they simply let you insert arbitrary code into different parts of the generated wrapper functions. Because arbitrary code can be inserted, it possible to completely change the way in which values are converted.

10.1.3 Pattern matching

As the name implies, the purpose of a typemap is to "map" C datatypes to types in the target language. Once a typemap is defined for a C datatype, it is applied to all future occurrences of that type in the input file. For example:

/* Convert from Perl --> C */
%typemap(in) int {
   $1 = SvIV($input);
}

...
int factorial(int n);
int gcd(int x, int y);
int count(char *s, char *t, int max);

The matching of typemaps to C datatypes is more than a simple textual match. In fact, typemaps are fully built into the underlying type system. Therefore, typemaps are unaffected by typedef, namespaces, and other declarations that might hide the underlying type. For example, you could have code like this:

/* Convert from Ruby--> C */
%typemap(in) int {
   $1 = NUM2INT($input);
}
...
typedef int Integer;
namespace foo {
    typedef Integer Number;
};

int foo(int x);
int bar(Integer y);
int spam(foo::Number a, foo::Number b);

In this case, the typemap is still applied to the proper arguments even though typenames don't always match the text "int". This ability to track types is a critical part of SWIG--in fact, all of the target language modules work merely define a set of typemaps for the basic types. Yet, it is never necessary to write new typemaps for typenames introduced by typedef.

In addition to tracking typenames, typemaps may also be specialized to match against a specific argument name. For example, you could write a typemap like this:

%typemap(in) double nonnegative {
   $1 = PyFloat_AsDouble($input);
   if ($1 < 0) {
        PyErr_SetString(PyExc_ValueError,"argument must be nonnegative.");
        return NULL;
   }
}

...
double sin(double x);
double cos(double x);
double sqrt(double nonnegative);

typedef double Real;
double log(Real nonnegative);
...

For certain tasks such as input argument conversion, typemaps can be defined for sequences of consecutive arguments. For example:

%typemap(in) (char *str, int len) {
    $1 = PyString_AsString($input);   /* char *str */
    $2 = PyString_Size($input);       /* int len   */
}
...
int count(char *str, int len, char c);

In this case, a single input object is expanded into a pair of C arguments. This example also provides a hint to the unusual variable naming scheme involving $1, $2, and so forth.

10.1.4 Reusing typemaps

Typemaps are normally defined for specific type and argument name patterns. However, typemaps can also be copied and reused. One way to do this is to use assignment like this:

%typemap(in) Integer = int;   
%typemap(in) (char *buffer, int size) = (char *str, int len);

A more general form of copying is found in the %apply directive like this:

%typemap(in) int {
   /* Convert an integer argument */
   ...
}
%typemap(out) int {
   /* Return an integer value */
   ...
}

/* Apply all of the integer typemaps to size_t */
%apply int { size_t };    

%apply merely takes all of the typemaps that are defined for one type and applies them to other types. Note: you can include a comma separated set of types in the { ... } part of %apply.

It should be noted that it is not necessary to copy typemaps for types that are related by typedef. For example, if you have this,

typedef int size_t;

then SWIG already knows that the int typemaps apply. You don't have to do anything.

10.1.5 What can be done with typemaps?

The primary use of typemaps is for defining wrapper generation behavior at the level of individual C/C++ datatypes. There are currently six general categories of problems that typemaps address:

Argument handling

int foo(int x, double y, char *s);

Return value handling

int foo(int x, double y, char *s);

Exception handling

int foo(int x, double y, char *s) throw(MemoryError, IndexError);

Global variables

int foo;

Member variables

struct Foo {
    int x[20];
};

Constant creation

#define FOO 3
%constant int BAR = 42;
enum { ALE, LAGER, STOUT };

Details of each of these typemaps will be covered shortly. Also, certain language modules may define additional typemaps that expand upon this list. For example, the Java module defines a variety of typemaps for controlling additional aspects of the Java bindings. Consult language specific documentation for further details.

10.1.6 What can't be done with typemaps?

Typemaps can't be used to define properties that apply to C/C++ declarations as a whole. For example, suppose you had a declaration like this,

Foo *make_Foo();

and you wanted to tell SWIG that make_Foo() returned a newly allocated object (for the purposes of providing better memory management). Clearly, this property of make_Foo() is not a property that would be associated with the datatype Foo * by itself. Therefore, a completely different SWIG customization mechanism (%feature) is used for this purpose. Consult the Customization Features chapter for more information about that.

Typemaps also can't be used to rearrange or transform the order of arguments. For example, if you had a function like this:

void foo(int, char *);

you can't use typemaps to interchange the arguments, allowing you to call the function like this:

foo("hello",3)          # Reversed arguments

If you want to change the calling conventions of a function, write a helper function instead. For example:

%rename(foo) wrap_foo;
%inline %{
void wrap_foo(char *s, int x) {
   foo(x,s);
}
%}

10.1.7 The rest of this chapter

The rest of this chapter provides detailed information for people who want to write new typemaps. This information is of particular importance to anyone who intends to write a new SWIG target language module. Power users can also use this information to write application specific type conversion rules.

Since typemaps are strongly tied to the underlying C++ type system, subsequent sections assume that you are reasonably familiar with the basic details of values, pointers, references, arrays, type qualifiers (e.g., const), structures, namespaces, templates, and memory management in C/C++. If not, you would be well-advised to consult a copy of "The C Programming Language" by Kernighan and Ritchie or "The C++ Programming Language" by Stroustrup before going any further.

10.2 Typemap specifications

This section describes the behavior of the %typemap directive itself.

10.2.1 Defining a typemap

New typemaps are defined using the %typemap declaration. The general form of this declaration is as follows (parts enclosed in [ ... ] are optional):

%typemap(method [, modifiers]) typelist code ;

method is a simply a name that specifies what kind of typemap is being defined. It is usually a name like "in", "out", or "argout". The purpose of these methods is described later.

modifiers is an optional comma separated list of name="value" values. These are sometimes to attach extra information to a typemap and is often target-language dependent.

typelist is a list of the C++ type patterns that the typemap will match. The general form of this list is as follows:

typelist    :  typepattern [, typepattern, typepattern, ... ] ;

typepattern :  type [ (parms) ]
            |  type name [ (parms) ]
            |  ( typelist ) [ (parms) ]

Each type pattern is either a simple type, a simple type and argument name, or a list of types in the case of multi-argument typemaps. In addition, each type pattern can be parameterized with a list of temporary variables (parms). The purpose of these variables will be explained shortly.

code specifies the C code used in the typemap. It can take any one of the following forms:

code       : { ... }
           | " ... "
           | %{ ... %}

Here are some examples of valid typemap specifications:

/* Simple typemap declarations */
%typemap(in) int {
   $1 = PyInt_AsLong($input);
}
%typemap(in) int "$1 = PyInt_AsLong($input);";
%typemap(in) int %{ 
   $1 = PyInt_AsLong($input);
%}

/* Typemap with extra argument name */
%typemap(in) int nonnegative {
   ...
}

/* Multiple types in one typemap */
%typemap(in) int, short, long { 
   $1 = SvIV($input);
}

/* Typemap with modifiers */
%typemap(in,doc="integer") int "$1 = gh_scm2int($input);";

/* Typemap applied to patterns of multiple arguments */
%typemap(in) (char *str, int len),
             (char *buffer, int size)
{
   $1 = PyString_AsString($input);
   $2 = PyString_Size($input);
}

/* Typemap with extra pattern parameters */
%typemap(in, numinputs=0) int *output (int temp),
                          long *output (long temp)
{
   $1 = &temp;
}

Admittedly, it's not the most readable syntax at first glance. However, the purpose of the individual pieces will become clear.

10.2.2 Typemap scope

Once defined, a typemap remains in effect for all of the declarations that follow. A typemap may be redefined for different sections of an input file. For example:

// typemap1
%typemap(in) int {
...
}

int fact(int);                    // typemap1
int gcd(int x, int y);            // typemap1

// typemap2
%typemap(in) int {
...
}

int isprime(int);                 // typemap2

One exception to the typemap scoping rules pertains to the %extend declaration. %extend is used to attach new declarations to a class or structure definition. Because of this, all of the declarations in an %extend block are subject to the typemap rules that are in effect at the point where the class itself is defined. For example:

class Foo {
   ...
};

%typemap(in) int {
 ...
}

%extend Foo {
   int blah(int x);    // typemap has no effect.  Declaration is attached to Foo which 
                       // appears before the %typemap declaration.
};

10.2.3 Copying a typemap

A typemap is copied by using assignment. For example:

%typemap(in) Integer = int;

or this:

%typemap(in) Integer, Number, int32_t = int;

Types are often managed by a collection of different typemaps. For example:

%typemap(in)     int { ... }
%typemap(out)    int { ... }
%typemap(varin)  int { ... }
%typemap(varout) int { ... }

To copy all of these typemaps to a new type, use %apply. For example:

%apply int { Integer };            // Copy all int typemaps to Integer
%apply int { Integer, Number };    // Copy all int typemaps to both Integer and Number

The patterns for %apply follow the same rules as for %typemap. For example:

%apply int *output { Integer *output };                    // Typemap with name
%apply (char *buf, int len) { (char *buffer, int size) };  // Multiple arguments

10.2.4 Deleting a typemap

A typemap can be deleted by simply defining no code. For example:

%typemap(in) int;               // Clears typemap for int
%typemap(in) int, long, short;  // Clears typemap for int, long, short
%typemap(in) int *output;       

The %clear directive clears all typemaps for a given type. For example:

%clear int;                     // Removes all types for int
%clear int *output, long *output;

Note: Since SWIG's default behavior is defined by typemaps, clearing a fundamental type like int will make that type unusable unless you also define a new set of typemaps immediately after the clear operation.

10.2.5 Placement of typemaps

Typemap declarations can be declared in the global scope, within a C++ namespace, and within a C++ class. For example:

%typemap(in) int {
   ...
}

namespace std {
    class string;
    %typemap(in) string {
        ...
    }
}

class Bar {
public:
    typedef const int & const_reference;
    %typemap(out) const_reference {
         ...
    }
};

When a typemap appears inside a namespace or class, it stays in effect until the end of the SWIG input (just like before). However, the typemap takes the local scope into account. Therefore, this code

namespace std {
    class string;
    %typemap(in) string {
       ...
    }
}

is really defining a typemap for the type std::string. You could have code like this:

namespace std {
    class string;
    %typemap(in) string {          /* std::string */
       ...
    }
}

namespace Foo {
    class string;
    %typemap(in) string {          /* Foo::string */
       ...
    }
}

In this case, there are two completely distinct typemaps that apply to two completely different types (std::string and Foo::string).

It should be noted that for scoping to work, SWIG has to know that string is a typename defined within a particular namespace. In this example, this is done using the class declaration class string .

10.3 Pattern matching rules

The section describes the pattern matching rules by which C datatypes are associated with typemaps.

10.3.1 Basic matching rules

Typemaps are matched using both a type and a name (typically the name of a argument). For a given TYPE NAME pair, the following rules are applied, in order, to find a match. The first typemap found is used.

If TYPE includes qualifiers (const, volatile, etc.), they are stripped and the following checks are made:

If TYPE is an array. The following transformation is made:

To illustrate, suppose that you had a function like this:

int foo(const char *s);

To find a typemap for the argument const char *s, SWIG will search for the following typemaps:

const char *s           Exact type and name match
const char *            Exact type match
char *s                 Type and name match (stripped qualifiers)
char *                  Type match (stripped qualifiers)

When more than one typemap rule might be defined, only the first match found is actually used. Here is an example that shows how some of the basic rules are applied:

%typemap(in) int *x {
   ... typemap 1
}

%typemap(in) int * {
   ... typemap 2
}

%typemap(in) const int *z {
   ... typemap 3
}

%typemap(in) int [4] {
   ... typemap 4
}

%typemap(in) int [ANY] {
   ... typemap 5
}

void A(int *x);        // int *x rule    (typemap 1)
void B(int *y);        // int * rule     (typemap 2)
void C(const int *x);  // int *x rule    (typemap 1)
void D(const int *z);  // int * rule     (typemap 3)
void E(int x[4]);      // int [4] rule   (typemap 4)
void F(int x[1000]);   // int [ANY] rule (typemap 5)

10.3.2 Typedef reductions

If no match is found using the rules in the previous section, SWIG applies a typedef reduction to the type and repeats the typemap search for the reduced type. To illustrate, suppose you had code like this:

%typemap(in) int {
   ... typemap 1
}

typedef int Integer;
void blah(Integer x);

To find the typemap for Integer x, SWIG will first search for the following typemaps:

Integer x
Integer

Finding no match, it then applies a reduction Integer -> int to the type and repeats the search.

int x
int      --> match: typemap 1

Even though two types might be the same via typedef, SWIG allows typemaps to be defined for each typename independently. This allows for interesting customization possibilities based solely on the typename itself. For example, you could write code like this:

typedef double  pdouble;     // Positive double

// typemap 1
%typemap(in) double {
   ... get a double ...
}
// typemap 2
%typemap(in) pdouble {
   ... get a positive double ...
}
double sin(double x);           // typemap 1
pdouble sqrt(pdouble x);        // typemap 2

When reducing the type, only one typedef reduction is applied at a time. The search process continues to apply reductions until a match is found or until no more reductions can be made.

For complicated types, the reduction process can generate a long list of patterns. Consider the following:

typedef int Integer;
typedef Integer Row4[4];
void foo(Row4 rows[10]);

To find a match for the Row4 rows[10] argument, SWIG would check the following patterns, stopping only when it found a match:

Row4 rows[10]
Row4 [10]
Row4 rows[ANY]
Row4 [ANY]

# Reduce Row4 --> Integer[4]
Integer rows[10][4]
Integer [10][4]
Integer rows[ANY][ANY]
Integer [ANY][ANY]

# Reduce Integer --> int
int rows[10][4]
int [10][4]
int rows[ANY][ANY]
int [ANY][ANY]

For parameterized types like templates, the situation is even more complicated. Suppose you had some declarations like this:

typedef int Integer;
typedef foo<Integer,Integer> fooii;
void blah(fooii *x);

In this case, the following typemap patterns are searched for the argument fooii *x:

fooii *x
fooii *

# Reduce fooii --> foo<Integer,Integer>
foo<Integer,Integer> *x
foo<Integer,Integer> *

# Reduce Integer -> int
foo<int, Integer> *x
foo<int, Integer> *

# Reduce Integer -> int
foo<int, int> *x
foo<int, int> *

Typemap reductions are always applied to the left-most type that appears. Only when no reductions can be made to the left-most type are reductions made to other parts of the type. This behavior means that you could define a typemap for foo<int,Integer>, but a typemap for foo<Integer,int> would never be matched. Admittedly, this is rather esoteric--there's little practical reason to write a typemap quite like that. Of course, you could rely on this to confuse your coworkers even more.

10.3.3 Default typemaps

Most SWIG language modules use typemaps to define the default behavior of the C primitive types. This is entirely straightforward. For example, a set of typemaps are written like this:

%typemap(in) int   "convert an int";
%typemap(in) short "convert a short";
%typemap(in) float "convert a float";
...

Since typemap matching follows all typedef declarations, any sort of type that is mapped to a primitive type through typedef will be picked up by one of these primitive typemaps.

The default behavior for pointers, arrays, references, and other kinds of types are handled by specifying rules for variations of the reserved SWIGTYPE type. For example:

%typemap(in) SWIGTYPE *            { ... default pointer handling ...         }
%typemap(in) SWIGTYPE &            { ... default reference handling ...       }
%typemap(in) SWIGTYPE []           { ... default array handling ...           }
%typemap(in) enum SWIGTYPE         { ... default handling for enum values ... }
%typemap(in) SWIGTYPE (CLASS::*)   { ... default pointer member handling ...  } 

These rules match any kind of pointer, reference, or array--even when multiple levels of indirection or multiple array dimensions are used. Therefore, if you wanted to change SWIG's default handling for all types of pointers, you would simply redefine the rule for SWIGTYPE *.

Finally, the following typemap rule is used to match against simple types that don't match any other rules:

%typemap(in) SWIGTYPE   { ... handle an unknown type ... }

This typemap is important because it is the rule that gets triggered when call or return by value is used. For instance, if you have a declaration like this:

double dot_product(Vector a, Vector b);

The Vector type will usually just get matched against SWIGTYPE. The default implementation of SWIGTYPE is to convert the value into pointers (as described in chapter 3).

By redefining SWIGTYPE it may be possible to implement other behavior. For example, if you cleared all typemaps for SWIGTYPE, SWIG simply won't wrap any unknown datatype (which might be useful for debugging). Alternatively, you might modify SWIGTYPE to marshal objects into strings instead of converting them to pointers.

The best way to explore the default typemaps is to look at the ones already defined for a particular language module. Typemaps definitions are usually found in the SWIG library in a file such as python.swg , tcl8.swg, etc.

10.3.4 Mixed default typemaps

The default typemaps described above can be mixed with const and with each other. For example the SWIGTYPE * typemap is for default pointer handling, but if a const SWIGTYPE * typemap is defined it will be used instead for constant pointers. Some further examples follow:

%typemap(in) enum SWIGTYPE &        { ... enum references ...                       }
%typemap(in) const enum SWIGTYPE &  { ... const enum references ...                 }
%typemap(in) SWIGTYPE *&            { ... pointers passed by reference ...          }
%typemap(in) SWIGTYPE * const &     { ... constant pointers passed by reference ... }
%typemap(in) SWIGTYPE[ANY][ANY]     { ... 2D arrays ...                             }

Note that the the typedef reduction described earlier is also used with these mixed default typemaps. For example, say the following typemaps are defined and SWIG is looking for the best match for the enum shown below:

%typemap(in) const Hello &          { ... }
%typemap(in) const enum SWIGTYPE &  { ... }
%typemap(in) enum SWIGTYPE &        { ... }
%typemap(in) SWIGTYPE &             { ... }
%typemap(in) SWIGTYPE               { ... }

enum Hello {};
const Hello &hi;

The typemap at the top of the list will be chosen, not because it is defined first, but because it is the closest match for the type being wrapped. If any of the typemaps in the above list were not defined, then the next one on the list would have precedence. In other words the typemap chosen is the closest explicit match.

Compatibility note: The mixed default typemaps were introduced in SWIG-1.3.23, but were not used much in this version. Expect to see them being used more and more within the various libraries in later versions of SWIG.

10.3.5 Multi-arguments typemaps

When multi-argument typemaps are specified, they take precedence over any typemaps specified for a single type. For example:

%typemap(in) (char *buffer, int len) {
   // typemap 1
}

%typemap(in) char *buffer {
   // typemap 2
}

void foo(char *buffer, int len, int count); // (char *buffer, int len)
void bar(char *buffer, int blah);           // char *buffer

Multi-argument typemaps are also more restrictive in the way that they are matched. Currently, the first argument follows the matching rules described in the previous section, but all subsequent arguments must match exactly.

10.4 Code generation rules

This section describes rules by which typemap code is inserted into the generated wrapper code.

10.4.1 Scope

When a typemap is defined like this:

%typemap(in) int {
   $1 = PyInt_AsLong($input);
}

the typemap code is inserted into the wrapper function using a new block scope. In other words, the wrapper code will look like this:

wrap_whatever() {
    ...
    // Typemap code
    {                    
       arg1 = PyInt_AsLong(obj1);
    }
    ...
}

Because the typemap code is enclosed in its own block, it is legal to declare temporary variables for use during typemap execution. For example:

%typemap(in) short {
   long temp;          /* Temporary value */
   if (Tcl_GetLongFromObj(interp, $input, &temp) != TCL_OK) {
      return TCL_ERROR;
   }
   $1 = (short) temp;
}

Of course, any variables that you declare inside a typemap are destroyed as soon as the typemap code has executed (they are not visible to other parts of the wrapper function or other typemaps that might use the same variable names).

Occasionally, typemap code will be specified using a few alternative forms. For example:

%typemap(in) int "$1 = PyInt_AsLong($input);";
%typemap(in) int %{
$1 = PyInt_AsLong($input);
%}

These two forms are mainly used for cosmetics--the specified code is not enclosed inside a block scope when it is emitted. This sometimes results in a less complicated looking wrapper function.

10.4.2 Declaring new local variables

Sometimes it is useful to declare a new local variable that exists within the scope of the entire wrapper function. A good example of this might be an application in which you wanted to marshal strings. Suppose you had a C++ function like this

int foo(std::string *s);

and you wanted to pass a native string in the target language as an argument. For instance, in Perl, you wanted the function to work like this:

$x = foo("Hello World");

To do this, you can't just pass a raw Perl string as the std::string * argument. Instead, you have to create a temporary std::string object, copy the Perl string data into it, and then pass a pointer to the object. To do this, simply specify the typemap with an extra parameter like this:

%typemap(in) std::string * (std::string temp) {
    unsigned int len;
    char        *s;
    s = SvPV($input,len);         /* Extract string data */
    temp.assign(s,len);           /* Assign to temp */
    $1 = &temp;                   /* Set argument to point to temp */
}

In this case, temp becomes a local variable in the scope of the entire wrapper function. For example:

wrap_foo() {
   std::string temp;    <--- Declaration of temp goes here
   ...

   /* Typemap code */
   {
      ...
      temp.assign(s,len);
      ...
   } 
   ...
}

When you set temp to a value, it persists for the duration of the wrapper function and gets cleaned up automatically on exit.

It is perfectly safe to use more than one typemap involving local variables in the same declaration. For example, you could declare a function as :

void foo(std::string *x, std::string *y, std::string *z);

This is safely handled because SWIG actually renames all local variable references by appending an argument number suffix. Therefore, the generated code would actually look like this:

wrap_foo() {
   int *arg1;    /* Actual arguments */
   int *arg2;
   int *arg3;
   std::string temp1;    /* Locals declared in the typemap */
   std::string temp2;
   std::string temp3;
   ...
   {
       char *s;
       unsigned int len;
       ...
       temp1.assign(s,len);
       arg1 = *temp1;
   }
   {
       char *s;
       unsigned int len;
       ...
       temp2.assign(s,len);
       arg2 = &temp2;
   }
   {
       char *s;
       unsigned int len;
       ...
       temp3.assign(s,len);
       arg3 = &temp3;
   }
   ...
}

Some typemaps do not recognize local variables (or they may simply not apply). At this time, only typemaps that apply to argument conversion support this.

10.4.3 Special variables

Within all typemaps, the following special variables are expanded.

VariableMeaning
$n A C local variable corresponding to type n in the typemap pattern.
$argnumArgument number. Only available in typemaps related to argument conversion
$n_nameArgument name
$n_typeReal C datatype of type n.
$n_ltypeltype of type n
$n_mangleMangled form of type n. For example _p_Foo
$n_descriptorType descriptor structure for type n. For example SWIGTYPE_p_Foo. This is primarily used when interacting with the run-time type checker (described later).
$*n_typeReal C datatype of type n with one pointer removed.
$*n_ltypeltype of type n with one pointer removed.
$*n_mangleMangled form of type n with one pointer removed.
$*n_descriptorType descriptor structure for type n with one pointer removed.
$&n_typeReal C datatype of type n with one pointer added.
$&n_ltypeltype of type n with one pointer added.
$&n_mangleMangled form of type n with one pointer added.
$&n_descriptorType descriptor structure for type n with one pointer added.
$n_basetypeBase typename with all pointers and qualifiers stripped.

Within the table, $n refers to a specific type within the typemap specification. For example, if you write this

%typemap(in) int *INPUT {

}

then $1 refers to int *INPUT. If you have a typemap like this,

%typemap(in) (int argc, char *argv[]) {
  ...
}

then $1 refers to int argc and $2 refers to char *argv[].

Substitutions related to types and names always fill in values from the actual code that was matched. This is useful when a typemap might match multiple C datatype. For example:

%typemap(in)  int, short, long {
   $1 = ($1_ltype) PyInt_AsLong($input);
}

In this case, $1_ltype is replaced with the datatype that is actually matched.

When typemap code is emitted, the C/C++ datatype of the special variables $1 and $2 is always an "ltype." An "ltype" is simply a type that can legally appear on the left-hand side of a C assignment operation. Here are a few examples of types and ltypes:

type              ltype
------            ----------------
int               int
const int         int
const int *       int *
int [4]           int *
int [4][5]        int (*)[5]

In most cases a ltype is simply the C datatype with qualifiers stripped off. In addition, arrays are converted into pointers.

Variables such as $&1_type and $*1_type are used to safely modify the type by removing or adding pointers. Although not needed in most typemaps, these substitutions are sometimes needed to properly work with typemaps that convert values between pointers and values.

If necessary, type related substitutions can also be used when declaring locals. For example:

%typemap(in) int * ($*1_type temp) {
    temp = PyInt_AsLong($input);
    $1 = &temp;
}

There is one word of caution about declaring local variables in this manner. If you declare a local variable using a type substitution such as $1_ltype temp, it won't work like you expect for arrays and certain kinds of pointers. For example, if you wrote this,

%typemap(in) int [10][20] {
   $1_ltype temp;
}

then the declaration of temp will be expanded as

int (*)[20] temp;

This is illegal C syntax and won't compile. There is currently no straightforward way to work around this problem in SWIG due to the way that typemap code is expanded and processed. However, one possible workaround is to simply pick an alternative type such as void * and use casts to get the correct type when needed. For example:

%typemap(in) int [10][20] {
   void *temp;
   ...
   (($1_ltype) temp)[i][j] = x;    /* set a value */
   ...
}

Another approach, which only works for arrays is to use the $1_basetype substitution. For example:

%typemap(in) int [10][20] {
   $1_basetype temp[10][20];
   ...
   temp[i][j] = x;    /* set a value */
   ...
}

10.5 Common typemap methods

The set of typemaps recognized by a language module may vary. However, the following typemap methods are nearly universal:

10.5.1 "in" typemap

The "in" typemap is used to convert function arguments from the target language to C. For example:

%typemap(in) int {
   $1 = PyInt_AsLong($input);
}

The following special variables are available:

$input            - Input object holding value to be converted.
$symname          - Name of function/method being wrapped

This is probably the most commonly redefined typemap because it can be used to implement customized conversions.

In addition, the "in" typemap allows the number of converted arguments to be specified. For example:

// Ignored argument.
%typemap(in, numinputs=0) int *out (int temp) {
    $1 = &temp;
}

At this time, only zero or one arguments may be converted.

Compatibility note: Specifying numinputs=0 is the same as the old "ignore" typemap.

10.5.2 "typecheck" typemap

The "typecheck" typemap is used to support overloaded functions and methods. It merely checks an argument to see whether or not it matches a specific type. For example:

%typemap(typecheck,precedence=SWIG_TYPECHECK_INTEGER) int {
   $1 = PyInt_Check($input) ? 1 : 0;
}

For typechecking, the $1 variable is always a simple integer that is set to 1 or 0 depending on whether or not the input argument is the correct type.

If you define new "in" typemaps and your program uses overloaded methods, you should also define a collection of "typecheck" typemaps. More details about this follow in a later section on "Typemaps and Overloading."

10.5.3 "out" typemap

The "out" typemap is used to convert function/method return values from C into the target language. For example:

%typemap(out) int {
   $result = PyInt_FromLong($1);
}

The following special variables are available.

$result           - Result object returned to target language.
$symname          - Name of function/method being wrapped

10.5.4 "arginit" typemap

The "arginit" typemap is used to set the initial value of a function argument--before any conversion has occurred. This is not normally necessary, but might be useful in highly specialized applications. For example:

// Set argument to NULL before any conversion occurs
%typemap(arginit) int *data {
   $1 = NULL;
}

10.5.5 "default" typemap

The "default" typemap is used to turn an argument into a default argument. For example:

%typemap(default) int flags {
   $1 = DEFAULT_FLAGS;
}
...
int foo(int x, int y, int flags);

The primary use of this typemap is to either change the wrapping of default arguments or specify a default argument in a language where they aren't supported (like C). Target languages that do not support optional arguments, such as Java and C#, effectively ignore the value specified by this typemap as all arguments must be given.

Once a default typemap has been applied to an argument, all arguments that follow must have default values. See the Default/optional arguments section for further information on default argument wrapping.

10.5.6 "check" typemap

The "check" typemap is used to supply value checking code during argument conversion. The typemap is applied after arguments have been converted. For example:

%typemap(check) int positive {
   if ($1 <= 0) {
       SWIG_exception(SWIG_ValueError,"Expected positive value.");
   }
}

10.5.7 "argout" typemap

The "argout" typemap is used to return values from arguments. This is most commonly used to write wrappers for C/C++ functions that need to return multiple values. The "argout" typemap is almost always combined with an "in" typemap---possibly to ignore the input value. For example:

/* Set the input argument to point to a temporary variable */
%typemap(in, numinputs=0) int *out (int temp) {
   $1 = &temp;
}

%typemap(argout) int *out {
   // Append output value $1 to $result
   ...
}

The following special variables are available.

$result           - Result object returned to target language.
$input            - The original input object passed.
$symname          - Name of function/method being wrapped

The code supplied to the "argout" typemap is always placed after the "out" typemap. If multiple return values are used, the extra return values are often appended to return value of the function.

See the typemaps.i library for examples.

10.5.8 "freearg" typemap

The "freearg" typemap is used to cleanup argument data. It is only used when an argument might have allocated resources that need to be cleaned up when the wrapper function exits. The "freearg" typemap usually cleans up argument resources allocated by the "in" typemap. For example:

// Get a list of integers
%typemap(in) int *items {
   int nitems = Length($input);    
   $1 = (int *) malloc(sizeof(int)*nitems);
}
// Free the list 
%typemap(freearg) int *items {
   free($1);
}

The "freearg" typemap inserted at the end of the wrapper function, just before control is returned back to the target language. This code is also placed into a special variable $cleanup that may be used in other typemaps whenever a wrapper function needs to abort prematurely.

10.5.9 "newfree" typemap

The "newfree" typemap is used in conjunction with the %newobject directive and is used to deallocate memory used by the return result of a function. For example:

%typemap(newfree) string * {
   delete $1;
}
%typemap(out) string * {
   $result = PyString_FromString($1->c_str());
}
...

%newobject foo;
...
string *foo();

See Object ownership and %newobject for further details.

10.5.10 "memberin" typemap

The "memberin" typemap is used to copy data from an already converted input value into a structure member. It is typically used to handle array members and other special cases. For example:

%typemap(memberin) int [4] {
   memmove($1, $input, 4*sizeof(int));
}

It is rarely necessary to write "memberin" typemaps---SWIG already provides a default implementation for arrays, strings, and other objects.

10.5.11 "varin" typemap

The "varin" typemap is used to convert objects in the target language to C for the purposes of assigning to a C/C++ global variable. This is implementation specific.

10.5.12 "varout" typemap

The "varout" typemap is used to convert a C/C++ object to an object in the target language when reading a C/C++ global variable. This is implementation specific.

10.5.13 "throws" typemap

The "throws" typemap is only used when SWIG parses a C++ method with an exception specification or has the %catches feature attached to the method. It provides a default mechanism for handling C++ methods that have declared the exceptions they will throw. The purpose of this typemap is to convert a C++ exception into an error or exception in the target language. It is slightly different to the other typemaps as it is based around the exception type rather than the type of a parameter or variable. For example:

%typemap(throws) const char * %{
  PyErr_SetString(PyExc_RuntimeError, $1);
  SWIG_fail;
%}
void bar() throw (const char *);

As can be seen from the generated code below, SWIG generates an exception handler with the catch block comprising the "throws" typemap content.

...
try {
    bar();
}
catch(char const *_e) {
    PyErr_SetString(PyExc_RuntimeError, _e);
    SWIG_fail;
    
}
...

Note that if your methods do not have an exception specification yet they do throw exceptions, SWIG cannot know how to deal with them. For a neat way to handle these, see the Exception handling with %exception section.

10.6 Some typemap examples

This section contains a few examples. Consult language module documentation for more examples.

10.6.1 Typemaps for arrays

A common use of typemaps is to provide support for C arrays appearing both as arguments to functions and as structure members.

For example, suppose you had a function like this:

void set_vector(int type, float value[4]);

If you wanted to handle float value[4] as a list of floats, you might write a typemap similar to this:


%typemap(in) float value[4] (float temp[4]) {
  int i;
  if (!PySequence_Check($input)) {
    PyErr_SetString(PyExc_ValueError,"Expected a sequence");
    return NULL;
  }
  if (PySequence_Length($input) != 4) {
    PyErr_SetString(PyExc_ValueError,"Size mismatch. Expected 4 elements");
    return NULL;
  }
  for (i = 0; i < 4; i++) {
    PyObject *o = PySequence_GetItem($input,i);
    if (PyNumber_Check(o)) {
      temp[i] = (float) PyFloat_AsDouble(o);
    } else {
      PyErr_SetString(PyExc_ValueError,"Sequence elements must be numbers");      
      return NULL;
    }
  }
  $1 = temp;
}

In this example, the variable temp allocates a small array on the C stack. The typemap then populates this array and passes it to the underlying C function.

When used from Python, the typemap allows the following type of function call:

>>> set_vector(type, [ 1, 2.5, 5, 20 ])

If you wanted to generalize the typemap to apply to arrays of all dimensions you might write this:

%typemap(in) float value[ANY] (float temp[$1_dim0]) {
  int i;
  if (!PySequence_Check($input)) {
    PyErr_SetString(PyExc_ValueError,"Expected a sequence");
    return NULL;
  }
  if (PySequence_Length($input) != $1_dim0) {
    PyErr_SetString(PyExc_ValueError,"Size mismatch. Expected $1_dim0 elements");
    return NULL;
  }
  for (i = 0; i < $1_dim0; i++) {
    PyObject *o = PySequence_GetItem($input,i);
    if (PyNumber_Check(o)) {
      temp[i] = (float) PyFloat_AsDouble(o);
    } else {
      PyErr_SetString(PyExc_ValueError,"Sequence elements must be numbers");      
      return NULL;
    }
  }
  $1 = temp;
}

In this example, the special variable $1_dim0 is expanded with the actual array dimensions. Multidimensional arrays can be matched in a similar manner. For example:

%typemap(in) float matrix[ANY][ANY] (float temp[$1_dim0][$1_dim1]) {
   ... convert a 2d array ...
}

For large arrays, it may be impractical to allocate storage on the stack using a temporary variable as shown. To work with heap allocated data, the following technique can be used.

%typemap(in) float value[ANY] {
  int i;
  if (!PySequence_Check($input)) {
    PyErr_SetString(PyExc_ValueError,"Expected a sequence");
    return NULL;
  }
  if (PySequence_Length($input) != $1_dim0) {
    PyErr_SetString(PyExc_ValueError,"Size mismatch. Expected $1_dim0 elements");
    return NULL;
  }
  $1 = (float *) malloc($1_dim0*sizeof(float));
  for (i = 0; i < $1_dim0; i++) {
    PyObject *o = PySequence_GetItem($input,i);
    if (PyNumber_Check(o)) {
      $1[i] = (float) PyFloat_AsDouble(o);
    } else {
      PyErr_SetString(PyExc_ValueError,"Sequence elements must be numbers");      
      free($1);
      return NULL;
    }
  }
}
%typemap(freearg) float value[ANY] {
   if ($1) free($1);
}

In this case, an array is allocated using malloc. The freearg typemap is then used to release the argument after the function has been called.

Another common use of array typemaps is to provide support for array structure members. Due to subtle differences between pointers and arrays in C, you can't just "assign" to a array structure member. Instead, you have to explicitly copy elements into the array. For example, suppose you had a structure like this:

struct SomeObject {
	float  value[4];
        ...
};

When SWIG runs, it won't produce any code to set the vec member. You may even get a warning message like this:

swig -python  example.i
Generating wrappers for Python
example.i:10.  Warning. Array member value will be read-only.

These warning messages indicate that SWIG does not know how you want to set the vec field.

To fix this, you can supply a special "memberin" typemap like this:

%typemap(memberin) float [ANY] {
  int i;
  for (i = 0; i < $1_dim0; i++) {
      $1[i] = $input[i];
  }
}

The memberin typemap is used to set a structure member from data that has already been converted from the target language to C. In this case, $input is the local variable in which converted input data is stored. This typemap then copies this data into the structure.

When combined with the earlier typemaps for arrays, the combination of the "in" and "memberin" typemap allows the following usage:

>>> s = SomeObject()
>>> s.x = [1, 2.5, 5, 10]

Related to structure member input, it may be desirable to return structure members as a new kind of object. For example, in this example, you will get very odd program behavior where the structure member can be set nicely, but reading the member simply returns a pointer:

>>> s = SomeObject()
>>> s.x = [1, 2.5, 5, 10]
>>> print s.x
_1008fea8_p_float
>>> 

To fix this, you can write an "out" typemap. For example:

%typemap(out) float [ANY] {
  int i;
  $result = PyList_New($1_dim0);
  for (i = 0; i < $1_dim0; i++) {
    PyObject *o = PyFloat_FromDouble((double) $1[i]);
    PyList_SetItem($result,i,o);
  }
}

Now, you will find that member access is quite nice:

>>> s = SomeObject()
>>> s.x = [1, 2.5, 5, 10]
>>> print s.x
[ 1, 2.5, 5, 10]

Compatibility Note: SWIG1.1 used to provide a special "memberout" typemap. However, it was mostly useless and has since been eliminated. To return structure members, simply use the "out" typemap.

10.6.2 Implementing constraints with typemaps

One particularly interesting application of typemaps is the implementation of argument constraints. This can be done with the "check" typemap. When used, this allows you to provide code for checking the values of function arguments. For example :

%module math

%typemap(check) double posdouble {
	if ($1 < 0) {
		croak("Expecting a positive number");
	}
}

...
double sqrt(double posdouble);

This provides a sanity check to your wrapper function. If a negative number is passed to this function, a Perl exception will be raised and your program terminated with an error message.

This kind of checking can be particularly useful when working with pointers. For example :

%typemap(check) Vector * {
    if ($1 == 0) {
        PyErr_SetString(PyExc_TypeError,"NULL Pointer not allowed");
        return NULL;
   }
}

will prevent any function involving a Vector * from accepting a NULL pointer. As a result, SWIG can often prevent a potential segmentation faults or other run-time problems by raising an exception rather than blindly passing values to the underlying C/C++ program.

Note: A more advanced constraint checking system is in development. Stay tuned.

10.7 Typemaps for multiple languages

The code within typemaps is usually language dependent, however, many languages support the same typemaps. In order to distinguish typemaps across different languages, the preprocessor should be used. For example, the "in" typemap for Perl and Ruby could be written as:

#if defined(SWIGPERL)
  %typemap(in) int "$1 = NUM2INT($input);"
#elif defined(SWIGRUBY)
  %typemap(in) int "$1 = ($1_ltype) SvIV($input);"
#else
  #warning no "in" typemap defined
#endif

The full set of language specific macros is defined in the Conditional Compilation section. The example above also shows a common approach of issuing a warning for an as yet unsupported language.

Compatibility note: In SWIG-1.1 different languages could be distinguished with the language name being put within the %typemap directive, for example,
%typemap(ruby,in) int "$1 = NUM2INT($input);".

10.8 Multi-argument typemaps

So far, the typemaps presented have focused on the problem of dealing with single values. For example, converting a single input object to a single argument in a function call. However, certain conversion problems are difficult to handle in this manner. As an example, consider the example at the very beginning of this chapter:

int foo(int argc, char *argv[]);

Suppose that you wanted to wrap this function so that it accepted a single list of strings like this:

>>> foo(["ale","lager","stout"])

To do this, you not only need to map a list of strings to char *argv[], but the value of int argc is implicitly determined by the length of the list. Using only simple typemaps, this type of conversion is possible, but extremely painful. Therefore, SWIG1.3 introduces the notion of multi-argument typemaps.

A multi-argument typemap is a conversion rule that specifies how to convert a single object in the target language to set of consecutive function arguments in C/C++. For example, the following multi-argument maps perform the conversion described for the above example:

%typemap(in) (int argc, char *argv[]) {
  int i;
  if (!PyList_Check($input)) {
    PyErr_SetString(PyExc_ValueError, "Expecting a list");
    return NULL;
  }
  $1 = PyList_Size($input);
  $2 = (char **) malloc(($1+1)*sizeof(char *));
  for (i = 0; i < $1; i++) {
    PyObject *s = PyList_GetItem($input,i);
    if (!PyString_Check(s)) {
        free($2);
        PyErr_SetString(PyExc_ValueError, "List items must be strings");
        return NULL;
    }
    $2[i] = PyString_AsString(s);
  }
  $2[i] = 0;
}

%typemap(freearg) (int argc, char *argv[]) {
   if ($2) free($2);
}

A multi-argument map is always specified by surrounding the arguments with parentheses as shown. For example:

%typemap(in) (int argc, char *argv[]) { ... }

Within the typemap code, the variables $1, $2, and so forth refer to each type in the map. All of the usual substitutions apply--just use the appropriate $1 or $2 prefix on the variable name (e.g., $2_type, $1_ltype, etc.)

Multi-argument typemaps always have precedence over simple typemaps and SWIG always performs longest-match searching. Therefore, you will get the following behavior:

%typemap(in) int argc                              { ... typemap 1 ... }
%typemap(in) (int argc, char *argv[])              { ... typemap 2 ... }
%typemap(in) (int argc, char *argv[], char *env[]) { ... typemap 3 ... }

int foo(int argc, char *argv[]);                   // Uses typemap 2
int bar(int argc, int x);                          // Uses typemap 1
int spam(int argc, char *argv[], char *env[]);     // Uses typemap 3

It should be stressed that multi-argument typemaps can appear anywhere in a function declaration and can appear more than once. For example, you could write this:

%typemap(in) (int scount, char *swords[]) { ... }
%typemap(in) (int wcount, char *words[]) { ... }

void search_words(int scount, char *swords[], int wcount, char *words[], int maxcount);

Other directives such as %apply and %clear also work with multi-argument maps. For example:

%apply (int argc, char *argv[]) {
    (int scount, char *swords[]),
    (int wcount, char *words[])
};
...
%clear (int scount, char *swords[]), (int wcount, char *words[]);
...

Although multi-argument typemaps may seem like an exotic, little used feature, there are several situations where they make sense. First, suppose you wanted to wrap functions similar to the low-level read() and write() system calls. For example:

typedef unsigned int size_t;

int read(int fd, void *rbuffer, size_t len);
int write(int fd, void *wbuffer, size_t len);

As is, the only way to use the functions would be to allocate memory and pass some kind of pointer as the second argument---a process that might require the use of a helper function. However, using multi-argument maps, the functions can be transformed into something more natural. For example, you might write typemaps like this:

// typemap for an outgoing buffer
%typemap(in) (void *wbuffer, size_t len) {
   if (!PyString_Check($input)) {
       PyErr_SetString(PyExc_ValueError, "Expecting a string");
       return NULL;
   }
   $1 = (void *) PyString_AsString($input);
   $2 = PyString_Size($input);
}

// typemap for an incoming buffer
%typemap(in) (void *rbuffer, size_t len) {
   if (!PyInt_Check($input)) {
       PyErr_SetString(PyExc_ValueError, "Expecting an integer");
       return NULL;
   }
   $2 = PyInt_AsLong($input);
   if ($2 < 0) {
       PyErr_SetString(PyExc_ValueError, "Positive integer expected");
       return NULL;
   }
   $1 = (void *) malloc($2);
}

// Return the buffer.  Discarding any previous return result
%typemap(argout) (void *rbuffer, size_t len) {
   Py_XDECREF($result);   /* Blow away any previous result */
   if (result < 0) {      /* Check for I/O error */
       free($1);
       PyErr_SetFromErrno(PyExc_IOError);
       return NULL;
   }
   $result = PyString_FromStringAndSize($1,result);
   free($1);
}

(note: In the above example, $result and result are two different variables. result is the real C datatype that was returned by the function. $result is the scripting language object being returned to the interpreter.).

Now, in a script, you can write code that simply passes buffers as strings like this:

>>> f = example.open("Makefile")
>>> example.read(f,40)
'TOP        = ../..\nSWIG       = $(TOP)/.'
>>> example.read(f,40)
'./swig\nSRCS       = example.c\nTARGET    '
>>> example.close(f)
0
>>> g = example.open("foo", example.O_WRONLY | example.O_CREAT, 0644)
>>> example.write(g,"Hello world\n")
12
>>> example.write(g,"This is a test\n")
15
>>> example.close(g)
0
>>>

A number of multi-argument typemap problems also arise in libraries that perform matrix-calculations--especially if they are mapped onto low-level Fortran or C code. For example, you might have a function like this:

int is_symmetric(double *mat, int rows, int columns);

In this case, you might want to pass some kind of higher-level object as an matrix. To do this, you could write a multi-argument typemap like this:

%typemap(in) (double *mat, int rows, int columns) {
    MatrixObject *a;
    a = GetMatrixFromObject($input);     /* Get matrix somehow */

    /* Get matrix properties */
    $1 = GetPointer(a);
    $2 = GetRows(a);
    $3 = GetColumns(a);
}

This kind of technique can be used to hook into scripting-language matrix packages such as Numeric Python. However, it should also be stressed that some care is in order. For example, when crossing languages you may need to worry about issues such as row-major vs. column-major ordering (and perform conversions if needed).

10.9 The run-time type checker

Most scripting languages need type information at run-time. This type information can include how to construct types, how to garbage collect types, and the inheritance relationships between types. If the language interface does not provide its own type information storage, the generated SWIG code needs to provide it.

Requirements for the type system:

10.9.1 Implementation

The run-time type checker is used by many, but not all, of SWIG's supported target languages. The run-time type checker features are not required and are thus not used for strongly typed languages such as Java and C#. The scripting and scheme based languages rely on it and it forms a critical part of SWIG's operation for these languages.

When pointers, arrays, and objects are wrapped by SWIG, they are normally converted into typed pointer objects. For example, an instance of Foo * might be a string encoded like this:

_108e688_p_Foo

At a basic level, the type checker simply restores some type-safety to extension modules. However, the type checker is also responsible for making sure that wrapped C++ classes are handled correctly---especially when inheritance is used. This is especially important when an extension module makes use of multiple inheritance. For example:

class Foo {
   int x;
};

class Bar {
   int y;
};

class FooBar : public Foo, public Bar {
   int z;
};

When the class FooBar is organized in memory, it contains the contents of the classes Foo and Bar as well as its own data members. For example:

FooBar --> | -----------|  <-- Foo
           |   int x    |
           |------------|  <-- Bar
           |   int y    |
           |------------|
           |   int z    |
           |------------|

Because of the way that base class data is stacked together, the casting of a Foobar * to either of the base classes may change the actual value of the pointer. This means that it is generally not safe to represent pointers using a simple integer or a bare void * ---type tags are needed to implement correct handling of pointer values (and to make adjustments when needed).

In the wrapper code generated for each language, pointers are handled through the use of special type descriptors and conversion functions. For example, if you look at the wrapper code for Python, you will see code like this:

if ((SWIG_ConvertPtr(obj0,(void **) &arg1, SWIGTYPE_p_Foo,1)) == -1) return NULL;

In this code, SWIGTYPE_p_Foo is the type descriptor that describes Foo *. The type descriptor is actually a pointer to a structure that contains information about the type name to use in the target language, a list of equivalent typenames (via typedef or inheritance), and pointer value handling information (if applicable). The SWIG_ConvertPtr() function is simply a utility function that takes a pointer object in the target language and a type-descriptor objects and uses this information to generate a C++ pointer. However, the exact name and calling conventions of the conversion function depends on the target language (see language specific chapters for details).

The actual type code is in swigrun.swg, and gets inserted near the top of the generated swig wrapper file. The phrase "a type X that can cast into a type Y" means that given a type X, it can be converted into a type Y. In other words, X is a derived class of Y or X is a typedef of Y. The structure to store type information looks like this:

/* Structure to store information on one type */
typedef struct swig_type_info {
  const char *name;             /* mangled name of this type */
  const char *str;              /* human readable name for this type */
  swig_dycast_func dcast;       /* dynamic cast function down a hierarchy */
  struct swig_cast_info *cast;  /* Linked list of types that can cast into this type */
  void *clientdata;             /* Language specific type data */
} swig_type_info;

/* Structure to store a type and conversion function used for casting */
typedef struct swig_cast_info {
  swig_type_info *type;          /* pointer to type that is equivalent to this type */
  swig_converter_func converter; /* function to cast the void pointers */
  struct swig_cast_info *next;   /* pointer to next cast in linked list */
  struct swig_cast_info *prev;   /* pointer to the previous cast */
} swig_cast_info;

Each swig_type_info stores a linked list of types that it is equivalent to. Each entry in this doubly linked list stores a pointer back to another swig_type_info structure, along with a pointer to a conversion function. This conversion function is used to solve the above problem of the FooBar class, correctly returning a pointer to the type we want.

The basic problem we need to solve is verifying and building arguments passed to functions. So going back to the SWIG_ConvertPtr() function example from above, we are expecting a Foo * and need to check if obj0 is in fact a Foo * . From before, SWIGTYPE_p_Foo is just a pointer to the swig_type_info structure describing Foo *. So we loop through the linked list of swig_cast_info structures attached to SWIGTYPE_p_Foo. If we see that the type of obj0 is in the linked list, we pass the object through the associated conversion function and then return a positive. If we reach the end of the linked list without a match, then obj0 can not be converted to a Foo * and an error is generated.

Another issue needing to be addressed is sharing type information between multiple modules. More explicitly, we need to have ONE swig_type_info for each type. If two modules both use the type, the second module loaded must lookup and use the swig_type_info structure from the module already loaded. Because no dynamic memory is used and the circular dependencies of the casting information, loading the type information is somewhat tricky, and not explained here. A complete description is in the Lib/swiginit.swg file (and near the top of any generated file).

Each module has one swig_module_info structure which looks like this:

/* Structure used to store module information
 * Each module generates one structure like this, and the runtime collects
 * all of these structures and stores them in a circularly linked list.*/
typedef struct swig_module_info {
  swig_type_info **types;         /* Array of pointers to swig_type_info structs in this module */
  int size;                       /* Number of types in this module */
  struct swig_module_info *next;  /* Pointer to next element in circularly linked list */
  swig_type_info **type_initial;  /* Array of initially generated type structures */
  swig_cast_info **cast_initial;  /* Array of initially generated casting structures */
  void *clientdata;               /* Language specific module data */
} swig_module_info;

Each module stores an array of pointers to swig_type_info structures and the number of types in this module. So when a second module is loaded, it finds the swig_module_info structure for the first module and searches the array of types. If any of its own types are in the first module and have already been loaded, it uses those swig_type_info structures rather than creating new ones. These swig_module_info structures are chained together in a circularly linked list.

10.9.2 Usage

This section covers how to use these functions from typemaps. To learn how to call these functions from external files (not the generated _wrap.c file), see the External access to the run-time system section.

When pointers are converted in a typemap, the typemap code often looks similar to this:

%typemap(in) Foo * {
  if ((SWIG_ConvertPtr($input, (void **) &$1, $1_descriptor)) == -1) return NULL;
}

The most critical part is the typemap is the use of the $1_descriptor special variable. When placed in a typemap, this is expanded into the SWIGTYPE_* type descriptor object above. As a general rule, you should always use $1_descriptor instead of trying to hard-code the type descriptor name directly.

There is another reason why you should always use the $1_descriptor variable. When this special variable is expanded, SWIG marks the corresponding type as "in use." When type-tables and type information is emitted in the wrapper file, descriptor information is only generated for those datatypes that were actually used in the interface. This greatly reduces the size of the type tables and improves efficiency.

Occasionally, you might need to write a typemap that needs to convert pointers of other types. To handle this, a special macro substitution $descriptor(type) can be used to generate the SWIG type descriptor name for any C datatype. For example:

%typemap(in) Foo * {
  if ((SWIG_ConvertPtr($input, (void **) &$1, $1_descriptor)) == -1) {
     Bar *temp;
     if ((SWIG_ConvertPtr($input, (void **) &temp, $descriptor(Bar *)) == -1) {
         return NULL;
     }
     $1 = (Foo *) temp;
  }
}

The primary use of $descriptor(type) is when writing typemaps for container objects and other complex data structures. There are some restrictions on the argument---namely it must be a fully defined C datatype. It can not be any of the special typemap variables.

In certain cases, SWIG may not generate type-descriptors like you expect. For example, if you are converting pointers in some non-standard way or working with an unusual combination of interface files and modules, you may find that SWIG omits information for a specific type descriptor. To fix this, you may need to use the %types directive. For example:

%types(int *, short *, long *, float *, double *);

When %types is used, SWIG generates type-descriptor information even if those datatypes never appear elsewhere in the interface file.

Further details about the run-time type checking can be found in the documentation for individual language modules. Reading the source code may also help. The file Lib/swigrun.swg in the SWIG library contains all of the source code for type-checking. This code is also included in every generated wrapped file so you probably just look at the output of SWIG to get a better sense for how types are managed.

10.10 Typemaps and overloading

In many target languages, SWIG fully supports C++ overloaded methods and functions. For example, if you have a collection of functions like this:

int foo(int x);
int foo(double x);
int foo(char *s, int y);

You can access the functions in a normal way from the scripting interpreter:

# Python
foo(3)           # foo(int)
foo(3.5)         # foo(double)
foo("hello",5)   # foo(char *, int)

# Tcl
foo 3            # foo(int)
foo 3.5          # foo(double)
foo hello 5      # foo(char *, int)

To implement overloading, SWIG generates a separate wrapper function for each overloaded method. For example, the above functions would produce something roughly like this:

// wrapper pseudocode
_wrap_foo_0(argc, args[]) {       // foo(int)
   int arg1;
   int result;
   ...
   arg1 = FromInteger(args[0]);
   result = foo(arg1);
   return ToInteger(result);
}

_wrap_foo_1(argc, args[]) {       // foo(double)
   double arg1;
   int result;
   ...
   arg1 = FromDouble(args[0]);
   result = foo(arg1);
   return ToInteger(result);
}

_wrap_foo_2(argc, args[]) {       // foo(char *, int)
   char *arg1;
   int   arg2;
   int result;
   ...
   arg1 = FromString(args[0]);
   arg2 = FromInteger(args[1]);
   result = foo(arg1,arg2);
   return ToInteger(result);
}

Next, a dynamic dispatch function is generated:

_wrap_foo(argc, args[]) {
   if (argc == 1) {
       if (IsInteger(args[0])) {
           return _wrap_foo_0(argc,args);
       } 
       if (IsDouble(args[0])) {
           return _wrap_foo_1(argc,args);
       }
   }
   if (argc == 2) {
       if (IsString(args[0]) && IsInteger(args[1])) {
          return _wrap_foo_2(argc,args);
       }
   }
   error("No matching function!\n");
}

The purpose of the dynamic dispatch function is to select the appropriate C++ function based on argument types---a task that must be performed at runtime in most of SWIG's target languages.

The generation of the dynamic dispatch function is a relatively tricky affair. Not only must input typemaps be taken into account (these typemaps can radically change the types of arguments accepted), but overloaded methods must also be sorted and checked in a very specific order to resolve potential ambiguity. A high-level overview of this ranking process is found in the "SWIG and C++ " chapter. What isn't mentioned in that chapter is the mechanism by which it is implemented---as a collection of typemaps.

To support dynamic dispatch, SWIG first defines a general purpose type hierarchy as follows:

Symbolic Name                   Precedence Value
------------------------------  ------------------
SWIG_TYPECHECK_POINTER           0  
SWIG_TYPECHECK_VOIDPTR           10 
SWIG_TYPECHECK_BOOL              15 
SWIG_TYPECHECK_UINT8             20 
SWIG_TYPECHECK_INT8              25 
SWIG_TYPECHECK_UINT16            30 
SWIG_TYPECHECK_INT16             35 
SWIG_TYPECHECK_UINT32            40 
SWIG_TYPECHECK_INT32             45 
SWIG_TYPECHECK_UINT64            50 
SWIG_TYPECHECK_INT64             55 
SWIG_TYPECHECK_UINT128           60 
SWIG_TYPECHECK_INT128            65 
SWIG_TYPECHECK_INTEGER           70 
SWIG_TYPECHECK_FLOAT             80 
SWIG_TYPECHECK_DOUBLE            90 
SWIG_TYPECHECK_COMPLEX           100 
SWIG_TYPECHECK_UNICHAR           110 
SWIG_TYPECHECK_UNISTRING         120 
SWIG_TYPECHECK_CHAR              130 
SWIG_TYPECHECK_STRING            140 
SWIG_TYPECHECK_BOOL_ARRAY        1015 
SWIG_TYPECHECK_INT8_ARRAY        1025 
SWIG_TYPECHECK_INT16_ARRAY       1035 
SWIG_TYPECHECK_INT32_ARRAY       1045 
SWIG_TYPECHECK_INT64_ARRAY       1055 
SWIG_TYPECHECK_INT128_ARRAY      1065 
SWIG_TYPECHECK_FLOAT_ARRAY       1080 
SWIG_TYPECHECK_DOUBLE_ARRAY      1090 
SWIG_TYPECHECK_CHAR_ARRAY        1130 
SWIG_TYPECHECK_STRING_ARRAY      1140 

(These precedence levels are defined in swig.swg, a library file that's included by all target language modules.)

In this table, the precedence-level determines the order in which types are going to be checked. Low values are always checked before higher values. For example, integers are checked before floats, single values are checked before arrays, and so forth.

Using the above table as a guide, each target language defines a collection of "typecheck" typemaps. The follow excerpt from the Python module illustrates this:

/* Python type checking rules */
/* Note:  %typecheck(X) is a macro for %typemap(typecheck,precedence=X) */

%typecheck(SWIG_TYPECHECK_INTEGER)
	 int, short, long,
 	 unsigned int, unsigned short, unsigned long,
	 signed char, unsigned char,
	 long long, unsigned long long,
	 const int &, const short &, const long &,
 	 const unsigned int &, const unsigned short &, const unsigned long &,
	 const long long &, const unsigned long long &,
	 enum SWIGTYPE,
         bool, const bool & 
{
  $1 = (PyInt_Check($input) || PyLong_Check($input)) ? 1 : 0;
}

%typecheck(SWIG_TYPECHECK_DOUBLE)
	float, double,
	const float &, const double &
{
  $1 = (PyFloat_Check($input) || PyInt_Check($input) || PyLong_Check($input)) ? 1 : 0;
}

%typecheck(SWIG_TYPECHECK_CHAR) char {
  $1 = (PyString_Check($input) && (PyString_Size($input) == 1)) ? 1 : 0;
}

%typecheck(SWIG_TYPECHECK_STRING) char * {
  $1 = PyString_Check($input) ? 1 : 0;
}

%typecheck(SWIG_TYPECHECK_POINTER) SWIGTYPE *, SWIGTYPE &, SWIGTYPE [] {
  void *ptr;
  if (SWIG_ConvertPtr($input, (void **) &ptr, $1_descriptor, 0) == -1) {
    $1 = 0;
    PyErr_Clear();
  } else {
    $1 = 1;
  }
}

%typecheck(SWIG_TYPECHECK_POINTER) SWIGTYPE {
  void *ptr;
  if (SWIG_ConvertPtr($input, (void **) &ptr, $&1_descriptor, 0) == -1) {
    $1 = 0;
    PyErr_Clear();
  } else {
    $1 = 1;
  }
}

%typecheck(SWIG_TYPECHECK_VOIDPTR) void * {
  void *ptr;
  if (SWIG_ConvertPtr($input, (void **) &ptr, 0, 0) == -1) {
    $1 = 0;
    PyErr_Clear();
  } else {
    $1 = 1;
  }
}

%typecheck(SWIG_TYPECHECK_POINTER) PyObject *
{
  $1 = ($input != 0);
}

It might take a bit of contemplation, but this code has merely organized all of the basic C++ types, provided some simple type-checking code, and assigned each type a precedence value.

Finally, to generate the dynamic dispatch function, SWIG uses the following algorithm:

If you haven't written any typemaps of your own, it is unnecessary to worry about the typechecking rules. However, if you have written new input typemaps, you might have to supply a typechecking rule as well. An easy way to do this is to simply copy one of the existing typechecking rules. Here is an example,

// Typemap for a C++ string
%typemap(in) std::string {
    if (PyString_Check($input)) {
         $1 = std::string(PyString_AsString($input));
     } else {
         SWIG_exception(SWIG_TypeError, "string expected");
     }
}
// Copy the typecheck code for "char *".  
%typemap(typecheck) std::string = char *;

The bottom line: If you are writing new typemaps and you are using overloaded methods, you will probably have to write typecheck code or copy existing code. Since this is a relatively new SWIG feature, there are few examples to work with. However, you might look at some of the existing library files likes 'typemaps.i' for a guide.

Notes:

10.11 More about %apply and %clear

In order to implement certain kinds of program behavior, it is sometimes necessary to write sets of typemaps. For example, to support output arguments, one often writes a set of typemaps like this:

%typemap(in,numinputs=0) int *OUTPUT (int temp) {
   $1 = &temp;
}
%typemap(argout) int *OUTPUT {
   // return value somehow
}

To make it easier to apply the typemap to different argument types and names, the %apply directive performs a copy of all typemaps from one type to another. For example, if you specify this,

%apply int *OUTPUT { int *retvalue, int32 *output };

then all of the int *OUTPUT typemaps are copied to int *retvalue and int32 *output.

However, there is a subtle aspect of %apply that needs more description. Namely, %apply does not overwrite a typemap rule if it is already defined for the target datatype. This behavior allows you to do two things:

For example:

%typemap(in) int *INPUT (int temp) {
   temp = ... get value from $input ...;
   $1 = &temp;
}

%typemap(check) int *POSITIVE {
   if (*$1 <= 0) {
      SWIG_exception(SWIG_ValueError,"Expected a positive number!\n");
      return NULL;
   }
}

...
%apply int *INPUT     { int *invalue };
%apply int *POSITIVE  { int *invalue };

Since %apply does not overwrite or replace any existing rules, the only way to reset behavior is to use the %clear directive. %clear removes all typemap rules defined for a specific datatype. For example:

%clear int *invalue;

10.12 Reducing wrapper code size

Since the code supplied to a typemap is inlined directly into wrapper functions, typemaps can result in a tremendous amount of code bloat. For example, consider this typemap for an array:

%typemap(in) float [ANY] {
  int i;
  if (!PySequence_Check($input)) {
    PyErr_SetString(PyExc_ValueError,"Expected a sequence");
    return NULL;
  }
  if (PySequence_Length($input) != $1_dim0) {
    PyErr_SetString(PyExc_ValueError,"Size mismatch. Expected $1_dim0 elements");
    return NULL;
  }
  $1 = (float) malloc($1_dim0*sizeof(float));
  for (i = 0; i < $1_dim0; i++) {
    PyObject *o = PySequence_GetItem($input,i);
    if (PyNumber_Check(o)) {
      $1[i] = (float) PyFloat_AsDouble(o);
    } else {
      PyErr_SetString(PyExc_ValueError,"Sequence elements must be numbers");      
      free(result);
      return NULL;
    }
  }
}

If you had a large interface with hundreds of functions all accepting array parameters, this typemap would be replicated repeatedly--generating a huge amount of code. A better approach might be to consolidate some of the typemap into a function. For example:

%{
/* Define a helper function */
static float *
convert_float_array(PyObject *input, int size) {
  int i;
  float *result;
  if (!PySequence_Check(input)) {
    PyErr_SetString(PyExc_ValueError,"Expected a sequence");
    return NULL;
  }
  if (PySequence_Length(input) != size) {
    PyErr_SetString(PyExc_ValueError,"Size mismatch. ");
    return NULL;
  }
  result = (float) malloc(size*sizeof(float));
  for (i = 0; i < size; i++) {
    PyObject *o = PySequence_GetItem(input,i);
    if (PyNumber_Check(o)) {
      result[i] = (float) PyFloat_AsDouble(o);
    } else {
      PyErr_SetString(PyExc_ValueError,"Sequence elements must be numbers");
      free(result);       
      return NULL;
    }
  }
  return result;
}
%}

%typemap(in) float [ANY] {
    $1 = convert_float_array($input, $1_dim0);
    if (!$1) return NULL;
}
%}

10.13 Passing data between typemaps

It is also important to note that the primary use of local variables is to create stack-allocated objects for temporary use inside a wrapper function (this is faster and less-prone to error than allocating data on the heap). In general, the variables are not intended to pass information between different types of typemaps. However, this can be done if you realize that local names have the argument number appended to them. For example, you could do this:

%typemap(in) int *(int temp) {
   temp = (int) PyInt_AsLong($input);
   $1 = &temp;
}

%typemap(argout) int * {
   PyObject *o = PyInt_FromLong(temp$argnum);
   ...
}

In this case, the $argnum variable is expanded into the argument number. Therefore, the code will reference the appropriate local such as temp1 and temp2. It should be noted that there are plenty of opportunities to break the universe here and that accessing locals in this manner should probably be avoided. At the very least, you should make sure that the typemaps sharing information have exactly the same types and names.

10.14 Where to go for more information?

The best place to find out more information about writing typemaps is to look in the SWIG library. Most language modules define all of their default behavior using typemaps. These are found in files such as python.swg, perl5.swg, tcl8.swg and so forth. The typemaps.i file in the library also contains numerous examples. You should look at these files to get a feel for how to define typemaps of your own. Some of the language modules support additional typemaps and further information is available in the individual chapters for each target language.


11 Customization Features

In many cases, it is desirable to change the default wrapping of particular declarations in an interface. For example, you might want to provide hooks for catching C++ exceptions, add assertions, or provide hints to the underlying code generator. This chapter describes some of these customization techniques. First, a discussion of exception handling is presented. Then, a more general-purpose customization mechanism known as "features" is described.

11.1 Exception handling with %exception

The %exception directive allows you to define a general purpose exception handler. For example, you can specify the following:

%exception {
    try {
        $action
    }
    catch (RangeError) {
        PyErr_SetString(PyExc_IndexError,"index out-of-bounds");
        return NULL;
    }
}

When defined, the code enclosed in braces is inserted directly into the low-level wrapper functions. The special symbol $action gets replaced with the actual operation to be performed (a function call, method invocation, attribute access, etc.). An exception handler remains in effect until it is explicitly deleted. This is done by using either %exception or %noexception with no code. For example:

%exception;   // Deletes any previously defined handler

Compatibility note: Previous versions of SWIG used a special directive %except for exception handling. That directive is deprecated--%exception provides the same functionality, but is substantially more flexible.

11.1.1 Handling exceptions in C code

C has no formal exception handling mechanism so there are several approaches that might be used. A somewhat common technique is to simply set a special error code. For example:

/* File : except.c */

static char error_message[256];
static int error_status = 0;

void throw_exception(char *msg) {
	strncpy(error_message,msg,256);
	error_status = 1;
}

void clear_exception() {
	error_status = 0;
}
char *check_exception() {
	if (error_status) return error_message;
	else return NULL;
}

To use these functions, functions simply call throw_exception() to indicate an error occurred. For example :

double inv(double x) {
	if (x != 0) return 1.0/x;
	else {
		throw_exception("Division by zero");
		return 0;
	}
}

To catch the exception, you can write a simple exception handler such as the following (shown for Perl5) :

%exception {
    char *err;
    clear_exception();
    $action
    if ((err = check_exception())) {
       croak(err);
    }
}

In this case, when an error occurs, it is translated into a Perl error. Each target language has its own approach to creating a runtime error/exception in and for Perl it is the croak method shown above.

11.1.2 Exception handling with longjmp()

Exception handling can also be added to C code using the <setjmp.h> library. Here is a minimalistic implementation that relies on the C preprocessor :

/* File : except.c
   Just the declaration of a few global variables we're going to use */

#include <setjmp.h>
jmp_buf exception_buffer;
int exception_status;

/* File : except.h */
#include <setjmp.h>
extern jmp_buf exception_buffer;
extern int exception_status;

#define try if ((exception_status = setjmp(exception_buffer)) == 0)
#define catch(val) else if (exception_status == val)
#define throw(val) longjmp(exception_buffer,val)
#define finally else

/* Exception codes */

#define RangeError     1
#define DivisionByZero 2
#define OutOfMemory    3

Now, within a C program, you can do the following :

double inv(double x) {
	if (x) return 1.0/x;
	else throw(DivisionByZero);
}

Finally, to create a SWIG exception handler, write the following :

%{
#include "except.h"
%}

%exception {
	try {
		$action
	} catch(RangeError) {
		croak("Range Error");
	} catch(DivisionByZero) {
		croak("Division by zero");
	} catch(OutOfMemory) {
		croak("Out of memory");
	} finally {
		croak("Unknown exception");
	}
}

Note: This implementation is only intended to illustrate the general idea. To make it work better, you'll need to modify it to handle nested try declarations.

11.1.3 Handling C++ exceptions

Handling C++ exceptions is also straightforward. For example:

%exception {
	try {
		$action
	} catch(RangeError) {
		croak("Range Error");
	} catch(DivisionByZero) {
		croak("Division by zero");
	} catch(OutOfMemory) {
		croak("Out of memory");
	} catch(...) {
		croak("Unknown exception");
	}
}

The exception types need to be declared as classes elsewhere, possibly in a header file :

class RangeError {};
class DivisionByZero {};
class OutOfMemory {};

11.1.4 Exception handlers for variables

By default all variables will ignore %exception, so it is effectively turned off for all variables wrappers. This applies to global variables, member variables and static member variables. The approach is certainly a logical one when wrapping variables in C. However, in C++, it is quite possible for an exception to be thrown while the variable is being assigned. To ensure %exception is used when wrapping variables, it needs to be 'turned on' using the %allowexception feature. Note that %allowexception is just a macro for %feature("allowexcept"), that is, it is a feature called "allowexcept". Any variable which has this feature attached to it, will then use the %exception feature, but of course, only if there is a %exception attached to the variable in the first place. The %allowexception feature works like any other feature and so can be used globally or for selective variables.

%allowexception;                // turn on globally
%allowexception Klass::MyVar;   // turn on for a specific variable

%noallowexception Klass::MyVar; // turn off for a specific variable
%noallowexception;              // turn off globally

11.1.5 Defining different exception handlers

By default, the %exception directive creates an exception handler that is used for all wrapper functions that follow it. Unless there is a well-defined (and simple) error handling mechanism in place, defining one universal exception handler may be unwieldy and result in excessive code bloat since the handler is inlined into each wrapper function.

To fix this, you can be more selective about how you use the %exception directive. One approach is to only place it around critical pieces of code. For example:

%exception {
	... your exception handler ...
}
/* Define critical operations that can throw exceptions here */

%exception;

/* Define non-critical operations that don't throw exceptions */

More precise control over exception handling can be obtained by attaching an exception handler to specific declaration name. For example:

%exception allocate {
    try {
        $action
    } 
    catch (MemoryError) {
        croak("Out of memory");
    }
}

In this case, the exception handler is only attached to declarations named "allocate". This would include both global and member functions. The names supplied to %exception follow the same rules as for %rename described in the section on Ambiguity resolution and renaming. For example, if you wanted to define an exception handler for a specific class, you might write this:

%exception Object::allocate {
    try {
        $action
    } 
    catch (MemoryError) {
        croak("Out of memory");
    }
}

When a class prefix is supplied, the exception handler is applied to the corresponding declaration in the specified class as well as for identically named functions appearing in derived classes.

%exception can even be used to pinpoint a precise declaration when overloading is used. For example:

%exception Object::allocate(int) {
    try {
        $action
    } 
    catch (MemoryError) {
        croak("Out of memory");
    }
}

Attaching exceptions to specific declarations is a good way to reduce code bloat. It can also be a useful way to attach exceptions to specific parts of a header file. For example:

%module example
%{
#include "someheader.h"
%}

// Define a few exception handlers for specific declarations
%exception Object::allocate(int) {
    try {
        $action
    } 
    catch (MemoryError) {
        croak("Out of memory");
    }
}

%exception Object::getitem {
    try {
       $action
    }
    catch (RangeError) {
       croak("Index out of range");
    }
}
...
// Read a raw header file
%include "someheader.h"

Compatibility note: The %exception directive replaces the functionality provided by the deprecated "except" typemap. The typemap would allow exceptions to be thrown in the target language based on the return type of a function and was intended to be a mechanism for pinpointing specific declarations. However, it never really worked that well and the new %exception directive is much better.

11.1.6 Using The SWIG exception library

The exception.i library file provides support for creating language independent exceptions in your interfaces. To use it, simply put an "%include exception.i" in your interface file. This creates a function SWIG_exception() that can be used to raise common scripting language exceptions in a portable manner. For example :

// Language independent exception handler
%include exception.i       

%exception {
    try {
        $action
    } catch(RangeError) {
        SWIG_exception(SWIG_ValueError, "Range Error");
    } catch(DivisionByZero) {
        SWIG_exception(SWIG_DivisionByZero, "Division by zero");
    } catch(OutOfMemory) {
        SWIG_exception(SWIG_MemoryError, "Out of memory");
    } catch(...) {
        SWIG_exception(SWIG_RuntimeError,"Unknown exception");
    }
}

As arguments, SWIG_exception() takes an error type code (an integer) and an error message string. The currently supported error types are :

SWIG_UnknownError
SWIG_IOError
SWIG_RuntimeError
SWIG_IndexError
SWIG_TypeError
SWIG_DivisionByZero
SWIG_OverflowError
SWIG_SyntaxError
SWIG_ValueError
SWIG_SystemError
SWIG_AttributeError
SWIG_MemoryError
SWIG_NullReferenceError

Since the SWIG_exception() function is defined at the C-level it can be used elsewhere in SWIG. This includes typemaps and helper functions.

11.2 Object ownership and %newobject

A common problem in some applications is managing proper ownership of objects. For example, consider a function like this:

Foo *blah() {
   Foo *f = new Foo();
   return f;
}

If you wrap the function blah(), SWIG has no idea that the return value is a newly allocated object. As a result, the resulting extension module may produce a memory leak (SWIG is conservative and will never delete objects unless it knows for certain that the returned object was newly created).

To fix this, you can provide an extra hint to the code generator using the %newobject directive. For example:

%newobject blah;
Foo *blah();

%newobject works exactly like %rename and %exception. In other words, you can attach it to class members and parameterized declarations as before. For example:

%newobject ::blah();                   // Only applies to global blah
%newobject Object::blah(int,double);   // Only blah(int,double) in Object
%newobject *::copy;                    // Copy method in all classes
...

When %newobject is supplied, many language modules will arrange to take ownership of the return value. This allows the value to be automatically garbage-collected when it is no longer in use. However, this depends entirely on the target language (a language module may also choose to ignore the %newobject directive).

Closely related to %newobject is a special typemap. The "newfree" typemap can be used to deallocate a newly allocated return value. It is only available on methods for which %newobject has been applied and is commonly used to clean-up string results. For example:

%typemap(newfree) char * "free($1);";
...
%newobject strdup;
...
char *strdup(const char *s);

In this case, the result of the function is a string in the target language. Since this string is a copy of the original result, the data returned by strdup() is no longer needed. The "newfree" typemap in the example simply releases this memory.

As a complement to the %newobject, from SWIG 1.3.28, you can use the %delobject directive. For example, if you have two methods, one to create objects and one to destroy them, you can use:

%newobject create_foo;
%delobject destroy_foo;
...
Foo *create_foo();
void destroy_foo(Foo *foo);

or in a member method as:

%delobject Foo::destroy;

class Foo {
public:
  void destroy() { delete this;}

private:
  ~Foo();
};

%delobject instructs SWIG that the first argument passed to the method will be destroyed, and therefore, the target language should not attempt to deallocate it twice. This is similar to use the DISOWN typemap in the first method argument, and in fact, it also depends on the target language on implementing the 'disown' mechanism properly.

Compatibility note: Previous versions of SWIG had a special %new directive. However, unlike %newobject, it only applied to the next declaration. For example:

%new char *strdup(const char *s);

For now this is still supported but is deprecated.

How to shoot yourself in the foot: The %newobject directive is not a declaration modifier like the old %new directive. Don't write code like this:

%newobject
char *strdup(const char *s);

The results might not be what you expect.

11.3 Features and the %feature directive

Both %exception and %newobject are examples of a more general purpose customization mechanism known as "features." A feature is simply a user-definable property that is attached to specific declarations. Features are attached using the %feature directive. For example:

%feature("except") Object::allocate {
    try {
        $action
    } 
    catch (MemoryError) {
        croak("Out of memory");
    }
}

%feature("new","1") *::copy;

In fact, the %exception and %newobject directives are really nothing more than macros involving %feature:

#define %exception %feature("except")
#define %newobject %feature("new","1")

The name matching rules outlined in the Ambiguity resolution and renaming section applies to all %feature directives. In fact the the %rename directive is just a special form of %feature. The matching rules mean that features are very flexible and can be applied with pinpoint accuracy to specific declarations if needed. Additionally, if no declaration name is given, a global feature is said to be defined. This feature is then attached to every declaration that follows. This is how global exception handlers are defined. For example:

/* Define a global exception handler */
%feature("except") {
   try {
     $action
   }
   ...
}

... bunch of declarations ...

The %feature directive can be used with different syntax. The following are all equivalent:

%feature("except") Object::method { $action };
%feature("except") Object::method %{ $action %};
%feature("except") Object::method " $action ";
%feature("except","$action") Object::method;

The syntax in the first variation will generate the { } delimiters used whereas the other variations will not.

11.3.1 Feature attributes

The %feature directive also accepts XML style attributes in the same way that typemaps do. Any number of attributes can be specified. The following is the generic syntax for features:

%feature("name","value", attribute1="AttributeValue1") symbol;
%feature("name", attribute1="AttributeValue1") symbol {value};
%feature("name", attribute1="AttributeValue1") symbol %{value%};
%feature("name", attribute1="AttributeValue1") symbol "value";

More than one attribute can be specified using a comma separated list. The Java module is an example that uses attributes in %feature("except"). The throws attribute specifies the name of a Java class to add to a proxy method's throws clause. In the following example, MyExceptionClass is the name of the Java class for adding to the throws clause.

%feature("except", throws="MyExceptionClass") Object::method { 
   try {
     $action
   } catch (...) {
     ... code to throw a MyExceptionClass Java exception ...
   }
};

Further details can be obtained from the Java exception handling section.

11.3.2 Feature flags

Feature flags are used to enable or disable a particular feature. Feature flags are a common but simple usage of %feature and the feature value should be either 1 to enable or 0 to disable the feature.

%feature("featurename")          // enables feature
%feature("featurename", "1")     // enables feature
%feature("featurename", "x")     // enables feature
%feature("featurename", "0")     // disables feature
%feature("featurename", "")      // clears feature

Actually any value other than zero will enable the feature. Note that if the value is omitted completely, the default value becomes 1, thereby enabling the feature. A feature is cleared by specifying no value, see Clearing features. The %immutable directive described in the Creating read-only variables section, is just a macro for %feature("immutable"), and can be used to demonstrates feature flags:

                                // features are disabled by default
int red;                        // mutable

%feature("immutable");          // global enable
int orange;                     // immutable

%feature("immutable","0");      // global disable
int yellow;                     // mutable

%feature("immutable","1");      // another form of global enable
int green;                      // immutable

%feature("immutable","");       // clears the global feature
int blue;                       // mutable

Note that features are disabled by default and must be explicitly enabled either globally or by specifying a targeted declaration. The above intersperses SWIG directives with C code. Of course you can target features explicitly, so the above could also be rewritten as:

%feature("immutable","1") orange;
%feature("immutable","1") green;
int red;                        // mutable
int orange;                     // immutable
int yellow;                     // mutable
int green;                      // immutable
int blue;                       // mutable

The above approach allows for the C declarations to be separated from the SWIG directives for when the C declarations are parsed from a C header file. The logic above can of course be inverted and rewritten as:

%feature("immutable","1");
%feature("immutable","0") red;
%feature("immutable","0") yellow;
%feature("immutable","0") blue;
int red;                        // mutable
int orange;                     // immutable
int yellow;                     // mutable
int green;                      // immutable
int blue;                       // mutable

As hinted above for %immutable, most feature flags can also be specified via alternative syntax. The alternative syntax is just a macro in the swig.swg Library file. The following shows the alternative syntax for the imaginary featurename feature:

%featurename       // equivalent to %feature("featurename", "1") ie enables feature
%nofeaturename     // equivalent to %feature("featurename", "0") ie disables feature
%clearfeaturename  // equivalent to %feature("featurename", "")  ie clears feature

The concept of clearing features is discussed next.

11.3.3 Clearing features

A feature stays in effect until it is explicitly cleared. A feature is cleared by supplying a %feature directive with no value. For example %feature("name",""). A cleared feature means that any feature exactly matching any previously defined feature is no longer used in the name matching rules. So if a feature is cleared, it might mean that another name matching rule will apply. To clarify, let's consider the except feature again (%exception):

// Define global exception handler
%feature("except") {
    try {
        $action
    } catch (...) {
        croak("Unknown C++ exception");
    }
}

// Define exception handler for all clone methods to log the method calls
%feature("except") *::clone() {
    try {
        logger.info("$action");
        $action
    } catch (...) {
        croak("Unknown C++ exception");
    }
}

... initial set of class declarations with clone methods ...

// clear the previously defined feature
%feature("except","") *::clone();

... final set of class declarations with clone methods ...

In the above scenario, the initial set of clone methods will log all method invocations from the target language. This specific feature is cleared for the final set of clone methods. However, these clone methods will still have an exception handler (without logging) as the next best feature match for them is the global exception handler.

Note that clearing a feature is not always the same as disabling it. Clearing the feature above with %feature("except","") *::clone() is not the same as specifying %feature("except","0") *::clone() . The former will disable the feature for clone methods - the feature is still a better match than the global feature. If on the other hand, no global exception handler had been defined at all, then clearing the feature would be the same as disabling it as no other feature would have matched.

Note that the feature must match exactly for it to be cleared by any previously defined feature. For example the following attempt to clear the initial feature will not work:

%feature("except") clone() { logger.info("$action"); $action }
%feature("except","") *::clone();

but this will:

%feature("except") clone() { logger.info("$action"); $action }
%feature("except","") clone();

11.3.4 Features and default arguments

SWIG treats methods with default arguments as separate overloaded methods as detailed in the default arguments section. Any %feature targeting a method with default arguments will apply to all the extra overloaded methods that SWIG generates if the default arguments are specified in the feature. If the default arguments are not specified in the feature, then the feature will match that exact wrapper method only and not the extra overloaded methods that SWIG generates. For example:

%feature("except") void hello(int i=0, double d=0.0) { ... }
void hello(int i=0, double d=0.0);

will apply the feature to all three wrapper methods, that is:

void hello(int i, double d);
void hello(int i);
void hello();

If the default arguments are not specified in the feature:

%feature("except") void hello(int i, double d) { ... }
void hello(int i=0, double d=0.0);

then the feature will only apply to this wrapper method:

void hello(int i, double d);

and not these wrapper methods:

void hello(int i);
void hello();

If compactdefaultargs are being used, then the difference between specifying or not specifying default arguments in a feature is not applicable as just one wrapper is generated.

Compatibility note: The different behaviour of features specified with or without default arguments was introduced in SWIG-1.3.23 when the approach to wrapping methods with default arguments was changed.

11.3.5 Feature example

As has been shown earlier, the intended use for the %feature directive is as a highly flexible customization mechanism that can be used to annotate declarations with additional information for use by specific target language modules. Another example is in the Python module. You might use %feature to rewrite proxy/shadow class code as follows:

%module example
%rename(bar_id) bar(int,double);

// Rewrite bar() to allow some nice overloading

%feature("shadow") Foo::bar(int) %{
def bar(*args):
    if len(args) == 3:
         return apply(examplec.Foo_bar_id,args)
    return apply(examplec.Foo_bar,args)
%}
    
class Foo {
public:
    int bar(int x);
    int bar(int x, double y);
}

Further details of %feature usage is described in the documentation for specific language modules.


12 Contracts

A common problem that arises when wrapping C libraries is that of maintaining reliability and checking for errors. The fact of the matter is that many C programs are notorious for not providing error checks. Not only that, when you expose the internals of an application as a library, it often becomes possible to crash it simply by providing bad inputs or using it in a way that wasn't intended.

This chapter describes SWIG's support for software contracts. In the context of SWIG, a contract can be viewed as a runtime constraint that is attached to a declaration. For example, you can easily attach argument checking rules, check the output values of a function and more. When one of the rules is violated by a script, a runtime exception is generated rather than having the program continue to execute.

12.1 The %contract directive

Contracts are added to a declaration using the %contract directive. Here is a simple example:

%contract sqrt(double x) {
require:
    x >= 0;
ensure:
    sqrt >= 0;
}

...
double sqrt(double);

In this case, a contract is being added to the sqrt() function. The %contract directive must always appear before the declaration in question. Within the contract there are two sections, both of which are optional. The require: section specifies conditions that must hold before the function is called. Typically, this is used to check argument values. The ensure: section specifies conditions that must hold after the function is called. This is often used to check return values or the state of the program. In both cases, the conditions that must hold must be specified as boolean expressions.

In the above example, we're simply making sure that sqrt() returns a non-negative number (if it didn't, then it would be broken in some way).

Once a contract has been specified, it modifies the behavior of the resulting module. For example:

>>> example.sqrt(2)
1.4142135623730951
>>> example.sqrt(-2)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
RuntimeError: Contract violation: require: (arg1>=0)
>>>

12.2 %contract and classes

The %contract directive can also be applied to class methods and constructors. For example:

%contract Foo::bar(int x, int y) {
require:
   x > 0;
ensure:
   bar > 0;
}

%contract Foo::Foo(int a) {
require:
   a > 0;
}

class Foo {
public:
    Foo(int);
    int bar(int, int);
};

The way in which %contract is applied is exactly the same as the %feature directive. Thus, any contract that you specified for a base class will also be attached to inherited methods. For example:

class Spam : public Foo {
public:
   int bar(int,int);    // Gets contract defined for Foo::bar(int,int)
};

In addition to this, separate contracts can be applied to both the base class and a derived class. For example:

%contract Foo::bar(int x, int) {
require:
    x > 0;
}

%contract Spam::bar(int, int y) {
require:
    y > 0;
}

class Foo {
public:
    int bar(int,int);   // Gets Foo::bar contract.
};

class Spam : public Foo {
public:
     int bar(int,int);   // Gets Foo::bar and Spam::bar contract
};

When more than one contract is applied, the conditions specified in a "require:" section are combined together using a logical-AND operation. In other words conditions specified for the base class and conditions specified for the derived class all must hold. In the above example, this means that both the arguments to Spam::bar must be positive.

12.3 Constant aggregation and %aggregate_check

Consider an interface file that contains the following code:

#define  UP     1
#define  DOWN   2
#define  RIGHT  3
#define  LEFT   4

void move(SomeObject *, int direction, int distance);

One thing you might want to do is impose a constraint on the direction parameter to make sure it's one of a few accepted values. To do that, SWIG provides an easy to use macro %aggregate_check() that works like this:

%aggregate_check(int, check_direction, UP, DOWN, LEFT, RIGHT);

This merely defines a utility function of the form

int check_direction(int x);

That checks the argument x to see if it is one of the values listed. This utility function can be used in contracts. For example:

%aggregate_check(int, check_direction, UP, DOWN, RIGHT, LEFT);

%contract move(SomeObject *, int direction, in) {
require:
     check_direction(direction);
}

#define  UP     1
#define  DOWN   2
#define  RIGHT  3
#define  LEFT   4

void move(SomeObject *, int direction, int distance);

Alternatively, it can be used in typemaps and other directives. For example:

%aggregate_check(int, check_direction, UP, DOWN, RIGHT, LEFT);

%typemap(check) int direction {
    if (!check_direction($1)) SWIG_exception(SWIG_ValueError, "Bad direction");
}

#define  UP     1
#define  DOWN   2
#define  RIGHT  3
#define  LEFT   4

void move(SomeObject *, int direction, int distance);

Regrettably, there is no automatic way to perform similar checks with enums values. Maybe in a future release.

12.4 Notes

Contract support was implemented by Songyan (Tiger) Feng and first appeared in SWIG-1.3.20.


13 Variable Length Arguments

(a.k.a, "The horror. The horror.")

This chapter describes the problem of wrapping functions that take a variable number of arguments. For instance, generating wrappers for the C printf() family of functions.

This topic is sufficiently advanced to merit its own chapter. In fact, support for varargs is an often requested feature that was first added in SWIG-1.3.12. Most other wrapper generation tools have wisely chosen to avoid this issue.

13.1 Introduction

Some C and C++ programs may include functions that accept a variable number of arguments. For example, most programmers are familiar with functions from the C library such as the following:

int printf(const char *fmt, ...)
int fprintf(FILE *, const char *fmt, ...);
int sprintf(char *s, const char *fmt, ...);

Although there is probably little practical purpose in wrapping these specific C library functions in a scripting language (what would be the point?), a library may include its own set of special functions based on a similar API. For example:

int  traceprintf(const char *fmt, ...);

In this case, you may want to have some kind of access from the target language.

Before describing the SWIG implementation, it is important to discuss the common uses of varargs that you are likely to encounter in real programs. Obviously, there are the printf() style output functions as shown. Closely related to this would be scanf() style input functions that accept a format string and a list of pointers into which return values are placed. However, variable length arguments are also sometimes used to write functions that accept a NULL-terminated list of pointers. A good example of this would be a function like this:

int execlp(const char *path, const char *arg1, ...);
...

/* Example */
execlp("ls","ls","-l",NULL);

In addition, varargs is sometimes used to fake default arguments in older C libraries. For instance, the low level open() system call is often declared as a varargs function so that it will accept two or three arguments:

int open(const char *path, int oflag, ...);
...

/* Examples */
f = open("foo", O_RDONLY);
g = open("bar", O_WRONLY | O_CREAT, 0644);

Finally, to implement a varargs function, recall that you have to use the C library functions defined in <stdarg.h>. For example:

List make_list(const char *s, ...) {
    va_list ap;
    List    x;
    ...
    va_start(ap, s);
    while (s) {
       x.append(s);
       s = va_arg(ap, const char *);
    }
    va_end(ap);
    return x;
}

13.2 The Problem

Generating wrappers for a variable length argument function presents a number of special challenges. Although C provides support for implementing functions that receive variable length arguments, there are no functions that can go in the other direction. Specifically, you can't write a function that dynamically creates a list of arguments and which invokes a varargs function on your behalf.

Although it is possible to write functions that accept the special type va_list, this is something entirely different. You can't take a va_list structure and pass it in place of the variable length arguments to another varargs function. It just doesn't work.

The reason this doesn't work has to do with the way that function calls get compiled. For example, suppose that your program has a function call like this:

printf("Hello %s. Your number is %d\n", name, num);

When the compiler looks at this, it knows that you are calling printf() with exactly three arguments. Furthermore, it knows that the number of arguments as well are their types and sizes is never going to change during program execution. Therefore, this gets turned to machine code that sets up a three-argument stack frame followed by a call to printf().

In contrast, suppose you attempted to make some kind of wrapper around printf() using code like this:

int wrap_printf(const char *fmt, ...) {
   va_list ap;
   va_start(ap,fmt);
   ...
   printf(fmt,ap);
   ...
   va_end(ap);
};

Although this code might compile, it won't do what you expect. This is because the call to printf() is compiled as a procedure call involving only two arguments. However, clearly a two-argument configuration of the call stack is completely wrong if your intent is to pass an arbitrary number of arguments to the real printf(). Needless to say, it won't work.

Unfortunately, the situation just described is exactly the problem faced by wrapper generation tools. In general, the number of passed arguments will not be known until run-time. To make matters even worse, you won't know the types and sizes of arguments until run-time as well. Needless to say, there is no obvious way to make the C compiler generate code for a function call involving an unknown number of arguments of unknown types.

In theory, it is possible to write a wrapper that does the right thing. However, this involves knowing the underlying ABI for the target platform and language as well as writing special purpose code that manually constructed the call stack before making a procedure call. Unfortunately, both of these tasks require the use of inline assembly code. Clearly, that's the kind of solution you would much rather avoid.

With this nastiness in mind, SWIG provides a number of solutions to the varargs wrapping problem. Most of these solutions are compromises that provide limited varargs support without having to resort to assembly language. However, SWIG can also support real varargs wrapping (with stack-frame manipulation) if you are willing to get hands dirty. Keep reading.

13.3 Default varargs support

When variable length arguments appear in an interface, the default behavior is to drop the variable argument list entirely, replacing them with a single NULL pointer. For example, if you had this function,

void traceprintf(const char *fmt, ...);

it would be wrapped as if it had been declared as follows:

void traceprintf(const char *fmt);

When the function is called inside the wrappers, it is called as follows:

traceprintf(arg1, NULL);

Arguably, this approach seems to defeat the whole point of variable length arguments. However, this actually provides enough support for many simple kinds of varargs functions to still be useful. For instance, you could make function calls like this (in Python):

>>> traceprintf("Hello World")
>>> traceprintf("Hello %s. Your number is %d\n" % (name, num))

Notice how string formatting is being done in Python instead of C.

13.4 Argument replacement using %varargs

Instead of dropping the variable length arguments, an alternative approach is to replace (...) with a set of suitable arguments. SWIG provides a special %varargs directive that can be used to do this. For example,

%varargs(int mode = 0) open;
...
int open(const char *path, int oflags, ...);

is equivalent to this:

int open(const char *path, int oflags, int mode = 0);

In this case, %varargs is simply providing more specific information about the extra arguments that might be passed to a function. If the parameters to a varargs function are of uniform type, %varargs can also accept a numerical argument count as follows:

%varargs(10,char *arg = NULL) execlp;
...
int execlp(const char *path, const char *arg1, ...);

This would wrap execlp() as a function that accepted up to 10 optional arguments. Depending on the application, this may be more than enough for practical purposes.

Argument replacement is most appropriate in cases where the types of the extra arguments is uniform and the maximum number of arguments is known. When replicated argument replacement is used, at least one extra argument is added to the end of the arguments when making the function call. This argument serves as a sentinel to make sure the list is properly terminated. It has the same value as that supplied to the %varargs directive.

Argument replacement is not as useful when working with functions that accept mixed argument types such as printf(). Providing general purpose wrappers to such functions presents special problems (covered shortly).

13.5 Varargs and typemaps

Variable length arguments may be used in typemap specifications. For example:

%typemap(in) (...) {
    // Get variable length arguments (somehow)
    ...
}

%typemap(in) (const char *fmt, ...) {
    // Multi-argument typemap
}

However, this immediately raises the question of what "type" is actually used to represent (...). For lack of a better alternative, the type of (...) is set to void *. Since there is no way to dynamically pass arguments to a varargs function (as previously described), the void * argument value is intended to serve as a place holder for storing some kind of information about the extra arguments (if any). In addition, the default behavior of SWIG is to pass the void * value as an argument to the function. Therefore, you could use the pointer to hold a valid argument value if you wanted.

To illustrate, here is a safer version of wrapping printf() in Python:

%typemap(in) (const char *fmt, ...) {
    $1 = "%s";                                /* Fix format string to %s */
    $2 = (void *) PyString_AsString($input);  /* Get string argument */
};
...
int printf(const char *fmt, ...);

In this example, the format string is implicitly set to "%s" . This prevents a program from passing a bogus format string to the extension. Then, the passed input object is decoded and placed in the void * argument defined for the (...) argument. When the actual function call is made, the underlying wrapper code will look roughly like this:

wrap_printf() {
   char *arg1;
   void *arg2;
   int   result;

   arg1 = "%s";
   arg2 = (void *) PyString_AsString(arg2obj);
   ...
   result = printf(arg1,arg2);
   ...
}

Notice how both arguments are passed to the function and it does what you would expect.

The next example illustrates a more advanced kind of varargs typemap. Disclaimer: this requires special support in the target language module and is not guaranteed to work with all SWIG modules at this time. It also starts to illustrate some of the more fundamental problems with supporting varargs in more generality.

If a typemap is defined for any form of (...), many SWIG modules will generate wrappers that accept a variable number of arguments as input and will make these arguments available in some form. The precise details of this depends on the language module being used (consult the appropriate chapter for more details). However, suppose that you wanted to create a Python wrapper for the execlp() function shown earlier. To do this using a typemap instead of using %varargs, you might first write a typemap like this:

%typemap(in) (...)(char *args[10]) {
    int i;
    int argc;
    for (i = 0; i < 10; i++) args[i] = 0;
    argc = PyTuple_Size(varargs);
    if (argc > 10) {
       PyErr_SetString(PyExc_ValueError,"Too many arguments");
       return NULL;
    }
    for (i = 0; i < argc; i++) {
       PyObject *o = PyTuple_GetItem(varargs,i);
       if (!PyString_Check(o)) {
           PyErr_SetString(PyExc_ValueError,"Expected a string");
           return NULL;
       }
       args[i] = PyString_AsString(o);
    }
    $1 = (void *) args;
}

In this typemap, the special variable varargs is a tuple holding all of the extra arguments passed (this is specific to the Python module). The typemap then pulls this apart and sticks the values into the array of strings args. Then, the array is assigned to $1 (recall that this is the void * variable corresponding to (...)). However, this assignment is only half of the picture----clearly this alone is not enough to make the function work. To patch everything up, you have to rewrite the underlying action code using the %feature directive like this:

%feature("action") execlp {
   char *args = (char **) arg3;
   result = execlp(arg1, arg2, args[0], args[1], args[2], args[3], args[4],
                   args[5],args[6],args[7],args[8],args[9], NULL);
}

int execlp(const char *path, const char *arg, ...);

This patches everything up and creates a function that more or less works. However, don't try explaining this to your coworkers unless you know for certain that they've had several cups of coffee. If you really want to elevate your guru status and increase your job security, continue to the next section.

13.6 Varargs wrapping with libffi

All of the previous examples have relied on features of SWIG that are portable and which don't rely upon any low-level machine-level details. In many ways, they have all dodged the real issue of variable length arguments by recasting a varargs function into some weaker variation with a fixed number of arguments of known types. In many cases, this works perfectly fine. However, if you want more generality than this, you need to bring out some bigger guns.

One way to do this is to use a special purpose library such as libffi ( http://sources.redhat.com/libffi). libffi is a library that allows you to dynamically construct call-stacks and invoke procedures in a relatively platform independent manner. Details about the library can be found in the libffi distribution and are not repeated here.

To illustrate the use of libffi, suppose that you really wanted to create a wrapper for execlp() that accepted any number of arguments. To do this, you might make a few adjustments to the previous example. For example:

/* Take an arbitrary number of extra arguments and place into an array
   of strings */

%typemap(in) (...) {
   char **argv;
   int    argc;
   int    i;

   argc = PyTuple_Size(varargs);
   argv = (char **) malloc(sizeof(char *)*(argc+1));
   for (i = 0; i < argc; i++) {
      PyObject *o = PyTuple_GetItem(varargs,i);
      if (!PyString_Check(o)) {
          PyErr_SetString(PyExc_ValueError,"Expected a string");
	  free(argv);
          return NULL;
      }
      argv[i] = PyString_AsString(o);
   }
   argv[i] = NULL;
   $1 = (void *) argv;
}

/* Rewrite the function call, using libffi */    

%feature("action") execlp {
  int       i, vc;
  ffi_cif   cif;
  ffi_type  **types;
  void      **values;
  char      **args;

  vc = PyTuple_Size(varargs);
  types  = (ffi_type **) malloc((vc+3)*sizeof(ffi_type *));
  values = (void **) malloc((vc+3)*sizeof(void *));
  args   = (char **) arg3;

  /* Set up path parameter */
  types[0] = &ffi_type_pointer;
  values[0] = &arg1;
  
  /* Set up first argument */
  types[1] = &ffi_type_pointer;
  values[1] = &arg2;

  /* Set up rest of parameters */
  for (i = 0; i <= vc; i++) {
    types[2+i] = &ffi_type_pointer;
    values[2+i] = &args[i];
  }
  if (ffi_prep_cif(&cif, FFI_DEFAULT_ABI, vc+3,
                   &ffi_type_uint, types) == FFI_OK) {
    ffi_call(&cif, (void (*)()) execlp, &result, values);
  } else {
    PyErr_SetString(PyExc_RuntimeError, "Whoa!!!!!");
    free(types);
    free(values);
    free(arg3);
    return NULL;
  }
  free(types);
  free(values);
  free(arg3);
}

/* Declare the function. Whew! */
int execlp(const char *path, const char *arg1, ...);

Looking at this example, you may start to wonder if SWIG is making life any easier. Given the amount of code involved, you might also wonder why you didn't just write a hand-crafted wrapper! Either that or you're wondering "why in the hell am I trying to wrap this varargs function in the first place?!?" Obviously, those are questions you'll have to answer for yourself.

As a more extreme example of libffi, here is some code that attempts to wrap printf(),

/* A wrapper for printf() using libffi */

%{
/* Structure for holding passed arguments after conversion */
  typedef struct {
    int type;
    union {
      int    ivalue;
      double dvalue;
      void   *pvalue;
    } val;
  } vtype;
  enum { VT_INT, VT_DOUBLE, VT_POINTER };
%}

%typemap(in) (const char *fmt, ...) {
  vtype *argv;
  int    argc;
  int    i;

  /* Format string */
  $1 = PyString_AsString($input);

  /* Variable length arguments */
  argc = PyTuple_Size(varargs);
  argv = (vtype *) malloc(argc*sizeof(vtype));
  for (i = 0; i < argc; i++) {
    PyObject *o = PyTuple_GetItem(varargs,i);
    if (PyInt_Check(o)) {
      argv[i].type = VT_INT;
      argv[i].val.ivalue = PyInt_AsLong(o);
    } else if (PyFloat_Check(o)) {
      argv[i].type = VT_DOUBLE;
      argv[i].val.dvalue = PyFloat_AsDouble(o);
    } else if (PyString_Check(o)) {
      argv[i].type = VT_POINTER;
      argv[i].val.pvalue = (void *) PyString_AsString(o);
    } else {
      PyErr_SetString(PyExc_ValueError,"Unsupported argument type");
      free(argv);
      return NULL;
    }
  }
  $2 = (void *) argv;
}

/* Rewrite the function call using libffi */    
%feature("action") printf {
  int       i, vc;
  ffi_cif   cif;
  ffi_type  **types;
  void      **values;
  vtype     *args;

  vc = PyTuple_Size(varargs);
  types  = (ffi_type **) malloc((vc+1)*sizeof(ffi_type *));
  values = (void **) malloc((vc+1)*sizeof(void *));
  args   = (vtype *) arg2;

  /* Set up fmt parameter */
  types[0] = &ffi_type_pointer;
  values[0] = &arg1;

  /* Set up rest of parameters */
  for (i = 0; i < vc; i++) {
    switch(args[i].type) {
    case VT_INT:
      types[1+i] = &ffi_type_uint;
      values[1+i] = &args[i].val.ivalue;
      break;
    case VT_DOUBLE:
      types[1+i] = &ffi_type_double;
      values[1+i] = &args[i].val.dvalue;
      break;
    case VT_POINTER:
      types[1+i] = &ffi_type_pointer;
      values[1+i] = &args[i].val.pvalue;
      break;
    default:
      abort();    /* Whoa! We're seriously hosed */
      break;   
    }
  }
  if (ffi_prep_cif(&cif, FFI_DEFAULT_ABI, vc+1,
                   &ffi_type_uint, types) == FFI_OK) {
    ffi_call(&cif, (void (*)()) printf, &result, values);
  } else {
    PyErr_SetString(PyExc_RuntimeError, "Whoa!!!!!");
    free(types);
    free(values);
    free(args);
    return NULL;
  }
  free(types);
  free(values);
  free(args);
}

/* The function */
int printf(const char *fmt, ...);

Much to your amazement, it even seems to work if you try it:

>>> import example
>>> example.printf("Grade: %s   %d/60 = %0.2f%%\n", "Dave", 47, 47.0*100/60)
Grade: Dave   47/60 = 78.33%
>>>

Of course, there are still some limitations to consider:

>>> example.printf("la de da de da %s", 42)
Segmentation fault (core dumped)

And, on this note, we leave further exploration of libffi to the reader as an exercise. Although Python has been used as an example, most of the techniques in this section can be extrapolated to other language modules with a bit of work. The only details you need to know is how the extra arguments are accessed in each target language. For example, in the Python module, we used the special varargs variable to get these arguments. Modules such as Tcl8 and Perl5 simply provide an argument number for the first extra argument. This can be used to index into an array of passed arguments to get values. Please consult the chapter on each language module for more details.

13.7 Wrapping of va_list

Closely related to variable length argument wrapping, you may encounter functions that accept a parameter of type va_list. For example:

int vfprintf(FILE *f, const char *fmt, va_list ap);

As far as we know, there is no obvious way to wrap these functions with SWIG. This is because there is no documented way to assemble the proper va_list structure (there are no C library functions to do it and the contents of va_list are opaque). Not only that, the contents of a va_list structure are closely tied to the underlying call-stack. It's not clear that exporting a va_list would have any use or that it would work at all.

13.8 C++ Issues

Wrapping of C++ member functions that accept a variable number of arguments presents a number of challenges. By far, the easiest way to handle this is to use the %varargs directive. This is portable and it fully supports classes much like the %rename directive. For example:

%varargs (10, char * = NULL) Foo::bar;

class Foo {
public:
     virtual void bar(char *arg, ...);   // gets varargs above
};

class Spam: public Foo {
public:
     virtual void bar(char *arg, ...);   // gets varargs above
};

%varargs also works with constructors, operators, and any other C++ programming construct that accepts variable arguments.

Doing anything more advanced than this is likely to involve a serious world of pain. In order to use a library like libffi, you will need to know the underlying calling conventions and details of the C++ ABI. For instance, the details of how this is passed to member functions as well as any hidden arguments that might be used to pass additional information. These details are implementation specific and may differ between compilers and even different versions of the same compiler. Also, be aware that invoking a member function is further complicated if it is a virtual method. In this case, invocation might require a table lookup to obtain the proper function address (although you might be able to obtain an address by casting a bound pointer to a pointer to function as described in the C++ ARM section 18.3.4).

If you do decide to change the underlying action code, be aware that SWIG always places the this pointer in arg1. Other arguments are placed in arg2, arg3, and so forth. For example:

%feature("action") Foo::bar {
   ...
   result = arg1->bar(arg2, arg3, etc.);
   ...
}

Given the potential to shoot yourself in the foot, it is probably easier to reconsider your design or to provide an alternative interface using a helper function than it is to create a fully general wrapper to a varargs C++ member function.

13.9 Discussion

This chapter has provided a number of techniques that can be used to address the problem of variable length argument wrapping. If you care about portability and ease of use, the %varargs directive is probably the easiest way to tackle the problem. However, using typemaps, it is possible to do some very advanced kinds of wrapping.

One point of discussion concerns the structure of the libffi examples in the previous section. Looking at that code, it is not at all clear that this is the easiest way to solve the problem. However, there are a number of subtle aspects of the solution to consider--mostly concerning the way in which the problem has been decomposed. First, the example is structured in a way that tries to maintain separation between wrapper-specific information and the declaration of the function itself. The idea here is that you might structure your interface like this:

%typemap(const char *fmt, ...) {
   ...
}
%feature("action") traceprintf {
   ...
}

/* Include some header file with traceprintf in it */
%include "someheader.h"

Second, careful scrutiny will reveal that the typemaps involving (...) have nothing whatsoever to do with the libffi library. In fact, they are generic with respect to the way in which the function is actually called. This decoupling means that it will be much easier to consider other library alternatives for making the function call. For instance, if libffi wasn't supported on a certain platform, you might be able to use something else instead. You could use conditional compilation to control this:

#ifdef USE_LIBFFI
%feature("action") printf {
   ...
}
#endif
#ifdef USE_OTHERFFI
%feature("action") printf {
...
}
#endif

Finally, even though you might be inclined to just write a hand-written wrapper for varargs functions, the techniques used in the previous section have the advantage of being compatible with all other features of SWIG such as exception handling.

As a final word, some C programmers seem to have the assumption that the wrapping of variable length argument functions is an easily solved problem. However, this section has hopefully dispelled some of these myths. All things being equal, you are better off avoiding variable length arguments if you can. If you can't avoid them, please consider some of the simple solutions first. If you can't live with a simple solution, proceed with caution. At the very least, make sure you carefully read the section "A7.3.2 Function Calls" in Kernighan and Ritchie and make sure you fully understand the parameter passing conventions used for varargs. Also, be aware of the platform dependencies and reliability issues that this will introduce. Good luck.


14 Warning Messages

14.1 Introduction

During compilation, SWIG may generate a variety of warning messages. For example:

example.i:16: Warning(501): Overloaded declaration ignored.  bar(double)
example.i:15: Warning(501): Previous declaration is bar(int)

Typically, warning messages indicate non-fatal problems with the input where the generated wrapper code will probably compile, but it may not work like you expect.

14.2 Warning message suppression

All warning messages have a numeric code that is shown in the warning message itself. To suppress the printing of a warning message, a number of techniques can be used. First, you can run SWIG with the -w command line option. For example:

% swig -python -w501 example.i
% swig -python -w501,505,401 example.i

Alternatively, warnings can be suppressed by inserting a special preprocessor pragma into the input file:

%module example
#pragma SWIG nowarn=501
#pragma SWIG nowarn=501,505,401

Finally, code-generation warnings can be disabled on a declaration by declaration basis using the %warnfilter directive. For example:

%module example
%warnfilter(501) foo;
...
int foo(int);
int foo(double);              // Silently ignored.

The %warnfilter directive has the same semantics as other declaration modifiers like %rename, %ignore, and %feature. For example, if you wanted to suppress a warning for a method in a class hierarchy, you could do this:

%warnfilter(501) Object::foo;
class Object {
public:
   int foo(int);
   int foo(double);      // Silently ignored
   ...
};

class Derived : public Object {
public:
   int foo(int);
   int foo(double);      // Silently ignored
   ...
};

Warnings can be suppressed for an entire class by supplying a class name. For example:

%warnfilter(501) Object;

class Object {
public:
   ...                      // All 501 warnings ignored in class
};

There is no option to suppress all SWIG warning messages. The warning messages are there for a reason---to tell you that something may be broken in your interface. Ignore the warning messages at your own peril.

14.3 Enabling additional warnings

Some warning messages are disabled by default and are generated only to provide additional diagnostics. All warning messages can be enabled using the -Wall option. For example:

% swig -Wall -python example.i

When -Wall is used, all other warning filters are disabled.

To selectively turn on extra warning messages, you can use the directives and options in the previous section--simply add a "+" to all warning numbers. For example:

% swig -w+309,+452 example.i

or

#pragma SWIG nowarn=+309,+452

or

%warnfilter(+309,+452) foo;

Note: selective enabling of warnings with %warnfilter overrides any global settings you might have made using -w or #pragma.

14.4 Issuing a warning message

Warning messages can be issued from an interface file using a number of directives. The %warn directive is the most simple:

%warn "750:This is your last warning!"

All warning messages are optionally prefixed by the warning number to use. If you are generating your own warnings, make sure you don't use numbers defined in the table at the end of this section.

The %ignorewarn directive is the same as %ignore except that it issues a warning message whenever a matching declaration is found. For example:

%ignorewarn("362:operator= ignored") operator=;

Warning messages can be associated with typemaps using the warning attribute of a typemap declaration. For example:

%typemap(in, warning="751:You are really going to regret this") blah * {
   ...
}

In this case, the warning message will be printed whenever the typemap is actually used.

14.5 Commentary

The ability to suppress warning messages is really only provided for advanced users and is not recommended in normal use. There are no plans to provide symbolic names or options that identify specific types or groups of warning messages---the numbers must be used explicitly.

Certain types of SWIG problems are errors. These usually arise due to parsing errors (bad syntax) or semantic problems for which there is no obvious recovery. There is no mechanism for suppressing error messages.

14.6 Warnings as errors

Warnings can be handled as errors by using the -Werror command line option. This will cause SWIG to exit with a non successful exit code if a warning is encountered.

14.7 Message output format

The output format for both warnings and errors can be selected for integration with your favourite IDE/editor. Editors and IDEs can usually parse error messages and if in the appropriate format will easily take you directly to the source of the error. The standard format is used by default except on Windows where the Microsoft format is used by default. These can be overridden using command line options, for example:

$ swig -python -Fstandard example.i
example.i:4: Syntax error in input.
$ swig -python -Fmicrosoft example.i
example.i(4): Syntax error in input.

14.8 Warning number reference

14.8.1 Deprecated features (100-199)

14.8.2 Preprocessor (200-299)

14.8.3 C/C++ Parser (300-399)

14.8.4 Types and typemaps (400-499)

14.8.5 Code generation (500-599)

14.8.6 Language module specific (800-899)

14.8.7 User defined (900-999)

These numbers can be used by your own application.

14.9 History

The ability to control warning messages was first added to SWIG-1.3.12.


15 Working with Modules

When first working with SWIG, users commonly start by creating a single module. That is, you might define a single SWIG interface that wraps some set of C/C++ code. You then compile all of the generated wrapper code into a module and use it. For large applications, however, this approach is problematic---the size of the generated wrapper code can be rather large. Moreover, it is probably easier to manage the target language interface when it is broken up into smaller pieces.

This chapter describes the problem of using SWIG in programs where you want to create a collection of modules.

15.1 The SWIG runtime code

Many of SWIG's target languages generate a set of functions commonly known as the "SWIG runtime." These functions are primarily related to the runtime type system which checks pointer types and performs other tasks such as proper casting of pointer values in C++. As a general rule, the statically typed target languages, such as Java, use the language's built in static type checking and have no need for a SWIG runtime. All the dynamically typed / interpreted languages rely on the SWIG runtime.

The runtime functions are private to each SWIG-generated module. That is, the runtime functions are declared with "static" linkage and are visible only to the wrapper functions defined in that module. The only problem with this approach is that when more than one SWIG module is used in the same application, those modules often need to share type information. This is especially true for C++ programs where SWIG must collect and share information about inheritance relationships that cross module boundaries.

To solve the problem of sharing information across modules, a pointer to the type information is stored in a global variable in the target language namespace. During module initialization, type information is loaded into the global data structure of type information from all modules.

This can present a problem with threads. If two modules try and load at the same time, the type information can become corrupt. SWIG currently does not provide any locking, and if you use threads, you must make sure that modules are loaded serially. Be careful if you use threads and the automatic module loading that some scripting languages provide. One solution is to load all modules before spawning any threads.

15.2 External access to the runtime

As described in The run-time type checker, the functions SWIG_TypeQuery, SWIG_NewPointerObj, and others sometimes need to be called. Calling these functions from a typemap is supported, since the typemap code is embedded into the _wrap.c file, which has those declarations available. If you need to call the SWIG run-time functions from another C file, there is one header you need to include. To generate the header that needs to be included, run the following command:

$ swig -python -external-runtime <filename>

The filename argument is optional and if it is not passed, then the default filename will be something like swigpyrun.h, depending on the language. This header file should be treated like any of the other _wrap.c output files, and should be regenerated when the _wrap files are. After including this header, your code will be able to call SWIG_TypeQuery, SWIG_NewPointerObj, SWIG_ConvertPtr and others. The exact argument parameters for these functions might differ between language modules; please check the language module chapters for more information.

Inside this header the functions are declared static and are included inline into the file, and thus the file does not need to be linked against any SWIG libraries or code (you might still need to link against the language libraries like libpython-2.3). Data is shared between this file and the _wrap.c files through a global variable in the scripting language. It is also possible to copy this header file along with the generated wrapper files into your own package, so that you can distribute a package that can be compiled without SWIG installed (this works because the header file is self-contained, and does not need to link with anything).

15.3 A word of caution about static libraries

When working with multiple SWIG modules, you should take care not to use static libraries. For example, if you have a static library libfoo.a and you link a collection of SWIG modules with that library, each module will get its own private copy of the library code inserted into it. This is very often NOT what you want and it can lead to unexpected or bizarre program behavior. When working with dynamically loadable modules, you should try to work exclusively with shared libraries.

15.4 References

Due to the complexity of working with shared libraries and multiple modules, it might be a good idea to consult an outside reference. John Levine's "Linkers and Loaders" is highly recommended.

15.5 Reducing the wrapper file size

Using multiple modules with the %import directive is the most common approach to modularising large projects. In this way a number of different wrapper files can be generated, thereby avoiding the generation of a single large wrapper file. There are a couple of alternative solutions for reducing the size of a wrapper file through the use of command line options and features.

-fcompact
This command line option will compact the size of the wrapper file without changing the code generated into the wrapper file. It simply removes blank lines and joins lines of code together. This is useful for compilers that have a maximum file size that can be handled.

-fvirtual
This command line option will remove the generation of superfluous virtual method wrappers. Consider the following inheritance hierarchy:

struct Base {
  virtual void method();
  ...
};

struct Derived : Base {
  virtual void method();
  ...
};

Normally wrappers are generated for both methods, whereas this command line option will suppress the generation of a wrapper for Derived::method. Normal polymorphic behaviour remains as Derived::method will still be called should you have a Derived instance and call the wrapper for Base::method.

%feature("compactdefaultargs")
This feature can reduce the number of wrapper methods when wrapping methods with default arguments. The section on default arguments discusses the feature and its limitations.


16 SWIG and Allegro Common Lisp

This chapter describes SWIG's support of Allegro Common Lisp. Allegro CL is a full-featured implementation of the Common Lisp language standard that includes many vendor-specific enhancements and add-on modules for increased usability.

One such module included in Allegro CL is the Foreign Functions Interface (FFI). This module, tailored primarily toward interfacing with C/C++ and, historically, Fortran, provides a means by which compiled foreign code can be loaded into a running lisp environment and executed. The interface supports the calling of foreign functions and methods, allows for executing lisp routines from foreign code (callbacks), and the passing of data between foreign and lisp code.

The goal of this module is to make it possible to quickly generate the necessary foreign function definitions so one can make use of C/C++ foreign libraries directly from lisp without the tedium of having to code them by hand. When necessary, it will also generate further C/C++ code that will need to be linked with the intended library for proper interfacing from lisp. It has been designed with an eye toward flexibility. Some foreign function calls may release the heap, while other should not. Some foreign functions should automatically convert lisp strings into native strings, while others should not. These adjustments and many more are possible with the current module.

It is significant to note that, while this is a vendor-specific module, we would like to acknowledge the current and ongoing work by developers in the open source lisp community that are working on similar interfaces to implementation-independent foreign function interfaces (UFFI or CFFI, for example). Such work can only benefit the lisp community, and we would not be unhappy to see some enterprising folk use this work to add to it.

16.1 Basics

16.1.1 Running Swig

If you're reading this, you must have some library you need to generate an interface for. In order for SWIG to do this work, however, it needs a bit of information about how it should go about creating your interface, and what you are interfacing to.

SWIG expects a description of what in the foreign interface you wish to connect to. It must consisting of C/C++ declarations and special SWIG directives. SWIG can be furnished with a header file, but an interface can also be generated without library headers by supplying a simple text file--called the interface file, which is typically named with a .i extension--containing any foreign declarations of identifiers you wish to use. The most common approach is to use a an interface file with directives to parse the needed headers. A straight parse of library headers will result in usable code, but SWIG directives provides much freedom in how a user might tailor the generated code to their needs or style of coding.

Note that SWIG does not require any function definitions; the declarations of those functions is all that is necessary. Be careful when tuning the interface as it is quite possible to generate code that will not load or compile.

An example interface file is shown below. It makes use of two SWIG directives, one of which requests that the declarations in a header file be used to generate part of the interface, and also includes an additional declaration to be added.

example.i
%module example

%include "header.h"

int fact(int n);

The contents of header.h are very simple:

header.h
int fact(char *statement);   // pass it a fact, and it will rate it.

The contents of example.cl will look like this:

example.cl
(defpackage :example
  (:use :common-lisp :swig :ff :excl))

  ... helper routines for defining the interface ...

(swig-in-package ())

(swig-defun ("fact")
  ((PARM0_statement cl:string (* :char) ))
  (:returning (:int )
   :strings-convert t)
  (let ((SWIG_arg0 PARM0_statement))
  (swig-ff-call SWIG_arg0)))

(swig-defun ("fact")
  ((PARM0_n cl:integer :int ))
  (:returning (:int )
   :strings-convert t)
  (let ((SWIG_arg0 PARM0_n))
  (swig-ff-call SWIG_arg0)))

(swig-dispatcher ("fact" :type :function :arities (1)))

The generated file contains calls to internal swig helper functions. In this case there are two calls to swig-defun. These calls will expand into code that will make the appropriate definitions using the Allegro FFI. Note also, that this code is erroneous. Function overloading is not supported in C, and this code will not compile even though SWIG did not complain.

In order to generate a C interface to Allegro CL using this code run swig using the -allegrocl option, as below:

% swig -allegrocl example.i

When building an interface to C++ code, include the -c++ option:

% swig -allegrocl -c++ example.i

As a result of running one of the above commands, a file named example.cl will be generated containing the lisp side of the interface. As well, a file example_wrap.cxx is also generated, containing C/C++ wrapper code to facilitate access to C++ methods, enumeration values, and constant values. Wrapper functions are necessary in C++ due to the lack of a standard for mangling the names of symbols across all C++ compilers. These wrapper functions are exported from the shared library as appropriate, using the C name mangling convention. The lisp code that is generated will interface to your foreign library through these wrappers.

It is possible to disable the creation of the .cxx file when generating a C interface by using the -nocwrap command-line argument. For interfaces that don't contain complex enum or constant expressions, contain nested struct/union declarations, or doesn't need to use many of the SWIG customization featuers, this will result in a more streamlined, direct interface to the intended module.

The generated wrapper file is below. It contains very simple wrappers by default, that simply pass the arguments to the actual function.

example_wrap.i
   ... lots of SWIG internals ...

EXPORT int ACL___fact__SWIG_0 (char *larg1) {
    int lresult = (int)0 ;
    char *arg1 = (char *) 0 ;
    int result;
    
    arg1 = larg1;
    try {
        result = (int)fact(arg1);
        
        lresult = result;
        return lresult;
    } catch (...) {
        return (int)0;
    }
}


EXPORT int ACL___fact__SWIG_1 (int larg1) {
    int lresult = (int)0 ;
    int arg1 ;
    int result;
    
    arg1 = larg1;
    try {
        result = (int)fact(arg1);
        
        lresult = result;
        return lresult;
    } catch (...) {
        return (int)0;
    }
}

And again, the generated lisp code. Note that it differs from what is generated when parsing C code:

   ...

(swig-in-package ())

(swig-defmethod ("fact" "ACL___fact__SWIG_0" :type :function :arity 1)
  ((PARM0_statement cl:string (* :char) ))
  (:returning (:int )
   :strings-convert t)
  (let ((SWIG_arg0 PARM0_statement))
  (swig-ff-call SWIG_arg0)))

(swig-defmethod ("fact" "ACL___fact__SWIG_1" :type :function :arity 1)
  ((PARM0_n cl:integer :int ))
  (:returning (:int )
   :strings-convert t)
  (let ((SWIG_arg0 PARM0_n))
  (swig-ff-call SWIG_arg0)))

(swig-dispatcher ("fact" :type :function :arities (1)))

In this case, the interface generates two swig-defmethod forms and a swig-dispatcher form. This provides a single functional interface for all overloaded routines. A more detailed description of this features is to be found in the section titled Function overloading/Parameter defaulting.

In order to load a C++ interface, you will need to build a shared library from example_wrap.cxx. Be sure to link in the actual library you created the interface for, as well as any other dependent shared libraries. For example, if you intend to be able to call back into lisp, you will also need to link in the Allegro shared library. The library you create from the C++ wrapper will be what you then load into Allegro CL.

16.1.2 Command Line Options

There are three Allegro CL specific command-line option:

swig -allegrocl [ options ] filename

   -identifier-converter [name] - Binds the variable swig:*swig-identifier-convert* 
                                  in the generated .cl file to name.
				  This function is used to generate symbols
				  for the lisp side of the interface. 

   -cwrap - [default] Generate a .cxx file containing C wrapper function when
            wrapping C code. The interface generated is similar to what is
	    done for C++ code.
   -nocwrap - Explicitly turn off generation of .cxx wrappers for C code. Reasonable
              for modules with simple interfaces. Can not handle all legal enum
	      and constant constructs, or take advantage of SWIG customization features.

   -isolate - With this command-line argument, all lisp helper functions are defined
              in a unique package named swig.<module-name> rather than
	      swig. This prevents conflicts when the module is
	      intended to be used with other swig generated interfaces that may, 
	      for instance, make use of different identifier converters.

See Section 17.5 Identifier converter functions for more details.

16.1.3 Inserting user code into generated files

It is often necessary to include user-defined code into the automatically generated interface files. For example, when building a C++ interface, example_wrap.cxx will likely not compile unless you add a #include "header.h" directive. This can be done using the SWIG %insert(section) %{ ...code... %} directive:

%module example

%insert("runtime") %{
#include "header.h"
%}

%include "header.h"

int fact(int n);

Additional sections have been added for inserting into the generated lisp interface file

Note that the block %{ ... %} is effectively a shortcut for %insert("runtime") %{ ... %}.

16.2 Wrapping Overview

New users to SWIG are encouraged to read SWIG Basics , and SWIG and C++, for those interested in generating an interface to C++.

16.2.1 Function Wrapping

Writing lisp code that directly invokes functions at the foreign function interface level can be cumbersome. Data must often be translated between lisp and foreign types, data extracted from objects, foreign objects allocated and freed upon completion of the foreign call. Dealing with pointers can be unwieldy when it comes to keeping them distinct from other valid integer values.

We make an attempt to ease some of these burdens by making the interface to foreign code much more lisp-like, rather than C like. How this is done is described in later chapters. The layers themselves, appear as follows:

        ______________
       |              |  (foreign side)
       | Foreign Code |  What we're generating an interface to.
       |______________|
               |
	       |
        _______v______
       |              |  (foreign side)
       | Wrapper code |  extern "C" wrappers calling C++ 
       |______________|  functions and methods.
               |
    .  . . - - + - - . .  .
        _______v______
       |              |  (lisp side)
       |  FFI Layer   |  Low level lisp interface. ff:def-foreign-call,
       |______________|  ff:def-foreign-variable
               |
	       +----------------------------
        _______v______              _______v______
       |              |            |              | (lisp side)    
       |    Defuns    |            |  Defmethods  | wrapper for overloaded
       |______________|            |______________| functions or those with
        (lisp side)                        |        defaulted arguments
	Wrapper for non-overloaded         |
	functions and methods       _______v______
	                           |              | (lisp side)
				   |    Defuns    | dispatch function
				   |______________| to overloads based
				                    on arity
  

16.2.2 Foreign Wrappers

These wrappers are as generated by SWIG default. The types of function parameters can be transformed in place using the CTYPE typemap. This is use for converting pass-by-value parameters to pass-by-reference where necessary. All wrapper parameters are then bound to local variables for possible transformation of values (see LIN typemap). Return values can be transformed via the OUT typemap.

16.2.3 FFI Wrappers

These are the generated ff:def-foreign-call forms. No typemaps are applicable to this layer, but the %ffargs directive is available for use in .i files, to specify which keyword arguments should be specified for a given function.

ffargs.i:
%module ffargs

%ffargs(strings_convert="nil",call_direct="t") foo;
%ffargs(strings_convert="nil",release_heap=":never",optimize_for_space="t") bar;

int foo(float f1, float f2);
int foo(float f1, char c2);

void bar(void *lisp_fn);

char *xxx();
  

Generates:

ffargs.cl:
(swig-in-package ())

(swig-defmethod ("foo" "ACL___foo__SWIG_0" :type :function :arity 2)
  ((PARM0_f1 cl:single-float :float )
   (PARM1_f2 cl:single-float :float ))
  (:returning (:int )
   :call-direct t
   :strings-convert nil)
  (let ((SWIG_arg0 PARM0_f1))
  (let ((SWIG_arg1 PARM1_f2))
  (swig-ff-call SWIG_arg0 SWIG_arg1))))

(swig-defmethod ("foo" "ACL___foo__SWIG_1" :type :function :arity 2)
  ((PARM0_f1 cl:single-float :float )
   (PARM1_c2 cl:character :char character))
  (:returning (:int )
   :call-direct t
   :strings-convert nil)
  (let ((SWIG_arg0 PARM0_f1))
  (let ((SWIG_arg1 PARM1_c2))
  (swig-ff-call SWIG_arg0 SWIG_arg1))))

(swig-dispatcher ("foo" :type :function :arities (2)))
(swig-defun ("bar" "ACL___bar__SWIG_0" :type :function)
  ((PARM0_lisp_fn  (* :void) ))
  (:returning (:void )
   :release-heap :never
   :optimize-for-space t
   :strings-convert nil)
  (let ((SWIG_arg0 PARM0_lisp_fn))
  (swig-ff-call SWIG_arg0)))


(swig-defun ("xxx" "ACL___xxx__SWIG_0" :type :function)
  (:void)
  (:returning ((* :char) )
   :strings-convert t)
  (swig-ff-call))
  
%ffargs(strings_convert="t");

Is the only default value specified in allegrocl.swg to force the muffling of warnings about automatic string conversion when defining ff:def-foreign-call's.

16.2.4 Non-overloaded Defuns

These are simple defuns. There is no typechecking of arguments. Parameters are bound to local variables for possible transformation of values, such as pulling values out of instance slots or allocating temporary stack allocated structures, via the lin typemap. These arguments are then passed to the foreign-call (where typechecking may occur). The return value from this function can be manipulated via the lout typemap.

16.2.5 Overloaded Defuns

In the case of overloaded functions, mulitple layers are generated. First, all the overloads for a given name are separated out into groups based on arity, and are wrapped in defmethods. Each method calls a distinct wrapper function, but are themselves distinguished by the types of their arguments (see lispclass typemap). These are further wrapped in a dispatching function (defun) which will invoke the appropriate generic-function based on arity. This provides a single functional interface to all overloads. The return value from this function can be manipulated via the lout typemap.

16.2.6 What about constant and variable access?

Along with the described functional layering, when creating a .cxx wrapper, this module will generate getter and--if not immutable--setter, functions for variables and constants. If the -nocwrap option is used, defconstant and ff:def-foreign-variable forms will be generated for accessing constants and global variables. These, along with the defuns listed above are the intended API for calling into the foreign module.

16.2.7 Object Wrapping

All non-primitive types (Classes, structs, unions, and typedefs involving same) have a corresponding foreign-type defined on the lisp side via ff:def-foreign-type.

All non-primitive types are further represented by a CLOS class, created via defclass. An attempt is made to create the same class hierarchy, with all classes inheriting directly or indirectly from ff:foreign-pointer. Further, wherever it is apparent, all pointers returned from foreign code are wrapped in a CLOS instance of the appropriate class. For ff:def-foreign-calls that have been defined to expect a :foreign-address type as argument, these CLOS instances can legally be passed and the pointer to the C++ object automatically extracted. This is a natural feature of Allegro's foreign function interface.

16.3 Wrapping Details

In this section is described how particular C/C++ constructs are translated into lisp.

16.3.1 Namespaces

C++ namespaces are translated into Lisp packages by SWIG. The Global namespace is mapped to a package named by the %module directive or the -module command-line argument. Further namespaces are generated by the swig-defpackage utility function and given names based on Allegro CLs nested namespace convention. For example:

foo.i:
%module foo

%{
#include "foo.h"
%}

%include "foo.h"

namespace car {
   ...
   namespace tires {
      int do_something(int n);
   }
}
    

Generates the following code.

foo.cl
(defpackage :foo
  (:use :common-lisp :swig :ff :excl))

...

(swig-defpackage ("car"))
(swig-defpackage ("car" "tires"))

...

(swig-in-package ("car" "tires"))
(swig-defun ("do_something" "ACL_car_tires__do_something__SWIG_0" :type :function)
  ((PARM0_n  :int ))
  (:returning (:int )
   :strings-convert t)
  (let ((SWIG_arg0 PARM0_n))
  (swig-ff-call SWIG_arg0)))
    

The above interface file would cause packages foo, foo.car, and foo.car.tires to be created. One would find the function wrapper for do_something defined in the foo.car.tires package(*).

(*) Except for the package named by the module, all namespace names are passed to the identifier-converter-function as strings with a :type of :namespace. It is the job of this function to generate the desired symbol, accounting for case preferences, additional naming cues, etc.

Note that packages created by swig-defpackage do not use the COMMON-LISP or EXCL package. This reduces possible conflicts when defining foreign types via the SWIG interface in all but the toplevel modules package. This may lead to confusion if, for example, the current package is foo.car.tires and you attempt to use a common-lisp function such as (car '(1 2 3).

16.3.2 Constants

Constants, as declared by the preprocessor #define macro or SWIG %constant directive, are included in SWIGs parse tree when it can be determined that they are, or could be reduced to, a literal value. Such values are translated into defconstant forms in the generated lisp wrapper when the -nocwrap command-line options is used. Else, wrapper functions are generated as in the case of variable access (see section below).

Here are examples of simple preprocessor constants when using -nocwrap.

#define A 1                    => (swig-defconstant "A" 1)  
#define B 'c'                  => (swig-defconstant "B" #\c)
#define C B                    => (swig-defconstant "C" #\c)
#define D 1.0e2                => (swig-defconstant "D" 1.0d2)
#define E 2222                 => (swig-defconstant "E" 2222)
#define F (unsigned int)2222   => no code generated
#define G 1.02e2f              => (swig-defconstant "G" 1.02f2)
#define H foo                  => no code generated
      

Note that where SWIG is unable to determine if a constant is a literal, no node is added to the SWIG parse tree, and so no values can be generated.

For preprocessor constants containing expressions which can be reduced to literal values, nodes are created, but with no simplification of the constant value. A very very simple infix to prefix converter has been implemented that tries to do the right thing for simple cases, but does not for more complex expressions. If the literal parser determines that something is wrong, a warning will be generated and the literal expression will be included in the generated code, but commented out.

#define I A + E                => (swig-defconstant "I" (+ 1 2222))
#define J 1|2                  => (swig-defconstant "J" (logior 1 2))
#define Y 1 + 2 * 3 + 4        => (swig-defconstant "Y" (* (+ 1 2) (+ 3 4)))
#define Y1 (1 + 2) * (3 + 4)   => (swig-defconstant "Y1" (* (+ 1 2) (+ 3 4)))
#define Y2 1 * 2 + 3 * 4       => (swig-defconstant "Y2" (* 1 (+ 2 3) 4))  ;; WRONG
#define Y3 (1 * 2) + (3 * 4)   => (swig-defconstant "Y3" (* 1 (+ 2 3) 4))  ;; WRONG
#define Z 1 + 2 - 3 + 4 * 5    => (swig-defconstant "Z" (* (+ 1 (- 2 3) 4) 5)) ;; WRONG
      

Users are cautioned to get to know their constants before use, or not use the -nocwrap command-line option.

16.3.3 Variables

For C wrapping, a def-foreign-variable call is generated for access to global variables.

When wrapping C++ code, both global and member variables, getter wrappers are generated for accessing their value, and if not immutable, setter wrappers as well. In the example below, note the lack of a setter wrapper for global_var, defined as const.

vars.h
namespace nnn {
  int const global_var = 2;
  float glob_float = 2.0;
}
    

Generated code:

vars.cl
(swig-in-package ("nnn"))
(swig-defun ("global_var" "ACL_nnn__global_var_get__SWIG_0" :type :getter)
  (:void)
  (:returning (:int )
   :strings-convert t)
  (swig-ff-call))


(swig-defun ("glob_float" "ACL_nnn__glob_float_set__SWIG_0" :type :setter)
  ((PARM0_glob_float  :float ))
  (:returning (:void )
   :strings-convert t)
  (let ((SWIG_arg0 PARM0_glob_float))
  (swig-ff-call SWIG_arg0)))


(swig-defun ("glob_float" "ACL_nnn__glob_float_get__SWIG_0" :type :getter)
  (:void)
  (:returning (:float )
   :strings-convert t)
  (swig-ff-call))
    

Note also, that where applicable, setter wrappers are implemented as setf methods on the getter function, providing a lispy interface to the foreign code.

user> (load "globalvar.dll")
; Foreign loading globalvar.dll.
t
user> (load "globalvar.cl")
; Loading c:\mikel\src\swig\test\globalvar.cl
t
user> 
globalvar> (globalvar.nnn::global_var)
2
globalvar> (globalvar.nnn::glob_float)
2.0
globalvar> (setf (globalvar.nnn::glob_float) 3.0)
3.0
globalvar> (globalvar.nnn::glob_float)
3.0
    

16.3.4 Enumerations

In C, an enumeration value is an integer value, while in C++ an enumeration value is implicitly convertible to an integer value, but can also be distinguished by it's enum type. For each enum declaration a def-foreign-type is generated, assigning the enum a default type of :int. Users may adjust the foreign type of enums via SWIG typemaps .

Enum values are a bit trickier as they can be initialized using any valid C/C++ expression. In C with the -nocwrap command-line option, we handle the typical cases (simple integer initialization) and generate a defconstant form for each enum value. This has the advantage of it not being necessary to probe into foreign space to retrieve enum values. When generating a .cxx wrapper file, a more general solution is employed. A wrapper variable is created in the module_wrap.cxx file, and a ff:def-foreign-variable call is generated to retrieve it's value into lisp.

For example, the following header file

enum.h:
enum COL { RED, GREEN, BLUE };	
enum FOO { FOO1 = 10, FOO2, FOO3 };
      

In -nocwrap mode, generates

enum.cl:
(swig-def-foreign-type "COL" :int)
(swig-defconstant "RED" 0)
(swig-defconstant "GREEN" (+ #.(swig-insert-id "RED" () :type :constant) 1))
(swig-defconstant "BLUE" (+ #.(swig-insert-id "GREEN" () :type :constant) 1))

(swig-def-foreign-type "FOO" :int)
(swig-defconstant "FOO1" 10)
(swig-defconstant "FOO2" (+ #.(swig-insert-id "FOO1" () :type :constant) 1))
(swig-defconstant "FOO3" (+ #.(swig-insert-id "FOO2" () :type :constant) 1))
      

And when generating a .cxx wrapper

enum_wrap.cxx:
EXPORT const int ACL_ENUM___RED__SWIG_0 = RED;
EXPORT const int ACL_ENUM___GREEN__SWIG_0 = GREEN;
EXPORT const int ACL_ENUM___BLUE__SWIG_0 = BLUE;
EXPORT const int ACL_ENUM___FOO1__SWIG_0 = FOO1;
EXPORT const int ACL_ENUM___FOO2__SWIG_0 = FOO2;
EXPORT const int ACL_ENUM___FOO3__SWIG_0 = FOO3;
      

and

enum.cl:
(swig-def-foreign-type "COL" :int)
(swig-defvar "RED" "ACL_ENUM___RED__SWIG_0" :type :constant)
(swig-defvar "GREEN" "ACL_ENUM___GREEN__SWIG_0" :type :constant)
(swig-defvar "BLUE" "ACL_ENUM___BLUE__SWIG_0" :type :constant)

(swig-def-foreign-type "FOO" :int)
(swig-defvar "FOO1" "ACL_ENUM___FOO1__SWIG_0" :type :constant)
(swig-defvar "FOO2" "ACL_ENUM___FOO2__SWIG_0" :type :constant)
(swig-defvar "FOO3" "ACL_ENUM___FOO3__SWIG_0" :type :constant)

      

16.3.5 Arrays

One limitation in the Allegro CL foreign-types module, is that, without macrology, expressions may not be used to specify the dimensions of an array declaration. This is not a horrible drawback unless it is necessary to allocate foreign structures based on the array declaration using ff:allocate-fobject. When it can be determined that an array bound is a valid numeric value, SWIG will include this in the generated array declaration on the lisp side, otherwise the value will be included, but commented out.

Below is a comprehensive example, showing a number of legal C/C++ array declarations and how they are translated into foreign-type specifications in the generated lisp code.

array.h
#define MAX_BUF_SIZE 1024

namespace FOO {
  int global_var1[13];
  float global_var2[MAX_BUF_SIZE];

}

enum COLOR { RED = 10, GREEN = 20, BLUE, PURPLE = 50, CYAN };

namespace BAR {
  char global_var3[MAX_BUF_SIZE + 1];
  float global_var4[MAX_BUF_SIZE][13];
  signed short global_var5[MAX_BUF_SIZE + MAX_BUF_SIZE];

  int enum_var5[GREEN];
  int enum_var6[CYAN];

  COLOR enum_var7[CYAN][MAX_BUF_SIZE];
}
    

Generates:

array.cl
(in-package #.*swig-module-name*)

(swig-defpackage ("FOO"))
(swig-defpackage ("BAR"))

(swig-in-package ())
(swig-def-foreign-type "COLOR" :int)
(swig-defvar "RED" "ACL_ENUM___RED__SWIG_0" :type :constant)
(swig-defvar "GREEN" "ACL_ENUM___GREEN__SWIG_0" :type :constant)
(swig-defvar "BLUE" "ACL_ENUM___BLUE__SWIG_0" :type :constant)
(swig-defvar "PURPLE" "ACL_ENUM___PURPLE__SWIG_0" :type :constant)
(swig-defvar "CYAN" "ACL_ENUM___CYAN__SWIG_0" :type :constant)

(swig-in-package ())

(swig-defconstant "MAX_BUF_SIZE" 1024)
(swig-in-package ("FOO"))

(swig-defun ("global_var1" "ACL_FOO__global_var1_get__SWIG_0" :type :getter)
  (:void)
  (:returning ((* :int) )
   :strings-convert t)
  (make-instance 'ff:foreign-pointer :foreign-address (swig-ff-call)))


(swig-defun ("global_var2" "ACL_FOO__global_var2_set__SWIG_0" :type :setter)
  ((global_var2  (:array :float 1024) ))
  (:returning (:void )
   :strings-convert t)
  (let ((SWIG_arg0 global_var2))
  (swig-ff-call SWIG_arg0)))


(swig-in-package ())
(swig-in-package ("BAR"))
(swig-defun ("global_var3" "ACL_BAR__global_var3_set__SWIG_0" :type :setter)
  ((global_var3  (:array :char #|1024+1|#) ))
  (:returning (:void )
   :strings-convert t)
  (let ((SWIG_arg0 global_var3))
  (swig-ff-call SWIG_arg0)))


(swig-defun ("global_var4" "ACL_BAR__global_var4_set__SWIG_0" :type :setter)
  ((global_var4  (:array (:array :float 13) 1024) ))
  (:returning (:void )
   :strings-convert t)
  (let ((SWIG_arg0 global_var4))
  (swig-ff-call SWIG_arg0)))


(swig-defun ("global_var4" "ACL_BAR__global_var4_get__SWIG_0" :type :getter)
  (:void)
  (:returning ((* (:array :float 13)) )
   :strings-convert t)
  (make-instance 'ff:foreign-pointer :foreign-address (swig-ff-call)))


(swig-defun ("global_var5" "ACL_BAR__global_var5_set__SWIG_0" :type :setter)
  ((global_var5  (:array :short #|1024+1024|#) ))
  (:returning (:void )
   :strings-convert t)
  (let ((SWIG_arg0 global_var5))
  (swig-ff-call SWIG_arg0)))


(swig-defun ("enum_var5" "ACL_BAR__enum_var5_set__SWIG_0" :type :setter)
  ((enum_var5  (:array :int #|GREEN|#) ))
  (:returning (:void )
   :strings-convert t)
  (let ((SWIG_arg0 enum_var5))
  (swig-ff-call SWIG_arg0)))


(swig-defun ("enum_var6" "ACL_BAR__enum_var6_set__SWIG_0" :type :setter)
  ((enum_var6  (:array :int #|CYAN|#) ))
  (:returning (:void )
   :strings-convert t)
  (let ((SWIG_arg0 enum_var6))
  (swig-ff-call SWIG_arg0)))


(swig-defun ("enum_var7" "ACL_BAR__enum_var7_set__SWIG_0" :type :setter)
  ((enum_var7  (:array (:array #.(swig-insert-id "COLOR" ()) 1024) #|CYAN|#) ))
  (:returning (:void )
   :strings-convert t)
  (let ((SWIG_arg0 enum_var7))
  (swig-ff-call SWIG_arg0)))


(swig-defun ("enum_var7" "ACL_BAR__enum_var7_get__SWIG_0" :type :getter)
  (:void)
  (:returning ((* (:array #.(swig-insert-id "COLOR" ()) 1024)) )
   :strings-convert t)
  (make-instance 'ff:foreign-pointer :foreign-address (swig-ff-call)))
    

16.3.6 Classes and Structs and Unions (oh my!)

16.3.6.1 CLOS wrapping of

Classes, unions, and structs are all treated the same way by the interface generator. For any of these objects, a def-foreign-type and a defclass form are generated. For every function that returns an object (or pointer/reference) of C/C++ type X, the wrapping defun (or defmethod) on the Lisp side will automatically wrap the pointer returned in an instance of the apropriate class. This makes it much easier to write and debug code than if pointers were passed around as a jumble of integer values.

16.3.6.2 CLOS Inheritance

The CLOS class schema generated by the interface mirrors the inheritance of the classes in foreign code, with the ff:foreign-pointer class at its root. ff:foreign-pointer is a thin wrapper for pointers that is made available by the foreign function interface. It's key benefit is that it may be passed as an argument to any ff:def-foreign-call that is expecting a pointer as the parameter.

16.3.6.3 Member fields and functions

All public fields will have accessor getter/setter functions generated for them, as appropriate. All public member functions will have wrapper functions generated.

We currently ignore anything that isn't public (i.e. private or protected), because the C++ compiler won't allow the wrapper functions to access such fields. Likewise, the interface does nothing for friend directives,

16.3.6.4 Why not directly access C++ classes using foreign types?

The def-foreign-type generated by the SWIG interface is currently incomplete. We can reliably generate the object layout of simple structs and unions; they can be allocated via ff:allocate-fobject, and their member variables accessed directly using the various ff:fslot-value-* functions. However, the layout of C++ classes is more complicated. Different compilers adjust class layout based on inheritance patterns, and the presence of virtual member functions. The size of member function pointers vary across compilers as well. As a result, it is recommended that users of any generated interface not attempt to access C++ instances via the foreign type system, but instead use the more robust wrapper functions.

16.3.7 Templates

16.3.7.1 Generating wrapper code for templates

SWIG provides support for dealing with templates, but by default, it will not generate any member variable or function wrappers for templated classes. In order to create these wrappers, you need to explicitly tell SWIG to instantiate them. This is done via the %template directive.

16.3.7.2 Implicit Template instantiation

While no wrapper code is generated for accessing member variables, or calling member functions, type code is generated to include these templated classes in the foreign-type and CLOS class schema.

16.3.8 Typedef, Templates, and Synonym Types

In C/C++ it is possible, via typedef, to have many names refer to the same type. In general, this is not a problem, though it can lead to confusion. Assume the below C++ header file:

synonyms.h
class A { 
   int x;
   int y;
};

typedef A Foo;

A *xxx(int i);         /* sets A->x = A->y = i */
Foo *yyy(int i);       /* sets Foo->x = Foo->y = i */

int zzz(A *inst = 0);  /* return inst->x + inst->y */
    

The function zzz is an overloaded functions; the foreign function call to it will be wrapped in a generic-function whose argument will be checked against a type of A. Assuming a simple implementation, a call to xxx(1) will return a pointer to an A object, which will be wrapped in a CLOS instance of class A , and a call to yyy(1) will result in a CLOS instance of type Foo being returned. Without establishing a clear type relationship between Foo and A, an attempt to call zzz(yyy(1)) will result in an error.

We resolve this issue, by noting synonym relationships between types while generating the interface. A Primary type is selected (more on this below) from the candidate list of synonyms. For all other synonyms, intead of generating a distinct CLOS class definition, we generate a form that expands to:

(setf (find-class <synonym>) <primary>)

The result is that all references to synonym types in foreign code, are wrapped in the same CLOS wrapper, and, in particular, method specialization in wrapping generic functions works as expected.

Given the above header file, synonym.h, a Lisp session would appear as follows:

CL-USER> (load "synonym.dll")
; Foreign loading synonym.dll.
t
CL-USER> (load "synonym.cl")
; Loading c:\mikel\src\swig\test\synonym.cl
t
CL-USER> 
synonym> (setf a (xxx 3))
#<A nil #x3261a0 @ #x207299da>
synonym> (setf foo (yyy 10))
#<A nil #x3291d0 @ #x2072e982>
synonym> (zzz a)
6
synonym> (zzz foo)
20
synonym> 
    

16.3.8.1 Choosing a primary type

The choice of a primary type is selected by the following criteria from a set of synonym types.

16.3.9 Function overloading/Parameter defaulting

For each possible argument combination, a distinct wrapper function is created in the .cxx file. On the Lisp side, a generic functions is defined for each possible arity the overloaded/defaulted call may have. Each distinct wrapper is then called from within a defmethod on the appropriate generic function. These are further wrapped inside a dispatch function that checks the number of arguments it is called with and passes them via apply to the appropriate generic-function. This allows for a single entry point to overloaded functions on the lisp side.

Example:

overload.h:

class A {
 public:
  int x;
  int y;
};

float xxx(int i, int x = 0);   /* return i * x */
float xxx(A *inst, int x);     /* return x + A->x + A->y */
    

Creates the following three wrappers, for each of the possible argument combinations

overload_wrap.cxx
EXPORT void ACL___delete_A__SWIG_0 (A *larg1) {
    A *arg1 = (A *) 0 ;
    
    arg1 = larg1;
    try {
        delete arg1;
        
    } catch (...) {
        
    }
}


EXPORT float ACL___xxx__SWIG_0 (int larg1, int larg2) {
    float lresult = (float)0 ;
    int arg1 ;
    int arg2 ;
    float result;
    
    arg1 = larg1;
    arg2 = larg2;
    try {
        result = (float)xxx(arg1,arg2);
        
        lresult = result;
        return lresult;
    } catch (...) {
        return (float)0;
    }
}


EXPORT float ACL___xxx__SWIG_1 (int larg1) {
    float lresult = (float)0 ;
    int arg1 ;
    float result;
    
    arg1 = larg1;
    try {
        result = (float)xxx(arg1);
        
        lresult = result;
        return lresult;
    } catch (...) {
        return (float)0;
    }
}


EXPORT float ACL___xxx__SWIG_2 (A *larg1, int larg2) {
    float lresult = (float)0 ;
    A *arg1 = (A *) 0 ;
    int arg2 ;
    float result;
    
    arg1 = larg1;
    arg2 = larg2;
    try {
        result = (float)xxx(arg1,arg2);
        
        lresult = result;
        return lresult;
    } catch (...) {
        return (float)0;
    }
}
    

And the following foreign-function-call and method definitions on the lisp side:

overload.cl
(swig-defmethod ("xxx" "ACL___xxx__SWIG_0" :type :function :arity 2)
  ((PARM0_i cl:integer :int )
   (PARM1_x cl:integer :int ))
  (:returning (:float )
   :strings-convert t)
  (let ((SWIG_arg0 PARM0_i))
  (let ((SWIG_arg1 PARM1_x))
  (swig-ff-call SWIG_arg0 SWIG_arg1))))

(swig-defmethod ("xxx" "ACL___xxx__SWIG_1" :type :function :arity 1)
  ((PARM0_i cl:integer :int ))
  (:returning (:float )
   :strings-convert t)
  (let ((SWIG_arg0 PARM0_i))
  (swig-ff-call SWIG_arg0)))

(swig-defmethod ("xxx" "ACL___xxx__SWIG_2" :type :function :arity 2)
  ((PARM0_inst #.(swig-insert-id "A" () :type :class) (* #.(swig-insert-id "A" ())) )
   (PARM1_x cl:integer :int ))
  (:returning (:float )
   :strings-convert t)
  (let ((SWIG_arg0 PARM0_inst))
  (let ((SWIG_arg1 PARM1_x))
  (swig-ff-call SWIG_arg0 SWIG_arg1))))

(swig-dispatcher ("xxx" :type :function :arities (1 2)))
    

And their usage in a sample lisp session:

overload> (setf a (new_A))
#<A nil #x329268 @ #x206cf612>
overload> (setf (A_x a) 10)
10
overload> (setf (A_y a) 20)
20
overload> (xxx 1)
0.0
overload> (xxx 3 10)
30.0
overload> (xxx a 1)
31.0
overload> (xxx a 2)
32.0
overload> 
    

16.3.10 Operator wrapping and Operator overloading

Wrappers to defined C++ Operators are automatically renamed, using %rename, to the following defaults:

/* name conversion for overloaded operators. */
#ifdef __cplusplus
%rename(__add__)	     *::operator+;
%rename(__pos__)	     *::operator+();
%rename(__pos__)	     *::operator+() const;

%rename(__sub__)	     *::operator-;
%rename(__neg__)	     *::operator-() const;
%rename(__neg__)	     *::operator-();

%rename(__mul__)	     *::operator*;
%rename(__deref__)	     *::operator*();
%rename(__deref__)	     *::operator*() const;

%rename(__div__)	     *::operator/;
%rename(__mod__)	     *::operator%;
%rename(__logxor__)	     *::operator^;
%rename(__logand__)	     *::operator&;
%rename(__logior__)	     *::operator|;
%rename(__lognot__)	     *::operator~();
%rename(__lognot__)	     *::operator~() const;

%rename(__not__)	     *::operator!();
%rename(__not__)	     *::operator!() const;

%rename(__assign__)	     *::operator=;

%rename(__add_assign__)      *::operator+=;
%rename(__sub_assign__)	     *::operator-=;
%rename(__mul_assign__)	     *::operator*=;
%rename(__div_assign__)	     *::operator/=;
%rename(__mod_assign__)	     *::operator%=;
%rename(__logxor_assign__)   *::operator^=;
%rename(__logand_assign__)   *::operator&=;
%rename(__logior_assign__)   *::operator|=;

%rename(__lshift__)	     *::operator<

>;
%rename(__rshift_assign__)   *::operator>>=;

%rename(__eq__)		     *::operator==;
%rename(__ne__)		     *::operator!=;
%rename(__lt__)		     *::operator

;
%rename(__lte__)	     *::operator<=;
%rename(__gte__)	     *::operator>=;

%rename(__and__)	     *::operator&&;
%rename(__or__)		     *::operator||;

%rename(__preincr__)	     *::operator++();
%rename(__postincr__)	     *::operator++(int);
%rename(__predecr__)	     *::operator--();
%rename(__postdecr__)	     *::operator--(int);

%rename(__comma__)	     *::operator,();
%rename(__comma__)	     *::operator,() const;

%rename(__member_ref__)      *::operator->;
%rename(__member_func_ref__) *::operator->*;

%rename(__funcall__)	     *::operator();
%rename(__aref__)	     *::operator[];
    

Name mangling occurs on all such renamed identifiers, so that wrapper name generated by B::operator= will be B___eq__ , i.e. <class-or-namespace>_ has been added. Users may modify these default names by adding %rename directives in their own .i files.

Operator overloading can be achieved by adding functions based on the mangled names of the function. In the following example, a class B is defined with a Operator== method defined. The swig %extend directive is used to add an overload method on Operator==.

opoverload.h
class B {
 public:
  int x;
  int y;
  bool operator==(B const& other) const;
};
    

and

opoverload.i
%module opoverload

%{
#include <fstream>
#include "opoverload.h"
%}

%{
bool B___eq__(B const *inst, int const x)
{
  // insert the function definition into the wrapper code before
  // the wrapper for it.
  // ... do stuff ...
}
%}

%include "opoverload.h"

%extend B {
 public:
  bool __eq__(int const x) const;
};
    

Either operator can be called via a single call to the dispatch function:

opoverload> (B___eq__ x1 x2)
nil
opoverload> (B___eq__ x1 3)
nil
opoverload> 
    

16.3.11 Varargs

Variable length argument lists are not supported, by default. If such a function is encountered, a warning will generated to stderr. Varargs are supported via the SWIG %vararg directive. This directive allows you to specify a (finite) argument list which will be inserted into the wrapper in place of the variable length argument indicator. As an example, consider the function printf(). It's declaration would appear as follows:

See the following section on Variable Length arguments provides examples on how %vararg can be used, along with other ways such functions can be wrapped.

16.3.12 C++ Exceptions

Each C++ wrapper includes a handler to catch any exceptions that may be thrown while in foreign code. This helps prevent simple C++ errors from killing the entire lisp process. There is currently no mechanism to have these exceptions forwarded to the lisp condition system, nor has any explicit support of the exception related SWIG typemaps been implemented.

16.3.13 Pass by value, pass by reference

Allegro CL does not support the passing of non-primitive foreign structures by value. As a result, SWIG must automatically detect and convert function parameters and return values to pointers whenever necessary. This is done via the use of typemaps, and should not require any fine tuning by the user, even for newly defined types.

16.4 Typemaps

SWIG Typemaps provide a powerful tool for automatically generating code to handle various menial tasks required of writing an interface to foreign code. The purpose of this section is to describe each of the typemaps used by the Allegro CL module. Please read the chapter on Typemaps for more information.

16.4.1 Code Generation in the C++ Wrapper

Every C++ wrapper generated by SWIG takes the following form:

return-val wrapper-name(parm0, parm1, ..., parmN)
{
   return-val lresult;   /* return value from wrapper */
   <local-declaration>
   ... results;          /* return value from function call */

   <binding locals to parameters>

   try {
      result = function-name(local0, local1, ..., localN);

      <convert and bind result to lresult>

      return lresult;
   catch (...) {
      return (int)0;
   }
    

16.4.1.1 IN Typemap

the in typemap is used to generate code to convert parameters passed to C++ wrapper functions into the arguments desired for the call being wrapped. That is, it fills in the code for the <binding locals to parameters> section above. We use this map to automatically convert parameters passed by reference to the wrapper function into by-value arguments for the wrapped call, and also to convert boolean values, which are passed as integers from lisp (by default), into the appropriate type for the language of code being wrapped.

These are the default specifications for the IN typemap. Here, $input refers to the parameter code is being generated for, and $1 is the local variable to which it is being assigned. The default settings of this typemap are as follows:

%typemap(in) bool                          "$1 = (bool)$input;";
%typemap(in) char, unsigned char, signed char,
             short, signed short, unsigned short,
             int, signed int, unsigned int,
             long, signed long, unsigned long,
             float, double, long double, char *, void *, void,
             enum SWIGTYPE, SWIGTYPE *,
             SWIGTYPE[ANY], SWIGTYPE &     "$1 = $input;";
%typemap(in) SWIGTYPE                      "$1 = *$input;";
    

16.4.1.2 OUT Typemap

The out typemap is used to generate code to form the return value of the wrapper from the return value of the wrapped function. This code is placed in the <convert and bind result to lresult> section of the above code diagram. It's default mapping is as follows:

%typemap(out) bool                          "$result = (int)$1;";
%typemap(out) char, unsigned char, signed char,
              short, signed short, unsigned short,
              int, signed int, unsigned int,
              long, signed long, unsigned long,
              float, double, long double, char *, void *, void,
              enum SWIGTYPE, SWIGTYPE *,
              SWIGTYPE[ANY], SWIGTYPE &    "$result = $1;";
%typemap(out) SWIGTYPE                     "$result = new $1_type($1);";
    

16.4.1.3 CTYPE Typemap

This typemap is not used for code generation, but purely for the transformation of types in the parameter list of the wrapper function. It's primary use is to handle by-value to by-reference conversion in the wrappers parameter list. Its default settings are:

%typemap(ctype) bool                       "int";
%typemap(ctype) char, unsigned char, signed char,
                short, signed short, unsigned short,
                int, signed int, unsigned int,
                long, signed long, unsigned long,
                float, double, long double, char *, void *, void,
                enum SWIGTYPE, SWIGTYPE *,
                SWIGTYPE[ANY], SWIGTYPE &  "$1_ltype";
%typemap(ctype) SWIGTYPE                   "$&1_type";
    

These three typemaps are specifically employed by the the Allegro CL interface generator. SWIG also implements a number of other typemaps that can be used for generating code in the C/C++ wrappers. You can read about these common typemaps here.

16.4.2 Code generation in Lisp wrappers

A number of custom typemaps have also been added to facilitate the generation of code in the lisp side of the interface. These are described below. The basic code generation structure is applied as a series of nested expressions, one for each parameter, then one for manipulating the return value, and last, the foreign function call itself.

Note that the typemaps below use fully qualified symbols where necessary. Users writing their own typemaps should do likewise. See the explanation in the last paragraph of 16.3.1 Namespaces for details.

16.4.2.1 LIN Typemap

The LIN typemap allows for the manipulating the lisp objects passed as arguments to the wrapping defun before passing them to the foreign function call. For example, when passing lisp strings to foreign code, it is often necessary to copy the string into a foreign structure of type (:char *) of appropriate size, and pass this copy to the foreign call. Using the LIN typemap, one could arrange for the stack-allocation of a foreign char array, copy your string into it, and not have to worry about freeing the copy after the function returns.

The LIN typemap accepts the following $variable references.

%typemap(lin)	SWIGTYPE 	"(cl:let (($out $in))\n  $body)";
    

16.4.2.2 LOUT Typemap

The LOUT typemap is the means by which we effect the wrapping of foreign pointers in CLOS instances. It is applied after all LIN typemaps, and immediately before the actual foreign-call.

The LOUT typemap uses the following $variable

%typemap(lout) bool, char, unsigned char, signed char,
               short, signed short, unsigned short,
               int, signed int, unsigned int,
               long, signed long, unsigned long,
               float, double, long double, char *, void *, void,
               enum SWIGTYPE    "$body";
%typemap(lout) SWIGTYPE[ANY], SWIGTYPE *,
               SWIGTYPE &       "(cl:make-instance '$lclass :foreign-address $body)";
%typemap(lout) SWIGTYPE    "(cl:let* ((address $body)\n
                            (ACL_result (cl:make-instance '$lclass :foreign-address address)))\n
                            (cl:unless (cl::zerop address)\n
                            (excl:schedule-finalization ACL_result #'$ldestructor))\n
                             ACL_result)";
    

16.4.2.3 FFITYPE Typemap

The FFITYPE typemap works as a helper for a body of code that converts C/C++ type specifications into Allegro CL foreign-type specifications. These foreign-type specifications appear in ff:def-foreing-type declarations, and in the argument list and return values of ff:def-foreign-calls. You would modify this typemap if you want to change how the FFI passes through arguments of a given type. For example, if you know that a particular compiler represents booleans as a single byte, you might add an entry for:

%typemap(ffitype) bool ":unsigned-char";
    

Note that this typemap is pure type transformation, and is not used in any code generations step the way the LIN and LOUT typemaps are. The default mappings for this typemap are:

%typemap(ffitype) bool ":int";
%typemap(ffitype) char ":char";
%typemap(ffitype) unsigned char ":unsigned-char";
%typemap(ffitype) signed char ":char";
%typemap(ffitype) short, signed short ":short";
%typemap(ffitype) unsigned short ":unsigned-short";
%typemap(ffitype) int, signed int ":int";
%typemap(ffitype) unsigned int ":unsigned-int";
%typemap(ffitype) long, signed long ":long";
%typemap(ffitype) unsigned long ":unsigned-long";
%typemap(ffitype) float ":float";
%typemap(ffitype) double ":double";
%typemap(ffitype) char * "(* :char)";
%typemap(ffitype) void * "(* :void)";
%typemap(ffitype) void ":void";
%typemap(ffitype) enum SWIGTYPE ":int";
%typemap(ffitype) SWIGTYPE & "(* :void)";
    

16.4.2.4 LISPTYPE Typemap

This is another type only transformation map, and is used to provide the lisp-type, which is the optional third argument in argument specifier in a ff:def-foreign-call form. Specifying a lisp-type allows the foreign call to perform type checking on the arguments passed in. The default entries in this typemap are:

%typemap(lisptype) bool "cl:boolean";
%typemap(lisptype) char "cl:character";
%typemap(lisptype) unsigned char "cl:integer";
%typemap(lisptype) signed char "cl:integer";
    

16.4.2.5 LISPCLASS Typemap

The LISPCLASS typemap is used to generate the method signatures for the generic-functions which wrap overloaded functions and functions with defaulted arguments. The default entries are:

%typemap(lispclass) bool "t";
%typemap(lispclass) char "cl:character";
%typemap(lispclass) unsigned char, signed char,
                    short, signed short, unsigned short,
                    int, signed int, unsigned int,
                    long, signed long, unsigned long,
                    enum SWIGTYPE       "cl:integer";
%typemap(lispclass) float "cl:single-float";
%typemap(lispclass) double "cl:double-float";
%typemap(lispclass) char * "cl:string";
    

16.4.3 Modifying SWIG behavior using typemaps

The following example shows how we made use of the above typemaps to add support for the wchar_t type.

%typecheck(SWIG_TYPECHECK_UNICHAR) wchar_t { $1 = 1; };

%typemap(in)        wchar_t "$1 = $input;";
%typemap(lin)       wchar_t "(cl:let (($out (cl:char-code $in)))\n  $body)";
%typemap(lin)       wchar_t* "(excl:with-native-string
                                         ($out $in
                                          :external-format #+little-endian :fat-le 
                                                           #-little-endian :fat)\n
                                 $body)"

%typemap(out)       wchar_t "$result = $1;";
%typemap(lout)      wchar_t "(cl:code-char $body)";
%typemap(lout)      wchar_t* "(excl:native-to-string $body
                                          :external-format #+little-endian :fat-le
                                                           #-little-endian :fat)";

%typemap(ffitype)   wchar_t ":unsigned-short";
%typemap(lisptype)  wchar_t "";
%typemap(ctype)     wchar_t "wchar_t";
%typemap(lispclass) wchar_t "cl:character";
%typemap(lispclass) wchar_t* "cl:string";
    

16.5 Identifier Converter functions

16.5.1 Creating symbols in the lisp environment

Various symbols must be generated in the lisp environment to which class definitions, functions, constants, variables, etc. must be bound. Rather than force a particular convention for naming these symbols, an identifier (to symbol) conversion function is used. A user-defined identifier-converter can then implement any symbol naming, case-modifying, scheme desired.

In generated SWIG code, whenever some interface object must be referenced by its lisp symbol, a macro is inserted that calls the identifier-converter function to generate the appropriate symbol reference. It is therefore expected that the identifier-converter function reliably return the same (eq) symbol given the same set of arguments.

16.5.2 Existing identifier-converter functions

Two basic identifier routines have been defined.

16.5.2.1 identifier-convert-null

No modification of the identifier string is performed. Based on other arguments, the identifier may be concatenated with other strings, from which a symbol will be created.

16.5.2.2 identifier-convert-lispify

All underscores in the identifier string are converted to hyphens. Otherwise, identifier-convert-lispify performs the same symbol transformations.

16.5.2.3 Default identifier to symbol conversions

Check the definitions of the above two default identifier-converters in Lib/allegrocl/allegrocl.swg for default naming conventions.

16.5.3 Defining your own identifier-converter

A user-defined identifier-converter function should conform to the following specification:

(defun identifier-convert-fn (id &key type class arity) ...body...)
result ==> symbol or (setf symbol)

The ID argument is a string representing an identifier in the foreign environment.

The :type keyword argument provides more information on the type of identifier. It's value is a symbol. This allows the identifier-converter to apply different heuristics when mapping different types of identifiers to symbols. SWIG will generate calls to your identifier-converter using the following types.

The :class keyword argument is a string naming a foreign class. When non-nil, it indicates that the current identifier has scope in the specified class.

The :arity keyword argument only appears in swig:swig-defmethod forms generated for overloaded functions. It's value is an integer indicating the number of arguments passed to the routine indicated by this identifier.

16.5.4 Instructing SWIG to use a particular identifier-converter

By default, SWIG will use identifier-converter-null. To specify another convert function, use the -identifier-converter command-line argument. The value should be a string naming the function you wish the interface to use instead, when generating symbols. ex:

% swig -allegrocl -c++ -module mymodule -identifier-converter my-identifier-converter

17 SWIG and C#

17.1 Introduction

The purpose of the C# module is to offer an automated way of accessing existing C/C++ code from .NET languages. The wrapper code implementation uses C# and the Platform Invoke (PInvoke) interface to access natively compiled C/C++ code. The PInvoke interface has been chosen over Microsoft's Managed C++ interface as it is portable to both Microsoft Windows and non-Microsoft platforms. PInvoke is part of the ECMA/ISO C# specification. It is also better suited for robust production environments due to the Managed C++ flaw called the Mixed DLL Loading Problem. Swig C# works equally well on non-Microsoft operating systems such as Linux, Solaris and Apple Mac using Mono and Portable.NET.

To get the most out of this chapter an understanding of interop is required. The Microsoft Developer Network (MSDN) has a good reference guide in a section titled "Interop Marshaling". Monodoc, available from the Mono project, has a very useful section titled Interop with native libraries.

17.2 Differences to the Java module

The C# module is very similar to the Java module, so until some more complete documentation has been written, please use the Java documentation as a guide to using SWIG with C#. The C# module has the same major SWIG features as the Java module. The rest of this section should be read in conjunction with the Java documentation as it lists the main differences. The most notable differences to Java are the following:

$dllimport
This is a C# only special variable that can be used in typemaps, pragmas, features etc. The special variable will get translated into the value specified by the -dllimport commandline option if specified, otherwise it is equivalent to the $module special variable.

$imclassname
This special variable expands to the intermediary class name. For C# this is usually the same as '$modulePINVOKE' ('$moduleJNI' for Java), unless the imclassname attribute is specified in the %module directive.

The directory Examples/csharp has a number of simple examples. Visual Studio .NET 2003 solution and project files are available for compiling with the Microsoft .NET C# compiler on Windows. If your SWIG installation went well on a Unix environment and your C# compiler was detected, you should be able to type make in each example directory, then ilrun runme.exe (Portable.NET C# compiler) or mono runme.exe (Mono C# compiler) to run the examples. Windows users can also get the examples working using a Cygwin or MinGW environment for automatic configuration of the example makefiles. Any one of the three C# compilers (Portable.NET, Mono or Microsoft) can be detected from within a Cygwin or Mingw environment if installed in your path.

17.3 C# Exceptions

It is possible to throw a C# Exception from C/C++ code. SWIG already provides the framework for throwing C# exceptions if it is able to detect that a C++ exception could be thrown. Automatically detecting that a C++ exception could be thrown is only possible when a C++ exception specification is used, see Exception specifications. The Exception handling with %exception section details the %exception feature. Customised code for handling exceptions with or without a C++ exception specification is possible and the details follow. However anyone wishing to do this should be familiar with the contents of the sections referred to above.

Unfortunately a C# exception cannot simply be thrown from unmanaged code for a variety of reasons. Most notably being that throwing a C# exception results in exceptions being thrown across the C PInvoke interface and C does not understand exceptions. The design revolves around a C# exception being constructed and stored as a pending exception, to be thrown only when the unmanaged code has completed. Implementing this is a tad involved and there are thus some unusual typemap constructs. Some practical examples follow and they should be read in conjunction with the rest of this section.

First some details about the design that must be followed. Each typemap or feature that generates unmanaged code supports an attribute called canthrow. This is simply a flag which when set indicates that the code in the typemap/feature has code which might want to throw a C# exception. The code in the typemap/feature can then raise a C# exception by calling one of the C functions, SWIG_CSharpSetPendingException() or SWIG_CSharpSetPendingExceptionArgument(). When called, the function makes a callback into the managed world via a delegate. The callback creates and stores an exception ready for throwing when the unmanaged code has finished. The typemap/feature unmanaged code is then expected to force an immediate return from the unmanaged wrapper function, so that the pending managed exception can then be thrown. The support code has been carefully designed to be efficient as well as thread-safe. However to achieve the goal of efficiency requires some optional code generation in the managed code typemaps. Code to check for pending exceptions is generated if and only if the unmanaged code has code to set a pending exception, that is if the canthrow attribute is set. The optional managed code is generated using the excode typemap attribute and $excode special variable in the relevant managed code typemaps. Simply, if any relevant unmanaged code has the canthrow attribute set, then any occurrences of $excode is replaced with the code in the excode attribute. If the canthrow attribute is not set, then any occurrences of $excode are replaced with nothing.

The prototypes for the SWIG_CSharpSetPendingException() and SWIG_CSharpSetPendingExceptionArgument() functions are

static void SWIG_CSharpSetPendingException(SWIG_CSharpExceptionCodes code,
                                           const char *msg);

static void SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpExceptionArgumentCodes code,
                                                   const char *msg,
                                                   const char *param_name);

The first parameter defines which .NET exceptions can be thrown:

typedef enum {
  SWIG_CSharpApplicationException,
  SWIG_CSharpArithmeticException,
  SWIG_CSharpDivideByZeroException,
  SWIG_CSharpIndexOutOfRangeException,
  SWIG_CSharpInvalidOperationException,
  SWIG_CSharpIOException,
  SWIG_CSharpNullReferenceException,
  SWIG_CSharpOutOfMemoryException,
  SWIG_CSharpOverflowException,
  SWIG_CSharpSystemException
} SWIG_CSharpExceptionCodes;

typedef enum {
  SWIG_CSharpArgumentException,
  SWIG_CSharpArgumentNullException,
  SWIG_CSharpArgumentOutOfRangeException,
} SWIG_CSharpExceptionArgumentCodes;

where, for example, SWIG_CSharpApplicationException corresponds to the .NET exception, ApplicationException. The msg and param_name parameters contain the C# exception message and parameter name associated with the exception.

The %exception feature in C# has the canthrow attribute set. The %csnothrowexception feature is like %exception, but it does not have the canthrow attribute set so should only be used when a C# exception is not created.

17.3.1 C# exception example using "check" typemap

Lets say we have the following simple C++ method:

void positivesonly(int number);

and we want to check that the input number is always positive and if not throw a C# ArgumentOutOfRangeException. The "check" typemap is designed for checking input parameters. Below you will see the canthrow attribute is set because the code contains a call to SWIG_CSharpSetPendingExceptionArgument(). The full example follows:

%module example

%typemap(check, canthrow=1) int number %{
if ($1 < 0) {
  SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentOutOfRangeException,
                                         "only positive numbers accepted", "number");
  return $null;
}
// SWIGEXCODE is a macro used by many other csout typemaps
%define SWIGEXCODE
 "\n    if ($modulePINVOKE.SWIGPendingException.Pending)"
 "\n      throw $modulePINVOKE.SWIGPendingException.Retrieve();"
%enddef
%typemap(csout, excode=SWIGEXCODE) void {
    $imcall;$excode
  }
%}

%inline %{

void positivesonly(int number) {
}

%}

When the following C# code is executed:

public class runme {
    static void Main() {
      example.positivesonly(-1);
    }
}

The exception is thrown:

Unhandled Exception: System.ArgumentOutOfRangeException: only positive numbers accepted
Parameter name: number
in <0x00034> example:positivesonly (int)
in <0x0000c> runme:Main ()

Now let's analyse the generated code to gain a fuller understanding of the typemaps. The generated unmanaged C++ code is:

SWIGEXPORT void SWIGSTDCALL CSharp_positivesonly(int jarg1) {
    int arg1 ;
    
    arg1 = (int)jarg1; 
    
    if (arg1 < 0) {
        SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentOutOfRangeException,
                                               "only positive numbers accepted", "number");
        return ;
    }
    
    positivesonly(arg1);
    
}

This largely comes from the "check" typemap. The managed code in the module class is:

public class example {
  public static void positivesonly(int number) {
    examplePINVOKE.positivesonly(number);
    if (examplePINVOKE.SWIGPendingException.Pending)
      throw examplePINVOKE.SWIGPendingException.Retrieve();
  }

}

This comes largely from the "csout" typemap.

The "csout" typemap is the same as the default void "csout" typemap so is not strictly necessary for the example. However, it is shown to demonstrate what managed output code typemaps should contain, that is, a $excode special variable and an excode attribute. Also note that $excode is expanded into the code held in the excode attribute. The $imcall as always expands into examplePINVOKE.positivesonly(number). The exception support code in the intermediary class, examplePINVOKE, is not shown, but is contained within the inner classes, SWIGPendingException and SWIGExceptionHelper and is always generated. These classes can be seen in any of the generated wrappers. However, all that is required of a user is as demonstrated in the "csin" typemap above. That is, is to check SWIGPendingException.Pending and to throw the exception returned by SWIGPendingException.Retrieve().

If the "check" typemap did not exist, then the following module class would instead be generated:

public class example {
  public static void positivesonly(int number) {
    examplePINVOKE.positivesonly(number);
  }

}

Here we see the pending exception checking code is omitted. In fact, the code above would be generated if the canthrow attribute was not in the "check" typemap, such as:

%typemap(check) int number %{
if ($1 < 0) {
  SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentOutOfRangeException,
                                         "only positive numbers accepted", "number");
  return $null;
}
%}

Note that if SWIG detects you have used SWIG_CSharpSetPendingException() or SWIG_CSharpSetPendingExceptionArgument() without setting the canthrow attribute you will get a warning message similar to

example.i:21: Warning(845): Unmanaged code contains a call to a SWIG_CSharpSetPendingException
method and C# code does not handle pending exceptions via the canthrow attribute.

Actually it will issue this warning for any function beginning with SWIG_CSharpSetPendingException.

17.3.2 C# exception example using %exception

Let's consider a similar, but more common example that throws a C++ exception from within a wrapped function. We can use %exception as mentioned in Exception handling with %exception .

%exception negativesonly(int value) %{
try {
  $action
} catch (std::out_of_range e) {
  SWIG_CSharpSetPendingException(SWIG_CSharpApplicationException, e.what());
}
%}

%inline %{
#include <stdexcept>
void negativesonly(int value) {
  if (value >= 0)
    throw std::out_of_range("number should be negative");
}
%}

The generated unmanaged code this time catches the C++ exception and converts it into a C# ApplicationException.

SWIGEXPORT void SWIGSTDCALL CSharp_negativesonly(int jarg1) {
    int arg1 ;
    
    arg1 = (int)jarg1; 
    
    try {
        negativesonly(arg1);
        
    } catch (std::out_of_range e) {
        SWIG_CSharpSetPendingException(SWIG_CSharpApplicationException, e.what());
        return ;
    }
    
}

The managed code generated does check for the pending exception as mentioned earlier as the C# version of %exception has the canthrow attribute set by default:

  public static void negativesonly(int value) {
    examplePINVOKE.negativesonly(value);
    if (examplePINVOKE.SWIGPendingException.Pending)
      throw examplePINVOKE.SWIGPendingException.Retrieve();
  }

17.3.3 C# exception example using exception specifications

When C++ exception specifications are used, SWIG is able to detect that the method might throw an exception. By default SWIG will automatically generate code to catch the exception and convert it into a managed ApplicationException, as defined by the default "throws" typemaps. The following example has a user supplied "throws" typemap which is used whenever an exception specification contains a std::out_of_range, such as the evensonly method below.

%typemap(throws, canthrow=1) std::out_of_range {
  SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentException, $1.what(), NULL);
  return $null;
}

%inline %{
#include <stdexcept>
void evensonly(int input) throw (std::out_of_range) {
  if (input%2 != 0)
    throw std::out_of_range("number is not even");
}
%}

Note that the type for the throws typemap is the type in the exception specification. SWIG generates a try catch block with the throws typemap code in the catch handler.

SWIGEXPORT void SWIGSTDCALL CSharp_evensonly(int jarg1) {
    int arg1 ;
    
    arg1 = (int)jarg1; 
    try {
        evensonly(arg1);
    }
    catch(std::out_of_range &_e) {
      {
          SWIG_CSharpSetPendingExceptionArgument(SWIG_CSharpArgumentException, (&_e)->what(), NULL);
          return ;
      }
    }
    
}

Multiple catch handlers are generated should there be more than one exception specifications declared.

17.3.4 Custom C# ApplicationException example

This example involves a user defined exception. The conventional .NET exception handling approach is to create a custom ApplicationException and throw it in your application. The goal in this example is to convert the STL std::out_of_range exception into one of these custom .NET exceptions.

The default exception handling is quite easy to use as the SWIG_CSharpSetPendingException() and SWIG_CSharpSetPendingExceptionArgument() methods are provided by SWIG. However, for a custom C# exception, the boiler plate code that supports these functions needs replicating. In essence this consists of some C/C++ code and C# code. The C/C++ code can be generated into the wrapper file using the %insert(runtime) directive and the C# code can be generated into the intermediary class using the imclasscode pragma as follows:

%insert(runtime) %{
  // Code to handle throwing of C# CustomApplicationException from C/C++ code.
  // The equivalent delegate to the callback, CSharpExceptionCallback_t, is CustomExceptionDelegate
  // and the equivalent customExceptionCallback instance is customDelegate
  typedef void (SWIGSTDCALL* CSharpExceptionCallback_t)(const char *);
  CSharpExceptionCallback_t customExceptionCallback = NULL;

  extern "C" SWIGEXPORT
  void SWIGSTDCALL CustomExceptionRegisterCallback(CSharpExceptionCallback_t customCallback) {
    customExceptionCallback = customCallback;
  }

  // Note that SWIG detects any method calls named starting with
  // SWIG_CSharpSetPendingException for warning 845
  static void SWIG_CSharpSetPendingExceptionCustom(const char *msg) {
    customExceptionCallback(msg);
  }
%}

%pragma(csharp) imclasscode=%{
  class CustomExceptionHelper {
    // C# delegate for the C/C++ customExceptionCallback
    public delegate void CustomExceptionDelegate(string message);
    static CustomExceptionDelegate customDelegate =
                                   new CustomExceptionDelegate(SetPendingCustomException);

    [DllImport("$dllimport", EntryPoint="CustomExceptionRegisterCallback")]
    public static extern
           void CustomExceptionRegisterCallback(CustomExceptionDelegate customCallback);

    static void SetPendingCustomException(string message) {
      SWIGPendingException.Set(new CustomApplicationException(message));
    }

    static CustomExceptionHelper() {
      CustomExceptionRegisterCallback(customDelegate);
    }
  }
  static CustomExceptionHelper exceptionHelper = new CustomExceptionHelper();
%}

The method stored in the C# delegate instance, customDelegate is what gets called by the C/C++ callback. However, the equivalent to the C# delegate, that is the C/C++ callback, needs to be assigned before any unmanaged code is executed. This is achieved by putting the initialisation code in the intermediary class. Recall that the intermediary class contains all the PInvoke methods, so the static variables in the intermediary class will be initialised before any of the PInvoke methods in this class are called. The exceptionHelper static variable ensures the C/C++ callback is initialised with the value in customDelegate by calling the CustomExceptionRegisterCallback method in the CustomExceptionHelper static constructor. Once this has been done, unmanaged code can make callbacks into the managed world as customExceptionCallback will be initialised with a valid callback/delegate. Any calls to SWIG_CSharpSetPendingExceptionCustom() will make the callback to create the pending exception in the same way that SWIG_CSharpSetPendingException() and SWIG_CSharpSetPendingExceptionArgument() does. In fact the method has been similarly named so that SWIG can issue the warning about missing canthrow attributes as discussed earlier. It is an invaluable warning as it is easy to forget the canthrow attribute when writing typemaps/features.

The SWIGPendingException helper class is not shown, but is generated as an inner class into the intermediary class. It stores the pending exception in Thread Local Storage so that the exception handling mechanism is thread safe.

The boiler plate code above must be used in addition to a handcrafted CustomApplicationException:

// Custom C# Exception
class CustomApplicationException : System.ApplicationException {
  public CustomApplicationException(string message) 
    : base(message) {
  }
}

and the SWIG interface code:

%typemap(throws, canthrow=1) std::out_of_range {
  SWIG_CSharpSetPendingExceptionCustom($1.what());
  return $null;
}

%inline %{
void oddsonly(int input) throw (std::out_of_range) {
  if (input%2 != 1)
    throw std::out_of_range("number is not odd");
}
%}

The "throws" typemap now simply calls our new SWIG_CSharpSetPendingExceptionCustom() function so that the exception can be caught, as such:

try {
  example.oddsonly(2);
} catch (CustomApplicationException e) {
  ...
}

17.4 C# Directors

The SWIG directors feature adds extra code to the generated C# proxy classes that enable these classes to be used in cross-language polymorphism. Essentially, it enables unmanaged C++ code to call back into managed code for virtual methods so that a C# class can derive from a wrapped C++ class.

The following sections provide information on the C# director implementation and contain most of the information required to use the C# directors. However, the Java directors section should also be read in order to gain more insight into directors.

17.4.1 Directors example

Imagine we are wrapping a C++ base class, Base, from which we would like to inherit in C#. Such a class is shown below as well as another class, Caller, which calls the virtual method UIntMethod from pure unmanaged C++ code.

// file: example.h
class Base {
public:
  virtual ~Base() {}

  virtual unsigned int UIntMethod(unsigned int x) {
    std::cout << "Base - UIntMethod(" << x << ")" << std::endl;
    return x;
  }
  virtual void BaseBoolMethod(const Base &b, bool flag) {}
};

class Caller {
public:
  Caller(): m_base(0) {}
  ~Caller() { delBase(); }
  void set(Base *b) { delBase(); m_base = b; }
  void reset() { m_base = 0; }
  unsigned int UIntMethodCall(unsigned int x) { return m_base->UIntMethod(x); }

private:
  Base *m_base;
  void delBase() { delete m_base; m_base = 0; }
};

The director feature is turned off by default and the following simple interface file shows how directors are enabled for the class Base.

/* File : example.i */
%module(directors="1") example
%{
#include "example.h"
%}

%feature("director") Base;

%include "example.h"

The following is a C# class inheriting from Base:

public class CSharpDerived : Base
{
  public override uint UIntMethod(uint x)
  {
    Console.WriteLine("CSharpDerived - UIntMethod({0})", x);
    return x;
  }
}

The Caller class can demonstrate the UIntMethod method being called from unmanaged code using the following C# code:

public class runme
{
  static void Main() 
  {
    Caller myCaller = new Caller();

    // Test pure C++ class
    using (Base myBase = new Base())
    {
      makeCalls(myCaller, myBase);
    }

    // Test director / C# derived class
    using (Base myBase = new CSharpDerived())
    {
      makeCalls(myCaller, myBase);
    }
  }

  static void makeCalls(Caller myCaller, Base myBase)
  {
    myCaller.set(myBase);
    myCaller.UIntMethodCall(123);
    myCaller.reset();
  }
}

If the above is run, the output is then:

Base - UIntMethod(123)
CSharpDerived - UIntMethod(123)

17.4.2 Directors implementation

The previous section demonstrated a simple example where the virtual UIntMethod method was called from C++ code, even when the overridden method is implemented in C#. The intention of this section is to gain an insight into how the director feature works. It shows the generated code for the two virtual methods, UIntMethod and BaseBoolMethod, when the director feature is enabled for the Base class.

Below is the generated C# Base director class.

using System;
using System.Runtime.InteropServices;

public class Base : IDisposable {
  private HandleRef swigCPtr;
  protected bool swigCMemOwn;

  internal Base(IntPtr cPtr, bool cMemoryOwn) {
    swigCMemOwn = cMemoryOwn;
    swigCPtr = new HandleRef(this, cPtr);
  }

  internal static HandleRef getCPtr(Base obj) {
    return (obj == null) ? new HandleRef(null, IntPtr.Zero) : obj.swigCPtr;
  }

  ~Base() {
    Dispose();
  }

  public virtual void Dispose() {
    lock(this) {
      if(swigCPtr.Handle != IntPtr.Zero && swigCMemOwn) {
        swigCMemOwn = false;
        examplePINVOKE.delete_Base(swigCPtr);
      }
      swigCPtr = new HandleRef(null, IntPtr.Zero);
      GC.SuppressFinalize(this);
    }
  }

  public virtual uint UIntMethod(uint x) {
    uint ret = examplePINVOKE.Base_UIntMethod(swigCPtr, x);
    return ret;
  }

  public virtual void BaseBoolMethod(Base b, bool flag) {
    examplePINVOKE.Base_BaseBoolMethod(swigCPtr, Base.getCPtr(b), flag);
    if (examplePINVOKE.SWIGPendingException.Pending)
      throw examplePINVOKE.SWIGPendingException.Retrieve();
  }

  public Base() : this(examplePINVOKE.new_Base(), true) {
    SwigDirectorConnect();
  }

  private void SwigDirectorConnect() {
    if (SwigDerivedClassHasMethod("UIntMethod", swigMethodTypes0))
      swigDelegate0 = new SwigDelegateBase_0(SwigDirectorUIntMethod);
    if (SwigDerivedClassHasMethod("BaseBoolMethod", swigMethodTypes1))
      swigDelegate1 = new SwigDelegateBase_1(SwigDirectorBaseBoolMethod);
    examplePINVOKE.Base_director_connect(swigCPtr, swigDelegate0, swigDelegate1);
  }

  private bool SwigDerivedClassHasMethod(string methodName, Type[] methodTypes) {
    System.Reflection.MethodInfo methodInfo = this.GetType().GetMethod(methodName, methodTypes);
    bool hasDerivedMethod = methodInfo.DeclaringType.IsSubclassOf(typeof(Base));
    return hasDerivedMethod;
  }

  private uint SwigDirectorUIntMethod(uint x) {
    return UIntMethod(x);
  }

  private void SwigDirectorBaseBoolMethod(IntPtr b, bool flag) {
    BaseBoolMethod(new Base(b, false), flag);
  }

  internal delegate uint SwigDelegateBase_0(uint x);
  internal delegate void SwigDelegateBase_1(IntPtr b, bool flag);

  private SwigDelegateBase_0 swigDelegate0;
  private SwigDelegateBase_1 swigDelegate1;

  private static Type[] swigMethodTypes0 = new Type[] { typeof(uint) };
  private static Type[] swigMethodTypes1 = new Type[] { typeof(Base), typeof(bool) };
}

Everything from the SwigDirectorConnect() method and below is code that is only generated when directors are enabled. The design comprises a C# delegate being initialised for each virtual method on construction of the class. Let's examine the BaseBoolMethod.

In the Base constructor a call is made to SwigDirectorConnect() which contains the initialisation code for all the virtual methods. It uses a support method, SwigDerivedClassHasMethod(), which simply uses reflection to determine if the named method, BaseBoolMethod, with the list of required parameter types, exists in a subclass. If it does not exist, the delegate is not initialised as there is no need for unmanaged code to call back into managed C# code. However, if there is an overridden method in any subclass, the delegate is required. It is then initialised to the SwigDirectorBaseBoolMethod which in turn will call BaseBoolMethod if invoked. The delegate is not initialised to the BaseBoolMethod directly as quite often types will need marshalling from the unmanaged type to the managed type in which case an intermediary method (SwigDirectorBaseBoolMethod ) is required for the marshalling. In this case, the C# Base class needs to be created from the unmanaged IntPtr type.

The last thing that SwigDirectorConnect() does is to pass the delegates to the unmanaged code. It calls the intermediary method Base_director_connect() which is really a call to the C function CSharp_Base_director_connect(). This method simply maps each C# delegate onto a C function pointer.

SWIGEXPORT void SWIGSTDCALL CSharp_Base_director_connect(void *objarg, 
                                        SwigDirector_Base::SWIG_Callback0_t callback0,
                                        SwigDirector_Base::SWIG_Callback1_t callback1) {
  Base *obj = (Base *)objarg;
  SwigDirector_Base *director = dynamic_cast<SwigDirector_Base *>(obj);
  if (director) {
    director->swig_connect_director(callback0, callback1);
  }
}

class SwigDirector_Base : public Base, public Swig::Director {
public:
    SwigDirector_Base();
    virtual unsigned int UIntMethod(unsigned int x);
    virtual ~SwigDirector_Base();
    virtual void BaseBoolMethod(Base const &b, bool flag);

    typedef unsigned int (SWIGSTDCALL* SWIG_Callback0_t)(unsigned int);
    typedef void (SWIGSTDCALL* SWIG_Callback1_t)(void *, unsigned int);
    void swig_connect_director(SWIG_Callback0_t callbackUIntMethod, 
                               SWIG_Callback1_t callbackBaseBoolMethod);

private:
    SWIG_Callback0_t swig_callbackUIntMethod;
    SWIG_Callback1_t swig_callbackBaseBoolMethod;
    void swig_init_callbacks();
};

void SwigDirector_Base::swig_connect_director(SWIG_Callback0_t callbackUIntMethod, 
                                              SWIG_Callback1_t callbackBaseBoolMethod) {
  swig_callbackUIntMethod = callbackUIntMethod;
  swig_callbackBaseBoolMethod = callbackBaseBoolMethod;
}

Note that for each director class SWIG creates an unmanaged director class for making the callbacks. For example Base has SwigDirector_Base and SwigDirector_Base is derived from Base. Should a C# class be derived from Base, the underlying C++ SwigDirector_Base is created rather than Base. The SwigDirector_Base class then implements all the virtual methods, redirecting calls up to managed code if the callback/delegate is non-zero. The implementation of SwigDirector_Base::BaseBoolMethod shows this - the callback is made by invoking the swig_callbackBaseBoolMethod function pointer:

void SwigDirector_Base::BaseBoolMethod(Base const &b, bool flag) {
  void * jb = 0 ;
  unsigned int jflag  ;
  
  if (!swig_callbackBaseBoolMethod) {
    Base::BaseBoolMethod(b,flag);
    return;
  } else {
    jb = (Base *) &b; 
    jflag = flag;
    swig_callbackBaseBoolMethod(jb, jflag);
  }
}

17.4.3 Director caveats

There are a few gotchas with directors. The first is that the base class virtual method should not be called directly otherwise a stack overflow will occur due to recursive calls. This might be fixed in a future version of SWIG, but is likely to slow down virtual methods calls. For example, given Base as a director enabled class:

class Base {
public:
  virtual ~Base();
  virtual unsigned int UIntMethod(unsigned int x);
};

Do not directly call the base method from a C# derived class:

public class CSharpDerived : Base
{
  public override uint UIntMethod(uint x)
  {
    return base.UIntMethod(x);
  }
}

Secondly, if default parameters are used, it is recommended to follow a pattern of always calling a single method in any C# derived class. An example will clarify this and the reasoning behind the recommendation. Consider the following C++ class wrapped as a director class:

class Defaults {
public:
  virtual ~Defaults();
  virtual void DefaultMethod(int a=-100);
};

Recall that C++ methods with default parameters generate overloaded methods for each defaulted parameter, so a C# derived class can be created with two DefaultMethod override methods:

public class CSharpDefaults : Defaults
{
  public override void DefaultMethod()
  {
    DefaultMethod(-100); // note C++ default value used
  }
  public override void DefaultMethod(int x)
  {
  }
}

It may not be clear at first, but should a user intend to call CSharpDefaults.DefaultMethod() from C++, a call is actually made to CSharpDefaults.DefaultMethod(int). This is because the initial call is made in C++ and therefore the DefaultMethod(int) method will be called as is expected with C++ calls to methods with defaults, with the default being set to -100. The callback/delegate matching this method is of course the overloaded method DefaultMethod(int). However, a call from C# to CSharpDefaults.DefaultMethod() will of course call this exact method and in order for behaviour to be consistent with calls from C++, the implementation should pass the call on to CSharpDefaults.DefaultMethod(int)using the C++ default value, as shown above.

17.5 C# Typemap examples

This section includes a few examples of typemaps. For more examples, you might look at the files "csharp.swg" and "typemaps.i " in the SWIG library.

17.5.1 Memory management when returning references to member variables

This example shows how to prevent premature garbage collection of objects when the underlying C++ class returns a pointer or reference to a member variable. The example is a direct equivalent to this Java equivalent.

Consider the following C++ code:

struct Wheel {
  int size;
  Wheel(int sz) : size(sz) {}
};

class Bike {
  Wheel wheel;
public:
  Bike(int val) : wheel(val) {}
  Wheel& getWheel() { return wheel; }
};

and the following usage from C# after running the code through SWIG:

      Wheel wheel = new Bike(10).getWheel();
      Console.WriteLine("wheel size: " + wheel.size);
      // Simulate a garbage collection
      System.GC.Collect();
      System.GC.WaitForPendingFinalizers();
      Console.WriteLine("wheel size: " + wheel.size);

Don't be surprised that if the resulting output gives strange results such as...

wheel size: 10
wheel size: 135019664

What has happened here is the garbage collector has collected the Bike instance as it doesn't think it is needed any more. The proxy instance, wheel, contains a reference to memory that was deleted when the Bike instance was collected. In order to prevent the garbage collector from collecting the Bike instance a reference to the Bike must be added to the wheel instance. You can do this by adding the reference when the getWheel() method is called using the following typemaps.

%typemap(cscode) Wheel %{
  // Ensure that the GC doesn't collect any Bike instance set from C#
  private Bike bikeReference;
  internal void addReference(Bike bike) {
    bikeReference = bike;
  }
%}

// Add a C# reference to prevent premature garbage collection and resulting use
// of dangling C++ pointer. Intended for methods that return pointers or
// references to a member variable.
%typemap(csout, excode=SWIGEXCODE) Wheel& getWheel {
    IntPtr cPtr = $imcall;$excode
    $csclassname ret = null;
    if (cPtr != IntPtr.Zero) {
      ret = new $csclassname(cPtr, $owner);
      ret.addReference(this);
    }
    return ret;
  }

The code in the first typemap gets added to the Wheel proxy class. The code in the second typemap constitutes the bulk of the code in the generated getWheel() function:

public class Wheel : IDisposable {
  ...
  // Ensure that the GC doesn't collect any Bike instance set from C#
  private Bike bikeReference;
  internal void addReference(Bike bike) {
    bikeReference = bike;
  }
}

public class Bike : IDisposable {
  ...
  public Wheel getWheel() {
    IntPtr cPtr = examplePINVOKE.Bike_getWheel(swigCPtr);
    Wheel ret = null;
    if (cPtr != IntPtr.Zero) {
      ret = new Wheel(cPtr, false);
      ret.addReference(this);
    }
    return ret;
  }
}

Note the addReference call.

17.5.2 Memory management for objects passed to the C++ layer

The example is a direct equivalent to this Java equivalent. Managing memory can be tricky when using C++ and C# proxy classes. The previous example shows one such case and this example looks at memory management for a class passed to a C++ method which expects the object to remain in scope after the function has returned. Consider the following two C++ classes:

struct Element {
  int value;
  Element(int val) : value(val) {}
};
class Container {
  Element* element;
public:
  Container() : element(0) {}
  void setElement(Element* e) { element = e; }
  Element* getElement() { return element; }
};

and usage from C++

    Container container;
    Element element(20);
    container.setElement(&element);
    cout << "element.value: " << container.getElement()->value << endl;

and more or less equivalent usage from C#

      Container container = new Container();
      Element element = new Element(20);
      container.setElement(element);

The C++ code will always print out 20, but the value printed out may not be this in the C# equivalent code. In order to understand why, consider a garbage collection occuring...

      Container container = new Container();
      Element element = new Element(20);
      container.setElement(element);
      Console.WriteLine("element.value: " + container.getElement().value);
      // Simulate a garbage collection
      System.GC.Collect();
      System.GC.WaitForPendingFinalizers();
      Console.WriteLine("element.value: " + container.getElement().value);

The temporary element created with new Element(20) could get garbage collected which ultimately means the container variable is holding a dangling pointer, thereby printing out any old random value instead of the expected value of 20. One solution is to add in the appropriate references in the C# layer...

public class Container : IDisposable {

  ...

  // Ensure that the GC doesn't collect any Element set from C#
  // as the underlying C++ class stores a shallow copy
  private Element elementReference;
  private HandleRef getCPtrAndAddReference(Element element) {
    elementReference = element;
    return Element.getCPtr(element);
  }

  public void setElement(Element e) {
    examplePINVOKE.Container_setElement(swigCPtr, getCPtrAndAddReference(e));
  }
}

The following typemaps will generate the desired code. The 'csin' typemap matches the input parameter type for the setElement method. The 'cscode' typemap simply adds in the specified code into the C# proxy class.

%typemap(csin) Element *e "getCPtrAndAddReference($csinput)"

%typemap(cscode) Container %{
  // Ensure that the GC doesn't collect any Element set from C#
  // as the underlying C++ class stores a shallow copy
  private Element elementReference;
  private HandleRef getCPtrAndAddReference(Element element) {
    elementReference = element;
    return Element.getCPtr(element);
  }
%}

18 SWIG and Chicken

This chapter describes SWIG's support of CHICKEN. CHICKEN is a Scheme-to-C compiler supporting most of the language features as defined in the Revised^5 Report on Scheme. Its main attributes are that it

  1. generates portable C code
  2. includes a customizable interpreter
  3. links to C libraries with a simple Foreign Function Interface
  4. supports full tail-recursion and first-class continuations

When confronted with a large C library, CHICKEN users can use SWIG to generate CHICKEN wrappers for the C library. However, the real advantages of using SWIG with CHICKEN are its support for C++ -- object-oriented code is difficult to wrap by hand in CHICKEN -- and its typed pointer representation, essential for C and C++ libraries involving structures or classes.

18.1 Preliminaries

CHICKEN support was introduced to SWIG in version 1.3.18. SWIG relies on some recent additions to CHICKEN, which are only present in releases of CHICKEN with version number greater than or equal to 1.89. To use a chicken version between 1.40 and 1.89, see the Garbage collection section below.

You may want to look at any of the examples in Examples/chicken/ or Examples/GIFPlot/Chicken for the basic steps to run SWIG CHICKEN.

18.1.1 Running SWIG in C mode

To run SWIG CHICKEN in C mode, use the -chicken option.

% swig -chicken example.i

To allow the wrapper to take advantage of future CHICKEN code generation improvements, part of the wrapper is direct CHICKEN function calls (example_wrap.c) and part is CHICKEN Scheme ( example.scm). The basic Scheme code must be compiled to C using your system's CHICKEN compiler or both files can be compiled directly using the much simpler csc.

% chicken example.scm -output-file oexample.c

So for the C mode of SWIG CHICKEN, example_wrap.c and oexample.c are the files that must be compiled to object files and linked into your project.

18.1.2 Running SWIG in C++ mode

To run SWIG CHICKEN in C++ mode, use the -chicken -c++ option.

% swig -chicken -c++ example.i

This will generate example_wrap.cxx and example.scm . The basic Scheme code must be compiled to C using your system's CHICKEN compiler or both files can be compiled directly using the much simpler csc.

% chicken example.scm -output-file oexample.c

So for the C++ mode of SWIG CHICKEN, example_wrap.cxx and oexample.c are the files that must be compiled to object files and linked into your project.

18.2 Code Generation

18.2.1 Naming Conventions

Given a C variable, function or constant declaration named Foo_Bar, the declaration will be available in CHICKEN as an identifier ending with Foo-Bar. That is, an underscore is converted to a dash.

You may control what the CHICKEN identifier will be by using the %rename SWIG directive in the SWIG interface file.

18.2.2 Modules

The name of the module must be declared one of two ways:

The generated example.scm file then exports (declare (unit modulename)). If you do not want SWIG to export the (declare (unit modulename)), pass the -nounit option to SWIG.

CHICKEN will be able to access the module using the (declare (uses modulename)) CHICKEN Scheme form.

18.2.3 Constants and Variables

Constants may be created using any of the four constructs in the interface file:

  1. #define MYCONSTANT1 ...
  2. %constant int MYCONSTANT2 = ...
  3. const int MYCONSTANT3 = ...
  4. enum { MYCONSTANT4 = ... };

In all cases, the constants may be accessed from within CHICKEN using the form (MYCONSTANT1); that is, the constants may be accessed using the read-only parameter form.

Variables are accessed using the full parameter form. For example, to set the C variable "int my_variable;", use the Scheme form (my-variable 2345). To get the C variable, use (my-variable) .

The %feature("constasvar") can be applied to any constant or immutable variable. Instead of exporting the constant as a function that must be called, the constant will appear as a scheme variable. This causes the generated .scm file to just contain the code (set! MYCONSTANT1 (MYCONSTANT1)). See Features and the %feature directive for info on how to apply the %feature.

18.2.4 Functions

C functions declared in the SWIG interface file will have corresponding CHICKEN Scheme procedures. For example, the C function "int sqrt(double x);" will be available using the Scheme form (sqrt 2345.0). A void return value will give C_SCHEME_UNDEFINED as a result.

A function may return more than one value by using the OUTPUT specifier (see Lib/chicken/typemaps.i). They will be returned as multiple values using (values) if there is more than one result (that is, a non-void return value and at least one argout parameter, or a void return value and at least two argout parameters). The return values can then be accessed with (call-with-values) .

18.2.5 Exceptions

The SWIG chicken module has support for exceptions thrown from C or C++ code to be caught in scheme. See Exception handling with %exception for more information about declaring exceptions in the interface file.

Chicken supports both the SWIG_exception(int code, const char *msg) interface as well as a SWIG_ThrowException(C_word val) function for throwing exceptions from inside the %exception blocks. SWIG_exception will throw a list consisting of the code (as an integer) and the message. Both of these will throw an exception using (abort), which can be handled by (handle-exceptions). See Chicken manual on Exceptions and SFRI-12. Since the exception values are thrown directly, if (condition-case) is used to catch an exception the exception will come through in the val () case.

The following simple module

%module exception_test

%inline %{
  void test_throw(int i) throws (int) { 
    if (i == 1) throw 15; 
  }
%}

could be run with

(handle-exceptions exvar 
  (if (= exvar 15)
    (print "Correct!") 
    (print "Threw something else " exvar))
  (test-throw 1))

18.3 TinyCLOS

The author of TinyCLOS, Gregor Kiczales, describes TinyCLOS as: "Tiny CLOS is a Scheme implementation of a `kernelized' CLOS, with a metaobject protocol. The implementation is even simpler than the simple CLOS found in `The Art of the Metaobject Protocol,' weighing in at around 850 lines of code, including (some) comments and documentation."

Almost all good Scheme books describe how to use metaobjects and generic procedures to implement an object-oriented Scheme system. Please consult a Scheme book if you are unfamiliar with the concept.

CHICKEN has a modified version of TinyCLOS, which SWIG CHICKEN uses if the -proxy argument is given. If -proxy is passed, then the generated example.scm file will contain TinyCLOS class definitions. A class named Foo is declared as <Foo>, and each member variable is allocated a slot. Member functions are exported as generic functions.

Primitive symbols and functions (the interface that would be presented if -proxy was not passed) are hidden and no longer accessible. If the -unhideprimitive command line argument is passed to SWIG, then the primitive symbols will be available, but each will be prefixed by the string "primitive:"

The exported symbol names can be controlled with the -closprefix and -useclassprefix arguments. If -useclassprefix is passed to SWIG, every member function will be generated with the class name as a prefix. If the -closprefix mymod: argument is passed to SWIG, then the exported functions will be prefixed by the string "mymod:". If -useclassprefix is passed, -closprefix is ignored.

18.4 Linkage

Please refer to CHICKEN - A practical and portable Scheme system - User's manual for detailed help on how to link object files to create a CHICKEN Scheme program. Briefly, to link object files, be sure to add `chicken-config -extra-libs -libs` or `chicken-config -shared -extra-libs -libs`to your linker options. Use the -shared option if you want to create a dynamically loadable module. You might also want to use the much simpler csc or csc.bat.

Each scheme file that is generated by SWIG contains (declare (uses modname)). This means that to load the module from scheme code, the code must include (declare (uses modname )).

18.4.1 Static binary or shared library linked at compile time

We can easily use csc to build a static binary.

$ swig -chicken example.i
$ csc -v example.scm example_impl.c example_wrap.c test_script.scm -o example
$ ./example

Similar to the above, any number of module.scm files could be compiled into a shared library, and then that shared library linked when compiling the main application.

$ swig -chicken example.i
$ csc -sv example.scm example_wrap.c example_impl.c -o example.so

The example.so file can then linked with test_script.scm when it is compiled, in which case test_script.scm must have (declare (uses example)). Multiple SWIG modules could have been linked into example.so and each one accessed with a (declare (uses ... )).

$ csc -v test_script.scm -lexample

An alternative is that the test_script.scm can have the code (load-library 'example "example.so"), in which case the test script does not need to be linked with example.so. The test_script.scm file can then be run with csi.

18.4.2 Building chicken extension libraries

Building a shared library like in the above section only works if the library is linked at compile time with a script containing (declare (uses ...)) or is loaded explicitly with (load-library 'example "example.so"). It is not the format that CHICKEN expects for extension libraries and eggs. The problem is the (declare (unit modname)) inside the modname.scm file. There are two possible solutions to this.

First, SWIG accepts a -nounit argument, in which case the (declare (unit modname)) is not generated. Then, the modname.scm and modname_wrap.c files must be compiled into their own shared library.

$ csc -sv modname.scm modname_wrap.c modname_impl.c -o modname.so

This library can then be loaded by scheme code with the (require 'modname) function. See Loading-extension-libraries in the eval unit inside the CHICKEN manual for more information.

Another alternative is to run SWIG normally and create a scheme file that contains (declare (uses modname)) and then compile that file into the shared library as well. For example, inside the mod_load.scm file,

(declare (uses mod1))
(declare (uses mod2))

Which would then be compiled with

$ swig -chicken mod1.i
$ swig -chicken mod2.i
$ csc -sv mod_load.scm mod1.scm mod2.scm mod1_wrap.c mod2_wrap.c mod1_impl.c mod2_impl.c -o mod.so

Then the extension library can be loaded with (require 'mod) . As we can see here, mod_load.scm contains the code that gets executed when the module is loaded. All this code does is load both mod1 and mod2. As we can see, this technique is more useful when you want to combine a few SWIG modules into one chicken extension library, especially if modules are related by %import

In either method, the files that are compiled into the shared library could also be packaged into an egg. The mod1_wrap.c and mod2_wrap.c files that are created by SWIG are stand alone and do not need SWIG to be installed to be compiled. Thus the egg could be distributed and used by anyone, even if SWIG is not installed.

See the Examples/chicken/egg directory in the SWIG source for an example that builds two eggs, one using the first method and one using the second method.

18.4.3 Linking multiple SWIG modules with TinyCLOS

Linking together multiple modules that share type information using the %import directive while also using -proxy is more complicated. For example, if mod2.i imports mod1.i , then the mod2.scm file contains references to symbols declared in mod1.scm, and thus a (declare (uses mod1 )) or (require 'mod1) must be exported to the top of mod2.scm. By default, when SWIG encounters an %import "modname.i" directive, it exports (declare (uses modname)) into the scm file. This works fine unless mod1 was compiled with the -nounit argument or was compiled into an extension library with other modules under a different name.

One option is to override the automatic generation of (declare (uses mod1)) by passing the -noclosuses option to SWIG when compiling mod2.i. SWIG then provides the %insert(closprefix) %{ %} directive. Any scheme code inside that directive is inserted into the generated .scm file, and if mod1 was compiled with -nounit, the directive should contain (require 'mod1). This option allows for mixed loading as well, where some modules are imported with (declare (uses modname )) (which means they were compiled without -nounit) and some are imported with (require 'modname).

The other option is to use the second idea in the above section. Compile all the modules normally, without any %insert(closprefix) , -nounit, or -noclosuses. Then the modules will import each other correctly with (declare (uses ...)). To create an extension library or an egg, just create a module_load.scm file that (declare (uses ...)) all the modules.

18.5 Typemaps

The Chicken module handles all types via typemaps. This information is read from Lib/chicken/typemaps.i and Lib/chicken/chicken.swg.

18.6 Pointers

For pointer types, SWIG uses CHICKEN tagged pointers. A tagged pointer is an ordinary CHICKEN pointer with an extra slot for a void *. With SWIG CHICKEN, this void * is a pointer to a type-info structure. So each pointer used as input or output from the SWIG-generated CHICKEN wrappers will have type information attached to it. This will let the wrappers correctly determine which method should be called according to the object type hierarchy exposed in the SWIG interface files.

To construct a Scheme object from a C pointer, the wrapper code calls the function SWIG_NewPointerObj(void *ptr, swig_type_info *type, int owner), The function that calls SWIG_NewPointerObj must have a variable declared C_word *known_space = C_alloc(C_SIZEOF_SWIG_POINTER); It is ok to call SWIG_NewPointerObj more than once, just make sure known_space has enough space for all the created pointers.

To get the pointer represented by a CHICKEN tagged pointer, the wrapper code calls the function SWIG_ConvertPtr(C_word s, void **result, swig_type_info *type, int flags), passing a pointer to a struct representing the expected pointer type. flags is either zero or SWIG_POINTER_DISOWN (see below).

18.6.1 Garbage collection

If the owner flag passed to SWIG_NewPointerObj is 1, NewPointerObj will add a finalizer to the type which will call the destructor or delete method of that type. The destructor and delete functions are no longer exported for use in scheme code, instead SWIG and chicken manage pointers. In situations where SWIG knows that a function is returning a type that should be garbage collected, SWIG will automatically set the owner flag to 1. For other functions, the %newobject directive must be specified for functions whose return values should be garbage collected. See Object ownership and %newobject for more information.

In situations where a C or C++ function will assume ownership of a pointer, and thus chicken should no longer garbage collect it, SWIG provides the DISOWN input typemap. After applying this typemap (see the Typemaps chapter for more information on how to apply typemaps), any pointer that gets passed in will no longer be garbage collected. An object is disowned by passing the SWIG_POINTER_DISOWN flag to SWIG_ConvertPtr . Warning: Since the lifetime of the object is now controlled by the underlying code, the object might get deleted while the scheme code still holds a pointer to it. Further use of this pointer can lead to a crash.

Adding a finalizer function from C code was added to chicken in the 1.89 release, so garbage collection does not work for chicken versions below 1.89. If you would like the SWIG generated code to work with chicken 1.40 to 1.89, pass the -nocollection argument to SWIG. This will not export code inside the _wrap.c file to register finalizers, and will then export destructor functions which must be called manually.

18.7 Unsupported features and known problems

18.7.1 TinyCLOS problems with Chicken version <= 1.92

In Chicken versions equal to or below 1.92, TinyCLOS has a limitation such that generic methods do not properly work on methods with different number of specializers: TinyCLOS assumes that every method added to a generic function will have the same number of specializers. SWIG generates functions with different lengths of specializers when C/C++ functions are overloaded. For example, the code

class Foo {};
int foo(int a, Foo *b);
int foo(int a);

will produce scheme code

(define-method (foo (arg0 <top>) (arg1 <Foo>)) (call primitive function))
(define-method (foo (arg0 <top>)) (call primitive function))

Using unpatched TinyCLOS, the second (define-method) will replace the first one, so calling (foo 3 f) will produce an error.

There are three solutions to this. The easist is to upgrade to the latest Chicken version. Otherwise, the file Lib/chicken/tinyclos-multi-generic.patch in the SWIG source contains a patch against tinyclos.scm inside the 1.92 chicken source to add support into TinyCLOS for multi-argument generics. (This patch was accepted into Chicken) This requires chicken to be rebuilt and custom install of chicken. An alternative is the Lib/chicken/multi-generic.scm file in the SWIG source. This file can be loaded after TinyCLOS is loaded, and it will override some functions inside TinyCLOS to correctly support multi-argument generics. Please see the comments at the top of both files for more information.


19 SWIG and Guile

This section details guile-specific support in SWIG.

19.1 Meaning of "Module"

There are three different concepts of "module" involved, defined separately for SWIG, Guile, and Libtool. To avoid horrible confusion, we explicitly prefix the context, e.g., "guile-module".

19.2 Using the SCM or GH Guile API

The guile module can currently export wrapper files that use the guile GH interface or the SCM interface. This is controlled by an argument passed to swig. The "-gh" argument causes swig to output GH code, and the "-scm" argument causes swig to output SCM code. Right now the "-scm" argument is the default. The "-scm" wrapper generation assumes a guile version >= 1.6 and has several advantages over the "-gh" wrapper generation including garbage collection and GOOPS support. The "-gh" wrapper generation can be used for older versions of guile. The guile GH wrapper code generation is depreciated and the SCM interface is the default. The SCM and GH interface differ greatly in how they store pointers and have completely different run-time code. See below for more info.

The GH interface to guile is deprecated. Read more about why in the Guile manual. The idea of the GH interface was to provide a high level API that other languages and projects could adopt. This was a good idea, but didn't pan out well for general development. But for the specific, minimal uses that the SWIG typemaps put the GH interface to use is ideal for using a high level API. So even though the GH interface is depreciated, SWIG will continue to use the GH interface and provide mappings from the GH interface to whatever API we need. We can maintain this mapping where guile failed because SWIG uses a small subset of all the GH functions which map easily. All the guile typemaps like typemaps.i and std_vector.i will continue to use the GH functions to do things like create lists of values, convert strings to integers, etc. Then every language module will define a mapping between the GH interface and whatever custom API the language uses. This is currently implemented by the guile module to use the SCM guile API rather than the GH guile API. For example, here are some of the current mapping file for the SCM API


#define gh_append2(a, b) scm_append(scm_listify(a, b, SCM_UNDEFINED)) 
#define gh_apply(a, b) scm_apply(a, b, SCM_EOL) 
#define gh_bool2scm SCM_BOOL 
#define gh_boolean_p SCM_BOOLP 
#define gh_car SCM_CAR 
#define gh_cdr SCM_CDR 
#define gh_cons scm_cons 
#define gh_double2scm scm_make_real 
...

This file is parsed by SWIG at wrapper generation time, so every reference to a gh_ function is replaced by a scm_ function in the wrapper file. Thus the gh_ function calls will never be seen in the wrapper; the wrapper will look exactly like it was generated for the specific API. Currently only the guile language module has created a mapping policy from gh_ to scm_, but there is no reason other languages (like mzscheme or chicken) couldn't also use this. If that happens, there is A LOT less code duplication in the standard typemaps.

19.3 Linkage

Guile support is complicated by a lack of user community cohesiveness, which manifests in multiple shared-library usage conventions. A set of policies implementing a usage convention is called a linkage.

19.3.1 Simple Linkage

The default linkage is the simplest; nothing special is done. In this case the function SWIG_init() is exported. Simple linkage can be used in several ways:

If you want to include several SWIG modules, you would need to rename SWIG_init via a preprocessor define to avoid symbol clashes. For this case, however, passive linkage is available.

19.3.2 Passive Linkage

Passive linkage is just like simple linkage, but it generates an initialization function whose name is derived from the module and package name (see below).

You should use passive linkage rather than simple linkage when you are using multiple modules.

19.3.3 Native Guile Module Linkage

SWIG can also generate wrapper code that does all the Guile module declarations on its own if you pass it the -Linkage module command-line option. This requires Guile 1.5.0 or later.

The module name is set with the -package and -module command-line options. Suppose you want to define a module with name (my lib foo); then you would have to pass the options -package my/lib -module foo . Note that the last part of the name can also be set via the SWIG directive %module.

You can use this linkage in several ways:

19.3.4 Old Auto-Loading Guile Module Linkage

Guile used to support an autoloading facility for object-code modules. This support has been marked deprecated in version 1.4.1 and is going to disappear sooner or later. SWIG still supports building auto-loading modules if you pass it the -Linkage ltdlmod command-line option.

Auto-loading worked like this: Suppose a module with name (my lib foo) is required and not loaded yet. Guile will then search all directories in its search path for a Scheme file my/modules/foo.scm or a shared library my/ modules/libfoo.so (or my/ modules/libfoo.la; see the GNU libtool documentation). If a shared library is found that contains the symbol scm_init_my_modules_foo_module, the library is loaded, and the function at that symbol is called with no arguments in order to initialize the module.

When invoked with the -Linkage ltdlmod command-line option, SWIG generates an exported module initialization function with an appropriate name.

19.3.5 Hobbit4D Linkage

The only other linkage supported at this time creates shared object libraries suitable for use by hobbit's (hobbit4d link) guile module. This is called the "hobbit" linkage, and requires also using the "-package" command line option to set the part of the module name before the last symbol. For example, both command lines:

swig -guile -package my/lib foo.i
swig -guile -package my/lib -module foo foo.i

would create module (my lib foo) (assuming in the first case foo.i declares the module to be "foo"). The installed files are my/lib/libfoo.so.X.Y.Z and friends. This scheme is still very experimental; the (hobbit4d link) conventions are not well understood.

19.4 Underscore Folding

Underscores are converted to dashes in identifiers. Guile support may grow an option to inhibit this folding in the future, but no one has complained so far.

You can use the SWIG directives %name and %rename to specify the Guile name of the wrapped functions and variables (see CHANGES).

19.5 Typemaps

The Guile module handles all types via typemaps. This information is read from Lib/guile/typemaps.i. Some non-standard typemap substitutions are supported:

A function returning void (more precisely, a function whose out typemap returns SCM_UNSPECIFIED) is treated as returning no values. In argout typemaps, one can use the macro GUILE_APPEND_RESULT in order to append a value to the list of function return values.

Multiple values can be passed up to Scheme in one of three ways:

See also the "multivalue" example.

Constants are exported as a function that returns the value. The %feature("constasvar") can be applied to any constant, immutable variable, or enum. Instead of exporting the constant as a function that must be called, the constant will appear as a scheme variable. See Features and the %feature directive for info on how to apply the %feature.

19.6 Representation of pointers as smobs

For pointer types, SWIG uses Guile smobs. SWIG smobs print like this: #<swig struct xyzzy * 0x1234affe> Two of them are equal? if and only if they have the same type and value.

To construct a Scheme object from a C pointer, the wrapper code calls the function SWIG_NewPointerObj(), passing a pointer to a struct representing the pointer type. The type index to store in the upper half of the CAR is read from this struct. To get the pointer represented by a smob, the wrapper code calls the function SWIG_ConvertPtr(), passing a pointer to a struct representing the expected pointer type. See also The run-time type checker. If the Scheme object passed was not a SWIG smob representing a compatible pointer, a wrong-type-arg exception is raised.

19.6.1 GH Smobs

In earlier versions of SWIG, C pointers were represented as Scheme strings containing a hexadecimal rendering of the pointer value and a mangled type name. As Guile allows registering user types, so-called "smobs" (small objects), a much cleaner representation has been implemented now. The details will be discussed in the following.

A smob is a cons cell where the lower half of the CAR contains the smob type tag, while the upper half of the CAR and the whole CDR are available. Every module creates its own smob type in the clientdata field of the module. So the lower 16 bits of the car of the smob store the tag and the upper 16 bits store the index this type is in the array. We can then, given a smob, find its swig_type_info struct by using the tag (lower 16 bits of car) to find which module this type is in (since each tag is unique for the module). Then we use the upper 16 bits to index into the array of types attached to this module. Looking up the module from the tag is worst case O(# of modules) but average case O(1). This is because the modules are stored in a circularly linked list, and when we start searching the modules for the tag, we start looking with the module that the function doing the lookup is in. SWIG_Guile_ConvertPtr() takes as its first argument the swig_module_info * of the calling function, which is where we start comparing tags. Most types will be looked up in the same module that created them, so the first module we check will most likely be correct. Once we have a swig_type_info structure, we loop through the linked list of casts, using pointer comparisons.

19.6.2 SCM Smobs

The SCM interface (using the "-scm" argument to swig) uses swigrun.swg. The whole type system, when it is first initialized, creates two smobs named "swig" and "collected_swig". The swig smob is used for non-garbage collected smobs, while the collected_swig smob is used as described below. Each smob has the same format, which is a double cell created by SCM_NEWSMOB2() The first word of data is the pointer to the object and the second word of data is the swig_type_info * structure describing this type. This is a lot easier than the GH interface above because we can store a pointer to the type info structure right in the type. With the GH interface, there was not enough room in the smob to store two whole words of data so we needed to store part of the "swig_type_info address" in the smob tag. If a generated GOOPS module has been loaded, smobs will be wrapped by the corresponding GOOPS class.

19.6.3 Garbage Collection

Garbage collection is a feature of the new SCM interface, and it is automatically included if you pass the "-scm" flag to swig. Thus the swig garbage collection support requires guile >1.6. Garbage collection works like this. Every swig_type_info structure stores in its clientdata field a pointer to the destructor for this type. The destructor is the generated wrapper around the delete function. So swig still exports a wrapper for the destructor, it just does not call scm_c_define_gsubr() for the wrapped delete function. So the only way to delete an object is from the garbage collector, since the delete function is not available to scripts. How swig determines if a type should be garbage collected is exactly like described in Object ownership and %newobject in the SWIG manual. All typemaps use an $owner var, and the guile module replaces $owner with 0 or 1 depending on feature:new.

19.7 Exception Handling

SWIG code calls scm_error on exception, using the following mapping:

      MAP(SWIG_MemoryError,	"swig-memory-error");
      MAP(SWIG_IOError,		"swig-io-error");
      MAP(SWIG_RuntimeError,	"swig-runtime-error");
      MAP(SWIG_IndexError,	"swig-index-error");
      MAP(SWIG_TypeError,	"swig-type-error");
      MAP(SWIG_DivisionByZero,	"swig-division-by-zero");
      MAP(SWIG_OverflowError,	"swig-overflow-error");
      MAP(SWIG_SyntaxError,	"swig-syntax-error");
      MAP(SWIG_ValueError,	"swig-value-error");
      MAP(SWIG_SystemError,	"swig-system-error");

The default when not specified here is to use "swig-error". See Lib/exception.i for details.

19.8 Procedure documentation

If invoked with the command-line option -procdoc file , SWIG creates documentation strings for the generated wrapper functions, describing the procedure signature and return value, and writes them to file. You need Guile 1.4 or later to make use of the documentation files.

SWIG can generate documentation strings in three formats, which are selected via the command-line option -procdocformat format :

You need to register the generated documentation file with Guile like this:

(use-modules (ice-9 documentation))
(set! documentation-files 
      (cons "file" documentation-files))

Documentation strings can be configured using the Guile-specific typemap argument doc. See Lib/guile/typemaps.i for details.

19.9 Procedures with setters

For global variables, SWIG creates a single wrapper procedure ( variable :optional value), which is used for both getting and setting the value. For struct members, SWIG creates two wrapper procedures (struct-member-get pointer) and (struct-member-set pointer value).

If invoked with the command-line option -emit-setters ( recommended), SWIG will additionally create procedures with setters. For global variables, the procedure-with-setter variable is created, so you can use (variable ) to get the value and (set! (variable) value) to set it. For struct members, the procedure-with-setter struct-member is created, so you can use (struct-member pointer) to get the value and (set! (struct -member pointer) value) to set it.

If invoked with the command-line option -only-setters, SWIG will only create procedures with setters, i.e., for struct members, the procedures (struct-member -get pointer) and (struct-member-set pointer value) are not generated.

19.10 GOOPS Proxy Classes

SWIG can also generate classes and generic functions for use with Guile's Object-Oriented Programming System (GOOPS). GOOPS is a sophisticated object system in the spirit of the Common Lisp Object System (CLOS).

GOOPS support is only available with the new SCM interface (enabled with the -scm command-line option of SWIG). To enable GOOPS support, pass the -proxy argument to swig. This will export the GOOPS wrapper definitions into the module.scm file in the directory specified by -outdir or the current directory. GOOPS support requires either passive or module linkage.

The generated file will contain definitions of GOOPS classes mimicking the C++ class hierarchy.

Enabling GOOPS support implies -emit-setters.

If -emit-slot-accessors is also passed as an argument, then the generated file will contain accessor methods for all the slots in the classes and for global variables. The input class

  class Foo {
    public:
      Foo(int i) : a(i) {}
      int a;
      int getMultBy(int i) { return a * i; }
      Foo getFooMultBy(int i) { return Foo(a * i); }
  }; 
  Foo getFooPlus(int i) { return Foo(a + i); }

will produce (if -emit-slot-accessors is not passed as a parameter)

(define-class <Foo> (<swig>)
  (a #:allocation #:swig-virtual 
     #:slot-ref primitive:Foo-a-get 
     #:slot-set! primitive:Foo-a-set)
  #:metaclass <swig-metaclass>
  #:new-function primitive:new-Foo
)
(define-method (getMultBy (swig_smob <Foo>) i)
  (primitive:Foo-getMultBy  (slot-ref swig_smob 'smob) i))
(define-method (getFooMultBy (swig_smob <Foo>) i)
  (make <Foo> #:init-smob (primitive:Foo-getFooMultBy  (slot-ref swig_smob 'smob) i)))

(define-method (getFooPlus i)
  (make <Foo> #:init-smob (primitive:getFooPlus i)))

(export <Foo> getMultBy getFooMultBy getFooPlus )

and will produce (if -emit-slot-accessors is passed as a parameter)

(define-class <Foo> (<swig>)
  (a #:allocation #:swig-virtual 
     #:slot-ref primitive:Foo-a-get 
     #:slot-set! primitive:Foo-a-set 
     #:accessor a)
  #:metaclass <swig-metaclass>
  #:new-function primitive:new-Foo
)
(define-method (getMultBy (swig_smob <Foo>) i)
  (primitive:Foo-getMultBy  (slot-ref swig_smob 'smob) i))
(define-method (getFooMultBy (swig_smob <Foo>) i)
  (make <Foo> #:init-smob (primitive:Foo-getFooMultBy  (slot-ref swig_smob 'smob) i)))

(define-method (getFooPlus i)
  (make <Foo> #:init-smob (primitive:getFooPlus i)))

(export <Foo> a getMultBy getFooMultBy getFooPlus )

which can then be used by this code

;; not using getters and setters
(define foo (make <Foo> #:args '(45)))
(slot-ref foo 'a)
(slot-set! foo 'a 3)
(getMultBy foo 4)
(define foo2 (getFooMultBy foo 7))
(slot-ref foo 'a)
(slot-ref (getFooPlus foo 4) 'a)

;; using getters and setters
(define foo (make <Foo> #:args '(45)))
(a foo)
(set! (a foo) 5)
(getMultBy foo 4)
(a (getFooMultBy foo 7))

Notice that constructor arguments are passed as a list after the #:args keyword. Hopefully in the future the following will be valid (make <Foo> #:a 5 #:b 4)

Also note that the order the declarations occur in the .i file make a difference. For example,

%module test

%{ #include "foo.h" %}

%inline %{
  int someFunc(Foo &a) {
    ...
  }
%}

%include "foo.h"

This is a valid SWIG file it will work as you think it will for primitive support, but the generated GOOPS file will be broken. Since the someFunc definition is parsed by SWIG before all the declarations in foo.h, the generated GOOPS file will contain the definition of someFunc() before the definition of <Foo>. The generated GOOPS file would look like

;;...

(define-method (someFunc (swig_smob <Foo>))
  (primitive:someFunc (slot-ref swig_smob 'smob)))

;;...

(define-class <Foo> (<swig>)
  ;;...
)

;;...

Notice that <Foo> is used before it is defined. The fix is to just put the %import "foo.h" before the %inline block.

19.10.1 Naming Issues

As you can see in the example above, there are potential naming conflicts. The default exported accessor for the Foo::a variable is named a. The name of the wrapper global function is getFooPlus. If the -useclassprefix option is passed to swig, the name of all accessors and member functions will be prepended with the class name. So the accessor will be called Foo-a and the member functions will be called Foo-getMultBy. Also, if the -goopsprefix goops: argument is passed to swig, every identifier will be prefixed by goops:

Two guile-modules are created by SWIG. The first module contains the primitive definitions of all the wrapped functions and variables, and is located either in the _wrap.cxx file (with -Linkage module ) or in the scmstub file (if -Linkage passive -scmstub). The name of this guile-module is the swig-module name (given on the command line with the -module argument or with the %module directive) concatenated with the string "-primitive". For example, if %module Test is set in the swig interface file, the name of the guile-module in the scmstub or -Linkage module will be Test-primitive. Also, the scmstub file will be named Test-primitive.scm. The string "primitive" can be changed by the -primsuffix swig argument. So the same interface, with the -primsuffix base will produce a module called Test-base . The second generated guile-module contains all the GOOPS class definitions and is located in a file named module.scm in the directory specified with -outdir or the current directory. The name of this guile-module is the name of the swig-module (given on the command line or with the %module directive). In the previous example, the GOOPS definitions will be in a file named Test.scm.

Because of the naming conflicts, you can't in general use both the -primitive and the GOOPS guile-modules at the same time. To do this, you need to rename the exported symbols from one or both guile-modules. For example,

(use-modules ((Test-primitive) #:renamer (symbol-prefix-proc 'primitive:)))
(use-modules ((Test) #:renamer (symbol-prefix-proc 'goops:)))

TODO: Renaming class name prefixes?

19.10.2 Linking

The guile-modules generated above all need to be linked together. GOOPS support requires either passive or module linkage. The exported GOOPS guile-module will be the name of the swig-module and should be located in a file called Module.scm. This should be installed on the autoload path for guile, so that (use-modules (Package Module)) will load everything needed. Thus, the top of the GOOPS guile-module will contain code to load everything needed by the interface (the shared library, the scmstub module, etc.). The %goops directive inserts arbitrary code into the generated GOOPS guile-module, and should be used to load the dependent libraries.

This breaks up into three cases

(Swig common): The generated GOOPS guile-module also imports definitions from the (Swig common) guile-module. This module is included with SWIG and should be installed by SWIG into the autoload path for guile (based on the configure script and whatever arguments are passed). If it is not, then the %goops directive also needs to contain code to load the common.scm file into guile. Also note that if you are trying to install the generated wrappers on a computer without SWIG installed, you will need to include the common.swg file along with the install.

Multiple Modules: Type dependencies between modules is supported. For example, if mod1 includes definitions of some classes, and mod2 includes some classes derived from classes in mod1, the generated GOOPS file for mod2 will declare the correct superclasses. The only problem is that since mod2 uses symbols from mod1, the mod2 GOOPS file must include a (use-modules (mod2)). Currently, SWIG does not automatically export this line; it must be included in the %goops directive of mod2. Maybe in the future SWIG can detect dependencies and export this line. (how do other language modules handle this problem?)


20 SWIG and Java

This chapter describes SWIG's support of Java. It covers most SWIG features, but certain low-level details are covered in less depth than in earlier chapters.

20.1 Overview

The 100% Pure Java effort is a commendable concept, however in the real world programmers often either need to re-use their existing code or in some situations want to take advantage of Java but are forced into using some native (C/C++) code. The Java extension to SWIG makes it very easy to plumb in existing C/C++ code for access from Java, as SWIG writes the Java Native Interface (JNI) code for you. It is different to using the 'javah' tool as SWIG will wrap existing C/C++ code, whereas javah takes 'native' Java function declarations and creates C/C++ function prototypes. SWIG wraps C/C++ code using Java proxy classes and is very useful if you want to have access to large amounts of C/C++ code from Java. If only one or two JNI functions are needed then using SWIG may be overkill. SWIG enables a Java program to easily call into C/C++ code from Java. Historically, SWIG was not able to generate any code to call into Java code from C++. However, SWIG now supports full cross language polymorphism and code is generated to call up from C++ to Java when wrapping C++ virtual methods.

Java is one of the few non-scripting language modules in SWIG. As SWIG utilizes the type safety that the Java language offers, it takes a somewhat different approach to that used for scripting languages. In particular runtime type checking and the runtime library are not used by Java. This should be borne in mind when reading the rest of the SWIG documentation. This chapter on Java is relatively self contained and will provide you with nearly everything you need for using SWIG and Java. However, the "SWIG Basics" chapter will be a useful read in conjunction with this one.

This chapter starts with a few practicalities on running SWIG and compiling the generated code. If you are looking for the minimum amount to read, have a look at the sections up to and including the tour of basic C/C++ wrapping section which explains how to call the various C/C++ code constructs from Java. Following this section are details of the C/C++ code and Java classes that SWIG generates. Due to the complexities of C and C++ there are different ways in which C/C++ code could be wrapped and called from Java. SWIG is a powerful tool and the rest of the chapter details how the default code wrapping can be tailored. Various customisation tips and techniques using SWIG directives are covered. The latter sections cover the advanced techniques of using typemaps for complete control of the wrapping process.

20.2 Preliminaries

SWIG 1.1 works with JDKs from JDK 1.1 to JDK1.4 (Java 2 SDK1.4) and should also work with any later versions. Given the choice, you should probably use the latest version of Sun's JDK. The SWIG Java module is known to work using Sun's JVM on Solaris, Linux and the various flavours of Microsoft Windows including Cygwin. The Kaffe JVM is known to give a few problems and at the time of writing was not a fully fledged JVM with full JNI support. The generated code is also known to work on vxWorks using WindRiver's PJava 3.1. The best way to determine whether your combination of operating system and JDK will work is to test the examples and test-suite that comes with SWIG. Run make -k check from the SWIG root directory after installing SWIG on Unix systems.

The Java module requires your system to support shared libraries and dynamic loading. This is the commonly used method to load JNI code so your system will more than likely support this.

20.2.1 Running SWIG

Suppose that you defined a SWIG module such as the following:

/* File: example.i */
%module test
%{
#include "stuff.h"
%}
int fact(int n);

To build a Java module, run SWIG using the -java option :

%swig -java example.i

If building C++, add the -c++ option:

$ swig -c++ -java example.i

This creates two different files; a C/C++ source file example_wrap.c or example_wrap.cxx and numerous Java files. The generated C/C++ source file contains the JNI wrapper code that needs to be compiled and linked with the rest of your C/C++ application.

The name of the wrapper file is derived from the name of the input file. For example, if the input file is example.i, the name of the wrapper file is example_wrap.c. To change this, you can use the -o option. It is also possible to change the output directory that the Java files are generated into using -outdir.

The following sections have further practical examples and details on how you might go about compiling and using the generated files.

20.2.2 Additional Commandline Options

The following table list the additional commandline options available for the Java module. They can also be seen by using:

swig -java -help 
Java specific options
-nopgcppsuppress the premature garbage collection prevention parameter
-noproxygenerate the low-level functional interface instead of proxy classes
-package <name>set name of the Java package to <name>

Their use will become clearer by the time you have finished reading this section on SWIG and Java.

20.2.3 Getting the right header files

In order to compile the C/C++ wrappers, the compiler needs the jni.h and jni_md.h header files which are part of the JDK. They are usually in directories like this:

/usr/java/include
/usr/java/include/<operating_system>

The exact location may vary on your machine, but the above locations are typical.

20.2.4 Compiling a dynamic module

The JNI code exists in a dynamic module or shared library (DLL on Windows) and gets loaded by the JVM. To build a shared library file, you need to compile your module in a manner similar to the following (shown for Solaris):

$ swig -java example.i
$ gcc -c example_wrap.c  -I/usr/java/include -I/usr/java/include/solaris
$ ld -G example_wrap.o  -o libexample.so

The exact commands for doing this vary from platform to platform. However, SWIG tries to guess the right options when it is installed. Therefore, you may want to start with one of the examples in the Examples/java directory. If that doesn't work, you will need to read the man-pages for your compiler and linker to get the right set of options. You might also check the SWIG Wiki for additional information. JNI compilation is a useful reference for compiling on different platforms.

Important
If you are going to use optimisations turned on with gcc (for example -O2), ensure you also compile with -fno-strict-aliasing. The GCC optimisations have become more aggressive from gcc-4.0 onwards and will result in code that fails with strict aliasing optimisations turned on. See the C/C++ to Java typemaps section for more details.

The name of the shared library output file is important. If the name of your SWIG module is "example", the name of the corresponding shared library file should be "libexample.so" (or equivalent depending on your machine, see Dynamic linking problems for more information). The name of the module is specified using the %module directive or -module command line option.

20.2.5 Using your module

To load your shared native library module in Java, simply use Java's System.loadLibrary method in a Java class:

// main.java

public class main {
  static {
    System.loadLibrary("example");
  }

  public static void main(String argv[]) {
    System.out.println(example.fact(4));
  }
}

Compile all the Java files and run:

$ javac *.java
$ java main
24
$

If it doesn't work have a look at the following section which discusses problems loading the shared library.

20.2.6 Dynamic linking problems

As shown in the previous section the code to load a native library (shared library) is System.loadLibrary("name"). This can fail with an UnsatisfiedLinkError exception and can be due to a number of reasons.

You may get an exception similar to this:

$ java main
Exception in thread "main" java.lang.UnsatisfiedLinkError: no example in java.library.path
        at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1312)
        at java.lang.Runtime.loadLibrary0(Runtime.java:749)
        at java.lang.System.loadLibrary(System.java:820)
        at main.<clinit>(main.java:5)

The most common cause for this is an incorrect naming of the native library for the name passed to the loadLibrary function. The string passed to the loadLibrary function must not include the file extension name in the string, that is .dll or .so. The string must be name and not libname for all platforms. On Windows the native library must then be called name.dll and on most Unix systems it must be called libname.so .

Another common reason for the native library not loading is because it is not in your path. On Windows make sure the path environment variable contains the path to the native library. On Unix make sure that your LD_LIBRARY_PATH contains the path to the native library. Adding paths to LD_LIBRARY_PATH can slow down other programs on your system so you may want to consider alternative approaches. For example you could recompile your native library with extra path information using -rpath if you're using GNU, see the GNU linker documentation (ld man page). You could use a command such as ldconfig (Linux) or crle (Solaris) to add additional search paths to the default system configuration (this requires root access and you will need to read the man pages).

The native library will also not load if there are any unresolved symbols in the compiled C/C++ code. The following exception is indicative of this:

$ java main
Exception in thread "main" java.lang.UnsatisfiedLinkError: libexample.so: undefined
symbol: fact
        at java.lang.ClassLoader$NativeLibrary.load(Native Method)
        at java.lang.ClassLoader.loadLibrary0(ClassLoader.java, Compiled Code)
        at java.lang.ClassLoader.loadLibrary(ClassLoader.java, Compiled Code)
        at java.lang.Runtime.loadLibrary0(Runtime.java, Compiled Code)
        at java.lang.System.loadLibrary(System.java, Compiled Code)
        at main.<clinit>(main.java:5)
$

This error usually indicates that you forgot to include some object files or libraries in the linking of the native library file. Make sure you compile both the SWIG wrapper file and the code you are wrapping into the native library file. Also make sure you pass all of the required libraries to the linker. The java -verbose:jni commandline switch is also a great way to get more information on unresolved symbols. One last piece of advice is to beware of the common faux pas of having more than one native library version in your path.

In summary, ensure that you are using the correct C/C++ compiler and linker combination and options for successful native library loading. If you are using the examples that ship with SWIG, then the Examples/Makefile must have these set up correctly for your system. The SWIG installation package makes a best attempt at getting these correct but does not get it right 100% of the time. The SWIG Wiki also has some settings for commonly used compiler and operating system combinations. The following section also contains some C++ specific linking problems and solutions.

20.2.7 Compilation problems and compiling with C++

On most machines, shared library files should be linked using the C++ compiler. For example:

% swig -c++ -java example.i
% g++ -c -fpic example.cxx
% g++ -c -fpic example_wrap.cxx -I/usr/java/j2sdk1.4.1/include -I/usr/java/
j2sdk1.4.1/include/linux
% g++ -shared example.o example_wrap.o -o libexample.so

In addition to this, you may need to include additional library files to make it work. For example, if you are using the Sun C++ compiler on Solaris, you often need to add an extra library -lCrun like this:

% swig -c++ -java example.i
% CC -c example.cxx
% CC -c example_wrap.cxx -I/usr/java/include -I/usr/java/include/solaris
% CC -G example.o example_wrap.o -L/opt/SUNWspro/lib -o libexample.so -lCrun

If you aren't entirely sure about the linking for C++, you might look at an existing C++ program. On many Unix machines, the ldd command will list library dependencies. This should give you some clues about what you might have to include when you link your shared library. For example:

$ ldd swig
        libstdc++-libc6.1-1.so.2 => /usr/lib/libstdc++-libc6.1-1.so.2 (0x40019000)
        libm.so.6 => /lib/libm.so.6 (0x4005b000)
        libc.so.6 => /lib/libc.so.6 (0x40077000)
        /lib/ld-linux.so.2 => /lib/ld-linux.so.2 (0x40000000)
$

Finally make sure the version of JDK header files matches the version of Java that you are running as incompatibilities could lead to compilation problems or unpredictable behaviour.

20.2.8 Building on Windows

Building on Windows is roughly similar to the process used with Unix. You will want to produce a DLL that can be loaded by the Java Virtual Machine. This section covers the process of using SWIG with Microsoft Visual C++ 6 although the procedure may be similar with other compilers. In order for everything to work, you will need to have a JDK installed on your machine in order to read the JNI header files.

20.2.8.1 Running SWIG from Visual Studio

If you are developing your application within Microsoft Visual studio, SWIG can be invoked as a custom build option. The Examples\java directory has a few Windows Examples containing Visual Studio project (.dsp) files. The process to re-create the project files for a C project are roughly:

Note: If using C++, choose a C++ suffix for the wrapper file, for example example_wrap.cxx. Use _wrap.cxx instead of _wrap.c in the instructions above and add -c++ when invoking swig.

Now, assuming all went well, SWIG will be automatically invoked when you build your project. When doing a build, any changes made to the interface file will result in SWIG being automatically invoked to produce a new version of the wrapper file.

The Java classes that SWIG output should also be compiled into .class files. To run the native code in the DLL (example.dll), make sure that it is in your path then run your Java program which uses it, as described in the previous section. If the library fails to load have a look at Dynamic linking problems .

20.2.8.2 Using NMAKE

Alternatively, a Makefile for use by NMAKE can be written. Make sure the environment variables for MSVC++ are available and the MSVC++ tools are in your path. Now, just write a short Makefile like this :

# Makefile for using SWIG and Java for C code

SRCS          = example.c
IFILE         = example
INTERFACE     = $(IFILE).i
WRAPFILE      = $(IFILE)_wrap.c

# Location of the Visual C++ tools (32 bit assumed)

TOOLS         = c:\msdev
TARGET        = example.dll
CC            = $(TOOLS)\bin\cl.exe
LINK          = $(TOOLS)\bin\link.exe
INCLUDE32     = -I$(TOOLS)\include
MACHINE       = IX86

# C Library needed to build a DLL

DLLIBC        = msvcrt.lib oldnames.lib  

# Windows libraries that are apparently needed
WINLIB        = kernel32.lib advapi32.lib user32.lib gdi32.lib comdlg32.lib winspool.lib

# Libraries common to all DLLs
LIBS          = $(DLLIBC) $(WINLIB) 

# Linker options
LOPT      = -debug:full -debugtype:cv /NODEFAULTLIB /RELEASE /NOLOGO \
             /MACHINE:$(MACHINE) -entry:_DllMainCRTStartup@12 -dll

# C compiler flags

CFLAGS        = /Z7 /Od /c /nologo
JAVA_INCLUDE    = -ID:\jdk1.3\include -ID:\jdk1.3\include\win32

java::
	swig -java -o $(WRAPFILE) $(INTERFACE)
	$(CC) $(CFLAGS) $(JAVA_INCLUDE) $(SRCS) $(WRAPFILE)
	set LIB=$(TOOLS)\lib
	$(LINK) $(LOPT) -out:example.dll $(LIBS) example.obj example_wrap.obj
	javac *.java

To build the DLL and compile the java code, run NMAKE (you may need to run vcvars32 first). This is a pretty simplistic Makefile, but hopefully its enough to get you started. Of course you may want to make changes for it to work for C++ by adding in the -c++ command line switch for swig and replacing .c with .cxx.

20.3 A tour of basic C/C++ wrapping

By default, SWIG attempts to build a natural Java interface to your C/C++ code. Functions are wrapped as functions, classes are wrapped as classes, variables are wrapped with JavaBean type getters and setters and so forth. This section briefly covers the essential aspects of this wrapping.

20.3.1 Modules, packages and generated Java classes

The SWIG %module directive specifies the name of the Java module. When you specify `%module example', the module name determines the name of some of the generated files in the module. The generated code consists of a module class file example.java , an intermediary JNI class file, exampleJNI.java as well as numerous other Java proxy class files. Each proxy class is named after the structs, unions and classes you are wrapping. You may also get a constants interface file if you are wrapping any unnamed enumerations or constants, for example exampleConstants.java. When choosing a module name, make sure you don't use the same name as one of the generated proxy class files nor a Java keyword. Sometimes a C/C++ type cannot be wrapped by a proxy class, for example a pointer to a primitive type. In these situations a type wrapper class is generated. Wrapping an enum generates an enum class, either a proper Java enum or a Java class that simulates the enums pattern. Details of all these generated classes will unfold as you read this section.

The JNI (C/C++) code is generated into a file which also contains the module name, for example example_wrap.cxx or example_wrap.c. These C or C++ files complete the contents of the module.

The generated Java classes can be placed into a Java package by using the -package commandline option. This is often combined with the -outdir to specify a package directory for generating the Java files.

swig -java -package com.bloggs.swig -outdir com/bloggs/swig example.i
SWIG won't create the directory, so make sure it exists beforehand.

20.3.2 Functions

There is no such thing as a global Java function so global C functions are wrapped as static methods in the module class. For example,

%module example
int fact(int n);

creates a static function that works exactly like you think it might:

public class example {
  public static int fact(int n) {
    // makes call using JNI to the C function
  }
}

The Java class example is the module class. The function can be used as follows from Java:

System.out.println(example.fact(4));

20.3.3 Global variables

C/C++ global variables are fully supported by SWIG. Java does not allow the overriding of the dot operator so all variables are accessed through getters and setters. Again because there is no such thing as a Java global variable, access to C/C++ global variables is done through static getter and setter functions in the module class.

// SWIG interface file with global variables
%module example
...
%inline %{
extern int My_variable;
extern double density;
%}
...

Now in Java :

// Print out value of a C global variable
System.out.println("My_variable = " + example.getMy_variable());
// Set the value of a C global variable
example.setDensity(0.8442);

The value returned by the getter will always be up to date even if the value is changed in C. Note that the getters and setters produced follow the JavaBean property design pattern. That is the first letter of the variable name is capitalized and preceded with set or get. If you have the misfortune of wrapping two variables that differ only in the capitalization of their first letters, use %rename to change one of the variable names. For example:

%rename Clash RenamedClash;
float Clash;
int clash;

If a variable is declared as const, it is wrapped as a read-only variable. That is only a getter is produced.

To make ordinary variables read-only, you can use the %immutable directive. For example:

%{
extern char *path;
%}
%immutable;
extern char *path;
%mutable;

The %immutable directive stays in effect until it is explicitly disabled or cleared using %mutable. See the Creatng read-only variables section for further details.

If you just want to make a specific variable immutable, supply a declaration name. For example:

%{
extern char *path;
%}
%immutable path;
...
extern char *path;      // Read-only (due to %immutable)

20.3.4 Constants

C/C++ constants are wrapped as Java static final variables. To create a constant, use #define or the %constant directive. For example:

#define PI 3.14159
#define VERSION "1.0"
%constant int FOO = 42;
%constant const char *path = "/usr/local";

By default the generated static final variables are initialized by making a JNI call to get their value. The constants are generated into the constants interface and look like this:

public interface exampleConstants {
  public final static double PI = exampleJNI.PI_get();
  public final static String VERSION = exampleJNI.VERSION_get();
  public final static int FOO = exampleJNI.FOO_get();
  public final static String path = exampleJNI.path_get();
}

Note that SWIG has inferred the C type and used an appropriate Java type that will fit the range of all possible values for the C type. By default SWIG generates runtime constants. They are not compiler constants that can, for example, be used in a switch statement. This can be changed by using the %javaconst(flag) directive. It works like all the other %feature directives. The default is %javaconst(0). It is possible to initialize all wrapped constants from pure Java code by placing a %javaconst(1) before SWIG parses the constants. Putting it at the top of your interface file would ensure this. Here is an example:

%javaconst(1);
%javaconst(0) BIG;
%javaconst(0) LARGE;

#define EXPRESSION (0x100+5)
#define BIG 1000LL
#define LARGE 2000ULL

generates:

public interface exampleConstants {
  public final static int EXPRESSION = (0x100+5);
  public final static long BIG = exampleJNI.BIG_get();
  public final static java.math.BigInteger LARGE = exampleJNI.LARGE_get();
}

Note that SWIG has inferred the C long long type from BIG and used an appropriate Java type (long) as a Java long is the smallest sized Java type that will take all possible values for a C long long. Similarly for LARGE.

Be careful using the %javaconst(1) directive as not all C code will compile as Java code. For example neither the 1000LL value for BIG nor 2000ULL for LARGE above would generate valid Java code. The example demonstrates how you can target particular constants (BIG and LARGE) with %javaconst. SWIG doesn't use %javaconst(1) as the default as it tries to generate code that will always compile. However, using a %javaconst(1) at the top of your interface file is strongly recommended as the preferred compile time constants will be generated and most C constants will compile as Java code and in any case the odd constant that doesn't can be fixed using %javaconst(0).

There is an alternative directive which can be used for these rare constant values that won't compile as Java code. This is the %javaconstvalue(value) directive, where value is a Java code replacement for the C constant and can be either a string or a number. This is useful if you do not want to use either the parsed C value nor a JNI call, such as when the C parsed value will not compile as Java code and a compile time constant is required. The same example demonstrates this:

%javaconst(1);
%javaconstvalue("new java.math.BigInteger(\"2000\")") LARGE;
%javaconstvalue(1000) BIG;

#define EXPRESSION (0x100+5)
#define BIG 1000LL
#define LARGE 2000ULL

Note the string quotes for "2000" are escaped. The following is then generated:

public interface exampleConstants {
  public final static int EXPRESSION = (0x100+5);
  public final static long BIG = 1000;
  public final static java.math.BigInteger LARGE = new java.math.BigInteger("2000");
}

Note: declarations declared as const are wrapped as read-only variables and will be accessed using a getter as described in the previous section. They are not wrapped as constants.

Compatibility Note: In SWIG-1.3.19 and earlier releases, the constants were generated into the module class and the constants interface didn't exist. Backwards compatibility is maintained as the module class implements the constants interface (even though some consider this type of interface implementation to be bad practice):

public class example implements exampleConstants {
}

You thus have the choice of accessing these constants from either the module class or the constants interface, for example, example.EXPRESSION or exampleConstants.EXPRESSION. Or if you decide this practice isn't so bad and your own class implements exampleConstants, you can of course just use EXPRESSION.

20.3.5 Enumerations

SWIG handles both named and unnamed (anonymous) enumerations. There is a choice of approaches to wrapping named C/C++ enums. This is due to historical reasons as SWIG's initial support for enums was limited and Java did not originally have support for enums. Each approach has advantages and disadvantages and it is important for the user to decide which is the most appropriate solution. There are four approaches of which the first is the default approach based on the so called Java typesafe enum pattern. The second generates proper Java enums. The final two approaches use simple integers for each enum item. Before looking at the various approaches for wrapping named C/C++ enums, anonymous enums are considered.

20.3.5.1 Anonymous enums

There is no name for anonymous enums and so they are handled like constants. For example:

enum { ALE, LAGER=10, STOUT, PILSNER, PILZ=PILSNER };

is wrapped into the constants interface, in a similar manner as constants (see previous section):

public interface exampleConstants {
  public final static int ALE = exampleJNI.ALE_get();
  public final static int LAGER = exampleJNI.LAGER_get();
  public final static int STOUT = exampleJNI.STOUT_get();
  public final static int PILSNER = exampleJNI.PILSNER_get();
  public final static int PILZ = exampleJNI.PILZ_get();
}

The %javaconst(flag) and %javaconstvalue(value) directive introduced in the previous section on constants can also be used with enums. As is the case for constants, the default is %javaconst(0) as not all C values will compile as Java code. However, it is strongly recommended to add in a %javaconst(1) directive at the top of your interface file as it is only on very rare occasions that this will produce code that won't compile under Java. Using %javaconst(1) will ensure compile time constants are generated, thereby allowing the enum values to be used in Java switch statements. Example usage:

%javaconst(1);
%javaconst(0) PILSNER;
enum { ALE, LAGER=10, STOUT, PILSNER, PILZ=PILSNER };

generates:

public interface exampleConstants {
  public final static int ALE = 0;
  public final static int LAGER = 10;
  public final static int STOUT = LAGER + 1;
  public final static int PILSNER = exampleJNI.PILSNER_get();
  public final static int PILZ = PILSNER;
}

As in the case of constants, you can access them through either the module class or the constants interface, for example, example.ALE or exampleConstants.ALE.

20.3.5.2 Typesafe enums

This is the default approach to wrapping named enums. The typesafe enum pattern is a relatively well known construct to work around the lack of enums in versions of Java prior to JDK 1.5. It basically defines a class for the enumeration and permits a limited number of final static instances of the class. Each instance equates to an enum item within the enumeration. The implementation is in the "enumtypesafe.swg" file. Let's look at an example:

%include "enumtypesafe.swg" // optional as typesafe enums are the default
enum Beverage { ALE, LAGER=10, STOUT, PILSNER, PILZ=PILSNER };

will generate:

public final class Beverage {
  public final static Beverage ALE = new Beverage("ALE");
  public final static Beverage LAGER = new Beverage("LAGER", exampleJNI.LAGER_get());
  public final static Beverage STOUT = new Beverage("STOUT");
  public final static Beverage PILSNER = new Beverage("PILSNER");
  public final static Beverage PILZ = new Beverage("PILZ", exampleJNI.PILZ_get());
  [... additional support methods omitted for brevity ...]
}

See Typesafe enum classes to see the omitted support methods. Note that the enum item with an initializer (LAGER) is initialized with the enum value obtained via a JNI call. However, as with anonymous enums and constants, use of the %javaconst directive is strongly recommended to change this behaviour:

%include "enumtypesafe.swg" // optional as typesafe enums are the default
%javaconst(1);
enum Beverage { ALE, LAGER=10, STOUT, PILSNER, PILZ=PILSNER };

will generate:

public final class Beverage {
  public final static Beverage ALE = new Beverage("ALE");
  public final static Beverage LAGER = new Beverage("LAGER", 10);
  public final static Beverage STOUT = new Beverage("STOUT");
  public final static Beverage PILSNER = new Beverage("PILSNER");
  public final static Beverage PILZ = new Beverage("PILZ", PILSNER);
  [... additional support methods omitted for brevity ...]
}

The generated code is easier to read and more efficient as a true constant is used instead of a JNI call. As is the case for constants, the default is %javaconst(0) as not all C values will compile as Java code. However, it is recommended to add in a %javaconst(1) directive at the top of your interface file as it is only on very rare occasions that this will produce code that won't compile under Java. The %javaconstvalue(value) directive can also be used for typesafe enums. Note that global enums are generated into a Java class within whatever package you are using. C++ enums defined within a C++ class are generated into a static final inner Java class within the Java proxy class.

Typesafe enums have their advantages over using plain integers in that they they can be used in a typesafe manner. However, there are limitations. For example, they cannot be used in switch statements and serialization is an issue. Please look at the following references for further information: Replace Enums with Classes in Effective Java Programming on the Sun website, Create enumerated constants in Java JavaWorld article, Java Tip 133: More on typesafe enums and Java Tip 122: Beware of Java typesafe enumerations JavaWorld tips.

Note that the syntax required for using typesafe enums is the same as that for proper Java enums. This is useful during the period that a project has to support legacy versions of Java. When upgrading to JDK 1.5 or later, proper Java enums could be used instead, without users having to change their code. The following section details proper Java enum generation.

20.3.5.3 Proper Java enums

Proper Java enums were only introduced in JDK 1.5 so this approach is only compatible with more recent versions of Java. Java enums have been designed to overcome all the limitations of both typesafe and type unsafe enums and should be the choice solution, provided older versions of Java do not have to be supported. In this approach, each named C/C++ enum is wrapped by a Java enum. Java enums, by default, do not support enums with initializers. Java enums are in many respects similar to Java classes in that they can be customised with additional methods. SWIG takes advantage of this feature to facilitate wrapping C/C++ enums that have initializers. In order to wrap all possible C/C++ enums using proper Java enums, the "enums.swg" file must be used. Let's take a look at an example.

%include "enums.swg"
%javaconst(1);
enum Beverage { ALE, LAGER=10, STOUT, PILSNER, PILZ=PILSNER };

will generate:

public enum Beverage {
  ALE,
  LAGER(10),
  STOUT,
  PILSNER,
  PILZ(PILSNER);
  [... additional support methods omitted for brevity ...]
}

See Proper Java enum classes to see the omitted support methods. The generated Java enum has numerous additional methods to support enums with initializers, such as LAGER above. Note that as with the typesafe enum pattern, enum items with initializers are by default initialized with the enum value obtained via a JNI call. However, this is not the case above as we have used the recommended %javaconst(1) to avoid the JNI call. The %javaconstvalue(value) directive covered in the Constants section can also be used for proper Java enums.

The additional support methods need not be generated if none of the enum items have initializers and this is covered later in the Simpler Java enums for enums without initializers section.

20.3.5.4 Type unsafe enums

In this approach each enum item in a named enumeration is wrapped as a static final integer in a class named after the C/C++ enum name. This is a commonly used pattern in Java to simulate C/C++ enums, but it is not typesafe. However, the main advantage over the typesafe enum pattern is enum items can be used in switch statements. In order to use this approach, the "enumtypeunsafe.swg" file must be used. Let's take a look at an example.

%include "enumtypeunsafe.swg"
%javaconst(1);
enum Beverage { ALE, LAGER=10, STOUT, PILSNER, PILZ=PILSNER };

will generate:

public final class Beverage {
  public final static int ALE = 0;
  public final static int LAGER = 10;
  public final static int STOUT = LAGER + 1;
  public final static int PILSNER = STOUT + 1;
  public final static int PILZ = PILSNER;
}

As is the case previously, the default is %javaconst(0) as not all C/C++ values will compile as Java code. However, again it is recommended to add in a %javaconst(1) directive. and the %javaconstvalue(value) directive covered in the Constants section can also be used for type unsafe enums. Note that global enums are generated into a Java class within whatever package you are using. C++ enums defined within a C++ class are generated into a static final inner Java class within the Java proxy class.

Note that unlike typesafe enums, this approach requires users to mostly use different syntax compared with proper Java enums. Thus the upgrade path to proper enums provided in JDK 1.5 is more painful.

20.3.5.5 Simple enums

This approach is similar to the type unsafe approach. Each enum item is also wrapped as a static final integer. However, these integers are not generated into a class named after the C/C++ enum. Instead, global enums are generated into the constants interface. Also, enums defined in a C++ class have their enum items generated directly into the Java proxy class rather than an inner class within the Java proxy class. In fact, this approach is effectively wrapping the enums as if they were anonymous enums and the resulting code is as per anonymous enums. The implementation is in the "enumsimple.swg" file.

Compatibility Note: SWIG-1.3.21 and earlier versions wrapped all enums using this approach. The type unsafe approach is preferable to this one and this simple approach is only included for backwards compatibility with these earlier versions of SWIG.

20.3.6 Pointers

C/C++ pointers are fully supported by SWIG. Furthermore, SWIG has no problem working with incomplete type information. Here is a rather simple interface:

%module example

FILE *fopen(const char *filename, const char *mode);
int fputs(const char *, FILE *);
int fclose(FILE *);

When wrapped, you will be able to use the functions in a natural way from Java. For example:

SWIGTYPE_p_FILE f = example.fopen("junk","w");
example.fputs("Hello World\n", f);
example.fclose(f);

C pointers in the Java module are stored in a Java long and cross the JNI boundary held within this 64 bit number. Many other SWIG language modules use an encoding of the pointer in a string. These scripting languages use the SWIG runtime type checker for dynamic type checking as they do not support static type checking by a compiler. In order to implement static type checking of pointers within Java, they are wrapped by a simple Java class. In the example above the FILE * pointer is wrapped with a type wrapper class called SWIGTYPE_p_FILE.

Once obtained, a type wrapper object can be freely passed around to different C functions that expect to receive an object of that type. The only thing you can't do is dereference the pointer from Java. Of course, that isn't much of a concern in this example.

As much as you might be inclined to modify a pointer value directly from Java, don't. The value is not necessarily the same as the logical memory address of the underlying object. The value will vary depending on the native byte-ordering of the platform (i.e., big-endian vs. little-endian). Most JVMs are 32 bit applications so any JNI code must also be compiled as 32 bit. The net result is pointers in JNI code are also 32 bits and are stored in the high order 4 bytes on big-endian machines and in the low order 4 bytes on little-endian machines. By design it is also not possible to manually cast a pointer to a new type by using Java casts as it is particularly dangerous especially when casting C++ objects. If you need to cast a pointer or change its value, consider writing some helper functions instead. For example:

%inline %{
/* C-style cast */
Bar *FooToBar(Foo *f) {
   return (Bar *) f;
}

/* C++-style cast */
Foo *BarToFoo(Bar *b) {
   return dynamic_cast<Foo*>(b);
}

Foo *IncrFoo(Foo *f, int i) {
    return f+i;
}
%}

Also, if working with C++, you should always try to use the new C++ style casts. For example, in the above code, the C-style cast may return a bogus result whereas as the C++-style cast will return a NULL pointer if the conversion can't be performed.

20.3.7 Structures

If you wrap a C structure, it is wrapped by a Java class with getters and setters for access to the member variables. For example,

struct Vector {
	double x,y,z;
};

is used as follows:

Vector v = new Vector();
v.setX(3.5);
v.setY(7.2);
double x = v.getX();
double y = v.getY();

The variable setters and getters are also based on the JavaBean design pattern already covered under the Global variables section. Similar access is provided for unions and the public data members of C++ classes.

This object is actually an instance of a Java class that has been wrapped around a pointer to the C structure. This instance doesn't actually do anything--it just serves as a proxy. The pointer to the C object is held in the Java proxy class in much the same way as pointers are held by type wrapper classes. Further details about Java proxy classes are covered a little later.

const members of a structure are read-only. Data members can also be forced to be read-only using the %immutable directive. For example:

struct Foo {
   ...
   %immutable;
   int x;        /* Read-only members */
   char *name;
   %mutable;
   ...
};

When char * members of a structure are wrapped, the contents are assumed to be dynamically allocated using malloc or new (depending on whether or not SWIG is run with the -c++ option). When the structure member is set, the old contents will be released and a new value created. If this is not the behavior you want, you will have to use a typemap (described later).

If a structure contains arrays, access to those arrays is managed through pointers. For example, consider this:

struct Bar {
    int  x[16];
};

If accessed in Java, you will see behavior like this:

Bar b = new Bar();
SWIGTYPE_p_int x = b.getX();

This pointer can be passed around to functions that expect to receive an int * (just like C). You can also set the value of an array member using another pointer. For example:

Bar b = new Bar();
SWIGTYPE_p_int x = b.getX();
Bar c = new Bar();
c.setX(x);                    // Copy contents of b.x to c.x

For array assignment (setters not getters), SWIG copies the entire contents of the array starting with the data pointed to by b.x . In this example, 16 integers would be copied. Like C, SWIG makes no assumptions about bounds checking---if you pass a bad pointer, you may get a segmentation fault or access violation. The default wrapping makes it hard to set or get just one element of the array and so array access from Java is somewhat limited. This can be changed easily though by using the approach outlined later in the Wrapping C arrays with Java arrays and Unbounded C Arrays sections.

When a member of a structure is itself a structure, it is handled as a pointer. For example, suppose you have two structures like this:

struct Foo {
   int a;
};

struct Bar {
   Foo f;
};

Now, suppose that you access the f member of Bar like this:

Bar b = new Bar();
Foo x = b.getF();

In this case, x is a pointer that points to the Foo that is inside b. This is the same value as generated by this C code:

Bar b;
Foo *x = &b->f;       /* Points inside b */

Because the pointer points inside the structure, you can modify the contents and everything works just like you would expect. For example:

Bar b = new Bar();
b.getF().setA(3);   // Modify b.f.a
Foo x = b.getF();                   
x.setA(3);          // Modify x.a - this is the same as b.f.a

20.3.8 C++ classes

C++ classes are wrapped by Java classes as well. For example, if you have this class,

class List {
public:
  List();
  ~List();
  int  search(char *item);
  void insert(char *item);
  void remove(char *item);
  char *get(int n);
  int  length;
};

you can use it in Java like this:

List l = new List();
l.insert("Ale");
l.insert("Stout");
l.insert("Lager");
String item = l.get(2);
int length = l.getLength();

Class data members are accessed in the same manner as C structures.

Static class members are unsurprisingly wrapped as static members of the Java class:

class Spam {
public:
   static void foo();
   static int bar;
};

The static members work like any other Java static member:

Spam.foo();
int bar = Spam.getBar();

20.3.9 C++ inheritance

SWIG is fully aware of issues related to C++ inheritance. Therefore, if you have classes like this

class Foo {
...
};

class Bar : public Foo {
...
};

those classes are wrapped into a hierarchy of Java classes that reflect the same inheritance structure:

Bar b = new Bar();
Class c = b.getClass();
System.out.println(c.getSuperclass().getName());

will of course display:

Foo

Furthermore, if you have functions like this

void spam(Foo *f);

then the Java function spam() accepts instances of Foo or instances of any other proxy classes derived from Foo.

Note that Java does not support multiple inheritance so any multiple inheritance in the C++ code is not going to work. A warning is given when multiple inheritance is detected and only the first base class is used.

20.3.10 Pointers, references, arrays and pass by value

In C++, there are many different ways a function might receive and manipulate objects. For example:

void spam1(Foo *x);      // Pass by pointer
void spam2(Foo &x);      // Pass by reference
void spam3(Foo x);       // Pass by value
void spam4(Foo x[]);     // Array of objects

In Java, there is no detailed distinction like this--specifically, there are only instances of classes. There are no pointers nor references. Because of this, SWIG unifies all of these types together in the wrapper code. For instance, if you actually had the above functions, it is perfectly legal to do this from Java:

Foo f = new Foo();  // Create a Foo
example.spam1(f);   // Ok. Pointer
example.spam2(f);   // Ok. Reference
example.spam3(f);   // Ok. Value.
example.spam4(f);   // Ok. Array (1 element)

Similar behavior occurs for return values. For example, if you had functions like this,

Foo *spam5();
Foo &spam6();
Foo  spam7();

then all three functions will return a pointer to some Foo object. Since the third function (spam7) returns a value, newly allocated memory is used to hold the result and a pointer is returned (Java will release this memory when the returned object's finalizer is run by the garbage collector).

20.3.10.1 Null pointers

Working with null pointers is easy. A Java null can be used whenever a method expects a proxy class or typewrapper class. However, it is not possible to pass null to C/C++ functions that take parameters by value or by reference. If you try you will get a NullPointerException.

example.spam1(null);   // Pointer - ok
example.spam2(null);   // Reference - NullPointerException
example.spam3(null);   // Value - NullPointerException
example.spam4(null);   // Array - ok

For spam1 and spam4 above the Java null gets translated into a NULL pointer for passing to the C/C++ function. The converse also occurs, that is, NULL pointers are translated into null Java objects when returned from a C/C++ function.

20.3.11 C++ overloaded functions

C++ overloaded functions, methods, and constructors are mostly supported by SWIG. For example, if you have two functions like this:

%module example

void foo(int);
void foo(char *c);

You can use them in Java in a straightforward manner:

example.foo(3);           // foo(int)
example.foo("Hello");     // foo(char *c)

Similarly, if you have a class like this,

class Foo {
public:
    Foo();
    Foo(const Foo &);
    ...
};

you can write Java code like this:

Foo f = new Foo();        // Create a Foo
Foo g = new Foo(f);       // Copy f

Overloading support is not quite as flexible as in C++. Sometimes there are methods that SWIG cannot disambiguate as there can be more than one C++ type mapping onto a single Java type. For example:

void spam(int);
void spam(unsigned short);

Here both int and unsigned short map onto a Java int. Here is another example:

void foo(Bar *b);
void foo(Bar &b);

If declarations such as these appear, you will get a warning message like this:

example.i:12: Warning(515): Overloaded method spam(unsigned short) ignored.
Method spam(int) at example.i:11 used.

To fix this, you either need to ignore or rename one of the methods. For example:

%rename(spam_short) spam(short);
...
void spam(int);    
void spam(short);   // Accessed as spam_short

or

%ignore spam(short);
...
void spam(int);    
void spam(short);   // Ignored

20.3.12 C++ default arguments

Any function with a default argument is wrapped by generating an additional function for each argument that is defaulted. For example, if we have the following C++:

%module example

void defaults(double d=10.0, int i=0);

The following methods are generated in the Java module class:

public class example {
  public static void defaults(double d, int i) { ... }
  public static void defaults(double d) { ... }
  public static void defaults() { ... }
}

It is as if SWIG had parsed three separate overloaded methods. The same approach is taken for static methods, constructors and member methods.

Compatibility note: Versions of SWIG prior to SWIG-1.3.23 wrapped these with a single wrapper method and so the default values could not be taken advantage of from Java. Further details on default arguments and how to restore this approach are given in the more general Default arguments section.

20.3.13 C++ namespaces

SWIG is aware of C++ namespaces, but namespace names do not appear in the module nor do namespaces result in a module that is broken up into submodules or packages. For example, if you have a file like this,

%module example

namespace foo {
   int fact(int n);
   struct Vector {
       double x,y,z;
   };
};

it works in Java as follows:

int f = example.fact(3);
Vector v = new Vector();
v.setX(3.4);
double y = v.getY();

If your program has more than one namespace, name conflicts (if any) can be resolved using %rename For example:

%rename(Bar_spam) Bar::spam;

namespace Foo {
    int spam();
}

namespace Bar {
    int spam();
}

If you have more than one namespace and you want to keep their symbols separate, consider wrapping them as separate SWIG modules. Each SWIG module can be placed into a separate package.

20.3.14 C++ templates

C++ templates don't present a huge problem for SWIG. However, in order to create wrappers, you have to tell SWIG to create wrappers for a particular template instantiation. To do this, you use the %template directive. For example:

%module example
%{
#include "pair.h"
%}

template<class T1, class T2>
struct pair {
   typedef T1 first_type;
   typedef T2 second_type;
   T1 first;
   T2 second;
   pair();
   pair(const T1&, const T2&);
  ~pair();
};

%template(pairii) pair<int,int>;

In Java:

pairii p = new pairii(3,4);
int first = p.getFirst();
int second = p.getSecond();

Obviously, there is more to template wrapping than shown in this example. More details can be found in the SWIG and C++ chapter.

20.3.15 C++ Smart Pointers

In certain C++ programs, it is common to use classes that have been wrapped by so-called "smart pointers." Generally, this involves the use of a template class that implements operator->() like this:

template<class T> class SmartPtr {
   ...
   T *operator->();
   ...
}

Then, if you have a class like this,

class Foo {
public:
     int x;
     int bar();
};

A smart pointer would be used in C++ as follows:

SmartPtr<Foo> p = CreateFoo();   // Created somehow (not shown)
...
p->x = 3;                        // Foo::x
int y = p->bar();                // Foo::bar

To wrap this in Java, simply tell SWIG about the SmartPtr class and the low-level Foo object. Make sure you instantiate SmartPtr using %template if necessary. For example:

%module example
...
%template(SmartPtrFoo) SmartPtr<Foo>;
...

Now, in Java, everything should just "work":

SmartPtrFoo p = example.CreateFoo(); // Create a smart-pointer somehow
p.setX(3);                           // Foo::x
int y = p.bar();                     // Foo::bar

If you ever need to access the underlying pointer returned by operator->() itself, simply use the __deref__() method. For example:

Foo f = p.__deref__();               // Returns underlying Foo *

20.4 Further details on the generated Java classes

In the previous section, a high-level view of Java wrapping was presented. A key component of this wrapping is that structures and classes are wrapped by Java proxy classes and type wrapper classes are used in situations where no proxies are generated. This provides a very natural, type safe Java interface to the C/C++ code and fits in with the Java programming paradigm. However, a number of low-level details were omitted. This section provides a brief overview of how the proxy classes work and then covers the type wrapper classes. Finally enum classes are covered. First, the crucial intermediary JNI class is considered.

20.4.1 The intermediary JNI class

In the "SWIG basics" and "SWIG and C++" chapters, details of low-level structure and class wrapping are described. To summarize those chapters, if you have a global function and class like this

class Foo {
public:
     int x;
     int spam(int num, Foo* foo);
};
void egg(Foo* chips);

then SWIG transforms the class into a set of low-level procedural wrappers. These procedural wrappers essentially perform the equivalent of this C++ code:

Foo *new_Foo() {
    return new Foo();
}
void delete_Foo(Foo *f) {
    delete f;
}
int Foo_x_get(Foo *f) {
    return f->x;
}
void Foo_x_set(Foo *f, int value) {
    f->x = value;
}
int Foo_spam(Foo *f, int num, Foo* foo) {
    return f->spam(num, foo);
}

These procedural function names don't actually exist, but their functionality appears inside the generated JNI functions. The JNI functions have to follow a particular naming convention so the function names are actually:

SWIGEXPORT jlong JNICALL Java_exampleJNI_new_1Foo(JNIEnv *jenv, jclass jcls);
SWIGEXPORT void JNICALL Java_exampleJNI_delete_1Foo(JNIEnv *jenv, jclass jcls,
                                                    jlong jarg1);
SWIGEXPORT void JNICALL Java_exampleJNI_Foo_1x_1set(JNIEnv *jenv, jclass jcls,
                                                    jlong jarg1, jobject jarg1_, jint jarg2);
SWIGEXPORT jint JNICALL Java_exampleJNI_Foo_1x_1get(JNIEnv *jenv, jclass jcls,
                                                    jlong jarg1, jobject jarg1_);
SWIGEXPORT jint JNICALL Java_exampleJNI_Foo_1spam(JNIEnv *jenv, jclass jcls,
                                                  jlong jarg1, jobject jarg1_, jint jarg2,
                                                  jlong jarg3, jobject jarg3_);
SWIGEXPORT void JNICALL Java_exampleJNI_egg(JNIEnv *jenv, jclass jcls,
                                            jlong jarg1, jobject jarg1_);

For every JNI C function there has to be a static native Java function. These appear in the intermediary JNI class:

class exampleJNI {
  public final static native long new_Foo();
  public final static native void delete_Foo(long jarg1);
  public final static native void Foo_x_set(long jarg1, Foo jarg1_, int jarg2);
  public final static native int Foo_x_get(long jarg1, Foo jarg1_);
  public final static native int Foo_spam(long jarg1, Foo jarg1_, int jarg2,
                                          long jarg3, Foo jarg3_);
  public final static native void egg(long jarg1, Foo jarg1_);
}

This class contains the complete Java - C/C++ interface so all function calls go via this class. As this class acts as a go-between for all JNI calls to C/C++ code from the Java proxy classes, type wrapper classes and module class, it is known as the intermediary JNI class.

You may notice that SWIG uses a Java long wherever a pointer or class object needs to be marshalled across the Java-C/C++ boundary. This approach leads to minimal JNI code which makes for better performance as JNI code involves a lot of string manipulation. SWIG favours generating Java code over JNI code as Java code is compiled into byte code and avoids the costly string operations needed in JNI code. This approach has a downside though as the proxy class might get collected before the native method has completed. You might notice above that there is an additional parameters with a underscore postfix, eg jarg1_. These are added in order to prevent premature garbage collection when marshalling proxy classes.

The functions in the intermediary JNI class cannot be accessed outside of its package. Access to them is gained through the module class for globals otherwise the appropriate proxy class.

The name of the intermediary JNI class can be changed from its default, that is, the module name with JNI appended after it. The module directive attribute jniclassname is used to achieve this:

%module (jniclassname="name") modulename

If name is the same as modulename then the module class name gets changed from modulename to modulenameModule.

20.4.1.1 The intermediary JNI class pragmas

The intermediary JNI class can be tailored through the use of pragmas, but is not commonly done. The pragmas for this class are:

PragmaDescription
jniclassbaseBase class for the intermediary JNI class
jniclassclassmodifiersClass modifiers and class type for the intermediary JNI class
jniclasscodeJava code is copied verbatim into the intermediary JNI class
jniclassimportsJava code, usually one or more import statements, placed before the intermediary JNI class definition
jniclassinterfacesComma separated interface classes for the intermediary JNI class

The pragma code appears in the generated intermediary JNI class where you would expect:

[ jniclassimports pragma ]
[ jniclassclassmodifiers pragma ] jniclassname extends [ jniclassbase pragma ]
                                          implements [ jniclassinterfaces pragma ] {
[ jniclasscode pragma ]
... SWIG generated native methods ...
}

The jniclasscode pragma is quite useful for adding in a static block for loading the shared library / dynamic link library and demonstrates how pragmas work:

%pragma(java) jniclasscode=%{
  static {
    try {
        System.loadLibrary("example");
    } catch (UnsatisfiedLinkError e) {
      System.err.println("Native code library failed to load. \n" + e);
      System.exit(1);
    }
  }
%}

Pragmas will take either "" or %{ %} as delimiters. For example, let's change the intermediary JNI class access to public.

%pragma(java) jniclassclassmodifiers="public class"

All the methods in the intermediary JNI class will then be callable outside of the package as the method modifiers are public by default.

20.4.2 The Java module class

All global functions and variable getters/setters appear in the module class. For our example, there is just one function:

public class example {
  public static void egg(Foo chips) {
    exampleJNI.egg(Foo.getCPtr(chips), chips);
  }
}

The module class is necessary as there is no such thing as a global in Java so all the C globals are put into this class. They are generated as static functions and so must be accessed as such by using the module name in the static function call:

example.egg(new Foo());

The primary reason for having the module class wrapping the calls in the intermediary JNI class is to implement static type checking. In this case only a Foo can be passed to the egg function, whereas any long can be passed to the egg function in the intermediary JNI class.

20.4.2.1 The Java module class pragmas

The module class can be tailored through the use of pragmas, in the same manner as the intermediary JNI class. The pragmas are similarly named and are used in the same way. The complete list follows:

PragmaDescription
modulebaseBase class for the module class
moduleclassmodifiersClass modifiers and class type for the module class
modulecodeJava code is copied verbatim into the module class
moduleimportsJava code, usually one or more import statements, placed before the module class definition
moduleinterfacesComma separated interface classes for the module class

The pragma code appears in the generated module class like this:

[ moduleimports pragma ]
[ modulemodifiers pragma ] modulename extends [ modulebase pragma ]
                                      implements [ moduleinterfaces pragma ] {
[ modulecode pragma ]
... SWIG generated wrapper functions ...
}

See The intermediary JNI class pragmas section for further details on using pragmas.

20.4.3 Java proxy classes

A Java proxy class is generated for each structure, union or C++ class that is wrapped. The default proxy class for our previous example looks like this:

public class Foo {
  private long swigCPtr;
  protected boolean swigCMemOwn;

  protected Foo(long cPtr, boolean cMemoryOwn) {
    swigCMemOwn = cMemoryOwn;
    swigCPtr = cPtr;
  }

  protected static long getCPtr(Foo obj) {
    return (obj == null) ? 0 : obj.swigCPtr;
  }

  protected void finalize() {
    delete();
  }

  public synchronized void delete() {
    if(swigCPtr != 0 && swigCMemOwn) {
      swigCMemOwn = false;
      exampleJNI.delete_Foo(swigCPtr);
    }
    swigCPtr = 0;
  }

  public void setX(int value) {
    exampleJNI.Foo_x_set(swigCPtr, this, value);
  }

  public int getX() {
    return exampleJNI.Foo_x_get(swigCPtr, this);
  }

  public int spam(int num, Foo foo) {
    return exampleJNI.Foo_spam(swigCPtr, this, num, Foo.getCPtr(foo), foo);
  }

  public Foo() {
    this(exampleJNI.new_Foo(), true);
  }

}

This class merely holds a pointer to the underlying C++ object ( swigCPtr). It also contains all the methods in the C++ class it is proxying plus getters and setters for public member variables. These functions call the native methods in the intermediary JNI class. The advantage of having this extra layer is the type safety that the proxy class functions offer. It adds static type checking which leads to fewer surprises at runtime. For example, you can see that if you attempt to use the spam() function it will only compile when the parameters passed are an int and a Foo. From a user's point of view, it makes the class work as if it were a Java class:

Foo f = new Foo();
f.setX(3);
int y = f.spam(5, new Foo());

20.4.3.1 Memory management

Each proxy class has an ownership flag swigCMemOwn. The value of this flag determines who is responsible for deleting the underlying C++ object. If set to true, the proxy class's finalizer will destroy the C++ object when the proxy class is garbage collected. If set to false, then the destruction of the proxy class has no effect on the C++ object.

When an object is created by a constructor or returned by value, Java automatically takes ownership of the result. On the other hand, when pointers or references are returned to Java, there is often no way to know where they came from. Therefore, the ownership is set to false. For example:

class Foo {
public:
    Foo();
    Foo bar1();
    Foo &bar2();
    Foo *bar2();
};

In Java:

Foo f = new Foo();   //  f.swigCMemOwn = true
Foo f1 = f.bar1();   // f1.swigCMemOwn = true
Foo f2 = f.bar2();   // f2.swigCMemOwn = false
Foo f3 = f.bar3();   // f3.swigCMemOwn = false

This behavior for pointers and references is especially important for classes that act as containers. For example, if a method returns a pointer to an object that is contained inside another object, you definitely don't want Java to assume ownership and destroy it!

For the most part, memory management issues remain hidden. However, there are situations where you might have to manually change the ownership of an object. For instance, consider code like this:

class Obj {};
class Node {
   Obj *value;
public:
   void set_value(Obj *v) { value = v; }
};

Now, consider the following Java code:

Node n = new Node();    // Create a node
{
  Obj o = new Obj();    // Create an object
  n.set_value(o);       // Set value
}                       // o goes out of scope

In this case, the Node n is holding a reference to o internally. However, SWIG has no way to know that this has occurred. The Java proxy class still thinks that it has ownership of o. As o has gone out of scope, it could be garbage collected in which case the C++ destructor will be invoked and n will then be holding a stale-pointer to o. If you're lucky, you will only get a segmentation fault.

To work around this, the ownership flag of o needs changing to false. The ownership flag is a private member variable of the proxy class so this is not possible without some customization of the proxy class. This can be achieved by using a typemap to customise the proxy class with pure Java code as detailed later in the section on Java typemaps.

Sometimes a function will create memory and return a pointer to a newly allocated object. SWIG has no way of knowing this so by default the proxy class does not manage the returned object. However, you can tell the proxy class to manage the memory if you specify the %newobject directive. Consider:

class Obj {...};
class Factory {
public:
    static Obj *createObj() { return new Obj(); }
};

If we call the factory function, then we have to manually delete the memory:

Obj obj = Factory.createObj();   // obj.swigCMemOwn = false
...
obj.delete();

Now add in the %newobject directive:

%newobject Factory::createObj();

class Obj {...};
class Factory {
public:
    static Obj *createObj() { return new Obj(); }
};

A call to delete() is no longer necessary as the garbage collector will make the C++ destructor call because swigCMemOwn is now true.

Obj obj = Factory.createObj();   // obj.swigCMemOwn = true;
...

Some memory management issues are quite tricky to fix and may only be noticeable after using for a long time. One such issue is premature garbage collection of an object created from Java and resultant usage from C++ code. The section on typemap examples cover two such scenarios, Memory management for objects passed to the C++ layer and Memory management when returning references to member variables

20.4.3.2 Inheritance

Java proxy classes will mirror C++ inheritance chains. For example, given the base class Base and its derived class Derived :

class Base {
public:
  virtual double foo();
};

class Derived : public Base {
public:
  virtual double foo();
};

The base class is generated much like any other proxy class seen so far:

public class Base {
  private long swigCPtr;
  protected boolean swigCMemOwn;

  protected Base(long cPtr, boolean cMemoryOwn) {
    swigCMemOwn = cMemoryOwn;
    swigCPtr = cPtr;
  }

  protected static long getCPtr(Base obj) {
    return (obj == null) ? 0 : obj.swigCPtr;
  }

  protected void finalize() {
    delete();
  }

  public synchronized void delete() {
    if(swigCPtr != 0 && swigCMemOwn) {
      swigCMemOwn = false;
      exampleJNI.delete_Base(swigCPtr);
    }
    swigCPtr = 0;
  }

  public double foo() {
    return exampleJNI.Base_foo(swigCPtr, this);
  }

  public Base() {
    this(exampleJNI.new_Base(), true);
  }

}

The Derived class extends Base mirroring the C++ class inheritance hierarchy.

public class Derived extends Base {
  private long swigCPtr;

  protected Derived(long cPtr, boolean cMemoryOwn) {
    super(exampleJNI.SWIGDerivedUpcast(cPtr), cMemoryOwn);
    swigCPtr = cPtr;
  }

  protected static long getCPtr(Derived obj) {
    return (obj == null) ? 0 : obj.swigCPtr;
  }

  protected void finalize() {
    delete();
  }

  public synchronized void delete() {
    if(swigCPtr != 0 && swigCMemOwn) {
      swigCMemOwn = false;
      exampleJNI.delete_Derived(swigCPtr);
    }
    swigCPtr = 0;
    super.delete();
  }

  public double foo() {
    return exampleJNI.Derived_foo(swigCPtr, this);
  }

  public Derived() {
    this(exampleJNI.new_Derived(), true);
  }

}

Note the memory ownership is controlled by the base class. However each class in the inheritance hierarchy has its own pointer value which is obtained during construction. The SWIGDerivedUpcast() call converts the pointer from a Derived * to a Base *. This is a necessity as C++ compilers are free to implement pointers in the inheritance hierarchy with different values.

It is of course possible to extend Base using your own Java classes. If Derived is provided by the C++ code, you could for example add in a pure Java class Extended derived from Base. There is a caveat and that is any C++ code will not know about your pure Java class Extended so this type of derivation is restricted. However, true cross language polymorphism can be achieved using the directors feature.

20.4.3.3 Proxy classes and garbage collection

By default each proxy class has a delete() and a finalize() method. The finalize() method calls delete() which frees any malloc'd memory for wrapped C structs or calls the C++ class destructors. The idea is for delete() to be called when you have finished with the C/C++ object. Ideally you need not call delete(), but rather leave it to the garbage collector to call it from the finalizer. The unfortunate thing is that Sun, in their wisdom, do not guarantee that the finalizers will be called. When a program exits, the garbage collector does not always call the finalizers. Depending on what the finalizers do and which operating system you use, this may or may not be a problem.

If the delete() call into JNI code is just for memory handling, there is not a problem when run on most operating systems, for example Windows and Unix. Say your JNI code creates memory on the heap which your finalizers should clean up, the finalizers may or may not be called before the program exits. In Windows and Unix all memory that a process uses is returned to the system on exit, so this isn't a problem. This is not the case in some operating systems like vxWorks. If however, your finalizer calls into JNI code invoking the C++ destructor which in turn releases a TCP/IP socket for example, there is no guarantee that it will be released. Note that with long running programs the garbage collector will eventually run, thereby calling any unreferenced object's finalizers.

Some not so ideal solutions are:

  1. Call the System.runFinalizersOnExit(true) or Runtime.getRuntime().runFinalizersOnExit(true) to ensure the finalizers are called before the program exits. The catch is that this is a deprecated function call as the documentation says:

    This method is inherently unsafe. It may result in finalizers being called on live objects while other threads are concurrently manipulating those objects, resulting in erratic behavior or deadlock.

    In many cases you will be lucky and find that it works, but it is not to be advocated. Have a look at Sun's Java web site and search for runFinalizersOnExit.

  2. From jdk1.3 onwards a new function, addShutdownHook(), was introduced which is guaranteed to be called when your program exits. You can encourage the garbage collector to call the finalizers, for example, add this static block to the class that has the main() function:

      static {
        Runtime.getRuntime().addShutdownHook( 
          new Thread() {
            public void run() { System.gc(); System.runFinalization(); }
          }
        );
      }
    

    Although this usually works, the documentation doesn't guarantee that runFinalization() will actually call the finalizers. As the the shutdown hook is guaranteed you could also make a JNI call to clean up any resources that are being tracked by the C/C++ code.

  3. Call the delete() function manually which will immediately invoke the C++ destructor. As a suggestion it may be a good idea to set the object to null so that should the object be inadvertently used again a Java null pointer exception is thrown, the alternative would crash the JVM by using a null C pointer. For example given a SWIG generated class A:

    A myA = new A();
    // use myA ...
    myA.delete();
    // any use of myA here would crash the JVM 
    myA=null;
    // any use of myA here would cause a Java null pointer exception to be thrown
    

    The SWIG generated code ensures that the memory is not deleted twice, in the event the finalizers get called in addition to the manual delete() call.

  4. Write your own object manager in Java. You could derive all SWIG classes from a single base class which could track which objects have had their finalizers run, then call the rest of them on program termination. The section on Java typemaps details how to specify a pure Java base class.

See the How to Handle Java Finalization's Memory-Retention Issues article for alternative approaches to managing memory by avoiding finalizers altogether.

20.4.3.4 The premature garbage collection prevention parameter for proxy class marshalling

As covered earlier, the C/C++ struct/class pointer is stored in the proxy class as a Java long and when needed is passed into the native method where it is cast into the appropriate type. This approach provides very fast marshalling but could be susceptible to premature garbage collection. Consider the following C++ code:

class Wibble {
};
void wobble(Wibble &w);

The module class contains the Java wrapper for the global wobble method:

public class example {
  ...
  public static void wobble(Wibble w) {
    exampleJNI.wobble(Wibble.getCPtr(w), w);
  }
}

where example is the name of the module. All native methods go through the intermediary class which has the native method declared as such:

public class exampleJNI {
  ...
  public final static native void wobble(long jarg1, Wibble jarg1_);
}

The second parameter, jarg1_, is the premature garbage collection prevention parameter and is added to the native method parameter list whenever a C/C++ struct or class is marshalled as a Java long. In order to understand why, consider the alternative where the intermediary class method is declared without the additional parameter:

public class exampleJNI {
  ...
  public final static native void wobble(long jarg1);
}

and the following simple call to wobble:

{
  Wibble w = new Wibble();
  example.wobble(w);
}

The hotspot compiler effectively sees something like:

{
  Wibble w = new Wibble();
  long w_ptr = Wibble.getCPtr(w);
  // w is no longer reachable
  exampleJNI.wobble(w_ptr);
}

The Wibble object is no longer reachable after the point shown as in this bit of code, the Wibble object is not referenced again after this point. This means that it is a candidate for garbage collection. Should wobble be a long running method, it is quite likely that the finalizer for the Wibble instance will be called. This in turn will call its underlying C++ destructor which is obviously disastrous while the method wobble is running using this object. Even if wobble is not a long running method, it is possible for the Wibble instance to be finalized. By passing the Wibble instance into the native method, it will not be finalized as the JVM guarantees not to finalize any objects until the native method returns. Effectively, the code then becomes

{
  Wibble w = new Wibble();
  long w_ptr = Wibble.getCPtr(w);
  exampleJNI.wobble(w_ptr, w);
  // w is no longer reachable
}

and therefore there is no possibility of premature garbage collection. In practice, this premature garbage collection was only ever observed in Sun's server JVM from jdk-1.3 onwards and in Sun's client JVM from jdk-1.6 onwards.

The premature garbage collection prevention parameter for proxy classes is generated by default whenever proxy classes are passed by value, reference or with a pointer. The additional parameters do impose a slight performance overhead and the parameter generation can be suppressed globally with the -nopgcpp commandline option. More selective suppression is possible with the 'nopgcpp' attribute in the "jnitype" Java typemap. The attribute is a flag and so should be set to "1" to enable the suppression, or it can be omitted or set to "0" to disable. For example:

%typemap(jtype, nopgcpp="1") Wibble & "long"

Compatibility note: The generation of this additional parameter did not occur in versions prior to SWIG-1.3.30.

20.4.4 Type wrapper classes

The generated type wrapper class, for say an int *, looks like this:

public class SWIGTYPE_p_int {
  private long swigCPtr;

  protected SWIGTYPE_p_int(long cPtr, boolean bFutureUse) {
    swigCPtr = cPtr;
  }

  protected SWIGTYPE_p_int() {
    swigCPtr = 0;
  }

  protected static long getCPtr(SWIGTYPE_p_int obj) {
    return obj.swigCPtr;
  }
}

The methods do not have public access, so by default it is impossible to do anything with objects of this class other than pass them around. The methods in the class are part of the inner workings of SWIG. If you need to mess around with pointers you will have to use some typemaps specific to the Java module to achieve this. The section on Java typemaps details how to modify the generated code.

Note that if you use a pointer or reference to a proxy class in a function then no type wrapper class is generated because the proxy class can be used as the function parameter. If however, you need anything more complicated like a pointer to a pointer to a proxy class then a typewrapper class is generated for your use.

Note that SWIG generates a type wrapper class and not a proxy class when it has not parsed the definition of a type that gets used. For example, say SWIG has not parsed the definition of class Snazzy because it is in a header file that you may have forgotten to use the %include directive on. Should SWIG parse Snazzy * being used in a function parameter, it will then generates a type wrapper class around a Snazzy pointer. Also recall from earlier that SWIG will use a pointer when a class is passed by value or by reference:

void spam(Snazzy *x, Snazzy &y, Snazzy z);

Should SWIG not know anything about Snazzy then a SWIGTYPE_p_Snazzy must be used for all 3 parameters in the spam function. The Java function generated is:

public static void spam(SWIGTYPE_p_Snazzy x, SWIGTYPE_p_Snazzy y, SWIGTYPE_p_Snazzy z) {
 ...
}

Note that typedefs are tracked by SWIG and the typedef name is used to construct the type wrapper class name. For example, consider the case where Snazzy is a typedef to an int which SWIG does parse:

typedef int Snazzy;
void spam(Snazzy *x, Snazzy &y, Snazzy z);

Because the typedefs have been tracked the Java function generated is:

public static void spam(SWIGTYPE_p_int x, SWIGTYPE_p_int y, int z) { ... }

20.4.5 Enum classes

SWIG can generate three types of enum classes. The Enumerations section discussed these but omitted all the details. The following sub-sections detail the various types of enum classes that can be generated.

20.4.5.1 Typesafe enum classes

The following example demonstrates the typesafe enum classes which SWIG generates:

%include "enumtypesafe.swg"
%javaconst(1);
enum Beverage { ALE, LAGER=10, STOUT, PILSNER, PILZ=PILSNER };

The following is the code that SWIG generates:

public final class Beverage {
  public final static Beverage ALE = new Beverage("ALE");
  public final static Beverage LAGER = new Beverage("LAGER", 10);
  public final static Beverage STOUT = new Beverage("STOUT");
  public final static Beverage PILSNER = new Beverage("PILSNER");
  public final static Beverage PILZ = new Beverage("PILZ", PILSNER);

  public final int swigValue() {
    return swigValue;
  }

  public String toString() {
    return swigName;
  }

  public static Beverage swigToEnum(int swigValue) {
    if (swigValue < swigValues.length && swigValue >= 0 &&
        swigValues[swigValue].swigValue == swigValue)
      return swigValues[swigValue];
    for (int i = 0; i < swigValues.length; i++)
      if (swigValues[i].swigValue == swigValue)
        return swigValues[i];
    throw new IllegalArgumentException("No enum " + Beverage.class + " with value " +
                                                                         swigValue);
  }

  private Beverage(String swigName) {
    this.swigName = swigName;
    this.swigValue = swigNext++;
  }

  private Beverage(String swigName, int swigValue) {
    this.swigName = swigName;
    this.swigValue = swigValue;
    swigNext = swigValue+1;
  }

  private Beverage(String swigName, Beverage swigEnum) {
    this.swigName = swigName;
    this.swigValue = swigEnum.swigValue;
    swigNext = this.swigValue+1;
  }

  private static Beverage[] swigValues = { ALE, LAGER, STOUT, PILSNER, PILZ };
  private static int swigNext = 0;
  private final int swigValue;
  private final String swigName;
}

As can be seen, there are a fair number of support methods for the typesafe enum pattern. The typesafe enum pattern involves creating a fixed number of static instances of the enum class. The constructors are private to enforce this. Three constructors are available - two for C/C++ enums with an initializer and one for those without an initializer. Note that the two enums with initializers, LAGER and PILZ, each call one the two different initializer constructors. In order to use one of these typesafe enums, the swigToEnum static method must be called to return a reference to one of the static instances. The JNI layer returns the enum value from the C/C++ world as an integer and this method is used to find the appropriate Java enum static instance. The swigValue method is used for marshalling in the other direction. The toString method is overridden so that the enum name is available.

20.4.5.2 Proper Java enum classes

The following example demonstrates the Java enums approach:

%include "enums.swg"
%javaconst(1);
enum Beverage { ALE, LAGER=10, STOUT, PILSNER, PILZ=PILSNER };

SWIG will generate the following Java enum:

public enum Beverage {
  ALE,
  LAGER(10),
  STOUT,
  PILSNER,
  PILZ(PILSNER);

  public final int swigValue() {
    return swigValue;
  }

  public static Beverage swigToEnum(int swigValue) {
    Beverage[] swigValues = Beverage.class.getEnumConstants();
    if (swigValue < swigValues.length && swigValue >= 0 &&
        swigValues[swigValue].swigValue == swigValue)
      return swigValues[swigValue];
    for (Beverage swigEnum : swigValues)
      if (swigEnum.swigValue == swigValue)
        return swigEnum;
    throw new IllegalArgumentException("No enum " + Beverage.class +
                                       " with value " + swigValue);
  }

  private Beverage() {
    this.swigValue = SwigNext.next++;
  }

  private Beverage(int swigValue) {
    this.swigValue = swigValue;
    SwigNext.next = swigValue+1;
  }

  private Beverage(Beverage swigEnum) {
    this.swigValue = swigEnum.swigValue;
    SwigNext.next = this.swigValue+1;
  }

  private final int swigValue;

  private static class SwigNext {
    private static int next = 0;
  }
}

The enum items appear first. Like the typesafe enum pattern, the constructors are private. The constructors are required to handle C/C++ enums with initializers. The next variable is in the SwigNext inner class rather than in the enum class as static primitive variables cannot be modified from within enum constructors. Marshalling between Java enums and the C/C++ enum integer value is handled via the swigToEnum and swigValue methods. All the constructors and methods in the Java enum are required just to handle C/C++ enums with initializers. These needn't be generated if the enum being wrapped does not have any initializers and the Simpler Java enums for enums without initializers section describes how typemaps can be used to achieve this.

20.4.5.3 Type unsafe enum classes

The following example demonstrates type unsafe enums:

%include "enumtypeunsafe.swg"
%javaconst(1);
enum Beverage { ALE, LAGER=10, STOUT, PILSNER, PILZ=PILSNER };

SWIG will generate the following simple class:

public final class Beverage {
  public final static int ALE = 0;
  public final static int LAGER = 10;
  public final static int STOUT = LAGER + 1;
  public final static int PILSNER = STOUT + 1;
  public final static int PILZ = PILSNER;
}

20.5 Cross language polymorphism using directors (experimental)

Proxy classes provide a natural, object-oriented way to wrap C++ classes. as described earlier, each proxy instance has an associated C++ instance, and method calls from Java to the proxy are passed to the C++ instance transparently via C wrapper functions.

This arrangement is asymmetric in the sense that no corresponding mechanism exists to pass method calls down the inheritance chain from C++ to Java. In particular, if a C++ class has been extended in Java (by deriving from the proxy class), these classes will not be visible from C++ code. Virtual method calls from C++ are thus not able to access the lowest implementation in the inheritance chain.

SWIG can address this problem and make the relationship between C++ classes and proxy classes more symmetric. To achieve this goal, new classes called directors are introduced at the bottom of the C++ inheritance chain. The job of the directors is to route method calls correctly, either to C++ implementations higher in the inheritance chain or to Java implementations lower in the inheritance chain. The upshot is that C++ classes can be extended in Java and from C++ these extensions look exactly like native C++ classes. Neither C++ code nor Java code needs to know where a particular method is implemented: the combination of proxy classes, director classes, and C wrapper functions transparently takes care of all the cross-language method routing.

20.5.1 Enabling directors

The director feature is disabled by default. To use directors you must make two changes to the interface file. First, add the "directors" option to the %module directive, like this:

%module(directors="1") modulename

Without this option no director code will be generated. Second, you must use the %feature("director") directive to tell SWIG which classes and methods should get directors. The %feature directive can be applied globally, to specific classes, and to specific methods, like this:

// generate directors for all classes that have virtual methods
%feature("director");         

// generate directors for all virtual methods in class Foo
%feature("director") Foo;      

// generate a director for just Foo::bar()
%feature("director") Foo::bar; 

You can use the %feature("nodirector") directive to turn off directors for specific classes or methods. So for example,

%feature("director") Foo;
%feature("nodirector") Foo::bar;

will generate directors for all virtual methods of class Foo except bar().

Directors can also be generated implicitly through inheritance. In the following, class Bar will get a director class that handles the methods one() and two() (but not three()):

%feature("director") Foo;
class Foo {
public:
    virtual void one();
    virtual void two();
};

class Bar: public Foo {
public:
    virtual void three();
};

20.5.2 Director classes

For each class that has directors enabled, SWIG generates a new class that derives from both the class in question and a special Swig::Director class. These new classes, referred to as director classes, can be loosely thought of as the C++ equivalent of the Java proxy classes. The director classes store a pointer to their underlying Java proxy classes.

For simplicity let's ignore the Swig::Director class and refer to the original C++ class as the director's base class. By default, a director class extends all virtual methods in the inheritance chain of its base class (see the preceding section for how to modify this behavior). Thus all virtual method calls, whether they originate in C++ or in Java via proxy classes, eventually end up in at the implementation in the director class. The job of the director methods is to route these method calls to the appropriate place in the inheritance chain. By "appropriate place" we mean the method that would have been called if the C++ base class and its Java derived classes were seamlessly integrated. That seamless integration is exactly what the director classes provide, transparently skipping over all the messy JNI glue code that binds the two languages together.

In reality, the "appropriate place" is one of only two possibilities: C++ or Java. Once this decision is made, the rest is fairly easy. If the correct implementation is in C++, then the lowest implementation of the method in the C++ inheritance chain is called explicitly. If the correct implementation is in Java, the Java API is used to call the method of the underlying Java object (after which the usual virtual method resolution in Java automatically finds the right implementation).

20.5.3 Overhead and code bloat

Enabling directors for a class will generate a new director method for every virtual method in the class' inheritance chain. This alone can generate a lot of code bloat for large hierarchies. Method arguments that require complex conversions to and from Java types can result in large director methods. For this reason it is recommended that directors are selectively enabled only for specific classes that are likely to be extended in Java and used in C++.

Although directors make it natural to mix native C++ objects with Java objects (as director objects), one should be aware of the obvious fact that method calls to Java objects from C++ will be much slower than calls to C++ objects. Additionally, compared to classes that do not use directors, the call routing in the director methods adds a small overhead. This situation can be optimized by selectively enabling director methods (using the %feature directive) for only those methods that are likely to be extended in Java.

20.5.4 Simple directors example

Consider the following SWIG interface file:

%module(directors="1") example;

%feature("director") DirectorBase;

class DirectorBase {
public:
  virtual ~DirectorBase() {}
  virtual void upcall_method() {}
};

void callup(DirectorBase *director) {
  director->upcall_method();
}

The following directorDerived Java class is derived from the Java proxy class DirectorBase and overrides upcall_method(). When C++ code invokes upcall_method() , the SWIG-generated C++ code redirects the call via JNI to the Java directorDerived subclass. Naturally, the SWIG generated C++ code and the generated Java intermediate class marshal and convert arguments between C++ and Java when needed.

public class directorDerived extends DirectorBase {
  public directorDerived() {
  }

  public void upcall_method() {
    System.out.println("directorDerived::upcall_method() invoked.");
  }
}

Running the following Java code

directorDerived director = new directorDerived();
example.callup(director);

will result in the following being output:

directorDerived::upcall_method() invoked.

20.6 Common customization features

An earlier section presented the absolute basics of C/C++ wrapping. If you do nothing but feed SWIG a header file, you will get an interface that mimics the behavior described. However, sometimes this isn't enough to produce a nice module. Certain types of functionality might be missing or the interface to certain functions might be awkward. This section describes some common SWIG features that are used to improve the interface to existing C/C++ code.

20.6.1 C/C++ helper functions

Sometimes when you create a module, it is missing certain bits of functionality. For example, if you had a function like this

typedef struct Image {...};
void set_transform(Image *im, double m[4][4]);

it would be accessible from Java, but there may be no easy way to call it. The problem here is that a type wrapper class is generated for the two dimensional array parameter so there is no easy way to construct and manipulate a suitable double [4][4] value. To fix this, you can write some extra C helper functions. Just use the %inline directive. For example:

%inline %{
/* Note: double[4][4] is equivalent to a pointer to an array double (*)[4] */
double (*new_mat44())[4] {
   return (double (*)[4]) malloc(16*sizeof(double));
}
void free_mat44(double (*x)[4]) {
   free(x);
}
void mat44_set(double x[4][4], int i, int j, double v) {
   x[i][j] = v;
}
double mat44_get(double x[4][4], int i, int j) {
   return x[i][j];
}
%}

From Java, you could then write code like this:

Image im = new Image();
SWIGTYPE_p_a_4__double a = example.new_mat44();
example.mat44_set(a,0,0,1.0);
example.mat44_set(a,1,1,1.0);
example.mat44_set(a,2,2,1.0);
...
example.set_transform(im,a);
example.free_mat44(a);

Admittedly, this is not the most elegant looking approach. However, it works and it wasn't too hard to implement. It is possible to improve on this using Java code, typemaps, and other customization features as covered in later sections, but sometimes helper functions are a quick and easy solution to difficult cases.

20.6.2 Class extension with %extend

One of the more interesting features of SWIG is that it can extend structures and classes with new methods or constructors. Here is a simple example:

%module example
%{
#include "someheader.h"
%}

struct Vector {
   double x,y,z;
};

%extend Vector {
   char *toString() {
       static char tmp[1024];
       sprintf(tmp,"Vector(%g,%g,%g)", $self->x,$self->y,$self->z);
       return tmp;
   }
   Vector(double x, double y, double z) {
       Vector *v = (Vector *) malloc(sizeof(Vector));
       v->x = x;
       v->y = y;
       v->z = z;
       return v;
   }
};

Now, in Java

Vector v = new Vector(2,3,4);
System.out.println(v);

will display

Vector(2,3,4)

%extend works with both C and C++ code. It does not modify the underlying object in any way---the extensions only show up in the Java interface.

20.6.3 Exception handling with %exception and %javaexception

If a C or C++ function throws an error, you may want to convert that error into a Java exception. To do this, you can use the %exception directive. The %exception directive simply lets you rewrite part of the generated wrapper code to include an error check. It is detailed in full in the Exception handling with %exception section.

In C, a function often indicates an error by returning a status code (a negative number or a NULL pointer perhaps). Here is a simple example of how you might handle that:

%exception malloc {
  $action
  if (!result) {
    jclass clazz = (*jenv)->FindClass(jenv, "java/lang/OutOfMemoryError");
    (*jenv)->ThrowNew(jenv, clazz, "Not enough memory");
    return $null;
  }
}
void *malloc(size_t nbytes);

In Java,

SWIGTYPE_p_void a = example.malloc(2000000000);

will produce a familiar looking Java exception:

Exception in thread "main" java.lang.OutOfMemoryError: Not enough memory
        at exampleJNI.malloc(Native Method)
        at example.malloc(example.java:16)
        at main.main(main.java:112)

If a library provides some kind of general error handling framework, you can also use that. For example:

%exception malloc {
  $action
  if (err_occurred()) {
    jclass clazz = (*jenv)->FindClass(jenv, "java/lang/OutOfMemoryError");
    (*jenv)->ThrowNew(jenv, clazz, "Not enough memory");
    return $null;
  }
}
void *malloc(size_t nbytes);

No declaration name is given to %exception, it is applied to all wrapper functions. The $action is a SWIG special variable and is replaced by the C/C++ function call being wrapped. The return $null; handles all native method return types, namely those that have a void return and those that do not. This is useful for typemaps that will be used in native method returning all return types. See the section on Java special variables for further explanation.

C++ exceptions are also easy to handle. We can catch the C++ exception and rethrow it as a Java exception like this:

%exception getitem {
  try {
     $action
  } catch (std::out_of_range &e) {
    jclass clazz = jenv->FindClass("java/lang/Exception");
    jenv->ThrowNew(clazz, "Range error");
    return $null;
   }
}

class FooClass {
public:
     FooClass *getitem(int index);      // Might throw std::out_of_range exception
     ...
};

In the example above, java.lang.Exception is a checked exception class and so ought to be declared in the throws clause of getitem. Classes can be specified for adding to the throws clause using %javaexception(classes) instead of %exception, where classes is a string containing one or more comma separated Java classes. The %nojavaexception feature is the equivalent to %noexception and clears previously declared exception handlers.

%javaexception("java.lang.Exception") getitem {
  try {
     $action
  } catch (std::out_of_range &e) {
    jclass clazz = jenv->FindClass("java/lang/Exception");
    jenv->ThrowNew(clazz, "Range error");
    return $null;
   }
}

class FooClass {
public:
     FooClass *getitem(int index);      // Might throw std::out_of_range exception
     ...
};

The generated proxy method now generates a throws clause containing java.lang.Exception:

public class FooClass {
  ...
  public FooClass getitem(int index) throws java.lang.Exception { ... }
  ...
}

The examples above first use the C JNI calling syntax then the C++ JNI calling syntax. The C++ calling syntax will not compile as C and also visa versa. It is however possible to write JNI calls which will compile under both C and C++ and is covered in the Typemaps for both C and C++ compilation section.

The language-independent exception.i library file can also be used to raise exceptions. See the SWIG Library chapter. The typemap example Handling C++ exception specifications as Java exceptions provides further exception handling capabilities.

20.6.4 Method access with %javamethodmodifiers

A Java feature called %javamethodmodifiers can be used to change the method modifiers from the default public. It applies to both module class methods and proxy class methods. For example:

%javamethodmodifiers protect_me() "protected";
void protect_me();

Will produce the method in the module class with protected access.

protected static void protect_me() {
  exampleJNI.protect_me();
}

20.7 Tips and techniques

Although SWIG is largely automatic, there are certain types of wrapping problems that require additional user input. Examples include dealing with output parameters, strings and arrays. This chapter discusses the common techniques for solving these problems.

20.7.1 Input and output parameters using primitive pointers and references

A common problem in some C programs is handling parameters passed as simple pointers or references. For example:

void add(int x, int y, int *result) {
   *result = x + y;
}

or perhaps

int sub(int *x, int *y) {
   return *x-*y;
}

The typemaps.i library file will help in these situations. For example:

%module example
%include "typemaps.i"

void add(int, int, int *OUTPUT);
int  sub(int *INPUT, int *INPUT);

In Java, this allows you to pass simple values. For example:

int result = example.sub(7,4);
System.out.println("7 - 4 = " + result);
int[] sum = {0};
example.add(3,4,sum);
System.out.println("3 + 4 = " + sum[0]);

Which will display:

7 - 4 = 3
3 + 4 = 7

Notice how the INPUT parameters allow integer values to be passed instead of pointers and how the OUTPUT parameter will return the result in the first element of the integer array.

If you don't want to use the names INPUT or OUTPUT , use the %apply directive. For example:

%module example
%include "typemaps.i"

%apply int *OUTPUT { int *result };
%apply int *INPUT  { int *x, int *y};

void add(int x, int y, int *result);
int  sub(int *x, int *y);

If a function mutates one of its parameters like this,

void negate(int *x) {
   *x = -(*x);
}

you can use INOUT like this:

%include "typemaps.i"
...
void negate(int *INOUT);

In Java, the input parameter is the first element in a 1 element array and is replaced by the output of the function. For example:

int[] neg = {3};
example.negate(neg);
System.out.println("Negative of 3 = " + neg[0]);

And no prizes for guessing the output:

Negative of 3 = -3

These typemaps can also be applied to C++ references. The above examples would work the same if they had been defined using references instead of pointers. For example, the Java code to use the negate function would be the same if it were defined either as it is above:

void negate(int *INOUT);

or using a reference:

void negate(int &INOUT);

Note: Since most Java primitive types are immutable and are passed by value, it is not possible to perform in-place modification of a type passed as a parameter.

Be aware that the primary purpose of the typemaps.i file is to support primitive datatypes. Writing a function like this

void foo(Bar *OUTPUT);

will not have the intended effect since typemaps.i does not define an OUTPUT rule for Bar.

20.7.2 Simple pointers

If you must work with simple pointers such as int * or double * another approach to using typemaps.i is to use the cpointer.i pointer library file. For example:

%module example
%include "cpointer.i"

%inline %{
extern void add(int x, int y, int *result);
%}

%pointer_functions(int, intp);

The %pointer_functions(type,name) macro generates five helper functions that can be used to create, destroy, copy, assign, and dereference a pointer. In this case, the functions are as follows:

int  *new_intp();
int  *copy_intp(int *x);
void  delete_intp(int *x);
void  intp_assign(int *x, int value);
int   intp_value(int *x);

In Java, you would use the functions like this:

SWIGTYPE_p_int intPtr = example.new_intp();
example.add(3,4,intPtr);
int result = example.intp_value(intPtr);
System.out.println("3 + 4 = " + result);

If you replace %pointer_functions(int,intp) by %pointer_class(int,intp), the interface is more class-like.

intp intPtr = new intp();
example.add(3,4,intPtr.cast());
int result = intPtr.value();
System.out.println("3 + 4 = " + result);

See the SWIG Library chapter for further details.

20.7.3 Wrapping C arrays with Java arrays

SWIG can wrap arrays in a more natural Java manner than the default by using the arrays_java.i library file. Let's consider an example:

%include "arrays_java.i";
int array[4];
void populate(int x[]) {
    int i;
    for (i=0; i


These one dimensional arrays can then be used as if they were Java arrays:

int[] array = new int[4];
example.populate(array);

System.out.print("array: ");
for (int i=0; i<array.length; i++)
    System.out.print(array[i] + " ");

example.setArray(array);

int[] global_array = example.getArray();

System.out.print("\nglobal_array: ");
for (int i=0; i<array.length; i++)
    System.out.print(global_array[i] + " ");

Java arrays are always passed by reference, so any changes a function makes to the array will be seen by the calling function. Here is the output after running this code:

array: 100 101 102 103
global_array: 100 101 102 103

Note that for assigning array variables the length of the C variable is used, so it is possible to use a Java array that is bigger than the C code will cope with. Only the number of elements in the C array will be used. However, if the Java array is not large enough then you are likely to get a segmentation fault or access violation, just like you would in C. When arrays are used in functions like populate, the size of the C array passed to the function is determined by the size of the Java array.

Please be aware that the typemaps in this library are not efficient as all the elements are copied from the Java array to a C array whenever the array is passed to and from JNI code. There is an alternative approach using the SWIG array library and this is covered in the next section.

20.7.4 Unbounded C Arrays

Sometimes a C function expects an array to be passed as a pointer. For example,

int sumitems(int *first, int nitems) {
    int i, sum = 0;
    for (i = 0; i < nitems; i++) {
        sum += first[i];
    }
    return sum;
}

One of the ways to wrap this is to apply the Java array typemaps that come in the arrays_java.i library file:

%include "arrays_java.i"
%apply int[] {int *};

The ANY size will ensure the typemap is applied to arrays of all sizes. You could narrow the typemap matching rules by specifying a particular array size. Now you can use a pure Java array and pass it to the C code:

int[] array = new int[10000000];          // Array of 10-million integers
for (int i=0; i<array.length; i++) {      // Set some values
  array[i] = i;
}
int sum = example.sumitems(array,10000);
System.out.println("Sum = " + sum);

and the sum would be displayed:

Sum = 49995000

This approach is probably the most natural way to use arrays. However, it suffers from performance problems when using large arrays as a lot of copying of the elements occurs in transferring the array from the Java world to the C++ world. An alternative approach to using Java arrays for C arrays is to use an alternative SWIG library file carrays.i. This approach can be more efficient for large arrays as the array is accessed one element at a time. For example:

%include "carrays.i"
%array_functions(int, intArray);

The %array_functions(type,name) macro generates four helper functions that can be used to create and destroy arrays and operate on elements. In this case, the functions are as follows:

int *new_intArray(int nelements);
void delete_intArray(int *x);
int intArray_getitem(int *x, int index);
void intArray_setitem(int *x, int index, int value);

In Java, you would use the functions like this:

SWIGTYPE_p_int array = example.new_intArray(10000000);  // Array of 10-million integers
for (int i=0; i


If you replace %array_functions(int,intp) by %array_class(int,intp), the interface is more class-like and a couple more helper functions are available for casting between the array and the type wrapper class.

%include "carrays.i"
%array_class(int, intArray);

The %array_class(type, name) macro creates wrappers for an unbounded array object that can be passed around as a simple pointer like int * or double *. For instance, you will be able to do this in Java:

intArray array = new intArray(10000000);  // Array of 10-million integers
for (int i=0; i


The array "object" created by %array_class() does not encapsulate pointers inside a special array object. In fact, there is no bounds checking or safety of any kind (just like in C). Because of this, the arrays created by this library are extremely low-level indeed. You can't iterate over them nor can you even query their length. In fact, any valid memory address can be accessed if you want (negative indices, indices beyond the end of the array, etc.). Needless to say, this approach is not going to suit all applications. On the other hand, this low-level approach is extremely efficient and well suited for applications in which you need to create buffers, package binary data, etc.

20.8 Java typemaps

This section describes how you can modify SWIG's default wrapping behavior for various C/C++ datatypes using the %typemap directive. You are advised to be familiar with the the material in the "Typemaps" chapter. While not absolutely essential knowledge, this section assumes some familiarity with the Java Native Interface (JNI). JNI documentation can be consulted either online at Sun's Java web site or from a good JNI book. The following two books are recommended:

Before proceeding, it should be stressed that typemaps are not a required part of using SWIG---the default wrapping behavior is enough in most cases. Typemaps are only used if you want to change some aspect of the generated code.

20.8.1 Default primitive type mappings

The following table lists the default type mapping from Java to C/C++.

C/C++ typeJava typeJNI type
bool
const bool &
booleanjboolean
char
const char &
charjchar
signed char
const signed char &
bytejbyte
unsigned char
const unsigned char &
shortjshort
short
const short &
shortjshort
unsigned short
const unsigned short &
intjint
int
const int &
intjint
unsigned int
const unsigned int &
longjlong
long
const long &
intjint
unsigned long
const unsigned long &
longjlong
long long
const long long &
longjlong
unsigned long long
const unsigned long long &
java.math.BigInteger jobject
float
const float &
floatjfloat
double
const double &
doublejdouble
char *
char []
Stringjstring

Note that SWIG wraps the C char type as a character. Pointers and arrays of this type are wrapped as strings. The signed char type can be used if you want to treat char as a signed number rather than a character. Also note that all const references to primitive types are treated as if they are passed by value.

Given the following C function:

void func(unsigned short a, char *b, const long &c, unsigned long long d);

The module class method would be:

public static void func(int a, String b, int c, java.math.BigInteger d) {...}

The intermediary JNI class would use the same types:

public final static native void func(int jarg1, String jarg2, int jarg3,
                                     java.math.BigInteger jarg4);

and the JNI function would look like this:

SWIGEXPORT void JNICALL Java_exampleJNI_func(JNIEnv *jenv, jclass jcls,
                jint jarg1, jstring jarg2, jint jarg3, jobject jarg4) {...}

The mappings for C int and C long are appropriate for 32 bit applications which are used in the 32 bit JVMs. There is no perfect mapping between Java and C as Java doesn't support all the unsigned C data types. However, the mappings allow the full range of values for each C type from Java.

20.8.2 Default typemaps for non-primitive types

The previous section covered the primitive type mappings. Non-primitive types such as classes and structs are mapped using pointers on the C/C++ side and storing the pointer into a Java long variable which is held by the proxy class or type wrapper class. This applies whether the type is marshalled as a pointer, by reference or by value. It also applies for any unknown/incomplete types which use type wrapper classes.

So in summary, the C/C++ pointer to non-primitive types is cast into the 64 bit Java long type and therefore the JNI type is a jlong. The Java type is either the proxy class or type wrapper class.

20.8.3 Sixty four bit JVMs

If you are using a 64 bit JVM you may have to override the C long, but probably not C int default mappings. Mappings will be system dependent, for example long will need remapping on Unix LP64 systems (long, pointer 64 bits, int 32 bits), but not on Microsoft 64 bit Windows which will be using a P64 IL32 (pointer 64 bits and int, long 32 bits) model. This may be automated in a future version of SWIG. Note that the Java write once run anywhere philosophy holds true for all pure Java code when moving to a 64 bit JVM. Unfortunately it won't of course hold true for JNI code.

20.8.4 What is a typemap?

A typemap is nothing more than a code generation rule that is attached to a specific C datatype. For example, to convert integers from Java to C, you might define a typemap like this:

%module example

%typemap(in) int {
  $1 = $input;
  printf("Received an integer : %d\n",  $1);
}
%inline %{
extern int fact(int nonnegative);
%}

Typemaps are always associated with some specific aspect of code generation. In this case, the "in" method refers to the conversion of input arguments to C/C++. The datatype int is the datatype to which the typemap will be applied. The supplied C code is used to convert values. In this code a number of special variables prefaced by a $ are used. The $1 variable is a placeholder for a local variable of type int. The $input variable contains the Java data, the JNI jint in this case.

When this example is compiled into a Java module, it can be used as follows:

System.out.println(example.fact(6));

and the output will be:

Received an integer : 6
720

In this example, the typemap is applied to all occurrences of the int datatype. You can refine this by supplying an optional parameter name. For example:

%module example

%typemap(in) int nonnegative {
  $1 = $input;
  printf("Received an integer : %d\n",  $1);
}

%inline %{
extern int fact(int nonnegative);
%}

In this case, the typemap code is only attached to arguments that exactly match int nonnegative.

The application of a typemap to specific datatypes and argument names involves more than simple text-matching--typemaps are fully integrated into the SWIG C++ type-system. When you define a typemap for int, that typemap applies to int and qualified variations such as const int. In addition, the typemap system follows typedef declarations. For example:

%typemap(in) int nonnegative {
  $1 = $input;
  printf("Received an integer : %d\n",  $1);
}
%inline %{
typedef int Integer;
extern int fact(Integer nonnegative);    // Above typemap is applied
%}

However, the matching of typedef only occurs in one direction. If you defined a typemap for Integer, it is not applied to arguments of type int.

Typemaps can also be defined for groups of consecutive arguments. For example:

%typemap(in) (char *str, int len) {
...
};

int count(char c, char *str, int len);

When a multi-argument typemap is defined, the arguments are always handled as a single Java parameter. This allows the function to be used like this (notice how the length parameter is omitted):

int c = example.count('e',"Hello World");

20.8.5 Typemaps for mapping C/C++ types to Java types

The typemaps available to the Java module include the common typemaps listed in the main typemaps section. There are a number of additional typemaps which are necessary for using SWIG with Java. The most important of these implement the mapping of C/C++ types to Java types:


 
TypemapDescription
jniJNI C types. These provide the default mapping of types from C/C++ to JNI for use in the JNI (C/C++) code.
jtypeJava intermediary types. These provide the default mapping of types from C/C++ to Java for use in the native functions in the intermediary JNI class. The type must be the equivalent Java type for the JNI C type specified in the "jni" typemap.
jstypeJava types. These provide the default mapping of types from C/C++ to Java for use in the Java module class, proxy classes and type wrapper classes.
javainConversion from jstype to jtype. These are Java code typemaps which transform the type used in the Java module class, proxy classes and type wrapper classes (as specified in the "jstype" typemap) to the type used in the Java intermediary JNI class (as specified in the "jtype" typemap). In other words the typemap provides the conversion to the native method call parameter types.
javaoutConversion from jtype to jstype. These are Java code typemaps which transform the type used in the Java intermediary JNI class (as specified in the "jtype" typemap) to the Java type used in the Java module class, proxy classes and type wrapper classes (as specified in the "jstype" typemap). In other words the typemap provides the conversion from the native method call return type.
javadirectorinConversion from jtype to jstype for director methods. These are Java code typemaps which transform the type used in the Java intermediary JNI class (as specified in the "jtype" typemap) to the Java type used in the Java module class, proxy classes and type wrapper classes (as specified in the "jstype" typemap). This typemap provides the conversion for the parameters in the director methods when calling up from C++ to Java. See Director typemaps.
javadirectoroutConversion from jstype to jtype for director methods. These are Java code typemaps which transform the type used in the Java module class, proxy classes and type wrapper classes (as specified in the "jstype" typemap) to the type used in the Java intermediary JNI class (as specified in the "jtype" typemap). This typemap provides the conversion for the return type in the director methods when returning from the C++ to Java upcall. See Director typemaps.
directorinConversion from C++ type to jni type for director methods. These are C++ typemaps which convert the parameters used in the C++ director method to the appropriate JNI intermediary type. The conversion is done in JNI code prior to calling the Java function from the JNI code. See Director typemaps.
directoroutConversion from jni type to C++ type for director methods. These are C++ typemaps which convert the JNI return type used in the C++ director method to the appropriate C++ return type. The conversion is done in JNI code after calling the Java function from the JNI code. See Director typemaps.

If you are writing your own typemaps to handle a particular type, you will normally have to write a collection of them. The default typemaps are in "java.swg" and so might be a good place for finding typemaps to base any new ones on.

The "jni", "jtype" and "jstype" typemaps are usually defined together to handle the Java to C/C++ type mapping. An "in" typemap should be accompanied by a "javain" typemap and likewise an "out" typemap by a "javaout" typemap. If an "in" typemap is written, a "freearg" and "argout" typemap may also need to be written as some types have a default "freearg" and/or "argout" typemap which may need overriding. The "freearg" typemap sometimes releases memory allocated by the "in" typemap. The "argout" typemap sometimes sets values in function parameters which are passed by reference in Java.

Note that the "in" typemap marshals the JNI type held in the "jni" typemap to the real C/C++ type and for the opposite direction, the "out" typemap marshals the real C/C++ type to the JNI type held in the "jni" typemap. For non-primitive types the "in" and "out" typemaps are responsible for casting between the C/C++ pointer and the 64 bit jlong type. There is no portable way to cast a pointer into a 64 bit integer type and the approach taken by SWIG is mostly portable, but breaks C/C++ aliasing rules. In summary, these rules state that a pointer to any type must never be dereferenced by a pointer to any other incompatible type. The following code snippet might aid in understand aliasing rules better:

    short a;
    short* pa = 0;
    int i = 0x1234;

    a = (short)i;    /* okay */
    a = *(short*)&i; /* breaks aliasing rules */

An email posting, Aliasing, pointer casts and gcc 3.3 elaborates further on the subject. In SWIG, the "in" and "out" typemaps for pointers are typically

    %typemap(in) struct Foo * %{
      $1 = *(struct Foo **)&$input; /* cast jlong into C ptr */
    %}
    %typemap(out) struct Bar * %{
      *(struct Bar **)&$result = $1; /* cast C ptr into jlong */
    %} 
    struct Bar {...};
    struct Foo {...};
    struct Bar * FooBar(struct Foo *f);

resulting in the following code which breaks the aliasing rules:

SWIGEXPORT jlong JNICALL Java_exampleJNI_FooBar(JNIEnv *jenv, jclass jcls,
                                                jlong jarg1, jobject jarg1_) {
  jlong jresult = 0 ;
  struct Foo *arg1 = (struct Foo *) 0 ;
  struct Bar *result = 0 ;
  
  (void)jenv;
  (void)jcls;
  (void)jarg1_;
  arg1 = *(struct Foo **)&jarg1; 
  result = (struct Bar *)FooBar(arg1);
  *(struct Bar **)&jresult = result; 
  return jresult;
}

If you are using gcc as your C compiler, you might get a "dereferencing type-punned pointer will break strict-aliasing rules" warning about this. Please see Compiling a dynamic module to avoid runtime problems with these strict aliasing rules.

The default code generated by SWIG for the Java module comes from the typemaps in the "java.swg" library file which implements the Default primitive type mappings and Default typemaps for non-primitive types covered earlier. There are other type mapping typemaps in the Java library. These are listed below:


 
C TypeTypemap FileKindJava Type Function
primitive pointers and referencesINPUT typemaps.iinputJava basic typesAllows values to be used for C functions taking pointers for data input.
primitive pointers and referencesOUTPUT typemaps.ioutputJava basic type arraysAllows values held within an array to be used for C functions taking pointers for data output.
primitive pointers and referencesINOUT typemaps.iinput
output
Java basic type arraysAllows values held within an array to be used for C functions taking pointers for data input and output.
string
wstring
[unnamed]std_string.iinput
output
StringUse for std::string mapping to Java String.
arrays of primitive types[unnamed] arrays_java.iinput
output
arrays of primitive Java typesUse for mapping C arrays to Java arrays.
arrays of classes/structs/unionsJAVA_ARRAYSOFCLASSES macroarrays_java.iinput
output
arrays of proxy classesUse for mapping C arrays to Java arrays.
arrays of enumsARRAYSOFENUMSarrays_java.i input
output
int[]Use for mapping C arrays to Java arrays (typeunsafe and simple enum wrapping approaches only).
char *BYTEvarious.iinput byte[]Java byte array is converted to char array
char **STRING_ARRAYvarious.iinput
output
String[]Use for mapping NULL terminated arrays of C strings to Java String arrays

20.8.6 Java typemap attributes

There is an additional typemap attribute that the Java module supports. This is the 'throws' attribute. The throws attribute is optional and specified after the typemap name and contains one or more comma separated classes for adding to the throws clause for any methods that use that typemap. It is analogous to the %javaexception feature's throws attribute.

%typemap(typemapname, throws="ExceptionClass1, ExceptionClass2") type { ... }

The attribute is necessary for supporting Java checked exceptions and can be added to just about any typemap. The list of typemaps include all the C/C++ (JNI) typemaps in the " Typemaps" chapter and the Java specific typemaps listed in the previous section, barring the "jni", "jtype" and "jstype" typemaps as they could never contain code to throw an exception.

The throws clause is generated for the proxy method as well as the JNI method in the JNI intermediary class. If a method uses more than one typemap and each of those typemaps have classes specified in the throws clause, the union of the exception classes is added to the throws clause ensuring there are no duplicate classes. See the NaN exception example for further usage.

The "jnitype" typemap has the 'nopgcpp' attribute which can be used to suppress the generation of the premature garbage collection prevention parameter.

20.8.7 Java special variables

The standard SWIG special variables are available for use within typemaps as described in the Typemaps documentation , for example $1, $input,$result etc.

The Java module uses a few additional special variables:

$javaclassname
$javaclassname is similar to $1_type. It expands to the class name for use in Java. When wrapping a union, struct or class, it expands to the Java proxy class name. Otherwise it expands to the type wrapper class name. For example, $javaclassname is replaced by Foo when the wrapping a struct Foo or struct Foo * and SWIGTYPE_p_unsigned_short is used for unsigned short *.

$null
Used in input typemaps to return early from JNI functions that have either void or a non-void return type. Example:

%typemap(check) int * %{ 
  if (error) {
    SWIG_JavaThrowException(jenv, SWIG_JavaIndexOutOfBoundsException, "Array element error");
    return $null;
  }
%}

If the typemap gets put into a function with void as return, $null will expand to nothing:

SWIGEXPORT void JNICALL Java_jnifn(...) {
    if (error) {
      SWIG_JavaThrowException(jenv, SWIG_JavaIndexOutOfBoundsException, "Array element error");
      return ;
    }
  ...
}

otherwise $null expands to NULL

SWIGEXPORT jobject JNICALL Java_jnifn(...) {
    if (error) {
      SWIG_JavaThrowException(jenv, SWIG_JavaIndexOutOfBoundsException, "Array element error");
      return NULL;
    }
  ...
}

$javainput, $jnicall and $owner
The $javainput special variable is used in "javain" typemaps and $jnicall and $owner are used in "javaout" typemaps. $jnicall is analogous to $action in %exception. It is replaced by the call to the native method in the intermediary JNI class. $owner is replaced by either true if %newobject has been used, otherwise false . $javainput is analogous to the $input special variable. It is replaced by the parameter name.

Here is an example:

%typemap(javain) Class "Class.getCPtr($javainput)"
%typemap(javain) unsigned short "$javainput"
%typemap(javaout) Class * {
    return new Class($jnicall, $owner);
  }

%inline %{
    class Class {...};
    Class * bar(Class cls, unsigned short ush) { return new Class(); };
%}

The generated proxy code is then:

public static Class bar(Class cls, int ush) {
  return new Class(exampleJNI.bar(Class.getCPtr(cls), cls, ush), false);
}

Here $javainput has been replaced by cls and ush. $jnicall has been replaced by the native method call, exampleJNI.bar(...) and $owner has been replaced by false. If %newobject is used by adding the following at the beginning of our example:

%newobject bar(Class cls, unsigned short ush);

The generated code constructs the return type using true indicating the proxy class Class is responsible for destroying the C++ memory allocated for it in bar:

public static Class bar(Class cls, int ush) {
  return new Class(exampleJNI.bar(Class.getCPtr(cls), cls, ush), true);
}

$static
This special variable expands to either static or nothing depending on whether the class is an inner Java class or not. It is used in the "javaclassmodifiers" typemap so that global classes can be wrapped as Java proxy classes and nested C++ classes/enums can be wrapped with the Java equivalent, that is, static inner proxy classes.

$jniinput, $javacall and $packagepath
These special variables are used in the directors typemaps. See Director specific typemaps for details.

$module
This special variable expands to the module name, as specified by %module or the -module commandline option.

$imclassname
This special variable expands to the intermediary class name. Usually this is the same as '$moduleJNI', unless the jniclassname attribute is specified in the %module directive.

20.8.8 Typemaps for both C and C++ compilation

JNI calls must be written differently depending on whether the code is being compiled as C or C++. For example C compilation requires the pointer to a function pointer struct member syntax like

const jclass clazz = (*jenv)->FindClass(jenv, "java/lang/String");

whereas C++ code compilation of the same function call is a member function call using a class pointer like

const jclass clazz = jenv->FindClass("java/lang/String");

To enable typemaps to be used for either C or C++ compilation, a set of JCALLx macros have been defined in Lib/java/javahead.swg, where x is the number of arguments in the C++ version of the JNI call. The above JNI calls would be written in a typemap like this

const jclass clazz = JCALL1(FindClass, jenv, "java/lang/String");

Note that the SWIG preprocessor expands these into the appropriate C or C++ JNI calling convention. The C calling convention is emitted by default and the C++ calling convention is emitted when using the -c++ SWIG commandline option. If you do not intend your code to be targeting both C and C++ then your typemaps can use the appropriate JNI calling convention and need not use the JCALLx macros.

20.8.9 Java code typemaps

Most of SWIG's typemaps are used for the generation of C/C++ code. The typemaps in this section are used solely for the generation of Java code. Elements of proxy classes and type wrapper classes come from the following typemaps (the defaults).

%typemap(javabase)

base (extends) for Java class: empty default
Note that this typemap accepts a replace attribute as an optional flag. When set to "1", it will replace/override any C++ base classes that might have been parsed. If this flag is not specified and there are C++ base classes, then a multiple inheritance warning is issued and the code in the typemap is ignored.

%typemap(javabody)

the essential support body for proxy classes (proxy base classes only), typewrapper classes and enum classes. Default contains extra constructors, memory ownership control member variables (swigCMemOwn, swigCPtr), the getCPtr method etc.

%typemap(javabody_derived)

the essential support body for proxy classes (derived classes only). Same as "javabody" typemap, but only used for proxy derived classes.

%typemap(javaclassmodifiers)

class modifiers for the Java class: default is "public class"

%typemap(javacode)

Java code is copied verbatim to the Java class: empty default

%typemap(javadestruct, methodname="delete", methodmodifiers="public synchronized")

destructor wrapper - the delete() method (proxy classes only), used for all proxy classes except those which have a base class : default calls C++ destructor (or frees C memory) and resets swigCPtr and swigCMemOwn flags

Note that the delete() method name is configurable and is specified by the methodname attribute. The method modifiers are also configurable via the methodmodifiers attribute.

%typemap(javadestruct_derived, methodname="delete", methodmodifiers="public synchronized")

destructor wrapper - the delete() method (proxy classes only), same as "javadestruct" but only used for derived proxy classes : default calls C++ destructor (or frees C memory) and resets swigCPtr and swigCMemOwn flags

Note that the delete() method name is configurable and is specified by the methodname attribute. The method modifiers are also configurable via the methodmodifiers attribute.

%typemap(javaimports)

import statements for Java class: empty default

%typemap(javainterfaces)

interfaces (extends) for Java class: empty default

%typemap(javafinalize)

the finalize() method (proxy classes only): default calls the delete() method

Compatibility Note: In SWIG-1.3.21 and earlier releases, typemaps called "javagetcptr" and "javaptrconstructormodifiers" were available. These are deprecated and the "javabody" typemap can be used instead.

In summary the contents of the typemaps make up a proxy class like this:

[ javaimports typemap ]
[ javaclassmodifiers typemap ] javaclassname extends [ javabase typemap ]
                                             implements [ javainterfaces typemap ] {
[ javabody or javabody_derived typemap ]
[ javafinalize typemap ]
public synchronized void delete() [ javadestruct OR javadestruct_derived typemap ]
[ javacode typemap ]
... proxy functions ...
}

Note the delete() methodname and method modifiers are configurable, see "javadestruct" and "javadestruct_derived" typemaps above.

The type wrapper class is similar in construction:

[ javaimports typemap ]
[ javaclassmodifiers typemap ] javaclassname extends [ javabase typemap ]
                                             implements [ javainterfaces typemap ] {
[ javabody typemap ]
[ javacode typemap ]
}

The enum class is also similar in construction:

[ javaimports typemap ]
[ javaclassmodifiers typemap ] javaclassname extends [ javabase typemap ]
                                             implements [ javainterfaces typemap ] {
... Enum values ...
[ javabody typemap ]
[ javacode typemap ]
}

The "javaimports" typemap is ignored if the enum class is wrapped by an inner Java class, that is when wrapping an enum declared within a C++ class.

The defaults can be overridden to tailor these classes. Here is an example which will change the getCPtr method and constructor from the default protected access to public access. This has a practical application if you are invoking SWIG more than once and generating the wrapped classes into different packages in each invocation. If the classes in one package are using the classes in another package, then these methods need to be public.

%typemap(javabody) SWIGTYPE %{
  private long swigCPtr;
  protected boolean swigCMemOwn;

  public $javaclassname(long cPtr, boolean cMemoryOwn) {
    swigCMemOwn = cMemoryOwn;
    swigCPtr = cPtr;
  }

  public static long getCPtr($javaclassname obj) {
    return (obj == null) ? 0 : obj.swigCPtr;
  }
%}

The typemap code is the same that is in "java.swg", barring the two method modifiers. Note that SWIGTYPE will target all proxy classes, but not the type wrapper classes. Also the above typemap is only used for proxy classes that are potential base classes. To target proxy classes that are derived from a wrapped class as well, the "javabody_derived" typemap should also be overridden.

For the typemap to be used in all type wrapper classes, all the different types that type wrapper classes could be used for should be targeted:

%typemap(javabody) SWIGTYPE *, SWIGTYPE &, SWIGTYPE [], SWIGTYPE (CLASS::*) %{
  private long swigCPtr;

  public $javaclassname(long cPtr, boolean bFutureUse) {
    swigCPtr = cPtr;
  }

  protected $javaclassname() {
    swigCPtr = 0;
  }

  public static long getCPtr($javaclassname obj) {
    return (obj == null) ? 0 : obj.swigCPtr;
  }
%}

Again this is the same that is in "java.swg", barring the method modifier for getCPtr.

20.8.10 Director specific typemaps

The Java directors feature requires the "javadirectorin", "javadirectorout", "directorin" and the "directorout" typemaps in order to work properly. The "javapackage" typemap is an optional typemap used to identify the Java package path for individual SWIG generated proxy classes.

%typemap(directorin)

The "directorin" typemap is used for converting arguments in the C++ director class to the appropriate JNI type before the upcall to Java. This typemap also specifies the JNI field descriptor for the type in the "descriptor" attribute. For example, integers are converted as follows:

%typemap(directorin,descriptor="I") int "$input = (jint) $1;"

$input is the SWIG name of the JNI temporary variable passed to Java in the upcall. The descriptor="I" will put an I into the JNI field descriptor that identifies the Java method that will be called from C++. For more about JNI field descriptors and their importance, refer to the JNI documentation mentioned earlier. A typemap for C character strings is:

%typemap(directorin,descriptor="Ljava/lang/String;") char *
  %{ $input = jenv->NewStringUTF($1); %}

User-defined types have the default "descriptor" attribute " L$packagepath/$javaclassname;" where $packagepath is the package name passed from the SWIG command line and $javaclassname is the Java proxy class' name. If the -package commandline option is not used to specify the package, then '$packagepath/' will be removed from the resulting output JNI field descriptor. Do not forget the terminating ';' for JNI field descriptors starting with 'L'. If the ';' is left out, Java will generate a "method not found" runtime error.

%typemap(directorout)

The "directorout" typemap is used for converting the JNI return type in the C++ director class to the appropriate C++ type after the upcall to Java. For example, integers are converted as follows:

%typemap(directorout) int %{ $result = (int)$input; %}

$input is the SWIG name of the JNI temporary variable returned from Java after the upcall. $result is the resulting output. A typemap for C character strings is:

%typemap(directorout) char * {
  $1 = 0;
  if ($input) {
    $result = (char *)jenv->GetStringUTFChars($input, 0);
    if (!$1) return $null;
  }
}

%typemap(javadirectorin)

Conversion from jtype to jstype for director methods. These are Java code typemaps which transform the type used in the Java intermediary JNI class (as specified in the "jtype" typemap) to the Java type used in the Java module class, proxy classes and type wrapper classes (as specified in the "jstype" typemap). This typemap provides the conversion for the parameters in the director methods when calling up from C++ to Java.

For primitive types, this typemap is usually specified as:

%typemap(javadirectorin) int "$jniinput"

The $jniinput special variable is analogous to $javainput special variable. It is replaced by the input parameter name.

%typemap(javadirectorout)

Conversion from jstype to jtype for director methods. These are Java code typemaps which transform the type used in the Java module class, proxy classes and type wrapper classes (as specified in the "jstype" typemap) to the type used in the Java intermediary JNI class (as specified in the "jtype" typemap). This typemap provides the conversion for the return type in the director methods when returning from the C++ to Java upcall.

For primitive types, this typemap is usually specified as:

%typemap(javadirectorout) int "$javacall"

The $javacall special variable is analogous to the $jnicall special variable. It is replaced by the call to the target Java method. The target method is the method in the Java proxy class which overrides the virtual C++ method in the C++ base class.

%typemap(javapackage)

The "javapackage" typemap is optional; it serves to identify a class's Java package. This typemap should be used in conjunction with classes that are defined outside of the current SWIG interface file. For example:

// class Foo is handled in a different interface file:
%import "Foo.i"

%feature("director") Example;

%inline {
  class Bar { };

  class Example {
  public:
    virtual ~Example();
    void     ping(Foo *arg1, Bar *arg2);
  };
}

Assume that the Foo class is part of the Java package com.wombat.foo but the above interface file is part of the Java package com.wombat.example. Without the "javapackage" typemap, SWIG will assume that the Foo class belongs to com.wombat.example class. The corrected interface file looks like:

// class Foo is handled in a different interface file:
%import "Foo.i"
%typemap("javapackage") Foo, Foo *, Foo & "com.wombat.foo";
%feature("director") Example;

%inline {
  class Bar { };

  class Example {
  public:
    virtual ~Example();
    void     ping(Foo *arg1, Bar *arg2);
  };
}

SWIG looks up the package based on the actual type (plain Foo, Foo pointer and Foo reference), so it is important to associate all three types with the desired package. Practically speaking, you should create a separate SWIG interface file, which is %import-ed into each SWIG interface file, when you have multiple Java packages. Note the helper macros below, OTHER_PACKAGE_SPEC and ANOTHER_PACKAGE_SPEC, which reduce the amount of extra typing. " TYPE..." is useful when passing templated types to the macro, since multiargument template types appear to the SWIG preprocessor as multiple macro arguments.

%typemap("javapackage") SWIGTYPE, SWIGTYPE *, SWIGTYPE &
                                            "package.for.most.classes";

%define OTHER_PACKAGE_SPEC(TYPE...)
%typemap("javapackage") TYPE, TYPE *, TYPE & "package.for.other.classes";
%enddef

%define ANOTHER_PACKAGE_SPEC(TYPE...)
%typemap("javapackage") TYPE, TYPE *, TYPE & "package.for.another.set";
%enddef

OTHER_PACKAGE_SPEC(Package_2_class_one)
ANOTHER_PACKAGE_SPEC(Package_3_class_two)
/* etc */

The basic strategy here is to provide a default package typemap for the majority of the classes, only providing "javapackage" typemaps for the exceptions.

20.9 Typemap Examples

This section includes a few examples of typemaps. For more examples, you might look at the files "java.swg" and "typemaps.i " in the SWIG library.

20.9.1 Simpler Java enums for enums without initializers

The default Proper Java enums approach to wrapping enums is somewhat verbose. This is to handle all possible C/C++ enums, in particular enums with initializers. The generated code can be simplified if the enum being wrapped does not have any initializers.

The following shows how to remove the support methods that are generated by default and instead use the methods in the Java enum base class java.lang.Enum and java.lang.Class for marshalling enums between C/C++ and Java. The type used for the typemaps below is enum SWIGTYPE which is the default type used for all enums. The "enums.swg" file should be examined in order to see the original overridden versions of the typemaps.

%include "enums.swg"

%typemap(javain) enum SWIGTYPE "$javainput.ordinal()"
%typemap(javaout) enum SWIGTYPE {
    return $javaclassname.class.getEnumConstants()[$jnicall];
  }
%typemap(javabody) enum SWIGTYPE ""

%inline %{
  enum HairType { blonde, ginger, brunette };
  void setHair(HairType h);
  HairType getHair();
%}

SWIG will generate the following Java enum, which is somewhat simpler than the default:

public enum HairType {
  blonde,
  ginger,
  brunette;
}

and the two Java proxy methods will be:

public static void setHair(HairType h) {
  exampleJNI.setHair(h.ordinal());
}

public static HairType getHair() {
  return HairType.class.getEnumConstants()[exampleJNI.getHair()];
}

For marshalling Java enums to C/C++ enums, the ordinal method is used to convert the Java enum into an integer value for passing to the JNI layer, see the "javain" typemap. For marshalling C/C++ enums to Java enums, the C/C++ enum value is cast to an integer in the C/C++ typemaps (not shown). This integer value is then used to index into the array of enum constants that the Java language provides. See the getEnumConstants method in the "javaout" typemap.

These typemaps can often be used as the default for wrapping enums as in many cases there won't be any enum initializers. In fact a good strategy is to always use these typemaps and to specifically handle enums with initializers using %apply. This would be done by using the original versions of these typemaps in "enums.swg" under another typemap name for applying using %apply.

20.9.2 Handling C++ exception specifications as Java exceptions

This example demonstrates various ways in which C++ exceptions can be tailored and converted into Java exceptions. Let's consider a simple file class SimpleFile and an exception class FileException which it may throw on error:

%include "std_string.i" // for std::string typemaps
#include <string>

class FileException {
  std::string message;
public:
  FileException(const std::string& msg) : message(msg) {}
  std::string what() {
    return message;
  }
};

class SimpleFile {
  std::string filename;
public:
  SimpleFile(const std::string& filename) : filename(filename) {}
  void open() throw(FileException) {
  ...
  }
};

As the open method has a C++ exception specification, SWIG will parse this and know that the method can throw an exception. The "throws" typemap is then used when SWIG encounters an exception specification. The default generic "throws" typemap looks like this:

%typemap(throws) SWIGTYPE, SWIGTYPE &, SWIGTYPE *, SWIGTYPE [ANY] %{
  SWIG_JavaThrowException(jenv, SWIG_JavaRuntimeException,
                          "C++ $1_type exception thrown");
  return $null;
%}

Basically SWIG will generate a C++ try catch block and the body of the "throws" typemap constitutes the catch block. The above typemap calls a SWIG supplied method which throws a java.lang.RuntimeException. This exception class is a runtime exception and therefore not a checked exception. If, however, we wanted to throw a checked exception, say java.io.IOException, then we could use the following typemap:

%typemap(throws, throws="java.io.IOException") FileException {
  jclass excep = jenv->FindClass("java/io/IOException");
  if (excep)
    jenv->ThrowNew(excep, $1.what().c_str());
  return $null;
}

Note that this typemap uses the 'throws' typemap attribute to ensure a throws clause is generated. The generated proxy method then specifies the checked exception by containing java.io.IOException in the throws clause:

public class SimpleFile {
  ...
  public void open() throws java.io.IOException { ... }
}

Lastly, if you don't want to map your C++ exception into one of the standard Java exceptions, the C++ class can be wrapped and turned into a custom Java exception class. If we go back to our example, the first thing we must do is get SWIG to wrap FileException and ensure that it derives from java.lang.Exception. Additionally, we might want to override the java.lang.Exception.getMessage() method. The typemaps to use then are as follows:

%typemap(javabase) FileException "java.lang.Exception";
%typemap(javacode) FileException %{
  public String getMessage() {
    return what();
  }
%}

This generates:

public class FileException extends java.lang.Exception {
  ...
  public String getMessage() {
    return what();
  }

  public FileException(String msg) { ... }

  public String what() {
    return exampleJNI.FileException_what(swigCPtr, this);
  }
}

We could alternatively have used %rename to rename what() into getMessage().

20.9.3 NaN Exception - exception handling for a particular type

A Java exception can be thrown from any Java or JNI code. Therefore, as most typemaps contain either Java or JNI code, just about any typemap could throw an exception. The following example demonstrates exception handling on a type by type basis by checking for 'Not a number' (NaN) whenever a parameter of type float is wrapped.

Consider the following C++ code:

bool calculate(float first, float second);

To validate every float being passed to C++, we could precede the code being wrapped by the following typemap which throws a runtime exception whenever the float is 'Not a Number':

%module example
%typemap(javain) float "$module.CheckForNaN($javainput)"
%pragma(java) modulecode=%{
  /** Simply returns the input value unless it is not a number,
      whereupon an exception is thrown. */
  static protected float CheckForNaN(float num) {
    if (Float.isNaN(num))
      throw new RuntimeException("Not a number");
    return num;
  }
%}

Note that the CheckForNaN support method has been added to the module class using the modulecode pragma. The following shows the generated code of interest:

public class example {
  ...

  /** Simply returns the input value unless it is not a number,
      whereupon an exception is thrown. */
  static protected float CheckForNaN(float num) {
    if (Float.isNaN(num))
      throw new RuntimeException("Not a number");
    return num;
  }

  public static boolean calculate(float first, float second) {
    return exampleJNI.calculate(example.CheckForNaN(first), example.CheckForNaN(second));
  }
}

Note that the "javain" typemap is used for every occurrence of a float being used as an input. Of course, we could have targeted the typemap at a particular parameter by using float first, say, instead of just float. If we decide that what we actually want is a checked exception instead of a runtime exception, we can change this easily enough. The proxy method that uses float as an input, must then add the exception class to the throws clause. SWIG can handle this as it supports the 'throws' typemap attribute for specifying classes for the throws clause. Thus we can modify the pragma and the typemap for the throws clause:

%typemap(javain, throws="java.lang.Exception") float "$module.CheckForNaN($javainput)"
%pragma(java) modulecode=%{
  /** Simply returns the input value unless it is not a number,
      whereupon an exception is thrown. */
  static protected float CheckForNaN(float num) throws java.lang.Exception {
    if (Float.isNaN(num))
      throw new RuntimeException("Not a number");
    return num;
  }
%}

The calculate method now has a throws clause and even though the typemap is used twice for both float first and float second, the throws clause contains a single instance of java.lang.Exception:

public class example {
  ...

  /** Simply returns the input value unless it is not a number,
      whereupon an exception is thrown. */
  static protected float CheckForNaN(float num) throws java.lang.Exception {
    if (Float.isNaN(num))
      throw new RuntimeException("Not a number");
    return num;
  }

  public static boolean calculate(float first, float second) throws java.lang.Exception {
    return exampleJNI.calculate(example.CheckForNaN(first), example.CheckForNaN(second));
  }
}

If we were a martyr to the JNI cause, we could replace the succinct code within the "javain" typemap with a few pages of JNI code. If we had, we would have put it in the "in" typemap which, like all JNI and Java typemaps, also supports the 'throws' attribute.

20.9.4 Converting Java String arrays to char **

A common problem in many C programs is the processing of command line arguments, which are usually passed in an array of NULL terminated strings. The following SWIG interface file allows a Java String array to be used as a char ** object.

%module example

/* This tells SWIG to treat char ** as a special case when used as a parameter
   in a function call */
%typemap(in) char ** (jint size) {
    int i = 0;
    size = (*jenv)->GetArrayLength(jenv, $input);
    $1 = (char **) malloc((size+1)*sizeof(char *));
    /* make a copy of each string */
    for (i = 0; i<size; i++) {
        jstring j_string = (jstring)(*jenv)->GetObjectArrayElement(jenv, $input, i);
        const char * c_string = (*jenv)->GetStringUTFChars(jenv, j_string, 0);
        $1[i] = malloc(strlen((c_string)+1)*sizeof(const char *));
        strcpy($1[i], c_string);
        (*jenv)->ReleaseStringUTFChars(jenv, j_string, c_string);
        (*jenv)->DeleteLocalRef(jenv, j_string);
    }
    $1[i] = 0;
}

/* This cleans up the memory we malloc'd before the function call */
%typemap(freearg) char ** {
    int i;
    for (i=0; i<size$argnum-1; i++)
      free($1[i]);
    free($1);
}

/* This allows a C function to return a char ** as a Java String array */
%typemap(out) char ** {
    int i;
    int len=0;
    jstring temp_string;
    const jclass clazz = (*jenv)->FindClass(jenv, "java/lang/String");

    while ($1[len]) len++;    
    jresult = (*jenv)->NewObjectArray(jenv, len, clazz, NULL);
    /* exception checking omitted */

    for (i=0; i<len; i++) {
      temp_string = (*jenv)->NewStringUTF(jenv, *result++);
      (*jenv)->SetObjectArrayElement(jenv, jresult, i, temp_string);
      (*jenv)->DeleteLocalRef(jenv, temp_string);
    }
}

/* These 3 typemaps tell SWIG what JNI and Java types to use */
%typemap(jni) char ** "jobjectArray"
%typemap(jtype) char ** "String[]"
%typemap(jstype) char ** "String[]"

/* These 2 typemaps handle the conversion of the jtype to jstype typemap type
   and visa versa */
%typemap(javain) char ** "$javainput"
%typemap(javaout) char ** {
    return $jnicall;
  }

/* Now a few test functions */
%inline %{

int print_args(char **argv) {
    int i = 0;
    while (argv[i]) {
         printf("argv[%d] = %s\n", i, argv[i]);
         i++;
    }
    return i;
}

char **get_args() {
  static char *values[] = { "Dave", "Mike", "Susan", "John", "Michelle", 0};
  return &values[0];
}

%}

Note that the 'C' JNI calling convention is used. Checking for any thrown exceptions after JNI function calls has been omitted. When this module is compiled, our wrapped C functions can be used by the following Java program:

// File main.java

public class main {

  static {
    try {
     System.loadLibrary("example");
    } catch (UnsatisfiedLinkError e) {
      System.err.println("Native code library failed to load. " + e);
      System.exit(1);
    }
  }

  public static void main(String argv[]) {
    String animals[] = {"Cat","Dog","Cow","Goat"};
    example.print_args(animals);
    String args[] = example.get_args();
    for (int i=0; i<args.length; i++)
        System.out.println(i + ":" + args[i]);
  }
}

When compiled and run we get:

$ java main
argv[0] = Cat
argv[1] = Dog
argv[2] = Cow
argv[3] = Goat
0:Dave
1:Mike
2:Susan
3:John
4:Michelle

In the example, a few different typemaps are used. The "in" typemap is used to receive an input argument and convert it to a C array. Since dynamic memory allocation is used to allocate memory for the array, the "freearg" typemap is used to later release this memory after the execution of the C function. The "out" typemap is used for function return values. Lastly the "jni", "jtype" and "jstype" typemaps are also required to specify what Java types to use.

20.9.5 Expanding a Java object to multiple arguments

Suppose that you had a collection of C functions with arguments such as the following:

int foo(int argc, char **argv);

In the previous example, a typemap was written to pass a Java String array as the char **argv. This allows the function to be used from Java as follows:

example.foo(4, new String[]{"red", "green", "blue", "white"});

Although this works, it's a little awkward to specify the argument count. To fix this, a multi-argument typemap can be defined. This is not very difficult--you only have to make slight modifications to the previous example's typemaps:

%typemap(in) (int argc, char **argv) {
    int i = 0;
    $1 = (*jenv)->GetArrayLength(jenv, $input);
    $2 = (char **) malloc(($1+1)*sizeof(char *));
    /* make a copy of each string */
    for (i = 0; i<$1; i++) {
        jstring j_string = (jstring)(*jenv)->GetObjectArrayElement(jenv, $input, i);
        const char * c_string = (*jenv)->GetStringUTFChars(jenv, j_string, 0);
        $2[i] = malloc(strlen((c_string)+1)*sizeof(const char *));
        strcpy($2[i], c_string);
        (*jenv)->ReleaseStringUTFChars(jenv, j_string, c_string);
        (*jenv)->DeleteLocalRef(jenv, j_string);
    }
    $2[i] = 0;
}

%typemap(freearg) (int argc, char **argv) {
    int i;
    for (i=0; i<$1-1; i++)
      free($2[i]);
    free($2);
}

%typemap(jni) (int argc, char **argv) "jobjectArray"
%typemap(jtype) (int argc, char **argv) "String[]"
%typemap(jstype) (int argc, char **argv) "String[]"

%typemap(javain) (int argc, char **argv) "$javainput"

When writing a multiple-argument typemap, each of the types is referenced by a variable such as $1 or $2. The typemap code simply fills in the appropriate values from the supplied Java parameter.

With the above typemap in place, you will find it no longer necessary to supply the argument count. This is automatically set by the typemap code. For example:

example.foo(new String[]{"red", "green", "blue", "white"});

20.9.6 Using typemaps to return arguments

A common problem in some C programs is that values may be returned in function parameters rather than in the return value of a function. The typemaps.i file defines INPUT, OUTPUT and INOUT typemaps which can be used to solve some instances of this problem. This library file uses an array as a means of moving data to and from Java when wrapping a C function that takes non const pointers or non const references as parameters.

Now we are going to outline an alternative approach to using arrays for C pointers. The INOUT typemap uses a double[] array for receiving and returning the double* parameters. In this approach we are able to use a Java class myDouble instead of double[] arrays where the C pointer double* is required.

Here is our example function:

/* Returns a status value and two values in out1 and out2 */
int spam(double a, double b, double *out1, double *out2);

If we define a structure MyDouble containing a double member variable and use some typemaps we can solve this problem. For example we could put the following through SWIG:

%module example

/* Define a new structure to use instead of double * */
%inline %{
typedef struct {
    double value;
} MyDouble;
%}


%{
/* Returns a status value and two values in out1 and out2 */
int spam(double a, double b, double *out1, double *out2) {
  int status = 1;
  *out1 = a*10.0;
  *out2 = b*100.0;
  return status;
};
%}

/* 
This typemap will make any double * function parameters with name OUTVALUE take an
argument of MyDouble instead of double *. This will 
allow the calling function to read the double * value after returning from the function.
*/
%typemap(in) double *OUTVALUE {
    jclass clazz = jenv->FindClass("MyDouble");
    jfieldID fid = jenv->GetFieldID(clazz, "swigCPtr", "J");
    jlong cPtr = jenv->GetLongField($input, fid);
    MyDouble *pMyDouble = NULL;
    *(MyDouble **)&pMyDouble = *(MyDouble **)&cPtr;
    $1 = &pMyDouble->value;
}

%typemap(jtype) double *OUTVALUE "MyDouble"
%typemap(jstype) double *OUTVALUE "MyDouble"
%typemap(jni) double *OUTVALUE "jobject"

%typemap(javain) double *OUTVALUE "$javainput"

/* Now we apply the typemap to the named variables */
%apply double *OUTVALUE { double *out1, double *out2 };
int spam(double a, double b, double *out1, double *out2);

Note that the C++ JNI calling convention has been used this time and so must be compiled as C++ and the -c++ commandline must be passed to SWIG. JNI error checking has been omitted for clarity.

What the typemaps do are make the named double* function parameters use our new MyDouble wrapper structure. The "in" typemap takes this structure, gets the C++ pointer to it, takes the double value member variable and passes it to the C++ spam function. In Java, when the function returns, we use the SWIG created getValue() function to get the output value. The following Java program demonstrates this:

// File: main.java

public class main {

  static {
    try {
      System.loadLibrary("example");
    } catch (UnsatisfiedLinkError e) {
      System.err.println("Native code library failed to load. " + e);
      System.exit(1);
    }
  }

  public static void main(String argv[]) {
    MyDouble out1 = new MyDouble();
    MyDouble out2 = new MyDouble();
    int ret = example.spam(1.2, 3.4, out1, out2);
    System.out.println(ret + "  " + out1.getValue() + "  " + out2.getValue());
  }
}

When compiled and run we get:

$ java main
1 12.0  340.0

20.9.7 Adding Java downcasts to polymorphic return types

SWIG support for polymorphism works in that the appropriate virtual function is called. However, the default generated code does not allow for downcasting. Let's examine this with the following code:

%include "std_string.i"

#include <iostream>
using namespace std;
class Vehicle {
public:
    virtual void start() = 0;
...
};

class Ambulance : public Vehicle {
    string vol;
public:
    Ambulance(string volume) : vol(volume) {}
    virtual void start() {
        cout << "Ambulance started" << endl;
    }
    void sound_siren() {
        cout << vol << " siren sounded!" << endl;
    }
...
};

Vehicle *vehicle_factory() {
    return new Ambulance("Very loud");
}

If we execute the following Java code:

Vehicle vehicle = example.vehicle_factory();
vehicle.start();

Ambulance ambulance = (Ambulance)vehicle;
ambulance.sound_siren();

We get:

Ambulance started
java.lang.ClassCastException
        at main.main(main.java:16)

Even though we know from examination of the C++ code that vehicle_factory returns an object of type Ambulance, we are not able to use this knowledge to perform the downcast in Java. This occurs because the runtime type information is not completely passed from C++ to Java when returning the type from vehicle_factory(). Usually this is not a problem as virtual functions do work by default, such as in the case of start(). There are a few solutions to getting downcasts to work.

The first is not to use a Java cast but a call to C++ to make the cast. Add this to your code:

%exception Ambulance::dynamic_cast(Vehicle *vehicle) {
    $action
    if (!result) {
        jclass excep = jenv->FindClass("java/lang/ClassCastException");
        if (excep) {
            jenv->ThrowNew(excep, "dynamic_cast exception");
        }
    }
}
%extend Ambulance {
    static Ambulance *dynamic_cast(Vehicle *vehicle) {
        return dynamic_cast<Ambulance *>(vehicle);
    }
};

It would then be used from Java like this

Ambulance ambulance = Ambulance.dynamic_cast(vehicle);
ambulance.sound_siren();

Should vehicle not be of type ambulance then a Java ClassCastException is thrown. The next solution is a purer solution in that Java downcasts can be performed on the types. Add the following before the definition of vehicle_factory:

%typemap(out) Vehicle * {
    Ambulance *downcast = dynamic_cast<Ambulance *>($1);
    *(Ambulance **)&$result = downcast;
}

%typemap(javaout) Vehicle * {
    return new Ambulance($jnicall, $owner);
  }

Here we are using our knowledge that vehicle_factory always returns type Ambulance so that the Java proxy is created as a type Ambulance. If vehicle_factory can manufacture any type of Vehicle and we want to be able to downcast using Java casts for any of these types, then a different approach is needed. Consider expanding our example with a new Vehicle type and a more flexible factory function:

class FireEngine : public Vehicle {
public:
    FireEngine() {}
    virtual void start() {
        cout << "FireEngine started" << endl;
    }
    void roll_out_hose() {
        cout << "Hose rolled out" << endl;
    }
 ...
};
Vehicle *vehicle_factory(int vehicle_number) {
    if (vehicle_number == 0)
        return new Ambulance("Very loud");
    else
        return new FireEngine();
}

To be able to downcast with this sort of Java code:

FireEngine fireengine = (FireEngine)example.vehicle_factory(1);
fireengine.roll_out_hose();
Ambulance ambulance = (Ambulance)example.vehicle_factory(0);
ambulance.sound_siren();

the following typemaps targeted at the vehicle_factory function will achieve this. Note that in this case, the Java class is constructed using JNI code rather than passing a pointer across the JNI boundary in a Java long for construction in Java code.

%typemap(jni) Vehicle *vehicle_factory "jobject"
%typemap(jtype) Vehicle *vehicle_factory "Vehicle"
%typemap(jstype) Vehicle *vehicle_factory "Vehicle"
%typemap(javaout) Vehicle *vehicle_factory {
    return $jnicall;
  }

%typemap(out) Vehicle *vehicle_factory {
    Ambulance *ambulance = dynamic_cast<Ambulance *>($1);
    FireEngine *fireengine = dynamic_cast<FireEngine *>($1);
    if (ambulance) {
        // call the Ambulance(long cPtr, boolean cMemoryOwn) constructor
        jclass clazz = jenv->FindClass("Ambulance");
        if (clazz) {
            jmethodID mid = jenv->GetMethodID(clazz, "<init>", "(JZ)V");
            if (mid) {
                jlong cptr = 0;
                *(Ambulance **)&cptr = ambulance; 
                $result = jenv->NewObject(clazz, mid, cptr, false);
            }
        }
    } else if (fireengine) {
        // call the FireEngine(long cPtr, boolean cMemoryOwn) constructor
        jclass clazz = jenv->FindClass("FireEngine");
        if (clazz) {
            jmethodID mid = jenv->GetMethodID(clazz, "<init>", "(JZ)V");
            if (mid) {
                jlong cptr = 0;
                *(FireEngine **)&cptr = fireengine; 
                $result = jenv->NewObject(clazz, mid, cptr, false);
            }
        }
    }
    else {
        cout << "Unexpected type " << endl;
    }

    if (!$result)
        cout << "Failed to create new java object" << endl;
}

Better error handling would need to be added into this code. There are other solutions to this problem, but this last example demonstrates some more involved JNI code. SWIG usually generates code which constructs the proxy classes using Java code as it is easier to handle error conditions and is faster. Note that the JNI code above uses a number of string lookups to call a constructor, whereas this would not occur using byte compiled Java code.

20.9.8 Adding an equals method to the Java classes

When a pointer is returned from a JNI function, it is wrapped using a new Java proxy class or type wrapper class. Even when the pointers are the same, it will not be possible to know that the two Java classes containing those pointers are actually the same object. It is common in Java to use the equals() method to check whether two objects are equivalent. The equals() method is usually accompanied by a hashCode() method in order to fulfill the requirement that the hash code is equal for equal objects. Pure Java code methods like these can be easily added:

%typemap(javacode) SWIGTYPE %{
  public boolean equals(Object obj) {
    boolean equal = false;
    if (obj instanceof $javaclassname)
      equal = ((($javaclassname)obj).swigCPtr == this.swigCPtr);
    return equal;
  }
  public int hashCode() {
     return (int)getPointer();
  }
%}

class Foo { };
Foo* returnFoo(Foo *foo) { return foo; }

The following would display false without the javacode typemap above. With the typemap defining the equals method the result is true.

Foo foo1 = new Foo();
Foo foo2 = example.returnFoo(foo1);
System.out.println("foo1? " + foo1.equals(foo2));

20.9.9 Void pointers and a common Java base class

One might wonder why the common code that SWIG emits for the proxy and type wrapper classes is not pushed into a base class. The reason is that although swigCPtr could be put into a common base class for all classes wrapping C structures, it would not work for C++ classes involved in an inheritance chain. Each class derived from a base needs a separate swigCPtr because C++ compilers sometimes use a different pointer value when casting a derived class to a base. Additionally as Java only supports single inheritance, it would not be possible to derive wrapped classes from your own pure Java classes if the base class has been 'used up' by SWIG. However, you may want to move some of the common code into a base class. Here is an example which uses a common base class for all proxy classes and type wrapper classes:

%typemap(javabase) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE [], 
                                                         SWIGTYPE (CLASS::*) "SWIG"

%typemap(javacode) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE [], 
                                                         SWIGTYPE (CLASS::*) %{
  protected long getPointer() {
    return swigCPtr;
  }
%}

Define new base class called SWIG:

public abstract class SWIG {
  protected abstract long getPointer();

  public boolean equals(Object obj) {
    boolean equal = false;
    if (obj instanceof SWIG)
      equal = (((SWIG)obj).getPointer() == this.getPointer());
    return equal;
  }
  
  SWIGTYPE_p_void getVoidPointer() {
    return new SWIGTYPE_p_void(getPointer(), false);
  }
}

This example contains some useful functionality which you may want in your code.

20.9.10 Struct pointer to pointer

Pointers to pointers are often used as output parameters in C factory type functions. These are a bit more tricky to handle. Consider the following situation where a Butler can be hired and fired:

typedef struct {
  int hoursAvailable;
  char *greeting;
} Butler;

// Note: HireButler will allocate the memory 
// The caller must free the memory by calling FireButler()!!
extern int HireButler(Butler **ppButler);
extern void FireButler(Butler *pButler);

C code implementation:

int HireButler(Butler **ppButler) {
  Butler *pButler = (Butler *)malloc(sizeof(Butler));
  pButler->hoursAvailable = 24;
  pButler->greeting = (char *)malloc(32);
  strcpy(pButler->greeting, "At your service Sir");
  *ppButler = pButler;
  return 1;
}
void FireButler(Butler *pButler) {
  free(pButler->greeting);
  free(pButler);
}

Let's take two approaches to wrapping this code. The first is to provide a functional interface, much like the original C interface. The following Java code shows how we intend the code to be used:

    Butler jeeves = new Butler();
    example.HireButler(jeeves);
    System.out.println("Greeting:     " + jeeves.getGreeting());
    System.out.println("Availability: " + jeeves.getHoursAvailable() + " hours per day");
    example.FireButler(jeeves);

Resulting in the following output when run:

Greeting:     At your service Sir
Availability: 24 hours per day

Note the usage is very much like it would be used if we were writing C code, that is, explicit memory management is needed. No C memory is allocated in the construction of the Butler proxy class and the proxy class will not destroy the underlying C memory when it is collected. A number of typemaps and features are needed to implement this approach. The following interface file code should be placed before SWIG parses the above C code.

%module example

// Do not generate the default proxy constructor or destructor
%nodefaultctor Butler;
%nodefaultdtor Butler;

// Add in pure Java code proxy constructor
%typemap(javacode) Butler %{
  /** This constructor creates the proxy which initially does not create nor own any C memory */
  public Butler() {
    this(0, false);
  }
%}

// Type typemaps for marshalling Butler **
%typemap(jni) Butler ** "jobject"
%typemap(jtype) Butler ** "Butler"
%typemap(jstype) Butler ** "Butler"

// Typemaps for Butler ** as a parameter output type
%typemap(in) Butler ** (Butler *ppButler = 0) %{
  $1 = &ppButler;
%}
%typemap(argout) Butler ** {
  // Give Java proxy the C pointer (of newly created object)
  jclass clazz = (*jenv)->FindClass(jenv, "Butler");
  jfieldID fid = (*jenv)->GetFieldID(jenv, clazz, "swigCPtr", "J");
  jlong cPtr = 0;
  *(Butler **)&cPtr = *$1;
  (*jenv)->SetLongField(jenv, $input, fid, cPtr);
}
%typemap(javain) Butler ** "$javainput"

Note that the JNI code sets the proxy's swigCPtr member variable to point to the newly created object. The swigCMemOwn remains unchanged (at false), so that the proxy does not own the memory.

Note: The old %nodefault directive disabled the default constructor and destructor at the same time. This is unsafe in most of the cases, and you can use the explicit %nodefaultctor and %nodefaultdtor directives to achieve the same result if needed.

The second approach offers a more object oriented interface to the Java user. We do this by making the Java proxy class's constructor call the HireButler() method to create the underlying C object. Additionally we get the proxy to take ownership of the memory so that the finalizer will call the FireButler() function. The proxy class will thus take ownership of the memory and clean it up when no longer needed. We will also prevent the user from being able to explicitly call the HireButler() and FireButler() functions. Usage from Java will simply be:

Butler jeeves = new Butler();
System.out.println("Greeting:     " + jeeves.getGreeting());
System.out.println("Availability: " + jeeves.getHoursAvailable() + " hours per day");

Note that the Butler class is used just like any other Java class and no extra coding by the user needs to be written to clear up the underlying C memory as the finalizer will be called by the garbage collector which in turn will call the FireButler() function. To implement this, we use the above interface file code but remove the javacode typemap and add the following:

// Don't expose the memory allocation/de-allocation functions
%ignore FireButler(Butler *pButler);
%ignore HireButler(Butler **ppButler);

// Add in a custom proxy constructor and destructor
%extend Butler {
  Butler() {
    Butler *pButler = 0;
    HireButler(&pButler);
    return pButler;
  }
  ~Butler() {
     FireButler($self);
   }
}

Note that the code in %extend is using a C++ type constructor and destructor, yet the generated code will still compile as C code, see Adding member functions to C structures. The C functional interface has been completely morphed into an object-oriented interface and the Butler class would behave much like any pure Java class and feel more natural to Java users.

20.9.11 Memory management when returning references to member variables

This example shows how to prevent premature garbage collection of objects when the underlying C++ class returns a pointer or reference to a member variable.

Consider the following C++ code:

struct Wheel {
  int size;
  Wheel(int sz) : size(sz) {}
};

class Bike {
  Wheel wheel;
public:
  Bike(int val) : wheel(val) {}
  Wheel& getWheel() { return wheel; }
};

and the following usage from Java after running the code through SWIG:

    Wheel wheel = new Bike(10).getWheel();
    System.out.println("wheel size: " + wheel.getSize());
    // Simulate a garbage collection
    System.gc();
    System.runFinalization();
    System.out.println("wheel size: " + wheel.getSize());

Don't be surprised that if the resulting output gives strange results such as...

wheel size: 10
wheel size: 135019664

What has happened here is the garbage collector has collected the Bike instance as it doesn't think it is needed any more. The proxy instance, wheel, contains a reference to memory that was deleted when the Bike instance was collected. In order to prevent the garbage collector from collecting the Bike instance a reference to the Bike must be added to the wheel instance. You can do this by adding the reference when the getWheel() method is called using the following typemaps.

%typemap(javacode) Wheel %{
  // Ensure that the GC doesn't collect any Bike instance set from Java
  private Bike bikeReference;
  protected void addReference(Bike bike) {
    bikeReference = bike;
  }
%}

// Add a Java reference to prevent premature garbage collection and resulting use
// of dangling C++ pointer. Intended for methods that return pointers or
// references to a member variable.
%typemap(javaout) Wheel& getWheel {
    long cPtr = $jnicall;
    $javaclassname ret = null;
    if (cPtr != 0) {
      ret = new $javaclassname(cPtr, $owner);
      ret.addReference(this);
    }
    return ret;
  }

The code in the first typemap gets added to the Wheel proxy class. The code in the second typemap constitutes the bulk of the code in the generated getWheel() function:

public class Wheel {
  ...
  // Ensure that the GC doesn't collect any bike set from Java 
  private Bike bikeReference;
  protected void addReference(Bike bike) {
    bikeReference = bike;
  }
}

public class Bike {
  ...
  public Wheel getWheel() {
    long cPtr = exampleJNI.Bike_getWheel(swigCPtr, this);
    Wheel ret = null;
    if (cPtr != 0) {
      ret = new Wheel(cPtr, false);
      ret.addReference(this);
    }
    return ret;
  }
}

Note the addReference call.

20.9.12 Memory management for objects passed to the C++ layer

Managing memory can be tricky when using C++ and Java proxy classes. The previous example shows one such case and this example looks at memory management for a class passed to a C++ method which expects the object to remain in scope after the function has returned. Consider the following two C++ classes:

struct Element {
  int value;
  Element(int val) : value(val) {}
};
class Container {
  Element* element;
public:
  Container() : element(0) {}
  void setElement(Element* e) { element = e; }
  Element* getElement() { return element; }
};

and usage from C++

    Container container;
    Element element(20);
    container.setElement(&element);
    cout << "element.value: " << container.getElement()->value << endl;

and more or less equivalent usage from Java

    Container container = new Container();
    container.setElement(new Element(20));
    System.out.println("element value: " + container.getElement().getValue());

The C++ code will always print out 20, but the value printed out may not be this in the Java equivalent code. In order to understand why, consider a garbage collection occuring...

    Container container = new Container();
    container.setElement(new Element(20));
    // Simulate a garbage collection
    System.gc();
    System.runFinalization();
    System.out.println("element value: " + container.getElement().getValue());

The temporary element created with new Element(20) could get garbage collected which ultimately means the container variable is holding a dangling pointer, thereby printing out any old random value instead of the expected value of 20. One solution is to add in the appropriate references in the Java layer...

public class Container {

  ...

  // Ensure that the GC doesn't collect any Element set from Java
  // as the underlying C++ class stores a shallow copy
  private Element elementReference;
  private long getCPtrAndAddReference(Element element) {
    elementReference = element;
    return Element.getCPtr(element);
  }

  public void setElement(Element e) {
    exampleJNI.Container_setElement(swigCPtr, this, getCPtrAndAddReference(e), e);
  }
}

The following typemaps will generate the desired code. The 'javain' typemap matches the input parameter type for the setElement method. The 'javacode' typemap simply adds in the specified code into the Java proxy class.

%typemap(javain) Element *e "getCPtrAndAddReference($javainput)"

%typemap(javacode) Container %{
  // Ensure that the GC doesn't collect any element set from Java
  // as the underlying C++ class stores a shallow copy
  private Element elementReference;
  private long getCPtrAndAddReference(Element element) {
    elementReference = element;
    return Element.getCPtr(element);
  }
%}

20.10 Living with Java Directors

This section is intended to address frequently asked questions and frequently encountered problems when using Java directors.

  1. When my program starts up, it complains that method_foo cannot be found in a Java method called swig_module_init. How do I fix this?

    Open up the C++ wrapper source code file and look for "method_foo" (include the double quotes, they are important!) Look at the JNI field descriptor and make sure that each class that occurs in the descriptor has the correct package name in front of it. If the package name is incorrect, put a "javapackage" typemap in your SWIG interface file.

  2. I'm compiling my code and I'm using templates. I provided a javapackage typemap, but SWIG doesn't generate the right JNI field descriptor.

    Use the template's renamed name as the argument to the "javapackage" typemap:

    %typemap(javapackage)  std::vector<int>  "your.package.here"
    %template(VectorOfInt) std::vector<int>;
    
  3. When I pass class pointers or references through a C++ upcall and I try to type cast them, Java complains with a ClassCastException. What am I doing wrong?

    Normally, a non-director generated Java proxy class creates temporary Java objects as follows:

    public static void MyClass_method_upcall(MyClass self, long jarg1)
    {
      Foo darg1 = new Foo(jarg1, false);
    
      self.method_upcall(darg1);
    }
    

    Unfortunately, this loses the Java type information that is part of the underlying Foo director proxy class's Java object pointer causing the type cast to fail. The SWIG Java module's director code attempts to correct the problem, but only for director-enabled classes, since the director class retains a global reference to its Java object. Thus, for director-enabled classes and only for director-enabled classes, the generated proxy Java code looks something like:

    public static void MyClass_method_upcall(MyClass self, long jarg1,
                                             Foo jarg1_object)
    {
      Foo darg1 = (jarg1_object != null ? jarg1_object : new Foo(jarg1, false));
    
      self.method_upcall(darg1);
    }
    

    When you import a SWIG interface file containing class definitions, the classes you want to be director-enabled must be have the feature("director") enabled for type symmetry to work. This applies even when the class being wrapped isn't a director-enabled class but takes parameters that are director-enabled classes.

    The current "type symmetry" design will work for simple C++ inheritance, but will most likely fail for anything more complicated such as tree or diamond C++ inheritance hierarchies. Those who are interested in challenging problems are more than welcome to hack the Java::Java_director_declaration method in Source/Modules/java.cxx.

    If all else fails, you can use the downcastXXXXX() method to attempt to recover the director class's Java object pointer. For the Java Foo proxy class, the Foo director class's java object pointer can be accessed through the javaObjectFoo() method. The generated method's signature is:

      public static Foo javaObjectFoo(Foo obj);
    

    From your code, this method is invoked as follows:

    public class MyClassDerived {
      public void method_upcall(Foo foo_object)
      {
        FooDerived    derived = (foo_object != null ?
                     (FooDerived) Foo.downcastFoo(foo_object) : null);
        /* rest of your code here */
      }
    }
    

    An good approach for managing downcasting is placing a static method in each derived class that performs the downcast from the superclass, e.g.,

    public class FooDerived extends Foo {
      /* ... */
      public static FooDerived downcastFooDerived(Foo foo_object)
      {
        try {
         return (foo_object != null ? (FooDerived) Foo.downcastFoo(foo_object);
        }
    
        catch (ClassCastException exc) {
          // Wasn't a FooDerived object, some other subclass of Foo
          return null;
        }
      }
    }
    

    Then change the code in MyClassDerived as follows:

    public class MyClassDerived extends MyClass {
      /* ... */
      public void method_upcall(Foo foo_object)
      {
        FooDerived    derived = FooDerived.downcastFooDerived(foo_object);
        /* rest of your code here */
      }
    }
    
  4. Why isn't the proxy class declared abstract? Why aren't the director upcall methods in the proxy class declared abstract?

    Declaring the proxy class and its methods abstract would break the JNI argument marshalling and SWIG's downcall functionality (going from Java to C++.) Create an abstract Java subclass that inherits from the director-enabled class instead. Using the previous Foo class example:

    public abstract class UserVisibleFoo extends Foo {
      /** Make sure user overrides this method, it's where the upcall
       * happens.
       */
      public abstract void method_upcall(Foo foo_object);
    
      /// Downcast from Foo to UserVisibleFoo
      public static UserVisibleFoo downcastUserVisibleFoo(Foo foo_object)
      {
        try {
         return (foo_object != null ? (FooDerived) Foo.downcastFoo(foo_object) : null);
        }
    
        catch (ClassCastException exc) {
          // Wasn't a FooDerived object, some other subclass of Foo
          return null;
        }
      }
    }
    

    This doesn't prevent the user from creating subclasses derived from Foo, however, UserVisibleFoo provides the safety net that reminds the user to override the method_upcall() method.

20.11 Odds and ends

20.11.1 JavaDoc comments

The SWIG documentation system is currently deprecated. When it is resurrected JavaDoc comments will be fully supported. If you can't wait for the full documentation system a couple of workarounds are available. The %javamethodmodifiers feature can be used for adding proxy class method comments and module class method comments. The "javaimports" typemap can be hijacked for adding in proxy class JavaDoc comments. The jniclassimports or jniclassclassmodifiers pragmas can also be used for adding intermediary JNI class comments and likewise the moduleimports or moduleclassmodifiers pragmas for the module class. Here is an example adding in a proxy class and method comment:

%javamethodmodifiers Barmy::lose_marbles() "
  /**
    * Calling this method will make you mad.
    * Use with <b>utmost</b> caution. 
    */
  public";

%typemap(javaimports) Barmy "
/** The crazy class. Use as a last resort. */"

class Barmy {
public:
  void lose_marbles() {}
};

Note the "public" added at the end of the %javamethodmodifiers as this is the default for this feature. The generated proxy class with JavaDoc comments is then as follows:

/** The crazy class. Use as a last resort. */
public class Barmy {
...
  /**
    * Calling this method will make you mad.
    * Use with <b>utmost</b> caution. 
    */
  public void lose_marbles() {
    ...
  }
...
}

20.11.2 Functional interface without proxy classes

It is possible to run SWIG in a mode that does not produce proxy classes by using the -noproxy commandline option. The interface is rather primitive when wrapping structures or classes and is accessed through function calls to the module class. All the functions in the module class are wrapped by functions with identical names as those in the intermediary JNI class.

Consider the example we looked at when examining proxy classes:

class Foo {
public:
     int x;
     int spam(int num, Foo* foo);
};

When using -noproxy, type wrapper classes are generated instead of proxy classes. Access to all the functions and variables is through a C like set of functions where the first parameter passed is the pointer to the class, that is an instance of a type wrapper class. Here is what the module class looks like:

public class example {
  public static void Foo_x_get(SWIGTYPE_p_Foo self, int x) {...}
  public static int Foo_x_get(SWIGTYPE_p_Foo self) {...}
  public static int Foo_spam(SWIGTYPE_p_Foo self, int num, SWIGTYPE_p_Foo foo) {...}
  public static SWIGTYPE_p_Foo new_Foo() {...}
  public static void delete_Foo(SWIGTYPE_p_Foo self) {...}
}

This approach is not nearly as natural as using proxy classes as the functions need to be used like this:

SWIGTYPE_p_Foo foo = example.new_Foo();
example.Foo_x_set(foo, 10);
int var = example.Foo_x_get(foo);
example.Foo_spam(foo, 20, foo);
example.delete_Foo(foo);

Unlike proxy classes, there is no attempt at tracking memory. All destructors have to be called manually for example the delete_Foo(foo) call above.

20.11.3 Using your own JNI functions

You may have some hand written JNI functions that you want to use in addition to the SWIG generated JNI functions. Adding these to your SWIG generated package is possible using the %native directive. If you don't want SWIG to wrap your JNI function then of course you can simply use the %ignore directive. However, if you want SWIG to generate just the Java code for a JNI function then use the %native directive. The C types for the parameters and return type must be specified in place of the JNI types and the function name must be the native method name. For example:

%native (HandRolled) void HandRolled(int, char *);
%{
JNIEXPORT void JNICALL Java_packageName_moduleName_HandRolled(JNIEnv *, jclass,
                                                              jlong, jstring);
%}

No C JNI function will be generated and the Java_packageName_moduleName_HandRolled function will be accessible using the SWIG generated Java native method call in the intermediary JNI class which will look like this:

  public final static native void HandRolled(int jarg1, String jarg2);

and as usual this function is wrapped by another which for a global C function would appear in the module class:

  public static void HandRolled(int arg0, String arg1) {
    exampleJNI.HandRolled(arg0, arg1);
  }

The packageName and moduleName must of course be correct else you will get linker errors when the JVM dynamically loads the JNI function. You may have to add in some "jtype", "jstype", "javain" and "javaout" typemaps when wrapping some JNI types. Here the default typemaps work for int and char *.

In summary the %native directive is telling SWIG to generate the Java code to access the JNI C code, but not the JNI C function itself. This directive is only really useful if you want to mix your own hand crafted JNI code and the SWIG generated code into one Java class or package.

20.11.4 Performance concerns and hints

If you're directly manipulating huge arrays of complex objects from Java, performance may suffer greatly when using the array functions in arrays_java.i. Try and minimise the expensive JNI calls to C/C++ functions, perhaps by using temporary Java variables instead of accessing the information directly from the C/C++ object.

Java classes without any finalizers generally speed up code execution as there is less for the garbage collector to do. Finalizer generation can be stopped by using an empty javafinalize typemap:

%typemap(javafinalize) SWIGTYPE ""

However, you will have to be careful about memory management and make sure that you code in a call to the delete() member function. This method normally calls the C++ destructor or free() for C code.

20.12 Examples

The directory Examples/java has a number of further examples. Take a look at these if you want to see some of the techniques described in action. The Examples/index.html file in the parent directory contains the SWIG Examples Documentation and is a useful starting point. If your SWIG installation went well Unix users should be able to type make in each example directory, then java main to see them running. For the benefit of Windows users, there are also Visual C++ project files in a couple of the Windows Examples.


21 SWIG and Common Lisp

Common Lisp is a high-level, all-purpose, object-oriented, dynamic, functional programming language with long history. Common Lisp is used in many fields, ranging from web development to finance, and also common in computer science education. There are more than 9 different implementations of common lisp which are available, all have different foreign function interfaces. SWIG currently supports only the Allegro Common Lisp, Common Foreign Function Interface(CFFI), CLisp and UFFI foreign function interfaces.

21.1 Allegro Common Lisp

Allegro Common Lisp support in SWIG has been updated to include support for both C and C++. You can read about the interface here

21.2 Common Foreign Function Interface(CFFI)

CFFI, the Common Foreign Function Interface, is a portable foreign function interface for ANSI Common Lisp systems, similar in spirit to UFFI. Unlike UFFI, CFFI requires only a small set of low-level functionality from the Lisp implementation, such as calling a foreign function by name, allocating foreign memory, and dereferencing pointers.

To run the cffi module of SWIG requires very little effort, you just need to run:

swig -cffi -module module-name   file-name 

But a better was of using all the power of SWIG is to write SWIG interface files. Below we will explain how to write interface files and the various things which you can do with them.

21.2.1 Additional Commandline Options

The following table list the additional commandline options available for the CLISP module. They can also be seen by using:

swig -cffi -help 

CFFI specific options
-generate-typedefIf this option is given then defctype will be used to generate shortcuts according to the typedefs in the input.
-[no]cwrapTurn on or turn off generation of an intermediate C file when creating a C interface. By default this is only done for C++ code.
-[no]swig-lispTurns on or off generation of code for helper lisp macro, functions, etc. which SWIG uses while generating wrappers. These macros, functions may still be used by generated wrapper code.

21.2.2 Generating CFFI bindings

As we mentioned earlier the ideal way to use SWIG is to use interface files. To illustrate the use of it, lets assume that we have a file named test.h with the following C code:
#define y 5
#define x (y >>  1)

typedef int days;

struct bar {
  short p, q;
    char a, b;
    int *z[1000];
    struct bar * n;
};
  
struct   bar * my_struct;

struct foo {
    int a;
    struct foo * b[100];
  
};

int pointer_func(void (*ClosureFun)( void* _fun, void* _data, void* _evt ), int p);

int func123(div_t * p,int **q[100],int r[][1000][10]);

void lispsort_double (int n, double * array);

enum color { RED, BLUE, GREEN};
Corresponding to this we will write a simple interface file:
%module test

%include "test.h"

The generated SWIG Code will be:
;;;SWIG wrapper code starts here

(cl:defmacro defanonenum (&body enums)
   "Converts anonymous enums to defconstants."
  `(cl:progn ,@(cl:loop for value in enums
                        for index = 0 then (cl:1+ index)
                        when (cl:listp value) do (cl:setf index (cl:second value)
                                                          value (cl:first value))
                        collect `(cl:defconstant ,value ,index))))

(cl:eval-when (:compile-toplevel :load-toplevel)
  (cl:unless (cl:fboundp 'swig-lispify)
    (cl:defun swig-lispify (name flag cl:&optional (package cl:*package*))
      (cl:labels ((helper (lst last rest cl:&aux (c (cl:car lst)))
                    (cl:cond
                      ((cl:null lst)
                       rest)
                      ((cl:upper-case-p c)
                       (helper (cl:cdr lst) 'upper
                               (cl:case last
                                 ((lower digit) (cl:list* c #\- rest))
                                 (cl:t (cl:cons c rest)))))
                      ((cl:lower-case-p c)
                       (helper (cl:cdr lst) 'lower (cl:cons (cl:char-upcase c) rest)))
                      ((cl:digit-char-p c)
                       (helper (cl:cdr lst) 'digit 
                               (cl:case last
                                 ((upper lower) (cl:list* c #\- rest))
                                 (cl:t (cl:cons c rest)))))
                      ((cl:char-equal c #\_)
                       (helper (cl:cdr lst) '_ (cl:cons #\- rest)))
                      (cl:t
                       (cl:error "Invalid character: ~A" c)))))
        (cl:let ((fix (cl:case flag
                        ((constant enumvalue) "+")
                        (variable "*")
                        (cl:t ""))))
          (cl:intern
           (cl:concatenate
            'cl:string
            fix
            (cl:nreverse (helper (cl:concatenate 'cl:list name) cl:nil cl:nil))
            fix)
           package))))))

;;;SWIG wrapper code ends here


(cl:defconstant y 5)

(cl:defconstant x (cl:ash 5 -1))

(cffi:defcstruct bar
	(p :short)
	(q :short)
	(a :char)
	(b :char)
	(z :pointer)
	(n :pointer))

(cffi:defcvar ("my_struct" my_struct)
 :pointer)

(cffi:defcstruct foo
	(a :int)
	(b :pointer))

(cffi:defcfun ("pointer_func" pointer_func) :int
  (ClosureFun :pointer)
  (p :int))

(cffi:defcfun ("func123" func123) :int
  (p :pointer)
  (q :pointer)
  (r :pointer))

(cffi:defcfun ("lispsort_double" lispsort_double) :void
  (n :int)
  (array :pointer))

(cffi:defcenum color
	:RED
	:BLUE
	:GREEN)

The SWIG wrapper code refers to the special code which SWIG may need to use while wrapping C code. You can turn on/off the generation of this code by using the -[no]swig-lisp option. You must have noticed that SWIG goes one extra step to ensure that CFFI does not do automatic lispification of the C function names. The reason SWIG does this is because quite often developers want to build a nice CLOS based lispy API, and this one to one correspondence between C function names and lisp function name helps.

Maybe you want to have your own convention for generating lisp function names for corresponding C function names, or you just want to lispify the names, also, before we forget you want to export the generated lisp names. To do this, we will use the SWIG feature directive. Lets edit the interface file such that the C type "div_t*" is changed to Lisp type ":my-pointer", we lispify all names, export everything, and do some more stuff.

%module test

%typemap(cin) div_t* ":my-pointer";

%feature("intern_function","1");
%feature("export");

%feature("inline") lispsort_double;

%feature("intern_function", "my-lispify") lispsort_double;
%rename func123 renamed_cool_func;
%ignore "pointer_func";

%include "test.h"

The typemap(cin) ensures that for all arguments which are input to C with the type "div_t*", the ":my-pointer" type be used. Similarly typemap(cout) are used for all types which are returned from C.

The feature intern_function ensures that all C names are interned using the swig-lispify function. The "1" given to the feature is optional. The use of feature like %feature("intern_function","1"); globally enables interning for everything. If you want to target a single function, or declaration then use the targeted version of feature, %feature("intern_function", "my-lispify") lispsort_double;, here we are using an additional feature which allows us to use our lispify function.

The export feature allows us to export the symbols. The inline feature declaims the declared function as inline. The rename directive allows us to change the name(it is useful when generating C wrapper code for handling overloaded functions). The ignore directive ignores a certain declaration.

There are several other things which are possible, to see some example of usage of SWIG look at the Lispbuilder and wxCL projects. The generated code with 'noswig-lisp' option is:

(cl:defconstant #.(swig-lispify "y" 'constant) 5)

(cl:export '#.(swig-lispify "y" 'constant))

(cl:defconstant #.(swig-lispify "x" 'constant) (cl:ash 5 -1))

(cl:export '#.(swig-lispify "x" 'constant))

(cffi:defcstruct #.(swig-lispify "bar" 'classname)
	(#.(swig-lispify "p" 'slotname) :short)
	(#.(swig-lispify "q" 'slotname) :short)
	(#.(swig-lispify "a" 'slotname) :char)
	(#.(swig-lispify "b" 'slotname) :char)
	(#.(swig-lispify "z" 'slotname) :pointer)
	(#.(swig-lispify "n" 'slotname) :pointer))

(cl:export '#.(swig-lispify "bar" 'classname))

(cl:export '#.(swig-lispify "p" 'slotname))

(cl:export '#.(swig-lispify "q" 'slotname))

(cl:export '#.(swig-lispify "a" 'slotname))

(cl:export '#.(swig-lispify "b" 'slotname))

(cl:export '#.(swig-lispify "z" 'slotname))

(cl:export '#.(swig-lispify "n" 'slotname))

(cffi:defcvar ("my_struct" #.(swig-lispify "my_struct" 'variable))
 :pointer)

(cl:export '#.(swig-lispify "my_struct" 'variable))

(cffi:defcstruct #.(swig-lispify "foo" 'classname)
	(#.(swig-lispify "a" 'slotname) :int)
	(#.(swig-lispify "b" 'slotname) :pointer))

(cl:export '#.(swig-lispify "foo" 'classname))

(cl:export '#.(swig-lispify "a" 'slotname))

(cl:export '#.(swig-lispify "b" 'slotname))

(cffi:defcfun ("renamed_cool_func" #.(swig-lispify "renamed_cool_func" 'function)) :int
  (p :my-pointer)
  (q :pointer)
  (r :pointer))

(cl:export '#.(swig-lispify "renamed_cool_func" 'function))

(cl:declaim (cl:inline #.(my-lispify "lispsort_double" 'function)))

(cffi:defcfun ("lispsort_double" #.(my-lispify "lispsort_double" 'function)) :void
  (n :int)
  (array :pointer))

(cl:export '#.(my-lispify "lispsort_double" 'function))

(cffi:defcenum #.(swig-lispify "color" 'enumname)
	#.(swig-lispify "RED" 'enumvalue :keyword)
	#.(swig-lispify "BLUE" 'enumvalue :keyword)
	#.(swig-lispify "GREEN" 'enumvalue :keyword))

(cl:export '#.(swig-lispify "color" 'enumname))

21.2.3 Generating CFFI bindings for C++ code

This feature to SWIG (for CFFI) is very new and still far from complete. Pitch in with your patches, bug reports and feature requests to improve it.

Generating bindings for C++ code, requires -c++ option to be present and it first generates C binding which will wrap the C++ code, and then generates the corresponding CFFI wrapper code. In the generated C wrapper code, you will often want to put your own C code, such as the code to include various files. This can be done by making use of "%{" and "%}" as shown below.

%{
 #include "Test/test.h"
%}

Also, while parsing the C++ file and generating C wrapper code SWIG may need to be able to understand various symbols used in other header files. To help SWIG in doing this while ensuring that wrapper code is generated for the target file, use the "import" directive. The "include" directive specifies the target file for which wrapper code will be generated.


%import "ancillary/header.h"

%include "target/header.h"

Various features which were available for C headers can also be used here. The target header which we are going to use here is:
namespace OpenDemo {
  class Test
    {
    public:
        float x;
        // constructors
        Test (void) {x = 0;}
        Test (float X) {x = X;}

        // vector addition
        Test operator+ (const Test& v) const {return Test (x+v.x);}

      // length squared
        float lengthSquared (void) const {return this->dot (*this);}

        static float distance (const Test& a, const Test& b){return(a-b).length();}

        inline Test parallelComponent (const Test& unitBasis) const {
          return unitBasis * projection;
        }

        Test setYtoZero (void) const {return Test (this->x);}

        static const Test zero;
    };


   inline Test operator* (float s, const Test& v) {return v*s;}


    inline std::ostream& operator<< (std::ostream& o, const Test& v)
    {
        return o << "(" << v.x << ")";
    }


    inline Test RandomUnitVectorOnXZPlane (void)
    {
        return RandomVectorInUnitRadiusSphere().setYtoZero().normalize();
    }
}

The interface used is:

%module test
%include "test.cpp"
SWIG generates 3 files, the first one is a C wrap which we don't show, the second is the plain CFFI wrapper which is as shown below:
(cffi:defcfun ("_wrap_Test_x_set" Test_x_set) :void
  (self :pointer)
  (x :float))

(cffi:defcfun ("_wrap_Test_x_get" Test_x_get) :float
  (self :pointer))

(cffi:defcfun ("_wrap_new_Test__SWIG_0" new_Test) :pointer)

(cffi:defcfun ("_wrap_new_Test__SWIG_1" new_Test) :pointer
  (X :float))

(cffi:defcfun ("_wrap_Test___add__" Test___add__) :pointer
  (self :pointer)
  (v :pointer))

(cffi:defcfun ("_wrap_Test_lengthSquared" Test_lengthSquared) :float
  (self :pointer))

(cffi:defcfun ("_wrap_Test_distance" Test_distance) :float
  (a :pointer)
  (b :pointer))

(cffi:defcfun ("_wrap_Test_parallelComponent" Test_parallelComponent) :pointer
  (self :pointer)
  (unitBasis :pointer))

(cffi:defcfun ("_wrap_Test_setYtoZero" Test_setYtoZero) :pointer
  (self :pointer))

(cffi:defcvar ("Test_zero" Test_zero)
 :pointer)

(cffi:defcfun ("_wrap_delete_Test" delete_Test) :void
  (self :pointer))

(cffi:defcfun ("_wrap___mul__" __mul__) :pointer
  (s :float)
  (v :pointer))

(cffi:defcfun ("_wrap___lshift__" __lshift__) :pointer
  (o :pointer)
  (v :pointer))

(cffi:defcfun ("_wrap_RandomUnitVectorOnXZPlane" RandomUnitVectorOnXZPlane) :pointer)
The output is pretty good but it fails in disambiguating overloaded functions such as the constructor, in this case. One way of resolving this problem is to make the interface use the rename directiv, but hopefully there are better solutions. In addition SWIG also generates, a CLOS file
(clos:defclass test()
  ((ff :reader ff-pointer)))

(clos:defmethod (cl:setf x) (arg0 (obj test))
  (Test_x_set (ff-pointer obj) arg0))

(clos:defmethod x ((obj test))
  (Test_x_get (ff-pointer obj)))

(cl:shadow "+")
(clos:defmethod + ((obj test) (self test) (v test))
  (Test___add__ (ff-pointer obj) (ff-pointer self) (ff-pointer v)))

(clos:defmethod length-squared ((obj test) (self test))
  (Test_lengthSquared (ff-pointer obj) (ff-pointer self)))

(clos:defmethod parallel-component ((obj test) (self test) (unitBasis test))
  (Test_parallelComponent (ff-pointer obj) (ff-pointer self) (ff-pointer unitBasis)))

(clos:defmethod set-yto-zero ((obj test) (self test))
  (Test_setYtoZero (ff-pointer obj) (ff-pointer self)))

I agree that the CFFI C++ module needs lot more work. But I hope it provides a starting point, on which you can base your work of importing C++ libraries to Lisp.

If you have any questions, suggestions, patches, etc., related to CFFI module feel free to contact us on the SWIG mailing list, and also please add a "[CFFI]" tag in the subject line.

21.3 CLISP

CLISP is a feature-loaded implementation of common lisp which is portable across most of the operating system environments and hardware. CLISP includes an interpreter, a compiler, a debugger, CLOS, MOP, a foreign language interface, i18n, regular expressions, a socket interface, and more. An X11 interface is available through CLX, Garnet and CLUE/CLIO. Command line editing is provided by readline. CLISP runs Maxima, ACL2 and many other Common Lisp packages.

To run the clisp module of SWIG requires very little effort, you just need to execute:

swig -clisp -module module-name   file-name 

Because of the high level nature of the CLISP FFI, the bindings generated by SWIG may not be absolutely correct, and you may need to modify them. The good thing is that you don't need to complex interface file for the CLISP module. The CLISP module tries to produce code which is both human readable and easily modifyable.

21.3.1 Additional Commandline Options

The following table list the additional commandline options available for the CLISP module. They can also be seen by using:

swig -clisp -help 

CLISP specific options
-extern-allIf this option is given then clisp definitions for all the functions
and global variables will be created otherwise only definitions for
externed functions and variables are created.
-generate-typedefIf this option is given then def-c-type will be used to generate
shortcuts according to the typedefs in the input.

21.3.2 Details on CLISP bindings

As mentioned earlier the CLISP bindings generated by SWIG may need some modifications. The clisp module creates a lisp file with the same name as the module name. This lisp file contains a 'defpackage' declaration, with the package name same as the module name. This package uses the 'common-lisp' and 'ffi' packages. Also, package exports all the functions, structures and variables for which an ffi binding was generated.
After generating the defpackage statement, the clisp module also sets the default language.

(defpackage :test
    (:use :common-lisp :ffi)
  (:export
   :make-bar
   :bar-x
   :bar-y
   :bar-a
   :bar-b
   :bar-z
   :bar-n
   :pointer_func
   :func123
   :make-cfunr
   :lispsort_double
   :test123))

(in-package :test)

(default-foreign-language :stdc)

The ffi wrappers for functions and variables are generated as shown below. When functions have arguments of type "double * array", SWIG doesn't knows whether it is an 'out' argument or it is an array which will be passed, so SWIG plays it safe by declaring it as an '(array (ffi:c-ptr DOUBLE-FLOAT))'. For arguments of type "int **z[100]" where SWIG has more information, i.e., it knows that 'z' is an array of pointers to pointers of integers, SWIG defines it to be '(z (ffi:c-ptr (ffi:c-array (ffi:c-ptr (ffi:c-ptr ffi:int)) 100)))'

extern "C" {
int pointer_func(void (*ClosureFun)( void* _fun, void* _data, void* _evt ), int y);

int func123(div_t * x,int **z[100],int y[][1000][10]);

void lispsort_double (int n, double * array);

void test123(float x , double y);

}
(ffi:def-call-out pointer_func
    (:name "pointer_func")
  (:arguments (ClosureFun (ffi:c-function (:arguments (arg0 (ffi:c-pointer NIL))
						      (arg1 (ffi:c-pointer NIL))
						      (arg2 (ffi:c-pointer NIL)))
					  (:return-type NIL)))
	      (y ffi:int))
  (:return-type ffi:int)
  (:library +library-name+))

(ffi:def-call-out func123
    (:name "func123")
  (:arguments (x (ffi:c-pointer div_t))
	      (z (ffi:c-ptr (ffi:c-array (ffi:c-ptr (ffi:c-ptr ffi:int)) 100)))
	      (y (ffi:c-ptr (ffi:c-ptr (ffi:c-array ffi:int (1000 10))))))
  (:return-type ffi:int)
  (:library +library-name+))


(ffi:def-call-out lispsort_double
    (:name "lispsort_double")
  (:arguments (n ffi:int)
	      (array (ffi:c-ptr DOUBLE-FLOAT)))
  (:return-type NIL)
  (:library +library-name+))

(ffi:def-call-out test123
    (:name "test")
  (:arguments (x SINGLE-FLOAT)
	      (y DOUBLE-FLOAT))
  (:return-type NIL)
  (:library +library-name+))

The module also handles strutcures and #define constants as shown below. SWIG automatically adds the constructors and accessors created for the struct to the list of symbols exported by the package.

struct bar {
    short x, y;
    char a, b;
    int *z[1000];
    struct bar * n;
};

#define max 1000
(ffi:def-c-struct bar
    (x :type ffi:short)
  (y :type ffi:short)
  (a :type character)
  (b :type character)
  (z :type (ffi:c-array (ffi:c-ptr ffi:int) 1000))
  (n :type (ffi:c-pointer bar)))

(defconstant max 1000)

21.4 UFFI


22 SWIG and Lua

Lua is an extension programming language designed to support general procedural programming with data description facilities. It also offers good support for object-oriented programming, functional programming, and data-driven programming. Lua is intended to be used as a powerful, light-weight configuration language for any program that needs one. Lua is implemented as a library, written in clean C (that is, in the common subset of ANSI C and C++). Its also a really tiny language, less than 6000 lines of code, which compiles to <100 kilobytes of binary code. It can be found at http://www.lua.org

22.1 Preliminaries

The current SWIG implementation is designed to work with Lua 5.0. It should work with later versions of Lua, but certainly not with Lua 4.0 due to substantial API changes. ((Currently SWIG generated code has only been tested on Windows with MingW, though given the nature of Lua, is should not have problems on other OS's)). It is possible to either static link or dynamic link a Lua module into the interpreter (normally Lua static links its libraries, as dynamic linking is not available on all platforms).

Note: Lua 5.1 (alpha) has just (as of September 05) been released. The current version of SWIG will produce wrappers which are compatible with Lua 5.1, though the dynamic loading mechanism has changed (see below). The configure script and makefiles should work correctly with with Lua 5.1, though some small tweaks may be needed.

22.2 Running SWIG

Suppose that you defined a SWIG module such as the following:

%module example
%{
#include "example.h"
%}
int gcd(int x, int y);
extern double Foo;

To build a Lua module, run SWIG using the -lua option.

$ swig -lua example.i

If building a C++ extension, add the -c++ option:

$ swig -c++ -lua example.i

This creates a C/C++ source file example_wrap.c or example_wrap.cxx. The generated C source file contains the low-level wrappers that need to be compiled and linked with the rest of your C/C++ application to create an extension module.

The name of the wrapper file is derived from the name of the input file. For example, if the input file is example.i, the name of the wrapper file is example_wrap.c. To change this, you can use the -o option. The wrappered module will export one function "int Example_Init(LuaState* L)" which must be called to register the module with the Lua interpreter. The name "Example_Init" depends upon the name of the module. Note: SWIG will automatically capitalise the module name, so "module example;" becomes "Example_Init".

22.2.1 Compiling and Linking and Interpreter

Normally Lua is embedded into another program and will be statically linked. An extremely simple stand-alone interpreter (min.c) is given below:

#include <stdio.h>
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"

extern int Example_Init(LuaState* L); // declare the wrapped module

int main(int argc,char* argv[])
{
 lua_State *L;
 if (argc

A much improved set of code can be found in the Lua distribution src/lua/lua.c. Include your module, just add the external declaration & add a #define LUA_EXTRALIBS {"example",Example_Init} , at the relevant place.

The exact commands for doing this vary from platform to platform. Here is a possible set of commands of doing this:

$ swig -lua example.i
$ gcc -I/usr/include/lua -c min.c -o min.o
$ gcc -I/usr/include/lua -c example_wrap.c -o example_wrap.o
$ gcc -c example.c -o example.o
$ gcc -I/usr/include/lua -L/usr/lib/lua min.o example_wrap.o example.o -o my_lua

22.2.2 Compiling a dynamic module

Most, but not all platforms support the dynamic loading of modules (Windows & Linux do). Refer to the Lua manual to determine if your platform supports it. For compiling a dynamically loaded module the same wrapper can be used. The commands will be something like this:

$ swig -lua example.i
$ gcc -I/usr/include/lua -c example_wrap.c -o example_wrap.o
$ gcc -c example.c -o example.o
$ gcc -shared -I/usr/include/lua -L/usr/lib/lua example_wrap.o example.o -o example.so

You will also need an interpreter with the loadlib function (such as the default interpreter compiled with Lua). In order to dynamically load a module you must call the loadlib function with two parameters: the filename of the shared library, and the function exported by SWIG. Calling loadlib should return the function, which you then call to initialise the module

my_init=loadlib("example.so","Example_Init") -- for Unix/Linux
--my_init=loadlib("example.dll","Example_Init") -- for Windows
assert(my_init) -- name sure its not nil
my_init()       -- call the init fn of the lib

Or can be done in a single line of Lua code

assert(loadlib("example.so","Example_Init"))()

Update for Lua 5.1 (alpha):
The wrappers produced by SWIG can be compiled and linked with Lua 5.1. The loading is now much simpler.

require("example")

If the code didn't work, don't panic. The best thing to do is to copy the module and your interpreter into a single directory and then execute the interpreter and try to manually load the module (take care, all this code is case sensitive).

a,b,c=loadlib("example.so","Example_Init") -- for Unix/Linux
--a,b,c=loadlib("example.dll","Example_Init") -- for Windows
print(a,b,c)

Note: for Lua 5.1:
The loadlib() function has been moved into the package table, so you must use package.loadlib() instead.

if 'a' is a function, this its all working fine, all you need to do is call it

  a()

to load your library which will add a table 'example' with all the functions added.

If it doesn't work, look at the error messages, in particular mesage 'b'
The specified module could not be found.
Means that is cannot find the module, check your the location and spelling of the module.
The specified procedure could not be found.
Means that it loaded the module, but cannot find the named function. Again check the spelling, and if possible check to make sure the functions were exported correctly.
'loadlib' not installed/supported
Is quite obvious (Go back and consult the Lua documents on how to enable loadlib for your platform).

22.2.3 Using your module

Assuming all goes well, you will be able to this:

$ ./my_lua
> print(example.gcd(4,6))
2
> print(example.Foo)
3
> example.Foo=4
> print(example.Foo)
4
>

22.3 A tour of basic C/C++ wrapping

By default, SWIG tries to build a very natural Lua interface to your C/C++ code. This section briefly covers the essential aspects of this wrapping.

22.3.1 Modules

The SWIG module directive specifies the name of the Lua module. If you specify `module example', then everything is wrapped into a Lua table 'example' containing all the functions and variables. When choosing a module name, make sure you don't use the same name as a built-in Lua command or standard module name.

22.3.2 Functions

Global functions are wrapped as new Lua built-in functions. For example,

%module example
int fact(int n);

creates a built-in function example.fact(n) that works exactly like you think it does:

> print example.fact(4)
24
>

To avoid name collisions, SWIG create a Lua table which it keeps all the functions and global variables in. It is possible to copy the functions out of this and into the global environment with the following code. This can easily overwrite existing functions, so this must be used with care.

> for k,v in pairs(example) do _G[k]=v end
> print(fact(4))
24
>

It is also possible to rename the module with an assignment.

> e=example
> print(e.fact(4))
24
> print(example.fact(4))
24

22.3.3 Global variables

Global variables (which are linked to C code) are supported, and appear to be just another variable in Lua. However the actual mechanism is more complex. Given a global variable:

%module example
extern double Foo;

SWIG will actually generate two functions example.Foo_set() and example.Foo_get(). It then adds a metatable to the table 'example' to call these functions at the correct time (when you attempt to set or get examples.Foo). Therefore if you were to attempt to assign the global to another variable, you will get a local copy within the interpreter, which is no longer linked to the C code.

> print(example.Foo)
3
> c=example.Foo   -- c is a COPY of example.Foo, not the same thing
> example.Foo=4
> print(c)
3
> c=5 -- this will not effect the original example.Foo
> print(example.Foo,c)
4    5

Its is therefore not possible to 'move' the global variable into the global namespace as it is with functions. It is however, possible to rename the module with an assignment, to make it more convenient.

> e=example
> -- e and example are the same table
> -- so e.Foo and example.Foo are the same thing
> example.Foo=4
> print(e.Foo)
4

If a variable is marked with the immutable directive then any attempts to set this variable are silently ignored.

Another interesting feature is that it is not possible to add new values into the module from within the interpreter, this is because of the metatable to deal with global variables. It is possible (though not recommended) to use rawset() to add a new value.

> -- example.PI does not exist
> print(example.PI)
nil
> example.PI=3.142 -- assign failed, example.PI does still not exist
> print(example.PI)
nil
> -- a rawset will work, after this the value is added
> rawset(example,"PI",3.142)
> print(example.PI)
3.142

22.3.4 Constants and enums

Because Lua doesn't really have the concept of constants, C/C++ constants are not really constant in Lua. They are actually just a copy of the value into the Lua interpreter. Therefore they can be changed just as any other value. For example given some constants:

%module example
%constant int ICONST=42;
#define    SCONST      "Hello World"
enum Days{SUNDAY,MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY};

This is 'effectively' converted into the following Lua code:

example.ICONST=42
example.SCONST="Hello World"
example.SUNDAY=0
....

Constants are not guaranteed to remain constant in Lua. The name of the constant could be accidentally reassigned to refer to some other object. Unfortunately, there is no easy way for SWIG to generate code that prevents this. You will just have to be careful.

22.3.5 Pointers

C/C++ pointers are fully supported by SWIG. Furthermore, SWIG has no problem working with incomplete type information. Given a wrapping of the <file.h> interface:

%module example

FILE *fopen(const char *filename, const char *mode);
int fputs(const char *, FILE *);
int fclose(FILE *);

When wrapped, you will be able to use the functions in a natural way from Lua. For example:

> f=example.fopen("